M3: library analytics count insertions and detachments of styles and variables

Applying a style or variable, or copying or duplicating content that uses it,
inserts it; the Detach button detaches it; an instance counts as its component
alone. Show usage and library.usage give them over the chosen period.
This commit is contained in:
bflatastic
2026-11-18 19:38:54 +07:00
parent 2d8c412e6b
commit e4bc567855
25 changed files with 484 additions and 77 deletions
+2 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
@@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
+1
View File
@@ -28,6 +28,7 @@ pub const LINKS: &str = "links.json";
pub const LIBRARY: &str = "library.bin";
pub const USAGE: &str = "usage.json";
pub const ACTIONS: &str = "actions.json";
pub const ASSET_ACTIONS: &str = "asset-actions.json";
const SNAP_MAGIC: &[u8; 4] = b"FCSN";
const LOG_MAGIC: &[u8; 4] = b"FCLG";
@@ -79,7 +79,7 @@ fn styles_and_variables_are_counted_per_layer_and_file() {
// 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));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"][0]["layers"] == 0);
assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}");
server.stop();
}
@@ -143,3 +143,40 @@ fn answer(raw: &mut Raw) -> LibraryReply {
other => panic!("not a library answer: {other:?}"),
}
}
#[test]
fn inserts_and_detaches_count_per_style_and_variable_in_the_period() {
let dir = TempDir::new("library-asset-actions");
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.0}));
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 p = publish(&mut a, dir.path(), addr);
ex(&mut a, "library.publishToServer", json!({}));
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) = (rect(&mut b, 0), rect(&mut b, 100));
ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"}));
ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["insertions"] == 2 && u["variables"][0]["insertions"] == 1);
assert_eq!(u["assetActionsKnown"], true, "{u}");
assert_eq!(u["styles"][0]["detachments"], 1, "{u}");
assert_eq!(u["variables"][0]["detachments"], 0, "{u}");
assert_eq!(u["insertions"], 0, "components count on their own: {u}");
// An undo and a redo count once, and a style no layer uses any more stays listed.
ex(&mut b, "edit.undo", json!({}));
ex(&mut b, "edit.redo", json!({}));
ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2);
assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}");
assert_eq!(u["variables"][0]["insertions"], 1, "{u}");
server.stop();
}
+8 -4
View File
@@ -40,8 +40,8 @@ use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use figcraft_collab::message::{
Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq,
LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
Access, Admin, AdminReply, AssetActions, 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};
@@ -52,7 +52,7 @@ use sha2::{Digest, Sha256};
use crate::abuse::{Abuse, AbuseConfig, Action};
use crate::codes::{self, Sealed};
use crate::directory::{Directory, DirectoryConfig};
use crate::disk::{self, ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
use crate::disk::{self, ACTIONS, ASSET_ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
mod backend;
mod files;
@@ -298,6 +298,8 @@ struct UsageCache {
list: Vec<UsageEntry>,
/// Insertions and detachments week by week, over every file (kept in `actions.json`).
weeks: Vec<WeekActions>,
/// The same for styles and variables (kept in `asset-actions.json`).
asset_weeks: Vec<WeekActions<String>>,
dirty: bool,
written: u64,
}
@@ -321,6 +323,8 @@ struct UsageEntry {
styles: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
variables: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
asset_peaks: Vec<(String, u32, u32)>,
}
fn is_zero(n: &u64) -> bool {
@@ -560,7 +564,7 @@ impl Store {
/// A file folder's description and links, after checking its snapshot and log. Leftover
/// temporary files (writes cut short) are removed.
fn check(&self, path: &Path) -> Result<Entry, String> {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS] {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS, ASSET_ACTIONS] {
let tmp = disk::temp_of(&path.join(name));
if tmp.exists() {
let _ = fs::remove_file(&tmp);
@@ -278,6 +278,8 @@ impl Backend for Store {
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),
LibraryReq::ReportAssetActions(a) => self.report_asset_actions(file, a).map_or_else(failed, |()| LibraryReply::Noted),
LibraryReq::AssetActions => self.library_asset_actions(file).map_or_else(failed, LibraryReply::AssetActions),
}
}
+64 -31
View File
@@ -1,9 +1,9 @@
use figcraft_collab::message::MAX_ASSET_USAGE;
use super::{
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,
ACTIONS, ASSET_ACTIONS, Action, AssetActions, 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,
};
/// Which of a file's totals a report brings.
@@ -46,49 +46,55 @@ fn read_kept<T: serde::de::DeserializeOwned>(path: &Path) -> Vec<T> {
disk::read_capped(path, MAX_USAGE_FILE).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// Raise the highest `kind` totals in `peaks` to `counts`, each from what `last` says was reported
/// before them; what grew past them, by how much.
fn grow<K: PartialEq + Clone>(peaks: &mut Vec<(K, u32, u32)>, counts: &[(K, u32)], kind: Count, last: impl Fn(&K) -> u32) -> Vec<(K, u32)> {
let mut grown = Vec::new();
for (c, n) in counts {
let at = match peaks.iter().position(|p| p.0 == *c) {
Some(at) => at,
None if peaks.len() < MAX_REPORTED => {
peaks.push((c.clone(), 0, 0));
peaks.len() - 1
}
None => continue,
};
let Some(p) = peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last(c));
if *n > base {
grown.push((c.clone(), *n - base));
}
*peak = base.max(*n);
}
grown
}
impl UsageEntry {
/// Raise this file's highest `kind` totals to `counts`; what grew past them, by how much.
/// A detach total reported before peaks were kept starts from that report.
fn grow_peaks(&mut self, counts: &[(NodeId, u32)], kind: Count) -> Vec<(NodeId, u32)> {
let mut grown = Vec::new();
for &(c, n) in counts {
let last = if kind == Count::Detached { self.detached.iter().find(|d| d.0 == c).map_or(0, |d| d.1) } else { 0 };
let at = match self.peaks.iter().position(|p| p.0 == c) {
Some(at) => at,
None if self.peaks.len() < MAX_REPORTED => {
self.peaks.push((c, 0, 0));
self.peaks.len() - 1
}
None => continue,
};
let Some(p) = self.peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last);
if n > base {
grown.push((c, n - base));
}
*peak = base.max(n);
}
grown
let detached = &self.detached;
grow(&mut self.peaks, counts, kind, |c| if kind == Count::Detached { detached.iter().find(|d| d.0 == *c).map_or(0, |d| d.1) } else { 0 })
}
}
/// Add `grown` to this week's `kind` counts in `weeks`, dropping weeks older than [`MAX_WEEKS`]
/// and, past [`MAX_WEEK_ROWS`], the oldest rows.
fn add_to_week(weeks: &mut Vec<WeekActions>, grown: &[(NodeId, u32)], kind: Count, t: u64) {
fn add_to_week<K: PartialEq + Clone>(weeks: &mut Vec<WeekActions<K>>, grown: &[(K, u32)], kind: Count, t: u64) {
let week = week_of(t);
weeks.retain(|w| w.week.saturating_add(MAX_WEEKS * WEEK) > week);
for &(component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == component) {
for (component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == *component) {
Some(at) => at,
None => {
weeks.push(WeekActions { week, component, insertions: 0, detachments: 0 });
weeks.push(WeekActions { week, component: component.clone(), insertions: 0, detachments: 0 });
weeks.len() - 1
}
};
if let Some(w) = weeks.get_mut(at) {
let slot = if kind == Count::Inserted { &mut w.insertions } else { &mut w.detachments };
*slot = slot.saturating_add(n);
*slot = slot.saturating_add(*n);
}
}
if weeks.len() > MAX_WEEK_ROWS {
@@ -184,8 +190,9 @@ impl Store {
}
if !self.usage.contains_key(file) {
let path = self.dir(file).join(USAGE);
let (list, weeks) = (read_kept(&path), read_kept(&self.dir(file).join(ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, dirty: false, written: now() });
let dir = self.dir(file);
let (list, weeks, asset_weeks) = (read_kept(&path), read_kept(&dir.join(ACTIONS)), read_kept(&dir.join(ASSET_ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, asset_weeks, dirty: false, written: now() });
}
Ok(self.usage.get_mut(file))
}
@@ -234,6 +241,31 @@ impl Store {
})
}
/// A file's library's styles' and variables' insertions and detachments week by week, over
/// the last [`MAX_WEEKS`] weeks (none when it has no library).
pub fn library_asset_actions(&mut self, file: &str) -> Result<Vec<WeekActions<String>>, String> {
let since = week_of(now()).saturating_sub((MAX_WEEKS - 1) * WEEK);
let weeks = self.usage_of(file)?.map(|u| u.asset_weeks.as_slice()).unwrap_or_default();
Ok(weeks.iter().filter(|w| w.week >= since).cloned().collect())
}
/// Note how many times one file has inserted and detached a file's library's styles and
/// variables: what its totals grew past their highest counts in this week.
pub fn report_asset_actions(&mut self, file: &str, actions: AssetActions) -> Result<(), String> {
for (counts, kind) in [(actions.inserted, Count::Inserted), (actions.detached, Count::Detached)] {
let mut grown = Vec::new();
self.report(file, &actions.file, known_assets(counts), |e, counts| {
grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0);
!grown.is_empty()
})?;
if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) {
add_to_week(&mut u.asset_weeks, &grown, kind, now());
u.dirty = true;
}
}
Ok(())
}
/// 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> {
@@ -325,7 +357,8 @@ impl Store {
if let Err(e) = write_json(&root.join(file).join(USAGE), &u.list) {
log::warn!("file {file}: library usage couldn't be kept: {e}");
}
if let Err(e) = write_json(&root.join(file).join(ACTIONS), &u.weeks) {
let actions = write_json(&root.join(file).join(ACTIONS), &u.weeks);
if let Err(e) = actions.and_then(|()| write_json(&root.join(file).join(ASSET_ACTIONS), &u.asset_weeks)) {
log::warn!("file {file}: library analytics couldn't be kept: {e}");
}
(u.dirty, u.written) = (false, t);
+4 -1
View File
@@ -277,7 +277,10 @@ 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(_) | LibraryReq::ReportAssets(_));
let report = matches!(
req,
LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_)
);
let reply = manage::library(&link, req, &limits, CONNECT);
if !report {
inbox.push(Event::Library { link, reply });
+18 -2
View File
@@ -629,6 +629,15 @@ pub struct AssetUsage {
pub variables: Vec<(String, u32)>,
}
/// How many times one file has inserted and detached a library's styles and variables, as its app
/// reports them: its name and its totals of each (by their ids in the library).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetActions {
pub file: String,
pub inserted: Vec<(String, u32)>,
pub detached: 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 {
@@ -655,9 +664,9 @@ pub struct FileDetached {
/// 1970 UTC, a Monday at 00:00), over every file that reported it: instances inserted (placed,
/// pasted or duplicated) and detached, counted when the server first heard of them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WeekActions {
pub struct WeekActions<K = NodeId> {
pub week: u64,
pub component: NodeId,
pub component: K,
pub insertions: u32,
pub detachments: u32,
}
@@ -692,6 +701,12 @@ pub enum LibraryReq {
ReportAssets(AssetUsage),
/// The style and variable reports of the files that use the library.
Assets,
/// How many times the asking file has inserted and detached the library's styles and variables
/// (answered with [`LibraryReply::Noted`]).
ReportAssetActions(AssetActions),
/// The library's styles' and variables' insertions and detachments week by week (answered with
/// [`LibraryReply::AssetActions`]).
AssetActions,
}
/// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]).
@@ -727,6 +742,7 @@ pub enum LibraryReply {
Detached(Vec<FileDetached>),
Actions(Vec<WeekActions>),
Assets(Vec<AssetUsage>),
AssetActions(Vec<WeekActions<String>>),
}
/// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach
+31
View File
@@ -217,6 +217,10 @@ pub struct Libraries {
/// or duplicated; reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] components.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inserted: Vec<DetachCount>,
/// How often this document has inserted and detached each library style and variable
/// (reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] of them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub asset_counts: Vec<AssetCount>,
}
/// Most library components a document counts detaches for.
@@ -233,6 +237,17 @@ pub struct DetachCount {
pub count: u32,
}
/// Inserts and detaches of one library style or variable in a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetCount {
/// The library's id.
pub library: String,
/// Its id in the library.
pub key: String,
pub inserted: u32,
pub detached: u32,
}
/// Count one more instance of component `key` of library `library` in `list` (a component not
/// counted yet is left out once [`MAX_DETACH_COUNTS`] are).
fn count(list: &mut Vec<DetachCount>, library: &str, key: NodeId) {
@@ -256,6 +271,21 @@ impl Libraries {
count(&mut self.inserted, library, key);
}
/// Count `n` more inserts (or, with `detach`, detaches) of style or variable `key` of library
/// `library` (one not counted yet is left out once [`MAX_DETACH_COUNTS`] are).
pub fn count_asset(&mut self, library: &str, key: &str, detach: bool, n: u32) {
let at = self.asset_counts.iter().position(|c| c.library == library && c.key == key);
let at = at.or_else(|| {
let room = self.asset_counts.len() < MAX_DETACH_COUNTS;
room.then(|| self.asset_counts.push(AssetCount { library: library.to_string(), key: key.to_string(), inserted: 0, detached: 0 }))?;
Some(self.asset_counts.len() - 1)
});
if let Some(c) = at.and_then(|at| self.asset_counts.get_mut(at)) {
let total = if detach { &mut c.detached } else { &mut c.inserted };
*total = total.saturating_add(n);
}
}
/// Whether nothing is enabled, kept or counted.
pub fn is_empty(&self) -> bool {
self.enabled.is_empty()
@@ -266,6 +296,7 @@ impl Libraries {
&& self.variables.is_empty()
&& self.detached.is_empty()
&& self.inserted.is_empty()
&& self.asset_counts.is_empty()
}
/// Serde helper: leave the field out of files that use no libraries.
+53 -4
View File
@@ -83,14 +83,57 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option<NodeId> {
chain.into_iter().rfind(|c| doc.node(*c).is_some_and(is_asset))
}
/// The styles and variables layer `n` links to, each once.
fn asset_links(n: &Node) -> BTreeSet<&str> {
style_links(n).map(String::as_str).chain(n.bound.values().map(String::as_str)).collect()
}
/// The library and the id there of a local copy of a library style or variable.
fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord> {
doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local)
}
/// How many layers link to each local copy of a library style or variable.
fn library_links(doc: &Document) -> BTreeMap<String, u32> {
let mut links = BTreeMap::new();
if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() {
return links;
}
for local in doc.nodes().flat_map(asset_links).filter(|l| asset_record(doc, l).is_some()) {
*links.entry(local.to_string()).or_default() += 1;
}
links
}
/// Run `edit`, a user's applying (or, with `detach`, detaching) of styles or variables, and count
/// the layers it links to library copies (or unlinks from them) for the libraries' analytics. A
/// style replaced by another isn't a detach: only what the action names counts.
pub(crate) fn counting_links<T>(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result<T>) -> Result<T> {
let before = library_links(s.doc()?);
let out = edit(s)?;
let after = library_links(s.doc()?);
let (from, to) = if detach { (&after, &before) } else { (&before, &after) };
let grown: Vec<_> = to.iter().map(|(l, n)| (l, n.saturating_sub(from.get(l).copied().unwrap_or(0)))).filter(|g| g.1 > 0).collect();
for (local, n) in grown {
let doc = s.doc_mut()?;
if let Some(r) = asset_record(doc, local).cloned() {
doc.libraries_mut().count_asset(&r.library, &r.key, detach, n);
}
}
Ok(out)
}
/// Count the instances of library components among `roots` (new layers: placed, pasted or
/// duplicated) and in what they hold as inserted, for the libraries' analytics. An instance inside
/// another instance is part of it and isn't counted on its own.
/// duplicated) and in what they hold as inserted, and the library styles and variables of the
/// rest, for the libraries' analytics. An instance inside another instance is part of it and isn't
/// counted on its own, and what an instance uses is counted as the instance alone.
pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
if doc.libraries.components.is_empty() {
let l = &doc.libraries;
if l.components.is_empty() && l.styles.is_empty() && l.variables.is_empty() {
return;
}
let mut found = Vec::new();
let mut assets = Vec::new();
let mut stack = roots.to_vec();
while let Some(id) = stack.pop() {
let Some(n) = doc.node(id) else { continue };
@@ -99,12 +142,18 @@ pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
let root = asset_root(doc, component);
found.extend(doc.libraries.components.iter().find(|r| Some(r.root) == root).map(|r| (r.library.clone(), r.key)));
}
_ => stack.extend(n.children.iter().copied()),
_ => {
stack.extend(n.children.iter().copied());
assets.extend(asset_links(n).into_iter().filter_map(|l| asset_record(doc, l)).cloned());
}
}
}
for (library, key) in found {
doc.libraries_mut().count_insert(&library, key);
}
for r in assets {
doc.libraries_mut().count_asset(&r.library, &r.key, false, 1);
}
}
/// Components the layers of `root` use: mains of instances, instance swap defaults and values.
+11 -1
View File
@@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::Arc;
use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_collab::message::{AssetActions, AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary};
use crate::live::{NetReply, NetRequest};
@@ -123,6 +123,15 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option<AssetUsage> {
Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) })
}
/// How many times `doc` has inserted and detached `library`'s styles and variables, its totals;
/// `None` when it has done neither.
pub fn asset_actions(doc: &Document, library: &str) -> Option<AssetActions> {
let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect();
let totals =
|n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).take(MAX_ASSET_USAGE).collect();
(!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) })
}
/// `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();
@@ -270,6 +279,7 @@ impl Session {
detached(doc, &l.id).map(LibraryReq::ReportDetached),
inserted(doc, &l.id).map(LibraryReq::ReportInserted),
asset_usage(doc, &l.id).map(LibraryReq::ReportAssets),
asset_actions(doc, &l.id).map(LibraryReq::ReportAssetActions),
];
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))
+39 -5
View File
@@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Err(EngineError::Waiting) => return Err(EngineError::Waiting),
_ => None,
};
let asset_weeks = asset_week_rows(s, &link, since)?;
let asset_actions = asset_period(asset_weeks.as_deref().unwrap_or_default());
let m = &lib.manifest;
// Component → (instances, files using it, instances detached).
let mut per: std::collections::BTreeMap<NodeId, (u64, u64, u64)> = std::collections::BTreeMap::new();
@@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
"files": rows,
"components": components,
"assetsKnown": assets.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| {
"assetActionsKnown": asset_weeks.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), &asset_actions, |id| {
m.style(id).map(|x| json!({"name": x.name, "type": x.kind}))
}),
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| {
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), &asset_actions, |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> {
/// The styles' and variables' weeks overlapping a period from `since`; `None` from a server from
/// before them.
fn asset_week_rows(s: &mut Session, link: &str, since: u64) -> Result<Option<Vec<WeekActions<String>>>> {
match s.library_request(link, LibraryReq::AssetActions) {
Ok(LibraryReply::AssetActions(w)) => Ok(Some(w.into_iter().filter(|w| w.week.saturating_add(7 * 86_400) > since).collect())),
Err(EngineError::Waiting) => Err(EngineError::Waiting),
_ => Ok(None),
}
}
/// Each style's or variable's insertions and detachments in `weeks`.
fn asset_period(weeks: &[WeekActions<String>]) -> std::collections::BTreeMap<&str, (u64, u64)> {
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
for w in weeks {
let e = per.entry(&w.component).or_default();
e.0 += u64::from(w.insertions);
e.1 += u64::from(w.detachments);
}
per
}
/// The style or variable reports' totals, the most used first: each one's `id`, `layers`, `files`,
/// `insertions` and `detachments` in the period, with what `describe` says of it (nothing for one
/// no longer published). One only inserted or detached is listed too, when it's of this kind.
fn asset_rows<'a>(
reports: impl Iterator<Item = &'a Vec<(String, u32)>>,
actions: &std::collections::BTreeMap<&str, (u64, u64)>,
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;
}
for id in actions.keys().filter(|id| describe(id).is_some()) {
per.entry(id).or_default();
}
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!({}));
let (insertions, detachments) = actions.get(id).copied().unwrap_or_default();
(r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files));
(r["insertions"], r["detachments"]) = (json!(insertions), json!(detachments));
r
};
rows.into_iter().map(row).collect()
+12
View File
@@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option<Paragra
}
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, true, |s| detach_style(s, p))
}
fn detach_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.detach";
let which = req_string(cmd, p, "which")?;
if which == "text" {
@@ -458,6 +462,10 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option<
}
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, false, |s| apply_style(s, p))
}
fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.apply";
let st = req_string(cmd, p, "style")?;
let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?;
@@ -846,6 +854,10 @@ pub fn sync_list_styles(doc: &mut Document, before: &Document, ids: &[NodeId]) {
/// `variable.bind`: bind (or with no variable, unbind) `field` of the targets.
pub fn bind(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p))
}
fn bind_field(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "variable.bind";
let field = req_string(cmd, p, "field")?;
let var = string(p, "variable");
+2
View File
@@ -404,6 +404,8 @@ mod keymap_tests;
#[cfg(test)]
mod layout_suggest_tests;
#[cfg(test)]
mod library_asset_counts_tests;
#[cfg(test)]
mod library_beacon_tests;
#[cfg(test)]
mod library_path_tests;
@@ -0,0 +1,115 @@
//! What a file counts as inserting and detaching a library's styles and variables, as the help
//! center's library analytics page says: applying one, or copying or duplicating content that uses
//! it, inserts it; the Detach button detaches it. Content that is an instance counts as the
//! instance alone, and local styles and variables count nothing. An undo takes its count back.
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, idv};
use crate::library_server::asset_actions;
use figcraft_doc::{AssetCount, NodeId, PublishedLibrary};
/// A file with a published library holding a paint style, a colour variable and a Card, and a
/// second file that uses it: the second session, the library's id and its keys.
fn user() -> (Session, String, Value) {
let mut a = Session::new();
let r = idv(&ex(&mut a, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40})));
let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let coll = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": coll["id"], "value": "#0D99FF"}));
let card = idv(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"})));
ex(&mut a, "style.apply", json!({"ids": [card.0], "style": style["id"]}));
ex(&mut a, "component.create", json!({"ids": [card.0]}));
ex(&mut a, "library.publish", json!({}));
let lib: PublishedLibrary = a.doc().unwrap().published.as_deref().unwrap().clone();
let path = std::env::temp_dir().join(format!("figcraft-asset-counts-{}-{:?}.figcraft", std::process::id(), std::thread::current().id()));
ex(&mut a, "file.save", json!({"path": path.to_string_lossy()}));
let mut b = Session::new();
let id = ex(&mut b, "library.add", json!({"path": path.to_string_lossy()}))["id"].as_str().unwrap().to_string();
assert_eq!(lib.manifest.id, id);
(b, id, json!({"style": "Brand", "variable": "Accent"}))
}
fn rect(s: &mut Session, x: i32) -> NodeId {
idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40})))
}
/// (inserted, detached) of the style and of the variable, as `doc` keeps them.
fn counts(s: &Session) -> ((u32, u32), (u32, u32)) {
let of = |key: &str| {
s.doc().unwrap().libraries.asset_counts.iter().find(|c: &&AssetCount| c.key.starts_with(key)).map_or((0, 0), |c| (c.inserted, c.detached))
};
(of("S:"), of("VariableID:"))
}
#[test]
fn applying_counts_once_per_layer_that_takes_it() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
assert_eq!(counts(&s).0, (2, 0));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
assert_eq!(counts(&s).0, (2, 0), "a layer that has it already adds nothing");
let three = rect(&mut s, 200);
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [three.0], "field": "fill"}));
assert_eq!(counts(&s).1, (1, 0));
}
#[test]
fn duplicating_and_pasting_content_counts_what_it_uses() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (2, 0), "the copy inserts it too");
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "edit.paste", json!({}));
assert_eq!(counts(&s).0, (3, 0));
}
#[test]
fn an_instance_counts_as_its_component_alone() {
let (mut s, lib, _) = user();
let i = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0})));
assert_eq!(counts(&s).0, (0, 0), "placing it");
ex(&mut s, "select.set", json!({"ids": [i.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (0, 0), "duplicating it");
assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2);
}
#[test]
fn only_the_detach_buttons_detach() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [two.0], "field": "stroke"}));
ex(&mut s, "style.detach", json!({"ids": [one.0, two.0], "which": "fill"}));
assert_eq!(counts(&s).0, (2, 2));
ex(&mut s, "variable.bind", json!({"ids": [two.0], "field": "stroke"}));
assert_eq!(counts(&s).1, (1, 1));
// Another style in its place isn't a detach of the first.
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
assert_eq!(counts(&s).0, (3, 2));
}
#[test]
fn local_styles_count_nothing_and_undo_takes_a_count_back() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
ex(&mut s, "style.detach", json!({"ids": [one.0], "which": "fill"}));
assert!(s.doc().unwrap().libraries.asset_counts.is_empty());
assert!(asset_actions(s.doc().unwrap(), &lib).is_none());
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
let report = asset_actions(s.doc().unwrap(), &lib).unwrap();
assert_eq!((report.inserted.len(), report.detached.len()), (1, 0));
ex(&mut s, "edit.undo", json!({}));
assert_eq!(counts(&s).0, (0, 0));
}
@@ -98,10 +98,13 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply {
LibraryReply::Published { version: 1 }
}
(LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()),
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted,
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_), _) => {
LibraryReply::Noted
}
(LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()),
(LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()),
(LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()),
(LibraryReq::AssetActions, _) => LibraryReply::AssetActions(Vec::new()),
}
}
+2
View File
@@ -290,6 +290,8 @@ mod ui_params_tests;
#[cfg(test)]
mod ui_scale_tests;
#[cfg(test)]
mod usage_summary_tests;
#[cfg(test)]
mod variable_picker_tests;
#[cfg(test)]
mod variables_export_ui_tests;
+28 -11
View File
@@ -1028,22 +1028,32 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
}
let actions = v["actionsKnown"].as_bool().unwrap_or(false);
let inserted_n = |n: u64| trn("{n} inserted", n as usize, &[]);
if actions {
let Some(kind) = usage_kind(ui, w, usage_id, &v) else {
ui.add_space(8.0);
return;
};
if let Some((i, d)) = period_totals(&v, kind) {
let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2);
let (i, d) = (v["insertions"].as_u64().unwrap_or(0), v["detachments"].as_u64().unwrap_or(0));
let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &trn("{n} detached", d as usize, &[]))]);
hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)]));
} else {
hint(ui, tr("This server doesn't count insertions"));
}
let Some(kind) = usage_kind(ui, w, usage_id, &v) else {
ui.add_space(8.0);
return;
};
if v["assetsKnown"].as_bool() == Some(true) && v[kind].as_array().is_none_or(Vec::is_empty) {
hint(ui, tr("Nothing counted yet"));
}
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))]);
// Inserted and detached in the period, after what it counts in all.
let (added, gone) = (a["insertions"].as_u64().unwrap_or(0), a["detachments"].as_u64().unwrap_or(0));
let counts = if added > 0 { trf("{used} · {inserted}", &[("used", &counts), ("inserted", &inserted_n(added))]) } else { counts };
let counts = if gone > 0 {
trf("{used} · {detached}", &[("used", &counts), ("detached", &trn("{n} detached", gone as usize, &[]))])
} else {
counts
};
usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts);
}
ui.add_space(8.0);
@@ -1067,6 +1077,17 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
ui.add_space(8.0);
}
/// What the `kind` list of a Show usage answer adds up to in its period: insertions and
/// detachments, `None` from a server that doesn't count them for that kind.
pub(crate) fn period_totals(v: &Value, kind: &str) -> Option<(u64, u64)> {
let known = if kind == "components" { "actionsKnown" } else { "assetActionsKnown" };
(v[known].as_bool() == Some(true)).then(|| {
let rows = v[kind].as_array().map_or(&[][..], Vec::as_slice);
let sum = |key: &str| rows.iter().filter_map(|r| r[key].as_u64()).sum();
(sum("insertions"), sum("detachments"))
})
}
/// 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.
@@ -1092,11 +1113,7 @@ fn usage_kind(ui: &mut Ui, w: f32, id: Id, v: &Value) -> Option<&'static str> {
});
});
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)
Some(KINDS.get(at)?.0)
}
/// A Show usage row: two lines, as the counts don't leave a name room on one.
+30
View File
@@ -0,0 +1,30 @@
//! Show usage's period line sums the list the Type choice shows, so it never reads 0 above a list
//! with counts, and a server that doesn't count a kind says so for that kind alone.
use serde_json::json;
use crate::panels::assets_panel::period_totals;
#[test]
fn the_period_line_sums_the_list_shown() {
let v = json!({
"actionsKnown": true,
"assetActionsKnown": true,
"insertions": 0,
"detachments": 0,
"components": [],
"styles": [{"insertions": 3, "detachments": 1}, {"insertions": 2, "detachments": 0}],
"variables": [{"insertions": 1, "detachments": 4}],
});
assert_eq!(period_totals(&v, "components"), Some((0, 0)));
assert_eq!(period_totals(&v, "styles"), Some((5, 1)));
assert_eq!(period_totals(&v, "variables"), Some((1, 4)));
}
#[test]
fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() {
let v = json!({"actionsKnown": true, "components": [{"insertions": 2, "detachments": 1}], "styles": [{"layers": 3}]});
assert_eq!(period_totals(&v, "components"), Some((2, 1)));
assert_eq!(period_totals(&v, "styles"), None, "a server from before them");
assert_eq!(period_totals(&json!({}), "components"), None);
}
+5 -3
View File
@@ -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 \| 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. |
| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets \| reportAssetActions {file, inserted, detached} \| assetActions}` | 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}] \| 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. |
| `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}] \| assetActions [{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. |
| `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. |
@@ -848,7 +848,9 @@ resuming with its offline edits, and leaving the session going back to snapshot
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
them. It sends `reportAssetActions` with its totals of inserted and detached styles and variables,
counted over the weeks as for components (`asset-actions.json`), and `assetActions` answers with
those weeks (`component` is the style's or variable's id). 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
+3 -2
View File
@@ -1,6 +1,6 @@
# Components, variants, styles and variables parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; 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)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; 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
@@ -54,7 +54,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Go to main component from an instance of a library component | done | opens the library file in a tab, or brings it to the front, on the page holding the main, selected and zoomed to; a variant goes to that variant. Team libraries on a server are refused with a note; no Return to instance yet |
| 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; the layers and files using each style and variable, without insertions, detachments or modes; 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, with their insertions and detachments over the same periods, no 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
@@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Date | Change | Summary |
|---|---|---|
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
| 2026-11-18 | patch | M3: Combine as variants gives every variant the component properties any of the components had (as a property added to a set goes to all its variants); a property made on one component before combining was missing from the others, so their layers couldn't be bound to it and an instance switched to them dropped its value. A variant with a property of the same name keeps its own. Tests: `variant_shared_props_tests`. |
| 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. |
| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. |
+6 -6
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1028,7 +1028,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, assetsKnown, styles [{id, name, type, layers, files}], variables [{id, name, collection, layers, files}], instances, detached, detachesKnown, days,
- `library.usage {library?, days?}` → `{id, name, assetsKnown, assetActionsKnown, styles [{id, name, type, layers, files, insertions, detachments}], variables [{id, name, collection, layers, files, insertions, detachments}], 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
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -254,8 +254,9 @@ which other files use without anyone copying the library file around.
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
layers and files using each style and variable with their insertions and detachments. Applying
a style or variable, or copying or duplicating content that uses it, inserts it, and the Detach
button detaches it. 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