M8: design context joins aliased and style-bound variables, and reads only valid targets

From review: the variables a style binds and those an alias or colour
calculation reads are joined too, followed to any depth; fonts come from the
text layers placed in the tree, so a second target's font isn't lost to a
separate walk's budget; and a malformed `id` or `ids` entry is an error
instead of reading the selection or dropping the entry. A regression test for
each fails without its fix.
This commit is contained in:
B-uchi committed 2026-11-18 20:37:44 +01:00
1 parent de6c66838d
commit ae592a0d71
3 files changed
+118 -25

No files matched your search

+64
View File
@@ -286,3 +286,67 @@ fn junk_parameters_are_errors_not_panics() {
assert!(s.execute("inspect.designContext", &json!({"ids": []})).is_ok());
assert!(s.execute("inspect.designContext", &json!({"maxNodes": 0})).is_ok());
}
/// A colour variable in collection Theme (Light, Dark): (collection id, variable id).
fn variable(s: &mut Session, name: &str, light: &str, dark: &str) -> (Value, String) {
let c = s.execute("variable.createCollection", &json!({"name": format!("{name} theme"), "modes": ["Light", "Dark"]})).unwrap()["id"].clone();
let v = s.execute("variable.create", &json!({"collection": c, "name": name, "type": "color", "values": {"Light": light, "Dark": dark}})).unwrap();
(c, v["id"].as_str().unwrap().to_string())
}
#[test]
fn a_variable_an_alias_reads_is_joined_too() {
let mut s = session();
let (c, brand) = variable(&mut s, "brand", "#3B5BDB", "#748FFC");
let button = s
.execute("variable.create", &json!({"collection": c, "name": "button", "type": "color", "values": {"Light": "#000000", "Dark": "#000000"}}))
.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
for mode in ["Light", "Dark"] {
s.execute("variable.set", &json!({"variable": button, "mode": mode, "value": {"alias": brand}})).unwrap();
}
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": {"$var": button}}}));
let v = context(&mut s, json!({"ids": [r]}));
assert!(v["variables"].get(&button).is_some());
assert_eq!(v["variables"][&brand]["name"], "brand", "the aliased variable is defined as well: {}", v["variables"]);
}
#[test]
fn a_variable_a_shared_style_binds_is_joined() {
let mut s = session();
let (_, brand) = variable(&mut s, "brand", "#3B5BDB", "#748FFC");
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": "#FF0000"}}));
let st = s.execute("style.create", &json!({"type": "paint", "name": "Brand/Fill", "from": r})).unwrap()["id"].clone();
s.execute("style.bind", &json!({"style": st, "field": "fill", "variable": brand})).unwrap();
s.execute("style.apply", &json!({"style": st, "ids": [r]})).unwrap();
let v = context(&mut s, json!({"ids": [r]}));
assert_eq!(only(&v)["tokens"]["style.fill"]["name"], "Brand/Fill");
assert_eq!(v["variables"][&brand]["name"], "brand", "the style's variable is defined: {}", v["variables"]);
}
#[test]
fn every_returned_text_layer_has_its_font_listed() {
let mut s = session();
let title = node(&mut s, json!({"type": "text", "text": "Title", "props": {"fontFamily": "Serif Display Test"}}));
let busy = node(&mut s, json!({"type": "frame", "x": 300, "width": 200, "height": 200}));
for _ in 0..12 {
node(&mut s, json!({"type": "rectangle", "parent": busy, "width": 4, "height": 4}));
}
let v = context(&mut s, json!({"ids": [title, busy], "maxNodes": 2}));
assert_eq!(v["target"]["layers"], 2);
let families: Vec<&str> = v["fonts"].as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap()).collect();
assert_eq!(families, ["Serif Display Test"], "{}", v["fonts"]);
}
#[test]
fn a_malformed_target_is_refused_rather_than_read_as_the_selection() {
let mut s = session();
let (f, _, _) = card(&mut s);
s.execute("select.set", &json!({"ids": [f]})).unwrap();
for p in [json!({"id": "not-an-id"}), json!({"id": true}), json!({"ids": [f, "nope"]}), json!({"ids": "1"})] {
assert!(s.execute("inspect.designContext", &p).is_err(), "{p}");
}
assert_eq!(context(&mut s, json!({"ids": []}))["target"]["layers"], 0, "an empty list reads nothing");
}
+53 -24
View File
@@ -45,6 +45,8 @@ struct Used {
left_out: usize,
/// Reached `depth` with children left.
cut_by_depth: bool,
/// Font families of the text layers placed, with their styles.
fonts: BTreeMap<String, BTreeSet<String>>,
}
/// `property` of a layer has no direct CSS equivalent, because `why`.
@@ -183,6 +185,11 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
fn layer(doc: &Document, id: NodeId, depth: usize, cap: usize, used: &mut Used) -> Option<Value> {
let n = doc.node(id)?;
used.nodes += 1;
if let NodeKind::Text(t) = &n.kind {
for (_, _, style) in t.spans() {
used.fonts.entry(style.font_family.clone()).or_default().insert(style.font_style.clone());
}
}
let Value::Object(mut explicit) = node_json(doc, id, 0) else { return None };
explicit.remove("childCount");
let mut out = Map::new();
@@ -251,8 +258,8 @@ fn value_json(v: &figcraft_doc::VariableValue) -> Value {
}
}
/// The variables the tree uses: every mode's stored and resolved value. A value that is an alias
/// or a calculation stays in `value`, and aliased variables are listed too, in `aliases`.
/// `ids`' variables: every mode's stored and resolved value. A value that is an alias or a
/// calculation stays in `value`; the variables it reads are in `ids` too ([`referenced`]).
fn variables_json(doc: &Document, ids: &BTreeSet<String>, missing: &mut Vec<Value>) -> Value {
let store = &doc.variables;
let mut out = Map::new();
@@ -287,6 +294,37 @@ fn variables_json(doc: &Document, ids: &BTreeSet<String>, missing: &mut Vec<Valu
Value::Object(out)
}
/// Most variables followed through aliases.
const MAX_VARIABLES: usize = 10_000;
/// The variables the tree uses: those its layers bind, those its shared styles bind, and those any
/// of them reads as an alias or in a colour calculation, however deep.
fn referenced(doc: &Document, used: &Used) -> BTreeSet<String> {
let mut out: BTreeSet<String> = used.variables.clone();
out.extend(doc.styles.iter().filter(|st| used.styles.contains(&st.id)).flat_map(|st| st.bound.values().cloned()));
let mut todo: Vec<String> = out.iter().cloned().collect();
while let Some(id) = todo.pop() {
if out.len() >= MAX_VARIABLES {
break;
}
let Some(var) = doc.variables.variables.iter().find(|v| v.id == id) else { continue };
for value in var.values.values() {
let reads: Vec<&String> = match value {
figcraft_doc::VariableValue::Alias(other) => vec![other],
figcraft_doc::VariableValue::ColorAlpha { variable, .. } => vec![variable],
figcraft_doc::VariableValue::ColorMix { from, to, .. } => from.variable().into_iter().chain(to.variable()).collect(),
_ => vec![],
};
for other in reads {
if out.insert(other.clone()) {
todo.push(other.clone());
}
}
}
}
out
}
/// The shared styles the tree uses, with what each sets.
fn styles_json(doc: &Document, ids: &BTreeSet<String>, missing: &mut Vec<Value>) -> Value {
let mut out = Map::new();
@@ -320,29 +358,13 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
Value::Object(out)
}
/// The font families under `ids`' tree, with their styles.
fn fonts(doc: &Document, roots: &[NodeId], cap: usize) -> Value {
let mut used: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut stack: Vec<NodeId> = roots.to_vec();
let mut seen = 0usize;
while let Some(id) = stack.pop() {
seen += 1;
if seen > cap {
break;
}
let Some(n) = doc.node(id) else { continue };
if let NodeKind::Text(t) = &n.kind {
for (_, _, s) in t.spans() {
used.entry(s.font_family.clone()).or_default().insert(s.font_style.clone());
}
}
stack.extend(n.children.iter().copied());
}
/// The font families the tree's text layers use, with their styles, and whether each is installed.
fn fonts(doc: &Document, used: &BTreeMap<String, BTreeSet<String>>) -> Value {
let gone = crate::fonts::missing(doc);
Value::Array(
used.into_iter()
used.iter()
.map(|(family, styles)| {
let installed = !gone.iter().any(|m| m.family.eq_ignore_ascii_case(&family));
let installed = !gone.iter().any(|m| m.family.eq_ignore_ascii_case(family));
json!({"family": family, "styles": styles, "installed": installed})
})
.collect(),
@@ -353,6 +375,13 @@ fn fonts(doc: &Document, roots: &[NodeId], cap: usize) -> Value {
fn roots(s: &Session, p: &Value) -> Result<(&'static str, Vec<NodeId>)> {
let cmd = "inspect.designContext";
let doc = s.doc()?;
let malformed = || bad(cmd, "ids: a list of layer ids (or id: one)");
match (get(p, "ids"), get(p, "id")) {
(Some(Value::Array(list)), _) if list.iter().all(|i| crate::params::id_of(i).is_some()) => {}
(Some(_), _) => return Err(malformed()),
(None, Some(one)) if crate::params::id_of(one).is_none() => return Err(malformed()),
_ => {}
}
if get(p, "ids").is_some() || get(p, "id").is_some() {
let ids: Vec<NodeId> = targets(s, p);
if let Some(gone) = ids.iter().find(|i| !doc.contains(**i)) {
@@ -400,10 +429,10 @@ fn design_context(s: &mut Session, p: &Value) -> Result<Value> {
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"}),
];
let variables = variables_json(doc, &used.variables, &mut missing);
let variables = variables_json(doc, &referenced(doc, &used), &mut missing);
let styles = styles_json(doc, &used.styles, &mut missing);
let components = components_json(doc, &used.components);
let fonts = fonts(doc, &ids, cap.saturating_mul(4));
let fonts = fonts(doc, &used.fonts);
let page = doc.node(s.page()?).map(|n| n.name.clone());
let mut out = json!({
"version": VERSION,
+1 -1
View File
@@ -431,7 +431,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
| `document` | `name`, `page`, `colorProfile` |
| `target` | `source` (`selection`, `ids`, `page`, `document`), `ids`, `layers` in the tree |
| `nodes` | The tree, below |
| `variables` | By id: `name`, `collection`, `type`, `codeSyntax`, and `modes` with each `mode`'s stored `value` and `resolved` value |
| `variables` | By id: `name`, `collection`, `type`, `codeSyntax`, and `modes` with each `mode`'s stored `value` and `resolved` value. The tree's layers and shared styles bind them, or another one reads them as an alias or in a colour calculation |
| `styles` | By id: the shared styles the tree uses |
| `components` | By id: `name`, `type`, `properties` with variants, `codeLinks` |
| `fonts` | `family`, `styles`, and whether it's `installed` |