Merge main into #2969

This commit is contained in:
bflatastic
2026-12-03 19:02:15 +07:00
15 changed files with 395 additions and 56 deletions
+14
View File
@@ -240,3 +240,17 @@ fn paints_set_with_their_binding_in_the_same_call_keep_it() {
assert_eq!(bound(&s, r), [("fill".to_string(), brand)]);
assert_eq!(fill_hex(&s, r), ["FF0000"], "the binding given with the paints applies");
}
/// `fill.add` with `replace` (the panel's + on mixed fills, #2973): the old fills go with their
/// bindings, and a frame and a shape get the same one default, so the selection shares it.
#[test]
fn a_replacing_fill_takes_the_old_fills_and_their_bindings() {
let (mut s, r) = setup();
let f = id(s.execute("node.create", &json!({"type": "frame", "x": 20, "y": 0, "width": 10, "height": 10})).unwrap());
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "brand"}));
ex(&mut s, "fill.add", json!({"ids": [r, f], "replace": true}));
assert!(bound(&s, r).is_empty(), "the binding goes with its fill");
let fills = |n| s.doc().unwrap().node(n).unwrap().fills.clone();
assert_eq!(fills(r).len(), 1);
assert_eq!(fills(r), fills(f), "the frame and the shape share one paint");
}
+4 -2
View File
@@ -390,11 +390,13 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"fill.add",
"Add fill",
"{ids?, paint? | color? (default #D9D9D9 or white for frames), regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
"{ids?, paint? | color? (default #D9D9D9 or white for frames), replace? (true: it replaces every fill), regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
true,
|s, p| paint_list(s, p, true, true)
),
spec!("stroke.add", "Add stroke", "{ids?, paint? | color? (default black)}", true, |s, p| paint_list(s, p, false, true)),
spec!("stroke.add", "Add stroke", "{ids?, paint? | color? (default black), replace? (true: it replaces every stroke)}", true, |s, p| {
paint_list(s, p, false, true)
}),
spec!("fill.remove", "Remove fill", "{ids?, index, regions?}", true, |s, p| paint_list(s, p, true, false)),
spec!("stroke.remove", "Remove stroke", "{ids?, index}", true, |s, p| paint_list(s, p, false, false)),
spec!(
+17 -2
View File
@@ -389,6 +389,8 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
let cmd = if fills { "fill" } else { "stroke" };
let ids = req_targets(cmd, s, p)?;
let index = if add || get(p, "index").is_none() { None } else { Some(req_index(cmd, p, "index")?) };
// `replace`: the new paint takes the place of every paint (a mixed selection's + in the panel).
let replace = add && boolean(p, "replace").unwrap_or(false);
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills) {
let paint = match get(p, "paint").or_else(|| get(p, "color")) {
Some(v) => Some(paint_of(v).ok_or_else(|| bad(cmd, "invalid paint"))?),
@@ -396,6 +398,9 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
};
edit_region_fills(s.doc_mut()?, id, &regions, |list| {
if add {
if replace {
list.clear();
}
list.push(paint.clone().unwrap_or_else(|| figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)));
} else {
let idx = index.unwrap_or(list.len().saturating_sub(1));
@@ -408,6 +413,8 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
return ok();
}
let doc = s.doc_mut()?;
// A replacing default is the first layer's, so every layer shares the one paint.
let first_frame = ids.first().and_then(|i| doc.node(*i)).is_some_and(|n| n.kind.is_frame_like());
for i in ids {
let n = doc.get_mut(i)?;
// A removal that names no paint among the rows shown changes nothing, the characters' own
@@ -422,7 +429,12 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
if fills {
crate::cmd::lists::take_character_fills(n);
}
let frameish = n.kind.is_frame_like();
let kind = if fills { crate::cmd::lists::BoundList::Fills } else { crate::cmd::lists::BoundList::Strokes };
if replace {
// The replaced paints' bindings go with them.
crate::cmd::lists::remap_list_bindings(n, kind, |_| None);
}
let frameish = if replace { first_frame } else { n.kind.is_frame_like() };
let list = if fills { &mut n.fills } else { &mut n.strokes };
if add {
let paint = match get(p, "paint").or_else(|| get(p, "color")) {
@@ -431,11 +443,14 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
None if fills => figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE),
None => figcraft_color::Paint::solid(figcraft_color::Color::BLACK),
};
if replace {
list.clear();
}
list.push(paint);
} else {
let idx = index.unwrap_or(list.len().saturating_sub(1));
// The paint's colour binding goes with it; later paints' move down one.
crate::cmd::lists::remove_item(n, if fills { crate::cmd::lists::BoundList::Fills } else { crate::cmd::lists::BoundList::Strokes }, idx);
crate::cmd::lists::remove_item(n, kind, idx);
}
}
ok()
+17 -6
View File
@@ -926,20 +926,31 @@ pub(crate) fn bind_variable(cmd: &str, doc: &mut Document, ids: &[NodeId], field
}
}
}
use super::lists::{BoundList, list_binding, paint_binding_key};
// `fill` and `fills/0/color` name the same paint colour: binding through one replaces the other.
let slot = match list_binding(field) {
Some((l @ (BoundList::Fills | BoundList::Strokes), i, "color")) => Some((l == BoundList::Fills, i)),
_ => None,
};
for i in ids {
let n = doc.get_mut(*i)?;
let prev = match slot {
Some((fills, idx)) => paint_binding_key(n, fills, idx).and_then(|k| n.bound.get(k)).cloned(),
None => n.bound.get(field).cloned(),
};
let had = match slot {
Some((fills, idx)) => unbind_slot(n, fills, idx),
None => n.bound.remove(field).is_some(),
};
match vid {
Some(v) => {
if n.bound.get(field).map(String::as_str) != Some(v) {
if prev.as_deref() != Some(v) {
rebind_paint_alpha(&mut n.fills, &mut n.strokes, field, true);
}
n.bound.insert(field.to_string(), v.to_string());
}
None => {
if n.bound.remove(field).is_some() {
rebind_paint_alpha(&mut n.fills, &mut n.strokes, field, false);
}
}
None if had => rebind_paint_alpha(&mut n.fills, &mut n.strokes, field, false),
None => {}
}
}
Ok(())
+14
View File
@@ -288,3 +288,17 @@ fn instance_properties_bind_to_boolean_and_string_variables() {
ex(&mut s, "component.detach", json!({"ids": [i]}));
assert!(node(&s, i).bound.is_empty());
}
#[test]
fn binding_a_paint_through_another_key_replaces_its_binding() {
let mut s = Session::new();
vars(&mut s);
ex(&mut s, "variable.create", json!({"collection": "T", "name": "accent", "type": "color", "value": "#00FF00"}));
let r = rect(&mut s);
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fills/0/color", "variable": "brand"}));
// `fill` names the same paint: the change replaces the indexed binding, and a detach leaves none.
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "accent"}));
assert_eq!(node(&s, r).bound.len(), 1);
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": null}));
assert!(node(&s, r).bound.is_empty(), "the old binding is gone too: {:?}", node(&s, r).bound);
}
@@ -0,0 +1,128 @@
//! A paint whose colour is bound to a variable shows the variable's name in a chip; a click on it
//! opens a picker to change it: the only paint of a list the style picker (styles and colour
//! variables), one of several the variable picker for that paint. Either marks the variable the
//! paint uses now.
use egui::accesskit::{Role, Toggled};
use egui::{Pos2, pos2};
use figcraft_doc::NodeId;
use figcraft_engine::Session;
use serde_json::json;
use crate::layers_drag_tests::Ui;
/// A selected rectangle with `fills` solid fills, the top one bound to the colour variable
/// "text/secondary" (beside "text/primary").
fn bound_rect(fills: usize) -> (Ui, NodeId) {
let mut s = Session::new();
let r = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
for _ in 1..fills {
s.execute("fill.add", &json!({"ids": [r]})).unwrap();
}
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
s.execute("variable.create", &json!({"collection": "Theme", "name": "text/primary", "type": "color", "value": "#000000"})).unwrap();
let v = s.execute("variable.create", &json!({"collection": "Theme", "name": "text/secondary", "type": "color", "value": "#808080"})).unwrap();
let key = if fills == 1 { "fill".to_string() } else { format!("fills/{}/color", fills - 1) };
s.execute("variable.bind", &json!({"ids": [r], "field": key, "variable": v["id"]})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
u.frame(vec![]);
(u, r)
}
/// The middle of the chip showing the variable `name`.
fn chip(u: &mut Ui, name: &str) -> Pos2 {
u.frame(vec![]);
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let n = nodes
.iter()
.map(|(_, n)| n)
.find(|n| n.role() == Role::ComboBox && n.value() == Some(name))
.unwrap_or_else(|| panic!("no chip showing {name:?}"));
let b = n.bounds().expect("bounds");
pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
}
/// Whether the open picker's row of the variable `name` is marked as the one in use.
fn marked(u: &mut Ui, name: &str) -> bool {
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let row = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::RadioButton && n.label() == Some(name));
row.unwrap_or_else(|| panic!("no picker row {name:?}")).toggled() == Some(Toggled::True)
}
/// The open picker's row of the variable `name` and the search field above its list, as
/// `(row top, row bottom, search bottom)`.
fn row_under_search(u: &mut Ui, name: &str) -> (f64, f64, f64) {
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let row = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::RadioButton && n.label() == Some(name)).expect("the row");
let search = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::TextInput).expect("the search field");
let (r, s) = (row.bounds().expect("row bounds"), search.bounds().expect("search bounds"));
(r.y0, r.y1, s.y1)
}
fn click(u: &mut Ui, p: Pos2) {
u.button(p, true);
u.button(p, false);
u.frame(vec![]);
}
#[test]
fn the_chip_of_the_only_fill_opens_the_style_picker() {
let (mut u, _) = bound_rect(1);
let p = chip(&mut u, "text/secondary");
click(&mut u, p);
assert!(u.app.ui.style_picker.is_some(), "the style picker opens");
assert!(!crate::variable_ui::picker_open(&u.ctx));
assert!(marked(&mut u, "text/secondary"), "the variable in use is marked");
assert!(!marked(&mut u, "text/primary"));
}
#[test]
fn the_chip_of_one_of_several_fills_opens_the_variable_picker() {
let (mut u, r) = bound_rect(2);
let p = chip(&mut u, "text/secondary");
click(&mut u, p);
assert!(crate::variable_ui::picker_open(&u.ctx), "the variable picker opens");
assert!(u.app.ui.style_picker.is_none());
assert!(!u.app.session.doc().unwrap().node(r).unwrap().bound.is_empty(), "opening it changes nothing");
assert!(marked(&mut u, "text/secondary"), "the variable in use is marked");
assert!(!marked(&mut u, "text/primary"));
}
#[test]
fn the_picker_opens_scrolled_to_the_variable_in_use() {
let (mut u, _) = bound_rect(1);
for i in 0..40 {
u.app.run("style.create", json!({"type": "paint", "name": format!("Swatch {i:02}"), "value": "#00ff00"}));
}
let p = chip(&mut u, "text/secondary");
click(&mut u, p);
u.frame(vec![]);
let (top, bottom, search) = row_under_search(&mut u, "text/secondary");
assert!(top > search && bottom < search + 360.0, "the row in use is in view below the search field: {top}..{bottom}, search ends at {search}");
assert!(marked(&mut u, "text/secondary"));
}
#[test]
fn with_a_style_linked_too_the_picker_opens_at_the_variable() {
let (mut u, r) = bound_rect(1);
for i in 0..40 {
u.app.run("style.create", json!({"type": "paint", "name": format!("Swatch {i:02}"), "value": "#00ff00"}));
}
// The first style, at the list's top, links the paint while the variable stays bound to it,
// as a file can have them (the commands keep one or the other).
let v = u.app.session.doc().unwrap().node(r).unwrap().bound["fill"].clone();
u.app.run("style.apply", json!({"ids": [r], "style": "Swatch 00", "target": "fill"}));
u.app.session.doc_mut().unwrap().get_mut(r).unwrap().bound.insert("fill".into(), v);
let n = u.app.session.doc().unwrap().node(r).unwrap().clone();
assert!(n.styles.fill.is_some() && !n.bound.is_empty(), "both links: {:?} {:?}", n.styles.fill, n.bound);
let p = chip(&mut u, "text/secondary");
click(&mut u, p);
u.frame(vec![]);
let (top, bottom, search) = row_under_search(&mut u, "text/secondary");
assert!(top > search && bottom < search + 360.0, "the variable's row is in view: {top}..{bottom}, search ends at {search}");
}
+2
View File
@@ -67,6 +67,8 @@ mod board_mind_outline_ui_tests;
mod board_picker_tests;
#[cfg(test)]
mod board_ui_tests;
#[cfg(test)]
mod bound_paint_chip_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod chat_tests;
#[cfg(test)]
+29 -13
View File
@@ -175,21 +175,37 @@ fn an_empty_sections_header_adds_its_item_but_a_full_one_only_adds_from_the_plus
assert_eq!(u.app.session.doc().unwrap().node(r).unwrap().strokes.len(), 1);
}
/// The + of a mixed selection replaces every layer's paints with one they share, opens its picker,
/// and one undo brings the old paints back (#2973).
#[test]
fn adding_a_fill_to_mixed_fills_opens_no_picker() {
let mut s = Session::new();
let a = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 50, "height": 50})).unwrap());
s.execute("fill.add", &json!({"ids": [b]})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
fn adding_a_paint_to_mixed_paints_replaces_them_with_one() {
for (fills, label) in [(true, "Add fill"), (false, "Add stroke")] {
let mut s = Session::new();
let a = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 50, "height": 50})).unwrap());
let add = if fills { "fill.add" } else { "stroke.add" };
s.execute(add, &json!({"ids": [a], "color": "#FF0000"})).unwrap();
s.execute(add, &json!({"ids": [b], "color": "#00FF00"})).unwrap();
s.execute(add, &json!({"ids": [b], "color": "#0000FF"})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let paints = |s: &Session, n: NodeId| {
let n = s.doc().unwrap().node(n).unwrap();
if fills { n.fills.clone() } else { n.strokes.clone() }
};
let before = (paints(&s, a), paints(&s, b));
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
let add_fill = button(&mut u, "Add fill");
click(&mut u, add_fill);
let doc = u.app.session.doc().unwrap();
assert_eq!((doc.node(a).unwrap().fills.len(), doc.node(b).unwrap().fills.len()), (2, 3));
assert_eq!(u.app.ui.picker, None);
let add_button = button(&mut u, label);
click(&mut u, add_button);
let (pa, pb) = (paints(&u.app.session, a), paints(&u.app.session, b));
assert_eq!(pa.len(), 1, "{label}: one paint is left");
assert_eq!(pa, pb, "{label}: the layers share it");
assert_eq!(u.app.ui.picker, Some(PickerTarget::Paint { fills, index: 0, ids: vec![a, b] }), "{label}: its picker opens");
u.app.run("edit.undo", json!({}));
assert_eq!((paints(&u.app.session, a), paints(&u.app.session, b)), before, "{label}: one undo restores them");
}
}
/// The shared popover's closing reaches the colour picker: a press on the canvas closes it.
+3 -1
View File
@@ -373,7 +373,9 @@ fn page_section(app: &mut FigApp, ui: &mut Ui, doc: &Document) {
let (sw, opacity) =
widgets::paint_field(ui, Id::unique("pagebg_swatch"), Id::unique("pagebg_a"), &p, ui.available_width(), |child, text_r| {
if let Some(name) = &bound {
crate::variable_ui::paint_chip(app, child, &[page], "background", name, text_r, Id::unique("pagebg_bound"));
if crate::variable_ui::paint_chip(app, child, &[page], "background", name, text_r, Id::unique("pagebg_bound")) {
crate::variable_ui::open(child, &[page], "background", VariableType::Color, text_r.left_bottom());
}
return;
}
hex_area = Some(text_r);
+17 -6
View File
@@ -370,11 +370,11 @@ pub(crate) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI
let (clicked, header) = widgets::section_header_resp(ui, title, &buttons, empty);
if let Some(i) = clicked {
if buttons.get(i).is_some_and(|(icon, _)| *icon == Icon::Plus) {
// The new paint goes on top; open its picker. A mixed selection has no one index to edit.
if app.run(if fills { "fill.add" } else { "stroke.add" }, json!({"ids": ids})).is_some()
&& let Some(l) = &list
{
app.open_picker(crate::colorpicker::PickerTarget::Paint { fills, index: l.len(), ids: ids.clone() }, Some(header.rect));
// The new paint goes on top and its picker opens; on a mixed selection it replaces every
// layer's paints, so the one paint they then share is edited across them all (#2973).
if app.run(if fills { "fill.add" } else { "stroke.add" }, json!({"ids": ids, "replace": list.is_none()})).is_some() {
let index = list.as_ref().map_or(0, |l| l.len());
app.open_picker(crate::colorpicker::PickerTarget::Paint { fills, index, ids: ids.clone() }, Some(header.rect));
}
} else {
style_picker::open(app, ui, &ids, slot);
@@ -557,7 +557,18 @@ fn paint_row(
match &display.kind {
PaintKind::Solid { .. } if bound.is_some() => {
let (key, name) = bound.clone().unwrap_or_default();
crate::variable_ui::paint_chip(app, child, &ids, &key, &name, text_r, Id::unique(("bound_paint", fills, i)));
if crate::variable_ui::paint_chip(app, child, &ids, &key, &name, text_r, Id::unique(("bound_paint", fills, i))) {
// The only paint opens the style picker the section's Styles button does (styles
// and colour variables); one of several opens the variable picker for itself.
let only = app.session.doc().ok().is_some_and(|d| {
ids.iter().all(|id| d.node(*id).is_some_and(|n| if fills { n.fills.len() } else { n.strokes.len() } == 1))
});
if only {
style_picker::open(app, child, &ids, if fills { StyleSlot::Fill } else { StyleSlot::Stroke });
} else {
crate::variable_ui::open(child, &ids, &key, VariableType::Color, text_r.left_bottom());
}
}
}
PaintKind::Solid { color } => {
let hex = shown.unwrap_or(*color).to_hex();
+90 -16
View File
@@ -43,6 +43,12 @@ struct Picker {
at: Pos2,
}
/// Open `p` (one picker at a time), its row in use scrolled into view.
fn open_picker(ui: &Ui, p: Picker) {
ask_reveal(ui.ctx());
ui.data_mut(|d| d.insert_temp(picker_id(), p));
}
/// Stable egui id for the variable picker.
fn picker_id() -> Id {
Id::unique("variable_picker")
@@ -50,12 +56,58 @@ fn picker_id() -> Id {
/// The variable `field` is bound to on every one of `ids` (its name), if they agree.
pub fn bound_name(doc: &Document, ids: &[NodeId], field: &str) -> Option<String> {
bound_id(doc, ids, field).and_then(|id| doc.variables.get_by_id(&id).map(|v| v.name.clone()))
}
/// The variable `field` is bound to on every one of `ids` (its id in this document), if they agree.
pub fn bound_id(doc: &Document, ids: &[NodeId], field: &str) -> Option<VariableId> {
let mut it = ids.iter().map(|i| doc.node(*i).and_then(|n| n.bound.get(field)).cloned());
let first = it.next().flatten()?;
if !it.all(|v| v.as_ref() == Some(&first)) {
return None;
it.all(|v| v.as_ref() == Some(&first)).then_some(first)
}
fn reveal_id() -> Id {
Id::unique("picker_reveal_current")
}
/// A picker opening now: its first frame scrolls the row in use into view
/// ([`reveal_if_asked`]), then [`end_reveal`] lets the list be scrolled freely.
pub fn ask_reveal(ctx: &egui::Context) {
ctx.data_mut(|d| d.insert_temp(reveal_id(), true));
}
/// Drop a pending [`ask_reveal`], so rows drawn before the one to reveal don't take it.
pub fn cancel_reveal(ctx: &egui::Context) {
ctx.data_mut(|d| d.remove_temp::<bool>(reveal_id()));
}
/// Scroll `rect` (the row in use) to the middle of its list when the picker has just opened, at
/// once rather than animated, so the list opens there. A popup's first pass only measures it, so
/// the request waits for the pass that is shown.
pub fn reveal_if_asked(ui: &Ui, rect: Rect) {
if ui.data(|d| d.get_temp::<bool>(reveal_id())).unwrap_or(false) {
ui.scroll_to_rect_animation(rect, Some(egui::Align::Center), egui::style::ScrollAnimation::none());
if !ui.is_sizing_pass() {
ui.data_mut(|d| d.remove_temp::<bool>(reveal_id()));
}
}
}
/// The picker's first shown frame is over (`ui` its list's): nothing more scrolls by itself.
pub fn end_reveal(ui: &Ui) {
if !ui.is_sizing_pass() {
ui.data_mut(|d| d.remove_temp::<bool>(reveal_id()));
}
}
/// Whether `v`, listed from `lib` (None: this file), is the variable `current` (an id in this
/// document): itself, or for a library variable the copy this document made of it.
pub fn is_current(doc: &Document, current: Option<&str>, lib: Option<&PublishedLibrary>, v: &Variable) -> bool {
let Some(current) = current else { return false };
match lib {
None => v.id == current,
Some(l) => doc.libraries.variables.iter().any(|r| r.library == l.manifest.id && r.key == v.id && r.local == current),
}
doc.variables.get_by_id(&first).map(|v| v.name.clone())
}
/// A variable a picker offers: one of this file's, or a published one of an enabled library.
@@ -186,11 +238,12 @@ pub fn mode_rows<'a>(doc: &'a Document, libs: &'a [Arc<PublishedLibrary>]) -> Ve
out
}
/// A picker row: the variable's swatch (colours) or icon, its name and (other types) its value in
/// the default modes; true when clicked.
pub fn variable_row(ui: &mut Ui, vars: &Variables, v: &Variable, width: f32) -> bool {
/// 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 {
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);
if resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(5), t.menu_hover);
}
@@ -200,9 +253,17 @@ pub fn variable_row(ui: &mut Ui, vars: &Variables, v: &Variable, width: f32) ->
Some(VariableValue::Color(c)) => widgets::paint_swatch(ui.painter(), lead, &figcraft_color::Paint::solid(*c)),
_ => icons::paint(ui.painter(), lead.shrink(1.0), Icon::Variable, t.menu_text),
}
let name_r = Rect::from_min_max(pos2(r.min.x + 26.0, r.min.y), pos2(r.max.x - 6.0, r.max.y));
let end = if current {
reveal_if_asked(ui, r);
let check = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(12.0, 12.0));
icons::paint(ui.painter(), check, Icon::Check, t.menu_text);
check.min.x - 4.0
} else {
r.max.x - 6.0
};
let name_r = Rect::from_min_max(pos2(r.min.x + 26.0, r.min.y), pos2(end, r.max.y));
if let Some(val) = value.filter(|v| !matches!(v, VariableValue::Color(_))) {
ui.painter().text(pos2(r.max.x - 6.0, r.center().y), Align2::RIGHT_CENTER, val.display(), regular(11.0), t.menu_dim);
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()
@@ -221,25 +282,25 @@ pub fn group_caption(ui: &mut Ui, lib: Option<&PublishedLibrary>, coll: &Collect
/// Open the picker for `field` of `ids` at `at`.
pub fn open(ui: &Ui, ids: &[NodeId], field: &str, kind: VariableType, at: Pos2) {
let target = Target::Bind { ids: ids.to_vec(), field: field.to_string() };
ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: Some(kind), at }));
open_picker(ui, Picker { target, kind: Some(kind), at });
}
/// Open the picker at `at` to pick a variable (of `kind`, or any) for a prototype action.
pub fn open_proto(ui: &Ui, slot: crate::proto_editor::VarSlot, kind: Option<VariableType>, at: Pos2) {
ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target: Target::Proto(slot), kind, at }));
open_picker(ui, Picker { target: Target::Proto(slot), kind, at });
}
/// Open the picker at `at` to bind a variable of `kind` to `field` of the shared style `style`.
pub fn open_style(ui: &Ui, style: &str, field: &str, kind: VariableType, at: Pos2) {
let target = Target::Style { style: style.to_string(), field: field.to_string() };
ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: Some(kind), at }));
open_picker(ui, Picker { target, kind: Some(kind), at });
}
/// Open the picker at `at` to bind a string (face name) or number (weight) variable to the weight of
/// the shared text style `style`.
pub fn open_style_weight(ui: &Ui, style: &str, at: Pos2) {
let target = Target::StyleWeight { style: style.to_string() };
ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: None, at }));
open_picker(ui, Picker { target, kind: None, at });
}
/// Where the open picker is on screen (clicks in it don't close what opened it).
@@ -255,7 +316,7 @@ pub fn picker_open(ctx: &egui::Context) -> bool {
/// Open the picker at `at` to alias `variable`'s value in `mode` to another variable.
pub fn open_alias(ui: &Ui, variable: &str, mode: &str, kind: VariableType, at: Pos2) {
let target = Target::Alias { variable: variable.to_string(), mode: mode.to_string() };
ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: Some(kind), at }));
open_picker(ui, Picker { target, kind: Some(kind), at });
}
/// Open the picker for `field` of `ids` under the pointer (from a section header button).
@@ -390,7 +451,8 @@ pub fn bindable(
/// In a paint field's text area `text_r`: the chip of the colour variable `name` that `key` of
/// `ids` is bound to (its last path part, the whole name on hover) and a button that detaches it.
pub fn paint_chip(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], key: &str, name: &str, text_r: Rect, id: Id) {
/// The chip is a button: true when it was clicked, for the caller to open a picker to change it.
pub fn paint_chip(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], key: &str, name: &str, text_r: Rect, id: Id) -> bool {
let t = Tokens::get(ui.ctx());
let r = ui.max_rect();
let chip = Rect::from_min_max(pos2(text_r.min.x - 2.0, r.min.y + 3.0), pos2(text_r.max.x - 20.0, r.max.y - 3.0));
@@ -404,13 +466,20 @@ pub fn paint_chip(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], key: &str, name
regular(11.0),
t.text,
);
let _ = ui.interact(chip, id, Sense::hover()).on_hover_text(name);
let resp = ui.interact(chip, id, Sense::click());
crate::a11y::combo(&resp, tr("Variable"), name, false);
if resp.hovered() {
ui.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.field_hover_border), egui::StrokeKind::Inside);
}
let clicked = resp.on_hover_text(name).clicked();
let dr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
let dresp = ui.interact(dr, id.with("detach"), Sense::click()).tip(tr("Detach variable"));
icons::paint(ui.painter(), dr.shrink(3.0), Icon::Detach, t.icon_secondary);
if dresp.clicked() {
app.run("variable.bind", json!({"ids": ids, "field": key, "variable": null}));
return false;
}
clicked
}
/// A variable button at the right end of `rect` while the pointer is over it: opens the picker
@@ -484,6 +553,10 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) {
Target::Bind { field, .. } => Some(field.as_str()),
_ => None,
};
let current = match &p.target {
Target::Bind { ids, field } => bound_id(&doc, ids, field),
_ => None,
};
let keep = |lib: Option<&PublishedLibrary>, v: &Variable| {
kind_fits(p.kind, field, v.kind)
&& !(local_only && lib.is_some())
@@ -523,12 +596,13 @@ 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) {
if variable_row(ui, all, v, 224.0, is_current(&doc, current.as_deref(), *lib, v)) {
chosen = Some(Pick { library: lib.map(|l| l.manifest.id.clone()), id: v.id.clone() });
}
}
}
});
end_reveal(ui);
if groups.is_empty() {
// Whole sentences per type: languages place the type differently.
let (fit, none) = match p.kind {
@@ -112,6 +112,12 @@ fn the_rows_styles_button_opens_the_style_picker_with_search_and_library_names()
assert_eq!(doc.node(b).unwrap().fills[0].solid_color().unwrap().to_hex(), "008080");
assert!(doc.node(a).unwrap().bound.is_empty());
assert!(u.app.ui.last_error.is_none());
// Opened again, the picker marks the library variable the row uses (by its copy here).
open_picker(&mut u, "Sea");
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let sea = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::RadioButton && n.label() == Some("Sea")).expect("the picker's Sea row");
assert_eq!(sea.toggled(), Some(egui::accesskit::Toggled::True), "the variable in use is marked");
let _ = std::fs::remove_dir_all(&dir);
}
+4 -4
View File
@@ -78,20 +78,20 @@ fn differently_coloured_characters_show_as_mixed_content_and_plus_replaces_them(
let (rows, note, plus) = fill_section(&c);
assert!(note, "the Fill section shows the note: {c:?}");
assert!(rows.is_empty(), "no row for the layer's own red: {rows:?}");
// + adds a fill on top of the layer's: every character shows the layer's fills now.
// + replaces the mixed fills with one the layer and every character share (#2973).
let steps = u.app.session.ds().unwrap().history.undo.len();
u.button(plus, true);
u.button(plus, false);
u.frame(vec![]);
let n = u.app.session.doc().unwrap().node(t).unwrap().clone();
assert_eq!(n.fills.len(), 2, "the new fill on the layer's: {:?}", n.fills);
assert_eq!(n.fills.len(), 1, "one fill replaces them: {:?}", n.fills);
assert!(n.kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own");
assert!(fills_shown(&u, t).iter().all(|f| f == "FF0000+D9D9D9"), "{:?}", fills_shown(&u, t));
assert!(fills_shown(&u, t).iter().all(|f| f == "D9D9D9"), "{:?}", fills_shown(&u, t));
assert_eq!(u.app.session.ds().unwrap().history.undo.len(), steps + 1, "one undo step");
let c = controls(&mut u);
let (rows, note, _) = fill_section(&c);
assert!(!note, "no note once the characters agree: {c:?}");
assert_eq!(rows, ["D9D9D9", "FF0000"], "the new fill above the layer's red: {c:?}");
assert_eq!(rows, ["D9D9D9"], "only the new fill: {c:?}");
}
#[test]
+47 -4
View File
@@ -167,6 +167,8 @@ pub struct Picker {
/// The Selection colors row it was opened for: a pick applies to these paints
/// (`selection.*` commands) instead of `slot` of `ids`.
colors: Option<Vec<PaintTarget>>,
/// Just opened: the next list scrolls the style or variable in use into view.
reveal: bool,
}
/// The source menu's choice: every source, this file's styles, or one enabled library's (by
@@ -203,7 +205,8 @@ pub fn open(app: &mut FigApp, ui: &Ui, ids: &[NodeId], slot: StyleSlot) {
// Opening the style picker closes the colour picker (it would linger beside it).
crate::colorpicker::close(app);
app.ui.style_picker_popover = None;
app.ui.style_picker = Some(Picker { slot, ids: ids.to_vec(), y, query: String::new(), edit: None, source: Source::All, colors: None });
app.ui.style_picker =
Some(Picker { slot, ids: ids.to_vec(), y, query: String::new(), edit: None, source: Source::All, colors: None, reveal: true });
}
/// Open the picker for a Selection colors row, level with the pointer: the style or colour
@@ -222,7 +225,7 @@ pub fn open_for_selection(app: &mut FigApp, slot: StyleSlot, style: Option<&str>
let edit = style.and_then(|s| app.session.doc().ok()?.style(s).map(editing));
crate::colorpicker::close(app);
app.ui.style_picker_popover = None;
app.ui.style_picker = Some(Picker { slot, ids, y: 140.0, query: String::new(), edit, source: Source::All, colors: None });
app.ui.style_picker = Some(Picker { slot, ids, y: 140.0, query: String::new(), edit, source: Source::All, colors: None, reveal: true });
}
fn editing(s: &Style) -> Editing {
@@ -235,6 +238,23 @@ fn colors_link(doc: &Document, ids: &[NodeId], targets: &[PaintTarget]) -> Optio
Some(selection_colors::collect(doc, ids).into_iter().find(|c| c.targets == targets).and_then(|c| c.style))
}
/// The colour variable the picker's paints use now (its id in this document): a Selection colors
/// row's `colors`, else the first paint of `slot` of `ids` when they all use the same one.
fn bound_variable(doc: &Document, ids: &[NodeId], slot: StyleSlot, colors: Option<&[PaintTarget]>) -> Option<String> {
if let Some(targets) = colors {
return selection_colors::collect(doc, ids).into_iter().find(|c| c.targets == targets).and_then(|c| c.variable);
}
if !slot.paints() {
return None;
}
let fills = slot == StyleSlot::Fill;
let mut it = ids
.iter()
.map(|id| doc.node(*id).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, 0).and_then(|k| n.bound.get(k).cloned())));
let first = it.next().flatten()?;
it.all(|v| v.as_ref() == Some(&first)).then_some(first)
}
/// The style `slot` of `ids` links to: `Some(Some(id))` one style, `Some(None)` none, None when
/// they differ. Text goes by chars: the selected chars of the text being edited, else every char.
fn link_of(app: &FigApp, doc: &Document, ids: &[NodeId], slot: StyleSlot) -> Option<Option<String>> {
@@ -540,6 +560,9 @@ fn style_row(ui: &mut Ui, s: &Style, key: Key, slot: StyleSlot, applied: bool, e
} else if applied {
icons::paint(ui.painter(), edit_r.shrink(5.0), Icon::Check, t.menu_text);
}
if applied {
crate::variable_ui::reveal_if_asked(ui, r);
}
let tip = match (s.description.is_empty(), text_def(s)) {
(true, None) if !s.bound.is_empty() => Some(format!("{}\n{}", s.name, tr("Uses variables: each layer shows them in its own mode"))),
(true, None) => None,
@@ -585,6 +608,7 @@ fn style_grid(ui: &mut Ui, list: &[(&Style, Key)], applied: Option<&Key>, editab
}
if applied == Some(key) {
ui.painter().rect_stroke(r.expand(2.0), CornerRadius::same(5), Stroke::new(2.0, crate::theme::ACCENT), egui::StrokeKind::Inside);
crate::variable_ui::reveal_if_asked(ui, r);
} else if resp.hovered() && !text {
ui.painter().rect_stroke(r.expand(2.0), CornerRadius::same(4), Stroke::new(1.0, t.menu_text), egui::StrokeKind::Inside);
}
@@ -642,6 +666,7 @@ fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut
None => link_of(app, doc, &p.ids, slot),
};
let applied = link.clone().flatten().map(|id| Key::of_local(doc, &id));
let current = bound_variable(doc, &p.ids, slot, p.colors.as_deref());
let grid = slot.has_grid() && app.ui.style_grid;
// The title is the popover's; this row keeps the view toggle, detach and create.
let (hr, _) = ui.allocate_exact_size(vec2(W, 24.0), Sense::hover());
@@ -709,6 +734,19 @@ fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut
} else {
Vec::new()
};
let reveal = p.reveal;
// A popup's first pass only measures it: the shown pass asks again.
p.reveal = reveal && ui.is_sizing_pass();
// The variable in use is revealed over the style in use (its chip opened the picker), so the
// request waits for its row, after the styles.
let reveal_var =
reveal && colors.iter().any(|(lib, _, vars)| vars.iter().any(|v| crate::variable_ui::is_current(doc, current.as_deref(), *lib, v)));
if reveal_var {
// The measuring pass's request is still pending: the style rows mustn't take it.
crate::variable_ui::cancel_reveal(ui.ctx());
} else if reveal {
crate::variable_ui::ask_reveal(ui.ctx());
}
egui::ScrollArea::vertical().id_salt("style_picker_scroll").max_height(320.0).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
if sources.iter().all(|(_, l)| l.is_empty()) {
@@ -774,16 +812,20 @@ fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut
ui.add_space(6.0);
caption(ui, tr("Color variables"));
}
if reveal_var {
crate::variable_ui::ask_reveal(ui.ctx());
}
for (lib, c, vars) in &colors {
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) {
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() }));
}
}
}
});
crate::variable_ui::end_reveal(ui);
}
/// One property row in the editor (a paint, an effect, a grid); paints open the colour picker.
@@ -1407,7 +1449,8 @@ fn edit_local(app: &mut FigApp, ui: &Ui, slot: StyleSlot, id: &str) {
let edit = app.session.doc().ok().and_then(|d| d.style(id).map(editing));
crate::colorpicker::close(app);
app.ui.style_picker_popover = None;
app.ui.style_picker = Some(Picker { slot, ids: app.session.selection(), y, query: String::new(), edit, source: Source::All, colors: None });
app.ui.style_picker =
Some(Picker { slot, ids: app.session.selection(), y, query: String::new(), edit, source: Source::All, colors: None, reveal: true });
}
/// `style.move` for the shown style `from` dropped at shown position `to` (`shown` in display
+3 -2
View File
File diff suppressed because one or more lines are too long