From a61c2b33f60ebe86a3f7caa6a5975a202e3d62e1 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 23:17:33 +0100 Subject: [PATCH 1/2] M8: a frame can say which screen size it is and carry rules for other sizes A design file has no breakpoints, so an agent implementing a frame can only guess how it should respond. The designer can now say it outright: `responsive.set` marks frames as the mobile, tablet or desktop version of a design (layer data, so the file format is unchanged), and `responsive.rule` adds a note to the Responsive annotation category, made if the file lacks it. `responsive.list` returns what was stated about the given layers, the layers above them and those inside them, and never infers anything from names or sizes. The Inspect tab gets a Screen sizes section for frames. Explicit targets are checked rather than falling back to the selection, a rule keeps to the limits `annotation.add` has (note length, annotations per layer, number of categories), and the result says `truncated` when there were too many layers to read every rule. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/dev.rs | 1 + crates/engine/src/dev/annotations.rs | 28 +-- crates/engine/src/dev/responsive.rs | 204 +++++++++++++++++++++ crates/engine/src/lib.rs | 3 + crates/engine/src/responsive_tests.rs | 172 +++++++++++++++++ crates/ui-egui/locales/en.toml | 7 + crates/ui-egui/src/panels/dev_mode.rs | 48 ++++- crates/ui-egui/src/panels/right/inspect.rs | 1 + docs/mcp.md | 11 ++ 11 files changed, 462 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/dev/responsive.rs create mode 100644 crates/engine/src/responsive_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 2286b0c6e..4fb9213dc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M8: screen sizes for agents. A frame can be marked as the mobile, tablet or desktop version of a design, and given rules for other sizes as notes in the Responsive annotation category, in the Inspect tab's Screen sizes section, `responsive.set` and `responsive.rule`. `responsive.list` returns only what the designer stated: nothing is inferred from names or sizes. Marks are layer data and rules are annotations, so the file format doesn't change. Numbers unchanged. Tests: `responsive_tests`. | | 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged | | 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`. | diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b90204504..bc656e824 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -101,6 +101,7 @@ fn registry() -> &'static Registry { list.extend(crate::codegen::specs()); list.extend(crate::devinspect::specs()); list.extend(crate::design_context::specs()); + list.extend(crate::responsive::specs()); list.extend(crate::component_codegen::specs()); list.extend(crate::playground::specs()); list.extend(crate::code_connect::specs()); diff --git a/crates/engine/src/dev.rs b/crates/engine/src/dev.rs index a1bc7bb18..e0044e7ed 100644 --- a/crates/engine/src/dev.rs +++ b/crates/engine/src/dev.rs @@ -7,4 +7,5 @@ pub mod dev_measurements; pub mod dev_resources; pub mod devcompare; pub mod devinspect; +pub mod responsive; pub mod tailwind; diff --git a/crates/engine/src/dev/annotations.rs b/crates/engine/src/dev/annotations.rs index 45b867ab8..fa4b5356d 100644 --- a/crates/engine/src/dev/annotations.rs +++ b/crates/engine/src/dev/annotations.rs @@ -44,6 +44,18 @@ pub fn find_category<'a>(list: &'a [AnnotationCategory], key: &str) -> Option<&' list.iter().find(|c| c.id == key).or_else(|| list.iter().find(|c| c.name.eq_ignore_ascii_case(key))) } +/// A colour no category in `list` has, if there is one. +pub(crate) fn unused_color(list: &[AnnotationCategory]) -> figcraft_color::Color { + let used = |c: &figcraft_color::Color| list.iter().any(|x| x.color.to_hex() == c.to_hex()); + let fallback = AnnotationCategory::COLORS.get(list.len() % AnnotationCategory::COLORS.len()).copied().unwrap_or(figcraft_color::Color::BLACK); + AnnotationCategory::COLORS.iter().find(|c| !used(c)).copied().unwrap_or(fallback) +} + +/// An id no category in `list` has. +pub(crate) fn free_category_id(list: &[AnnotationCategory]) -> String { + (1..=MAX_CATEGORIES + 1).map(|k| format!("custom-{k}")).find(|i| !list.iter().any(|c| c.id == *i)).unwrap_or_default() +} + fn category_json(c: &AnnotationCategory) -> Value { json!({"id": c.id, "name": c.name, "color": c.color.to_css_hex()}) } @@ -188,7 +200,7 @@ fn parse_properties(cmd: &str, p: &Value) -> crate::Result>> } /// `label` from params, trimmed of trailing whitespace and capped. -fn parse_label(cmd: &str, p: &Value) -> crate::Result> { +pub(crate) fn parse_label(cmd: &str, p: &Value) -> crate::Result> { match get(p, "label").or_else(|| get(p, "text")) { None => Ok(None), Some(Value::String(s)) => Ok(Some(s.trim_end().chars().take(MAX_LABEL).collect())), @@ -381,18 +393,8 @@ pub fn specs() -> Vec { return Err(bad(cmd, format!("a file has at most {MAX_CATEGORIES} categories"))); } let name = category_name(cmd, &list, None, p)?.ok_or_else(|| bad(cmd, "`name` required"))?; - let color = match category_color(cmd, p)? { - Some(c) => c, - None => { - let used = |c: &figcraft_color::Color| list.iter().any(|x| x.color.to_hex() == c.to_hex()); - let fallback = AnnotationCategory::COLORS - .get(list.len() % AnnotationCategory::COLORS.len()) - .copied() - .unwrap_or(figcraft_color::Color::BLACK); - AnnotationCategory::COLORS.iter().find(|c| !used(c)).copied().unwrap_or(fallback) - } - }; - let id = (1..=MAX_CATEGORIES + 1).map(|k| format!("custom-{k}")).find(|i| !list.iter().any(|c| c.id == *i)).unwrap_or_default(); + let color = category_color(cmd, p)?.unwrap_or_else(|| unused_color(&list)); + let id = free_category_id(&list); list.push(AnnotationCategory { id: id.clone(), name, color }); s.doc_mut()?.annotation_categories = Some(list); Ok(json!({"id": id})) diff --git a/crates/engine/src/dev/responsive.rs b/crates/engine/src/dev/responsive.rs new file mode 100644 index 000000000..6ac1124ac --- /dev/null +++ b/crates/engine/src/dev/responsive.rs @@ -0,0 +1,204 @@ +//! Responsive context: what the designer states about other screen sizes. A file has no +//! breakpoints, so this holds only what was said outright: frames marked as the mobile, tablet or +//! desktop version of one design (in layer data, so the file format doesn't change), and notes in +//! the Responsive annotation category. Nothing here is worked out from names or sizes: an agent +//! must never take a guess for the designer's word. + +use figcraft_doc::{Annotation, AnnotationCategory, Document, NodeId, NodeKind}; +use serde_json::{Value, json}; + +use crate::annotations::{MAX_CATEGORIES, MAX_PER_LAYER, categories, category_of, find_category, free_category_id, parse_label, unused_color}; +use crate::cmd::CommandSpec; +use crate::params::{get, req_targets, string}; +use crate::{Result, Session, bad, spec}; + +/// Layer data key: which version of a design a frame is. +pub const VIEWPORT_KEY: &str = "figcraft.viewport"; +/// Layer data key: which design it is a version of. +pub const GROUP_KEY: &str = "figcraft.viewportGroup"; +/// The annotation category responsive rules go in. +pub const RULES_CATEGORY: &str = "Responsive"; +/// The versions a frame can be. +pub const VIEWPORTS: [&str; 3] = ["mobile", "tablet", "desktop"]; +/// Longest group name (chars). +const MAX_GROUP: usize = 100; +/// Most layers looked through for rules. +const MAX_WALK: usize = 50_000; + +/// A marked frame as JSON. +fn frame_json(doc: &Document, id: NodeId) -> Option { + let n = doc.node(id)?; + Some( + json!({"id": id, "name": n.name, "viewport": n.plugin_data.get(VIEWPORT_KEY)?, "width": n.width, "height": n.height, "page": doc.page_of(id)}), + ) +} + +/// Every design with marked frames, narrowest first. +pub fn groups(doc: &Document) -> Vec<(String, Vec)> { + let mut out: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for n in doc.nodes().filter(|n| n.plugin_data.contains_key(VIEWPORT_KEY)) { + let group = n.plugin_data.get(GROUP_KEY).cloned().unwrap_or_else(|| n.name.clone()); + out.entry(group).or_default().push(n.id); + } + for frames in out.values_mut() { + frames.sort_by(|a, b| doc.node(*a).map_or(0.0, |n| n.width).total_cmp(&doc.node(*b).map_or(0.0, |n| n.width))); + } + out.into_iter().collect() +} + +fn group_json(doc: &Document, group: &str, frames: &[NodeId]) -> Value { + json!({"group": group, "frames": frames.iter().filter_map(|f| frame_json(doc, *f)).collect::>()}) +} + +/// Whether `a` is a responsive rule. +fn is_rule(doc: &Document, a: &Annotation) -> bool { + category_of(doc, a).is_some_and(|c| c.name.eq_ignore_ascii_case(RULES_CATEGORY)) +} + +/// `ids`, the layers above them and those under them, at most `max`; and whether some were left +/// out. +fn around(doc: &Document, ids: &[NodeId], max: usize) -> (Vec, bool) { + let mut cut = false; + let mut out = Vec::new(); + for id in ids { + let mut at = doc.node(*id).and_then(|n| n.parent); + while let Some(p) = at { + out.push(p); + at = doc.node(p).and_then(|n| n.parent); + } + out.extend(doc.subtree(*id)); + if out.len() > max { + out.truncate(max); + cut = true; + break; + } + } + out.sort_unstable(); + out.dedup(); + (out, cut) +} + +/// What the designer states about `ids` and the design they belong to. +pub fn context(doc: &Document, ids: &[NodeId]) -> Value { + context_within(doc, ids, MAX_WALK) +} + +/// [`context`], looking through at most `max` layers. +pub(crate) fn context_within(doc: &Document, ids: &[NodeId], max: usize) -> Value { + let (near, cut) = around(doc, ids, max); + let rules: Vec = near + .iter() + .filter_map(|i| doc.node(*i).map(|n| (i, n))) + .flat_map(|(i, n)| n.annotations.iter().filter(|a| is_rule(doc, a)).map(move |a| json!({"id": i, "layer": n.name, "text": a.label}))) + .collect(); + let versions: Vec = groups(doc) + .iter() + .filter(|(_, frames)| frames.iter().any(|f| near.contains(f))) + .map(|(group, frames)| group_json(doc, group, frames)) + .collect(); + let mut out = json!({"explicit": !rules.is_empty() || !versions.is_empty(), "versions": versions, "rules": rules}); + if cut { + // Rules on the layers left out weren't read: say so rather than imply there are none. + out["truncated"] = json!(true); + } + out +} + +fn set(s: &mut Session, p: &Value) -> Result { + let cmd = "responsive.set"; + let ids = req_targets(cmd, s, p)?; + // `get` reads an explicit null as left out; here it means clear. + let viewport = match p.get("viewport") { + None => return Err(bad(cmd, "`viewport` required: mobile|tablet|desktop, or null to clear")), + Some(Value::Null) => None, + Some(Value::String(v)) if VIEWPORTS.contains(&v.as_str()) => Some(v.clone()), + Some(_) => return Err(bad(cmd, "viewport: mobile|tablet|desktop, or null to clear")), + }; + let group = string(p, "group").map(|g| g.trim().to_string()); + if group.as_ref().is_some_and(|g| g.is_empty() || g.chars().count() > MAX_GROUP) { + return Err(bad(cmd, format!("group: a name up to {MAX_GROUP} characters"))); + } + let doc = s.doc_mut()?; + for id in &ids { + let n = doc.get(*id)?; + if !(n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })) { + return Err(bad(cmd, format!("{id} isn't a frame"))); + } + } + for id in &ids { + let n = doc.get_mut(*id)?; + match &viewport { + Some(v) => { + n.plugin_data.insert(VIEWPORT_KEY.into(), v.clone()); + if let Some(g) = &group { + n.plugin_data.insert(GROUP_KEY.into(), g.clone()); + } + } + None => { + n.plugin_data.remove(VIEWPORT_KEY); + n.plugin_data.remove(GROUP_KEY); + } + } + } + Ok(json!({"ids": ids, "viewport": viewport})) +} + +fn rule(s: &mut Session, p: &Value) -> Result { + let cmd = "responsive.rule"; + let id = req_targets(cmd, s, p)?.first().copied().ok_or_else(|| bad(cmd, "select a layer"))?; + // Capped like `annotation.add`'s note. + let text = parse_label(cmd, p)?.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).ok_or_else(|| bad(cmd, "`text` required"))?; + let doc = s.doc_mut()?; + if doc.get(id)?.annotations.len() >= MAX_PER_LAYER { + return Err(bad(cmd, format!("a layer has at most {MAX_PER_LAYER} annotations"))); + } + let mut list = categories(doc).to_vec(); + let category = match find_category(&list, RULES_CATEGORY) { + Some(c) => c.id.clone(), + None if list.len() >= MAX_CATEGORIES => { + return Err(bad(cmd, format!("a file has at most {MAX_CATEGORIES} annotation categories, and none is {RULES_CATEGORY}"))); + } + None => { + let (cid, color) = (free_category_id(&list), unused_color(&list)); + list.push(AnnotationCategory { id: cid.clone(), name: RULES_CATEGORY.into(), color }); + doc.annotation_categories = Some(list); + cid + } + }; + let n = doc.get_mut(id)?; + n.annotations.push(Annotation { label: text, properties: Vec::new(), category: Some(category) }); + Ok(json!({"id": id, "index": n.annotations.len() - 1})) +} + +pub fn specs() -> Vec { + vec![ + spec!( + "responsive.set", + "Mark as screen size version", + "{ids? (frames; default the selection), viewport: mobile|tablet|desktop (null: clear), group? (the design they are versions of; default each frame's name)} says which version of a design a frame is, in its layer data", + true, + set + ), + spec!( + "responsive.rule", + "Add responsive rule", + "{id? (default the first selected layer), text (e.g. \"Sidebar becomes a drawer below 768 px\")} a note in the Responsive annotation category, made if the file lacks it", + true, + rule + ), + spec!( + "responsive.list", + "List screen size versions", + "{ids? | id? (what is stated about those layers; default every marked frame)} only what the designer stated, nothing inferred → {versions: [{group, frames: [{id, name, viewport, width, height, page}]}], rules?: [{id, layer, text}], explicit?, truncated? (true: too many layers to read every rule)}", + false, + |s, p| { + let doc = s.doc()?; + if get(p, "ids").is_some() || get(p, "id").is_some() { + let ids = req_targets("responsive.list", s, p)?; + return Ok(context(doc, &ids)); + } + Ok(json!({"versions": groups(doc).iter().map(|(g, f)| group_json(doc, g, f)).collect::>()})) + } + ), + ] +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ad6bb085e..bc4c8d103 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -70,6 +70,7 @@ pub use dev::dev_measurements; pub use dev::dev_resources; pub use dev::devcompare; pub use dev::devinspect; +pub use dev::responsive; pub use dev::tailwind; pub use extensions::plugin_directory; pub use extensions::plugins; @@ -543,6 +544,8 @@ mod proto_run_tests; #[cfg(test)] mod proto_tail_tests; #[cfg(test)] +mod responsive_tests; +#[cfg(test)] mod rest_slot_tests; #[cfg(test)] mod retained_walk_tests; diff --git a/crates/engine/src/responsive_tests.rs b/crates/engine/src/responsive_tests.rs new file mode 100644 index 000000000..e0175cc6d --- /dev/null +++ b/crates/engine/src/responsive_tests.rs @@ -0,0 +1,172 @@ +//! Responsive context holds only what the designer stated. + +use serde_json::{Value, json}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +fn frame(s: &mut Session, name: &str, width: u32) -> u64 { + s.execute("node.create", &json!({"type": "frame", "name": name, "width": width, "height": 800})).unwrap()["id"].as_u64().unwrap() +} + +/// What is stated about layer `id`. +fn context(s: &mut Session, id: u64) -> Value { + s.execute("responsive.list", &json!({"ids": [id]})).unwrap() +} + +#[test] +fn nothing_is_inferred_from_names_or_sizes() { + let mut s = session(); + let phone = frame(&mut s, "Home / Mobile", 390); + frame(&mut s, "Home / Desktop", 1440); + let v = context(&mut s, phone); + assert_eq!(v, json!({"explicit": false, "versions": [], "rules": []})); +} + +#[test] +fn marked_frames_are_told_apart_and_come_with_their_alternates() { + let mut s = session(); + let phone = frame(&mut s, "Home phone", 390); + let tablet = frame(&mut s, "Home tablet", 768); + let desk = frame(&mut s, "Home large", 1440); + let other = frame(&mut s, "About", 1440); + for (id, viewport) in [(desk, "desktop"), (phone, "mobile"), (tablet, "tablet")] { + s.execute("responsive.set", &json!({"id": id, "viewport": viewport, "group": "Home"})).unwrap(); + } + s.execute("responsive.set", &json!({"id": other, "viewport": "desktop"})).unwrap(); + let v = context(&mut s, desk); + assert_eq!(v["explicit"], true); + let versions = v["versions"].as_array().unwrap(); + assert_eq!(versions.len(), 1, "other designs stay out: {versions:?}"); + let frames: Vec<&str> = versions[0]["frames"].as_array().unwrap().iter().map(|f| f["viewport"].as_str().unwrap()).collect(); + assert_eq!(frames, ["mobile", "tablet", "desktop"], "narrowest first"); + let all = s.execute("responsive.list", &json!({})).unwrap(); + assert_eq!(all["versions"].as_array().unwrap().len(), 2); +} + +#[test] +fn a_rule_is_the_designers_words_in_their_category() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let side = s.execute("node.create", &json!({"type": "frame", "parent": f, "name": "Sidebar", "width": 240, "height": 800})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("responsive.rule", &json!({"id": side, "text": "Sidebar becomes a drawer below 768 px"})).unwrap(); + s.execute("annotation.add", &json!({"id": side, "label": "Ordinary note"})).unwrap(); + let v = context(&mut s, f); + let rules = v["rules"].as_array().unwrap(); + assert_eq!(rules.len(), 1); + assert_eq!((rules[0]["layer"].as_str(), rules[0]["text"].as_str()), (Some("Sidebar"), Some("Sidebar becomes a drawer below 768 px"))); + let kept = s.execute("annotation.categories", &json!({})).unwrap(); + assert_eq!(kept["categories"].as_array().unwrap().iter().filter(|c| c["name"] == "Responsive").count(), 1); + s.execute("responsive.rule", &json!({"id": f, "text": "Second"})).unwrap(); + let kept = s.execute("annotation.categories", &json!({})).unwrap(); + assert_eq!(kept["categories"].as_array().unwrap().iter().filter(|c| c["name"] == "Responsive").count(), 1, "not made twice"); +} + +#[test] +fn a_rule_on_the_frame_reaches_a_layer_read_on_its_own() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let child = s.execute("node.create", &json!({"type": "rectangle", "parent": f, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("responsive.rule", &json!({"id": f, "text": "Cards stack on mobile"})).unwrap(); + assert_eq!(context(&mut s, child)["rules"][0]["text"], "Cards stack on mobile"); +} + +#[test] +fn marking_is_undoable_saved_and_clearable() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + s.execute("responsive.set", &json!({"id": f, "viewport": "desktop", "group": "Home"})).unwrap(); + let path = std::env::temp_dir().join(format!("figcraft-responsive-{}.figcraft", std::process::id())); + s.execute("file.save", &json!({"path": path})).unwrap(); + let mut back = Session::new(); + back.execute("file.open", &json!({"path": path})).unwrap(); + assert_eq!(crate::responsive::groups(back.doc().unwrap()).len(), 1, "it survives saving"); + let _ = std::fs::remove_file(&path); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(crate::responsive::groups(s.doc().unwrap()).is_empty()); + s.execute("responsive.set", &json!({"id": f, "viewport": "mobile"})).unwrap(); + s.execute("responsive.set", &json!({"id": f, "viewport": null})).unwrap(); + assert!(crate::responsive::groups(s.doc().unwrap()).is_empty()); +} + +#[test] +fn bad_input_is_refused() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let r = s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + for p in [ + json!({"id": f}), + json!({"id": f, "viewport": "watch"}), + json!({"id": r, "viewport": "mobile"}), + json!({"id": f, "viewport": "mobile", "group": " "}), + ] { + assert!(s.execute("responsive.set", &p).is_err(), "{p}"); + } + assert!(s.execute("responsive.rule", &json!({"id": f, "text": " "})).is_err()); + assert!(s.execute("responsive.rule", &json!({"id": f})).is_err()); +} + +#[test] +fn malformed_targets_are_refused_rather_than_read_as_the_selection() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let calls = [ + ("responsive.set", json!({"ids": [f, "nope"], "viewport": "mobile"})), + ("responsive.set", json!({"ids": [999_999], "viewport": "mobile"})), + ("responsive.rule", json!({"id": "not-an-id", "text": "A rule"})), + ("responsive.list", json!({"id": "not-an-id"})), + ("responsive.list", json!({"ids": [f, "nope"]})), + ("responsive.list", json!({"ids": [999_999]})), + ]; + for (command, p) in calls { + assert!(s.execute(command, &p).is_err(), "{command} {p}"); + } + assert!(s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations.is_empty(), "the selection wasn't used instead"); +} + +#[test] +fn a_rule_keeps_to_the_limits_annotations_have() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let long = "x".repeat(crate::annotations::MAX_LABEL + 50); + let at = s.execute("responsive.rule", &json!({"id": f, "text": long})).unwrap()["index"].as_u64().unwrap() as usize; + let label = s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations[at].label.chars().count(); + assert_eq!(label, crate::annotations::MAX_LABEL, "capped like annotation.add"); + while s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations.len() < crate::annotations::MAX_PER_LAYER { + s.execute("annotation.add", &json!({"id": f, "label": "note"})).unwrap(); + } + assert!(s.execute("responsive.rule", &json!({"id": f, "text": "One too many"})).is_err(), "a layer's annotation limit holds"); +} + +#[test] +fn no_responsive_category_is_made_past_the_category_limit() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let mut k = 0; + while s.execute("annotation.categories", &json!({})).unwrap()["categories"].as_array().unwrap().len() < crate::annotations::MAX_CATEGORIES { + s.execute("annotation.addCategory", &json!({"name": format!("Category {k}")})).unwrap(); + k += 1; + } + assert!(s.execute("responsive.rule", &json!({"id": f, "text": "A rule"})).is_err()); +} + +#[test] +fn a_walk_stopped_at_its_cap_says_so() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + for _ in 0..10 { + s.execute("node.create", &json!({"type": "rectangle", "parent": f, "width": 4, "height": 4})).unwrap(); + } + let doc = s.doc().unwrap(); + let id = figcraft_doc::NodeId(f); + assert!(crate::responsive::context_within(doc, &[id], 100).get("truncated").is_none()); + assert_eq!(crate::responsive::context_within(doc, &[id], 5)["truncated"], true); +} diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index e42a1c21c..e966da54e 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -45,6 +45,7 @@ name = "English" "Add a layer or component to tile first" = "Add a layer or component to tile first" "Add a minute" = "Add a minute" "Add a note for developers" = "Add a note for developers" +"Add a rule" = "Add a rule" "Add action" = "Add action" "Add actions for when no condition holds" = "Add actions for when no condition holds" "Add an annotation for developers" = "Add an annotation for developers" @@ -72,6 +73,7 @@ name = "English" "Add properties to make instances configurable" = "Add properties to make instances configurable" "Add reaction" = "Add reaction" "Add row" = "Add row" +"Add rule" = "Add rule" "Add starting point" = "Add starting point" "Add stroke" = "Add stroke" "Add variant" = "Add variant" @@ -471,6 +473,7 @@ name = "English" "Description" = "Description" "Description (optional)" = "Description (optional)" "Design" = "Design" +"Design it's a version of" = "Design it's a version of" "Design panel" = "Design panel" "Design system starter" = "Design system starter" "Desktop" = "Desktop" @@ -932,6 +935,7 @@ name = "English" "Mixed" = "Mixed" "Mixed fonts" = "Mixed fonts" "Mixed interactions: click + to replace them" = "Mixed interactions: click + to replace them" +"Mobile" = "Mobile" "Mobile app" = "Mobile app" "Mode" = "Mode" "Model" = "Model" @@ -1338,6 +1342,7 @@ name = "English" "Rows" = "Rows" "Rows {count}" = "Rows {count}" "Rulers" = "Rulers" +"Rules appear under Annotations, in the Responsive category." = "Rules appear under Annotations, in the Responsive category." "Run" = "Run" "Run {label}" = "Run {label}" "Save file" = "Save file" @@ -1360,6 +1365,7 @@ name = "English" "Scatter" = "Scatter" "Scoping: where pickers offer it" = "Scoping: where pickers offer it" "Screen" = "Screen" +"Screen sizes" = "Screen sizes" "Scroll behavior" = "Scroll behavior" "Scroll to" = "Scroll to" "Scroll to layer" = "Scroll to layer" @@ -1453,6 +1459,7 @@ name = "English" "Show/Hide UI" = "Show/Hide UI" "Side by side" = "Side by side" "Sidebar" = "Sidebar" +"Sidebar becomes a drawer below 768 px" = "Sidebar becomes a drawer below 768 px" "Simplify stroke" = "Simplify stroke" "Size" = "Size" "Size jitter" = "Size jitter" diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index 09c3b9732..3d28eef7c 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -7,7 +7,7 @@ //! document. use egui::{Align2, Color32, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; -use figcraft_doc::{Annotation, AnnotationCategory, CodeLink, DevStatus, Document, NodeId}; +use figcraft_doc::{Annotation, AnnotationCategory, CodeLink, DevStatus, Document, NodeId, NodeKind}; use figcraft_engine::annotations::{self, PINNABLE, Pinnable}; use figcraft_engine::code_connect; use figcraft_engine::codegen::{CodeLang, code_for}; @@ -15,7 +15,7 @@ use figcraft_engine::dev_measurements::{self, Placed}; use figcraft_engine::devinspect::{self, DevItem, Prop}; use figcraft_engine::plugins::Access; use figcraft_engine::snap::Guide; -use figcraft_engine::{components, dev_resources}; +use figcraft_engine::{components, dev_resources, responsive}; use serde_json::json; use crate::a11y::Tip; @@ -499,6 +499,50 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId ui.add_space(4.0); } +/// Screen sizes for a frame: which version of a design it is, and rules for other sizes. What's +/// here is the designer's word: agents read it instead of guessing. +pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId) { + // Screens are frames: a component isn't a version of one. + let Some(n) = doc.node(id).filter(|n| matches!(n.kind, NodeKind::Frame)) else { return }; + let t = Tokens::get(ui.ctx()); + let current = n.plugin_data.get(responsive::VIEWPORT_KEY).map(String::as_str); + widgets::separator(ui); + widgets::section_header(ui, tr("Screen sizes"), &[], current.is_none()); + let labels = [(tr("Mobile"), "mobile"), (tr("Tablet"), "tablet"), (tr("Desktop"), "desktop")]; + row(ui, 32.0, |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (label, viewport) in labels { + let on = current == Some(viewport); + if widgets::button(ui, label, on, true).clicked() { + app.run("responsive.set", json!({"id": id, "viewport": if on { json!(null) } else { json!(viewport) }})); + } + } + }); + if current.is_some() { + widgets::sublabels(ui, tr("Design it's a version of"), None); + let group = n.plugin_data.get(responsive::GROUP_KEY).unwrap_or(&n.name); + row(ui, 32.0, |ui| { + let width = ui.available_width() - 2.0 * PAD; + if let Some(v) = widgets::text_field(ui, Id::unique(("responsive_group", id)), group, width, tr("Design it's a version of")) { + app.run("responsive.set", json!({"id": id, "viewport": current, "group": v})); + } + }); + } + let field = Id::unique(("responsive_rule", id)); + let draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); + widgets::sublabels(ui, tr("Add a rule"), None); + if let Some(v) = widgets::multiline_field(ui, field, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { + ui.data_mut(|d| d.insert_temp(field, v)); + } + row(ui, 32.0, |ui| { + if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { + app.run("responsive.rule", json!({"id": id, "text": draft})); + ui.data_mut(|d| d.remove_temp::(field)); + } + }); + widgets::note(ui, tr("Rules appear under Annotations, in the Responsive category."), t.text_secondary); +} + /// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab. pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) { let runnable: Vec<(String, String, String)> = app diff --git a/crates/ui-egui/src/panels/right/inspect.rs b/crates/ui-egui/src/panels/right/inspect.rs index d71e74f69..de3162a9c 100644 --- a/crates/ui-egui/src/panels/right/inspect.rs +++ b/crates/ui-egui/src/panels/right/inspect.rs @@ -206,6 +206,7 @@ pub(super) fn inspect(app: &mut FigApp, ui: &mut Ui) { } crate::dev_mode::status(app, ui, &doc, &sel); crate::dev_mode::annotations_section(app, ui, &doc, first); + crate::dev_mode::responsive_section(app, ui, &doc, first); crate::dev_mode::dev_resources_section(app, ui, &doc, first); crate::dev_mode::measurements_section(app, ui, &doc, &sel); use figcraft_engine::devinspect::ColorFormat; diff --git a/docs/mcp.md b/docs/mcp.md index c1f3992a9..46afff7cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1922,6 +1922,17 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path the defaults (old files open with the defaults). In the app, with nothing selected, the Inspect tab filters the callouts by category and edits the categories (colour, name, delete, add); each note has a category menu. +- **Screen sizes:** a file has no breakpoints, so the designer states what happens at other sizes and + agents read that rather than guess. Undoable `responsive.set {ids?, viewport, group?}` marks frames + as the `mobile`, `tablet` or `desktop` version of a design (`null` clears the mark; `group` names the + design, by default each frame's name). Undoable `responsive.rule {id?, text}` adds a note to the + **Responsive** annotation category, making the category if the file lacks it; the note keeps to + `annotation.add`'s limits. `responsive.list {}` → `{versions: [{group, frames: [{id, name, viewport, + width, height, page}]}]}`, narrowest first; with `ids` or `id`, what is stated about those layers, + the layers above them and those inside them: `{explicit, versions, rules: [{id, layer, text}], + truncated?}` (`truncated`: too many layers to read every rule). Nothing is inferred from names or + sizes. Marks are layer data (`figcraft.viewport`, `figcraft.viewportGroup`), so they save and sync + with no change to the file format. In the app, a frame's Inspect tab has a **Screen sizes** section. - **Ready for dev:** frames at the top of a page or section, and sections, carry a handoff status (`node.set {devStatus: none|readyForDev|completed}`; other layers are refused a status). `inspect.readyForDev {status?: readyForDev|changed|completed|any, page?}` lists them across pages From f8bc54cd44c7d3548827430dd9386ac5aa29d890 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Thu, 19 Nov 2026 03:07:40 +0100 Subject: [PATCH 2/2] M8: screen sizes join the design context and read only what is a mark - `inspect.designContext` returns the target's responsive context under `responsive`, and names the missing breakpoints only when nothing was stated. - `responsive.set` marks frames and sections only, as the Inspect section shows; a component or instance is refused. `group: null` goes back to the frame's name, and emptying the field in the Inspect tab sends it. - A stored viewport that isn't mobile, tablet or desktop is ignored, and an empty or over-long group reads as none (`node.set {pluginData}` can write anything there). - The walk for rules counts each layer once and stops at its cap without collecting a whole subtree first, so overlapping targets don't use it up; `near` is searched by binary search. - `responsive.rule` refuses a page before making the category, as `annotation.add` does. - Developer Mode makes responsive edits, like its annotations (`dev_mode_allows`). - The Inspect tab keeps a rule's draft per document and keeps it when the rule is refused. - Status line, row and revision row in docs/dev-mode-parity.md. --- crates/engine/src/design_context_tests.rs | 16 ++++ crates/engine/src/dev/design_context.rs | 12 ++- crates/engine/src/dev/devinspect.rs | 4 +- crates/engine/src/dev/responsive.rs | 109 +++++++++++++++------- crates/engine/src/responsive_tests.rs | 80 ++++++++++++++++ crates/ui-egui/src/dev_mode_tests.rs | 17 ++++ crates/ui-egui/src/panels/dev_mode.rs | 33 +++++-- docs/dev-mode-parity.md | 4 +- docs/mcp.md | 17 ++-- 9 files changed, 234 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/design_context_tests.rs b/crates/engine/src/design_context_tests.rs index 5d6f51304..706d5fd9a 100644 --- a/crates/engine/src/design_context_tests.rs +++ b/crates/engine/src/design_context_tests.rs @@ -407,3 +407,19 @@ fn a_join_stopped_at_its_budget_says_so() { let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3); assert_eq!((some.len(), complete), (3, false), "{some:?}"); } + +#[test] +fn stated_screen_sizes_come_with_the_context() { + let mut s = session(); + let f = node(&mut s, json!({"type": "frame", "name": "Home", "width": 1440, "height": 900})); + let unmarked = context(&mut s, json!({"ids": [f]})); + assert_eq!(unmarked["responsive"]["explicit"], false, "{unmarked}"); + let says = |v: &Value| v["missing"].as_array().unwrap().iter().any(|m| m["what"] == "responsive behaviour"); + assert!(says(&unmarked), "nothing stated: the gap is named"); + s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop"})).unwrap(); + s.execute("responsive.rule", &json!({"id": f, "text": "Sidebar becomes a drawer below 768 px"})).unwrap(); + let marked = context(&mut s, json!({"ids": [f]})); + assert_eq!(marked["responsive"]["explicit"], true, "{marked}"); + assert_eq!(marked["responsive"]["rules"][0]["text"], "Sidebar becomes a drawer below 768 px"); + assert!(!says(&marked), "{marked}"); +} diff --git a/crates/engine/src/dev/design_context.rs b/crates/engine/src/dev/design_context.rs index c21467110..bd6faa475 100644 --- a/crates/engine/src/dev/design_context.rs +++ b/crates/engine/src/dev/design_context.rs @@ -427,9 +427,12 @@ fn design_context(s: &mut Session, p: &Value) -> Result { } nodes.extend(layer(doc, *id, depth, cap, &mut used)); } - let mut missing = vec![ - json!({"what": "responsive behaviour", "why": "the file stores no breakpoints: sizes are as designed here, and constraints, sizing and annotations are all it says about other widths"}), - ]; + // Only what the designer stated about other sizes; without it, the gap is named. + let responsive = crate::responsive::context(doc, &ids); + let mut missing = Vec::new(); + if responsive["explicit"] != true { + missing.push(json!({"what": "responsive behaviour", "why": "the file stores no breakpoints: sizes are as designed here, and constraints, sizing and annotations are all it says about other widths"})); + } let (joined, complete) = referenced(doc, &used.variables, &used.styles, MAX_VARIABLES); let variables = variables_json(doc, &joined, &mut missing); let styles = styles_json(doc, &used.styles, &mut missing); @@ -450,6 +453,7 @@ fn design_context(s: &mut Session, p: &Value) -> Result { "components": components, "fonts": fonts, "assets": assets, + "responsive": responsive, "missing": missing, }); if used.left_out > 0 || used.cut_by_depth { @@ -466,7 +470,7 @@ pub fn specs() -> Vec { vec![spec!( "inspect.designContext", "Design context", - "{ids? | id? (those layers), scope?: selection|page|document (default the selection, or the page with nothing selected), depth? (default 32), maxNodes? (default 2000)} everything needed to build them, in one read → {version, document, target {source, ids, layers}, nodes [{id, name, type, explicit, derived?, tokens?, unsupported? [{property, why}], code?, children?, childCount?}], variables, styles, components, fonts, assets, missing [{what, why}], truncated?}", + "{ids? | id? (those layers), scope?: selection|page|document (default the selection, or the page with nothing selected), depth? (default 32), maxNodes? (default 2000)} everything needed to build them, in one read → {version, document, target {source, ids, layers}, nodes [{id, name, type, explicit, derived?, tokens?, unsupported? [{property, why}], code?, children?, childCount?}], variables, styles, components, fonts, assets, responsive {explicit, versions, rules, truncated?}, missing [{what, why}], truncated?}", false, design_context )] diff --git a/crates/engine/src/dev/devinspect.rs b/crates/engine/src/dev/devinspect.rs index 5ac74b9ee..606cd8ebd 100644 --- a/crates/engine/src/dev/devinspect.rs +++ b/crates/engine/src/dev/devinspect.rs @@ -223,10 +223,10 @@ pub struct DevItem { /// Whether Dev Mode runs command `id` from the menus and shortcuts: commands that don't edit the /// document, and Dev Mode's own edits (annotations, statuses, dev resources, measurements, code -/// connections, comments). Choosing a tool other than moving around and commenting is refused too, +/// connections, screen size marks and rules, comments). Choosing a tool other than moving around and commenting is refused too, /// and so is Revert to saved, which isn't an undo step but throws the design's unsaved edits away. pub fn dev_mode_allows(id: &str) -> bool { - const OWN: [&str; 6] = ["annotation.", "dev.", "devMode.", "devResource.", "codeConnect.", "comment."]; + const OWN: [&str; 7] = ["annotation.", "dev.", "devMode.", "devResource.", "codeConnect.", "responsive.", "comment."]; // Edits recorded as one grouped undo step, so their spec says no history of its own. const GROUPED: [&str; 1] = ["data.fill"]; match id.strip_prefix("tool.") { diff --git a/crates/engine/src/dev/responsive.rs b/crates/engine/src/dev/responsive.rs index 6ac1124ac..1e21269c5 100644 --- a/crates/engine/src/dev/responsive.rs +++ b/crates/engine/src/dev/responsive.rs @@ -4,12 +4,14 @@ //! the Responsive annotation category. Nothing here is worked out from names or sizes: an agent //! must never take a guess for the designer's word. -use figcraft_doc::{Annotation, AnnotationCategory, Document, NodeId, NodeKind}; +use std::collections::BTreeSet; + +use figcraft_doc::{Annotation, AnnotationCategory, Document, Node, NodeId, NodeKind}; use serde_json::{Value, json}; use crate::annotations::{MAX_CATEGORIES, MAX_PER_LAYER, categories, category_of, find_category, free_category_id, parse_label, unused_color}; use crate::cmd::CommandSpec; -use crate::params::{get, req_targets, string}; +use crate::params::{get, req_targets}; use crate::{Result, Session, bad, spec}; /// Layer data key: which version of a design a frame is. @@ -25,20 +27,34 @@ const MAX_GROUP: usize = 100; /// Most layers looked through for rules. const MAX_WALK: usize = 50_000; +/// Whether a layer can be marked as a version of a design: frames and sections are screens. +pub fn can_mark(kind: &NodeKind) -> bool { + matches!(kind, NodeKind::Frame | NodeKind::Section { .. }) +} + +/// The version `n` is marked as. Layer data can hold anything (`node.set {pluginData}`), so +/// only the three versions count. +pub fn viewport_of(n: &Node) -> Option<&str> { + n.plugin_data.get(VIEWPORT_KEY).map(String::as_str).filter(|v| VIEWPORTS.contains(v)) +} + +/// The design `n` is a version of: its stored group, or its name when there is none, or the +/// stored one is empty or too long. +pub fn group_of(n: &Node) -> &str { + n.plugin_data.get(GROUP_KEY).map(|g| g.trim()).filter(|g| !g.is_empty() && g.chars().count() <= MAX_GROUP).unwrap_or(&n.name) +} + /// A marked frame as JSON. fn frame_json(doc: &Document, id: NodeId) -> Option { let n = doc.node(id)?; - Some( - json!({"id": id, "name": n.name, "viewport": n.plugin_data.get(VIEWPORT_KEY)?, "width": n.width, "height": n.height, "page": doc.page_of(id)}), - ) + Some(json!({"id": id, "name": n.name, "viewport": viewport_of(n)?, "width": n.width, "height": n.height, "page": doc.page_of(id)})) } /// Every design with marked frames, narrowest first. pub fn groups(doc: &Document) -> Vec<(String, Vec)> { let mut out: std::collections::BTreeMap> = std::collections::BTreeMap::new(); - for n in doc.nodes().filter(|n| n.plugin_data.contains_key(VIEWPORT_KEY)) { - let group = n.plugin_data.get(GROUP_KEY).cloned().unwrap_or_else(|| n.name.clone()); - out.entry(group).or_default().push(n.id); + for n in doc.nodes().filter(|n| viewport_of(n).is_some()) { + out.entry(group_of(n).to_string()).or_default().push(n.id); } for frames in out.values_mut() { frames.sort_by(|a, b| doc.node(*a).map_or(0.0, |n| n.width).total_cmp(&doc.node(*b).map_or(0.0, |n| n.width))); @@ -55,27 +71,36 @@ fn is_rule(doc: &Document, a: &Annotation) -> bool { category_of(doc, a).is_some_and(|c| c.name.eq_ignore_ascii_case(RULES_CATEGORY)) } -/// `ids`, the layers above them and those under them, at most `max`; and whether some were left -/// out. +/// Counts layer `id` into `seen`: false when it is new and `max` layers are already counted. +fn take(seen: &mut BTreeSet, id: NodeId, max: usize) -> bool { + seen.contains(&id) || (seen.len() < max && seen.insert(id)) +} + +/// `ids`, the layers above them and those under them, each once and at most `max` (sorted), and +/// whether some were left out. The walk stops at `max`: a huge subtree isn't collected first. fn around(doc: &Document, ids: &[NodeId], max: usize) -> (Vec, bool) { - let mut cut = false; - let mut out = Vec::new(); + let mut seen = BTreeSet::new(); + let mut walked = BTreeSet::new(); for id in ids { - let mut at = doc.node(*id).and_then(|n| n.parent); - while let Some(p) = at { - out.push(p); - at = doc.node(p).and_then(|n| n.parent); + for p in doc.ancestors(*id) { + if !take(&mut seen, p, max) { + return (seen.into_iter().collect(), true); + } } - out.extend(doc.subtree(*id)); - if out.len() > max { - out.truncate(max); - cut = true; - break; + let mut stack = vec![*id]; + while let Some(c) = stack.pop() { + // A layer under an earlier target was walked with it. + if !walked.insert(c) { + continue; + } + let Some(n) = doc.node(c) else { continue }; + if !take(&mut seen, c, max) { + return (seen.into_iter().collect(), true); + } + stack.extend(n.children.iter().rev()); } } - out.sort_unstable(); - out.dedup(); - (out, cut) + (seen.into_iter().collect(), false) } /// What the designer states about `ids` and the design they belong to. @@ -93,7 +118,7 @@ pub(crate) fn context_within(doc: &Document, ids: &[NodeId], max: usize) -> Valu .collect(); let versions: Vec = groups(doc) .iter() - .filter(|(_, frames)| frames.iter().any(|f| near.contains(f))) + .filter(|(_, frames)| frames.iter().any(|f| near.binary_search(f).is_ok())) .map(|(group, frames)| group_json(doc, group, frames)) .collect(); let mut out = json!({"explicit": !rules.is_empty() || !versions.is_empty(), "versions": versions, "rules": rules}); @@ -114,15 +139,18 @@ fn set(s: &mut Session, p: &Value) -> Result { Some(Value::String(v)) if VIEWPORTS.contains(&v.as_str()) => Some(v.clone()), Some(_) => return Err(bad(cmd, "viewport: mobile|tablet|desktop, or null to clear")), }; - let group = string(p, "group").map(|g| g.trim().to_string()); - if group.as_ref().is_some_and(|g| g.is_empty() || g.chars().count() > MAX_GROUP) { - return Err(bad(cmd, format!("group: a name up to {MAX_GROUP} characters"))); - } + // `group`: left out keeps it, null goes back to each frame's name. + let group = match p.get("group") { + None => None, + Some(Value::Null) => Some(None), + Some(Value::String(g)) if !g.trim().is_empty() && g.trim().chars().count() <= MAX_GROUP => Some(Some(g.trim().to_string())), + Some(_) => return Err(bad(cmd, format!("group: a name up to {MAX_GROUP} characters, or null for the frame's name"))), + }; let doc = s.doc_mut()?; for id in &ids { let n = doc.get(*id)?; - if !(n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })) { - return Err(bad(cmd, format!("{id} isn't a frame"))); + if !can_mark(&n.kind) { + return Err(bad(cmd, format!("{id} isn't a frame or section"))); } } for id in &ids { @@ -130,8 +158,14 @@ fn set(s: &mut Session, p: &Value) -> Result { match &viewport { Some(v) => { n.plugin_data.insert(VIEWPORT_KEY.into(), v.clone()); - if let Some(g) = &group { - n.plugin_data.insert(GROUP_KEY.into(), g.clone()); + match &group { + Some(Some(g)) => { + n.plugin_data.insert(GROUP_KEY.into(), g.clone()); + } + Some(None) => { + n.plugin_data.remove(GROUP_KEY); + } + None => {} } } None => { @@ -149,7 +183,12 @@ fn rule(s: &mut Session, p: &Value) -> Result { // Capped like `annotation.add`'s note. let text = parse_label(cmd, p)?.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).ok_or_else(|| bad(cmd, "`text` required"))?; let doc = s.doc_mut()?; - if doc.get(id)?.annotations.len() >= MAX_PER_LAYER { + let n = doc.get(id)?; + // As `annotation.add`: before anything is made. + if n.is_page() { + return Err(bad(cmd, "pages can't be annotated")); + } + if n.annotations.len() >= MAX_PER_LAYER { return Err(bad(cmd, format!("a layer has at most {MAX_PER_LAYER} annotations"))); } let mut list = categories(doc).to_vec(); @@ -175,7 +214,7 @@ pub fn specs() -> Vec { spec!( "responsive.set", "Mark as screen size version", - "{ids? (frames; default the selection), viewport: mobile|tablet|desktop (null: clear), group? (the design they are versions of; default each frame's name)} says which version of a design a frame is, in its layer data", + "{ids? (frames or sections; default the selection), viewport: mobile|tablet|desktop (null: clear), group? (the design they are versions of; null or left out on a new mark: each frame's name)} says which version of a design a frame is, in its layer data", true, set ), diff --git a/crates/engine/src/responsive_tests.rs b/crates/engine/src/responsive_tests.rs index e0175cc6d..eea489e3d 100644 --- a/crates/engine/src/responsive_tests.rs +++ b/crates/engine/src/responsive_tests.rs @@ -170,3 +170,83 @@ fn a_walk_stopped_at_its_cap_says_so() { assert!(crate::responsive::context_within(doc, &[id], 100).get("truncated").is_none()); assert_eq!(crate::responsive::context_within(doc, &[id], 5)["truncated"], true); } + +#[test] +fn overlapping_targets_count_each_layer_once() { + let mut s = session(); + let a = frame(&mut s, "A", 1440); + let c = s.execute("node.create", &json!({"type": "frame", "parent": a, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("node.create", &json!({"type": "rectangle", "parent": c, "width": 4, "height": 4})).unwrap(); + let b = frame(&mut s, "B", 390); + s.execute("responsive.rule", &json!({"id": b, "text": "B stacks"})).unwrap(); + let doc = s.doc().unwrap(); + let ids = [figcraft_doc::NodeId(a), figcraft_doc::NodeId(c), figcraft_doc::NodeId(b)]; + let distinct = { + let mut all: Vec<_> = ids.iter().flat_map(|i| doc.ancestors(*i).into_iter().chain(doc.subtree(*i))).collect(); + all.sort_unstable(); + all.dedup(); + all.len() + }; + let v = crate::responsive::context_within(doc, &ids, distinct); + assert!(v.get("truncated").is_none(), "{v}"); + assert_eq!(v["rules"][0]["text"], "B stacks", "{v}"); + assert_eq!(crate::responsive::context_within(doc, &ids, distinct - 1)["truncated"], true); +} + +#[test] +fn a_page_takes_no_rule() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let page = s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().parent.unwrap(); + let before = s.execute("annotation.categories", &json!({})).unwrap(); + assert!(s.execute("responsive.rule", &json!({"id": page.0, "text": "A rule"})).is_err()); + assert!(s.doc().unwrap().node(page).unwrap().annotations.is_empty()); + assert_eq!(s.execute("annotation.categories", &json!({})).unwrap(), before, "no category made"); +} + +#[test] +fn frames_and_sections_are_marked_and_components_are_not() { + let mut s = session(); + let f = frame(&mut s, "Card", 300); + let c = s.execute("component.create", &json!({"ids": [f]})).unwrap()["id"].as_u64().unwrap(); + let i = s.execute("instance.create", &json!({"component": c})).unwrap()["id"].as_u64().unwrap(); + for id in [c, i] { + assert!(s.execute("responsive.set", &json!({"ids": [id], "viewport": "mobile"})).is_err(), "{id}"); + } + let section = + s.execute("node.create", &json!({"type": "section", "x": 2000, "y": 0, "width": 400, "height": 400})).unwrap()["id"].as_u64().unwrap(); + let home = frame(&mut s, "Home", 1440); + s.execute("responsive.set", &json!({"ids": [section, home], "viewport": "desktop"})).unwrap(); +} + +#[test] +fn stored_values_that_arent_marks_are_left_out() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + let odd = frame(&mut s, "Odd", 800); + s.execute("node.set", &json!({"ids": [odd], "props": {"pluginData": {"figcraft.viewport": "watch"}}})).unwrap(); + let long = "g".repeat(500); + s.execute("node.set", &json!({"ids": [f], "props": {"pluginData": {"figcraft.viewport": "desktop", "figcraft.viewportGroup": long}}})).unwrap(); + let v = s.execute("responsive.list", &json!({})).unwrap(); + let versions = v["versions"].as_array().unwrap(); + assert_eq!(versions.len(), 1, "{v}"); + assert_eq!(versions[0]["group"], "Home", "an over-long group reads as none: {v}"); + assert_eq!(versions[0]["frames"][0]["id"], f); +} + +#[test] +fn a_group_can_go_back_to_the_frames_name() { + let mut s = session(); + let f = frame(&mut s, "Home", 1440); + s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop", "group": "Landing"})).unwrap(); + assert_eq!(s.execute("responsive.list", &json!({})).unwrap()["versions"][0]["group"], "Landing"); + s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop", "group": null})).unwrap(); + assert_eq!(s.execute("responsive.list", &json!({})).unwrap()["versions"][0]["group"], "Home"); +} + +#[test] +fn developer_mode_makes_its_own_responsive_edits() { + for id in ["responsive.set", "responsive.rule", "responsive.list"] { + assert!(crate::devinspect::dev_mode_allows(id), "{id}"); + } +} diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index b7a9f129d..0e8fa2726 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -240,3 +240,20 @@ fn the_toolbar_keeps_the_inspect_tab_for_the_annotation_tool() { crate::toolbar::choose(&mut u.app, figcraft_engine::ToolId::Rectangle); assert_eq!(u.app.ui.right_tab, crate::RightTab::Design, "a drawing tool leaves it"); } + +#[test] +fn a_rule_draft_belongs_to_its_document_and_outlives_a_refusal() { + let (mut u, f, _) = setup(); + let gone = NodeId(999_999); + let field = crate::dev_mode::rule_draft(&u.app, gone); + u.ctx.data_mut(|d| d.insert_temp(field, "Cards stack".to_string())); + crate::dev_mode::add_rule(&mut u.app, &u.ctx, gone, "Cards stack"); + assert_eq!(u.ctx.data(|d| d.get_temp::(field)).as_deref(), Some("Cards stack"), "a refused rule keeps its text"); + let field = crate::dev_mode::rule_draft(&u.app, f); + u.ctx.data_mut(|d| d.insert_temp(field, "Cards stack".to_string())); + crate::dev_mode::add_rule(&mut u.app, &u.ctx, f, "Cards stack"); + assert_eq!(u.ctx.data(|d| d.get_temp::(field)), None, "an added rule clears it"); + // Another document's layer with the same id has a draft of its own. + u.run("file.new", json!({})); + assert_ne!(crate::dev_mode::rule_draft(&u.app, f), field); +} diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index 3d28eef7c..0ee5768fd 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -7,7 +7,7 @@ //! document. use egui::{Align2, Color32, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; -use figcraft_doc::{Annotation, AnnotationCategory, CodeLink, DevStatus, Document, NodeId, NodeKind}; +use figcraft_doc::{Annotation, AnnotationCategory, CodeLink, DevStatus, Document, NodeId}; use figcraft_engine::annotations::{self, PINNABLE, Pinnable}; use figcraft_engine::code_connect; use figcraft_engine::codegen::{CodeLang, code_for}; @@ -502,10 +502,10 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId /// Screen sizes for a frame: which version of a design it is, and rules for other sizes. What's /// here is the designer's word: agents read it instead of guessing. pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId) { - // Screens are frames: a component isn't a version of one. - let Some(n) = doc.node(id).filter(|n| matches!(n.kind, NodeKind::Frame)) else { return }; + // Screens are frames and sections: a component isn't a version of one. + let Some(n) = doc.node(id).filter(|n| responsive::can_mark(&n.kind)) else { return }; let t = Tokens::get(ui.ctx()); - let current = n.plugin_data.get(responsive::VIEWPORT_KEY).map(String::as_str); + let current = responsive::viewport_of(n); widgets::separator(ui); widgets::section_header(ui, tr("Screen sizes"), &[], current.is_none()); let labels = [(tr("Mobile"), "mobile"), (tr("Tablet"), "tablet"), (tr("Desktop"), "desktop")]; @@ -520,15 +520,17 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod }); if current.is_some() { widgets::sublabels(ui, tr("Design it's a version of"), None); - let group = n.plugin_data.get(responsive::GROUP_KEY).unwrap_or(&n.name); + let group = responsive::group_of(n); row(ui, 32.0, |ui| { let width = ui.available_width() - 2.0 * PAD; if let Some(v) = widgets::text_field(ui, Id::unique(("responsive_group", id)), group, width, tr("Design it's a version of")) { - app.run("responsive.set", json!({"id": id, "viewport": current, "group": v})); + // Emptied: back to the frame's name. + let group = if v.trim().is_empty() { json!(null) } else { json!(v) }; + app.run("responsive.set", json!({"id": id, "viewport": current, "group": group})); } }); } - let field = Id::unique(("responsive_rule", id)); + let field = rule_draft(app, id); let draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); widgets::sublabels(ui, tr("Add a rule"), None); if let Some(v) = widgets::multiline_field(ui, field, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { @@ -536,13 +538,26 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod } row(ui, 32.0, |ui| { if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { - app.run("responsive.rule", json!({"id": id, "text": draft})); - ui.data_mut(|d| d.remove_temp::(field)); + add_rule(app, ui.ctx(), id, &draft); } }); widgets::note(ui, tr("Rules appear under Annotations, in the Responsive category."), t.text_secondary); } +/// Where the Screen sizes section keeps the rule being typed for layer `id`. +pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id { + // Layer ids repeat across open documents. + Id::unique(("responsive_rule", app.session.ds().ok().map(|d| d.uid), id)) +} + +/// Add `text` as a rule on `id`. The draft stays when the rule is refused, so nothing typed is lost. +pub(crate) fn add_rule(app: &mut FigApp, ctx: &egui::Context, id: NodeId, text: &str) { + let field = rule_draft(app, id); + if app.run("responsive.rule", json!({"id": id, "text": text})).is_some() { + ctx.data_mut(|d| d.remove_temp::(field)); + } +} + /// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab. pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) { let runnable: Vec<(String, String, String)> = app diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 0443708c0..561e619b2 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-19 · **Change:** minor (Screen sizes: a frame or section can be marked as the mobile, tablet or desktop version of a design and carry rules for other sizes in the Responsive annotation category, from the Inspect tab or `responsive.set`, `responsive.rule` and `responsive.list`; `inspect.designContext` returns them under `responsive`. Percentages and hours unchanged) **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -17,6 +17,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | +| Screen sizes (which version of a design a frame is, rules for other sizes) | done | ours: the incumbent has no such field. A frame or section is marked mobile, tablet or desktop and named after the design it is a version of (layer data, so no file format change); rules are notes in the Responsive annotation category. Agents read only what was stated (`responsive.list`, `design_context`'s `responsive`); nothing is inferred from names or sizes | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | | Focus view (one frame, previous / next) | done | | | Compare changes (before/after side by side or overlaid, property diffs) | done | against the snapshot taken when a frame was first changed after it was marked ready, or any saved version (`dev.compare {version}`; the view's Compare with menu); a frame that isn't ready for dev compares with versions | @@ -30,6 +31,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Screen sizes: the Inspect tab's Screen sizes section, `responsive.set` (frames and sections; `group: null` goes back to the frame's name), `responsive.rule` (a note in the Responsive annotation category, with `annotation.add`'s limits; pages refused) and `responsive.list`. Developer Mode makes these edits, like its annotations. Stored values that aren't a version are ignored. `inspect.designContext` returns the target's under `responsive` and names the missing breakpoints only when nothing was stated. Percentages and hours unchanged | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | diff --git a/docs/mcp.md b/docs/mcp.md index 46afff7cd..bf2ad762c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -436,7 +436,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `components` | By id: `name`, `type`, `properties` with variants, `codeLinks` | | `fonts` | `family`, `styles`, and whether it's `installed` | | `assets` | What `inspect.assets` lists, for the layers in the tree | -| `missing` | `{what, why}`: what the design doesn't specify. Always says that the file stores no breakpoints | +| `responsive` | What the designer stated about other screen sizes, as `responsive.list` gives it for the target: `explicit`, `versions`, `rules`. Nothing is inferred from names or sizes | +| `missing` | `{what, why}`: what the design doesn't specify. Says that the file stores no breakpoints unless `responsive` is `explicit` | | `truncated` | When `depth` or `maxNodes` cut the tree, or `maxBytes` made the tool ask for fewer layers: `layersLeftOut`, `assetsLeftOut`, `depth`, `maxNodes`; and `variables` when aliases went deeper than the 10,000 variables followed | Each layer in `nodes` has `id`, `name`, `type` and: @@ -1924,15 +1925,17 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path note has a category menu. - **Screen sizes:** a file has no breakpoints, so the designer states what happens at other sizes and agents read that rather than guess. Undoable `responsive.set {ids?, viewport, group?}` marks frames - as the `mobile`, `tablet` or `desktop` version of a design (`null` clears the mark; `group` names the - design, by default each frame's name). Undoable `responsive.rule {id?, text}` adds a note to the - **Responsive** annotation category, making the category if the file lacks it; the note keeps to - `annotation.add`'s limits. `responsive.list {}` → `{versions: [{group, frames: [{id, name, viewport, + or sections as the `mobile`, `tablet` or `desktop` version of a design (`null` clears the mark; + `group` names the design, and `null` goes back to each frame's name). Undoable `responsive.rule {id?, + text}` adds a note to the **Responsive** annotation category, making the category if the file lacks + it; the note keeps to `annotation.add`'s limits, and pages are refused. Developer Mode makes both + edits, as it does annotations. `responsive.list {}` → `{versions: [{group, frames: [{id, name, viewport, width, height, page}]}]}`, narrowest first; with `ids` or `id`, what is stated about those layers, the layers above them and those inside them: `{explicit, versions, rules: [{id, layer, text}], truncated?}` (`truncated`: too many layers to read every rule). Nothing is inferred from names or - sizes. Marks are layer data (`figcraft.viewport`, `figcraft.viewportGroup`), so they save and sync - with no change to the file format. In the app, a frame's Inspect tab has a **Screen sizes** section. + sizes, and stored values that aren't one of the three versions are ignored. `design_context` gives + the same for its target under `responsive`. Marks are layer data (`figcraft.viewport`, `figcraft.viewportGroup`), so they save and sync + with no change to the file format. In the app, a frame's or section's Inspect tab has a **Screen sizes** section. - **Ready for dev:** frames at the top of a page or section, and sections, carry a handoff status (`node.set {devStatus: none|readyForDev|completed}`; other layers are refused a status). `inspect.readyForDev {status?: readyForDev|changed|completed|any, page?}` lists them across pages