diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 822b92ca7..d9451579a 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -40,6 +40,13 @@ pub fn specs() -> Vec { true, sort_variables ), + spec!( + "variable.sortCollections", + "Sort collections", + "{descending? (Z to A)} this file's collections by name, numbers by value; their variables keep their order", + true, + sort_collections + ), spec!("variable.renameMode", "Rename mode", "{collection, mode, name}", true, rename_mode), spec!("variable.removeMode", "Delete mode", "{collection, mode} (a collection keeps at least one mode)", true, remove_mode), spec!("variable.moveMode", "Move mode", "{collection, mode, to (index; 0 = the default mode, layers on Auto follow it)}", true, move_mode), @@ -297,9 +304,18 @@ fn sort_variables(s: &mut Session, p: &Value) -> Result { ok() } +fn sort_collections(s: &mut Session, p: &Value) -> Result { + let descending = boolean(p, "descending").unwrap_or(false); + s.doc_mut()?.variables.collections.sort_by(|a, b| { + let o = natural_cmp(&a.name, &b.name); + if descending { o.reverse() } else { o } + }); + ok() +} + /// Compare names with each run of digits as a number ("50" < "100" < "950") and letters ignoring /// case; names equal that way compare as plain text. -fn natural_cmp(a: &str, b: &str) -> Ordering { +pub fn natural_cmp(a: &str, b: &str) -> Ordering { fn digits(it: &mut std::iter::Peekable) -> String { std::iter::from_fn(|| it.next_if(char::is_ascii_digit)).collect() } diff --git a/crates/engine/src/variables_editor_tests.rs b/crates/engine/src/variables_editor_tests.rs index c0389d404..4aff5e1ef 100644 --- a/crates/engine/src/variables_editor_tests.rs +++ b/crates/engine/src/variables_editor_tests.rs @@ -233,6 +233,28 @@ fn moving_variables_reorders_their_collection_only_and_undoes() { assert_eq!(names_in(&s, "Tokens"), before); } +#[test] +fn sorting_collections_reorders_only_the_collections_and_undoes() { + let mut s = Session::new(); + for c in ["Spacing 10", "brand", "Spacing 2"] { + ex(&mut s, "variable.createCollection", json!({"name": c})); + } + for n in ["b", "a"] { + ex(&mut s, "variable.create", json!({"collection": "brand", "name": n, "type": "number", "value": 1})); + } + let collections = |s: &Session| s.doc().unwrap().variables.collections.iter().map(|c| c.name.clone()).collect::>(); + let before = collections(&s); + ex(&mut s, "variable.sortCollections", json!({})); + assert_eq!(collections(&s), ["brand", "Spacing 2", "Spacing 10"]); + ex(&mut s, "variable.sortCollections", json!({"descending": true})); + assert_eq!(collections(&s), ["Spacing 10", "Spacing 2", "brand"]); + // The variables keep their order. + assert_eq!(names_in(&s, "brand"), ["b", "a"]); + ex(&mut s, "edit.undo", json!({})); + ex(&mut s, "edit.undo", json!({})); + assert_eq!(collections(&s), before); +} + #[test] fn sorting_orders_numbers_by_value_within_the_group_asked() { let mut s = Session::new(); diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 777e89524..2b6476334 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -323,6 +323,7 @@ name = "English" "Arrange" = "Arrange" "Arrow" = "Arrow" "As typed" = "As typed" +"Ascending" = "Ascending" "Asking the server…" = "Asking the server…" "Assets" = "Assets" "Aug" = "Aug" @@ -431,6 +432,7 @@ name = "English" "CSS custom properties…" = "CSS custom properties…" "Create from color" = "Create from color" "Curve" = "Curve" +"Custom order" = "Custom order" "Dart constants for Flutter…" = "Dart constants for Flutter…" "Uno Platform theme resources…" = "Uno Platform theme resources…" "Calculated from other variables; it follows them" = "Calculated from other variables; it follows them" @@ -696,6 +698,7 @@ name = "English" "Delete “{name}”? This can't be undone." = "Delete “{name}”? This can't be undone." "Density" = "Density" "Depth" = "Depth" +"Descending" = "Descending" "Describe how and when to use this component" = "Describe how and when to use this component" "Describe what changed" = "Describe what changed" "Description" = "Description" @@ -1752,6 +1755,7 @@ name = "English" "Sort" = "Sort" "Sort A to Z" = "Sort A to Z" "Sort Z to A" = "Sort Z to A" +"Sort variables" = "Sort variables" "Sort by" = "Sort by" "Sort by date" = "Sort by date" "Sort by page" = "Sort by page" diff --git a/crates/ui-egui/src/a11y.rs b/crates/ui-egui/src/a11y.rs index da0aad507..6151805f8 100644 --- a/crates/ui-egui/src/a11y.rs +++ b/crates/ui-egui/src/a11y.rs @@ -892,6 +892,18 @@ pub fn named_button(resp: &Response, label: &str) { node(resp, label, |n| n.set_role(Role::Button)); } +/// A column header that sorts its table when clicked, `sorted` = Some(descending) while the +/// table is sorted by it. +pub fn column_header(resp: &Response, label: &str, sorted: Option) { + node(resp, label, |n| { + n.set_role(Role::ColumnHeader); + n.add_action(accesskit::Action::Click); + if let Some(descending) = sorted { + n.set_sort_direction(if descending { accesskit::SortDirection::Descending } else { accesskit::SortDirection::Ascending }); + } + }); +} + /// A link, named by its text. pub fn link(resp: &Response, label: &str) { node(resp, label, |n| n.set_role(Role::Link)); diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 38d0b8824..d38663962 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -7,8 +7,12 @@ //! and write the variables JSON (or CSS). Everything goes through `variable.*` / `library.*` //! commands, so it's undoable and the same over MCP. +use std::cmp::Ordering; +use std::collections::BTreeMap; + use egui::{Align2, Context, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; use figcraft_doc::{Collection, Document, PublishedLibrary, Variable, VariableType, VariableValue, Variables, scopes_for}; +use figcraft_engine::cmd::variables::natural_cmp; use figcraft_engine::library; use serde_json::{Value, json}; @@ -38,6 +42,22 @@ enum Rename { Group(String, String), } +/// How the table orders its rows within each group, a view of them (the stored order the pickers +/// and exports follow stays): by name, or by their values in a mode (its id), A to Z or Z to A. +#[derive(Clone, Debug, PartialEq)] +struct Sort { + mode: Option, + descending: bool, +} + +impl Sort { + /// A click on the header of `mode` (None: Name): the other way round when it is the order + /// already, else A to Z. + fn clicked(sort: Option<&Sort>, mode: Option<&str>) -> Sort { + Sort { mode: mode.map(str::to_string), descending: sort.is_some_and(|s| s.mode.as_deref() == mode && !s.descending) } + } +} + /// The open editor's state (`UiState::variables`; None = closed). #[derive(Clone, Default)] pub struct Editor { @@ -59,6 +79,11 @@ pub struct Editor { pub(crate) anchor: Option, /// The variable ids the table shows now, in row order (the range a Shift+click covers). pub(crate) order: Vec, + /// The table's order; None = the stored order (Move up and Move down work then). + sort: Option, + /// The order before the last click on a mode's header: a double-click there renames the mode + /// and leaves the order as it was. + sort_before: Option, /// The variables the compact "Edit variables" editor is open on (empty = closed). bulk_edit: Vec, /// That editor's tab: 0 Details, 1 Scope. @@ -453,9 +478,23 @@ pub(crate) fn unique(base: &str, taken: impl Fn(&str) -> bool) -> String { /// Draw the collections sidebar with library headings, collection rows and a create-collection /// button. fn sidebar(app: &mut FigApp, ui: &mut Ui, views: &[View], local: &Variables, st: &mut Editor) { - let t = Tokens::get(ui.ctx()); let (hr, _) = ui.allocate_exact_size(vec2(SIDEBAR_W, 40.0), Sense::hover()); - ui.painter().text(pos2(hr.min.x + 16.0, hr.center().y), Align2::LEFT_CENTER, tr("Collections"), semibold(11.0), t.text_secondary); + // The header sorts this file's collections (only them, not their variables), A to Z then Z to A. + let sorted_by = |descending: bool| { + local.collections.is_sorted_by(|a, b| { + let o = natural_cmp(&a.name, &b.name); + (if descending { o.reverse() } else { o }).is_le() + }) + }; + let sorted = match (sorted_by(false), sorted_by(true)) { + (true, false) => Some(false), + (false, true) => Some(true), + _ => None, + }; + let cell = Rect::from_min_max(pos2(hr.min.x + 8.0, hr.min.y + 6.0), pos2(hr.max.x - 36.0, hr.max.y - 6.0)); + if widgets::sort_header(ui, cell, Id::unique("vars_sort_collections"), tr("Collections"), 8.0, sorted).clicked() && local.collections.len() > 1 { + app.run("variable.sortCollections", json!({"descending": sorted == Some(false)})); + } if widgets::icon_button_at( ui, Id::unique("vars_add_coll"), @@ -536,7 +575,7 @@ fn collection_row(app: &mut FigApp, ui: &mut Ui, view: &View, c: &Collection, st ui.close(); } if view.editable() { - sort_items(app, ui, json!({"collection": c.id})); + sort_items(app, ui, "variable.sortCollections", json!({})); } if view.editable() && menu_item(ui, tr("Delete collection"), "") { app.run("variable.deleteCollection", json!({"collection": c.id})); @@ -623,7 +662,7 @@ fn group_rows(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st: duplicate_group(app, &members, &list, g); ui.close(); } - sort_items(app, ui, json!({"collection": coll.id, "group": g})); + sort_items(app, ui, "variable.sort", json!({"collection": coll.id, "group": g})); if menu_item(ui, tr("Delete group"), "") { let steps: Vec = members .iter() @@ -703,22 +742,26 @@ fn duplicate_group(app: &mut FigApp, members: &[&Variable], list: &[String], g: app.run("command.batch", json!({"label": "Duplicate group", "commands": steps})); } -/// Sort by name, A to Z and Z to A, menu items for the variables `scope` names (`variable.sort`'s -/// collection and group). -fn sort_items(app: &mut FigApp, ui: &mut Ui, scope: Value) { +/// Sort by name, A to Z and Z to A, menu items running `cmd` (`variable.sort` on the variables +/// `scope` names, or `variable.sortCollections`). +fn sort_items(app: &mut FigApp, ui: &mut Ui, cmd: &str, scope: Value) { for (label, descending) in [(tr_noop("Sort A to Z"), false), (tr_noop("Sort Z to A"), true)] { if menu_item(ui, tr(label), "") { let mut p = scope.clone(); p["descending"] = json!(descending); - app.run("variable.sort", p); + app.run(cmd, p); ui.close(); } } } /// The `variable.move` params that move `v` one row up (or `down`) past its neighbour among the -/// table's rows of its group; None at the group's end. +/// table's rows of its group; None at the group's end, or while the table is sorted (its rows +/// aren't the stored order then). fn step_move(view: &View, coll: &Collection, st: &Editor, v: &Variable, down: bool) -> Option { + if st.sort.is_some() { + return None; + } let g = group_of(&v.name); let rows: Vec<&String> = st.order.iter().filter(|id| view.vars.get_by_id(id).is_some_and(|x| group_of(&x.name) == g)).collect(); let i = rows.iter().position(|id| **id == v.id)?; @@ -732,6 +775,80 @@ fn step_move(view: &View, coll: &Collection, st: &Editor, v: &Variable, down: bo Some(json!({"variables": [v.id], "before": after})) } +/// The sort dropdown beside the search field: the stored order, by name or by a mode's values, +/// then which way round. +fn sort_menu(ui: &mut Ui, coll: &Collection, st: &mut Editor) { + let by = |sort: Option<&Sort>| match sort { + None => tr("Custom order"), + Some(Sort { mode: None, .. }) => tr("Name"), + Some(Sort { mode: Some(m), .. }) => coll.modes.iter().find(|x| &x.id == m).map_or("", |x| x.name.as_str()), + }; + let label = by(st.sort.as_ref()).to_string(); + let resp = widgets::dropdown(ui, &label, ui.available_width(), None).on_hover_text(tr("Sort variables")); + crate::right::menu_popup(&resp).show(|ui| { + let keys = [None, Some(None)].into_iter().chain(coll.modes.iter().map(|m| Some(Some(m.id.as_str())))); + for key in keys { + let sort = key.map(|mode| Sort { mode: mode.map(str::to_string), descending: false }); + let on = st.sort.as_ref().map(|s| s.mode.as_deref()) == key; + if crate::right::menu_check(ui, on, by(sort.as_ref()), "") { + // Keep the direction when only the column changes. + st.sort = sort.map(|s| Sort { descending: st.sort.as_ref().is_some_and(|o| o.descending), ..s }); + ui.close(); + } + } + let Some(sort) = st.sort.clone() else { return }; + ui.separator(); + let (up, down) = if sort.mode.is_none() { (tr("A to Z"), tr("Z to A")) } else { (tr("Ascending"), tr("Descending")) }; + for (descending, label) in [(false, up), (true, down)] { + if crate::right::menu_check(ui, sort.descending == descending, label, "") { + st.sort = Some(Sort { descending, ..sort.clone() }); + ui.close(); + } + } + }); +} + +/// Order the table's rows `list` (variables of `coll`) by `sort`, within their groups; the stored +/// order within each group when None. +fn sort_rows(list: &mut [&Variable], vars: &Variables, coll: &Collection, sort: Option<&Sort>) { + let flip = |o: Ordering| if sort.is_some_and(|s| s.descending) { o.reverse() } else { o }; + match sort.map(|s| s.mode.as_deref()) { + None => list.sort_by(|a, b| group_of(&a.name).cmp(group_of(&b.name))), + Some(None) => list.sort_by(|a, b| { + let leaf = |v: &Variable| v.name.rsplit('/').next().unwrap_or_default().to_string(); + flip(natural_cmp(group_of(&a.name), group_of(&b.name)).then_with(|| natural_cmp(&leaf(a), &leaf(b)))) + }), + Some(Some(mode)) => { + let modes = BTreeMap::from([(coll.id.clone(), mode.to_string())]); + let mut keyed: Vec<(&Variable, Option)> = list.iter().map(|v| (*v, vars.resolve(&v.id, &modes))).collect(); + keyed.sort_by(|(a, x), (b, y)| group_of(&a.name).cmp(group_of(&b.name)).then_with(|| flip(value_cmp(x.as_ref(), y.as_ref())))); + for (slot, (v, _)) in list.iter_mut().zip(keyed) { + *slot = v; + } + } + } +} + +/// How two values (resolved, in one mode) order: by type as the create menu lists them, then +/// numbers by value, text by name order (50 before 100), false before true and colours by hex code; +/// a value that doesn't resolve comes after the rest (before them Z to A). +fn value_cmp(a: Option<&VariableValue>, b: Option<&VariableValue>) -> Ordering { + let rank = |v: Option<&VariableValue>| match v { + Some(VariableValue::Color(_)) => 0, + Some(VariableValue::Number(_)) => 1, + Some(VariableValue::String(_)) => 2, + Some(VariableValue::Boolean(_)) => 3, + _ => 4, + }; + match (a, b) { + (Some(VariableValue::Number(x)), Some(VariableValue::Number(y))) => x.total_cmp(y), + (Some(VariableValue::String(x)), Some(VariableValue::String(y))) => natural_cmp(x, y), + (Some(VariableValue::Boolean(x)), Some(VariableValue::Boolean(y))) => x.cmp(y), + (Some(VariableValue::Color(x)), Some(VariableValue::Color(y))) => x.to_hex().cmp(&y.to_hex()), + _ => rank(a).cmp(&rank(b)), + } +} + fn create_collection(app: &mut FigApp, vars: &Variables, st: &mut Editor) { let name = unique("Collection", |n| vars.collections.iter().any(|c| c.name == n)); if let Some(id) = @@ -792,7 +909,9 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) { .align(egui::Align2::LEFT_CENTER), ); 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 menu = Rect::from_min_size(pos2(field.max.x + 8.0, field.min.y), vec2(120.0, field.height())); + sort_menu(&mut ui.new_child(UiBuilder::new().max_rect(menu)), coll, st); + let note = Rect::from_min_max(pos2(menu.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_by_id(p))) { (Some((lib, name)), _) => { @@ -813,7 +932,9 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) { let in_group = |v: &Variable| st.group.as_ref().is_none_or(|g| v.name.starts_with(&format!("{g}/"))); let mut list: Vec<&Variable> = view.in_collection(&coll.id).filter(|v| in_group(v) && (q.is_empty() || v.name.to_lowercase().contains(&q))).collect(); - list.sort_by(|a, b| group_of(&a.name).cmp(group_of(&b.name))); + // A sort by a mode another collection has (picked there) falls back to the stored order. + st.sort = st.sort.take().filter(|s| s.mode.as_ref().is_none_or(|m| coll.modes.iter().any(|x| &x.id == m))); + sort_rows(&mut list, view.vars, coll, st.sort.as_ref()); st.order = list.iter().map(|v| v.id.clone()).collect(); let order = st.order.clone(); st.selected.retain(|id| order.contains(id)); @@ -878,7 +999,12 @@ fn header_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st: // An extended collection has the modes of the one it extends. let editable = view.editable() && coll.extends.is_none(); let (r, _) = ui.allocate_exact_size(vec2(width, 32.0), Sense::hover()); - ui.painter().text(pos2(r.min.x + 16.0, r.center().y), Align2::LEFT_CENTER, tr("Name"), regular(11.0), t.text_secondary); + // A header click sorts by its column (again: the other way round). + let sorted = |st: &Editor, mode: Option<&str>| st.sort.as_ref().filter(|s| s.mode.as_deref() == mode).map(|s| s.descending); + let name_cell = Rect::from_min_max(pos2(r.min.x + 8.0, r.min.y + 4.0), pos2(r.min.x + NAME_W - 8.0, r.max.y - 4.0)); + if widgets::sort_header(ui, name_cell, Id::unique("vars_sort_name"), tr("Name"), 8.0, sorted(st, None)).clicked() { + st.sort = Some(Sort::clicked(st.sort.as_ref(), None)); + } for (i, m) in coll.modes.iter().enumerate() { let x = r.min.x + NAME_W + i as f32 * MODE_W; let cell = Rect::from_min_max(pos2(x + 4.0, r.min.y + 4.0), pos2(x + MODE_W - 8.0, r.max.y - 4.0)); @@ -889,18 +1015,16 @@ fn header_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st: } continue; } - let name_pos = pos2(cell.min.x + 4.0, cell.center().y); - if !editable { - ui.painter().with_clip_rect(cell).text(name_pos, Align2::LEFT_CENTER, &m.name, regular(11.0), t.text_secondary); - continue; - } - let resp = ui.interact(cell, Id::unique(("vars_mode", &m.id)), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(cell, CornerRadius::same(4), t.hover); - } - ui.painter().with_clip_rect(cell).text(name_pos, Align2::LEFT_CENTER, &m.name, regular(11.0), t.text_secondary); - if resp.double_clicked() { + let resp = widgets::sort_header(ui, cell, Id::unique(("vars_mode", &m.id)), &m.name, 4.0, sorted(st, Some(&m.id))); + if editable && resp.double_clicked() { + st.sort = st.sort_before.take(); start_rename(st, target.clone()); + } else if resp.clicked() { + st.sort_before = st.sort.clone(); + st.sort = Some(Sort::clicked(st.sort.as_ref(), Some(&m.id))); + } + if !editable { + continue; } crate::right::context_popup(&resp).show(|ui| { if menu_item(ui, tr("Rename mode"), "") { @@ -1430,7 +1554,36 @@ fn bulk_details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Edit #[cfg(test)] mod tests { - use super::{group_renames, groups, tri}; + use super::{Sort, group_renames, groups, sort_rows, tri}; + + /// The names of collection "Theme"'s rows, made from `(name, value)` numbers, ordered by `sort`. + fn sorted(rows: &[(&str, f64)], sort: Option) -> Vec { + let mut s = figcraft_engine::Session::new(); + s.execute("variable.createCollection", &serde_json::json!({"name": "Theme"})).unwrap(); + for (n, v) in rows { + s.execute("variable.create", &serde_json::json!({"collection": "Theme", "name": n, "type": "number", "value": v})).unwrap(); + } + let vars = &s.doc().unwrap().variables; + let coll = &vars.collections[0]; + let sort = sort.map(|s| Sort { mode: s.mode.map(|_| coll.modes[0].id.clone()), ..s }); + let mut list: Vec<_> = vars.variables.iter().collect(); + sort_rows(&mut list, vars, coll, sort.as_ref()); + list.iter().map(|v| v.name.clone()).collect() + } + + #[test] + fn the_table_sorts_rows_within_their_groups_by_name_or_value() { + let rows = [("space/100", 1.0), ("b", 30.0), ("space/50", 20.0), ("a", 4.0), ("space/9", 3.0)]; + // Stored order within each group, the ungrouped first. + assert_eq!(sorted(&rows, None), ["b", "a", "space/100", "space/50", "space/9"]); + let by_name = |descending| Some(Sort { mode: None, descending }); + assert_eq!(sorted(&rows, by_name(false)), ["a", "b", "space/9", "space/50", "space/100"]); + assert_eq!(sorted(&rows, by_name(true)), ["space/100", "space/50", "space/9", "b", "a"]); + // By value: groups stay in place, numbers compare as numbers. + let by_value = |descending| Some(Sort { mode: Some(String::new()), descending }); + assert_eq!(sorted(&rows, by_value(false)), ["a", "b", "space/100", "space/9", "space/50"]); + assert_eq!(sorted(&rows, by_value(true)), ["b", "a", "space/50", "space/9", "space/100"]); + } #[test] fn tri_is_checked_empty_or_mixed() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 6fb9beb98..4ece8a74f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -989,6 +989,30 @@ fn select_all_id(te_id: Id) -> Id { te_id.with("select_all_on_focus") } +/// A table column header in `cell` that sorts by its column: `label` `pad` from the left, bold with +/// an arrow (up ascending, down descending) while the table is sorted by it (`sorted` = +/// Some(descending)). Sort when the response is clicked. +pub fn sort_header(ui: &mut Ui, cell: Rect, id: Id, label: &str, pad: f32, sorted: Option) -> Response { + let t = Tokens::get(ui.ctx()); + let resp = ui.interact(cell, id, Sense::click()); + a11y::column_header(&resp, label, sorted); + if resp.hovered() { + ui.painter().rect_filled(cell, CornerRadius::same(4), t.hover); + } + let (font, color) = if sorted.is_some() { (semibold(11.0), t.text) } else { (regular(11.0), t.text_secondary) }; + let text = Rect::from_min_max(pos2(cell.min.x + pad, cell.min.y), pos2(cell.max.x - if sorted.is_some() { 18.0 } else { 4.0 }, cell.max.y)); + let shown = elide_font(ui, label, text.width(), font.clone()); + let end = ui.painter().text(text.left_center(), Align2::LEFT_CENTER, &shown, font, color).max.x; + if let Some(descending) = sorted { + let icon = if descending { Icon::Chevron } else { Icon::ChevronUp }; + icons::paint(ui.painter(), Rect::from_center_size(pos2(end + 10.0, cell.center().y), vec2(10.0, 10.0)), icon, t.icon_secondary); + } + if resp.has_focus() { + ui.painter().rect_stroke(cell, CornerRadius::same(4), Stroke::new(2.0, t.focus), StrokeKind::Outside); + } + if shown != label { resp.on_hover_text(label) } else { resp } +} + /// What a dropdown shows before its label. #[derive(Clone, Copy)] pub enum DropLead { diff --git a/docs/components-parity.md b/docs/components-parity.md index 48eea2dac..cf019f121 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (variables export as Uno Platform theme resources, #2170; frames a REST import made of instances of library components link to an enabled library's component of the same key with Link instances to library, `library.relink` (#2442); a text or instance swap property's default follows its bound layer on the main and the main follows a new default, and a new instance of a variant shows that variant's own text and icon (#2179); variables export and import as DTCG design tokens (#1687); one variant selected shows a Current variant section, a dropdown of each variant property at its value, and a button that selects the set, which has the property editor (#2346); `node.set` warns when a variant reaches past a component set that clips it and has no auto layout (#2182); a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-04 · **Change:** minor (the Local variables window sorts its table as a view: a sort dropdown beside the search field and sortable Name and mode column headers, the stored order kept; the Collections header and a collection's Sort A to Z / Z to A sort the collections, not their variables, `variable.sortCollections` (#3000); variables export as Uno Platform theme resources, #2170; frames a REST import made of instances of library components link to an enabled library's component of the same key with Link instances to library, `library.relink` (#2442); a text or instance swap property's default follows its bound layer on the main and the main follows a new default, and a new instance of a variant shows that variant's own text and icon (#2179); variables export and import as DTCG design tokens (#1687); one variant selected shows a Current variant section, a dropdown of each variant property at its value, and a button that selects the set, which has the property editor (#2346); `node.set` warns when a variant reaches past a component set that clips it and has no auto layout (#2182); a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -69,7 +69,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) | | Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow 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; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); Create variable makes the variable in the group shown, and a row's rename edits the name's last part; the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | -| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow 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; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); variables keep the order they are put in: Move up / Move down (Alt+↑ / Alt+↓) on a row and Sort A to Z / Z to A on a collection or group, numbers by value (`variable.move`, `variable.sort`, #2633); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow 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; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); variables keep the order they are put in: Move up / Move down (Alt+↑ / Alt+↓) on a row and Sort A to Z / Z to A on a group, numbers by value (`variable.move`, `variable.sort`, #2633); the table can be shown sorted without changing that order: a dropdown beside the search field (Custom order, Name or a mode's values, either way round) and clickable Name and mode headers (again: the other way round, an arrow shows which), Move up / Move down being off while it is; the Collections header (click again: Z to A) and a collection's Sort A to Z / Z to A reorder this file's collections and leave their variables as they are (`variable.sortCollections`, #3000); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Text styles in the Variables JSON export and import (`textStyles`, a FigCraft extension: the REST `styles` metadata has no values) | done | `variable.export {format: "json"}` adds a top-level `textStyles` array (values and `bound`, ids matching `meta.variables`); `variable.import` merges it by style name and re-points bindings; CSS, Tailwind and Dart are variables only | @@ -85,6 +85,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-12-04 | minor | M3, #3000: sorting variables lived only in the context menus, as an edit. The Local variables window now sorts its table as a view, leaving the stored order the pickers and exports follow as it is: a dropdown beside the search field picks Custom order (the stored one), Name or a mode's values (numbers by value, text in name order, colours by hex code), A to Z or Z to A; a click on the Name or a mode's header sorts by that column and a second click turns it round, with an arrow on the header. Rows stay under their group headers. Move up / Move down are off while the table is sorted. The Collections header sorts this file's collections A to Z, then Z to A, and so do a collection's Sort A to Z / Z to A (they sorted its variables before); neither moves a variable. New command `variable.sortCollections {descending?}`, one undo step. Tests: `variables_editor_tests::sorting_collections_reorders_only_the_collections_and_undoes`, `variables_panel::tests::the_table_sorts_rows_within_their_groups_by_name_or_value`. Grade unchanged. | | 2026-12-02 | minor | M7, #2170: `variable.export {format: "uno"}` (also Variables › Export… › Uno Platform theme resources…) writes one C# file: a `VariableResources` class based on `ResourceDictionary`, with collections of one mode in it and those of two or more modes in its Light and Dark theme dictionaries (each theme the mode of its name, else the first mode the other doesn't take; other modes left out with a warning), colours as brushes, corner radii as `CornerRadius`, other numbers as `double`, keys from variable names unique per file, aliases resolved per theme. | | 2026-12-02 | patch | M7, #2170 follow-up: the Uno variables export writes a Display P3 file's colours as sRGB (what `Color.FromArgb` reads), and names that collide take their number suffix in variable-id order, so reordering variables no longer swaps two keys; Variables › Export… shows how many warnings an export has and the first one. Tests: `variables_export_as_uno_theme_resources`, `uno_keys_of_names_that_collide_survive_a_reorder`, `an_export_that_leaves_something_out_says_what`. Numbers unchanged. | | 2026-12-01 | patch | M3, #2186: a frame holding main components, duplicated or pasted in its file, always got new mains, so a themed copy of a components page had to be rebuilt from instances by hand. Edit > Duplicate as instances (`edit.duplicateAsInstances`), and `mains: "instances"` on `edit.duplicate` and `edit.paste`, make each main inside the copied layers an instance of the original and each component set an instance of its default variant; copied instances of those mains stay linked to the originals with their overrides; a variant copied into its set stays a variant; a paste whose mains were cut or deleted keeps them as mains. The default is unchanged. Tests: `duplicate_as_instances_tests`. Numbers unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 9092c0ac1..fb6cb2478 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -519,7 +519,8 @@ ArtCraft Launcher's agents switch for FigCraft. (index 0 is the default mode, which layers on Auto follow). `variable.move {variables, before?}` reorders variables within their collection (the order the Variables window and the pickers list), `variable.sort {collection, group?, descending?}` sorts them by name, numbers by value (50 before - 100). `variable.update {codeSyntax: {WEB?, + 100), `variable.sortCollections {descending?}` sorts the file's collections the same way (their + variables keep their order). `variable.update {codeSyntax: {WEB?, iOS?, ANDROID?}}` sets code names (`""` clears); generated CSS uses the Web one, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there). - **Live previews**: `text.preview {command, params}` shows what `style.apply`, diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 30df8a480..b4c5fdf34 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -2,7 +2,7 @@ > **Generated:** 2026-12-04 by `cargo xtask parity`. Do not edit by hand. -FigCraft commands registered for the incumbent's main menu and toolbar (710 commands in the engine). +FigCraft commands registered for the incumbent's main menu and toolbar (711 commands in the engine). **216 / 216 menu items (100.0%)**