diff --git a/.changepacks/changepack_log_pLGAn-QZITPX71heBZ0EO.json b/.changepacks/changepack_log_pLGAn-QZITPX71heBZ0EO.json new file mode 100644 index 00000000..214347d5 --- /dev/null +++ b/.changepacks/changepack_log_pLGAn-QZITPX71heBZ0EO.json @@ -0,0 +1,7 @@ +{ + "changes": { + "Cargo.toml": "Patch" + }, + "note": "Export collision-free Figma colour token names, verify source-map variable bindings against each node, keep fixed icons from shrinking, and report code tokens that differ from the Figma binding", + "date": "2026-11-28T15:16:06.146464Z" +} diff --git a/crates/devup-mcp-devup-ui/src/codegen/component/component_generation.rs b/crates/devup-mcp-devup-ui/src/codegen/component/component_generation.rs index d666d0e2..c3ba191f 100644 --- a/crates/devup-mcp-devup-ui/src/codegen/component/component_generation.rs +++ b/crates/devup-mcp-devup-ui/src/codegen/component/component_generation.rs @@ -78,6 +78,15 @@ impl CodegenOptions { ) -> Self { self.text_style_tokens = named_tokens(styles, "styles"); self.variable_tokens = named_tokens(variables, "variables"); + // The theme's own names, collision-free across the whole catalog, so + // a `$token` in the code is the key `devup.json` defines for exactly + // that variable. + if let Some(snapshot) = + variables.and_then(|result| crate::theme::variable_snapshot_from_result(result).ok()) + { + self.variable_tokens + .extend(crate::theme::variable_token_names(&snapshot)); + } self.length_tokens = length_tokens(variables); let mut snapshot = variables .and_then(|result| crate::theme::variable_snapshot_from_result(result).ok()) @@ -139,15 +148,13 @@ fn length_tokens(variables: Option<&UpstreamResult>) -> BTreeMap, style_tokens: &BTreeMap, entries: &mut Vec, + unverified: &mut Vec, ) { + let node_id = node.id.as_str(); let source = &tsx[range.start..range.end]; + let bound = bound_variable_ids(node, None); let view = node.typed_view(); let segments = view .value("styledTextSegments") @@ -389,6 +391,19 @@ fn add_text_entries( let prop_end = source[start..] .find('"') .map_or(start + needle.len(), |offset| start + offset + 1); + if !bound.contains(variable_id) { + unverified.push(UnverifiedVariableEntry { + node_id: node_id.to_owned(), + property: "styledTextSegments".to_owned(), + token: token.clone(), + candidate_variable_ids: vec![variable_id.clone()], + generated_range: Some(GeneratedRange { + start: range.start + prop_start, + end: range.start + prop_end, + }), + }); + continue; + } entries.push(generated_entry( range.start + prop_start, range.start + prop_end, @@ -650,3 +665,173 @@ mod line_height_calculation_tests { ); } } + +/// A `$token` in a generated attribute whose variable is not bound where the +/// attribute says it came from. Never recorded as a variable mapping; counted +/// so the summary says how many were refused. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UnverifiedVariableEntry { + pub node_id: String, + pub property: String, + pub token: String, + pub candidate_variable_ids: Vec, + #[serde(skip)] + pub generated_range: Option, +} + +/// Every variable id bound on `node`, in document order of its fields: the +/// `boundVariables` map and any `VARIABLE_ALIAS` inside a paint, effect or +/// segment. With `property`, only the bindings of that field — +/// `boundVariables[property]` and `paint.boundVariables.color` of the paints +/// in it — and, for a paint list, the paint drawn on top first. +fn bound_variable_ids(node: &devup_mcp_figma::RawNode, property: Option<&str>) -> Vec { + fn scan(value: &serde_json::Value, output: &mut Vec) { + match value { + serde_json::Value::Object(object) => { + if object.get("type").and_then(serde_json::Value::as_str) == Some("VARIABLE_ALIAS") + && let Some(id) = object + .get("id") + .and_then(serde_json::Value::as_str) + .filter(|id| !id.is_empty() && *id != "figma.mixed" && *id != "MIXED") + && !output.iter().any(|known| known == id) + { + output.push(id.to_owned()); + } + object.values().for_each(|value| scan(value, output)); + } + serde_json::Value::Array(values) => values.iter().for_each(|value| scan(value, output)), + _ => {} + } + } + let view = node.typed_view(); + let mut output = Vec::new(); + match property { + Some(property) => { + if let Some(paints) = view.value(property).and_then(serde_json::Value::as_array) { + // Figma paints the last paint of a list on top: that is the + // one a single CSS colour stands for. + for paint in paints.iter().rev() { + if paint.get("visible").and_then(serde_json::Value::as_bool) != Some(false) { + scan(paint, &mut output); + } + } + } else if let Some(value) = view.value(property) { + scan(value, &mut output); + } + if let Some(bound) = view.value("boundVariables").and_then(|b| b.get(property)) { + scan(bound, &mut output); + } + // Mixed text keeps its paints per character range: in the + // segments, and as `textRangeFills` among the bindings. + if node.node_type == "TEXT" && property == "fills" { + if let Some(bound) = view + .value("boundVariables") + .and_then(|b| b.get("textRangeFills")) + { + scan(bound, &mut output); + } + for segment in view + .value("styledTextSegments") + .and_then(serde_json::Value::as_array) + .into_iter() + .flatten() + { + if let Some(fills) = segment.get("fills") { + scan(fills, &mut output); + } + } + } + } + None => { + for (_, value) in node.fields.iter().chain(&node.extra) { + scan(value, &mut output); + } + } + } + output +} + +/// The fields whose bindings a `$token` written for `property` can come +/// from. A paint list is its own evidence; any other field (a radius, a +/// padding, a size) may be bound under a more specific key, so the whole node +/// is. +fn binding_is_paint(property: &str) -> bool { + matches!(property, "fills" | "strokes" | "effects") +} + +/// The variable a generated attribute value stands for on `node`, proven by +/// the node's own bindings: of the variables whose `$token` appears in +/// `value`, the one bound to `property` (the paint drawn on top first), else +/// one bound anywhere on the node for a non-paint property. A token no +/// binding of the node accounts for is returned as unverified instead. +/// +/// Returns the node whose binding proves it, too: `node` +/// itself, or — with `snapshot` — a descendant that is not an element of its +/// own (`emitted` has no range for it) and so is drawn by this one, as an +/// icon's vector is drawn by the box that masks it. A descendant that is its +/// own element is never evidence for its parent: an inlined button's label +/// binds the label, not the button. +fn verified_resource_source( + value: &str, + tokens: &BTreeMap, + snapshot: Option<&Snapshot>, + node: &devup_mcp_figma::RawNode, + property: &str, + emitted: &BTreeMap, +) -> Result, UnverifiedVariableEntry> { + let candidates = tokens + .iter() + .filter(|(id, token)| { + find_resource_id(value, &BTreeMap::from([((*id).clone(), (*token).clone())]), '$') + .is_some() + }) + .map(|(id, _)| id.clone()) + .collect::>(); + if candidates.is_empty() { + return Ok(None); + } + let own = bound_variable_ids(node, Some(property)); + if let Some(id) = own.iter().find(|id| candidates.contains(id)) { + return Ok(Some((node.id.clone(), id.clone()))); + } + if !binding_is_paint(property) + && let Some(id) = bound_variable_ids(node, None) + .into_iter() + .find(|id| candidates.contains(id)) + { + return Ok(Some((node.id.clone(), id))); + } + if let Some(snapshot) = snapshot { + let mut pending = node.typed_view().child_ids().map(str::to_owned).collect::>(); + while let Some(child_id) = pending.pop() { + if emitted.contains_key(&child_id) { + continue; + } + let Some(child) = snapshot.nodes.get(&child_id) else { + continue; + }; + if child.typed_view().bool("visible") == Some(false) { + continue; + } + if let Some(id) = bound_variable_ids(child, Some(property)) + .into_iter() + .find(|id| candidates.contains(id)) + { + return Ok(Some((child_id, id))); + } + pending.extend(child.typed_view().child_ids().map(str::to_owned)); + } + } + Err(UnverifiedVariableEntry { + node_id: node.id.clone(), + property: property.to_owned(), + token: candidates + .first() + .and_then(|id| tokens.get(id)) + .cloned() + .unwrap_or_default(), + candidate_variable_ids: candidates, + generated_range: None, + }) +} diff --git a/crates/devup-mcp-devup-ui/src/provenance/baked_into_assets.rs b/crates/devup-mcp-devup-ui/src/provenance/baked_into_assets.rs index b4446350..77401c54 100644 --- a/crates/devup-mcp-devup-ui/src/provenance/baked_into_assets.rs +++ b/crates/devup-mcp-devup-ui/src/provenance/baked_into_assets.rs @@ -574,6 +574,7 @@ pub(crate) fn finalize_tsx( .push(asset); } let mut entries = Vec::new(); + let mut unverified_variables = Vec::::new(); for (node_id, range) in node_ranges { let Some(node) = snapshot.nodes.get(&node_id) else { continue; @@ -703,7 +704,32 @@ pub(crate) fn finalize_tsx( }; let end = value_start + value_end + 1; let value = &opening[value_start..value_start + value_end]; - let variable_id = find_resource_id(value, variable_tokens, '$'); + let mut evidence_node = None; + let variable_id = match verified_resource_source( + value, + variable_tokens, + Some(snapshot), + node, + property, + &emitted_ranges, + ) { + // A descendant drawn by this element proves the variable; the + // attribute stays this element's, and the variable is entered + // under the descendant that binds it. + Ok(Some((source_node, variable_id))) if source_node != node_id => { + evidence_node = Some((source_node, variable_id)); + None + } + Ok(found) => found.map(|(_, variable_id)| variable_id), + Err(mut unverified) => { + unverified.generated_range = Some(GeneratedRange { + start: range.start + open_relative + start, + end: range.start + open_relative + end, + }); + unverified_variables.push(unverified); + None + } + }; let style_id = (*prop == "typography") .then(|| { style_tokens @@ -793,6 +819,17 @@ pub(crate) fn finalize_tsx( style_id, resolution, )); + if let Some((source_node, variable_id)) = evidence_node { + entries.push(generated_entry( + range.start + open_relative + start, + range.start + open_relative + end, + &source_node, + property, + Some(variable_id), + None, + "variable-token", + )); + } } if crate::codegen::folded_mask_dimensions(snapshot, node).is_some() { @@ -865,11 +902,11 @@ pub(crate) fn finalize_tsx( add_text_entries( &tsx, &range, - &node_id, node, variable_tokens, style_tokens, &mut entries, + &mut unverified_variables, ); } } @@ -881,6 +918,19 @@ pub(crate) fn finalize_tsx( &assets_by_node, &mut entries, ); + // A token the attribute's own node does not bind may still be the + // flattened paint of a descendant it represents; that pass recorded it + // under the descendant's id. Only a token nothing accounts for is left. + unverified_variables.retain(|unverified| { + !entries.iter().any(|entry| { + entry.resolution == "variable-token" + && entry.generated_range == unverified.generated_range + && entry + .variable_id + .as_ref() + .is_some_and(|id| unverified.candidate_variable_ids.contains(id)) + }) + }); entries.sort_by(|left, right| { let left_range = left.generated_range.as_ref(); let right_range = right.generated_range.as_ref(); @@ -898,6 +948,7 @@ pub(crate) fn finalize_tsx( asset_css_mappings: Vec::new(), variable_tokens: variable_tokens.clone(), style_tokens: style_tokens.clone(), + unverified_variables, }, ) } diff --git a/crates/devup-mcp-devup-ui/src/provenance/source_map_and_contracts.rs b/crates/devup-mcp-devup-ui/src/provenance/source_map_and_contracts.rs index 3d6431c7..c11f6d85 100644 --- a/crates/devup-mcp-devup-ui/src/provenance/source_map_and_contracts.rs +++ b/crates/devup-mcp-devup-ui/src/provenance/source_map_and_contracts.rs @@ -86,6 +86,11 @@ pub struct SourceMap { pub variable_tokens: BTreeMap, #[serde(skip)] pub style_tokens: BTreeMap, + /// `$token`s found in the code that no binding of the node they were + /// generated for accounts for. They are not entries; the fidelity + /// summary reports how many there were. + #[serde(skip)] + pub unverified_variables: Vec, } impl Serialize for SourceMap { @@ -169,6 +174,7 @@ impl SourceMap { asset_css_mappings: Vec::new(), variable_tokens: BTreeMap::new(), style_tokens: BTreeMap::new(), + unverified_variables: Vec::new(), } } } @@ -256,6 +262,14 @@ pub struct FidelityReport { /// `impacts`, `strict_compatible`, or the reported status. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub uncovered_layout: Vec, + /// How many `$token`s in the code failed verification against the Figma + /// bindings of the node they were generated for, and so were left out of + /// the source map. Zero when every variable mapping is proven. + #[serde(default)] + pub unverified_variable_entries: usize, + /// The first of them, bounded by [`MAX_REPORTED_UNCOVERED`]. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unverified_variables: Vec, } /// Enough to see the shape of a shortfall without turning a diagnostic into a @@ -750,6 +764,14 @@ pub fn validate_fidelity( layout: FidelityCoverage::new(layout.len(), covered_layout), impacts, uncovered_layout, + unverified_variable_entries: output.source_map.unverified_variables.len(), + unverified_variables: output + .source_map + .unverified_variables + .iter() + .take(MAX_REPORTED_UNCOVERED) + .cloned() + .collect(), }) } diff --git a/crates/devup-mcp-devup-ui/src/theme/devup_json.rs b/crates/devup-mcp-devup-ui/src/theme/devup_json.rs index a6cbb71b..d27e8de4 100644 --- a/crates/devup-mcp-devup-ui/src/theme/devup_json.rs +++ b/crates/devup-mcp-devup-ui/src/theme/devup_json.rs @@ -3,3 +3,4 @@ include!("devup_json/theme_generation.rs"); include!("devup_json/typography_values.rs"); include!("devup_json/responsive_entry.rs"); include!("devup_json/mode_projection.rs"); +include!("devup_json/token_names.rs"); diff --git a/crates/devup-mcp-devup-ui/src/theme/devup_json/theme_generation.rs b/crates/devup-mcp-devup-ui/src/theme/devup_json/theme_generation.rs index 4177140f..0b7c88a1 100644 --- a/crates/devup-mcp-devup-ui/src/theme/devup_json/theme_generation.rs +++ b/crates/devup-mcp-devup-ui/src/theme/devup_json/theme_generation.rs @@ -178,6 +178,22 @@ pub fn generate_devup_json( snapshot: &VariableSnapshot, scope: ThemeScope, ) -> Result { + generate_devup_json_named(snapshot, scope, &variable_token_names(snapshot)) +} + +/// [`generate_devup_json`] under names computed from a larger catalog than +/// `snapshot` — a selection of it keeps the names the whole file gives. +pub(crate) fn generate_devup_json_named( + snapshot: &VariableSnapshot, + scope: ThemeScope, + names: &BTreeMap, +) -> Result { + let name_of = |variable: &VariableDefinition| { + names + .get(&variable.id) + .cloned() + .unwrap_or_else(|| base_variable_token(variable)) + }; let mut diagnostics = Vec::new(); let mut conflicts = Vec::new(); let mut unresolved_variables = Vec::new(); @@ -267,10 +283,7 @@ pub fn generate_devup_json( { continue; } - let token = variable_token( - &variable.name, - variable.code_syntax.get("WEB").map(String::as_str), - ); + let token = name_of(variable); let is_alias = |mode_id: &str| { variable .values_by_mode @@ -449,13 +462,7 @@ pub fn generate_devup_json( let variable_names = variables .values() .map(|variable| { - ( - variable.id.as_str(), - variable_token( - &variable.name, - variable.code_syntax.get("WEB").map(String::as_str), - ), - ) +(variable.id.as_str(), name_of(variable)) }) .collect::>(); let selected_style_ids = (scope != ThemeScope::File && !snapshot.used_style_ids.is_empty()) diff --git a/crates/devup-mcp-devup-ui/src/theme/devup_json/token_names.rs b/crates/devup-mcp-devup-ui/src/theme/devup_json/token_names.rs new file mode 100644 index 00000000..b2246c7b --- /dev/null +++ b/crates/devup-mcp-devup-ui/src/theme/devup_json/token_names.rs @@ -0,0 +1,330 @@ +/// The `$token` every variable of a snapshot is written as, by variable id. +/// +/// A variable used to be named after the last segment of its path, so +/// `gold/200`, `line/200` and `red/200` all became `_200` and `devup.json` +/// could hold only one of their colours: the generated code then pointed at +/// one name for three different variables, and whatever picked between them +/// later picked wrong. The names here are unique per kind of token wherever +/// two variables could meet in one theme: +/// +/// - a WEB code syntax, when the file declares one, names the variable; +/// - a leaf that is only a scale step (`200`, `50`) is not a name on its own, +/// so the group path is kept (`gold/200` → `gold200`) whether or not +/// another group has the same step today, and adding `red/200` later does +/// not rename `gold200`; +/// - any other leaf is the name while it is unique (`text/primary` → +/// `primary`); when two variables share it, each of them takes its whole +/// path, then its collection, then a numbered suffix, until no two do — +/// except that a file's own variable keeps its name against a library +/// variable, which is the one qualified. +/// +/// Names are computed over the whole catalog of the snapshot, never over a +/// scope's selection of it, so the theme, the code and a minimal theme of the +/// used tokens agree on every name. +pub fn variable_token_names(snapshot: &VariableSnapshot) -> BTreeMap { + struct Entry<'a> { + variable: &'a VariableDefinition, + remote: bool, + kind: &'static str, + buckets: BTreeSet, + candidates: Vec, + } + let collections = snapshot + .collections + .iter() + .map(|collection| (collection.id.as_str(), collection)) + .collect::>(); + let mut seen = BTreeSet::new(); + let remote_ids = snapshot + .used_remote_variables + .iter() + .map(|variable| variable.id.as_str()) + .filter(|id| !snapshot.variables.iter().any(|local| local.id == *id)) + .collect::>(); + let mut entries = snapshot + .variables + .iter() + .chain(&snapshot.used_remote_variables) + .filter(|variable| seen.insert(variable.id.as_str())) + .map(|variable| { + let collection = collections.get(variable.variable_collection_id.as_str()); + let collection_name = collection.map_or("", |collection| collection.name.as_str()); + let path = normalize_token(&variable.name); + let qualified = normalize_token(&format!("{collection_name}/{}", variable.name)); + Entry { + variable, + remote: remote_ids.contains(variable.id.as_str()), + kind: match variable.resolved_type.as_str() { + "COLOR" => "color", + "FLOAT" => "length", + _ => "other", + }, + buckets: collection.map_or_else( + || BTreeSet::from([String::new()]), + |collection| theme_buckets(collection), + ), + candidates: { + let mut candidates = vec![base_variable_token(variable)]; + for name in [path, qualified] { + if !candidates.contains(&name) { + candidates.push(name); + } + } + candidates + }, + } + }) + .collect::>(); + // Deterministic whatever order the catalog arrived in. + entries.sort_by(|left, right| left.variable.id.cmp(&right.variable.id)); + let mut level = vec![0usize; entries.len()]; + let name_of = |index: usize, level: &[usize]| -> String { + let candidates = &entries[index].candidates; + candidates[level[index].min(candidates.len() - 1)].clone() + }; + let meets = |left: usize, right: usize| { + entries[left].kind == entries[right].kind + && !entries[left].buckets.is_disjoint(&entries[right].buckets) + }; + loop { + let names = (0..entries.len()) + .map(|index| name_of(index, &level)) + .collect::>(); + let mut changed = false; + for index in 0..entries.len() { + if level[index] + 1 >= entries[index].candidates.len() { + continue; + } + // A file's own variable keeps its name against a library's: the + // library variable is the one qualified, so linking a library + // never renames tokens the project already uses. + if (0..entries.len()).any(|other| { + other != index + && names[other] == names[index] + && meets(index, other) + && (entries[index].remote || !entries[other].remote) + }) { + level[index] += 1; + changed = true; + } + } + if !changed { + break; + } + } + // Two variables with the same collection and path — a local copy of a + // library variable, say — are still two variables. Number them, in id + // order, so neither of them shares a name. + let mut names = (0..entries.len()) + .map(|index| name_of(index, &level)) + .collect::>(); + for index in 0..entries.len() { + let clashes = |name: &str, names: &[String]| { + (0..index).any(|other| names[other] == name && meets(index, other)) + }; + if !clashes(&names[index], &names) { + continue; + } + let base = names[index].clone(); + let mut counter = 2; + while clashes(&format!("{base}{counter}"), &names) { + counter += 1; + } + names[index] = format!("{base}{counter}"); + } + entries + .iter() + .zip(names) + .map(|(entry, name)| (entry.variable.id.clone(), name)) + .collect() +} + +/// The name a variable has before it is compared with any other. +fn base_variable_token(variable: &VariableDefinition) -> String { + let web = variable.code_syntax.get("WEB").map(String::as_str); + let token = variable_token(&variable.name, web); + let explicit = web.is_some_and(|syntax| !syntax.trim().is_empty()); + if !explicit && token.starts_with('_') && variable.name.contains('/') { + normalize_token(&variable.name) + } else { + token + } +} + +/// The themes a collection's modes can be written under. Light and the +/// unnamed default are one bucket: a lone `Mode 1` is written under `light` +/// when another collection has one. +fn theme_buckets(collection: &VariableCollection) -> BTreeSet { + let mut buckets = collection + .modes + .iter() + .map(|mode| { + let meaning = mode_meaning(&mode.name); + let single_default = collection.modes.len() == 1 + && matches!( + meaning.to_ascii_lowercase().as_str(), + "mode1" | "value" | "default" + ); + if single_default || meaning == "light" { + "default".to_owned() + } else { + meaning + } + }) + .collect::>(); + if buckets.is_empty() { + buckets.insert("default".to_owned()); + } + buckets +} + +#[cfg(test)] +mod token_name_tests { + use super::*; + + fn variable(id: &str, name: &str, collection: &str, kind: &str) -> VariableDefinition { + VariableDefinition { + id: id.into(), + name: name.into(), + resolved_type: kind.into(), + variable_collection_id: collection.into(), + code_syntax: BTreeMap::new(), + values_by_mode: BTreeMap::new(), + } + } + + fn collection(id: &str, name: &str, modes: &[&str]) -> VariableCollection { + VariableCollection { + id: id.into(), + name: name.into(), + default_mode_id: format!("{id}:0"), + modes: modes + .iter() + .enumerate() + .map(|(index, mode)| VariableMode { + mode_id: format!("{id}:{index}"), + name: (*mode).into(), + }) + .collect(), + } + } + + fn snapshot( + collections: Vec, + variables: Vec, + ) -> VariableSnapshot { + VariableSnapshot { + collections, + variables, + styles: Vec::new(), + used_remote_variables: Vec::new(), + used_variable_ids: Vec::new(), + used_style_ids: Vec::new(), + local_complete: true, + used_remote_complete: true, + } + } + + #[test] + fn a_scale_step_keeps_its_group() { + let names = variable_token_names(&snapshot( + vec![collection("c", "Colors", &["Mode 1"])], + vec![ + variable("1", "gold/200", "c", "COLOR"), + variable("2", "line/200", "c", "COLOR"), + variable("3", "red/200", "c", "COLOR"), + variable("4", "ink/700", "c", "COLOR"), + variable("5", "green/700", "c", "COLOR"), + variable("6", "blue/50", "c", "COLOR"), + ], + )); + assert_eq!(names["1"], "gold200"); + assert_eq!(names["2"], "line200"); + assert_eq!(names["3"], "red200"); + assert_eq!(names["4"], "ink700"); + assert_eq!(names["5"], "green700"); + assert_eq!(names["6"], "blue50"); + } + + #[test] + fn a_unique_leaf_stays_short_and_a_shared_one_takes_its_path() { + let names = variable_token_names(&snapshot( + vec![collection("c", "Colors", &["Light", "Dark"])], + vec![ + variable("1", "text/primary", "c", "COLOR"), + variable("2", "button/default", "c", "COLOR"), + variable("3", "card/default", "c", "COLOR"), + ], + )); + assert_eq!(names["1"], "primary"); + assert_eq!(names["2"], "buttonDefault"); + assert_eq!(names["3"], "cardDefault"); + } + + #[test] + fn same_path_in_two_collections_takes_the_collection_and_kinds_do_not_meet() { + let names = variable_token_names(&snapshot( + vec![ + collection("a", "Brand", &["Mode 1"]), + collection("b", "Product", &["Mode 1"]), + ], + vec![ + variable("1", "accent", "a", "COLOR"), + variable("2", "accent", "b", "COLOR"), + variable("3", "gap", "a", "FLOAT"), + variable("4", "gap", "b", "COLOR"), + ], + )); + assert_eq!(names["1"], "brandAccent"); + assert_eq!(names["2"], "productAccent"); + assert_eq!(names["3"], "gap"); + assert_eq!(names["4"], "gap"); + } + + #[test] + fn identical_path_and_collection_are_numbered() { + let mut snapshot = snapshot( + vec![collection("c", "Colors", &["Mode 1"])], + vec![variable("1", "primary", "c", "COLOR")], + ); + snapshot + .used_remote_variables + .push(variable("2", "primary", "c", "COLOR")); + let names = variable_token_names(&snapshot); + assert_eq!(names["1"], "primary"); + assert_ne!(names["1"], names["2"]); + } + + #[test] + fn a_local_variable_keeps_its_name_against_a_library_one() { + let mut snapshot = snapshot( + vec![ + collection("site", "Site", &["Light", "Dark"]), + collection("lib", "Library", &["Light", "Dark"]), + ], + vec![variable("1", "background", "site", "COLOR")], + ); + snapshot + .used_remote_variables + .push(variable("2", "background", "lib", "COLOR")); + let names = variable_token_names(&snapshot); + assert_eq!(names["1"], "background"); + assert_eq!(names["2"], "libraryBackground"); + } + + #[test] + fn collections_whose_themes_never_meet_keep_the_short_name() { + let names = variable_token_names(&snapshot( + vec![ + collection("a", "Light", &["Light"]), + collection("b", "Dark", &["Dark"]), + ], + vec![ + variable("1", "primary", "a", "COLOR"), + variable("2", "primary", "b", "COLOR"), + ], + )); + assert_eq!(names["1"], "primary"); + assert_eq!(names["2"], "primary"); + } +} diff --git a/crates/devup-mcp-devup-ui/src/theme/mod.rs b/crates/devup-mcp-devup-ui/src/theme/mod.rs index 43468659..b9da9993 100644 --- a/crates/devup-mcp-devup-ui/src/theme/mod.rs +++ b/crates/devup-mcp-devup-ui/src/theme/mod.rs @@ -10,7 +10,7 @@ pub use devup_json::{ Completeness, ThemeConflict, ThemeConflictCandidate, ThemeCounts, ThemeOutput, ThemeScope, ThemeSkippedStyle, ThemeUnresolvedVariable, ThemeVariableSource, VariableCollection, VariableDefinition, VariableMode, VariableSnapshot, VariableStyle, generate_devup_json, - variable_snapshot_from_result, + variable_snapshot_from_result, variable_token_names, }; pub use project_theme::{ ProjectTheme, TokenCategory, TokenEntry, closest_tokens, edit_distance, normalize_identifier, diff --git a/crates/devup-mcp-devup-ui/src/theme/usage.rs b/crates/devup-mcp-devup-ui/src/theme/usage.rs index 07486a90..43889bd1 100644 --- a/crates/devup-mcp-devup-ui/src/theme/usage.rs +++ b/crates/devup-mcp-devup-ui/src/theme/usage.rs @@ -101,13 +101,13 @@ pub fn generate_used_devup_json( .iter() .chain(&snapshot.used_remote_variables) .collect::>(); + let names = super::variable_token_names(snapshot); let mut ids = variables .iter() .filter(|variable| { - usage.tokens.contains(&super::tokens::variable_token( - &variable.name, - variable.code_syntax.get("WEB").map(String::as_str), - )) + names + .get(&variable.id) + .is_some_and(|name| usage.tokens.contains(name)) }) .map(|variable| variable.id.clone()) .collect::>(); @@ -150,7 +150,8 @@ pub fn generate_used_devup_json( .used_remote_variables .retain(|variable| ids.contains(&variable.id)); selected.used_variable_ids = ids.into_iter().collect(); - let mut output = super::generate_devup_json(&selected, ThemeScope::File)?; + let mut output = + super::devup_json::generate_devup_json_named(&selected, ThemeScope::File, &names)?; restrict_devup_json(&mut output, usage)?; Ok(output) } diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/token_bindings.rs b/crates/devup-mcp-devup-ui/src/ui_validate/token_bindings.rs new file mode 100644 index 00000000..bd51f5bd --- /dev/null +++ b/crates/devup-mcp-devup-ui/src/ui_validate/token_bindings.rs @@ -0,0 +1,213 @@ +//! `token-binding-mismatch`: a `$token` in the code that is not the token of +//! the Figma variable the attribute was generated from. +//! +//! `unknown-token` proves a token exists; it cannot prove it is the right +//! one. A theme in which `gold200`, `line200` and `red200` all exist accepts +//! every one of them on a card border that Figma binds to `line/200`, and a +//! script or a person who swaps one for another — the failure that turned a +//! grey border yellow — passes every other check. The export's source map +//! knows, for each element and attribute, which variable the node bound and +//! which token that variable was written as; this check holds the code to it. +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; + +use super::{Severity, Violation}; +use crate::provenance::attributes::generated_attributes; + +pub const RULE: &str = "token-binding-mismatch"; + +/// One source-map fact: the element and attribute an export generated from +/// a Figma node whose `property` was bound to `variable_id`. +#[derive(Debug, Clone, Default)] +pub struct TokenBinding { + pub element_index: usize, + pub node_id: Option, + pub property: Option, + /// The generated attribute as the export wrote it, e.g. `bg="$line200"`. + pub generated_property: String, + pub variable_id: String, +} + +/// The `$token`s named in an attribute value. +fn tokens_in(text: &str) -> BTreeSet { + text.split('$') + .skip(1) + .map(|tail| { + tail.chars() + .take_while(|c| c.is_alphanumeric() || matches!(c, '_' | '-')) + .collect::() + }) + .filter(|token| !token.is_empty()) + .collect() +} + +fn attribute_name(generated: &str) -> Option<&str> { + let name = generated.split('=').next()?.trim(); + (!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | ':'))) + .then_some(name) +} + +/// Every attribute in `tsx` whose `$token` differs from the token the export +/// wrote there for the variable the Figma node binds. An attribute the code +/// no longer has, or one that carries no token, is not judged: the first is +/// a restructured element, the second a `hardcoded-*` finding. +pub fn token_binding_findings(tsx: &str, bindings: &[TokenBinding]) -> Vec { + // (element, attribute) -> expected tokens, with the evidence for each. + let mut expected = BTreeMap::<(usize, String), Vec<(&TokenBinding, BTreeSet)>>::new(); + for binding in bindings { + let Some(name) = attribute_name(&binding.generated_property) else { + continue; + }; + let tokens = tokens_in(&binding.generated_property); + if tokens.is_empty() { + continue; + } + expected + .entry((binding.element_index, name.to_owned())) + .or_default() + .push((binding, tokens)); + } + if expected.is_empty() { + return Vec::new(); + } + let mut findings = Vec::new(); + for attribute in generated_attributes(tsx) { + let Some(bound) = expected.get(&(attribute.element, attribute.name.clone())) else { + continue; + }; + let value = attribute + .source + .split_once('=') + .map_or("", |(_, value)| value); + let written = tokens_in(value); + if written.is_empty() { + continue; + } + let allowed = bound + .iter() + .flat_map(|(_, tokens)| tokens.iter().cloned()) + .collect::>(); + let wrong = written.difference(&allowed).cloned().collect::>(); + if wrong.is_empty() { + continue; + } + let mut context = serde_json::Map::new(); + context.insert("elementIndex".into(), json!(attribute.element)); + context.insert("attribute".into(), json!(attribute.name)); + context.insert("tag".into(), json!(attribute.tag)); + context.insert("writtenTokens".into(), json!(written)); + context.insert("expectedTokens".into(), json!(allowed)); + context.insert( + "figmaBindings".into(), + json!( + bound + .iter() + .map(|(binding, tokens)| json!({ + "nodeId": binding.node_id, + "property": binding.property, + "variableId": binding.variable_id, + "tokens": tokens, + })) + .collect::>() + ), + ); + findings.push(Violation { + rule: RULE, + severity: Severity::Error, + byte_range: [attribute.start, attribute.end], + context, + message: format!( + "`{}` uses ${} but the Figma node binds {} here, which the export wrote as ${}.", + attribute.name, + wrong.join(", $"), + bound + .iter() + .map(|(binding, _)| binding.variable_id.as_str()) + .collect::>() + .into_iter() + .collect::>() + .join(", "), + allowed.iter().cloned().collect::>().join(", $"), + ), + suggestion: Some(format!( + "Use ${} as exported, or bind a different variable in Figma and export again.", + allowed.iter().cloned().collect::>().join(", $") + )), + }); + } + findings +} + +#[cfg(test)] +mod token_binding_tests { + use super::*; + + fn binding(element: usize, generated: &str, variable: &str) -> TokenBinding { + TokenBinding { + element_index: element, + node_id: Some(format!("1:{element}")), + property: Some("strokes".into()), + generated_property: generated.into(), + variable_id: variable.into(), + } + } + + const TSX: &str = r#"export function Card() { + return ( + + + + + ); +}"#; + + #[test] + fn a_swapped_token_is_an_error_naming_the_binding() { + let findings = token_binding_findings( + &TSX.replace("$line200", "$gold200"), + &[ + binding(0, r#"border="1px solid $line200""#, "VariableID:15:22"), + binding(1, r#"bg="$green700""#, "VariableID:15:30"), + binding(2, r#"bg="$ink700""#, "VariableID:15:31"), + ], + ); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!(findings[0].severity, Severity::Error); + assert_eq!(findings[0].context["elementIndex"], 0); + assert_eq!(findings[0].context["writtenTokens"], json!(["gold200"])); + assert_eq!(findings[0].context["expectedTokens"], json!(["line200"])); + assert_eq!( + findings[0].context["figmaBindings"][0]["variableId"], + "VariableID:15:22" + ); + } + + #[test] + fn the_exported_tokens_and_unmapped_attributes_pass() { + let bindings = [ + binding(0, r#"border="1px solid $line200""#, "VariableID:15:22"), + binding(1, r#"bg="$green700""#, "VariableID:15:30"), + ]; + assert!(token_binding_findings(TSX, &bindings).is_empty()); + // Element 2 has no binding in the map: not judged. + assert!(token_binding_findings(&TSX.replace("$ink700", "$red200"), &bindings).is_empty()); + // A hardcoded value is another rule's finding. + assert!(token_binding_findings(&TSX.replace("$green700", "#00ff00"), &bindings).is_empty()); + } + + #[test] + fn a_child_binding_swapped_into_its_parent_is_caught() { + // The button binds green/700; its label child binds ink/700. Code + // that gives the button the child's colour is wrong. + let findings = token_binding_findings( + &TSX.replace(r#""#, r#""#), + &[ + binding(1, r#"bg="$green700""#, "VariableID:15:30"), + binding(2, r#"bg="$ink700""#, "VariableID:15:31"), + ], + ); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].context["elementIndex"], 1); + } +} diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/types_and_helpers.rs b/crates/devup-mcp-devup-ui/src/ui_validate/types_and_helpers.rs index eab422bb..7b28c78e 100644 --- a/crates/devup-mcp-devup-ui/src/ui_validate/types_and_helpers.rs +++ b/crates/devup-mcp-devup-ui/src/ui_validate/types_and_helpers.rs @@ -6,6 +6,8 @@ mod blur_layers; pub mod site; #[path = "wiring.rs"] pub mod wiring; +#[path = "token_bindings.rs"] +pub mod token_bindings; #[path = "visual_behavior.rs"] pub mod visual_behavior; #[path = "delivery_quality.rs"] diff --git a/crates/devup-mcp-devup-ui/tests/color_token_collisions.rs b/crates/devup-mcp-devup-ui/tests/color_token_collisions.rs new file mode 100644 index 00000000..88933c11 --- /dev/null +++ b/crates/devup-mcp-devup-ui/tests/color_token_collisions.rs @@ -0,0 +1,304 @@ +//! A catalog whose colour groups share numeric steps — `gold/200`, +//! `line/200`, `red/200`, `ink/700`, `green/700` — used to collapse to `_200` +//! and `_700`: one token for several colours in the code, one value for it +//! in `devup.json`, and source-map entries naming variables the node never +//! bound. The export has to be committable as it comes: every token unique, +//! the theme and the code agreeing on each one, and every variable mapping +//! proven by the node's own binding — including a button instance whose +//! label binds a different variable from the button itself. + +use std::collections::{BTreeMap, BTreeSet}; + +use devup_mcp_devup_ui::codegen::{CodegenOptions, generate_component}; +use devup_mcp_devup_ui::theme::{ + ThemeScope, generate_devup_json, variable_snapshot_from_result, variable_token_names, +}; +use devup_mcp_devup_ui::ui_validate::token_bindings::{TokenBinding, token_binding_findings}; +use devup_mcp_figma::{Snapshot, SnapshotChunk, UpstreamResult, merge_chunks}; +use serde_json::{Value, json}; + +fn rgb(r: f64, g: f64, b: f64) -> Value { + json!({"r": r, "g": g, "b": b, "a": 1}) +} + +fn variables() -> UpstreamResult { + let color = |id: &str, name: &str, value: Value| { + json!({"id": id, "name": name, "resolvedType": "COLOR", + "variableCollectionId": "c", "valuesByMode": {"m": value}}) + }; + UpstreamResult { + raw: json!({ + "collections": [ + {"id": "c", "name": "Colors", "defaultModeId": "m", + "modes": [{"modeId": "m", "name": "Mode 1"}]} + ], + "variables": [ + color("VariableID:15:14", "red/200", rgb(1.0, 0.8, 0.8)), + color("VariableID:15:18", "gold/200", rgb(1.0, 0.9, 0.5)), + color("VariableID:15:22", "line/200", rgb(0.9, 0.9, 0.9)), + color("VariableID:15:30", "green/700", rgb(0.1, 0.5, 0.2)), + color("VariableID:15:31", "ink/700", rgb(0.2, 0.2, 0.2)), + color("VariableID:15:40", "green/50", rgb(0.9, 1.0, 0.9)), + color("VariableID:15:41", "gold/50", rgb(1.0, 1.0, 0.9)) + ], + "styles": [], + "usedVariableIds": ["VariableID:15:22", "VariableID:15:30", "VariableID:15:31", "VariableID:15:18"], + "usedRemoteVariables": [], + "localComplete": true, + "usedRemoteComplete": true + }), + } +} + +fn paint(id: &str, color: Value) -> Value { + json!([{"type": "SOLID", "visible": true, "color": color, + "boundVariables": {"color": {"type": "VARIABLE_ALIAS", "id": id}}}]) +} + +fn snapshot() -> Snapshot { + let node = |id: &str, kind: &str, fields: Value| json!({"id": id, "type": kind, "extra": {}, "fieldErrors": {}, "fields": fields}); + let chunk: SnapshotChunk = serde_json::from_value(json!({ + "fileKey": "file-key", + "version": "1", + "rootIds": ["15:399"], + "nodes": [ + node("15:399", "FRAME", json!({ + "name": "Card", "childrenIds": ["15:400", "15:410", "15:420"], + "layoutMode": "VERTICAL", "itemSpacing": 12, + "layoutSizingHorizontal": "FIXED", "layoutSizingVertical": "HUG", + "width": 320, "height": 160, "strokeWeight": 1, "strokeAlign": "INSIDE", + "fills": [], + "strokes": paint("VariableID:15:22", rgb(0.9, 0.9, 0.9)) + })), + // A notice: gold/200, and nothing else in the card is gold. + node("15:400", "FRAME", json!({ + "name": "Notice", "parentId": "15:399", "childrenIds": [], + "layoutMode": "HORIZONTAL", + "layoutSizingHorizontal": "FILL", "layoutSizingVertical": "FIXED", + "width": 320, "height": 40, + "fills": paint("VariableID:15:18", rgb(1.0, 0.9, 0.5)) + })), + // A button instance painted green/700 whose label is ink/700. + node("15:410", "INSTANCE", json!({ + "name": "Button", "parentId": "15:399", "childrenIds": ["15:411"], + "layoutMode": "HORIZONTAL", "paddingLeft": 16, "paddingRight": 16, + "paddingTop": 8, "paddingBottom": 8, + "layoutSizingHorizontal": "HUG", "layoutSizingVertical": "HUG", + "width": 100, "height": 40, + "fills": paint("VariableID:15:30", rgb(0.1, 0.5, 0.2)) + })), + node("15:411", "TEXT", json!({ + "name": "Label", "parentId": "15:410", "childrenIds": [], + "characters": "Apply", "textAutoResize": "WIDTH_AND_HEIGHT", + "layoutSizingHorizontal": "HUG", "layoutSizingVertical": "HUG", + "width": 68, "height": 24, + "fills": paint("VariableID:15:31", rgb(0.2, 0.2, 0.2)), + "styledTextSegments": [{ + "characters": "Apply", + "fontName": {"family": "Pretendard", "style": "Bold"}, + "fontSize": 16, "fontWeight": 700, + "lineHeight": {"unit": "PIXELS", "value": 24}, + "fills": paint("VariableID:15:31", rgb(0.2, 0.2, 0.2)) + }] + })), + // An icon beside a label in a row that fits as drawn. + node("15:420", "FRAME", json!({ + "name": "Row", "parentId": "15:399", "childrenIds": ["15:421", "15:422"], + "layoutMode": "HORIZONTAL", "itemSpacing": 8, + "layoutSizingHorizontal": "FILL", "layoutSizingVertical": "HUG", + "width": 320, "height": 24, "fills": [] + })), + node("15:421", "VECTOR", json!({ + "name": "Icon", "parentId": "15:420", "childrenIds": [], + "layoutSizingHorizontal": "FIXED", "layoutSizingVertical": "FIXED", + "width": 24, "height": 24, + "fills": paint("VariableID:15:30", rgb(0.1, 0.5, 0.2)) + })), + node("15:422", "TEXT", json!({ + "name": "Caption", "parentId": "15:420", "childrenIds": [], + "characters": "Short label", "textAutoResize": "HEIGHT", + "layoutSizingHorizontal": "FILL", "layoutSizingVertical": "HUG", + "width": 288, "height": 20, + "fills": paint("VariableID:15:31", rgb(0.2, 0.2, 0.2)), + "styledTextSegments": [{ + "characters": "Short label", + "fontName": {"family": "Pretendard", "style": "Regular"}, + "fontSize": 14, "fontWeight": 400, + "lineHeight": {"unit": "PIXELS", "value": 20}, + "fills": paint("VariableID:15:31", rgb(0.2, 0.2, 0.2)) + }] + })) + ], + "diagnostics": [] + })) + .expect("synthetic snapshot"); + merge_chunks(vec![chunk]).expect("snapshot") +} + +fn options() -> CodegenOptions { + CodegenOptions { + include_diagnostics: true, + inline_instances: true, + ..CodegenOptions::default() + } + .with_resource_results(Some(&variables()), None) +} + +#[test] +fn colour_groups_sharing_a_step_get_unique_names_in_theme_and_code() { + let catalog = variable_snapshot_from_result(&variables()).expect("catalog"); + let names = variable_token_names(&catalog); + assert_eq!(names["VariableID:15:14"], "red200"); + assert_eq!(names["VariableID:15:18"], "gold200"); + assert_eq!(names["VariableID:15:22"], "line200"); + assert_eq!(names["VariableID:15:30"], "green700"); + assert_eq!(names["VariableID:15:31"], "ink700"); + assert_eq!(names["VariableID:15:40"], "green50"); + assert_eq!(names["VariableID:15:41"], "gold50"); + + for scope in [ThemeScope::File, ThemeScope::Node] { + let theme = generate_devup_json(&catalog, scope).expect("theme"); + assert!(theme.conflicts.is_empty(), "{:?}", theme.conflicts); + let json: Value = serde_json::from_str(&theme.json).expect("devup.json"); + let colors = json["theme"]["colors"] + .as_object() + .and_then(|themes| themes.values().next()) + .and_then(Value::as_object) + .expect("one colour theme"); + assert!( + colors.keys().all(|token| !token.starts_with('_')), + "{colors:?}" + ); + // One name, one variable id. + let mut by_token = BTreeMap::>::new(); + for entry in &theme.source_map.entries { + if let (Some(pointer), Some(id)) = (&entry.json_pointer, &entry.variable_id) { + by_token + .entry(pointer.rsplit('/').next().unwrap().to_owned()) + .or_default() + .insert(id.clone()); + } + } + assert!(!by_token.is_empty()); + assert!(by_token.values().all(|ids| ids.len() == 1), "{by_token:?}"); + } + + let output = generate_component(&snapshot(), "15:399", &options()).expect("codegen"); + assert!(output.tsx.contains("$line200"), "{}", output.tsx); + assert!(output.tsx.contains("$gold200"), "{}", output.tsx); + assert!(output.tsx.contains("$green700"), "{}", output.tsx); + assert!(output.tsx.contains("$ink700"), "{}", output.tsx); + assert!(!output.tsx.contains("$_"), "{}", output.tsx); + assert!(!output.tsx.contains("$red200"), "{}", output.tsx); +} + +#[test] +fn every_source_map_variable_is_the_one_the_node_binds() { + let snapshot = snapshot(); + let output = generate_component(&snapshot, "15:399", &options()).expect("codegen"); + let bound = |node_id: &str| -> BTreeSet { + fn scan(value: &Value, ids: &mut BTreeSet) { + match value { + Value::Object(object) => { + if object.get("type").and_then(Value::as_str) == Some("VARIABLE_ALIAS") + && let Some(id) = object.get("id").and_then(Value::as_str) + { + ids.insert(id.to_owned()); + } + object.values().for_each(|value| scan(value, ids)); + } + Value::Array(values) => values.iter().for_each(|value| scan(value, ids)), + _ => {} + } + } + let mut ids = BTreeSet::new(); + for value in snapshot.nodes[node_id].fields.values() { + scan(value, &mut ids); + } + ids + }; + let mapped = output + .source_map + .entries + .iter() + .filter_map(|entry| Some((entry.node_id.clone()?, entry.variable_id.clone()?))) + .collect::>(); + assert!(!mapped.is_empty()); + for (node_id, variable_id) in &mapped { + assert!( + bound(node_id).contains(variable_id), + "{node_id} does not bind {variable_id}: {mapped:?}" + ); + } + // The card's own stroke is line/200, and only line/200. + let card_stroke = mapped + .iter() + .filter(|(node_id, _)| node_id == "15:399") + .map(|(_, id)| id.as_str()) + .collect::>(); + assert_eq!(card_stroke, BTreeSet::from(["VariableID:15:22"])); + // The button keeps green/700; its label's ink/700 is the label's. + let button = mapped + .iter() + .filter(|(node_id, _)| node_id == "15:410") + .map(|(_, id)| id.as_str()) + .collect::>(); + assert_eq!(button, BTreeSet::from(["VariableID:15:30"])); + assert!(mapped.contains(&("15:411".into(), "VariableID:15:31".into()))); + assert_eq!(output.fidelity_report.unverified_variable_entries, 0); + assert!( + output.fidelity_report.variables.complete(), + "{:?}", + output.fidelity_report.variables + ); +} + +#[test] +fn a_fixed_icon_in_a_row_never_shrinks() { + let output = generate_component(&snapshot(), "15:399", &options()).expect("codegen"); + let start = output + .tsx + .find("boxSize=\"24px\"") + .unwrap_or_else(|| panic!("icon: {}", output.tsx)); + let open = output.tsx[..start].rfind('<').expect("icon opening"); + let close = start + output.tsx[start..].find('>').expect("icon end"); + let icon = &output.tsx[open..close]; + assert!(icon.contains("flexShrink=\"0\""), "{}", output.tsx); + // The label beside it may shrink; only the fixed asset is held. + let label = &output.tsx[close..]; + let label = &label[..label.find("Short label").expect("label")]; + assert!(!label.contains("flexShrink"), "{}", output.tsx); +} + +#[test] +fn a_token_swapped_after_export_is_a_validation_error() { + let output = generate_component(&snapshot(), "15:399", &options()).expect("codegen"); + let bindings = output + .source_map + .entries + .iter() + .filter(|entry| entry.resolution == "variable-token") + .filter_map(|entry| { + Some(TokenBinding { + element_index: entry.element_index?, + node_id: entry.node_id.clone(), + property: entry.property.clone(), + generated_property: entry.generated_property.clone()?, + variable_id: entry.variable_id.clone()?, + }) + }) + .collect::>(); + assert!(!bindings.is_empty()); + assert!(token_binding_findings(&output.tsx, &bindings).is_empty()); + // The post-processing that turned a grey border yellow. + let swapped = output.tsx.replacen("$line200", "$gold200", 1); + let findings = token_binding_findings(&swapped, &bindings); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!( + findings[0].context["figmaBindings"][0]["variableId"], + "VariableID:15:22" + ); + // And the one that turned a green button grey. + let swapped = output.tsx.replacen("$green700", "$ink700", 1); + assert_eq!(token_binding_findings(&swapped, &bindings).len(), 1); +} diff --git a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_devup_ui.snap b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_devup_ui.snap index 0c93ee87..1ce1e55b 100644 --- a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_devup_ui.snap +++ b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_devup_ui.snap @@ -65,7 +65,13 @@ export function AStoryFProofread() { > 담담체 - write + write
@@ -99,6 +105,7 @@ export function AStoryFProofread() { aspectRatio="1" bg="$caption" boxSize="16px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -208,6 +215,7 @@ export function AStoryFProofread() { aspectRatio="1" bg="$text" boxSize="20px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -241,7 +249,13 @@ export function AStoryFProofread() { 제목 - write + write - write + write - write + write - write + write - write + write 담담체 - write + write
@@ -93,6 +99,7 @@ export function AStoryFProofread() { aspectRatio="1" bg="$caption" boxSize="16px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -202,6 +209,7 @@ export function AStoryFProofread() { aspectRatio="1" bg="$text" boxSize="20px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -235,7 +243,13 @@ export function AStoryFProofread() { 제목 - write + write - write + write - write + write - write + write - write + write \n \n " + " \n \n " ], "fallback": null, "heightPreservation": { @@ -1137,6 +1137,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "3879:35525", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 20, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "3879:35522", + "width": 20 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "3879:35522" + }, + "elementIndex": 8, + "propertyMappingVerified": true, + "assetId": "3879:35525:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -1285,6 +1322,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "3879:35530", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "3879:35527", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "3879:35527" + }, + "elementIndex": 13, + "propertyMappingVerified": true, + "assetId": "3879:35530:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -1927,6 +2001,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "3879:35541", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 20, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "3879:35540", + "width": 20 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "3879:35540" + }, + "elementIndex": 28, + "propertyMappingVerified": true, + "assetId": "3879:35541:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -2178,6 +2289,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "I3879:35545;1690:32934", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "I3879:35545;1690:32948", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "I3879:35545;1690:32948" + }, + "elementIndex": 34, + "propertyMappingVerified": true, + "assetId": "I3879:35545;1690:32934:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -2458,6 +2606,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "I3879:35549;1690:32934", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "I3879:35549;1690:32948", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "I3879:35549;1690:32948" + }, + "elementIndex": 42, + "propertyMappingVerified": true, + "assetId": "I3879:35549;1690:32934:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -2738,6 +2923,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "I3879:35553;1690:32934", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "I3879:35553;1690:32948", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "I3879:35553;1690:32948" + }, + "elementIndex": 52, + "propertyMappingVerified": true, + "assetId": "I3879:35553;1690:32934:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -3206,6 +3428,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "I3879:35557;1690:32934", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "I3879:35557;1690:32948", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "I3879:35557;1690:32948" + }, + "elementIndex": 70, + "propertyMappingVerified": true, + "assetId": "I3879:35557;1690:32934:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", @@ -3486,6 +3745,43 @@ expression: diagnostics "evidenceLimit": "No browser or SVG/CSS composition measurement." } }, + { + "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", + "message": "Source derivation verified.", + "nodeId": "I3879:35561;1690:32934", + "severity": "info", + "fidelityImpact": "none", + "property": "flexShrink", + "details": { + "stage": "layout", + "generatedProperty": "flexShrink=\"0\"", + "sourceFields": [ + "layoutSizingHorizontal", + "layoutSizingVertical", + "layoutGrow", + "parentId", + "width", + "height" + ], + "originalValue": { + "height": 16, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "parentId": "I3879:35561;1690:32948", + "width": 16 + }, + "calculation": "push_layout_props: preserve the fixed primary-axis size in the parent flex layout by disabling shrink.", + "context": { + "rootLayout": "standalone", + "isRenderRoot": false, + "parentNodeId": "I3879:35561;1690:32948" + }, + "elementIndex": 86, + "propertyMappingVerified": true, + "assetId": "I3879:35561;1690:32934:node", + "evidenceLimit": "No browser or SVG/CSS composition measurement." + } + }, { "code": "DEVUP_CODEGEN_PROPERTY_EVIDENCE", "message": "Source derivation verified.", diff --git a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_source_map.snap b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_source_map.snap index fc336210..91ef3516 100644 --- a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_source_map.snap +++ b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151__wquw_151_proofread_source_map.snap @@ -873,8 +873,7 @@ expression: output.source_map "generatedProperty": "bg=\"$caption\"", "nodeId": "3879:35530", "property": "fills", - "variableId": "VariableID:1:1009", - "resolution": "variable-token", + "resolution": "raw-fallback", "elementIndex": 13 }, { @@ -1039,8 +1038,7 @@ expression: output.source_map "generatedProperty": "bg=\"$captionLight\"", "nodeId": "3879:35534", "property": "fills", - "variableId": "VariableID:63:2093", - "resolution": "variable-token", + "resolution": "raw-fallback", "elementIndex": 16 }, { @@ -1669,8 +1667,7 @@ expression: output.source_map "generatedProperty": "bg=\"$text\"", "nodeId": "3879:35541", "property": "fills", - "variableId": "VariableID:1:998", - "resolution": "variable-token", + "resolution": "raw-fallback", "elementIndex": 28 }, { diff --git a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_35503.snap b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_35503.snap index 8295a324..7c70e339 100644 --- a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_35503.snap +++ b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_35503.snap @@ -24,6 +24,7 @@ export function Wquw151Frame387935503() { 담담체 - write + write
@@ -101,6 +107,7 @@ export function Wquw151Frame387935518() { aspectRatio="1" bg="$caption" boxSize="16px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -216,6 +223,7 @@ export function Wquw151Frame387935518() { aspectRatio="1" bg="$text" boxSize="20px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -249,7 +257,13 @@ export function Wquw151Frame387935518() { 제목 - write + write - write + write - write + write - write + write - write + write 담담체 - write + write
- write + write - write + write - write + write - write + write - write + write 담담체 - write + write - write + write - write + write - write + write - write + write - write + write 담담체 - write + write - write + write - write + write - write + write - write + write - write + write 담담체 - write + write - write + write - write + write - write + write - write + write - write + write 담담체 - write + write - write + write - write + write - write + write - write + write - write + write @@ -174,6 +178,7 @@ export function Wquw151Frame387936059() { aspectRatio="1" boxShadow="0 4px 32px 0 #46608740" boxSize="80px" + flexShrink="0" src="/icons/a-story-f-record-recording-image.svg" /> @@ -196,6 +201,7 @@ export function Wquw151Frame387936059() { aspectRatio="1" boxShadow="0 4px 32px 0 #46608740" boxSize="60px" + flexShrink="0" src="/icons/a-story-f-record-recording-image.svg" /> diff --git a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36108.snap b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36108.snap index d62a5eb4..fb3286bd 100644 --- a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36108.snap +++ b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36108.snap @@ -21,6 +21,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" bg="$caption" boxSize="32px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -34,6 +35,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" bg="$captionLight" boxSize="20px" + flexShrink="0" maskImage="url(/icons/arrow-7134700-1.svg)" maskPos="center" maskRepeat="no-repeat" @@ -90,6 +92,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" bg="$secondary" boxSize="16px" + flexShrink="0" maskImage="url(/icons/information-button-1176-1.svg)" maskPos="center" maskRepeat="no-repeat" @@ -146,6 +149,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" boxShadow="0 4px 32px 0 #46608740" boxSize="60px" + flexShrink="0" src="/icons/a-story-f-record-recording-image.svg" /> @@ -168,6 +172,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" boxShadow="0 4px 32px 0 #46608740" boxSize="80px" + flexShrink="0" src="/icons/a-story-f-record-recording-image.svg" /> @@ -190,6 +195,7 @@ export function Wquw151Frame387936108() { aspectRatio="1" boxShadow="0 4px 32px 0 #46608740" boxSize="60px" + flexShrink="0" src="/icons/a-story-f-record-recording-image.svg" /> diff --git a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36144.snap b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36144.snap index fcc06d8a..02ec9164 100644 --- a/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36144.snap +++ b/crates/devup-mcp-devup-ui/tests/snapshots/wquw_151_frames__wquw_151_frame_3879_36144.snap @@ -72,6 +72,7 @@ export function Wquw151Frame387936144() { aspectRatio="1" bg="$caption" boxSize="16px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -187,6 +188,7 @@ export function Wquw151Frame387936144() { aspectRatio="1" bg="$text" boxSize="20px" + flexShrink="0" maskImage="url(/icons/icons.svg)" maskPos="center" maskRepeat="no-repeat" @@ -220,7 +222,13 @@ export function Wquw151Frame387936144() { 제목 - write + write - write + write - write + write - write + write - write + write >(), - vec!["var:a", "var:z"] - ); - assert_eq!( - first.conflicts[0].candidates[0].collection_name, - "Foundation" - ); - assert_eq!(first.conflicts[0].candidates[0].raw_name, "Color/Primary"); - assert_eq!(first.conflicts[0].candidates[0].mode_id, "mode:default"); - assert_eq!( - first.conflicts[0].candidates[0].value_hash, - "db5d24235bf240470a890fbfe94cc1cc2a17489e1aa65c9ede395d8be4d0f71a" - ); - assert_eq!( - first.conflicts[0].candidates[1].value_hash, - "904aff52bad2d6d9406b096ad03367bbe25737d47d36eb06f74411bd126f72b9" + assert!( + first.json.contains("\"colorPrimary\": \"#ff0000\""), + "{}", + first.json ); assert!( - first - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "DEVUP_THEME_TOKEN_CONFLICT") + first.json.contains("\"legacyPrimary\": \"#0000ff\""), + "{}", + first.json ); + assert!(!first.json.contains("\"primary\""), "{}", first.json); + assert!(first.conflicts.is_empty(), "{:?}", first.conflicts); + assert_eq!(first.conflicts, reversed.conflicts); } fn conflicting_variables(reversed: bool) -> VariableSnapshot { diff --git a/crates/devup-mcp-devup-ui/tests/theme_modes.rs b/crates/devup-mcp-devup-ui/tests/theme_modes.rs index b846403d..6295be94 100644 --- a/crates/devup-mcp-devup-ui/tests/theme_modes.rs +++ b/crates/devup-mcp-devup-ui/tests/theme_modes.rs @@ -103,7 +103,10 @@ fn used_only_drops_unused_modes_and_missing_only_preserves_existing_values() { } #[test] -fn incompatible_same_meaning_tokens_report_conflict() { +fn incompatible_same_meaning_tokens_get_their_own_names() { + // A library's `background` used to overwrite or conflict with the file's + // own. The file's keeps the name; the library's is qualified by its + // collection, and each theme holds both colours. let mut snapshot = incident(); snapshot.used_variable_ids.push("sds-icon".into()); snapshot.used_remote_variables[0].name = "background".into(); @@ -111,11 +114,12 @@ fn incompatible_same_meaning_tokens_report_conflict() { .values_by_mode .insert("sd".into(), json!({"r":1,"g":0,"b":0})); let output = generate_devup_json(&snapshot, ThemeScope::File).unwrap(); - assert!( - output - .conflicts - .iter() - .any(|conflict| conflict.mode == "dark" && conflict.token == "background") + assert!(output.conflicts.is_empty(), "{:?}", output.conflicts); + let theme: Value = serde_json::from_str(&output.json).unwrap(); + assert_eq!(theme["theme"]["colors"]["dark"]["background"], "#000000"); + assert_eq!( + theme["theme"]["colors"]["dark"]["simpleDesignSystemBackground"], + "#ff0000" ); } diff --git a/crates/devup-mcp/src/server/handlers/devup_ui_validate.rs b/crates/devup-mcp/src/server/handlers/devup_ui_validate.rs index 87dfdee4..fe008700 100644 --- a/crates/devup-mcp/src/server/handlers/devup_ui_validate.rs +++ b/crates/devup-mcp/src/server/handlers/devup_ui_validate.rs @@ -207,6 +207,11 @@ impl DevupServer { // And with no theme the token check is skipped rather than passed, // which a bare `checkedTokens` cannot distinguish. use devup_mcp_devup_ui::ui_validate::Severity; + let mismatched = token_binding_violations(&input); + if !mismatched.is_empty() { + report.ok = false; + } + report.violations.extend(mismatched); relax_unbound_token_matches(&mut report.violations, &input); if input.strict { report.ok = report.violations.iter().all(|finding| { diff --git a/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs b/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs index bddeaccc..d199497c 100644 --- a/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs +++ b/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs @@ -160,6 +160,9 @@ fn attach_layout_and_source_links(result: &mut Value, input: &UiValidateInput) { if input.section_coverage.is_some() { rules.push(asset_guard::COVERAGE_RULE); } + if input.source_map.is_some() && input.files.is_none() { + rules.push(devup_mcp_devup_ui::ui_validate::token_bindings::RULE); + } if input.files.is_some() { rules.extend([ "file-placement", @@ -261,6 +264,35 @@ fn attach_layout_and_source_links(result: &mut Value, input: &UiValidateInput) { } } +/// `$token`s in the tsx that are not the token the export wrote for the +/// variable the Figma node binds there, joined to the supplied sourceMap on +/// elementIndex + attribute. Only variable-token entries are evidence; the +/// sourceMap describes one tsx, so a files bundle is not checked. +fn token_binding_violations( + input: &UiValidateInput, +) -> Vec { + use devup_mcp_devup_ui::ui_validate::token_bindings::{TokenBinding, token_binding_findings}; + let (Some(source_map), None) = (&input.source_map, &input.files) else { + return Vec::new(); + }; + let bindings = source_map + .entries + .iter() + .chain(&source_map.tsx) + .filter(|entry| entry.resolution.as_deref().is_none_or(|r| r == "variable-token")) + .filter_map(|entry| { + Some(TokenBinding { + element_index: entry.element_index?, + node_id: entry.node_id.clone(), + property: entry.property.clone(), + generated_property: entry.generated_property.clone()?, + variable_id: entry.variable_id.clone()?, + }) + }) + .collect::>(); + token_binding_findings(&input.tsx, &bindings) +} + /// A hardcoded value whose Figma node binds no variable is what the design /// says, so a token that only shares the value is a coincidence: the finding /// drops to info and offers no replacement. Runs before severities are diff --git a/crates/devup-mcp/src/server/projection/w1_regressions_r7_real_wquw118_layout_contracts_are_preserved.rs b/crates/devup-mcp/src/server/projection/w1_regressions_r7_real_wquw118_layout_contracts_are_preserved.rs index 6eb9c6e2..5e53b9e6 100644 --- a/crates/devup-mcp/src/server/projection/w1_regressions_r7_real_wquw118_layout_contracts_are_preserved.rs +++ b/crates/devup-mcp/src/server/projection/w1_regressions_r7_real_wquw118_layout_contracts_are_preserved.rs @@ -319,10 +319,14 @@ async fn r16_verdict_scope_identifies_remaining_asset_axes_without_diagnostics() #[tokio::test] async fn r16_complete_scope_and_mapping_semantics_survive_resource_delivery() { + // The real wquw-118 screen sits at the 1 MiB inline cap, which its + // verified provenance (one derivation per emitted attribute) passes; + // `Auto` is the delivery the cap's own error points callers to, and it + // must keep the same semantics as an explicit resource. for (delivery_mode, real_fill) in [ (DeliveryMode::Inline, false), (DeliveryMode::Resource, false), - (DeliveryMode::Inline, true), + (DeliveryMode::Auto, true), (DeliveryMode::Resource, true), ] { let data: CollectedPayload = if real_fill { diff --git a/crates/devup-mcp/src/server/tools.rs b/crates/devup-mcp/src/server/tools.rs index 9381088c..04434e71 100644 --- a/crates/devup-mcp/src/server/tools.rs +++ b/crates/devup-mcp/src/server/tools.rs @@ -425,8 +425,10 @@ pub struct UiValidateInput { pub strict: bool, /// The `sourceMap` devup_figma_export returned with this tsx. Violations /// are joined to its entries on `elementIndex`, naming the Figma node and - /// field the offending attribute was generated from. Not joined with - /// files, which number elements per file. + /// field the offending attribute was generated from, and a `$token` that + /// differs from the one exported for the variable the node binds is a + /// `token-binding-mismatch` error. Not joined with files, which number + /// elements per file. #[serde(default)] pub source_map: Option, /// The width in px the tsx was written for, used by `layoutRisks` where a diff --git a/crates/devup-mcp/tests/downstream_integration.rs b/crates/devup-mcp/tests/downstream_integration.rs index f4d058ce..cb43daf0 100644 --- a/crates/devup-mcp/tests/downstream_integration.rs +++ b/crates/devup-mcp/tests/downstream_integration.rs @@ -439,19 +439,22 @@ async fn converts_figma_variables_to_structured_devup_json() -> anyhow::Result<( ) .await?; - assert_eq!(result["status"], "partial"); + // Two variables declare the same WEB syntax with different colours. One + // name cannot hold both, so each gets its own instead of one winning. + assert_eq!(result["status"], "complete"); assert_eq!(result["quality"]["acquisition"], "complete"); assert_eq!(result["quality"]["projection"], "not-requested"); - assert_eq!(result["quality"]["theme"], "conflicted"); + assert_eq!(result["quality"]["theme"], "complete"); + let devup_json = result["devupJson"].as_str().unwrap(); + assert!(devup_json.contains("\"colorPrimary\""), "{devup_json}"); + assert!(devup_json.contains("\"colorPrimaryAlt\""), "{devup_json}"); + assert!(!devup_json.contains("\"primary\""), "{devup_json}"); + assert_eq!(result["completeness"], "used-tokens"); assert!( - result["devupJson"] - .as_str() - .unwrap() - .contains("\"primary\"") + result["conflicts"].as_array().is_none_or(Vec::is_empty), + "{}", + result["conflicts"] ); - assert_eq!(result["completeness"], "used-tokens"); - assert_eq!(result["conflicts"][0]["token"], "primary"); - assert_eq!(result["conflicts"][0]["winnerVariableId"], "v"); assert_eq!(result["unresolvedVariables"], json!([])); assert_eq!( std::fs::read_to_string(&output_path)?, diff --git a/fixtures/devup-figma-plugin/README.md b/fixtures/devup-figma-plugin/README.md index 332bdb2d..e696acb3 100644 --- a/fixtures/devup-figma-plugin/README.md +++ b/fixtures/devup-figma-plugin/README.md @@ -125,3 +125,12 @@ inventory are unchanged; only these seven snapshot checksums change. This is a browser line-balancing policy, not new pixel evidence for the pinned screens; a diff caused only by Figma breaking inside a Korean word is a documented policy difference. + +The fixed-asset shrink correction adds `flexShrink="0"` to 24 reviewed codegen +snapshots. Each changed element is an icon or image whose captured size on its +parent's auto-layout axis is FIXED; Figma never shrinks such a child, while CSS +shrinks it when a neighbouring label runs longer than the drawing. The review +checks that every other attribute value and text node is unchanged, allowing +formatter line wrapping. Only those snapshot checksums are synchronized; case +inputs, upstream source identity and test inventory are preserved. This is a +static layout correction, not a new browser pixel measurement. diff --git a/fixtures/devup-figma-plugin/manifest.json b/fixtures/devup-figma-plugin/manifest.json index 17dc3f5c..168072f9 100644 --- a/fixtures/devup-figma-plugin/manifest.json +++ b/fixtures/devup-figma-plugin/manifest.json @@ -1799,11 +1799,11 @@ }, { "path": "snapshots/codegen/upstream-codegen-164-33e4c6591c.snap", - "sha256": "b9b66439d24391371700a2ab4280e9edaff4657639607b5475d68ecd245f1edd" + "sha256": "fa56d8bbe319bed7d99809c5c051fc3b4610d6730e3e0a3a6ceedc10ea198210" }, { "path": "snapshots/codegen/upstream-codegen-165-501ee1df12.snap", - "sha256": "c75e81c1bb8880944ea3af6e732c3bf3cb1d65c57fc08f927ae3936e4bbadece" + "sha256": "cea3373fe6faa4e20a31097aea34b57b37bd95f39fed9426431ac623b7c44a9e" }, { "path": "snapshots/codegen/upstream-codegen-166-cda14f0b08.snap", @@ -1915,27 +1915,27 @@ }, { "path": "snapshots/codegen/upstream-codegen-193-bd488a5710.snap", - "sha256": "ff913f1e601b8bad6114a3ea95ae6f79459a5904fa6eaad3cf7784b4ae913979" + "sha256": "5606babe674a29cc51ff32f27ea0df28520ef88539f4b0d1f2b32d48de150aad" }, { "path": "snapshots/codegen/upstream-codegen-194-17922977f6.snap", - "sha256": "986188d03130c1c0515b2d0925fa374c5c67b7504ec4e23d07c741ce19705824" + "sha256": "354507562e4656457f60c153ab18cad3bee3ce2678fec1d791ca77d900277a95" }, { "path": "snapshots/codegen/upstream-codegen-195-1a6efe22a8.snap", - "sha256": "9e00d9af3e785eba11704a2e01c2ab8e361d0b492ccbe043881415d8f38d74dc" + "sha256": "b7993729b89605b1c463eb34d093d887ed02de3e8054768dde6d662d5755d9ea" }, { "path": "snapshots/codegen/upstream-codegen-196-d14f03afcd.snap", - "sha256": "5ade484c7e55951217a8959aade09f18e74c1a0c50e631f0524bd7e53cc5121e" + "sha256": "7399e969ab0c2f356244abfbc952d7d84e1265440b0e9a2eb97fd5b2b61afbf0" }, { "path": "snapshots/codegen/upstream-codegen-197-026402bf2e.snap", - "sha256": "359d83f6170ba3427403c44b536d2ab4906ef3ae5dbd23b5b7a363dbd039e212" + "sha256": "6a1c5533671418bbf57721199a4955db6bc1adccc8095118bfbc354e53135810" }, { "path": "snapshots/codegen/upstream-codegen-198-a9ea7ba9c3.snap", - "sha256": "6c564c6e0cd515a27ef4db4307757956feb30c6bf060cf38ec53c999e8a95512" + "sha256": "2e67e525fdedde27a9532b3ad6f280da92a353f735586f531e7762a69ef92b8d" }, { "path": "snapshots/codegen/upstream-codegen-199-829a5c949d.snap", @@ -1943,7 +1943,7 @@ }, { "path": "snapshots/codegen/upstream-codegen-200-3313d92719.snap", - "sha256": "9966e2f1cbf0146e1ad8f8945baa74d509ab72d7e5c14714c9d40e72efeb4bf4" + "sha256": "49fceee9e3c86714421f1a3c71e56aeec323649e0ce6e9b424ea84fe28773eee" }, { "path": "snapshots/codegen/upstream-codegen-201-8207a4008e.snap", @@ -1987,15 +1987,15 @@ }, { "path": "snapshots/codegen/upstream-codegen-211-2e15c55701.snap", - "sha256": "0ce5ab49c39576c61cc60242ccce7811a96928d920465d56a4dd7bbd5db5e1f0" + "sha256": "6afead02c1545503423cd73412f3bd2c7111e5d7a5ef2317a12815b638693de8" }, { "path": "snapshots/codegen/upstream-codegen-212-2a8f7b4a99.snap", - "sha256": "0bc18390879276f924e7a3836111e65f4835bc5eaa31c8430f5b5260dda9e443" + "sha256": "dc3b473a01f41213c2beda0e54b4fccd6c06bf6232eb3abb66e801cfce509bca" }, { "path": "snapshots/codegen/upstream-codegen-213-aa53408d2f.snap", - "sha256": "72286fcd4fdf9b7e1d37ed6d1c440215534382bf51a00d4348d1a4e4c784e822" + "sha256": "1ad4fccee35b05f1bdcc1eea8b2b82d488972a7dbede44844c9ce6b8747d3d09" }, { "path": "snapshots/codegen/upstream-codegen-214-6dc49544c0.snap", @@ -2035,7 +2035,7 @@ }, { "path": "snapshots/codegen/upstream-codegen-223-4dc8092992.snap", - "sha256": "d3faf189f7216a005ddac21cb28ceeff661a4019a2f37110750b0b34cf0032a2" + "sha256": "e9a06333ad6a4e65d7397740fd68b2d847b4ca4ef72f635a1c3cc8e53a95fe3c" }, { "path": "snapshots/codegen/upstream-codegen-224-075a41e65c.snap", @@ -2083,35 +2083,35 @@ }, { "path": "snapshots/codegen/upstream-codegen-235-8a3992468b.snap", - "sha256": "11174b57bee12c67805eb3012860fa77ac794265f584995382d73f4507e2102c" + "sha256": "47fd13317b49d169cc3df0f8c79b9330b6bba234cbbfe4ba4ff2eaeda7bafea3" }, { "path": "snapshots/codegen/upstream-codegen-236-621c6d6a9e.snap", - "sha256": "09b73b6e9ce938be1e0f32b7ce651182cc5fd5cf2b5c1ca6a15692aaf4e1e1aa" + "sha256": "0a52546a500390e33d9244bb15f5531fcc5b1f236c074e59d6f6f650b4fada94" }, { "path": "snapshots/codegen/upstream-codegen-237-01ee478666.snap", - "sha256": "6a0cf91ec198452b8696fb591d269cbb7af94842077ee95bbdaf85b222526ec6" + "sha256": "672388fb2191e02c44d30f766d26d1cf8d69da658a7d3d31cdb5ec4dbb8619d3" }, { "path": "snapshots/codegen/upstream-codegen-238-1a8cf8c870.snap", - "sha256": "bcbf286a3d27852647054e1ff161aae2eaa73e681e011df86e90dd095d47e648" + "sha256": "db3629e2529256df7da9941da4ffadde0e8558388a435f1c83990ecb67b2504d" }, { "path": "snapshots/codegen/upstream-codegen-239-a6dada3682.snap", - "sha256": "4e7d5594ab96b2874e9ab27267c80d49f31ba57699b96af142d193d6777c0f1a" + "sha256": "fc276a1c2ae1d0ecf30d25d48d731ec8f302b894b4827997402041785e992b80" }, { "path": "snapshots/codegen/upstream-codegen-240-77d56a1585.snap", - "sha256": "bcbf286a3d27852647054e1ff161aae2eaa73e681e011df86e90dd095d47e648" + "sha256": "db3629e2529256df7da9941da4ffadde0e8558388a435f1c83990ecb67b2504d" }, { "path": "snapshots/codegen/upstream-codegen-241-e171ef72ce.snap", - "sha256": "4e7d5594ab96b2874e9ab27267c80d49f31ba57699b96af142d193d6777c0f1a" + "sha256": "fc276a1c2ae1d0ecf30d25d48d731ec8f302b894b4827997402041785e992b80" }, { "path": "snapshots/codegen/upstream-codegen-242-5c198a8490.snap", - "sha256": "b30a5a535c44e00856ebc964ad2912300ceebb114e646067253d04558acb2920" + "sha256": "7efc63bee039a5faba69e4d1fd8207a9cd53420f03452b454448e944ee47a7fe" }, { "path": "snapshots/codegen/upstream-codegen-243-14366a47ff.snap", @@ -2147,15 +2147,15 @@ }, { "path": "snapshots/codegen/upstream-codegen-251-50acddfb96.snap", - "sha256": "d39f49e2a8ba47a507ae6ef24c45587fb11a00ce72992c59eb4c1d5ebb875573" + "sha256": "8076f48ab0d1c365ffc58db8e217e81211670eee93d4592e4a15d9eaf2b2f689" }, { "path": "snapshots/codegen/upstream-codegen-252-49e979239e.snap", - "sha256": "56645bf5c1c7924e03a1d4336d930ee187f8757c53d5f088a0268558e547e015" + "sha256": "d44abef91eab436a79d824dc16cda5062293c1cc44de0a48e5725418655a9f9e" }, { "path": "snapshots/codegen/upstream-codegen-253-347a2e5fb2.snap", - "sha256": "eb90618d14e93b280230b68373576b090b95a79b6792ced6c7299c85a061cf5d" + "sha256": "ec88bce73a1148abd37f382c38f46b7d0f3d4837dc44c5162b3cb949383b181a" }, { "path": "snapshots/codegen/upstream-codegen-254-9f340b6a10.snap", diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-164-33e4c6591c.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-164-33e4c6591c.snap index f99f9a57..f99b08d3 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-164-33e4c6591c.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-164-33e4c6591c.snap @@ -30,6 +30,7 @@ expression: actual - puzzle-piece + puzzle-piece - + - plus + plus ) }" diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-239-a6dada3682.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-239-a6dada3682.snap index 679e1523..6996480e 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-239-a6dada3682.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-239-a6dada3682.snap @@ -16,6 +16,7 @@ expression: actual aspectRatio="1" bg="#000" boxSize="28px" + flexShrink="0" maskImage="url(/icons/cog.svg)" maskPos="center" maskRepeat="no-repeat" diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-240-77d56a1585.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-240-77d56a1585.snap index 5c6aca34..fade7ef6 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-240-77d56a1585.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-240-77d56a1585.snap @@ -6,7 +6,13 @@ expression: actual "export function SvgDetail() { return (
- plus + plus
) }" diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-241-e171ef72ce.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-241-e171ef72ce.snap index 679e1523..6996480e 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-241-e171ef72ce.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-241-e171ef72ce.snap @@ -16,6 +16,7 @@ expression: actual aspectRatio="1" bg="#000" boxSize="28px" + flexShrink="0" maskImage="url(/icons/cog.svg)" maskPos="center" maskRepeat="no-repeat" diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-242-5c198a8490.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-242-5c198a8490.snap index 5f852cbb..ef86f841 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-242-5c198a8490.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-242-5c198a8490.snap @@ -12,7 +12,13 @@ expression: actual flexDir="column" p="10px" > - cog + cog ) }" diff --git a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-251-50acddfb96.snap b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-251-50acddfb96.snap index 92884edf..33dc31cc 100644 --- a/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-251-50acddfb96.snap +++ b/fixtures/devup-figma-plugin/snapshots/codegen/upstream-codegen-251-50acddfb96.snap @@ -34,6 +34,7 @@ expression: actual