feat(stroke): compact reorderable width profile dropdown (#3527, #10826)

- Add stroke.widthProfile.move and stroke.widthProfile.rename commands and persist width_profile_order / hidden_width_profiles in Prefs
- Replace standard Select with ProfileSelect dropdown featuring inline management footer (Add to Profiles, Delete Profile, Reset Profiles with confirmation), drag/keyboard reordering (keeping Uniform pinned first and undeletable), and deleting non-Uniform built-in profiles
- Save immediately from the dropdown footer using next_profile_name(), hide text captions on user-added dropdown rows while keeping drag reordering and inline rename, shrink closed and opened dropdown widths, and allow expanding vertically when space is available
This commit is contained in:
erolkarino committed 2026-12-05 10:10:16 +03:00
1 parent b36fbc76bd
commit f647b9c734
6 files changed
+1158 -46

No files matched your search

+159 -17
View File
@@ -12,7 +12,7 @@ use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
use super::paint::{live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index_opt, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -68,8 +68,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Profile",
[],
None,
"{name?} remove a saved profile from the Profile list (default: the selected stroke's); built-in profiles can't be deleted, and strokes keep their widths → {deleted}",
has_saved_profiles,
"{name?} remove a built-in or saved profile from the Profile list (default: the selected stroke's); \"uniform\" can't be deleted, and strokes keep their widths → {deleted}",
has_deletable_profiles,
profile_delete
),
cmd!(
@@ -77,10 +77,28 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profiles",
[],
None,
"{} remove every saved profile, leaving the built-ins → {removed: count}",
has_saved_profiles,
"{} remove every saved profile and restore the default built-in profiles and order → {removed: count}",
can_reset_profiles,
profile_reset
),
cmd!(
"stroke.widthProfile.move",
"Move Width Profile",
[],
None,
"{name: profile id or name (not \"uniform\"), to: index among reorderable profiles (0 = first after Uniform, clamped)} reorder a width profile in the Profile list (kept with the preferences) → {order}",
always,
profile_move
),
cmd!(
"stroke.widthProfile.rename",
"Rename Width Profile",
[],
None,
"{name: saved profile name, to: new name (unique, not a built-in's)} rename a saved width profile → {name}",
has_saved_profiles,
profile_rename
),
cmd!(
query "stroke.widthProfile.list",
"Width Profiles",
@@ -710,12 +728,38 @@ impl ProfileEntry<'_> {
}
impl Session {
/// The Profile list: the built-in profiles, then the saved ones.
/// The Profile list: Uniform first, then the built-in and saved profiles in [`Prefs::width_profile_order`].
pub fn profile_entries(&self) -> impl Iterator<Item = ProfileEntry<'_>> {
let built_in = WidthProfile::PRESETS.iter().map(|p| ProfileEntry { id: p.id, label: p.label, points: p.points, built_in: true });
let saved =
self.prefs.width_profiles.iter().map(|p| ProfileEntry { id: &p.name, label: &p.name, points: &p.profile.points, built_in: false });
built_in.chain(saved)
let uniform = WidthProfile::PRESETS[0];
let uniform = ProfileEntry { id: uniform.id, label: uniform.label, points: uniform.points, built_in: true };
let candidates: Vec<ProfileEntry<'_>> = WidthProfile::PRESETS[1..]
.iter()
.filter(|p| !self.prefs.hidden_width_profiles.iter().any(|h| h == p.id))
.map(|p| ProfileEntry { id: p.id, label: p.label, points: p.points, built_in: true })
.chain(self.prefs.width_profiles.iter().map(|p| ProfileEntry { id: &p.name, label: &p.name, points: &p.profile.points, built_in: false }))
.collect();
let mut out = Vec::with_capacity(1 + candidates.len());
out.push(uniform);
if self.prefs.width_profile_order.is_empty() {
out.extend(candidates);
} else {
let mut used = vec![false; candidates.len()];
for id in &self.prefs.width_profile_order {
if id == uniform.id {
continue;
}
if let Some(pos) = candidates.iter().enumerate().position(|(i, e)| !used[i] && e.id == id) {
used[pos] = true;
out.push(candidates[pos]);
}
}
for (i, entry) in candidates.into_iter().enumerate() {
if !used[i] {
out.push(entry);
}
}
}
out.into_iter()
}
/// The Profile list row showing `p` (`None`: the plain stroke), if it is listed.
@@ -735,9 +779,10 @@ impl Session {
(1..).map(|n| format!("Width Profile {n}")).find(|n| !self.profile_name_taken(n)).unwrap_or_default()
}
/// Does a listed profile have `name` as its id or label (ignoring case)?
/// Does a listed or built-in profile have `name` as its id or label (ignoring case)?
fn profile_name_taken(&self, name: &str) -> bool {
self.profile_entries().any(|e| e.id.eq_ignore_ascii_case(name) || e.label.eq_ignore_ascii_case(name))
|| WidthProfile::PRESETS.iter().any(|b| b.id.eq_ignore_ascii_case(name) || b.label.eq_ignore_ascii_case(name))
}
/// The variable width Add to Profiles saves: the shown stroke's profile, when it isn't listed.
@@ -759,6 +804,32 @@ fn has_saved_profiles(s: &Session) -> std::result::Result<(), String> {
if s.prefs.width_profiles.is_empty() { Err("no saved profiles".into()) } else { Ok(()) }
}
fn has_deletable_profiles(s: &Session) -> std::result::Result<(), String> {
if s.prefs.width_profiles.is_empty() && !s.profile_entries().any(|e| e.id != WidthProfile::PRESETS[0].id) {
Err("no deletable profiles".into())
} else {
Ok(())
}
}
fn can_reset_profiles(s: &Session) -> std::result::Result<(), String> {
if s.prefs.width_profiles.is_empty() && s.prefs.width_profile_order.is_empty() && s.prefs.hidden_width_profiles.is_empty() {
Err("no saved profiles".into())
} else {
Ok(())
}
}
/// The default order of reorderable profiles (visible built-ins after Uniform, then saved profiles).
fn default_profile_order(s: &Session) -> Vec<String> {
WidthProfile::PRESETS[1..]
.iter()
.filter(|p| !s.prefs.hidden_width_profiles.iter().any(|h| h == p.id))
.map(|p| p.id.to_string())
.chain(s.prefs.width_profiles.iter().map(|sp| sp.name.clone()))
.collect()
}
fn profile_add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthProfile.add";
let profile = s.profile_to_add().map_err(|e| bad(C, e))?;
@@ -769,6 +840,9 @@ fn profile_add(s: &mut Session, p: &Value) -> Result<Value> {
Some(n) => n.to_string(),
};
s.prefs.width_profiles.push(SavedProfile { name: name.clone(), profile });
if !s.prefs.width_profile_order.is_empty() && !s.prefs.width_profile_order.iter().any(|id| id == &name) {
s.prefs.width_profile_order.push(name.clone());
}
Ok(json!({ "name": name }))
}
@@ -779,22 +853,90 @@ fn profile_delete(s: &mut Session, p: &Value) -> Result<Value> {
None => {
let shown = s.shown_stroke().and_then(|st| st.profile);
let entry = shown.as_ref().and_then(|p| s.profile_entry(Some(p)));
entry.map(|e| e.id.to_string()).ok_or_else(|| bad(C, "give a name, or select a stroke with a saved profile"))?
entry.map(|e| e.id.to_string()).ok_or_else(|| bad(C, "give a name, or select a stroke with a deletable profile"))?
}
};
if WidthProfile::PRESETS.iter().any(|b| b.id == name || b.label == name) {
return Err(bad(C, format!("{name} is built in and can't be deleted")));
let uniform = WidthProfile::PRESETS[0];
if name == uniform.id || name.eq_ignore_ascii_case(uniform.label) {
return Err(bad(C, "Uniform can't be deleted"));
}
let i = s.prefs.width_profiles.iter().position(|sp| sp.name == name).ok_or_else(|| bad(C, format!("no saved profile called {name}")))?;
s.prefs.width_profiles.remove(i);
Ok(json!({ "deleted": name }))
let deleted = if let Some(preset) = WidthProfile::PRESETS[1..]
.iter()
.find(|b| (b.id == name || b.label.eq_ignore_ascii_case(&name)) && !s.prefs.hidden_width_profiles.iter().any(|h| h == b.id))
{
s.prefs.hidden_width_profiles.push(preset.id.to_string());
preset.id.to_string()
} else if let Some(i) = s.prefs.width_profiles.iter().position(|sp| sp.name == name) {
s.prefs.width_profiles.remove(i);
name
} else {
return Err(bad(C, format!("no profile called {name}")));
};
s.prefs.width_profile_order.retain(|id| id != &deleted);
if s.prefs.width_profile_order == default_profile_order(s) {
s.prefs.width_profile_order.clear();
}
Ok(json!({ "deleted": deleted }))
}
fn profile_reset(s: &mut Session, _: &Value) -> Result<Value> {
let removed = std::mem::take(&mut s.prefs.width_profiles).len();
s.prefs.width_profile_order.clear();
s.prefs.hidden_width_profiles.clear();
Ok(json!({ "removed": removed }))
}
fn profile_move(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthProfile.move";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing name"))?;
let to = index_opt(p, "to", C)?.ok_or_else(|| bad(C, "missing `to` (an index)"))?;
let uniform = WidthProfile::PRESETS[0];
if name == uniform.id || name.eq_ignore_ascii_case(uniform.label) {
return Err(bad(C, "Uniform stays first and can't be moved"));
}
let mut order: Vec<String> = s.profile_entries().skip(1).map(|e| e.id.to_string()).collect();
let from = order.iter().position(|id| id == name).ok_or_else(|| bad(C, format!("no width profile called {name}")))?;
if !order.is_empty() {
let to = to.min(order.len() - 1);
if from != to {
let item = order.remove(from);
order.insert(to, item);
}
}
if order == default_profile_order(s) {
s.prefs.width_profile_order.clear();
} else {
s.prefs.width_profile_order = order.clone();
}
Ok(json!({ "order": order }))
}
fn profile_rename(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthProfile.rename";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing name"))?;
let to = str_param(p, "to").map(str::trim).ok_or_else(|| bad(C, "missing `to`"))?;
if to.is_empty() {
return Err(bad(C, "the name is empty"));
}
if WidthProfile::PRESETS.iter().any(|b| b.id == name || b.label == name) {
return Err(bad(C, format!("{name} is built in and can't be renamed")));
}
if WidthProfile::PRESETS.iter().any(|b| b.id.eq_ignore_ascii_case(to) || b.label.eq_ignore_ascii_case(to)) {
return Err(bad(C, format!("a profile is already called {to}")));
}
let i = s.prefs.width_profiles.iter().position(|sp| sp.name == name).ok_or_else(|| bad(C, format!("no saved profile called {name}")))?;
if !to.eq_ignore_ascii_case(name) && s.profile_name_taken(to) {
return Err(bad(C, format!("a profile is already called {to}")));
}
s.prefs.width_profiles[i].name = to.to_string();
for id in &mut s.prefs.width_profile_order {
if id == name {
*id = to.to_string();
}
}
Ok(json!({ "name": to }))
}
fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
let profiles: Vec<Value> = s
.profile_entries()
+11
View File
@@ -361,6 +361,15 @@ pub struct Prefs {
/// Preferences dialog field, so it has no [`cmd::prefscmds::PREF_SPECS`] row.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub width_profiles: Vec<vectorcraft_doc::SavedProfile>,
/// Display order of non-uniform width profiles (`stroke.widthProfile.move`), holding built-in
/// ids and saved profile names. Empty means default order (built-ins then saved). Not a
/// Preferences dialog field, so resetting preferences keeps it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub width_profile_order: Vec<String>,
/// Built-in non-uniform width profile ids deleted/hidden by the user; Reset Profiles clears
/// this list to restore all built-in presets.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hidden_width_profiles: Vec<String>,
/// General → Use Japanese Crop Marks: the style of Create Trim Marks and Effect → Crop Marks.
pub japanese_crop_marks: bool,
/// Appearance panel → New Art Has Basic Appearance (on): new art takes one fill and stroke;
@@ -718,6 +727,8 @@ impl Default for Prefs {
trace_presets: vec![],
gradient_presets: vec![],
width_profiles: vec![],
width_profile_order: vec![],
hidden_width_profiles: vec![],
japanese_crop_marks: false,
new_art_basic: true,
color_themes: vec![],
+81 -7
View File
@@ -84,7 +84,7 @@ fn add_list_apply_delete_reset() {
}
#[test]
fn built_ins_cant_be_deleted_and_names_stay_unique() {
fn uniform_cant_be_deleted_and_built_ins_delete_and_reset() {
let (mut s, id) = session_with_line();
set_profile(&mut s, id, custom());
for taken in ["lens", "Taper Start", "UNIFORM"] {
@@ -92,16 +92,30 @@ fn built_ins_cant_be_deleted_and_names_stay_unique() {
}
assert!(s.execute("stroke.widthProfile.add", &json!({"name": " "})).is_err());
s.execute("stroke.widthProfile.add", &json!({"name": "Mine"})).unwrap();
for b in ["lens", "Lens", "uniform", "wave"] {
let e = s.execute("stroke.widthProfile.delete", &json!({"name": b})).unwrap_err().to_string();
assert!(e.contains("built in"), "{b}: {e}");
}
// With a built-in profile selected, Delete has nothing to delete.
s.execute("stroke.set", &json!({"profile": "pinch"})).unwrap();
// Uniform cannot be deleted by id or label, nor when selected on the stroke.
s.execute("stroke.set", &json!({"profile": "uniform"})).unwrap();
assert!(s.execute("stroke.widthProfile.delete", &json!({})).is_err());
for u in ["uniform", "Uniform", "UNIFORM"] {
let e = s.execute("stroke.widthProfile.delete", &json!({"name": u})).unwrap_err().to_string();
assert!(e.contains("Uniform"), "{u}: {e}");
}
// Non-uniform built-in profiles CAN be deleted (by name/id or active selection) and restored on Reset.
assert_eq!(s.execute("stroke.widthProfile.delete", &json!({"name": "Lens"})).unwrap()["deleted"], "lens");
assert!(!s.profile_entries().any(|e| e.id == "lens"));
s.execute("stroke.set", &json!({"profile": "pinch"})).unwrap();
assert_eq!(s.execute("stroke.widthProfile.delete", &json!({})).unwrap()["deleted"], "pinch");
assert!(!s.profile_entries().any(|e| e.id == "pinch"));
assert!(s.execute("stroke.widthProfile.delete", &json!({"name": "Lens"})).is_err(), "already deleted");
assert!(s.execute("stroke.widthProfile.delete", &json!({"name": "Other"})).is_err());
assert_eq!(s.next_profile_name(), "Width Profile 1");
assert_eq!(s.execute("stroke.widthProfile.delete", &json!({"name": "Mine"})).unwrap()["deleted"], "Mine");
// Reset restores all deleted built-ins as well.
assert!(s.execute("stroke.widthProfile.reset", &json!({})).is_ok());
assert_eq!(ids(&s.execute("stroke.widthProfile.list", &json!({})).unwrap()), WidthProfile::PRESETS.iter().map(|p| p.id).collect::<Vec<_>>());
}
#[test]
@@ -138,3 +152,63 @@ fn every_built_in_applies_and_the_params_doc_names_them() {
assert_eq!(profile(&s, id).map(|w| w.points), (p.id != "uniform").then(|| p.points.to_vec()));
}
}
#[test]
fn move_reorders_presets_and_saved_profiles_while_keeping_uniform_pinned() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("stroke.set", &json!({"weight": 6.0})).unwrap();
s.execute("stroke.widthPoint.set", &json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
s.execute("stroke.widthProfile.add", &json!({"name": "Alpha"})).unwrap();
s.execute("stroke.widthPoint.set", &json!({"id": id, "t": 0.7, "left": 2.0, "right": 14.0})).unwrap();
s.execute("stroke.widthProfile.add", &json!({"name": "Beta"})).unwrap();
// Uniform cannot be moved, even when named by display label.
assert!(s.execute("stroke.widthProfile.move", &json!({"name": "uniform", "to": 2})).is_err());
assert!(s.execute("stroke.widthProfile.move", &json!({"name": "Uniform", "to": 1})).is_err());
// Moving a built-in ("wave") and a saved profile ("Beta") puts them at exact slots after Uniform.
s.execute("stroke.widthProfile.move", &json!({"name": "wave", "to": 0})).unwrap();
s.execute("stroke.widthProfile.move", &json!({"name": "Beta", "to": 0})).unwrap();
let ids: Vec<String> = s.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(ids[0], "uniform", "Uniform stays pinned first");
assert_eq!(ids[1], "Beta", "saved profile moves right after Uniform");
assert_eq!(ids[2], "wave", "built-in preset moves after Beta");
// Order survives preferences JSON round-trip.
let saved_prefs = serde_json::to_string(&s.prefs).unwrap();
let mut restored = Session::new();
restored.prefs = serde_json::from_str(&saved_prefs).unwrap();
let restored_ids: Vec<String> = restored.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(restored_ids, ids);
// Reset works even if only built-ins were reordered (no saved profiles).
let mut built_ins_only = Session::new();
built_ins_only.execute("stroke.widthProfile.move", &json!({"name": "wave", "to": 0})).unwrap();
assert!(built_ins_only.execute("stroke.widthProfile.reset", &json!({})).is_ok());
let default_ids: Vec<String> = built_ins_only.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(default_ids, vec!["uniform", "lens", "taperStart", "taperEnd", "pinch", "teardrop", "wave"]);
}
#[test]
fn rename_updates_saved_profile_in_place_and_refuses_built_ins() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("stroke.set", &json!({"weight": 6.0})).unwrap();
s.execute("stroke.widthPoint.set", &json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
s.execute("stroke.widthProfile.add", &json!({"name": "Alpha"})).unwrap();
s.execute("stroke.widthProfile.move", &json!({"name": "Alpha", "to": 1})).unwrap();
assert!(s.execute("stroke.widthProfile.rename", &json!({"name": "uniform", "to": "Other"})).is_err());
assert!(s.execute("stroke.widthProfile.rename", &json!({"name": "lens", "to": "Other"})).is_err());
assert!(s.execute("stroke.widthProfile.rename", &json!({"name": "Alpha", "to": " "})).is_err());
assert!(s.execute("stroke.widthProfile.rename", &json!({"name": "Alpha", "to": "Wave"})).is_err());
s.execute("stroke.widthProfile.rename", &json!({"name": "Alpha", "to": "Renamed"})).unwrap();
let ids: Vec<String> = s.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(ids[0], "uniform");
assert_eq!(ids[2], "Renamed", "renamed profile keeps its custom slot");
}
+52 -22
View File
@@ -5,6 +5,9 @@
use std::sync::LazyLock;
mod profile_picker;
use profile_picker::{ProfileAction, ProfileActions, ProfileOption, ProfileSample, ProfileSelect};
use craft::behavior::{ColumnWidth, EditEvent, GestureId, IconId, Mixed};
use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSections};
use craft::keymap::CommandRef;
@@ -887,50 +890,77 @@ pub(crate) fn profile_select(app: &mut VectorcraftApp, ui: &mut Ui) {
brush_keeps_size(app, shown.as_ref())
};
let mut entries = vec![];
// Each entry's id and silhouette, as `WidthProfile::points`.
let mut shapes: Vec<(String, Option<Vec<_>>)> = vec![];
let mut picked = String::new();
let mut divide = true;
for e in app.session.profile_entries().filter(|e| brushed != Some(true) || e.matches(None)) {
if !e.built_in && std::mem::take(&mut divide) {
entries.push(Entry::separator());
}
if e.matches(cur) {
picked = e.id.to_string();
}
// A saved profile's name is the user's.
entries.push(Entry::new(e.id.to_string(), super::label_or_name(e.label, e.built_in).to_string()));
shapes.push((e.id.to_string(), silhouette(e.points).map(<[_]>::to_vec)));
entries.push(ProfileOption {
id: e.id.to_string(),
label: super::label_or_name(e.label, e.built_in).to_string(),
points: silhouette(e.points).map(<[ProfileSample]>::to_vec),
built_in: e.built_in,
});
}
let brush_tip = tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.");
// While a brush keeps the size of a profiled stroke the select stays on, to its Uniform row, and still says why.
let tip = TooltipSpec::new(if brushed == Some(true) { brush_tip } else { tl!("Variable Width Profile") }).disabled_text(brush_tip);
// A profile no row shows (an unsaved one, or a listed one the brushed list leaves out) is drawn and named on the
// face under the empty id, without a row of its own.
// face without a row of its own.
let unlisted = match cur {
Some(profile) if picked.is_empty() => {
shapes.push((String::new(), silhouette(&profile.points).map(<[_]>::to_vec)));
Some(app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned())
let label = app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned();
Some((label, silhouette(&profile.points).map(<[ProfileSample]>::to_vec)))
}
_ => None,
};
let select = Select::new(tl!("Profile"), Bind::given(picked), &entries);
let actions = ProfileActions {
can_add: cur.is_some() && brushed != Some(true) && crate::menus::enabled(app, "stroke.widthProfile.add"),
can_delete: cur.as_ref().and_then(|p| app.session.profile_entry(Some(p))).is_some_and(|e| e.id != "uniform")
&& brushed != Some(true)
&& crate::menus::enabled(app, "stroke.widthProfile.delete"),
can_reset: crate::menus::enabled(app, "stroke.widthProfile.reset"),
can_reorder: brushed != Some(true),
};
let select = ProfileSelect::new(tl!("Profile"), Bind::given(picked), entries, paint_profile, actions);
let select = match unlisted {
Some(label) => select.unlisted_label(label),
Some((label, points)) => select.unlisted(label, points),
None => select,
};
let out = select
.picture(|id: &String, cx, rect| {
if let Some((_, points)) = shapes.iter().find(|(i, _)| i == id) {
paint_profile(cx, rect, points.as_deref());
}
})
// Brushed strokes with a profile still open the list, to its Uniform row.
.enabled(brushed != Some(false))
.tooltip(tip)
.show(ui);
// A cancel puts back what the gesture changed instead of applying the empty id, which names no profile.
apply_select(app, "profile", &out, |app, id| set(app, json!({"profile": id})));
apply_select(app, "profile", &out.edit, |app, id| set(app, json!({"profile": id})));
if let Some(action) = out.action {
apply_profile_action(app, action);
}
}
fn apply_profile_action(app: &mut VectorcraftApp, action: ProfileAction) {
match action {
ProfileAction::Add => {
crate::menus::invoke(app, "stroke.widthProfile.add", json!({"name": app.session.next_profile_name()}));
}
ProfileAction::Delete(Some(name)) => {
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({"name": name}));
}
ProfileAction::Delete(None) => {
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({}));
}
ProfileAction::Reset => {
crate::dialogs::confirm::ask(app, tl!("Do you want to reset profiles?"), "", "stroke.widthProfile.reset", json!({}));
}
ProfileAction::Move { name, to } => {
crate::menus::invoke(app, "stroke.widthProfile.move", json!({"name": name, "to": to}));
}
ProfileAction::Rename { name, to } => {
crate::menus::invoke(app, "stroke.widthProfile.rename", json!({"name": name, "to": to}));
}
}
}
/// The command a ≡ menu row runs to ask for the name of a new saved profile.
@@ -960,10 +990,10 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
states.set(CommandRef::new("ui.stroke.options"), CommandState::new().title(options));
let enabled = |id: &str| crate::menus::enabled(app, id);
states.set(add_profile(app), CommandState::new().title(tl!("Add to Profiles…")).enabled(enabled("stroke.widthProfile.add")));
// Deletes the selected stroke's saved profile.
// Deletes the selected stroke's non-Uniform profile.
let shown = current_stroke(app).and_then(|s| s.profile);
let saved = shown.as_ref().and_then(|p| app.session.profile_entry(Some(p))).is_some_and(|e| !e.built_in);
states.set(CommandRef::new("stroke.widthProfile.delete"), CommandState::new().title(tl!("Delete Profile")).enabled(saved));
let deletable = shown.as_ref().and_then(|p| app.session.profile_entry(Some(p))).is_some_and(|e| e.id != "uniform");
states.set(CommandRef::new("stroke.widthProfile.delete"), CommandState::new().title(tl!("Delete Profile")).enabled(deletable));
states.set(
CommandRef::new("stroke.widthProfile.reset"),
CommandState::new().title(tl!("Reset Profiles")).enabled(enabled("stroke.widthProfile.reset")),
@@ -0,0 +1,672 @@
//! The Variable Width Profile dropdown (`ProfileSelect`): a combo box whose popup shows the width
//! profile list with drag/keyboard reordering (keeping Uniform pinned first), built-in labels and
//! captionless user-added thumbnails, right-click row actions, and a footer bar with Add to
//! Profiles…, Delete Profile, and Reset Profiles.
use std::borrow::Cow;
use std::collections::HashSet;
use craft::behavior::overlay::MinWidth;
use craft::behavior::{
CancelReason, ColumnKey, ColumnWidth, DisplayOrder, EditEvent, GesturePhase, HitLevel, HitPriority, IconId, ItemSource, Metrics, NavMove,
PartKey, Proposal, Selection, Sense, TypeAhead,
};
use craft::ui::contract::overlay::OverlayFit;
use craft::ui::contract::{
Access, ActivateOn, Bind, BindMut, CollectionEvent, ColumnSpec, Common, Component, Cx, Edit as _, EditResponse, Focus as _, HoverLead, Input,
LeadOnOpen, LeadSource, ListDrag, MeasureCx, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Popup, PopupHandle,
Props, ReorderRule, Role, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _, request_rename,
};
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::pickers::{SelectFace, toggle_on_key};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::KeyUse;
use craft::ui::runtime::memory::Remember as _;
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::style::{ComponentStyle, StyleCx};
use egui::{Rect, Response, Vec2};
const UNIFORM_ID: &str = "uniform";
const SEPARATOR_KEY: &str = "__profile_separator__";
const PROFILE_COL: ColumnKey = ColumnKey::new("profile");
const DROPDOWN_MIN_WIDTH: f32 = 132.0;
const CLOSED_MAX_WIDTH: f32 = 145.0;
const PAGE_ROWS: isize = 12;
const FACE: PartKey = PartKey::new("face");
const POPUP: &str = "list";
const LIST_SALT: &str = "items";
/// One silhouette sample `(t, left_offset, right_offset)` returned by `stroke::silhouette`.
pub(super) type ProfileSample = (f64, f64, f64);
fn profile_thumb_aspect() -> ThumbAspect {
ThumbAspect::new(14, 5)
}
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct ProfileGraphicStyle {
#[style(metrics)]
metrics: Metrics,
}
/// Passive width-profile graphic for captionless user-added rows (`Sense::empty()` lets clicks and
/// reorder drags go straight through to the list row).
#[derive(Component, Props)]
#[component(content_painter, sample = ProfileGraphic::sample)]
struct ProfileGraphic {
#[common]
common: Common,
points: Option<Vec<ProfileSample>>,
paint: ProfilePaint,
size: Vec2,
}
impl ProfileGraphic {
fn new(paint: ProfilePaint, points: Option<Vec<ProfileSample>>, size: Vec2) -> Self {
Self { common: Common::new(), points, paint, size }
}
fn sample() -> Self {
Self::new(|_, _, _| {}, None, Vec2::new(80.0, 20.0))
}
}
impl Component for ProfileGraphic {
const ROLE: Role = Role::None;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = ProfileGraphicStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: ProfileGraphicStyleKey) -> ProfileGraphicStyle {
ProfileGraphicStyle { metrics: Metrics::new() }
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
self.size
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let painter = ui.content_painter(cx);
(self.paint)(&painter, cx.rect.shrink2(Vec2::new(0.0, 2.0)), self.points.as_deref());
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// One entry in the Variable Width Profile dropdown.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ProfileOption {
/// Engine preset id (`"uniform"`, `"lens"`, …) or saved profile name.
pub id: String,
/// Display label shown in the closed face, and in the dropdown row for built-in profiles.
pub label: String,
/// Profile silhouette samples (`None` for Uniform).
pub points: Option<Vec<ProfileSample>>,
/// Built-in profiles keep their text captions in the dropdown and cannot be renamed.
pub built_in: bool,
}
/// Enable state for the management controls inside the dropdown footer and row menu.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ProfileActions {
pub can_add: bool,
pub can_delete: bool,
pub can_reset: bool,
pub can_reorder: bool,
}
/// A management action requested by the dropdown footer, row menu, drag-reorder, or inline rename.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ProfileAction {
Add,
Delete(Option<String>),
Reset,
Move { name: String, to: usize },
Rename { name: String, to: String },
}
/// Output of [`ProfileSelect`]: the underlying profile pick/preview edit and any management action.
#[derive(Debug)]
pub(super) struct ProfileSelectOutput {
pub edit: EditResponse<String>,
pub action: Option<ProfileAction>,
}
impl Outcome for ProfileSelectOutput {
type Value = String;
fn response(&self) -> &Response {
&self.edit.response
}
}
/// Paint callback shared between the closed face and list rows.
pub(super) type ProfilePaint = fn(&ContentPainterCx, Rect, Option<&[ProfileSample]>);
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
pub(super) struct ProfileSelectStyle {
#[style(metrics)]
metrics: Metrics,
}
#[derive(Clone, Default)]
struct PickerMemory {
/// Target key of an open per-row context menu.
menu: Option<String>,
/// Pre-typed query buffered on focus while closed.
type_ahead: TypeAhead,
/// Pending lead override when opening from closed type-ahead.
reveal_on_open: Option<String>,
/// Whether a preview proposal was issued during this open popup session.
previewed: bool,
}
/// Custom dropdown for stroke width profiles with Illustrator-style management footer and reordering.
#[derive(Component, Props)]
#[component(overlay, sample = ProfileSelect::sample)]
pub(super) struct ProfileSelect {
#[common]
common: Common,
value: Bind<'static, String>,
entries: Vec<ProfileOption>,
unlisted_label: Option<String>,
unlisted_points: Option<Vec<ProfileSample>>,
paint: ProfilePaint,
actions: ProfileActions,
action: Option<ProfileAction>,
}
impl ProfileSelect {
pub(super) fn new(
label: impl Into<craft::ui::runtime::env::Label>,
value: Bind<'static, String>,
entries: Vec<ProfileOption>,
paint: ProfilePaint,
actions: ProfileActions,
) -> Self {
Self { common: Common::new(), value, entries, unlisted_label: None, unlisted_points: None, paint, actions, action: None }.label(label)
}
pub(super) fn unlisted(mut self, label: String, points: Option<Vec<ProfileSample>>) -> Self {
self.unlisted_label = Some(label);
self.unlisted_points = points;
self
}
fn sample() -> Self {
Self::new(
"Profile",
Bind::given("uniform".to_owned()),
vec![ProfileOption { id: "uniform".to_owned(), label: "Uniform".to_owned(), points: None, built_in: true }],
|_, _, _| {},
ProfileActions::default(),
)
}
fn option(&self, id: &str) -> Option<&ProfileOption> {
self.entries.iter().find(|e| e.id == id)
}
fn display_for(&self, current: Option<&String>) -> (String, Option<Vec<ProfileSample>>, bool) {
let Some(id) = current else {
return (tl!("Mixed").to_owned(), None, true);
};
if let Some(opt) = self.option(id) {
return (opt.label.clone(), opt.points.clone(), false);
}
if let Some(label) = &self.unlisted_label {
return (label.clone(), self.unlisted_points.clone(), false);
}
(tl!("Mixed").to_owned(), None, true)
}
fn face(&self, current: Option<&String>) -> SelectFace<'static> {
let (text, points, placeholder) = self.display_for(current);
let paint = self.paint;
let face = SelectFace::new(text).fit(true).thumb(profile_thumb_aspect(), move |cx, rect| paint(cx, rect, points.as_deref()));
if placeholder { face.placeholder() } else { face }
}
fn has_separator(&self) -> bool {
self.entries.len() > 1
}
fn step_entry(&self, current: Option<&String>, steps: isize) -> Option<String> {
if self.entries.is_empty() {
return None;
}
let cur = current.and_then(|id| self.entries.iter().position(|e| &e.id == id));
let next = match cur {
Some(at) => (at as isize + steps).clamp(0, (self.entries.len() - 1) as isize) as usize,
None if steps >= 0 => 0,
None => self.entries.len() - 1,
};
self.entries.get(next).map(|e| e.id.clone())
}
fn nav_target(&self, current: Option<&String>, mv: NavMove) -> Option<String> {
match mv {
NavMove::Up | NavMove::Back => self.step_entry(current, -1),
NavMove::Down | NavMove::Forward => self.step_entry(current, 1),
NavMove::Start => self.entries.first().map(|e| e.id.clone()),
NavMove::End => self.entries.last().map(|e| e.id.clone()),
NavMove::PageUp => self.step_entry(current, -PAGE_ROWS),
NavMove::PageDown => self.step_entry(current, PAGE_ROWS),
_ => None,
}
}
}
struct ProfileRows<'a> {
entries: &'a [ProfileOption],
separator: bool,
}
impl<'a> ProfileRows<'a> {
fn entry_at(&self, at: usize) -> Option<&'a ProfileOption> {
if at == 0 {
return self.entries.first();
}
if self.separator { if at == 1 { None } else { self.entries.get(at - 1) } } else { self.entries.get(at) }
}
}
impl DisplayOrder<String> for ProfileRows<'_> {
fn len(&self) -> usize {
self.entries.len() + usize::from(self.separator)
}
fn key(&self, at: usize) -> String {
self.entry_at(at).map_or_else(|| SEPARATOR_KEY.to_owned(), |e| e.id.clone())
}
fn is_section(&self, at: usize) -> bool {
self.separator && at == 1
}
fn enabled(&self, at: usize) -> bool {
!(self.separator && at == 1)
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
self.entry_at(at).map(|e| Cow::Borrowed(e.label.as_str()))
}
}
impl ItemSource<String> for ProfileRows<'_> {}
impl Component for ProfileSelect {
const ROLE: Role = Role::COMBO_BOX;
const INPUT: Input = Input::Pointer;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_moves().with_type_ahead();
type Style = ProfileSelectStyle;
type Output = ProfileSelectOutput;
fn style(_: &StyleCx<'_>, _: ProfileSelectStyleKey) -> ProfileSelectStyle {
ProfileSelectStyle { metrics: Metrics::new() }
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS | Sense::WHEEL
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let mut size = cx.face(self.face(cx.value()));
let paint = self.paint;
let aspect = profile_thumb_aspect();
for entry in self.entries.iter().filter(|e| e.built_in) {
let points = entry.points.clone();
let mut face = SelectFace::new(entry.label.clone()).fit(true).thumb(aspect, move |painter, rect| paint(painter, rect, points.as_deref()));
let measured = cx.child("option", &mut face, Proposal::Ideal);
size.x = size.x.max(measured.x);
size.y = size.y.max(measured.y);
}
Vec2::new(size.x.clamp(DROPDOWN_MIN_WIDTH, CLOSED_MAX_WIDTH), size.y)
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
cx.part(FACE, rect)
.sense(Sense::CLICK | Sense::HOVER | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Body, 0))
.pointer_only("Enter, Space and Alt+Down open the list")
.toggles(POPUP);
}
fn bind(&mut self) -> Option<BindMut<'_, String>> {
Some(self.value.reborrow())
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let popup = cx.popup(POPUP);
toggle_on_key(cx, popup);
if popup.is_open(cx) {
return;
}
if let Some(wheel) = cx.take_wheel() {
let notch = if wheel.lines.y != 0.0 {
wheel.lines.y.trunc() as isize
} else if wheel.scroll.y != 0.0 {
wheel.scroll.y.signum() as isize
} else {
0
};
if notch != 0
&& let Some(target) = self.step_entry(cx.value().cloned().as_ref(), -notch)
{
cx.propose(target);
cx.commit();
}
}
if !cx.is_focused() {
return;
}
if let Some((mv, _)) = cx.intents().take_move()
&& let Some(target) = self.nav_target(cx.value().cloned().as_ref(), mv)
{
cx.propose(target);
cx.commit();
}
if let Some(typed) = cx.intents().take_text() {
let folder = cx.env.folder();
let now = cx.ctx.input(|i| i.time);
let cur_idx = cx.value().and_then(|id| self.entries.iter().position(|e| &e.id == id));
let matched = {
let mem = cx.memory::<PickerMemory>();
let mut prefix = String::new();
for ch in typed.chars() {
prefix = mem.type_ahead.push(ch, now).to_owned();
}
TypeAhead::pick(&prefix, cur_idx, self.entries.len(), |at| Cow::Borrowed(self.entries[at].label.as_str()), |text| folder.key(text))
};
if let Some(at) = matched {
let id = self.entries[at].id.clone();
let mem = cx.memory::<PickerMemory>();
mem.reveal_on_open = Some(id.clone());
mem.previewed = true;
cx.propose(id);
popup.open(cx);
}
}
}
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
let popup = cx.popup(POPUP);
let list_id = cx.id.with(LIST_SALT);
let mut overlay = Overlay::dropdown()
.fit(OverlayFit::Content)
.min_width(MinWidth::None)
.min_size(Vec2::new(DROPDOWN_MIN_WIDTH, 0.0))
.body_scroll(false)
.list(list_id);
overlay.dismiss.on_activate = false;
let fresh = Popup::opening(popup, cx);
if fresh {
let mem = cx.memory::<PickerMemory>();
mem.menu = None;
if mem.reveal_on_open.is_none() {
mem.previewed = false;
}
}
let current = cx.value().cloned().filter(|id| !id.is_empty());
let reveal = cx.memory::<PickerMemory>().reveal_on_open.take().or_else(|| fresh.then(|| current.clone()).flatten());
let selection = current.as_ref().map_or_else(Selection::default, |id| Selection::single(id.clone()));
let saved: HashSet<String> = self.entries.iter().filter(|e| !e.built_in).map(|e| e.id.clone()).collect();
let can_reorder = self.actions.can_reorder && self.has_separator();
let view = PopupView { list_id, selection: &selection, reveal: reveal.as_deref(), saved: &saved, can_reorder };
let body_out = ui.show(popup, overlay, |ui, _| show_popup_body(ui, cx, self, view));
if let Some((events, footer_action, menu_action)) = body_out {
self.handle_list_events(cx, popup, &events);
if let Some(act) = footer_action.or(menu_action) {
if matches!(act, ProfileAction::Reset) {
popup.close(cx);
}
self.action = Some(act);
}
}
if let Some(reason) = ui.closing(popup) {
let mem = cx.memory::<PickerMemory>();
mem.menu = None;
if std::mem::take(&mut mem.previewed) {
let cancel = if reason == CloseReason::Escape { CancelReason::Escape } else { CancelReason::Dismissed };
cx.cancel(cancel);
}
}
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let (text, _, _) = self.display_for(cx.value());
access.value(text);
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
ui.face(FACE, self.face(cx.value()));
}
fn finish(mut self, cx: Cx<'_, Self>) -> ProfileSelectOutput {
ProfileSelectOutput { edit: cx.edit_response(), action: self.action.take() }
}
}
impl ProfileSelect {
fn handle_list_events(&mut self, cx: &mut Cx<'_, Self>, popup: PopupHandle, events: &[CollectionEvent<String, RowEvent>]) {
for event in events {
match event {
CollectionEvent::LeadMoved { key, by: LeadSource::Keys } if key != SEPARATOR_KEY => {
cx.memory::<PickerMemory>().previewed = true;
cx.propose(key.clone());
}
CollectionEvent::Activate(key) | CollectionEvent::Item(key, RowEvent::ThumbClicked { .. }) if key != SEPARATOR_KEY => {
cx.propose(key.clone());
cx.commit();
cx.memory::<PickerMemory>().previewed = false;
popup.close(cx);
}
CollectionEvent::Reorder(EditEvent::Set { after, .. } | EditEvent::Commit { after, .. }) => {
if after.key != UNIFORM_ID && after.key != SEPARATOR_KEY {
self.action = Some(ProfileAction::Move { name: after.key.clone(), to: after.to.saturating_sub(2) });
}
}
CollectionEvent::Rename(edit) => {
let ended = matches!(edit.phase(), Some(GesturePhase::Commit) | None);
if let Some(rename) = edit.value().filter(|_| ended) {
let trimmed = rename.name.trim();
if !trimmed.is_empty() && trimmed != rename.key {
self.action = Some(ProfileAction::Rename { name: rename.key.clone(), to: trimmed.to_owned() });
}
}
}
_ => {}
}
}
}
}
#[derive(Clone, Copy)]
struct PopupView<'a> {
list_id: egui::Id,
selection: &'a Selection<String>,
reveal: Option<&'a str>,
saved: &'a HashSet<String>,
can_reorder: bool,
}
fn show_popup_body(
ui: &mut egui::Ui,
cx: &mut Cx<'_, ProfileSelect>,
picker: &ProfileSelect,
view: PopupView<'_>,
) -> (Vec<CollectionEvent<String, RowEvent>>, Option<ProfileAction>, Option<ProfileAction>) {
let mut footer_action = None;
let mut events = Vec::new();
let mut list_resp = None;
let label = cx.label();
let rows = ProfileRows { entries: &picker.entries, separator: picker.has_separator() };
let paint = picker.paint;
let actions = picker.actions;
let builtin_aspect = profile_thumb_aspect();
Stack::new()
.fill_width()
.footer(|ui, _| {
footer_action = show_footer(ui, view.list_id, actions);
})
.show(ui, |ui, _| {
let saved_for_rename = view.saved.clone();
let mut list = List::<String>::options(label.clone())
.id(view.list_id)
.header(false)
.columns(vec![ColumnSpec::new(PROFILE_COL, Label::Empty, ColumnWidth::fill(1.0))])
.hover_lead(HoverLead::Lead)
.activate(ActivateOn::Click)
.lead_on_open(LeadOnOpen::First)
.selection(Bind::given(view.selection.clone()))
.can_rename(move |key: &String| saved_for_rename.contains(key));
if view.can_reorder {
list = list
.can_drag(|key: &String| key != UNIFORM_ID && key != SEPARATOR_KEY)
.reorder(ReorderRule::new())
.accepts(|drag, _, insert| !drag.keys.iter().any(|k| k == UNIFORM_ID || k == SEPARATOR_KEY) && insert >= 2);
}
if let Some(key) = view.reveal {
list = list.reveal(key.to_owned());
}
let out = list.show_items(ui, &rows, &mut |key, icx| {
if key == SEPARATOR_KEY {
return ListRow::separator();
}
let Some(entry) = picker.option(key) else {
return ListRow::spacer();
};
let points = entry.points.clone();
if entry.built_in {
ListRow::new(entry.label.clone()).option().cells(icx.cells()).thumb_aspect(
ThumbSize::Small,
builtin_aspect,
move |painter, rect| paint(painter, rect, points.as_deref()),
)
} else {
ListRow::new("").accessible_name(entry.label.clone()).option().cells(icx.cells()).cell_field(
PROFILE_COL,
ProfileGraphic::new(paint, points, Vec2::new(80.0, 20.0)),
|_| {},
)
}
});
events = out.events;
list_resp = Some(out.response);
});
let list_response = list_resp.unwrap_or_else(|| ui.response().clone());
for event in &events {
if let CollectionEvent::ContextMenu(request) = event
&& request.key != SEPARATOR_KEY
{
cx.memory::<PickerMemory>().menu = Some(request.key.clone());
}
}
let menu_action = show_row_menu(ui, cx, picker, view.list_id, &list_response, view.saved);
(events, footer_action, menu_action)
}
fn show_footer(ui: &mut egui::Ui, list_id: egui::Id, actions: ProfileActions) -> Option<ProfileAction> {
// End-edge placement lays out actions from the right edge inward, so index 0 (`Reset Profiles`)
// sits rightmost, with `Delete Profile` and `Add to Profiles` to its left.
let bar = FooterBar::actions([
FooterAction::new(IconId::new("rotate-ccw"), tl!("Reset Profiles")).enabled(actions.can_reset),
FooterAction::new(IconId::new("trash-2"), tl!("Delete Profile"))
.enabled(actions.can_delete)
.takes_drops_disabled(true)
.drop_hint(tl!("Delete Profile"))
.accepts_drops::<ListDrag<String>>(move |drag| drag.list == list_id && drag.keys.iter().any(|k| k != UNIFORM_ID && k != SEPARATOR_KEY)),
FooterAction::new(IconId::new("dc-new-item"), tl!("Add to Profiles")).enabled(actions.can_add),
])
.show_footer(ui);
if let Some(drop) = &bar.dropped
&& drop.index == 1
&& let Some(key) = drop.payload::<ListDrag<String>>().and_then(|d| d.keys.iter().find(|k| *k != UNIFORM_ID && *k != SEPARATOR_KEY))
{
return Some(ProfileAction::Delete(Some(key.clone())));
}
match bar.picked {
Some(0) => Some(ProfileAction::Reset),
Some(1) => Some(ProfileAction::Delete(None)),
Some(2) => Some(ProfileAction::Add),
_ => None,
}
}
fn show_row_menu(
ui: &mut egui::Ui,
cx: &mut Cx<'_, ProfileSelect>,
picker: &ProfileSelect,
list_id: egui::Id,
anchor: &Response,
saved: &HashSet<String>,
) -> Option<ProfileAction> {
let target = cx.memory::<PickerMemory>().menu.clone()?;
let Some(entry) = picker.option(&target) else {
cx.memory::<PickerMemory>().menu = None;
return None;
};
let title = entry.label.clone();
let is_uniform = target == UNIFORM_ID;
let is_saved = saved.contains(&target);
let pos = picker.entries.iter().position(|e| e.id == target).unwrap_or(0);
let last = picker.entries.len().saturating_sub(1);
let can_up = !is_uniform && picker.actions.can_reorder && pos > 1;
let can_down = !is_uniform && picker.actions.can_reorder && pos < last;
let mut action = None;
let mut start_rename = false;
let shown = Menu::context(title, anchor).show(ui, |ui, _| {
if is_uniform {
if MenuItem::new(tl!("Reset Profiles")).enabled(picker.actions.can_reset).show(ui).ran {
action = Some(ProfileAction::Reset);
}
return;
}
if MenuItem::new(tl!("Move Up")).enabled(can_up).show(ui).ran {
// `entries[1..]` holds reorderable items, so removing `target` at `pos - 1` and placing
// it one slot earlier targets `pos - 2`.
action = Some(ProfileAction::Move { name: target.clone(), to: pos.saturating_sub(2) });
}
if MenuItem::new(tl!("Move Down")).enabled(can_down).show(ui).ran {
// After removing `target` at `pos - 1`, placing it one slot later targets `pos`.
action = Some(ProfileAction::Move { name: target.clone(), to: pos });
}
if is_saved && MenuItem::new(tl!("Rename…")).show(ui).ran {
start_rename = true;
}
if MenuItem::new(tl!("Delete Profile")).show(ui).ran {
action = Some(ProfileAction::Delete(Some(target.clone())));
}
});
if start_rename {
request_rename(ui, list_id, &target);
}
if action.is_some() || start_rename || shown.closed.is_some() {
cx.memory::<PickerMemory>().menu = None;
}
action
}
@@ -320,3 +320,186 @@ fn arrowhead_select_lists_the_notched_arrow_after_arrow() {
panel.click("Notched Arrow");
assert_eq!(current_stroke(&panel.app()).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::NotchedArrow));
}
#[test]
fn dropdown_footer_manages_profiles_and_confirms_reset() {
use craft::ui::contract::Role;
use craft::ui::dialog::StackDialog as _;
use egui::Modifiers;
let mut session = vectorcraft_engine::Session::new();
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
session.execute("stroke.set", &serde_json::json!({"weight": 6.0, "profile": "taperStart"})).unwrap();
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown shrinks to compact width: {:?}", panel.rect("Profile"));
panel.click_role("Profile", Role::COMBO_BOX);
assert!(!panel.shows("Flip Along"), "Flip Along button is not shown inside the dropdown");
assert!(!panel.shows("Flip Across"), "Flip Across button is not shown inside the dropdown");
assert!(panel.shows("Add to Profiles"), "dropdown shows Add to Profiles footer button");
assert!(panel.shows("Delete Profile"), "dropdown shows Delete Profile footer button");
assert!(panel.shows("Reset Profiles"), "dropdown shows Reset Profiles footer button");
assert!(panel.enabled("Delete Profile"), "non-Uniform built-in profile can be deleted");
assert!(
panel.rect("Reset Profiles").left() >= panel.rect("Delete Profile").right() - 0.5
&& panel.rect("Delete Profile").left() >= panel.rect("Add to Profiles").right() - 0.5,
"Reset Profiles sits rightmost in the footer"
);
assert!(panel.rect("Wave").width() <= 165.0, "dropdown shrinks to fit its items: {:?}", panel.rect("Wave"));
// Selecting Uniform disables Delete Profile; Uniform cannot be deleted.
panel.click("Uniform");
panel.click_role("Profile", Role::COMBO_BOX);
assert!(!panel.enabled("Delete Profile"), "Uniform profile cannot be deleted");
// Non-Uniform built-in ("Taper Start") can be deleted directly from the dropdown footer.
panel.click("Taper Start");
panel.click_role("Profile", Role::COMBO_BOX);
assert!(panel.enabled("Delete Profile"));
panel.click("Delete Profile");
assert!(!panel.app().session.profile_entries().any(|e| e.id == "taperStart"), "built-in preset was deleted");
// Custom profile: clicking Add to Profiles saves immediately without opening a name dialog,
// and user-added rows hide their text captions in the dropdown.
panel.app().session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
panel.frame();
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Custom"));
panel.click("Add to Profiles");
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty(), "Add to Profiles does not prompt for a name");
let saved_label = panel.app().session.profile_entries().find(|e| !e.built_in).map(|e| e.label.to_owned()).unwrap();
let face_rect = panel.rect("Profile");
let popup_captions: Vec<_> = panel.painted(&saved_label).into_iter().filter(|r| !face_rect.contains(r.center())).collect();
assert!(popup_captions.is_empty(), "user-added profile shows no caption text in the pulldown: {popup_captions:?}");
assert!(!panel.painted("Wave").is_empty(), "built-in profile still shows its caption text");
// Dragging a user-added profile row reorders it past built-in profiles while keeping Uniform first.
let wave_rect = panel.rect("Wave");
let saved_rect = panel.rect(&saved_label);
let top_target = wave_rect.left_top() + egui::vec2(wave_rect.width() * 0.75, 2.0);
panel.drag_between(saved_rect.center(), top_target, Modifiers::NONE);
let order_after_drag: Vec<String> = panel.app().session.profile_entries().map(|e| e.id.to_owned()).collect();
let saved_pos = order_after_drag.iter().position(|id| id == &saved_label).unwrap();
let wave_pos = order_after_drag.iter().position(|id| id == "wave").unwrap();
assert_eq!(order_after_drag[0], "uniform", "Uniform stays first after drag reorder");
assert!(
saved_pos < wave_pos,
"custom profile reordered ahead of Wave by dragging (saved_rect={saved_rect:?}, wave_rect={wave_rect:?}, open_after={}): {order_after_drag:?}",
panel.shows("Reset Profiles")
);
// No three-dot menu buttons appear next to any profile row.
assert!(!panel.shows("More (Uniform)"));
assert!(!panel.shows("More (Wave)"));
assert!(!panel.shows(&format!("More ({saved_label})")));
// Clicking Reset Profiles closes the dropdown and opens the confirmation prompt ("Do you want to reset profiles?").
panel.click("Reset Profiles");
assert!(!panel.shows("Add to Profiles"), "dropdown closes when confirmation prompt opens");
let ctx = panel.ctx().clone();
{
let mut app = panel.app();
let (message, _, command) = crate::dialogs::confirm::open_question(&app).expect("reset confirmation is open");
assert_eq!(message, "Do you want to reset profiles?");
assert_eq!(command, "stroke.widthProfile.reset");
app.dialogs().unwrap().with(|host| {
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
assert!(host.cancel_by_id(&ctx, qid));
});
crate::dialogs::confirm::pump(&mut app, &ctx);
assert!(app.session.profile_entries().any(|e| !e.built_in), "cancelling reset preserves profiles");
}
// Confirming OK executes the reset and restores deleted built-ins.
panel.click_role("Profile", Role::COMBO_BOX);
panel.click("Reset Profiles");
let mut app = panel.app();
app.dialogs().unwrap().with(|host| {
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
host.set_json_field(&ctx, qid, "choice", serde_json::json!("proceed")).unwrap();
assert!(host.confirm_by_id(&ctx, qid));
});
crate::dialogs::confirm::pump(&mut app, &ctx);
assert!(app.session.profile_entries().all(|e| e.built_in), "Reset Profiles clears saved presets");
assert!(app.session.profile_entries().any(|e| e.id == "taperStart"), "Reset Profiles restores deleted built-ins");
}
#[test]
fn dropdown_reordering_moves_presets_via_row_menu_and_keeps_uniform_pinned() {
use craft::ui::contract::Role;
let mut session = vectorcraft_engine::Session::new();
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": "Mine"})).unwrap();
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown shrinks to compact width: {:?}", panel.rect("Profile"));
panel.click_role("Profile", Role::COMBO_BOX);
// Uniform's context menu only exposes Reset Profiles and never offers Move Up / Move Down.
panel.secondary_click("Uniform");
assert!(panel.shows_role("Reset Profiles", Role::MENU_ITEM), "Uniform menu shows Reset Profiles");
assert!(!panel.shows("Move Up"), "Uniform cannot move up");
assert!(!panel.shows("Move Down"), "Uniform cannot move down");
assert!(!panel.shows_role("Delete Profile", Role::MENU_ITEM), "Uniform cannot be deleted");
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
// Moving saved profile "Mine" up moves it ahead of Wave while leaving Uniform at index 0.
panel.secondary_click("Mine");
assert!(panel.shows_role("Rename…", Role::MENU_ITEM), "saved profile exposes Rename…");
assert!(panel.shows_role("Delete Profile", Role::MENU_ITEM), "saved profile exposes Delete Profile");
panel.click("Move Up");
let ids: Vec<String> = panel.app().session.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(ids[0], "uniform", "Uniform remains pinned first after reordering");
assert_eq!(ids[ids.len() - 2], "Mine", "Mine moves up one slot before Wave");
// Move built-in "Wave" up past "Mine" too.
panel.secondary_click("Wave");
panel.click("Move Up");
let ids_after: Vec<String> = panel.app().session.profile_entries().map(|e| e.id.to_owned()).collect();
assert_eq!(ids_after[0], "uniform");
let wave_pos = ids_after.iter().position(|id| id == "wave").unwrap();
let mine_pos = ids_after.iter().position(|id| id == "Mine").unwrap();
assert!(wave_pos < mine_pos, "built-in preset reorders past saved profile: {ids_after:?}");
}
#[test]
fn dropdown_expands_into_available_vertical_space() {
use craft::ui::contract::Role;
let mut session = vectorcraft_engine::Session::new();
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
for i in 0..10 {
session
.execute(
"stroke.widthPoint.set",
&serde_json::json!({"id": id, "t": 0.25 + 0.05 * f64::from(i), "left": 8.0 + f64::from(i), "right": 4.0}),
)
.unwrap();
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": format!("Saved {i}")})).unwrap();
}
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown stays compact even with custom profiles: {:?}", panel.rect("Profile"));
panel.click_role("Profile", Role::COMBO_BOX);
assert!(panel.shows("Saved 9"), "dropdown expands past 12 rows when space is available");
assert!(
panel.rect("Saved 9").bottom() - panel.rect("Uniform").top() > 350.0,
"dropdown opens taller when vertical space allows: uniform={:?}, last={:?}",
panel.rect("Uniform"),
panel.rect("Saved 9")
);
assert!(panel.shows("Reset Profiles"), "footer remains visible with expanded list");
}