mirror of
https://github.com/storytold/figcraft.git
synced 2026-10-31 05:46:46 -06:00
Builds on #1618. Variables::get and Variables::collection take an exact id before a name; stored mode ids go through Collection::mode_by_id (expressions, the prototype's mode switch); font family variables and the colour picker, prototype editor and panels read stored ids exactly. Ported from fix/stored-ids-exact.
This commit is contained in:
+2
-1
File diff suppressed because one or more lines are too long
@@ -110,7 +110,7 @@ impl Expr {
|
||||
let v = vars.get_by_id(variable)?;
|
||||
let c = vars.collection_by_id(&v.collection)?;
|
||||
let mut at = modes.clone();
|
||||
at.insert(c.id.clone(), c.find_mode(mode)?.id.clone());
|
||||
at.insert(c.id.clone(), c.mode_by_id(mode)?.id.clone());
|
||||
return vars.resolve(&v.id, &at);
|
||||
}
|
||||
Expr::Op { op, args } => (*op, args),
|
||||
@@ -159,7 +159,7 @@ impl Expr {
|
||||
let var = vars.get_by_id(variable);
|
||||
let mode = var
|
||||
.and_then(|v| vars.collection_by_id(&v.collection))
|
||||
.and_then(|c| c.find_mode(mode))
|
||||
.and_then(|c| c.mode_by_id(mode))
|
||||
.map_or("(missing mode)", |m| m.name.as_str());
|
||||
format!("{}[{}]", Expr::var(variable.clone()).display_at(vars, depth + 1), name_arg(mode))
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ impl Expr {
|
||||
Expr::InMode { variable, mode } => {
|
||||
let v = vars.get_by_id(variable).ok_or_else(|| format!("No variable `{variable}`"))?;
|
||||
let c = vars.collection_by_id(&v.collection).ok_or_else(|| format!("No variable collection `{}`", v.collection))?;
|
||||
return c.find_mode(mode).map(|_| v.kind).ok_or_else(|| format!("{} has no mode `{mode}`", c.name));
|
||||
return c.mode_by_id(mode).map(|_| v.kind).ok_or_else(|| format!("{} has no mode `{mode}`", c.name));
|
||||
}
|
||||
Expr::Op { op, args } => (*op, args),
|
||||
};
|
||||
|
||||
@@ -223,9 +223,14 @@ impl Collection {
|
||||
self.modes.first().map(|m| &m.id)
|
||||
}
|
||||
|
||||
/// The mode with id `key`, else the one named `key`.
|
||||
/// The mode with id `key`, else the one named `key` (what someone typed).
|
||||
pub fn find_mode(&self, key: &str) -> Option<&Mode> {
|
||||
self.modes.iter().find(|m| m.id == key).or_else(|| self.modes.iter().find(|m| m.name == key))
|
||||
self.mode_by_id(key).or_else(|| self.modes.iter().find(|m| m.name == key))
|
||||
}
|
||||
|
||||
/// The mode with id `id` exactly: a stored reference, which no mode's name stands in for (#1613).
|
||||
pub fn mode_by_id(&self, id: &str) -> Option<&Mode> {
|
||||
self.modes.iter().find(|m| m.id == id)
|
||||
}
|
||||
|
||||
/// The mode the collection is in under `modes` (collection → chosen mode): the chosen one if it
|
||||
@@ -356,8 +361,10 @@ pub struct Variables {
|
||||
}
|
||||
|
||||
impl Variables {
|
||||
pub fn get(&self, id: &str) -> Option<&Variable> {
|
||||
self.variables.iter().find(|v| v.id == id || v.name == id)
|
||||
/// The variable a person named: the one with id `key`, else the one named `key`. A stored
|
||||
/// reference goes through [`get_by_id`](Self::get_by_id) instead.
|
||||
pub fn get(&self, key: &str) -> Option<&Variable> {
|
||||
self.get_by_id(key).or_else(|| self.variables.iter().find(|v| v.name == key))
|
||||
}
|
||||
|
||||
/// Look up an already resolved variable id (a stored binding or alias): exact ids only, so a
|
||||
@@ -366,11 +373,14 @@ impl Variables {
|
||||
self.variables.iter().find(|v| v.id == id)
|
||||
}
|
||||
|
||||
pub fn collection(&self, id: &str) -> Option<&Collection> {
|
||||
self.collections.iter().find(|c| c.id == id || c.name == id)
|
||||
/// The collection a person named: the one with id `key`, else the one named `key`. A stored
|
||||
/// reference goes through [`collection_by_id`](Self::collection_by_id) instead.
|
||||
pub fn collection(&self, key: &str) -> Option<&Collection> {
|
||||
self.collection_by_id(key).or_else(|| self.collections.iter().find(|c| c.name == key))
|
||||
}
|
||||
|
||||
/// Look up a stored collection reference by exact id, without matching collection names.
|
||||
/// [`get_by_id`](Self::get_by_id) for collections: a stored collection id (a variable's own, a
|
||||
/// prototype action's, a library record's) never matches another collection's name (#1613).
|
||||
pub fn collection_by_id(&self, id: &str) -> Option<&Collection> {
|
||||
self.collections.iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
@@ -282,6 +282,26 @@ fn variables_resolve_stored_ids_never_by_name() {
|
||||
// A deleted id stays unresolved instead of picking up the variable named like it.
|
||||
assert_eq!(v.resolve("VariableID:9", &modes), None);
|
||||
assert_eq!(v.resolve("VariableID:4", &modes), None);
|
||||
// What a person types: an id wins over a name, and a name still finds its variable (#1613).
|
||||
assert_eq!(v.get("VariableID:2").map(|x| x.name.as_str()), Some("surface"));
|
||||
assert_eq!(v.get("surface").map(|x| x.id.as_str()), Some("VariableID:2"));
|
||||
assert!(v.get_by_id("surface").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_and_modes_resolve_stored_ids_never_by_name() {
|
||||
let mut v = Variables::default();
|
||||
let coll = |id: &str, name: &str, modes: Vec<Mode>| Collection { id: id.into(), name: name.into(), modes, extends: None };
|
||||
let mode = |id: &str, name: &str| Mode { id: id.into(), name: name.into() };
|
||||
v.collections.push(coll("c1", "c2", vec![mode("m1", "m2")]));
|
||||
v.collections.push(coll("c2", "Theme", vec![mode("m2", "Dark"), mode("m3", "m9")]));
|
||||
assert_eq!(v.collection("c2").map(|c| c.name.as_str()), Some("Theme"), "an id wins over a name");
|
||||
assert_eq!(v.collection("Theme").map(|c| c.id.as_str()), Some("c2"));
|
||||
assert!(v.collection_by_id("Theme").is_none() && v.collection_by_id("c9").is_none());
|
||||
let theme = v.collection_by_id("c2").unwrap();
|
||||
assert_eq!(theme.mode_by_id("m2").map(|m| m.name.as_str()), Some("Dark"));
|
||||
assert!(theme.mode_by_id("m9").is_none(), "a deleted mode id isn't the mode named like it");
|
||||
assert_eq!(theme.find_mode("Dark").map(|m| m.id.as_str()), Some("m2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -262,7 +262,7 @@ fn set_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.or_else(|| published_collections(&lib).find(|c| c.name == key))
|
||||
.ok_or_else(|| bad(cmd, format!("\"{}\" publishes no variable collection `{key}`", link.name)))?;
|
||||
let m = req_string(cmd, p, "mode")?;
|
||||
let mode = coll.modes.iter().find(|x| x.id == m || x.name == m).map(|x| x.id.clone()).ok_or_else(|| bad(cmd, "no such mode"))?;
|
||||
let mode = coll.find_mode(&m).map(|x| x.id.clone()).ok_or_else(|| bad(cmd, "no such mode"))?;
|
||||
let key = coll.id.clone();
|
||||
let map = import_variables(s.doc_mut()?, &lib, &BTreeSet::new(), &BTreeSet::from([key.clone()]), false);
|
||||
let local = map.collections.get(&key).cloned().ok_or_else(|| EngineError::Other("the collection didn't import".into()))?;
|
||||
|
||||
@@ -981,7 +981,7 @@ pub fn var_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let var = doc.variables.get(&v).cloned().ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
let coll = doc.variables.collection_by_id(&var.collection).cloned().ok_or_else(|| bad(cmd, "variable has no collection"))?;
|
||||
let mode = match string(p, "mode") {
|
||||
Some(m) => coll.modes.iter().find(|x| x.id == m || x.name == m).map(|x| x.id.clone()).ok_or_else(|| bad(cmd, "no such mode"))?,
|
||||
Some(m) => coll.find_mode(&m).map(|x| x.id.clone()).ok_or_else(|| bad(cmd, "no such mode"))?,
|
||||
None => coll.default_mode().cloned().ok_or_else(|| bad(cmd, "collection has no modes"))?,
|
||||
};
|
||||
let raw = get(p, "value").ok_or_else(|| bad(cmd, "invalid value"))?;
|
||||
|
||||
@@ -111,7 +111,7 @@ fn string_values(vars: &Variables, id: &str) -> Vec<String> {
|
||||
if !seen.insert(id.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(var) = vars.get(&id) else { continue };
|
||||
let Some(var) = vars.get_by_id(&id) else { continue };
|
||||
for v in var.values.values() {
|
||||
match v {
|
||||
VariableValue::String(s) => out.push(s.clone()),
|
||||
|
||||
@@ -523,6 +523,8 @@ mod sketch_import_tests;
|
||||
#[cfg(test)]
|
||||
mod slot_tests;
|
||||
#[cfg(test)]
|
||||
mod stored_ids_tests;
|
||||
#[cfg(test)]
|
||||
mod stroke_style_tests;
|
||||
#[cfg(test)]
|
||||
mod style_tests;
|
||||
|
||||
@@ -66,15 +66,17 @@ pub fn set_variable(doc: &mut Document, node: NodeId, variable: &str, value: &Va
|
||||
/// on the page's top-level frames that chose another mode of it (modes chosen deeper inside still
|
||||
/// win), then re-apply bindings. False for an unknown collection or mode.
|
||||
pub fn set_mode(doc: &mut Document, frame: NodeId, collection: &str, mode: &str) -> bool {
|
||||
let Some(id) = doc.variables.collection(collection).map(|c| c.id.clone()) else { return false };
|
||||
set_mode_by_id(doc, frame, &id, mode)
|
||||
let Some(c) = doc.variables.collection(collection) else { return false };
|
||||
let Some(m) = c.find_mode(mode) else { return false };
|
||||
let (collection, mode) = (c.id.clone(), m.id.clone());
|
||||
set_mode_by_id(doc, frame, &collection, &mode)
|
||||
}
|
||||
|
||||
/// Switch a stored collection id to `mode`, without matching another collection's name.
|
||||
/// Otherwise behaves like [`set_mode`].
|
||||
/// Switch a stored collection id to a stored mode id (a prototype action's), without matching
|
||||
/// another collection's or mode's name (#1613). Otherwise behaves like [`set_mode`].
|
||||
pub fn set_mode_by_id(doc: &mut Document, frame: NodeId, collection: &str, mode: &str) -> bool {
|
||||
let Some(c) = doc.variables.collection_by_id(collection) else { return false };
|
||||
let Some(mode) = c.find_mode(mode).map(|m| m.id.clone()) else {
|
||||
let Some(mode) = c.mode_by_id(mode).map(|m| m.id.clone()) else {
|
||||
return false;
|
||||
};
|
||||
let cid = c.id.clone();
|
||||
|
||||
@@ -315,8 +315,9 @@ fn stored_variable_ids_resolve_only_incoming_action_and_expression_names() {
|
||||
let actions = &doc.node(frame).unwrap().interactions[0].actions;
|
||||
let Action::SetVariable { variable, expr: Some(expr), .. } = &actions[0] else { panic!("no set variable") };
|
||||
assert_eq!(variable, &target);
|
||||
// A JSON expression is command input: it still accepts names, even one that resembles an id.
|
||||
assert_eq!(expr.eval(&doc.variables, &Default::default()), Some(VariableValue::Number(100.0)));
|
||||
// A JSON expression is command input: it accepts names, but an exact id comes first, so the
|
||||
// variable renamed to target's id doesn't take its place (#1613).
|
||||
assert_eq!(expr.eval(&doc.variables, &Default::default()), Some(VariableValue::Number(5.0)));
|
||||
let Action::Conditional { blocks } = &actions[1] else { panic!("no conditional") };
|
||||
assert_eq!(blocks[0].condition.as_ref().unwrap().eval(&doc.variables, &Default::default()), Some(VariableValue::Boolean(true)));
|
||||
let Action::SetVariable { value: stored, .. } = &blocks[0].actions[0] else { panic!("no nested set variable") };
|
||||
@@ -332,15 +333,19 @@ fn stored_variable_ids_switch_only_the_prototype_collection() {
|
||||
shadow.id = "shadow".into();
|
||||
shadow.name = theme.id.clone();
|
||||
doc.variables.collections.insert(0, shadow);
|
||||
assert!(crate::proto_run::set_mode_by_id(&mut doc, frame, &theme.id, "Dark"));
|
||||
let dark = theme.find_mode("Dark").unwrap().id.clone();
|
||||
assert!(!crate::proto_run::set_mode_by_id(&mut doc, frame, &theme.id, "Dark"), "a stored mode is an id, not a name");
|
||||
assert!(crate::proto_run::set_mode_by_id(&mut doc, frame, &theme.id, &dark));
|
||||
assert_eq!(fill_hex(&doc, r).as_deref(), Some("000000"));
|
||||
let page = doc.page_of(frame).unwrap();
|
||||
assert!(!doc.node(page).unwrap().var_modes.contains_key("shadow"));
|
||||
// The public name-accepting wrapper keeps its existing lookup behavior.
|
||||
// The name-accepting wrapper takes an exact id before a name (#1613).
|
||||
assert!(set_mode(&mut doc, frame, &theme.id, "Light"));
|
||||
assert!(!doc.node(page).unwrap().var_modes.contains_key("shadow"));
|
||||
assert!(set_mode(&mut doc, frame, "shadow", "Light"), "the other collection by its id");
|
||||
assert!(doc.node(page).unwrap().var_modes.contains_key("shadow"));
|
||||
doc.variables.collections.retain(|c| c.id != theme.id);
|
||||
let before = doc.clone();
|
||||
assert!(!crate::proto_run::set_mode_by_id(&mut doc, frame, &theme.id, "Dark"));
|
||||
assert!(!crate::proto_run::set_mode_by_id(&mut doc, frame, &theme.id, &dark));
|
||||
assert_eq!(doc, before);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! A variable renamed to another one's id never takes its place (#1613), beside #1618's tests:
|
||||
//! an id a person types (`variable.bind`, `variable.set`) finds the variable with that exact id
|
||||
//! before one named like it, and the Tailwind export and expressions read the stored id. Names still
|
||||
//! work where a person types them.
|
||||
|
||||
use figcraft_doc::VariableValue;
|
||||
use figcraft_doc::proto::Expr;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::components::tests::ex;
|
||||
|
||||
/// The issue's document: Theme with `shadow`, `surface` and `alias` (→ surface), then `shadow`
|
||||
/// renamed to surface's id with Web code syntax `--shadow`. Ids of shadow, surface and alias.
|
||||
fn renamed_like_an_id() -> (Session, String, String, String) {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Theme"}));
|
||||
let id = |v: Value| v["id"].as_str().unwrap().to_string();
|
||||
let shadow = id(ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "shadow", "type": "color", "value": "#FF0000"})));
|
||||
let surface = id(ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "surface", "type": "color", "value": "#0D99FF"})));
|
||||
let alias = id(ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "alias", "type": "color", "value": {"alias": "surface"}})));
|
||||
ex(&mut s, "variable.update", json!({"variable": shadow, "name": surface, "codeSyntax": {"WEB": "--shadow"}}));
|
||||
(s, shadow, surface, alias)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_aliases_point_at_the_stored_id() {
|
||||
let (mut s, ..) = renamed_like_an_id();
|
||||
let css = ex(&mut s, "variable.export", json!({"format": "css"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(css.contains("--alias: var(--surface);"), "{css}");
|
||||
let tw = ex(&mut s, "variable.export", json!({"format": "tailwind"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(tw.contains("var(--color-surface)") && !tw.contains("var(--shadow)"), "{tw}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_inspect_names_the_bound_variable() {
|
||||
let (mut s, _, surface, _) = renamed_like_an_id();
|
||||
let r = ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
let r = crate::params::id_of(&r["id"]).unwrap();
|
||||
ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": surface}));
|
||||
let doc = s.doc().unwrap();
|
||||
let found = crate::devinspect::bound_variable(doc, doc.node(r).unwrap(), "fill").unwrap();
|
||||
assert_eq!(found.name, "surface");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expressions_read_and_show_the_stored_variable() {
|
||||
let (mut s, _, surface, _) = renamed_like_an_id();
|
||||
ex(&mut s, "variable.addMode", json!({"collection": "Theme", "name": "Dark"}));
|
||||
ex(&mut s, "variable.set", json!({"variable": surface, "mode": "Dark", "value": "#00FF00"}));
|
||||
let vars = &s.doc().unwrap().variables;
|
||||
let theme = vars.collection("Theme").unwrap().clone();
|
||||
let dark = theme.find_mode("Dark").unwrap().id.clone();
|
||||
let e = Expr::InMode { variable: surface.clone(), mode: dark };
|
||||
assert!(matches!(e.eval(vars, &Default::default()), Some(VariableValue::Color(c)) if c.to_hex() == "00FF00"));
|
||||
assert_eq!(e.display(vars), "surface[Dark]");
|
||||
assert_eq!(Expr::var(surface).display(vars), "surface");
|
||||
}
|
||||
@@ -258,10 +258,11 @@ fn stored_variable_ids_keep_remapped_import_aliases() {
|
||||
let alias = vars.get("alias").unwrap();
|
||||
assert_eq!(alias.values.values().next(), Some(&VariableValue::Alias(target.clone())));
|
||||
assert_eq!(vars.resolve(&alias.id, &Default::default()), Some(VariableValue::Number(5.0)));
|
||||
// The command's alias argument remains name-accepting, unlike the import's remapped id.
|
||||
// The command's alias argument accepts names, but an exact id comes first (#1613): the
|
||||
// variable renamed to target's id doesn't take its place.
|
||||
ex(&mut s, "variable.set", json!({"variable": "alias", "value": {"alias": target}}));
|
||||
let vars = &s.doc().unwrap().variables;
|
||||
assert_eq!(vars.resolve(&vars.get("alias").unwrap().id, &Default::default()), Some(VariableValue::Number(100.0)));
|
||||
assert_eq!(vars.resolve(&vars.get("alias").unwrap().id, &Default::default()), Some(VariableValue::Number(5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -259,7 +259,7 @@ impl<'d> Exporter<'d> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference to variable `var` (its stored id) as variable data.
|
||||
/// A reference to variable `var` (a stored id: no name stands in for it, #1613) as variable data.
|
||||
fn alias(&mut self, var: &str) -> Option<Kv<'static>> {
|
||||
let found = self.doc.variables.get_by_id(var).and_then(|v| Some((v.kind, *self.var_ids.get(v.id.as_str())?)));
|
||||
let Some((kind, local)) = found else {
|
||||
|
||||
@@ -443,7 +443,7 @@ impl Ctx<'_> {
|
||||
let vars = &self.doc.variables;
|
||||
let found = parts.filter(|(id, _)| self.var_kinds.contains_key(*id)).and_then(|(id, mode)| {
|
||||
let v = vars.get_by_id(id)?;
|
||||
let m = vars.collection_by_id(&v.collection)?.modes.iter().find(|m| m.id == mode)?;
|
||||
let m = vars.collection_by_id(&v.collection)?.mode_by_id(mode)?;
|
||||
Some(Expr::InMode { variable: v.id.clone(), mode: m.id.clone() })
|
||||
});
|
||||
if found.is_none() {
|
||||
|
||||
@@ -556,7 +556,7 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) {
|
||||
crate::widgets::select_all_on_focus(ui, &r, &st.query);
|
||||
let note = Rect::from_min_max(pos2(field.max.x + 16.0, sr.min.y + 8.0), pos2(sr.max.x - 16.0, sr.max.y - 8.0));
|
||||
let mut bar = ui.new_child(UiBuilder::new().max_rect(note).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
let text = match (view.library, coll.extends.as_deref().and_then(|p| view.vars.collection(p))) {
|
||||
let text = match (view.library, coll.extends.as_deref().and_then(|p| view.vars.collection_by_id(p))) {
|
||||
(Some((lib, name)), _) => {
|
||||
let tip = tr("A collection of this file with these modes and variables: override their values per mode and add variables of its own");
|
||||
if widgets::button(&mut bar, tr("Extend collection"), false, true).on_hover_text(tip).clicked() {
|
||||
@@ -801,7 +801,7 @@ fn value_cell(app: &mut FigApp, ui: &mut Ui, view: &View, v: &Variable, coll: &C
|
||||
}
|
||||
}
|
||||
if let VariableValue::Alias(target) = val {
|
||||
let full = view.vars.get(target).map(|x| x.name.as_str()).unwrap_or(tr("Missing variable"));
|
||||
let full = view.vars.get_by_id(target).map(|x| x.name.as_str()).unwrap_or(tr("Missing variable"));
|
||||
let resp = ui.interact(body, id.with("alias"), if editable { Sense::click() } else { Sense::hover() });
|
||||
let resp = if editable { resp.on_hover_text(tr("Change alias")) } else { resp };
|
||||
ui.painter().rect_filled(body, CornerRadius::same(5), t.field);
|
||||
@@ -968,7 +968,7 @@ fn create_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
|
||||
/// The details of one of this file's variables: name, description, where pickers offer it and
|
||||
/// whether publishing the file as a library leaves it out.
|
||||
fn details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Editor) {
|
||||
let Some(v) = st.details.as_ref().filter(|_| st.library.is_none()).and_then(|id| vars.get(id)).cloned() else {
|
||||
let Some(v) = st.details.as_ref().filter(|_| st.library.is_none()).and_then(|id| vars.get_by_id(id)).cloned() else {
|
||||
st.details = None;
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -904,7 +904,7 @@ fn publish_form(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
if !all.collections.is_empty() {
|
||||
crate::widgets::sublabels(ui, tr("Variable collections"), None);
|
||||
for c in &all.collections {
|
||||
let name = doc.variables.collection(c).map(|x| x.name.as_str()).unwrap_or_default();
|
||||
let name = doc.variables.collection_by_id(c).map(|x| x.name.as_str()).unwrap_or_default();
|
||||
if check(ui, format!("v{c}"), def.collections.contains(c), name) {
|
||||
include.push(json!(c));
|
||||
}
|
||||
|
||||
@@ -445,7 +445,7 @@ pub fn ops_for(kind: Option<VariableType>) -> &'static [ExprOp] {
|
||||
fn with_op(s: &Simple, op: ExprOp, vars: &Variables) -> Simple {
|
||||
let rhs = match (op, &s.rhs) {
|
||||
(ExprOp::Not, _) => Rhs::Nothing,
|
||||
(_, Rhs::Nothing) => Rhs::Value(vars.get(&s.var).map_or(VariableValue::Boolean(true), |v| start_value(vars, v))),
|
||||
(_, Rhs::Nothing) => Rhs::Value(vars.get_by_id(&s.var).map_or(VariableValue::Boolean(true), |v| start_value(vars, v))),
|
||||
(_, r) => r.clone(),
|
||||
};
|
||||
Simple { var: s.var.clone(), op, rhs }
|
||||
@@ -479,7 +479,7 @@ fn condition_editor(app: &mut FigApp, ui: &mut Ui, cx: &Cx, slot: &Slot, b: usiz
|
||||
|
||||
fn builder_row(app: &mut FigApp, ui: &mut Ui, cx: &Cx, slot: &Slot, b: usize, s: &Simple) {
|
||||
let vars = &cx.doc.variables;
|
||||
let var = vars.get(&s.var);
|
||||
let var = vars.get_by_id(&s.var);
|
||||
let kind = var.map(|v| v.kind);
|
||||
row(ui, 32.0, |ui| {
|
||||
let w = ui.available_width();
|
||||
@@ -507,7 +507,7 @@ fn builder_row(app: &mut FigApp, ui: &mut Ui, cx: &Cx, slot: &Slot, b: usize, s:
|
||||
Rhs::Nothing => {}
|
||||
Rhs::Variable(other) => {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(side, FIELD_H), Sense::hover());
|
||||
let name = vars.get(other).map_or(tr("Missing variable"), |v| v.name.as_str());
|
||||
let name = vars.get_by_id(other).map_or(tr("Missing variable"), |v| v.name.as_str());
|
||||
match widgets::bound_field(ui, slot.id("proto_cond_rhs_var").with(b), Lead::None, rect, name) {
|
||||
Some(BindEvent::Open(at)) => crate::variable_ui::open_proto(ui, VarSlot { slot: slot.clone(), part: VarPart::Rhs(b) }, kind, at),
|
||||
Some(BindEvent::Detach) => {
|
||||
@@ -569,7 +569,7 @@ fn literal_field(ui: &mut Ui, id: Id, cur: &VariableValue, w: f32) -> Option<Var
|
||||
/// computed by an expression when the action runs (`count + 1`, `"Hi " + name`).
|
||||
fn set_variable_fields(app: &mut FigApp, ui: &mut Ui, cx: &Cx, slot: &Slot, variable: &str, value: &Value, expr: Option<&Expr>) {
|
||||
let vars = &cx.doc.variables;
|
||||
let var = vars.get(variable);
|
||||
let var = vars.get_by_id(variable);
|
||||
widgets::sublabels(ui, tr("Variable"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let name = var.map_or(tr("Choose variable"), |v| v.name.as_str());
|
||||
@@ -694,19 +694,19 @@ where
|
||||
pub fn pick_variable(app: &mut FigApp, vs: &VarSlot, id: &str) {
|
||||
let Ok(doc) = app.session.ds().map(|d| d.doc.clone()) else { return };
|
||||
let vars = &doc.variables;
|
||||
let Some(picked) = vars.get(id) else { return };
|
||||
let Some(picked) = vars.get_by_id(id) else { return };
|
||||
let current = doc.node(vs.slot.node).and_then(|n| n.interactions.get(vs.slot.k)).and_then(|it| action_at(&it.actions, &vs.slot.path));
|
||||
match (vs.part, current) {
|
||||
(VarPart::SetVariable, Some(Action::SetVariable { variable, value, expr })) => {
|
||||
// Another type starts from the new variable's value.
|
||||
let same = vars.get(variable).is_some_and(|v| v.kind == picked.kind);
|
||||
let same = vars.get_by_id(variable).is_some_and(|v| v.kind == picked.kind);
|
||||
let (value, expr) = if same { (value.clone(), expr.clone()) } else { (value_json(&start_value(vars, picked)), None) };
|
||||
set_action(app, &vs.slot, Action::SetVariable { variable: picked.id.clone(), value, expr });
|
||||
}
|
||||
(VarPart::Lhs(b), Some(Action::Conditional { blocks })) => {
|
||||
let cur = blocks.get(b).and_then(|x| x.condition.as_ref()).and_then(simple);
|
||||
let next = match cur {
|
||||
Some(s) if vars.get(&s.var).is_some_and(|v| v.kind == picked.kind) => Simple { var: picked.id.clone(), ..s },
|
||||
Some(s) if vars.get_by_id(&s.var).is_some_and(|v| v.kind == picked.kind) => Simple { var: picked.id.clone(), ..s },
|
||||
_ => Simple { var: picked.id.clone(), op: ExprOp::Equals, rhs: Rhs::Value(start_value(vars, picked)) },
|
||||
};
|
||||
set_condition(app, &vs.slot, b, &next.expr());
|
||||
|
||||
@@ -198,14 +198,14 @@ pub(crate) fn action_summary(doc: &Document, a: &Action) -> String {
|
||||
match a {
|
||||
Action::OpenUrl { url } if !url.is_empty() => trf("Open link {url}", &[("url", url)]),
|
||||
Action::SetVariable { variable, expr, .. } => {
|
||||
let name = vars.get(variable).map_or(variable.as_str(), |v| v.name.as_str());
|
||||
let name = vars.get_by_id(variable).map_or(variable.as_str(), |v| v.name.as_str());
|
||||
match expr {
|
||||
Some(e) => trf("Set {name} to {value}", &[("name", &name), ("value", &e.display(vars))]),
|
||||
None => trf("Set variable {name}", &[("name", &name)]),
|
||||
}
|
||||
}
|
||||
Action::SetVariableMode { collection, mode } => {
|
||||
let c = vars.collection(collection);
|
||||
let c = vars.collection_by_id(collection);
|
||||
let mode = c.and_then(|c| c.modes.iter().find(|m| &m.id == mode)).map_or(mode.as_str(), |m| m.name.as_str());
|
||||
trf("Set {name} to {value}", &[("name", &c.map_or(collection.as_str(), |c| c.name.as_str())), ("value", &mode)])
|
||||
}
|
||||
@@ -1060,7 +1060,7 @@ pub(crate) fn action_fields(app: &mut FigApp, ui: &mut Ui, doc: &Document, page:
|
||||
}
|
||||
Action::SetVariableMode { collection, mode } => {
|
||||
let colls = &doc.variables.collections;
|
||||
let current = doc.variables.collection(collection);
|
||||
let current = doc.variables.collection_by_id(collection);
|
||||
widgets::sublabels(ui, tr("Collection"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let resp = widgets::dropdown(ui, current.map_or(tr("Choose collection"), |c| c.name.as_str()), ui.available_width(), None);
|
||||
|
||||
@@ -82,7 +82,7 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
.style
|
||||
.as_ref()
|
||||
.and_then(|id| doc.style(id).map(|s| s.name.as_str()))
|
||||
.or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get(id).map(|v| v.name.as_str())));
|
||||
.or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get_by_id(id).map(|v| v.name.as_str())));
|
||||
if let Some(name) = linked_name {
|
||||
let response = widgets::dropdown(ui, name, width, None);
|
||||
toggle(app, group.targets.clone(), Some(&response));
|
||||
|
||||
@@ -288,7 +288,7 @@ mod variable_tests {
|
||||
/// The name of the variable `field` of the text layer is bound to.
|
||||
fn bound_to(&self, field: &str) -> Option<String> {
|
||||
let doc = self.app.session.doc().unwrap();
|
||||
doc.node(self.text).unwrap().bound.get(field).and_then(|v| doc.variables.get(v)).map(|v| v.name.clone())
|
||||
doc.node(self.text).unwrap().bound.get(field).and_then(|v| doc.variables.get_by_id(v)).map(|v| v.name.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn bound_name(doc: &Document, ids: &[NodeId], field: &str) -> Option<String>
|
||||
if !it.all(|v| v.as_ref() == Some(&first)) {
|
||||
return None;
|
||||
}
|
||||
doc.variables.get(&first).map(|v| v.name.clone())
|
||||
doc.variables.get_by_id(&first).map(|v| v.name.clone())
|
||||
}
|
||||
|
||||
/// A variable a picker offers: one of this file's, or a published one of an enabled library.
|
||||
@@ -397,7 +397,7 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) {
|
||||
// variables never lead back to this file's).
|
||||
let (scope, own) = match &p.target {
|
||||
Target::Bind { ids, field } => (ids.first().and_then(|id| figcraft_engine::cmd::variables::field_scope(&doc, *id, field)), None),
|
||||
Target::Alias { variable, .. } => (None, doc.variables.get(variable)),
|
||||
Target::Alias { variable, .. } => (None, doc.variables.get_by_id(variable)),
|
||||
Target::Proto(_) | Target::Style { .. } => (None, None),
|
||||
};
|
||||
// A style's fields offer variables scoped to one of the properties the field sets.
|
||||
|
||||
@@ -77,7 +77,9 @@ fn counter_then_conditional_navigation() {
|
||||
fn set_variable_mode_recolours_bound_layers() {
|
||||
let (mut doc, a, _, button) = setup();
|
||||
let theme = doc.variables.collection("Theme").unwrap().id.clone();
|
||||
on_click(&mut doc, button, vec![Action::SetVariableMode { collection: theme.clone(), mode: "Dark".into() }]);
|
||||
// Actions store mode ids (commands and imports turn names into them).
|
||||
let dark = doc.variables.collection("Theme").unwrap().find_mode("Dark").unwrap().id.clone();
|
||||
on_click(&mut doc, button, vec![Action::SetVariableMode { collection: theme.clone(), mode: dark }]);
|
||||
let hex = |p: &Presenter| p.doc.as_ref().and_then(|d| d.node(a)?.fills.first()?.solid_color()).map(|c| c.to_hex());
|
||||
let mut p = Presenter::new(a);
|
||||
p.sync(&Arc::new(doc), 0.0);
|
||||
@@ -118,7 +120,8 @@ fn stored_variable_ids_keep_player_collection_identity() {
|
||||
if missing {
|
||||
doc.variables.collections.retain(|c| c.id != theme.id);
|
||||
}
|
||||
on_click(&mut doc, button, vec![Action::SetVariableMode { collection: theme.id.clone(), mode: "Dark".into() }]);
|
||||
let dark = theme.find_mode("Dark").unwrap().id.clone();
|
||||
on_click(&mut doc, button, vec![Action::SetVariableMode { collection: theme.id.clone(), mode: dark }]);
|
||||
let mut p = Presenter::new(a);
|
||||
p.sync(&Arc::new(doc), 0.0);
|
||||
assert_eq!(p.fire(button, 0, None, 1.0), !missing);
|
||||
|
||||
@@ -97,7 +97,7 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option<Paint> {
|
||||
}
|
||||
PickerTarget::Effect { ids, index, secondary } => doc.node(*ids.first()?)?.effects.get(*index)?.color(*secondary).map(Paint::solid),
|
||||
PickerTarget::TextRange { id, start, .. } => range_fills(doc, *id, *start)?.into_iter().next(),
|
||||
PickerTarget::Variable { id, mode } => match doc.variables.get(id)?.values.get(mode)? {
|
||||
PickerTarget::Variable { id, mode } => match doc.variables.get_by_id(id)?.values.get(mode)? {
|
||||
figcraft_doc::VariableValue::Color(c) => {
|
||||
let mut p = Paint::solid(c.with_alpha(1.0));
|
||||
p.opacity = c.a;
|
||||
|
||||
@@ -667,7 +667,7 @@ fn binding_cell(ui: &mut Ui, doc: &Document, style: &Style, field: &str, kind: f
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let row = ui.min_rect();
|
||||
let row = Rect::from_min_max(pos2(row.min.x, row.max.y - ROW_H), row.max);
|
||||
let Some(name) = style.bound.get(field).map(|v| doc.variables.get(v).map_or(v.as_str(), |x| x.name.as_str())) else {
|
||||
let Some(name) = style.bound.get(field).map(|v| doc.variables.get_by_id(v).map_or(v.as_str(), |x| x.name.as_str())) else {
|
||||
let b = Rect::from_center_size(pos2(row.max.x - 13.0, row.center().y), vec2(20.0, 20.0));
|
||||
if ui.rect_contains_pointer(row) && menu_icon(ui, b, Icon::Variable, tr("Apply variable"), false).clicked() {
|
||||
crate::variable_ui::open_style(ui, &style.id, field, kind, row.left_bottom());
|
||||
@@ -732,7 +732,7 @@ fn text_binding(ui: &mut Ui, binding: TextBinding<'_>, out: &mut Frame) {
|
||||
|
||||
/// The text style's variable name for `field`, or None when the field is not bound.
|
||||
fn bound_name(doc: &Document, style: &Style, field: &str) -> Option<String> {
|
||||
style.bound.get(field).map(|v| doc.variables.get(v).map_or_else(|| v.clone(), |x| x.name.clone()))
|
||||
style.bound.get(field).map(|v| doc.variables.get_by_id(v).map_or_else(|| v.clone(), |x| x.name.clone()))
|
||||
}
|
||||
|
||||
/// Redefines the text style `def` through `f`; the edit is queued only when it changes the style.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Components, variants, styles and variables parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (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
|
||||
@@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-30 | minor | M3, #1613: a variable, collection or mode named like another one's id no longer takes its place where an id is stored or typed (expressions, prototype mode switches, font family variables, the panels' labels); names still work where a person types them. Grade unchanged. |
|
||||
| 2026-10-30 | minor | M3, #1280: a colour variable can be calculated from others, per mode: `{"alpha": {"variable", "opacity"}}` is that variable's colour with its alpha replaced (replace, not multiply, so re-editing the source's alpha never compounds), `{"mix": {"from", "to", "t"}}` blends two operands (`{"variable"}` or `{"literal"}`) per channel over the stored values in the document's colour profile, alpha included (converting the profile keeps a mix's ends exact and moves its colours in between slightly). Calculations resolve lazily like aliases, so bound layers, mode switches, instances and undo follow their sources; they compose (a calculation of a calculation), a loop is refused when it is set, and one resolve consults at most 32 variables. Files keep them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes (other collections in their default modes, so a CSS calculation doesn't follow another collection's `data-` mode); deleting a source leaves its readers on the colour they showed; library import and swap re-point their operands. The panel shows them read-only (swatch and formula) and can swap one for an alias or detach it to its colour. Tests: `engine/src/variables_colour_tests.rs`, `doc/src/tests.rs`. Left: editing calculations in the panel; files using them need this build to open. Numbers unchanged |
|
||||
| 2026-10-30 | minor | M3, follow-up to #1542: stored variable and collection references use exact ids in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker, and prototype actions and expressions. Interaction edits resolve only incoming names and leave stored references alone. Command arguments still accept names as before. Tests: the `stored_variable_ids_*` tests in the doc, engine, format and ui-egui present and responsive suites. Numbers unchanged |
|
||||
| 2026-10-30 | minor | M8: the component set's Properties section fits the narrowest right panel: variant values wrap onto more lines and every + and − button stays visible. Grade unchanged. |
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user