diff --git a/ROADMAP.md b/ROADMAP.md index ad2ae9f69..107a11f96 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. | diff --git a/apps/figcraft-server/src/disk.rs b/apps/figcraft-server/src/disk.rs index 219bce324..19cbfc8d3 100644 --- a/apps/figcraft-server/src/disk.rs +++ b/apps/figcraft-server/src/disk.rs @@ -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"; diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4c9b8aaef..9cbf24e1d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -5,12 +5,15 @@ use std::time::{Duration, Instant}; -use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg}; +use figcraft_collab::message::{ + Access, AssetActions, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg, Usage, +}; use figcraft_collab_net::Invite; use figcraft_doc::NodeId; use figcraft_engine::Session; use serde_json::{Value, json}; +use crate::store::{MAX_USERS, Store}; use crate::test_util::{Raw, TempDir, config, publish, session}; fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { @@ -79,7 +82,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 +146,76 @@ 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["assetActionsKnown"] == true + && u["styles"][0]["insertions"] == 2 + && u["styles"][0]["detachments"] == 1 + && 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 && u["styles"][0]["layers"] == 0); + 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(); +} + +#[test] +fn evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice() { + let dir = TempDir::new("library-asset-peaks-evict"); + 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 p = publish(&mut a, dir.path(), addr); + ex(&mut a, "library.publishToServer", json!({})); + let file = Invite::parse(&p.edit).unwrap().file; + server.stop(); + drop(server); + + let mut store = Store::open(dir.path(), cfg.store()).unwrap(); + for i in 0..MAX_USERS { + store.report_usage(&file, Usage { file: format!("Old{i}"), components: Vec::new() }).unwrap(); + } + let actions = AssetActions { file: "Kept".into(), inserted: vec![("Brand".into(), 2)], detached: Vec::new() }; + store.report_asset_actions(&file, actions.clone()).unwrap(); + // One more usage-only file would evict "Kept" if asset activity did not count for retention. + store.report_usage(&file, Usage { file: "Extra".into(), components: Vec::new() }).unwrap(); + store.report_asset_actions(&file, actions).unwrap(); + let weeks = store.library_asset_actions(&file).unwrap(); + let brand: Vec<_> = weeks.iter().filter(|w| w.component == "Brand").collect(); + assert_eq!(brand.len(), 1, "{weeks:?}"); + assert_eq!(brand[0].insertions, 2, "lost peaks would grow the same totals again: {weeks:?}"); + assert_eq!(brand[0].detachments, 0, "{weeks:?}"); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index 2e713deb2..d75a24f1b 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -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; @@ -103,7 +103,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published /// Most files whose usage of one library is kept (the least recently changed go first), and most /// components one file's report keeps. -const MAX_USERS: usize = 200; +pub(crate) const MAX_USERS: usize = 200; const MAX_REPORTED: usize = 1_000; /// Largest `usage.json` (and `actions.json`) read. const MAX_USAGE_FILE: u64 = 16 << 20; @@ -298,6 +298,8 @@ struct UsageCache { list: Vec, /// Insertions and detachments week by week, over every file (kept in `actions.json`). weeks: Vec, + /// The same for styles and variables (kept in `asset-actions.json`). + asset_weeks: Vec>, dirty: bool, written: u64, } @@ -321,6 +323,11 @@ 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)>, + /// When this file last reported style or variable insertions or detachments (seconds since 1970, UTC). + #[serde(default, skip_serializing_if = "is_zero")] + asset_updated: u64, } fn is_zero(n: &u64) -> bool { @@ -560,7 +567,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 { - 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); diff --git a/apps/figcraft-server/src/store/backend.rs b/apps/figcraft-server/src/store/backend.rs index 5d4a3bfe9..42900e6b8 100644 --- a/apps/figcraft-server/src/store/backend.rs +++ b/apps/figcraft-server/src/store/backend.rs @@ -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), } } diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 322c906e8..42d284b04 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -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(path: &Path) -> Vec { 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(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, grown: &[(NodeId, u32)], kind: Count, t: u64) { +fn add_to_week(weeks: &mut Vec>, 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,37 @@ 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>, 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); + if grown.is_empty() { + return false; + } + // Heard from for retention: evicting the row would drop asset_peaks, the + // baseline grow uses so a later identical report is not counted twice. + e.asset_updated = now(); + true + })?; + 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> { @@ -297,7 +335,7 @@ impl Store { let at = match u.list.iter().position(|e| e.usage.file == name) { Some(at) => at, None => { - u.list.push(UsageEntry { usage: Usage { file: name, components: Vec::new() }, ..UsageEntry::default() }); + u.list.push(UsageEntry { usage: Usage { file: name.clone(), components: Vec::new() }, ..UsageEntry::default() }); u.list.len() - 1 } }; @@ -306,7 +344,13 @@ impl Store { return Ok(()); } if u.list.len() > MAX_USERS { - u.list.sort_by_key(|e| std::cmp::Reverse(e.updated.max(e.detached_updated))); + // The file just heard from stays, even when several share a timestamp (now() is + // seconds). Asset-action reports use asset_updated so their peaks are not dropped + // in favour of a usage-only row from the same second. + u.list.sort_by_key(|e| { + let recent = e.usage.file == name; + std::cmp::Reverse((e.updated.max(e.detached_updated).max(e.asset_updated), recent)) + }); u.list.truncate(MAX_USERS); } u.dirty = true; @@ -325,7 +369,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); @@ -345,3 +390,17 @@ fn library_file(dir: &Path, version: u64) -> PathBuf { let path = dir.join(library_name(version)); if path.exists() { path } else { dir.join(LIBRARY) } } + +#[cfg(test)] +mod grow_tests { + use super::*; + + #[test] + fn a_new_key_is_dropped_once_peaks_are_full() { + let mut peaks: Vec<(u32, u32, u32)> = (0..MAX_REPORTED as u32).map(|i| (i, 1, 0)).collect(); + let grown = grow(&mut peaks, &[(MAX_REPORTED as u32, 3)], Count::Inserted, |_| 0); + assert!(grown.is_empty(), "a key past the cap must not start a peak or count as growth"); + assert_eq!(peaks.len(), MAX_REPORTED); + assert!(peaks.iter().all(|p| p.0 < MAX_REPORTED as u32)); + } +} diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 30bc587c3..198022a09 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -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 }); diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..1ba0896aa 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -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 { 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), Actions(Vec), Assets(Vec), + AssetActions(Vec>), } /// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 35279aae4..828e1605b 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -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, + /// 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, } /// 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, 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. diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 785e6c748..054710464 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -83,14 +83,66 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option { 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. An instance and the +/// layers in it don't count: an instance counts as its component alone, as in [`count_inserted`]. +fn library_links(doc: &Document) -> BTreeMap { + let mut links = BTreeMap::new(); + if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() { + return links; + } + let mut stack = doc.pages.clone(); + while let Some(id) = stack.pop() { + let Some(n) = doc.node(id) else { continue }; + if matches!(n.kind, NodeKind::Instance { .. }) { + continue; + } + stack.extend(n.children.iter().copied()); + for local in asset_links(n).into_iter().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(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result) -> Result { + 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 +151,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. diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 81889be5d..f8ddf0e50 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -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,43 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option { 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. Every count the document keeps is included (up to +/// [`figcraft_doc::MAX_DETACH_COUNTS`]); the wire message is capped at [`MAX_ASSET_USAGE`], so +/// [`asset_action_reports`] splits them into batches an older server still accepts. +pub fn asset_actions(doc: &Document, library: &str) -> Option { + 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))).collect(); + (!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) }) +} + +/// Reports for the server, each with at most [`MAX_ASSET_USAGE`] inserted and detached counts. +pub fn asset_action_reports(doc: &Document, library: &str) -> Vec { + let Some(full) = asset_actions(doc, library) else { return Vec::new() }; + chunk_asset_actions(full) +} + +fn chunk_asset_actions(actions: AssetActions) -> Vec { + let AssetActions { file, inserted, detached } = actions; + if inserted.is_empty() && detached.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + let mut i = 0; + let mut d = 0; + loop { + let ins: Vec<_> = inserted.get(i..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + let det: Vec<_> = detached.get(d..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + if ins.is_empty() && det.is_empty() { + break; + } + i += ins.len(); + d += det.len(); + out.push(AssetActions { file: file.clone(), inserted: ins, detached: det }); + } + out +} + /// `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(); @@ -271,8 +308,9 @@ impl Session { inserted(doc, &l.id).map(LibraryReq::ReportInserted), asset_usage(doc, &l.id).map(LibraryReq::ReportAssets), ]; + let asset_reports = asset_action_reports(doc, &l.id).into_iter().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)) + std::iter::once(fetch).chain(reports.into_iter().flatten()).chain(asset_reports).map(|req| (l.path.clone(), req)) }) .collect(); // Confined to automation roots, nothing reaches a server (#1095). diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index d8e2e6893..e562b142b 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { 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 = std::collections::BTreeMap::new(); @@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { "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>, describe: impl Fn(&str) -> Option) -> Vec { +/// 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>>> { + 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]) -> 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>, + actions: &std::collections::BTreeMap<&str, (u64, u64)>, + describe: impl Fn(&str) -> Option, +) -> Vec { 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() diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 710eec76e..f5a0dd6a0 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option Result { + crate::library::counting_links(s, true, |s| detach_style(s, p)) +} + +fn detach_style(s: &mut Session, p: &Value) -> Result { 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 { + crate::library::counting_links(s, false, |s| apply_style(s, p)) +} + +fn apply_style(s: &mut Session, p: &Value) -> Result { 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 { + crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p)) +} + +fn bind_field(s: &mut Session, p: &Value) -> Result { let cmd = "variable.bind"; let field = req_string(cmd, p, "field")?; let var = string(p, "variable"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a74219fb6..3e4af48c3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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; diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs new file mode 100644 index 000000000..1eb3a1403 --- /dev/null +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -0,0 +1,183 @@ +//! 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_action_reports, asset_actions}; +use figcraft_collab::message::MAX_ASSET_USAGE; +use figcraft_doc::{AssetCount, Document, NodeId, NodeKind, 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); +} + +/// Applying and detaching a library style or variable on an instance, on a layer in it, or on a +/// layer of an instance nested in it counts nothing either: what an instance uses counts as it. +#[test] +fn applying_and_detaching_inside_an_instance_counts_nothing() { + let (mut s, lib, _) = user(); + let placed = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0}))); + // A Button holding a rectangle and an Icon instance (the Icon holds a dot), and a Button instance. + let icon = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 24, "height": 24, "name": "Icon"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 8, "height": 8, "parent": icon.0})); + let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon.0]}))); + let button = idv(&ex(&mut s, "frame.create", json!({"x": 100, "y": 200, "width": 80, "height": 40, "name": "Button"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 80, "height": 40, "parent": button.0})); + ex(&mut s, "instance.create", json!({"component": icon.0, "parent": button.0, "x": 4, "y": 4})); + let button = idv(&ex(&mut s, "component.create", json!({"ids": [button.0]}))); + let i = idv(&ex(&mut s, "instance.create", json!({"component": button.0, "x": 300, "y": 200}))); + let (layer, nested, deep) = { + let d = s.doc().unwrap(); + let kids = |id: NodeId| d.node(id).unwrap().children.clone(); + let nested = kids(i).into_iter().find(|k| matches!(d.node(*k).unwrap().kind, NodeKind::Instance { .. })).unwrap(); + let layer = kids(i).into_iter().find(|k| *k != nested).unwrap(); + (layer, nested, kids(nested)[0]) + }; + let targets = [placed.0, i.0, layer.0, nested.0, deep.0]; + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": targets})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": targets, "field": "stroke"})); + let d = s.doc().unwrap(); + assert!(d.node(deep).unwrap().styles.fill.is_some() && !d.node(deep).unwrap().bound.is_empty(), "the nested layer took both"); + ex(&mut s, "style.detach", json!({"ids": targets, "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": targets, "field": "stroke"})); + assert_eq!(counts(&s), ((0, 0), (0, 0))); + // The same on a plain layer counts. + let plain = rect(&mut s, 600); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [plain.0]})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [plain.0], "field": "stroke"})); + ex(&mut s, "style.detach", json!({"ids": [plain.0], "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": [plain.0], "field": "stroke"})); + assert_eq!(counts(&s), ((1, 1), (1, 1))); +} + +#[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)); +} + +#[test] +fn asset_action_reports_cover_every_count_past_the_message_cap() { + let mut doc = Document::new("File"); + let n = MAX_ASSET_USAGE + 1; + let libraries = std::sync::Arc::make_mut(&mut doc.libraries); + for i in 0..n { + let key = format!("s{i}"); + libraries.count_asset("Lib", &key, false, 1); + libraries.count_asset("Lib", &key, true, 2); + } + // Another library's counts do not belong in these reports. + libraries.count_asset("Other", "x", false, 9); + libraries.count_asset("Other", "x", true, 9); + + let full = asset_actions(&doc, "Lib").unwrap(); + assert_eq!(full.inserted.len(), n, "the document's counts are not truncated"); + assert_eq!(full.detached.len(), n); + + let reports = asset_action_reports(&doc, "Lib"); + assert!(reports.len() >= 2, "one message cannot carry {n} counts"); + assert!(reports.iter().all(|r| r.file == "File" && r.inserted.len() <= MAX_ASSET_USAGE && r.detached.len() <= MAX_ASSET_USAGE)); + let inserted: Vec<_> = reports.iter().flat_map(|r| r.inserted.iter().cloned()).collect(); + let detached: Vec<_> = reports.iter().flat_map(|r| r.detached.iter().cloned()).collect(); + assert_eq!(inserted, full.inserted); + assert_eq!(detached, full.detached); + assert!(asset_action_reports(&doc, "Missing").is_empty()); +} diff --git a/crates/engine/src/sharing/background/tests.rs b/crates/engine/src/sharing/background/tests.rs index 6f98841df..cd9bc951c 100644 --- a/crates/engine/src/sharing/background/tests.rs +++ b/crates/engine/src/sharing/background/tests.rs @@ -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()), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fcabb5d8f..fecdc3882 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -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; diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 41f7762ff..9ee6c0dfe 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1008,63 +1008,109 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { }); app.run_background(&ui.ctx().clone(), USAGE, json!({"days": period.unwrap_or(days)}), done); } - let Some(v) = shown else { - ui.add_space(8.0); - return; - }; + match shown { + Some(v) => usage_answer(ui, w, usage_id, &v), + None => ui.add_space(8.0), + } +} + +/// Show usage's answer `v`: what uses the library, the period's insertions and detachments and +/// the rows of the list chosen (the choice kept with `id`). +pub(crate) fn usage_answer(ui: &mut Ui, w: f32, id: Id, v: &Value) { + let days = v["days"].as_u64().unwrap_or(USAGE_PERIODS[0].0); let files = v["files"].as_array().map_or(0, Vec::len); let instances = v["instances"].as_u64().unwrap_or(0); - let files_n = |n: u64| trn("{n} files", n as usize, &[]); - let instances_n = |n: u64| trn("{n} instances", n as usize, &[]); - // Detached instances, beside what they are counted with (a server from before them keeps none). let known = v["detachesKnown"].as_bool().unwrap_or(false); - let with_detached = |used: String, n: u64| { - if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &trn("{n} detached", n as usize, &[]))]) } else { used } - }; let used = trf("Used in {files} · {instances}", &[("files", &files_n(files as u64)), ("instances", &instances_n(instances))]); - hint(ui, &with_detached(used, v["detached"].as_u64().unwrap_or(0))); + hint(ui, &with_detached(known, used, v["detached"].as_u64().unwrap_or(0))); if !known { hint(ui, tr("This server doesn't count detached instances")); } - 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, 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, &[]))]); + let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &detached_n(d))]); 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 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; + 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" { + component_rows(ui, w, v, known); + } else { + asset_rows(ui, w, v, kind); + } + ui.add_space(8.0); +} + +fn files_n(n: u64) -> String { + trn("{n} files", n as usize, &[]) +} + +fn instances_n(n: u64) -> String { + trn("{n} instances", n as usize, &[]) +} + +fn inserted_n(n: u64) -> String { + trn("{n} inserted", n as usize, &[]) +} + +fn detached_n(n: u64) -> String { + trn("{n} detached", n as usize, &[]) +} + +/// `used`, with the detached instances beside it (a server from before them keeps none: `known`). +fn with_detached(known: bool, used: String, n: u64) -> String { + if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &detached_n(n))]) } else { used } +} + +/// `used`, with the insertions counted in the period after it. +fn with_inserted(used: String, n: u64) -> String { + if n > 0 { trf("{used} · {inserted}", &[("used", &used), ("inserted", &inserted_n(n))]) } else { used } +} + +/// Show usage's rows for a style or variable list. +fn asset_rows(ui: &mut Ui, w: f32, v: &Value, kind: &str) { + 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))]); + let counts = with_detached(true, with_inserted(counts, a["insertions"].as_u64().unwrap_or(0)), a["detachments"].as_u64().unwrap_or(0)); + usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); + } +} + +/// Show usage's rows for the components; `known`: the server counts detached instances. +fn component_rows(ui: &mut Ui, w: f32, v: &Value, known: bool) { + let actions = v["actionsKnown"].as_bool().unwrap_or(false); 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 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 { - trn("{n} detached", gone as usize, &[]) + detached_n(gone) } else { - with_detached(trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) + with_detached(known, trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) }; - // 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 }; - usage_row(ui, w, name, &right); + let added = if actions { c["insertions"].as_u64().unwrap_or(0) } else { 0 }; + usage_row(ui, w, name, &with_inserted(right, added)); } - 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 @@ -1092,11 +1138,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. diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs new file mode 100644 index 000000000..72941743f --- /dev/null +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -0,0 +1,89 @@ +//! 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. The answer draws +//! its totals, its period and the rows of the list chosen. + +use serde_json::json; + +use crate::live_tests::{flat, has_text}; +use crate::panels::assets_panel::{period_totals, usage_answer}; + +#[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); +} + +/// The texts Show usage draws for the answer `v` with the Type choice at `kind` (0 components, +/// 1 styles, 2 variables). +fn drawn(v: &serde_json::Value, kind: usize) -> Vec { + let ctx = egui::Context::default(); + let id = egui::Id::unique("usage_summary_tests"); + ctx.data_mut(|d| d.insert_temp(id.with("kind"), kind)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| usage_answer(ui, 600.0, id, v)); + out.textures_delta.clear(); + flat(&out.shapes) +} + +#[test] +fn show_usage_draws_the_totals_the_period_and_the_list_chosen() { + let v = json!({ + "days": 90, + "files": [{}, {}], + "instances": 5, + "detachesKnown": true, + "detached": 3, + "actionsKnown": true, + "assetActionsKnown": true, + "assetsKnown": true, + "components": [ + {"name": "Button", "instances": 4, "files": 2, "detached": 2, "insertions": 6, "detachments": 2}, + {"name": "Gone", "instances": 0, "files": 0, "detached": 3}, + ], + "styles": [{"name": "Brand", "layers": 7, "files": 3, "insertions": 2, "detachments": 0}], + "variables": [], + }); + let components = drawn(&v, 0); + for text in [ + "Used in 2 files · 5 instances · 3 detached", + "Past 90 days: 6 inserted · 2 detached", + "4 instances in 2 files · 2 detached · 6 inserted", + "3 detached", + ] { + assert!(has_text(&components, text), "{text}"); + } + let styles = drawn(&v, 1); + assert!(has_text(&styles, "Past 90 days: 2 inserted · 0 detached")); + assert!(has_text(&styles, "7 layers in 3 files · 2 inserted")); + assert!(has_text(&drawn(&v, 2), "Nothing counted yet"), "an empty list says so"); +} + +#[test] +fn show_usage_from_an_older_server_says_what_it_doesnt_count() { + let shapes = drawn(&json!({"files": [{}, {}], "instances": 5, "components": []}), 0); + for text in [ + "Used in 2 files · 5 instances", + "This server doesn't count detached instances", + "This server doesn't count styles and variables", + "This server doesn't count insertions", + ] { + assert!(has_text(&shapes, text), "{text}"); + } +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 41c73190d..a3e9ccae5 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -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 diff --git a/docs/components-parity.md b/docs/components-parity.md index 73d1d8ced..bb2a3e2ab 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -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. | diff --git a/docs/gaps.md b/docs/gaps.md index 8e1d60686..bb3ede386 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); 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 count insertions for components only | Feature | 4–8 | [components-parity](components-parity.md) | +| 10 | Team libraries: no team-wide lists or accounts; analytics don't count modes | 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) | @@ -378,11 +378,10 @@ 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 count insertions for components only +### 10. Team libraries: no team-wide lists or accounts; analytics don't count modes - **Missing:** libraries listed for a whole team or organization (each file enables a library by - 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), + its link), accounts and per-person library permissions, mode counts (a component's instances and a style's + or variable's layers are counted, with their insertions and detachments 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 @@ -618,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | | 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | diff --git a/docs/mcp.md b/docs/mcp.md index 0a557c6b2..8940fa184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 78f4d4df3..b797063a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; 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; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); 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; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); 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; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); 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); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); 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); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **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; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; 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; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); 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; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); 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; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); 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); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); 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); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | 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-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | diff --git a/docs/server.md b/docs/server.md index 37f0182d9..c7cbe3093 100644 --- a/docs/server.md +++ b/docs/server.md @@ -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