From 5e455cedcbe95a7419f8bf7c8f2172b85c8990cd Mon Sep 17 00:00:00 2001 From: BFlat Date: Sat, 5 Dec 2026 22:18:07 +0700 Subject: [PATCH] M4: hovering a colour style or variable in the style picker previews it on the canvas (#3043) (#3054) --- crates/engine/src/canvas/textpreview.rs | 14 +++-- crates/engine/src/cmd/text.rs | 2 +- crates/ui-egui/src/panels/variable_ui.rs | 22 ++++--- crates/ui-egui/src/widgets/style_picker.rs | 63 ++++++++++--------- .../ui-egui/src/widgets/style_picker/tests.rs | 36 +++++++++++ docs/control-protocol.md | 2 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 3 +- 8 files changed, 100 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/canvas/textpreview.rs b/crates/engine/src/canvas/textpreview.rs index 07d3b0214..7bd36d1d8 100644 --- a/crates/engine/src/canvas/textpreview.rs +++ b/crates/engine/src/canvas/textpreview.rs @@ -1,6 +1,6 @@ //! Live previews: what a command would do, shown on the canvas without an undo step — while the -//! pointer is over a font family or style, a text style in the style browser, a font's named -//! instance or a blend mode, or while a variable font axis slider is dragged. The document under +//! pointer is over a font family or style, a style or colour variable in the style browser, a +//! font's named instance or a blend mode, or while a variable font axis slider is dragged. The document under //! the preview is kept and comes back when the preview ends ([`end`], `text.endPreview`). Every //! other command ends it first, so committing (running the command for real) applies to the //! document itself as one undo step, and Escape just ends the preview. @@ -14,11 +14,15 @@ use crate::{EngineError, Result, Session, bad, find_command, guard, normalize}; /// The commands that show or end a preview (they don't end the one showing). pub const COMMANDS: [&str; 3] = ["text.preview", "text.endPreview", "widget.hover"]; -/// What can be previewed: text styles, font styles and axis values, layers' properties and the -/// blend of a paint on a layer, a selection or a style. -pub const PREVIEWABLE: [&str; 9] = [ +/// What can be previewed: styles and colour variables on layers or Selection colors paints, font +/// styles and axis values, layers' properties and the blend of a paint on a layer, a selection or a style. +pub const PREVIEWABLE: [&str; 13] = [ "style.apply", "library.applyStyle", + "selection.applyColorStyle", + "variable.bind", + "library.bindVariable", + "selection.bindColorVariable", "text.setVariations", "text.style", "node.set", diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c48339b0b..23cb6a907 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -646,7 +646,7 @@ pub fn specs() -> Vec { spec!( "text.preview", "Preview a change", - "{command: style.apply|library.applyStyle|text.setVariations|text.style|node.set|fill.set|stroke.set|selection.setPaint|style.update, params} shows what the command would do on the canvas without an undo step (a hovered font family or style, text style, named instance, blend mode, or a dragged axis slider), in place of an earlier preview; text.endPreview or any other command ends it, so running the command for real commits it as one undo step", + "{command: style.apply|library.applyStyle|selection.applyColorStyle|variable.bind|library.bindVariable|selection.bindColorVariable|text.setVariations|text.style|node.set|fill.set|stroke.set|selection.setPaint|style.update, params} shows what the command would do on the canvas without an undo step (a hovered font family or style, style or colour variable, named instance, blend mode, or a dragged axis slider), in place of an earlier preview; text.endPreview or any other command ends it, so running the command for real commits it as one undo step", false, |s, p| { let c = req_string("text.preview", p, "command")?; diff --git a/crates/ui-egui/src/panels/variable_ui.rs b/crates/ui-egui/src/panels/variable_ui.rs index 906af6070..ef9f5d67a 100644 --- a/crates/ui-egui/src/panels/variable_ui.rs +++ b/crates/ui-egui/src/panels/variable_ui.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use egui::{Align2, Color32, CornerRadius, Id, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use figcraft_doc::{Collection, Document, ModeId, NodeId, PublishedLibrary, Variable, VariableId, VariableType, VariableValue, Variables}; use figcraft_engine::library; -use serde_json::json; +use serde_json::{Value, json}; use crate::FigApp; use crate::a11y::Tip; @@ -121,10 +121,16 @@ pub struct Pick { /// Bind `field` of `ids` to `pick` (a library variable is copied in first). pub fn bind(app: &mut FigApp, ids: &[NodeId], field: &str, pick: &Pick) { + let (cmd, params) = bind_command(ids, field, pick); + app.run(cmd, params); +} + +/// The command (and its params) [`bind`] runs. +pub fn bind_command(ids: &[NodeId], field: &str, pick: &Pick) -> (&'static str, Value) { match &pick.library { - Some(lib) => app.run("library.bindVariable", json!({"library": lib, "variable": pick.id, "ids": ids, "field": field})), - None => app.run("variable.bind", json!({"ids": ids, "field": field, "variable": pick.id})), - }; + Some(lib) => ("library.bindVariable", json!({"library": lib, "variable": pick.id, "ids": ids, "field": field})), + None => ("variable.bind", json!({"ids": ids, "field": field, "variable": pick.id})), + } } /// The enabled libraries this session has read, for pickers and the Variables editor. @@ -239,8 +245,8 @@ pub fn mode_rows<'a>(doc: &'a Document, libs: &'a [Arc]) -> Ve } /// A picker row: the variable's swatch (colours) or icon, its name, (other types) its value in -/// the default modes and a check when it is `current` (what the field uses now); true when clicked. -pub fn variable_row(ui: &mut Ui, vars: &Variables, v: &Variable, width: f32, current: bool) -> bool { +/// the default modes and a check when it is `current` (what the field uses now). +pub fn variable_row(ui: &mut Ui, vars: &Variables, v: &Variable, width: f32, current: bool) -> egui::Response { let t = Tokens::get(ui.ctx()); let (r, resp) = ui.allocate_exact_size(vec2(width, 26.0), Sense::click()); crate::a11y::radio(&resp, &v.name, current); @@ -266,7 +272,7 @@ pub fn variable_row(ui: &mut Ui, vars: &Variables, v: &Variable, width: f32, cur ui.painter().text(pos2(end, r.center().y), Align2::RIGHT_CENTER, val.display(), regular(11.0), t.menu_dim); } ui.painter().with_clip_rect(name_r).text(name_r.left_center(), Align2::LEFT_CENTER, &v.name, regular(11.0), t.menu_text); - resp.clicked() + resp } /// A group's caption: the collection's name, after its library's name for library variables. @@ -596,7 +602,7 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) { group_caption(ui, *lib, c); let all = lib.map_or(&doc.variables, |l| &l.doc.variables); for v in vars { - if variable_row(ui, all, v, 224.0, is_current(&doc, current.as_deref(), *lib, v)) { + if variable_row(ui, all, v, 224.0, is_current(&doc, current.as_deref(), *lib, v)).clicked() { chosen = Some(Pick { library: lib.map(|l| l.manifest.id.clone()), id: v.id.clone() }); } } diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index fb6f98bc1..b3ceca555 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -377,6 +377,24 @@ impl Key { } } +/// The command (and its params) picking a style ([`Act::Apply`]) or colour variable ([`Act::Bind`]) +/// runs on `ids`' `slot`, or on a Selection colors row's paints `colors`; None for other acts. +fn pick_command(act: &Act, ids: &[NodeId], slot: StyleSlot, colors: Option<&[PaintTarget]>) -> Option<(&'static str, Value)> { + Some(match (act, colors) { + (Act::Apply(key), Some(targets)) => key.apply_to_colors(targets), + (Act::Apply(key), None) => key.apply(ids, slot), + (Act::Bind(pick), Some(targets)) => { + let mut q = json!({"targets": targets, "variable": pick.id}); + if let Some(lib) = &pick.library { + q["library"] = json!(lib); + } + ("selection.bindColorVariable", q) + } + (Act::Bind(pick), None) => crate::variable_ui::bind_command(ids, slot.key(), pick), + _ => return None, + }) +} + /// What the user asked the picker to do this frame. enum Act { Apply(Key), @@ -396,10 +414,11 @@ enum Act { ToggleView, } -/// What a listing reports besides acts: the style under the pointer, and the preview budget. +/// What a listing reports besides acts: the style or variable under the pointer (as the pick it +/// would be), and the preview budget. struct Frame { act: Option, - hover: Option, + hover: Option, /// Text previews still allowed to render this frame. budget: usize, } @@ -509,7 +528,7 @@ fn preview(ui: &Ui, r: Rect, s: &Style, slot: StyleSlot) { /// Click, right-click and hover on a listed style become acts. fn react(resp: &Response, key: Key, editable: bool, out: &mut Frame) { if resp.hovered() { - out.hover = Some(key.clone()); + out.hover = Some(Act::Apply(key.clone())); } if resp.secondary_clicked() && editable { out.act = Some(Act::Edit(key.style)); @@ -819,8 +838,13 @@ fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut crate::variable_ui::group_caption(ui, *lib, c); let all = lib.map_or(&doc.variables, |l| &l.doc.variables); for v in vars { - if crate::variable_ui::variable_row(ui, all, v, W, crate::variable_ui::is_current(doc, current.as_deref(), *lib, v)) { - out.act = Some(Act::Bind(crate::variable_ui::Pick { library: lib.map(|l| l.manifest.id.clone()), id: v.id.clone() })); + let resp = crate::variable_ui::variable_row(ui, all, v, W, crate::variable_ui::is_current(doc, current.as_deref(), *lib, v)); + let pick = || Act::Bind(crate::variable_ui::Pick { library: lib.map(|l| l.manifest.id.clone()), id: v.id.clone() }); + if resp.hovered() { + out.hover = Some(pick()); + } + if resp.clicked() { + out.act = Some(pick()); } } } @@ -1341,34 +1365,17 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { let ids = p.ids.clone(); let slot = p.slot; let colors = p.colors.clone(); - // The canvas shows the text style under the pointer on the selected text. - if slot == StyleSlot::Text - && !close + // The canvas shows the style or colour variable under the pointer on what the picker acts on. + if !close && out.act.is_none() - && let Some(key) = &out.hover + && let Some((cmd, params)) = out.hover.as_ref().and_then(|h| pick_command(h, &ids, slot, colors.as_deref())) { - let (cmd, params) = key.apply(&ids, slot); app.preview_text(ctx, cmd, params); } match out.act { - Some(Act::Apply(key)) => { - let (cmd, params) = match &colors { - Some(targets) => key.apply_to_colors(targets), - None => key.apply(&ids, slot), - }; - app.run(cmd, params); - close = true; - } - Some(Act::Bind(pick)) => { - match &colors { - Some(targets) => { - let mut q = json!({"targets": targets, "variable": pick.id}); - if let Some(lib) = &pick.library { - q["library"] = json!(lib); - } - app.run("selection.bindColorVariable", q); - } - None => crate::variable_ui::bind(app, &ids, slot.key(), &pick), + Some(pick @ (Act::Apply(_) | Act::Bind(_))) => { + if let Some((cmd, params)) = pick_command(&pick, &ids, slot, colors.as_deref()) { + app.run(cmd, params); } close = true; } diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index 7b69e32a9..2620a9bf3 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -143,6 +143,42 @@ fn text_styles_preview_on_hover_and_apply_on_click() { assert_eq!(doc.node(t).unwrap().styles.text.as_deref(), doc.style("Type/Heading").map(|s| s.id.as_str())); } +/// Asserts hovering a colour style and a colour variable in a text's fill picker each previews +/// on the text without an edit, and leaving the popover puts the fill back (#3043). +#[test] +fn colour_styles_and_variables_preview_on_hover() { + let (mut s, t) = text_session(); + s.execute("style.create", &json!({"type": "paint", "name": "Shade/500", "value": [{"type": "solid", "color": "#0D99FF"}]})).unwrap(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + s.execute("variable.create", &json!({"collection": "Theme", "name": "accent", "type": "color", "value": "#F24822"})).unwrap(); + let mut app = FigApp::new(s, Box::new(NoServices)); + app.ui.style_grid = false; + let ctx = crate::framework::headless_context(); + let mut time = 0.0; + open_for_selection(&mut app, StyleSlot::Fill, None); + for _ in 0..3 { + frame(&ctx, &mut app, &mut time); + } + let area = ctx.memory(|m| m.area_rect(Id::unique("style_picker_area"))).expect("the picker shows"); + let fills = |app: &FigApp| format!("{:?}", app.session.doc().unwrap().node(t).unwrap().fills); + let (before, undo) = (fills(&app), app.session.ds().unwrap().history.undo.len()); + // Down the popover, noting each fill a hovered row previews: the style's, then the variable's. + let mut previews = std::collections::BTreeSet::new(); + for y in (area.min.y as i32..area.max.y as i32).step_by(4) { + frame_with(&ctx, &mut app, &mut time, vec![egui::Event::PointerMoved(Pos2::new(area.center().x - 40.0, y as f32))]); + frame(&ctx, &mut app, &mut time); + if figcraft_engine::textpreview::active(&app.session) { + previews.insert(fills(&app)); + } + } + assert!(previews.len() >= 2 && !previews.contains(&before), "the style and the variable each preview: {previews:?}"); + assert_eq!(app.session.ds().unwrap().history.undo.len(), undo, "a preview is no edit"); + frame_with(&ctx, &mut app, &mut time, vec![egui::Event::PointerMoved(Pos2::new(600.0, 600.0))]); + frame(&ctx, &mut app, &mut time); + assert!(!figcraft_engine::textpreview::active(&app.session)); + assert_eq!(fills(&app), before); +} + #[test] fn chars_linked_to_several_styles_show_mixed() { let (mut s, t) = text_session(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8644e67fc..5f891ed81 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -309,7 +309,7 @@ when nothing plays). `presentOptions` holds the options the next presentation starts with (`scale`, `deviceFrame`, `comments`, `hotspotHints`, `inspect`, `hideUi`). `viewOnly` is set when the window only presents one file (the browser build's `#present=`): the `file`, and the `note` that says why there is nothing to present (`null` while it presents). -`textPreview` is true while a live text preview shows on the canvas (a hovered text style or named +`textPreview` is true while a live text preview shows on the canvas (a hovered style, colour variable or named instance, a dragged axis slider; see `text.preview` in [mcp.md](mcp.md)). `focus` is keyboard navigation's state: the `region` with the keyboard (`toolbar`, `layers`, `canvas` or `properties`), whether `keyboard` mode is on (F6 or Tab moved the focus since the last diff --git a/docs/mcp.md b/docs/mcp.md index 10acce8a7..aabbf039e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -549,7 +549,8 @@ ArtCraft Launcher's agents switch for FigCraft. 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`, - `library.applyStyle`, `text.setVariations` or `text.style` would do on the canvas without an undo + `library.applyStyle`, `selection.applyColorStyle`, `variable.bind`, `library.bindVariable`, + `selection.bindColorVariable`, `text.setVariations` or `text.style` (among others) would do on the canvas without an undo step (in place of an earlier preview); `text.endPreview` puts the document back. Any other command ends the preview first, so running the command for real commits it as one undo step. - Every mutation is one undo step (`batch` makes several one step). A failing command leaves the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7eb5541..f13e45cd5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -286,7 +286,8 @@ Hours in this narrative are the builders' estimates; the tables above supersede the typography, create from the selected chars, hover to preview on the canvas, "Mixed" when the chars use several styles); text styles link chars, not just layers (what the chars set unlike their style stays linked as a local change, shown as "+N" beside the style's name with Reset to - style, and style edits move the rest, #2435). Live previews of a hovered named instance or font style and of a + style, and style edits move the rest, #2435). Live previews of a hovered named instance or font style, of a + hovered style or colour variable in a style picker (a shade on the selected text or layer, #3043) and of a dragged axis slider (one undo step on release, Escape cancels). Visual QA: list markers keep the paragraph's font, renames start with the name selected and centred, Max lines shows while truncating. Truncation fills the last line shown before the ellipsis ("Lorem consec…", not