Stroke: leave profile reordering and renaming out of the footer change

stroke.widthProfile.move, Prefs::width_profile_order, the drag and Move
Up/Move Down reordering, stroke.widthProfile.rename and the row menu's
Rename item are taken out, along with their tests, so this change holds
the drop-down footer alone. Reordering and renaming go to their own pull
requests. Dragging a row onto the footer's trash button goes with the
row drag. The engine's width profile commands are now the same as on
main.

A saved row's right-click menu keeps Delete Profile; built-in rows have
no menu.
This commit is contained in:
dotCooCoo
2026-12-05 07:39:22 -08:00
parent 8a7ed03908
commit bd1186eb32
6 changed files with 41 additions and 349 deletions
+8 -127
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, index_opt, ok, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -77,27 +77,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profiles",
[],
None,
"{} remove every saved profile and restore the default 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}",
"{} remove every saved profile, leaving the built-ins → {removed: count}",
has_saved_profiles,
profile_rename
profile_reset
),
cmd!(
query "stroke.widthProfile.list",
@@ -728,37 +710,12 @@ impl ProfileEntry<'_> {
}
impl Session {
/// The Profile list: Uniform first, then the built-in and saved profiles in [`Prefs::width_profile_order`].
/// The Profile list: the built-in profiles, then the saved ones.
pub fn profile_entries(&self) -> impl Iterator<Item = ProfileEntry<'_>> {
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()
.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()
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)
}
/// The Profile list row showing `p` (`None`: the plain stroke), if it is listed.
@@ -802,23 +759,6 @@ 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 can_reset_profiles(s: &Session) -> std::result::Result<(), String> {
if s.prefs.width_profiles.is_empty() && s.prefs.width_profile_order.is_empty() {
Err("no saved profiles".into())
} else {
Ok(())
}
}
/// The default order of reorderable profiles (the built-ins after Uniform, then saved profiles).
fn default_profile_order(s: &Session) -> Vec<String> {
WidthProfile::PRESETS[1..]
.iter()
.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))?;
@@ -829,9 +769,6 @@ 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 }))
}
@@ -850,70 +787,14 @@ fn profile_delete(s: &mut Session, p: &Value) -> Result<Value> {
}
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);
s.prefs.width_profile_order.retain(|id| id != &name);
if s.prefs.width_profile_order == default_profile_order(s) {
s.prefs.width_profile_order.clear();
}
Ok(json!({ "deleted": name }))
}
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();
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()
-6
View File
@@ -373,11 +373,6 @@ 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>,
/// 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;
@@ -737,7 +732,6 @@ impl Default for Prefs {
trace_presets: vec![],
gradient_presets: vec![],
width_profiles: vec![],
width_profile_order: vec![],
japanese_crop_marks: false,
new_art_basic: true,
color_themes: vec![],
-60
View File
@@ -138,63 +138,3 @@ 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");
}
-7
View File
@@ -921,7 +921,6 @@ pub(crate) fn profile_select(app: &mut VectorcraftApp, ui: &mut Ui) {
&& 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 {
@@ -954,12 +953,6 @@ fn apply_profile_action(app: &mut VectorcraftApp, action: ProfileAction) {
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}));
}
}
}
@@ -1,7 +1,7 @@
//! 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.
//! profile list with built-in labels and captionless user-added thumbnails, a right-click Delete
//! Profile on saved rows, and a footer bar with Add to Profiles…, Delete Profile, and Reset
//! Profiles.
use std::borrow::Cow;
use std::collections::HashSet;
@@ -9,14 +9,14 @@ use std::collections::HashSet;
use craft::behavior::nav::{StepResult, ValueAxes, ValueSteps};
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, WheelPhase, wheel_step,
CancelReason, ColumnKey, ColumnWidth, DisplayOrder, GesturePhase, HitLevel, HitPriority, IconId, ItemSource, Metrics, NavMove, PartKey,
Proposal, Selection, Sense, TypeAhead, WheelPhase, wheel_step,
};
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,
LeadOnOpen, LeadSource, MeasureCx, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Popup, PopupHandle, Props, Role,
Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _,
};
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize};
@@ -31,7 +31,6 @@ use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::style::{ComponentStyle, StyleCx, SurfaceLook};
use egui::{Rect, Response, Vec2};
const UNIFORM_ID: &str = "uniform";
const PROFILE_COL: ColumnKey = ColumnKey::new("profile");
const DROPDOWN_MIN_WIDTH: f32 = 132.0;
const CLOSED_MAX_WIDTH: f32 = 145.0;
@@ -55,10 +54,6 @@ impl ProfileRowKey {
ProfileRowKey::Separator => None,
}
}
fn is_reorderable(&self) -> bool {
self.profile().is_some_and(|id| id != UNIFORM_ID)
}
}
/// One silhouette sample `(t, left_offset, right_offset)` returned by `stroke::silhouette`.
@@ -135,27 +130,24 @@ pub(super) struct ProfileOption {
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.
/// Built-in profiles keep their text captions in the dropdown and cannot be deleted.
pub built_in: bool,
}
/// Enable state for the management controls inside the dropdown footer and row menu.
/// Enable state for the management controls inside the dropdown footer.
#[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.
/// A management action requested by the dropdown footer or a saved row's menu.
#[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.
@@ -453,8 +445,7 @@ impl Component for ProfileSelect {
cx.memory::<PickerMemory>().reveal_on_open.take().or_else(|| fresh.then(|| current.clone()).flatten()).map(ProfileRowKey::Profile);
let selection = current.as_ref().map_or_else(Selection::default, |id| Selection::single(ProfileRowKey::Profile(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_ref(), saved: &saved, can_reorder };
let view = PopupView { list_id, selection: &selection, reveal: reveal.as_ref(), saved: &saved };
let body_out = ui.show(popup, overlay, |ui, _| show_popup_body(ui, cx, self, view));
@@ -511,24 +502,6 @@ impl ProfileSelect {
cx.memory::<PickerMemory>().previewed = false;
popup.close(cx);
}
CollectionEvent::Reorder(EditEvent::Set { after, .. } | EditEvent::Commit { after, .. }) => {
if let ProfileRowKey::Profile(key) = &after.key
&& key != UNIFORM_ID
{
self.action = Some(ProfileAction::Move { name: 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 ProfileRowKey::Profile(key) = &rename.key
{
let trimmed = rename.name.trim();
if !trimmed.is_empty() && trimmed != key {
self.action = Some(ProfileAction::Rename { name: key.clone(), to: trimmed.to_owned() });
}
}
}
_ => {}
}
}
@@ -541,7 +514,6 @@ struct PopupView<'a> {
selection: &'a Selection<ProfileRowKey>,
reveal: Option<&'a ProfileRowKey>,
saved: &'a HashSet<String>,
can_reorder: bool,
}
fn show_popup_body(
@@ -563,10 +535,9 @@ fn show_popup_body(
Stack::new()
.fill_width()
.footer(|ui, _| {
footer_action = show_footer(ui, view.list_id, actions, view.saved);
footer_action = show_footer(ui, actions);
})
.show(ui, |ui, _| {
let saved_for_rename = view.saved.clone();
let mut list = List::<ProfileRowKey>::options(label.clone())
.id(view.list_id)
.header(false)
@@ -574,15 +545,7 @@ fn show_popup_body(
.hover_lead(HoverLead::Lead)
.activate(ActivateOn::Click)
.lead_on_open(LeadOnOpen::First)
.selection(Bind::given(view.selection.clone()))
.can_rename(move |key: &ProfileRowKey| key.profile().is_some_and(|id| saved_for_rename.contains(id)));
if view.can_reorder {
list = list
.can_drag(|key: &ProfileRowKey| key.is_reorderable())
.reorder(ReorderRule::new())
.accepts(|drag, _, insert| drag.keys.iter().all(ProfileRowKey::is_reorderable) && insert >= 2);
}
.selection(Bind::given(view.selection.clone()));
if let Some(key) = view.reveal {
list = list.reveal(key.clone());
}
@@ -615,40 +578,28 @@ fn show_popup_body(
let list_response = list_resp.unwrap_or_else(|| ui.response().clone());
for event in &events {
// Only a saved row has a menu: its one item deletes it, and a built-in can't be deleted.
if let CollectionEvent::ContextMenu(request) = event
&& let Some(id) = request.key.profile()
&& view.saved.contains(id)
{
cx.memory::<PickerMemory>().menu = Some(id.to_owned());
}
}
let menu_action = show_row_menu(ui, cx, picker, view.list_id, &list_response, view.saved);
let menu_action = show_row_menu(ui, cx, picker, &list_response);
(events, footer_action, menu_action)
}
fn show_footer(ui: &mut egui::Ui, list_id: egui::Id, actions: ProfileActions, saved: &HashSet<String>) -> Option<ProfileAction> {
// Only saved profiles can be deleted; the built-in ones stay in the list.
let droppable = saved.clone();
let is_saved = move |key: &ProfileRowKey| key.profile().is_some_and(|id| droppable.contains(id));
fn show_footer(ui: &mut egui::Ui, 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<ProfileRowKey>>(move |drag| drag.list == list_id && drag.keys.iter().any(&is_saved)),
FooterAction::new(IconId::new("trash-2"), tl!("Delete Profile")).enabled(actions.can_delete),
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(id) = drop.payload::<ListDrag<ProfileRowKey>>().and_then(|d| d.keys.iter().find_map(ProfileRowKey::profile))
&& saved.contains(id)
{
return Some(ProfileAction::Delete(Some(id.to_owned())));
}
match bar.picked {
Some(0) => Some(ProfileAction::Reset),
Some(1) => Some(ProfileAction::Delete(None)),
@@ -657,56 +608,21 @@ fn show_footer(ui: &mut egui::Ui, list_id: egui::Id, actions: ProfileActions, sa
}
}
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> {
fn show_row_menu(ui: &mut egui::Ui, cx: &mut Cx<'_, ProfileSelect>, picker: &ProfileSelect, anchor: &Response) -> Option<ProfileAction> {
let target = cx.memory::<PickerMemory>().menu.clone()?;
let Some(entry) = picker.option(&target) else {
let Some(entry) = picker.option(&target).filter(|e| !e.built_in) 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 is_saved && MenuItem::new(tl!("Delete Profile")).show(ui).ran {
if MenuItem::new(tl!("Delete Profile")).show(ui).ran {
action = Some(ProfileAction::Delete(Some(target.clone())));
}
});
if start_rename {
request_rename(ui, list_id, &ProfileRowKey::Profile(target));
}
if action.is_some() || start_rename || shown.closed.is_some() {
if action.is_some() || shown.closed.is_some() {
cx.memory::<PickerMemory>().menu = None;
}
action
+11 -43
View File
@@ -325,7 +325,6 @@ fn arrowhead_select_lists_the_notched_arrow_after_arrow() {
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();
@@ -368,21 +367,6 @@ fn dropdown_footer_manages_profiles_and_confirms_reset() {
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)"));
@@ -419,7 +403,7 @@ fn dropdown_footer_manages_profiles_and_confirms_reset() {
}
#[test]
fn dropdown_reordering_moves_presets_via_row_menu_and_keeps_uniform_pinned() {
fn dropdown_row_menu_deletes_saved_profiles_only() {
use craft::ui::contract::Role;
let mut session = vectorcraft_engine::Session::new();
@@ -431,36 +415,20 @@ fn dropdown_reordering_moves_presets_via_row_menu_and_keeps_uniform_pinned() {
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);
// A built-in row offers no Delete Profile.
for built_in in ["Uniform", "Wave"] {
panel.secondary_click(built_in);
assert!(!panel.shows_role("Delete Profile", Role::MENU_ITEM), "{built_in} can't be deleted");
}
// Moving saved profile "Mine" up moves it ahead of Wave while leaving Uniform at index 0.
// A saved row's menu deletes it.
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:?}");
assert!(panel.shows_role("Delete Profile", Role::MENU_ITEM), "a saved profile offers Delete Profile");
panel.click_menu_item("Delete Profile");
assert!(!panel.app().session.profile_entries().any(|e| e.id == "Mine"), "the saved profile is deleted");
assert!(panel.app().session.profile_entries().any(|e| e.id == "wave"), "the built-ins stay");
}
#[test]