Merge pull request #9326 from dotCooCoo/fix/gradient-panel-rows-wrap

Gradient panel: rows wrap so the panel stays inside its dock column
This commit is contained in:
BFlat
2026-11-26 16:49:00 +07:00
committed by GitHub
4 changed files with 248 additions and 96 deletions
+59 -43
View File
@@ -25,7 +25,7 @@
//! gradient behind the active proxy, keeping its placement (`gradient.presets.*`). Hide Presets in
//! the panel menu leaves the row out.
use craft::behavior::{EditEvent, IconId, Mixed};
use craft::behavior::{ColumnWidth, EditEvent, IconId, Mixed};
use craft::color_ui::gradient::stops::AltDrop;
use craft::color_ui::ui::DropperButton;
use craft::color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, StopDrop, StopRef, StopRow, StopRows, StopRules};
@@ -35,7 +35,8 @@ use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented, Swatch};
use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::display::{Divider, Icon, Shade, Text};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout::CellAlign;
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::notices::Notice;
@@ -66,6 +67,9 @@ use crate::panel_drag::PanelDrag;
/// The Angle field's preset menu, degrees.
const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0];
/// The header's columns: the thumbnail with its swatch menu, and the type buttons with Edit Gradient, each as wide
/// as its content.
const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content];
/// The Aspect Ratio field's preset menu, percent.
const ASPECT_PRESETS: [f64; 9] = [10.0, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 400.0];
// PLAN: the sheet drops `HIDE_OPTIONS` and `HIDE_PRESETS`, but each key is read by `show`, `menu_states` and `run`; kept as the op.A5 hide-store keys.
@@ -171,7 +175,7 @@ pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) {
(GradientKind::Diamond, "dc-grad-diamond", tl!("Diamond Gradient")),
(GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")),
]);
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(tl!("Type:")).shade(Shade::Muted).show(ui);
let pick = Segmented::new(tl!("Type"), lit(kind), &entries).show(ui);
if let Some(k) = pick.events.committed() {
@@ -309,19 +313,23 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
let kind = g.gradient.kind;
let hidden = part_hidden(app, HIDE_OPTIONS);
// Header: the thumbnail and its swatch menu, the type buttons and Edit Gradient.
Row::new().show(ui, |ui, _| {
fill_box(app, ui, &g, is_grad);
if hidden {
if hidden {
Row::new().show(ui, |ui, _| {
fill_box(app, ui, &g, is_grad);
super::proxy(app, ui);
return;
}
Stack::new().show(ui, |ui, _| {
type_row(app, ui);
if Button::new(tl!("Edit Gradient")).show(ui).clicked() {
app.select_tool("gradient");
}
});
});
} else {
// The type buttons go beside the thumbnail, level with its top, or under it in a narrow panel.
Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| fill_box(app, ui, &g, is_grad));
Stack::new().show(ui, |ui, _| {
type_row(app, ui);
if Button::new(tl!("Edit Gradient")).show(ui).clicked() {
app.select_tool("gradient");
}
});
});
}
let freeform = is_grad && kind == GradientKind::Freeform;
let points = is_grad && edits_points(app, &g);
if hidden {
@@ -458,7 +466,7 @@ fn method_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr
]
.map(|(m, label)| Entry::new(m, label));
let current = g.gradient.method;
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(tl!("Method:")).shade(Shade::Muted).show(ui);
let pick = Select::new(tl!("Method"), Bind::given(current), &methods).enabled(is_grad).show(ui);
if let Some(m) = pick.events.committed().filter(|m| **m != current) {
@@ -475,7 +483,7 @@ fn spread_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr
.map(|(s, label)| Entry::new(s, label));
let current = g.gradient.spread;
let presets = number_presets(&REPEAT_PRESETS, "");
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(tl!("Spread:")).shade(Shade::Muted).show(ui);
let pick = Select::new(tl!("Spread"), Bind::given(current), &spreads).enabled(is_grad).show(ui);
if let Some(s) = pick.events.committed().filter(|s| **s != current) {
@@ -690,34 +698,42 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo
}
});
}
Row::new().show(ui, |ui, _| {
Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui);
let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0);
let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui);
apply_number(app, &opacity.edit, |app, v, phase| {
let Some(i) = sel else { return };
let mut v2 = stops.clone();
if let Some(s) = v2.get_mut(i) {
s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32;
}
set_stops(app, &v2, Some(i), phase);
// In a narrow panel the row wraps; each caption stays on the line of its field.
Row::new().wrap(true).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui);
let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0);
let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui);
apply_number(app, &opacity.edit, |app, v, phase| {
let Some(i) = sel else { return };
let mut v2 = stops.clone();
if let Some(s) = v2.get_mut(i) {
s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32;
}
set_stops(app, &v2, Some(i), phase);
});
});
Text::new(tl!("Location:")).shade(Shade::Muted).show(ui);
let loc = match (mid, stop) {
(Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)),
(None, Some(s)) => percent(s.offset),
_ => 0.0,
};
let location =
NumberField::new(tl!("Location"), Bind::given(Some(loc))).range(0.0..=100.0).unit("%").enabled(sel.is_some() || mid.is_some()).show(ui);
apply_number(app, &location.edit, |app, v, phase| {
let v = (v / 100.0) as f32;
if let Some(m) = mid {
set_stops(app, &set_midpoint(stops, m, v), None, phase);
} else if let Some(i) = sel {
let (v2, ni) = move_stop(stops, i, v);
set_stops(app, &v2, Some(ni), phase);
}
Row::new().show(ui, |ui, _| {
Text::new(tl!("Location:")).shade(Shade::Muted).show(ui);
let loc = match (mid, stop) {
(Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)),
(None, Some(s)) => percent(s.offset),
_ => 0.0,
};
let location = NumberField::new(tl!("Location"), Bind::given(Some(loc)))
.range(0.0..=100.0)
.unit("%")
.enabled(sel.is_some() || mid.is_some())
.show(ui);
apply_number(app, &location.edit, |app, v, phase| {
let v = (v / 100.0) as f32;
if let Some(m) = mid {
set_stops(app, &set_midpoint(stops, m, v), None, phase);
} else if let Some(i) = sel {
let (v2, ni) = move_stop(stops, i, v);
set_stops(app, &v2, Some(ni), phase);
}
});
});
let can_del = sel.is_some() && stops.len() > MIN_STOPS;
let delete = IconButton::new(IconId::new("trash-2")).label(tl!("Delete Stop")).tooltip(tl!("Delete Stop")).enabled(can_del).show(ui);
@@ -6,6 +6,7 @@ use egui::{Key, Modifiers, Pos2, pos2, vec2};
use vectorcraft_engine::Session;
use super::*;
use crate::tests::panel_harness::{Place, Shown, floated};
#[test]
fn dropped_colours_recolour_or_add_an_opaque_stop() {
@@ -364,6 +365,85 @@ fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() {
assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays");
}
// ---------- the panel in the app window ----------
/// A selected gradient stop: the panel shows its Color row.
fn select_a_stop(app: &mut VectorcraftApp) {
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
}
/// The Gradient panel shown at `place` in the whole app window over a selected rectangle that `setup` paints, drawn
/// in `lang`, with the catalog strings `names` as `lang` shows them. The Gradient Fill box is always asked for, so a
/// docked panel is found by it.
fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&str]) -> Shown {
let mut app = super::super::tests_appearance::app_with_rect();
setup(&mut app);
let asked: Vec<&str> = names.iter().copied().chain(["Gradient Fill"]).collect();
floated(app, "gradient", lang, place, &asked)
}
/// Docked, every control of the panel stays inside its column, with a solid fill (the panel shows its notice) and
/// with a stop selected (its Color row), in languages with longer words.
#[test]
fn the_gradient_panel_stays_inside_its_dock_column() {
for lang in ["en", "fr", "de"] {
for setup in [|_: &mut VectorcraftApp| {}, select_a_stop] {
let panel = shown(lang, Place::Docked, setup, &[]);
let past = panel.past(panel.nodes.clone());
assert!(past.is_empty(), "past the docked panel in {lang}: {past:?}");
}
}
}
/// In a panel at the narrowest panel width the Type, Method, Spread and stop rows wrap: their controls stay inside
/// the panel, except the last type button. The five type buttons are one `Segmented` control, which keeps its
/// segments on one line, so at this width Freeform Gradient reaches 2 pt past the panel's right edge. The test
/// holds that button to the 2 pt until the widget can wrap its segments.
#[test]
fn the_gradient_rows_wrap_in_a_narrow_panel() {
/// How far Freeform Gradient reaches past the panel's right edge at the narrowest width.
const TYPE_OVERFLOW: f32 = 2.0;
let names = [
"Linear Gradient",
"Radial Gradient",
"Conic Gradient",
"Diamond Gradient",
"Edit Gradient",
"Method",
"Spread",
"Repeats",
"Opacity",
"Location",
"Delete Stop",
];
for lang in ["en", "fr"] {
let asked: Vec<&str> = names.iter().copied().chain(["Freeform Gradient"]).collect();
let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &asked);
let past = panel.past_named(&names);
assert!(past.is_empty(), "past the panel in {lang}: {past:?}");
for freeform in panel.rects("Freeform Gradient") {
let inside = freeform.left() >= panel.body.left() - 0.5 && freeform.right() <= panel.body.right() + TYPE_OVERFLOW + 0.5;
assert!(inside, "Freeform Gradient at {freeform:?} is more than {TYPE_OVERFLOW} pt past {:?} in {lang}", panel.body);
}
}
}
/// In a wide panel the rows stay on one line each, and the thumbnail stays level with the top of the type buttons.
#[test]
fn the_gradient_rows_stay_on_one_line_in_a_wide_panel() {
let rows: [&[&str]; 3] =
[&["Method:", "Method"], &["Spread:", "Spread", "Repeats"], &["Opacity:", "Opacity", "Location:", "Location", "Delete Stop"]];
let names: Vec<&'static str> = rows.iter().flat_map(|row| row.iter().copied()).chain(["Gradient Fill", "Linear Gradient"]).collect();
let panel = shown("en", Place::Floating(400.0), select_a_stop, &names);
for row in rows {
let middles = panel.middles(row);
assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{row:?} is not on one line: {middles:?}");
}
let (thumb, linear) = (panel.rects("Gradient Fill")[0], panel.rects("Linear Gradient")[0]);
assert!((thumb.top() - linear.top()).abs() < 1.0, "the thumbnail {thumb:?} is not level with the type buttons {linear:?}");
}
/// The paints of the selected object's appearance rows, in stack order.
fn row_paints(app: &VectorcraftApp) -> Vec<Paint> {
let st = app.session.active().unwrap();
+6 -52
View File
@@ -1,12 +1,9 @@
//! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width.
use serde_json::json;
use super::tests_appearance::app_with_rect;
use super::*;
use crate::i18n::Lang;
use crate::panel_docking::PANEL_MIN_WIDTH;
use crate::tests::panel_harness::{Panel, ROOM};
use crate::tests::panel_harness::{Panel, Place, ROOM, floated};
#[test]
fn the_arrowhead_row_stays_inside_the_stroke_panel() {
@@ -30,62 +27,19 @@ fn the_color_themes_hex_row_stays_inside_a_narrow_panel() {
}
}
/// Panel `panel` floated `width` wide in the whole app window, drawn in `lang`: the rect of its body, and the rects of
/// the controls named each of `names` (catalog strings, shown in `lang`).
fn floated(panel: &str, lang: &str, width: f32, names: &[&str]) -> (egui::Rect, Vec<(String, Vec<egui::Rect>)>) {
use egui::accesskit::Role;
const AT: f32 = 520.0;
let mut app = app_with_rect();
app.session.prefs.interface_language = lang.into();
app.run("window.panel", json!({ "panel": panel })).unwrap();
app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap();
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
let mut nodes = Vec::new();
for at in 1..=8 {
let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() };
let out = crate::testing::app_frame(&mut app, &ctx, input);
nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes);
}
// The frames set the language from the preference; the names are looked up in it before English is put back.
let shown: Vec<&str> = names.iter().map(|name| crate::i18n::t(name)).collect();
crate::i18n::set_current(Lang::EN);
let rect = |node: &egui::accesskit::Node| {
node.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
};
// The floating panel's body: the tab panel at the left edge the float asked for.
let body = nodes
.iter()
.filter(|(_, n)| n.role() == Role::TabPanel)
.find_map(|(_, n)| rect(n).filter(|r| (r.left() - AT).abs() < 1.0))
.unwrap_or_else(|| panic!("{panel} does not float at x {AT}"));
assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for");
let controls = shown
.into_iter()
.map(|name| {
let found: Vec<egui::Rect> = nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l == name)).filter_map(|(_, n)| rect(n)).collect();
assert!(!found.is_empty(), "{panel} shows no {name:?}");
(name.to_owned(), found)
})
.collect();
(body, controls)
}
/// The controls named `names` (catalog strings, shown in `lang`) that reach past either side of panel `panel`,
/// floated at the narrowest panel width in the whole app window, each with its rect.
fn past_a_narrow_panel(panel: &str, lang: &str, names: &[&str]) -> Vec<String> {
let (body, controls) = floated(panel, lang, PANEL_MIN_WIDTH, names);
let outside = |r: &egui::Rect| r.left() < body.left() - 0.5 || r.right() > body.right() + 0.5;
controls.iter().flat_map(|(name, found)| found.iter().filter(|r| outside(r)).map(move |r| format!("{name} at {r:?}"))).collect()
floated(app_with_rect(), panel, lang, Place::Floating(PANEL_MIN_WIDTH), names).past_named(names)
}
#[test]
fn the_profile_row_stays_on_one_line_in_a_wide_stroke_panel() {
let (_, controls) = floated("stroke", "en", 360.0, &["Profile", "Flip Along", "Flip Across"]);
let names = ["Profile", "Flip Along", "Flip Across"];
let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(360.0), &names);
// The field, its caption, the list and the two buttons share one line, so their middles are level.
let middles: Vec<f32> = controls.iter().flat_map(|(_, found)| found.iter().map(|r| r.center().y)).collect();
assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{controls:?}");
let middles = panel.middles(&names);
assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?}");
}
#[test]
+103 -1
View File
@@ -6,6 +6,7 @@
use std::{
cell::{RefCell, RefMut},
collections::HashMap,
rc::Rc,
};
@@ -13,7 +14,8 @@ use craft::behavior::PartRef;
use craft::ui::runtime::frame::take_output;
use craft::ui::testing::pointer::part_rect_of_node;
use craft::ui::testing::{Fixture, Target};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, vec2};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, pos2, vec2};
use serde_json::json;
use crate::VectorcraftApp;
@@ -361,3 +363,103 @@ impl Panel {
self.fixture.tree().focused_key() == self.look(name).node
}
}
/// Where [`floated`] shows a panel in the app window.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Place {
/// Docked in its column.
Docked,
/// Floating at x 520, this many points wide.
Floating(f32),
}
/// A panel as one frame of the whole app window drew it.
pub(crate) struct Shown {
/// The panel's body.
pub(crate) body: Rect,
/// The name and rect of every named node in the body.
pub(crate) nodes: Vec<(String, Rect)>,
/// Each catalog string asked for, with the text the panel's language shows for it.
names: Vec<(String, String)>,
}
impl Shown {
/// The rects of the nodes named `name` (a catalog string asked for).
pub(crate) fn rects(&self, name: &str) -> Vec<Rect> {
let shown = self.names.iter().find(|(asked, _)| asked == name).map_or(name, |(_, shown)| shown.as_str());
let found: Vec<Rect> = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect();
assert!(!found.is_empty(), "the panel shows no {shown:?}");
found
}
/// The nodes of `nodes` that reach past either side of the body, each with its rect.
pub(crate) fn past(&self, nodes: impl IntoIterator<Item = (String, Rect)>) -> Vec<String> {
let outside = |r: &Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5;
nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect()
}
/// The nodes named each of `names` (catalog strings asked for) that reach past either side of the body, each with
/// its rect.
pub(crate) fn past_named(&self, names: &[&str]) -> Vec<String> {
self.past(names.iter().flat_map(|name| self.rects(name).into_iter().map(|r| ((*name).to_owned(), r))))
}
/// The vertical middles of the nodes named `names`, in order.
pub(crate) fn middles(&self, names: &[&str]) -> Vec<f32> {
names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect()
}
}
/// Panel `panel` of `app` shown at `place` in the whole app window (1440 by 900 pt), drawn in `lang`, with the catalog
/// strings `names` as `lang` shows them. The test sets `app` up before the call. A floating panel's body is the tab
/// panel at the left edge the float asked for; a docked panel's body is the tab panel that shows every one of `names`.
pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: Place, names: &[&str]) -> Shown {
use egui::accesskit::{Node, NodeId, Role};
const AT: f32 = 520.0;
app.session.prefs.interface_language = lang.into();
app.run("window.panel", json!({ "panel": panel })).unwrap();
match place {
Place::Docked => app.run("window.panel.dock", json!({ "panel": panel })).unwrap(),
Place::Floating(width) => app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(),
};
app.run("window.panel.activate", json!({ "panel": panel })).unwrap();
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0));
let mut nodes: Vec<(NodeId, Node)> = Vec::new();
for at in 1..=8 {
let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() };
let out = crate::testing::app_frame(&mut app, &ctx, input);
nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes);
}
// The frames set the language from the preference; the names are looked up in it before English is put back.
let names: Vec<(String, String)> = names.iter().map(|name| ((*name).to_owned(), crate::i18n::t(name).to_owned())).collect();
crate::i18n::set_current(crate::i18n::Lang::EN);
let rect = |node: &Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)));
let by_id: HashMap<NodeId, &Node> = nodes.iter().map(|(id, n)| (*id, n)).collect();
let under = |root: NodeId| {
let mut found = Vec::new();
let mut todo = vec![root];
while let Some(id) = todo.pop() {
let Some(node) = by_id.get(&id) else { continue };
if let (Some(label), Some(r)) = (node.label(), rect(node)) {
found.push((label.to_owned(), r));
}
todo.extend(node.children().iter().copied());
}
found
};
let mut bodies = nodes.iter().filter(|(_, n)| n.role() == Role::TabPanel).filter_map(|(id, n)| Some((rect(n)?, under(*id))));
let found = match place {
Place::Docked => {
assert!(!names.is_empty(), "a docked panel is found by the names it shows");
bodies.find(|(_, named)| names.iter().all(|(_, shown)| named.iter().any(|(label, _)| label == shown)))
}
Place::Floating(_) => bodies.find(|(r, _)| (r.left() - AT).abs() < 1.0),
};
let (body, nodes) = found.unwrap_or_else(|| panic!("no {panel} panel at {place:?} in {lang}"));
if let Place::Floating(width) = place {
assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for");
}
Shown { body, nodes, names }
}