mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-01 06:16:46 -06:00
M3: library analytics list how each style and variable is used (#1730)
* M3: library analytics list how each style and variable is used A file reports how many of its layers use each of a team library's styles and variables, and Show usage lists them by a Type choice with their layers and files. Layers in instances count for their component. Also ignores plugins/target. * M3: the style analytics test waits for the instance report too
This commit is contained in:
@@ -3,6 +3,7 @@ plan/
|
||||
plans/
|
||||
/target/
|
||||
/target-*/
|
||||
/plugins/target/
|
||||
/dist/
|
||||
/corpus/
|
||||
/log/
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
@@ -107,6 +107,8 @@ mod idle_io_tests;
|
||||
#[cfg(test)]
|
||||
mod library_actions_tests;
|
||||
#[cfg(test)]
|
||||
mod library_assets_tests;
|
||||
#[cfg(test)]
|
||||
mod library_detach_tests;
|
||||
#[cfg(test)]
|
||||
mod library_tests;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Styles and variables in a team library's analytics, end to end over loopback: a file that uses
|
||||
//! them reports how many of its layers do, the library's owner sees them per style and variable
|
||||
//! with their names and files, and a file that stops using them stops counting. Reports are cleaned
|
||||
//! and capped, and the usage list keeps its encoding.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg};
|
||||
use figcraft_collab_net::Invite;
|
||||
use figcraft_doc::NodeId;
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::test_util::{Raw, TempDir, config, publish, session};
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// `a`'s analytics once `done` holds for them; `b` reports again each time, as a check asked for
|
||||
/// while the last one still runs is dropped.
|
||||
fn usage_when(a: &mut Session, b: &mut Session, done: impl Fn(&Value) -> bool) -> Value {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
b.refresh_server_libraries();
|
||||
let u = ex(a, "library.usage", json!({}));
|
||||
if done(&u) {
|
||||
return u;
|
||||
}
|
||||
assert!(start.elapsed() < Duration::from_secs(30), "the reports never arrived: {u}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: i32) -> NodeId {
|
||||
id(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40})))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_and_variables_are_counted_per_layer_and_file() {
|
||||
let dir = TempDir::new("library-assets");
|
||||
let cfg = config(dir.path());
|
||||
let mut server = crate::start(&cfg).unwrap();
|
||||
let addr = server.addr();
|
||||
// Ada's library: a colour style, a colour variable, and a Card that uses the style.
|
||||
let mut a = session("Ada");
|
||||
let r = rect(&mut a, 0);
|
||||
let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r}));
|
||||
let brand = style["id"].as_str().unwrap().to_string();
|
||||
let collection = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
|
||||
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": collection["id"], "value": "#0D99FF"}));
|
||||
let card = id(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"})));
|
||||
ex(&mut a, "style.apply", json!({"ids": [card], "style": brand}));
|
||||
ex(&mut a, "component.create", json!({"ids": [card]}));
|
||||
let p = publish(&mut a, dir.path(), addr);
|
||||
ex(&mut a, "library.publishToServer", json!({}));
|
||||
|
||||
// Bo uses the style on two layers and the variable on one, and places a Card: it belongs to
|
||||
// the component, so it doesn't count for the style.
|
||||
let mut b = session("Bo");
|
||||
let lid = ex(&mut b, "library.add", json!({"path": p.view}))["id"].as_str().unwrap().to_string();
|
||||
let (one, two, three) = (rect(&mut b, 0), rect(&mut b, 100), rect(&mut b, 200));
|
||||
ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one, two]}));
|
||||
ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [three], "field": "fill"}));
|
||||
ex(&mut b, "library.place", json!({"library": lid, "component": "Card", "x": 300, "y": 0}));
|
||||
|
||||
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 2 && u["variables"][0]["layers"] == 1 && u["instances"] == 1);
|
||||
assert_eq!(u["assetsKnown"], true, "{u}");
|
||||
let s = &u["styles"][0];
|
||||
assert_eq!((s["name"].clone(), s["type"].clone(), s["files"].clone()), (json!("Brand"), json!("paint"), json!(1)), "{u}");
|
||||
let v = &u["variables"][0];
|
||||
assert_eq!((v["name"].clone(), v["collection"].clone(), v["files"].clone()), (json!("Accent"), json!("Tokens"), json!(1)), "{u}");
|
||||
assert_eq!(u["instances"], 1, "components count as before: {u}");
|
||||
|
||||
// Bo takes the style off one layer and the variable off its only one.
|
||||
ex(&mut b, "style.detach", json!({"ids": [two], "which": "fill"}));
|
||||
ex(&mut b, "variable.bind", json!({"ids": [three], "field": "fill"}));
|
||||
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"].as_array().is_some_and(Vec::is_empty));
|
||||
assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}");
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/// Reports from the wire: names cleaned, counts capped and long ids dropped, one count per id; the
|
||||
/// reports survive the server's restart, and a server's list has only files that use something.
|
||||
#[test]
|
||||
fn asset_reports_are_capped_and_kept() {
|
||||
let dir = TempDir::new("library-assets-wire");
|
||||
let cfg = config(dir.path());
|
||||
let mut server = crate::start(&cfg).unwrap();
|
||||
let addr = server.addr();
|
||||
let mut a = session("Ada");
|
||||
let r = rect(&mut a, 0);
|
||||
ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r}));
|
||||
let p = publish(&mut a, dir.path(), addr);
|
||||
ex(&mut a, "library.publishToServer", json!({}));
|
||||
let view = Invite::parse(&p.view).unwrap();
|
||||
let open = |addr| {
|
||||
let mut raw = Raw::connect(addr);
|
||||
raw.send(&ClientMsg::OpenLibrary(OpenLibrary {
|
||||
protocol: PROTOCOL,
|
||||
file: view.file.clone(),
|
||||
token: view.token.clone(),
|
||||
client_version: String::new(),
|
||||
}));
|
||||
assert_eq!(answer(&mut raw), LibraryReply::Ready { access: Access::View });
|
||||
raw
|
||||
};
|
||||
let mut raw = open(addr);
|
||||
let flood = (0..5_000).map(|i| (format!("s{i}"), 1)).collect();
|
||||
let noted = |raw: &mut Raw, a| {
|
||||
raw.send(&ClientMsg::Library(LibraryReq::ReportAssets(a)));
|
||||
assert_eq!(answer(raw), LibraryReply::Noted);
|
||||
};
|
||||
noted(&mut raw, AssetUsage { file: "Spam".into(), styles: flood, variables: Vec::new() });
|
||||
let odd = vec![("x".repeat(65), 7), ("a".into(), 4), ("a".into(), 9), ("b".into(), 0)];
|
||||
noted(&mut raw, AssetUsage { file: "\u{7}Shop\n".into(), styles: Vec::new(), variables: odd });
|
||||
noted(&mut raw, AssetUsage { file: "Nothing".into(), ..AssetUsage::default() });
|
||||
raw.send(&ClientMsg::Library(LibraryReq::Assets));
|
||||
let LibraryReply::Assets(files) = answer(&mut raw) else { panic!("no reports") };
|
||||
assert_eq!(files.len(), 2, "a file that uses nothing isn't listed: {files:?}");
|
||||
assert_eq!(files.iter().find(|f| f.file == "Spam").unwrap().styles.len(), MAX_ASSET_USAGE);
|
||||
assert_eq!(files.iter().find(|f| f.file == "Shop").unwrap().variables, [("a".to_string(), 4)]);
|
||||
// Older apps ask for the usage list, where nobody reported using the library.
|
||||
raw.send(&ClientMsg::Library(LibraryReq::Usage));
|
||||
assert_eq!(answer(&mut raw), LibraryReply::Usage(Vec::new()));
|
||||
server.stop();
|
||||
|
||||
let mut server = crate::start(&cfg).unwrap();
|
||||
let mut raw = open(server.addr());
|
||||
raw.send(&ClientMsg::Library(LibraryReq::Assets));
|
||||
let LibraryReply::Assets(kept) = answer(&mut raw) else { panic!("no reports") };
|
||||
assert_eq!(kept, files);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
fn answer(raw: &mut Raw) -> LibraryReply {
|
||||
match raw.next() {
|
||||
ServerMsg::Library(r) => *r,
|
||||
other => panic!("not a library answer: {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,8 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use figcraft_collab::message::{
|
||||
Access, Admin, AdminReply, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq, LinkInfo,
|
||||
MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
|
||||
Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq,
|
||||
LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
|
||||
};
|
||||
use figcraft_collab::{Change, NodeId, Replica, Server, same_secret};
|
||||
use figcraft_collab_net::hub::{Admission, Backend, Closing, Handled, OpenFile, ip_blocks, ip_key};
|
||||
@@ -106,7 +106,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published
|
||||
const MAX_USERS: usize = 200;
|
||||
const MAX_REPORTED: usize = 1_000;
|
||||
/// Largest `usage.json` (and `actions.json`) read.
|
||||
const MAX_USAGE_FILE: u64 = 4 << 20;
|
||||
const MAX_USAGE_FILE: u64 = 16 << 20;
|
||||
/// Weeks of a library's insertions and detachments kept (a year and the current week), and most
|
||||
/// rows (a component in a week) kept in all.
|
||||
const MAX_WEEKS: u64 = 53;
|
||||
@@ -317,6 +317,10 @@ struct UsageEntry {
|
||||
detached_updated: u64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
peaks: Vec<(NodeId, u32, u32)>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
styles: Vec<(String, u32)>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
variables: Vec<(String, u32)>,
|
||||
}
|
||||
|
||||
fn is_zero(n: &u64) -> bool {
|
||||
|
||||
@@ -274,6 +274,8 @@ impl Backend for Store {
|
||||
LibraryReq::Detached => self.library_detached(file).map_or_else(failed, LibraryReply::Detached),
|
||||
LibraryReq::ReportInserted(d) => self.report_inserted(file, d).map_or_else(failed, |()| LibraryReply::Noted),
|
||||
LibraryReq::Actions => self.library_actions(file).map_or_else(failed, LibraryReply::Actions),
|
||||
LibraryReq::ReportAssets(a) => self.report_assets(file, a).map_or_else(failed, |()| LibraryReply::Noted),
|
||||
LibraryReq::Assets => self.library_assets(file).map_or_else(failed, LibraryReply::Assets),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use figcraft_collab::message::MAX_ASSET_USAGE;
|
||||
|
||||
use super::{
|
||||
ACTIONS, Action, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply,
|
||||
ACTIONS, Action, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply,
|
||||
MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, NodeId, Path, PathBuf,
|
||||
Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json,
|
||||
};
|
||||
@@ -12,6 +14,8 @@ enum Count {
|
||||
}
|
||||
|
||||
const WEEK: u64 = 7 * 86_400;
|
||||
/// Longest style or variable id a report may name.
|
||||
const MAX_ASSET_ID: usize = 64;
|
||||
|
||||
/// The start of the week `t` falls in (seconds since 1970 UTC, a Monday at 00:00).
|
||||
fn week_of(t: u64) -> u64 {
|
||||
@@ -20,6 +24,20 @@ fn week_of(t: u64) -> u64 {
|
||||
u64::try_from(monday.and_time(chrono::NaiveTime::MIN).and_utc().timestamp()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A report's counts cleaned: positive, one per key, at most [`MAX_REPORTED`].
|
||||
fn cleaned<K: Ord>(counts: Vec<(K, u32)>) -> Vec<(K, u32)> {
|
||||
let mut counts: Vec<_> = counts.into_iter().filter(|(_, n)| *n > 0).take(MAX_REPORTED * 4).collect();
|
||||
counts.sort();
|
||||
counts.dedup_by(|a, b| a.0 == b.0);
|
||||
counts.truncate(MAX_REPORTED);
|
||||
counts
|
||||
}
|
||||
|
||||
/// A report's style or variable counts: ids of a sensible length, at most [`MAX_ASSET_USAGE`].
|
||||
fn known_assets(counts: Vec<(String, u32)>) -> Vec<(String, u32)> {
|
||||
counts.into_iter().filter(|(id, _)| id.len() <= MAX_ASSET_ID).take(MAX_ASSET_USAGE).collect()
|
||||
}
|
||||
|
||||
/// A kept list of statistics, or an empty one when it is missing or damaged (it starts over).
|
||||
fn read_kept<T: serde::de::DeserializeOwned>(path: &Path) -> Vec<T> {
|
||||
if !path.exists() {
|
||||
@@ -188,6 +206,13 @@ impl Store {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The style and variable reports kept for a file's library (none when it has no library).
|
||||
pub fn library_assets(&mut self, file: &str) -> Result<Vec<AssetUsage>, String> {
|
||||
let list = self.usage_of(file)?.map(|u| u.list.as_slice()).unwrap_or_default();
|
||||
let used = list.iter().filter(|e| !e.styles.is_empty() || !e.variables.is_empty());
|
||||
Ok(used.map(|e| AssetUsage { file: e.usage.file.clone(), styles: e.styles.clone(), variables: e.variables.clone() }).collect())
|
||||
}
|
||||
|
||||
/// A file's library's components' insertions and detachments week by week, over the last
|
||||
/// [`MAX_WEEKS`] weeks (none when it has no library).
|
||||
pub fn library_actions(&mut self, file: &str) -> Result<Vec<WeekActions>, String> {
|
||||
@@ -209,6 +234,19 @@ impl Store {
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep how many layers of one file use a file's library's styles and variables (as
|
||||
/// [`Self::report_usage`] keeps its usage, beside it).
|
||||
pub fn report_assets(&mut self, file: &str, assets: AssetUsage) -> Result<(), String> {
|
||||
let variables = cleaned(known_assets(assets.variables));
|
||||
self.report(file, &assets.file, known_assets(assets.styles), |e, styles| {
|
||||
if e.styles == styles && e.variables == variables {
|
||||
return false;
|
||||
}
|
||||
(e.styles, e.variables) = (styles, variables);
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep how many instances of a file's library components one file has detached (as
|
||||
/// [`Self::report_usage`] keeps its usage, beside it); what it detached since its last report
|
||||
/// counts in this week.
|
||||
@@ -241,24 +279,20 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep `counts` from the file called `name` (cleaned: positive counts, one per component, at
|
||||
/// most [`MAX_REPORTED`]) in its entry with `set` (which says whether anything changed),
|
||||
/// Keep `counts` from the file called `name` ([`cleaned`]) in its entry with `set` (which says whether anything changed),
|
||||
/// keeping at most [`MAX_USERS`] files, the ones heard from most recently.
|
||||
fn report(
|
||||
fn report<K: Ord>(
|
||||
&mut self,
|
||||
file: &str,
|
||||
name: &str,
|
||||
counts: Vec<(NodeId, u32)>,
|
||||
set: impl FnOnce(&mut UsageEntry, Vec<(NodeId, u32)>) -> bool,
|
||||
counts: Vec<(K, u32)>,
|
||||
set: impl FnOnce(&mut UsageEntry, Vec<(K, u32)>) -> bool,
|
||||
) -> Result<(), String> {
|
||||
let name = clean_name(name);
|
||||
if name.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut counts: Vec<_> = counts.into_iter().filter(|(_, n)| *n > 0).take(MAX_REPORTED * 4).collect();
|
||||
counts.sort();
|
||||
counts.dedup_by_key(|c| c.0);
|
||||
counts.truncate(MAX_REPORTED);
|
||||
let counts = cleaned(counts);
|
||||
let Some(u) = self.usage_of(file)? else { return Ok(()) };
|
||||
let at = match u.list.iter().position(|e| e.usage.file == name) {
|
||||
Some(at) => at,
|
||||
|
||||
@@ -234,7 +234,7 @@ impl LiveLink for NetLink {
|
||||
let spawned = std::thread::Builder::new().name("library-fetch".into()).spawn(move || {
|
||||
for (link, req) in jobs {
|
||||
// A report's answer says nothing about the library (and an older server refuses it).
|
||||
let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_));
|
||||
let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_));
|
||||
let reply = manage::library(&link, req, &limits, CONNECT);
|
||||
if !report {
|
||||
inbox.push(Event::Library { link, reply });
|
||||
|
||||
@@ -617,6 +617,18 @@ pub struct Usage {
|
||||
pub components: Vec<(NodeId, u32)>,
|
||||
}
|
||||
|
||||
/// Most styles and most variables of one library one file reports using.
|
||||
pub const MAX_ASSET_USAGE: usize = 250;
|
||||
|
||||
/// How many layers of one file use each of a library's styles and variables, as its app reports
|
||||
/// them: the file's name and the counts (by their ids in the library).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AssetUsage {
|
||||
pub file: String,
|
||||
pub styles: Vec<(String, u32)>,
|
||||
pub variables: Vec<(String, u32)>,
|
||||
}
|
||||
|
||||
/// A file's last usage report, with when it came (seconds since 1970, UTC).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FileUsage {
|
||||
@@ -675,6 +687,11 @@ pub enum LibraryReq {
|
||||
/// The library's components' insertions and detachments week by week (answered with
|
||||
/// [`LibraryReply::Actions`]).
|
||||
Actions,
|
||||
/// How many layers of the asking file use the library's styles and variables (answered with
|
||||
/// [`LibraryReply::Noted`]).
|
||||
ReportAssets(AssetUsage),
|
||||
/// The style and variable reports of the files that use the library.
|
||||
Assets,
|
||||
}
|
||||
|
||||
/// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]).
|
||||
@@ -709,6 +726,7 @@ pub enum LibraryReply {
|
||||
Noted,
|
||||
Detached(Vec<FileDetached>),
|
||||
Actions(Vec<WeekActions>),
|
||||
Assets(Vec<AssetUsage>),
|
||||
}
|
||||
|
||||
/// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
//! ([`Session::refresh_server_libraries`]) and keeps the last library fetched while the server
|
||||
//! can't be reached.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_collab::message::{Detached, LibraryReply, LibraryReq, Usage};
|
||||
use figcraft_doc::{DetachCount, Document, NodeId, NodeKind, PublishedLibrary};
|
||||
use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
|
||||
use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary};
|
||||
|
||||
use crate::live::{NetReply, NetRequest};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -91,6 +92,42 @@ pub fn usage(doc: &Document, library: &str) -> Usage {
|
||||
Usage { file: doc.name.clone(), components: counts.into_iter().take(MAX_USAGE).collect() }
|
||||
}
|
||||
|
||||
/// How many layers of `doc` use each of `library`'s styles and variables, the most used first (a
|
||||
/// instance, a layer inside one or the library copies belongs to its component, which is what's
|
||||
/// counted); `None` when it has none of them, so a file that stops using them still reports that.
|
||||
pub fn asset_usage(doc: &Document, library: &str) -> Option<AssetUsage> {
|
||||
let keys = |records: &[ImportedRecord]| -> BTreeMap<String, String> {
|
||||
records.iter().filter(|r| r.library == library).map(|r| (r.local.clone(), r.key.clone())).collect()
|
||||
};
|
||||
let (style_keys, variable_keys) = (keys(&doc.libraries.styles), keys(&doc.libraries.variables));
|
||||
if style_keys.is_empty() && variable_keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let store = doc.library_store();
|
||||
let (mut styles, mut variables) = (BTreeMap::<&str, u32>::new(), BTreeMap::<&str, u32>::new());
|
||||
let instance = |n: &figcraft_doc::Node| matches!(n.kind, NodeKind::Instance { .. }) || crate::components::inside_instance(doc, n.id);
|
||||
let own = doc.nodes().filter(|n| store.is_none_or(|st| doc.page_of(n.id) != Some(st)) && !instance(n));
|
||||
for n in own {
|
||||
let used = crate::library::style_links(n).filter_map(|s| style_keys.get(s)).collect::<BTreeSet<_>>();
|
||||
for k in used {
|
||||
*styles.entry(k).or_default() += 1;
|
||||
}
|
||||
let used = n.bound.values().filter_map(|v| variable_keys.get(v)).collect::<BTreeSet<_>>();
|
||||
for k in used {
|
||||
*variables.entry(k).or_default() += 1;
|
||||
}
|
||||
}
|
||||
Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) })
|
||||
}
|
||||
|
||||
/// `counts`, the most used first, at most [`MAX_ASSET_USAGE`].
|
||||
fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> {
|
||||
let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect();
|
||||
list.sort_by_key(|c| std::cmp::Reverse(c.1));
|
||||
list.truncate(MAX_ASSET_USAGE);
|
||||
list
|
||||
}
|
||||
|
||||
/// How many instances of `library`'s components `doc` has detached, as its server keeps them;
|
||||
/// `None` when it has detached none.
|
||||
pub fn detached(doc: &Document, library: &str) -> Option<Detached> {
|
||||
@@ -226,7 +263,11 @@ impl Session {
|
||||
};
|
||||
// Then the detaches and insertions, when there are any (a server from before them
|
||||
// refuses the request, and nothing comes of it).
|
||||
let reports = [detached(doc, &l.id).map(LibraryReq::ReportDetached), inserted(doc, &l.id).map(LibraryReq::ReportInserted)];
|
||||
let reports = [
|
||||
detached(doc, &l.id).map(LibraryReq::ReportDetached),
|
||||
inserted(doc, &l.id).map(LibraryReq::ReportInserted),
|
||||
asset_usage(doc, &l.id).map(LibraryReq::ReportAssets),
|
||||
];
|
||||
let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) };
|
||||
std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req))
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use figcraft_doc::{Document, ImportedComponent, ImportedRecord, LibraryLink, LibraryManifest, NodeId, PublishedLibrary, VariableId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use figcraft_collab::message::{FileDetached, LibraryReply, LibraryReq, WeekActions};
|
||||
use figcraft_collab::message::{AssetUsage, FileDetached, LibraryReply, LibraryReq, WeekActions};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::library::{
|
||||
@@ -427,6 +427,7 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let detached = detach_reports(s.library_request(&link, LibraryReq::Detached))?;
|
||||
let assets = asset_reports(s.library_request(&link, LibraryReq::Assets))?;
|
||||
let days = num(p, "days").filter(|d| d.is_finite()).map_or(30, |d| d.round().clamp(1.0, 365.0) as u64);
|
||||
// Weeks overlapping the period; a server from before weekly counts refuses the request.
|
||||
let since = crate::cmd::comment::now_secs().saturating_sub(days * 86_400);
|
||||
@@ -479,9 +480,45 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"weeks": actions.weeks,
|
||||
"files": rows,
|
||||
"components": components,
|
||||
"assetsKnown": assets.is_some(),
|
||||
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| {
|
||||
m.style(id).map(|x| json!({"name": x.name, "type": x.kind}))
|
||||
}),
|
||||
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| {
|
||||
let v = m.variable(id)?;
|
||||
Some(json!({"name": v.name, "collection": m.collection(&v.collection).map(|c| c.name.clone())}))
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The style or variable reports' totals, the most used first: each one's `id`, `layers` and
|
||||
/// `files`, with what `describe` says of it (nothing for one no longer published).
|
||||
fn asset_rows<'a>(reports: impl Iterator<Item = &'a Vec<(String, u32)>>, describe: impl Fn(&str) -> Option<Value>) -> Vec<Value> {
|
||||
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
|
||||
for (id, n) in reports.flatten() {
|
||||
let e = per.entry(id).or_default();
|
||||
e.0 += u64::from(*n);
|
||||
e.1 += 1;
|
||||
}
|
||||
let mut rows: Vec<_> = per.into_iter().collect();
|
||||
rows.sort_by_key(|r| std::cmp::Reverse(r.1.0));
|
||||
let row = |(id, (layers, files)): (&str, (u64, u64))| {
|
||||
let mut r = describe(id).unwrap_or_else(|| json!({}));
|
||||
(r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files));
|
||||
r
|
||||
};
|
||||
rows.into_iter().map(row).collect()
|
||||
}
|
||||
|
||||
/// The style and variable reports, `None` from a server from before them.
|
||||
fn asset_reports(reply: Result<LibraryReply>) -> Result<Option<Vec<AssetUsage>>> {
|
||||
match reply {
|
||||
Ok(LibraryReply::Assets(a)) => Ok(Some(a)),
|
||||
Err(EngineError::Waiting) => Err(EngineError::Waiting),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A period's insertions and detachments: per component, in all, and week by week (ascending).
|
||||
struct PeriodActions {
|
||||
per: std::collections::BTreeMap<NodeId, (u64, u64)>,
|
||||
|
||||
@@ -91,9 +91,10 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply {
|
||||
LibraryReply::Published { version: 1 }
|
||||
}
|
||||
(LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()),
|
||||
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_), _) => LibraryReply::Noted,
|
||||
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted,
|
||||
(LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()),
|
||||
(LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()),
|
||||
(LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -986,6 +986,7 @@ name = "English"
|
||||
"Not read yet" = "Not read yet"
|
||||
"Not shared" = "Not shared"
|
||||
"Note {n}" = "Note {n}"
|
||||
"Nothing counted yet" = "Nothing counted yet"
|
||||
"Nothing changed since this version." = "Nothing changed since this version."
|
||||
"Nothing changed since this was marked ready for dev." = "Nothing changed since this was marked ready for dev."
|
||||
"Nothing here yet. Set a frame's status to list it." = "Nothing here yet. Set a frame's status to list it."
|
||||
@@ -1319,6 +1320,7 @@ name = "English"
|
||||
"Search results" = "Search results"
|
||||
"Search fonts" = "Search fonts"
|
||||
"This server doesn't count insertions" = "This server doesn't count insertions"
|
||||
"This server doesn't count styles and variables" = "This server doesn't count styles and variables"
|
||||
"Someone who left" = "Someone who left"
|
||||
"Take the results off the board; they stay in the file" = "Take the results off the board; they stay in the file"
|
||||
"Upload from computer" = "Upload from computer"
|
||||
|
||||
@@ -1036,11 +1036,22 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
|
||||
} else {
|
||||
hint(ui, tr("This server doesn't count insertions"));
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some(kind) = usage_kind(ui, w, usage_id, &v) else {
|
||||
ui.add_space(8.0);
|
||||
return;
|
||||
};
|
||||
if kind != "components" {
|
||||
for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) {
|
||||
let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0));
|
||||
let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]);
|
||||
usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
return;
|
||||
}
|
||||
for c in v["components"].as_array().into_iter().flatten().take(USAGE_ROWS) {
|
||||
let name = c["name"].as_str().unwrap_or(tr("(no longer published)"));
|
||||
let (n, f) = (c["instances"].as_u64().unwrap_or(0), c["files"].as_u64().unwrap_or(0));
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, 34.0), Sense::hover());
|
||||
let gone = c["detached"].as_u64().unwrap_or(0);
|
||||
// A component only detached (no instances left anywhere) says just that.
|
||||
let right = if n == 0 && known && gone > 0 {
|
||||
@@ -1051,14 +1062,52 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
|
||||
// Inserted in the period, after what the component counts in all.
|
||||
let added = c["insertions"].as_u64().unwrap_or(0);
|
||||
let right = if actions && added > 0 { trf("{used} · {inserted}", &[("used", &right), ("inserted", &inserted_n(added))]) } else { right };
|
||||
// Two lines: the counts don't leave a name room on one.
|
||||
crate::bidi::paint_name(ui.painter(), pos2(r.min.x + PAD, r.min.y + 10.0), name, regular(11.0), t.text, w - PAD * 2.0);
|
||||
let counts = crate::widgets::elide_font(ui, &right, w - PAD * 2.0, regular(10.0));
|
||||
ui.painter().text(pos2(r.min.x + PAD, r.min.y + 25.0), Align2::LEFT_CENTER, counts, regular(10.0), t.text_secondary);
|
||||
usage_row(ui, w, name, &right);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
|
||||
/// Which list Show usage shows: `components`, `styles` or `variables` (a choice kept with the
|
||||
/// answer's `id`), `None` for nothing to list. A server from before style and variable reports
|
||||
/// shows just components, and says so.
|
||||
fn usage_kind(ui: &mut Ui, w: f32, id: Id, v: &Value) -> Option<&'static str> {
|
||||
const KINDS: [(&str, &str); 3] = [("components", "Components"), ("styles", "Styles"), ("variables", "Variables")];
|
||||
if v["assetsKnown"].as_bool() != Some(true) {
|
||||
hint(ui, tr("This server doesn't count styles and variables"));
|
||||
return Some(KINDS[0].0);
|
||||
}
|
||||
let id = id.with("kind");
|
||||
let mut at = ui.data(|d| d.get_temp::<usize>(id)).unwrap_or(0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(PAD);
|
||||
let chosen = KINDS.get(at).map_or("", |k| tr(k.1));
|
||||
let resp = crate::widgets::dropdown(ui, chosen, w - PAD * 2.0, None);
|
||||
crate::right::menu_popup(&resp).width(w - PAD * 2.0).show(|ui| {
|
||||
for (i, k) in KINDS.iter().enumerate() {
|
||||
if crate::right::menu_item(ui, tr(k.1), "") {
|
||||
at = i;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(id, at));
|
||||
let kind = KINDS.get(at)?.0;
|
||||
if v[kind].as_array().is_none_or(Vec::is_empty) {
|
||||
hint(ui, tr("Nothing counted yet"));
|
||||
}
|
||||
Some(kind)
|
||||
}
|
||||
|
||||
/// A Show usage row: two lines, as the counts don't leave a name room on one.
|
||||
fn usage_row(ui: &mut Ui, w: f32, name: &str, counts: &str) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, 34.0), Sense::hover());
|
||||
crate::bidi::paint_name(ui.painter(), pos2(r.min.x + PAD, r.min.y + 10.0), name, regular(11.0), t.text, w - PAD * 2.0);
|
||||
let counts = crate::widgets::elide_font(ui, counts, w - PAD * 2.0, regular(10.0));
|
||||
ui.painter().text(pos2(r.min.x + PAD, r.min.y + 25.0), Align2::LEFT_CENTER, counts, regular(10.0), t.text_secondary);
|
||||
}
|
||||
|
||||
/// Draw the libraries enabled in this file with version/count/status, remove and swap
|
||||
/// actions, add-file and pasted-link controls, and background fetch/cancel handling.
|
||||
fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
|
||||
@@ -257,7 +257,7 @@ Client → server:
|
||||
| `Manage {protocol, key, client_version}` | Instead of `Hello`: manage a server's files with its key. |
|
||||
| `Admin {publish {name, snapshot} \| files \| links {file} \| createLink {file, access, label} \| revoke {file, link} \| remove {file}}` | A request on a managing connection; each gets one `Admin` reply, in order. |
|
||||
| `OpenLibrary {protocol, file, token, client_version}` | Instead of `Hello`: use a file's team library with one of the file's share links. |
|
||||
| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. |
|
||||
| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. |
|
||||
| `Signal {kind, text}` | Ephemeral presence, only after the server's `ready`: `chat` (the cursor chat message; empty: closed), `spotlight` (`"on"`, or empty: stopped) or `name` (your new name: the server keeps it, cleaned like a hello's, and sends everyone, you too, your `PeerJoined`; never passed on as a signal). |
|
||||
| `OpenPlugins {protocol, key, client_version}` | Instead of `Hello`: use the server's plugin directory; `key` empty to browse, the server key to publish too. |
|
||||
| `OpenHosting {protocol, client_version, file, owner}` | Instead of `Hello`: ask about the server's hosting; publish without the key (`Admin publish`) when it is open to the public; with a file's id and owner token, manage that file (`Admin links \| createLink \| revoke \| rename \| remove` of it). Answered with `Hosting` or `Refused`. |
|
||||
@@ -279,7 +279,7 @@ Server → client:
|
||||
| `Refused {reason}` | The connection is refused (protocol version, token, session full, a message out of place). |
|
||||
| `Pong` | Keep-alive. |
|
||||
| `Admin {ready \| published {file, edit, view} \| files \| links \| link \| done \| failed {reason}}` | A managing connection's answer: the key is right, a published file with its first two links (tokens shown once), listings, a new link, done, or why not. |
|
||||
| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. |
|
||||
| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}] \| assets [{file, styles, variables}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. |
|
||||
| `Signal {client_id, signal: {kind, text}}` | Someone's cursor chat or spotlight, cleaned by the server; `ready` (about the client itself, after its welcome): signals may be sent. Only to clients whose hello announced `signals`. |
|
||||
| `Hosting {open, operator, terms, idle_secs, max_file_mb, expires?}` | The answer to `OpenHosting`, and after a welcome to clients whose hello announced `hosting`: anyone may publish, how to reach the operator, the terms (a URL), how long files published without the key are kept unopened, the largest file, and this file's expiry (seconds since 1970). |
|
||||
| `Admin {hosted {file, edit, view, owner, expires?} \| listing [row] \| reports [report] \| blocked [ip]}` | A file published without the key with its links and owner token (shown once), and the answers to the later managing requests. |
|
||||
@@ -821,7 +821,11 @@ resuming with its offline edits, and leaving the session going back to snapshot
|
||||
`reportInserted` the same way with the instances it has inserted (placed, pasted or duplicated;
|
||||
not those nested in another instance). What either total grows past that file's highest counts
|
||||
in the current week, a Monday at 00:00 UTC, over all files (`actions.json`, a year of weeks,
|
||||
capped), and `actions` answers with those weeks. The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new
|
||||
capped), and `actions` answers with those weeks. A file that holds copies of the library's
|
||||
styles or variables sends `reportAssets` with how many of its layers use each (at most 250 of
|
||||
each kind, the most used first; none is a report too, so a file that stops using them stops
|
||||
counting); the server keeps the latest in the same `usage.json` entry and answers `assets` with
|
||||
them. The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new
|
||||
requests, and the app ignores that.
|
||||
|
||||
*Built* (the plugin directory; operating it: [`server.md`](server.md#plugin-directory), publishing and
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Components, variants, styles and variables parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
|
||||
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
|
||||
@@ -52,7 +52,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
| Enable a library in a file; read-only linked copies | done | |
|
||||
| Library updates available; overrides kept | done | a library file saved again within two seconds of being read, at the same length, is read again (its time stamp can't prove it unchanged; #652) |
|
||||
| Team libraries: publish to a `figcraft-server` under the file, enable by a share link (a view link reads it), background update checks | done | [server.md](server.md#team-libraries); no team-wide library list or accounts ([gaps](gaps.md) #10) |
|
||||
| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components only: no styles or variables, no chart |
|
||||
| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, without insertions, detachments or modes; no chart |
|
||||
| Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step |
|
||||
|
||||
## Styles and variables
|
||||
@@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-31 | minor | M3, gap 10: library analytics cover styles and variables. A file reports how many of its layers use each of a library's styles and variables, and Show usage (`library.usage`) lists them beside the components, by a Type choice, with their layers and files. Layers inside instances count for their component. Insertions, detachments and modes aren't counted for them yet. Numbers unchanged. Tests: `library_assets_tests`. |
|
||||
| 2026-10-31 | minor | M6: as the help center describes code syntax, Dev Mode's SwiftUI and Compose code now writes a bound variable's iOS or Android code syntax in place of its value, as CSS already wrote the Web one: fills, strokes and their weight, sizes, corner radius, gaps, padding, opacity, the font family and size and the characters. A variable with no code syntax for the platform keeps the value, since a name made up here wouldn't exist in the code it lands in. ArkUI and Flutter have no code syntax platform and are unchanged. Test: `variables_behaviour_tests::swiftui_and_compose_name_variables_by_their_code_syntax`. Numbers unchanged. Grade unchanged |
|
||||
| 2026-10-31 | minor | M3, gap 10: library analytics over time. A file counts the instances of library components it inserts (placed, created, pasted or duplicated, Alt-dragged copies too; not those nested in another instance) and reports them like its detaches (`ReportInserted`). The server counts what a file's insertion and detach totals grow past their highest in the current week, a Monday at 00:00 UTC, so an undo and a redo count once, and keeps a year of weeks in `actions.json` (`Actions`). `library.usage {days?}` adds `insertions`, `detachments` and `weeks`, and per component `insertions` and `detachments`; Show usage has a 30 days, 90 days or 1 year choice, the period's totals, and each component's counts on a line of their own. The new variants are appended, so older messages keep their bytes; an older server refuses them and Show usage says it doesn't count insertions. A file's first report after this counts its total in that week. Tests: `library_actions_tests`, `inserting_library_instances_counts_them`. Grade unchanged |
|
||||
| 2026-10-30 | minor | M3, gap 14: a collection of this file can be extended, as the help center shows (right-click a collection, Extend collection); before, only a library's could. `variable.extendCollection {collection, name?}` makes "<name> (extended)" with its modes and one inheriting variable per variable, and the Variables editor's collection menu offers it beside Rename and Delete collection. Edits of the collection it extends reach it at once (values in modes it doesn't override, new variables and modes, renames, mode order), so normalising keeps extensions in step whenever variables change, not only on library updates; undo takes both back. An extended collection extends again (parents settle first; an extension doesn't take its parent's overrides as its own), and a loop of extensions from a hostile file comes apart into plain collections keeping their values. Deleting the parent leaves a plain collection with the values it showed, as for libraries. Tests: `extended_chain_tests` (engine), `variables_rename_tests::a_collection_of_this_file_extends_from_its_context_menu` (headless UI). Grade unchanged |
|
||||
|
||||
+7
-5
@@ -1,6 +1,6 @@
|
||||
# Where FigCraft falls short of Figma
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from
|
||||
doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The
|
||||
@@ -23,7 +23,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
| 7 | CPU canvas where Figma uses the GPU | Hardware/performance | 30–60 | [hardware-parity](hardware-parity.md) |
|
||||
| 8 | Platform QA: Linux and the browser left (Windows pass done 2026-10-11) | Stability/platforms | 10–20 | [hardware-parity](hardware-parity.md) |
|
||||
| 9 | Figma Draw: pen pressure on macOS/Linux tablets (multi-edit, brushes, pressure, text on a path and pattern fills landed) | Feature | 1–3 | [target-app-parity](target-app-parity.md) |
|
||||
| 10 | Team libraries: no team-wide lists or accounts; analytics cover components only | Feature | 4–8 | [components-parity](components-parity.md) |
|
||||
| 10 | Team libraries: no team-wide lists or accounts; analytics count insertions for components only | Feature | 4–8 | [components-parity](components-parity.md) |
|
||||
| 11 | Spell check | Feature | 4–8 | [target-app-parity](target-app-parity.md) |
|
||||
| 12 | Video fills; HEIC images | File format | 5–10 | [file-format-parity](file-format-parity.md) |
|
||||
| 13 | Vector tail: none left (boolean hit testing on the result landed 2026-10-11) | Feature | — | [target-app-parity](target-app-parity.md) |
|
||||
@@ -351,10 +351,11 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
- **Impact:** illustration-flavoured work moved into Figma Draw in 2025.
|
||||
- **Estimate:** 1–3 h once winit (or a platform tablet API behind it) reports pressure there.
|
||||
|
||||
### 10. Team libraries: no team-wide lists or accounts; analytics cover components only
|
||||
### 10. Team libraries: no team-wide lists or accounts; analytics count insertions for components only
|
||||
- **Missing:** libraries listed for a whole team or organization (each file enables a library by
|
||||
its link), accounts and per-person library permissions, analytics of styles and variables (a
|
||||
component's instances, insertions and detachments are counted, the last two week by week),
|
||||
its link), accounts and per-person library permissions, insertions, detachments and mode counts for
|
||||
styles and variables (they count layers and files using them; a component's instances,
|
||||
insertions and detachments are counted, the last two week by week),
|
||||
update notices pushed by the server (apps ask every 30 seconds while the Assets panel shows).
|
||||
- **Evidence:** a file's library is published to `figcraft-server` under the file and enabled in
|
||||
other files by a share link, with per-asset versions, updates with overrides kept, usage counts
|
||||
@@ -588,6 +589,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-31 | minor | Gap 10: library analytics list the layers and files using each style and variable; their insertions, detachments and modes stay on the missing list. |
|
||||
| 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. |
|
||||
| 2026-10-30 | minor | Gap 7: text reads only the fallback fonts it draws with: a face per fallback family and style, a file's bytes shared between families, the faces worked out once per style (first text laid out: 41 font files and 265 MiB read down to 3 files and 20 MiB on a Linux machine with Noto Sans CJK). Numbers unchanged |
|
||||
| 2026-10-31 | minor | Gap 6: widgets draw lines and SVG pictures (plugin API 6), so that item leaves the missing list. |
|
||||
|
||||
+1
-1
@@ -957,7 +957,7 @@ most when it can't be reached).
|
||||
`library.acceptUpdates` takes it, overrides kept. The app's own background checks ask only about
|
||||
team libraries added (`library.add`) or checked (`library.check {library?}`) on this computer,
|
||||
so opening a file that names another one contacts nothing (#1097).
|
||||
- `library.usage {library?, days?}` → `{id, name, instances, detached, detachesKnown, days,
|
||||
- `library.usage {library?, days?}` → `{id, name, assetsKnown, styles [{id, name, type, layers, files}], variables [{id, name, collection, layers, files}], instances, detached, detachesKnown, days,
|
||||
insertions, detachments, actionsKnown, weeks: [{week, insertions, detachments}], files: [{name,
|
||||
updated, instances, detached}], components: [{id, name, instances, files, detached, insertions,
|
||||
detachments}]}`: what the files using it reported (each fetch reports the asking document's name
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
+6
-3
@@ -250,9 +250,12 @@ which other files use without anyone copying the library file around.
|
||||
styles asks the server too, since you did that yourself.
|
||||
- **Usage.** Each time a file's app asks for the library it reports which of its components the
|
||||
file uses and how often, and then how many instances of each the file has detached and inserted
|
||||
(counted in the file when you detach one, or place, paste or duplicate one). **Show usage** in
|
||||
the library file (`library.usage`) lists the files and the instances and detaches of each
|
||||
component, and the insertions and detachments of the past 30 days, 90 days or year. Files are
|
||||
(counted in the file when you detach one, or place, paste or duplicate one), and how many of its
|
||||
layers use each of the library's styles and variables. **Show usage** in the library file
|
||||
(`library.usage`) lists the files and the instances and detaches of each component, the
|
||||
insertions and detachments of the past 30 days, 90 days or year, and, by its Type choice, the
|
||||
layers and files using each style and variable. Layers inside instances count for their
|
||||
component. Files are
|
||||
told apart by their names; a file's report changes only when its usage does. The server counts
|
||||
what a file's totals grow past their highest in the week it hears of it, keeps a year of weeks,
|
||||
and counts an undo and a redo once. A server from before these counts refuses the reports
|
||||
|
||||
Reference in New Issue
Block a user