mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
document-panels-w11: net change of 1 commits
- document-panels-w11: written by an agent
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,139 +1,130 @@
|
||||
//! Layers panel › Panel Options…: Show Layers Only, Locate Selected Objects, the row size and
|
||||
//! which rows show thumbnails.
|
||||
//!
|
||||
//! Fields: `layersOnly`, `locateSelected`, `rowSize` (`small`, `medium`, `large` or `other`),
|
||||
//! `otherSize` (points, 12–100, for `other`), `thumbLayers`, `thumbGroups` and `thumbObjects`. OK
|
||||
//! applies them to the panel (kept with the UI state).
|
||||
//! Fields: `layersOnly`, `locateSelected`, `rowSize` (`small`, `medium` or `large`), `thumbLayers`,
|
||||
//! `thumbGroups` and `thumbObjects`. OK applies them to the panel (kept with the UI state).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::DialogSpec;
|
||||
use super::swatch_options::{grid, label};
|
||||
use crate::panels::layers::{PanelOptions, ROW_LARGE, ROW_MEDIUM, ROW_SMALL};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::host::open_held;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::layers::{PanelOptions, RowSize};
|
||||
|
||||
/// The dialog kind of the Layers Panel Options.
|
||||
pub const KIND: &str = "layersPanelOptions";
|
||||
/// The command Layers Panel Options answers for; the key of its dialog.
|
||||
const CMD: &str = "ui.layersPanelOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Layers Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM };
|
||||
/// The row sizes the dialog offers: the field's value and the size it stands for.
|
||||
const SIZES: [(&str, RowSize); 3] = [("small", RowSize::Small), ("medium", RowSize::Medium), ("large", RowSize::Large)];
|
||||
|
||||
const SIZES: [(&str, &str, f32); 3] = [("small", "Small", ROW_SMALL), ("medium", "Medium", ROW_MEDIUM), ("large", "Large", ROW_LARGE)];
|
||||
/// The dialog's rows.
|
||||
// PLAN: the sheet names `Param::bool`/`Param::choice`; the framework has `Param::new(key, label, ParamKind::..)` only.
|
||||
fn rows() -> Vec<Param> {
|
||||
let sizes = [("small", tl!("Small")), ("medium", tl!("Medium")), ("large", tl!("Large"))];
|
||||
let sizes = sizes.into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect();
|
||||
vec![
|
||||
Param::new("layersOnly", tl!("Show Layers Only"), ParamKind::bool(false)),
|
||||
Param::new("locateSelected", tl!("Locate Selected Objects"), ParamKind::bool(false)),
|
||||
Param::new("rowSize", tl!("Row Size:"), ParamKind::choice(sizes, Some("medium".to_owned()))),
|
||||
Param::section(tl!("Thumbnails:")),
|
||||
Param::new("thumbLayers", tl!("Layers"), ParamKind::bool(true)),
|
||||
Param::new("thumbGroups", tl!("Group"), ParamKind::bool(true)),
|
||||
Param::new("thumbObjects", tl!("Object"), ParamKind::bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
/// `ui.layersPanelOptions`: open the dialog on the panel's options.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let o = &app.ui.layers_panel;
|
||||
let size = SIZES.iter().find(|s| (s.2 - o.row()).abs() < 0.01).map_or("other", |s| s.0);
|
||||
let fields = json!({
|
||||
"layersOnly": o.layers_only, "locateSelected": o.locate_selected, "rowSize": size, "otherSize": o.row(),
|
||||
"thumbLayers": o.thumb_layers, "thumbGroups": o.thumb_groups, "thumbObjects": o.thumb_objects,
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("layersOnly", o.layers_only);
|
||||
fields.set("locateSelected", o.locate_selected);
|
||||
fields.set("rowSize", SIZES.iter().find(|s| s.1 == o.row_size).map_or("medium", |s| s.0));
|
||||
fields.set("thumbLayers", o.thumb_layers);
|
||||
fields.set("thumbGroups", o.thumb_groups);
|
||||
fields.set("thumbObjects", o.thumb_objects);
|
||||
let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| {
|
||||
ParamDialog::command(CMD, tl!("Layers Panel Options"), rows()).values(Bind::bound(fields))
|
||||
});
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
|
||||
let f = &result.fields;
|
||||
let flag = |key: &str| f.bool(key).unwrap_or_default();
|
||||
app.ui.layers_panel = PanelOptions {
|
||||
layers_only: flag("layersOnly"),
|
||||
locate_selected: flag("locateSelected"),
|
||||
row_size: SIZES.iter().find(|s| Some(s.0) == f.text("rowSize")).map_or(RowSize::Medium, |s| s.1),
|
||||
thumb_layers: flag("thumbLayers"),
|
||||
thumb_groups: flag("thumbGroups"),
|
||||
thumb_objects: flag("thumbObjects"),
|
||||
};
|
||||
Ok(())
|
||||
};
|
||||
open_held(app, dialog, ok).ok_or("no window")?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) {
|
||||
let v = d.bool(key);
|
||||
if widgets::check(ui, text, v, true) {
|
||||
d.fields.insert(key.into(), json!(!v));
|
||||
}
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
check(ui, d, "layersOnly", tl!("Show Layers Only"));
|
||||
check(ui, d, "locateSelected", tl!("Locate Selected Objects"));
|
||||
ui.add_space(8.0);
|
||||
grid(ui, |ui| {
|
||||
label(ui, tl!("Row Size:"));
|
||||
ui.horizontal(|ui| {
|
||||
let cur = d.str("rowSize");
|
||||
let labels: Vec<&str> = SIZES.iter().map(|s| s.1).chain(["Other"]).collect();
|
||||
let shown = SIZES.iter().find(|s| s.0 == cur).map_or("Other", |s| s.1);
|
||||
if let Some(i) = widgets::dropdown(ui, "layers-row-size", shown, &labels, 110.0) {
|
||||
d.fields.insert("rowSize".into(), json!(SIZES.get(i).map_or("other", |s| s.0)));
|
||||
}
|
||||
let v = d.f64("otherSize", f64::from(ROW_MEDIUM));
|
||||
let other = d.str("rowSize") == "other";
|
||||
if let Some(v) = ui.add_enabled_ui(other, |ui| widgets::range_field(ui, "otherSize", v, 12.0..=100.0, " pt", 0, 60.0)).inner {
|
||||
d.fields.insert("otherSize".into(), json!(v));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
label(ui, tl!("Thumbnails:"));
|
||||
check(ui, d, "thumbLayers", tl!("Layers"));
|
||||
check(ui, d, "thumbGroups", tl!("Group"));
|
||||
check(ui, d, "thumbObjects", tl!("Object"));
|
||||
false
|
||||
}
|
||||
|
||||
/// The options the fields describe.
|
||||
pub(crate) fn options(d: &Dialog) -> PanelOptions {
|
||||
let size = d.str("rowSize");
|
||||
let row_size = SIZES.iter().find(|s| s.0 == size).map_or_else(|| (d.f64("otherSize", f64::from(ROW_MEDIUM)) as f32).clamp(12.0, 100.0), |s| s.2);
|
||||
PanelOptions {
|
||||
layers_only: d.bool("layersOnly"),
|
||||
locate_selected: d.bool("locateSelected"),
|
||||
row_size: if row_size.is_finite() { row_size } else { ROW_MEDIUM },
|
||||
thumb_layers: d.bool("thumbLayers"),
|
||||
thumb_groups: d.bool("thumbGroups"),
|
||||
thumb_objects: d.bool("thumbObjects"),
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
app.ui.layers_panel = options(d);
|
||||
app.ui.dialog = None;
|
||||
Ok(serde_json::to_value(&app.ui.layers_panel).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(egui::Context::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// The open dialog's id and fields.
|
||||
fn open_dialog(app: &VectorcraftApp) -> (craft::ui::dialog::DialogId, Value) {
|
||||
let open = app.dialogs().unwrap().with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(CMD))).unwrap();
|
||||
(open.id, open.fields.unwrap())
|
||||
}
|
||||
|
||||
/// Sets `edits` in the open dialog, presses OK and runs the host pump, which runs the held OK.
|
||||
fn apply(app: &mut VectorcraftApp, edits: &[(&str, Value)]) {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let (id, _) = open_dialog(app);
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
for (field, value) in edits {
|
||||
dialogs.with(|host| host.set_json_field(&ctx, id, field, value.clone())).unwrap();
|
||||
}
|
||||
dialogs.with(|host| host.confirm_by_id(&ctx, id));
|
||||
crate::dialogs::host::pump(app, &ctx);
|
||||
dialogs.with(|host| host.confirm_by_id(&ctx, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_options_round_trip_and_apply() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let mut app = app();
|
||||
app.run("ui.layersPanelOptions", json!({})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("rowSize"), "medium");
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("layersOnly".into(), json!(true));
|
||||
d.fields.insert("rowSize".into(), json!("other"));
|
||||
d.fields.insert("otherSize".into(), json!(500));
|
||||
d.fields.insert("thumbObjects".into(), json!(false));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(open_dialog(&app).1["rowSize"], json!("medium"));
|
||||
apply(&mut app, &[("layersOnly", json!(true)), ("rowSize", json!("large")), ("thumbObjects", json!(false))]);
|
||||
let o = &app.ui.layers_panel;
|
||||
assert!(o.layers_only && !o.thumb_objects && o.thumb_layers);
|
||||
assert_eq!(o.row(), 100.0, "kept to 100 pt");
|
||||
assert_eq!(o.row_size, RowSize::Large);
|
||||
app.run("ui.layersPanelOptions", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("rowSize".into(), json!("large"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(app.ui.layers_panel.row(), ROW_LARGE);
|
||||
assert_eq!(open_dialog(&app).1["rowSize"], json!("large"), "opens on the saved size");
|
||||
// Options saved with a row height in points load as the nearest size.
|
||||
let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"rowSize": 500}})).unwrap();
|
||||
assert_eq!(old.layers_panel.row_size, RowSize::Large);
|
||||
}
|
||||
|
||||
/// Locate Selected Objects is off by default and in options saved without it; OK turns it on
|
||||
/// and keeps it with the UI state, and the dialog opens on it again.
|
||||
#[test]
|
||||
fn locate_selected_objects_is_off_by_default_and_kept_with_the_ui_state() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let mut app = app();
|
||||
app.run("ui.layersPanelOptions", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
assert_eq!(d.fields.get("locateSelected"), Some(&json!(false)));
|
||||
d.fields.insert("locateSelected".into(), json!(true));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(open_dialog(&app).1["locateSelected"], json!(false));
|
||||
apply(&mut app, &[("locateSelected", json!(true))]);
|
||||
let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
|
||||
assert!(back.layers_panel.locate_selected, "kept with the UI state");
|
||||
app.run("ui.layersPanelOptions", json!({})).unwrap();
|
||||
assert!(app.ui.dialog.as_ref().unwrap().bool("locateSelected"));
|
||||
assert_eq!(open_dialog(&app).1["locateSelected"], json!(true));
|
||||
let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap();
|
||||
assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it");
|
||||
}
|
||||
|
||||
@@ -1,63 +1,162 @@
|
||||
//! Navigator panel › Panel Options…: the color the view box is drawn in, a preset or a custom
|
||||
//! color, and Draw Dashed Lines as Solid Lines for the thumbnail.
|
||||
//!
|
||||
//! Fields: `color` (`#rrggbb`, or a preset's name such as "Light Red") and `solidDashes`. OK runs
|
||||
//! Fields: `color` (`#rrggbb`; a preset's name such as "Light Red" is read too) and `solidDashes`. OK runs
|
||||
//! `ui.navigatorPanelOptions` with them (kept with the UI state).
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use craft::color_ui::{ChosenColor, ColorChoice, NamedColor};
|
||||
use craft::theme::Srgba;
|
||||
use craft::ui::contract::{Bind, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::patterns::form_dialogs::FormDialog;
|
||||
use craft::ui::runtime::requests::ColorRequest;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
|
||||
use super::swatch_options::{grid, label};
|
||||
use super::{DialogSpec, run_and_close};
|
||||
use super::layer_options::{check, rgb8, srgb};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::navigator::{VIEW_BOX_RED, resolve, view_box_colors};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of the Navigator Panel Options.
|
||||
pub const KIND: &str = "navigatorPanelOptions";
|
||||
/// The key of the Navigator Panel Options dialog.
|
||||
const KEY: &str = "ui.navigatorPanelOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Navigator Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM };
|
||||
/// The options the dialog edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct NavigatorOptionsValue {
|
||||
/// The view box's colour: a preset's, or any other the Custom row holds.
|
||||
rgb: [u8; 3],
|
||||
solid_dashes: bool,
|
||||
}
|
||||
|
||||
impl NavigatorOptionsValue {
|
||||
/// The colour as `ui.navigatorPanelOptions` takes it.
|
||||
fn color_text(&self) -> String {
|
||||
let [r, g, b] = self.rgb;
|
||||
Color::rgb8(r, g, b).to_hex()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NavigatorOptionsValue {
|
||||
fn default() -> Self {
|
||||
NavigatorOptionsValue { rgb: VIEW_BOX_RED, solid_dashes: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.navigatorPanelOptions` without options: open the dialog on the panel's options.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let o = &app.ui.navigator_panel;
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({ "color": o.color, "solidDashes": o.solid_dashes })));
|
||||
let value = NavigatorOptionsValue { rgb: resolve(&o.color).unwrap_or(VIEW_BOX_RED), solid_dashes: o.solid_dashes };
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
dialogs.with(|host| host.open(NavigatorOptionsDialog::new(value)));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let [r, g, b] = resolve(&d.str("color")).unwrap_or(VIEW_BOX_RED);
|
||||
let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect();
|
||||
let preset = presets.iter().position(|(_, c)| *c == [r, g, b]);
|
||||
let names: Vec<&str> = presets.iter().map(|(n, _)| *n).chain(["Custom"]).collect();
|
||||
grid(ui, |ui| {
|
||||
label(ui, tl!("Color:"));
|
||||
ui.horizontal(|ui| {
|
||||
if let Some((_, [r, g, b])) =
|
||||
widgets::dropdown(ui, "navigator-view-box", names[preset.unwrap_or(presets.len())], &names, 140.0).and_then(|i| presets.get(i))
|
||||
{
|
||||
d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex()));
|
||||
}
|
||||
// Any other color (the preset list shows Custom then).
|
||||
let mut rgb = [r, g, b];
|
||||
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||
d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex()));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
let solid = d.bool("solidDashes");
|
||||
if widgets::check(ui, tl!("Draw Dashed Lines as Solid Lines"), solid, true) {
|
||||
d.fields.insert("solidDashes".into(), json!(!solid));
|
||||
}
|
||||
false
|
||||
/// The Navigator Panel Options dialog; its answer is the options OK confirmed, which [`pump`] applies.
|
||||
pub(crate) struct NavigatorOptionsDialog {
|
||||
id: DialogId,
|
||||
open: bool,
|
||||
value: NavigatorOptionsValue,
|
||||
/// The Custom… press, until the app takes it.
|
||||
color_request: Option<ColorRequest>,
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let params = json!({ "color": d.fields.get("color").cloned().unwrap_or(Value::Null), "solidDashes": d.bool("solidDashes") });
|
||||
run_and_close(app, "ui.navigatorPanelOptions", params)
|
||||
impl NavigatorOptionsDialog {
|
||||
/// The dialog over `value`.
|
||||
fn new(value: NavigatorOptionsValue) -> Self {
|
||||
NavigatorOptionsDialog { id: dialog_id(KEY), open: true, value, color_request: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for NavigatorOptionsDialog {
|
||||
type Result = NavigatorOptionsValue;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<NavigatorOptionsValue>> {
|
||||
let requested = RefCell::new(None);
|
||||
let shown = FormDialog::new(tl!("Navigator Panel Options"), Bind::bound(&mut self.value)).opened(Bind::bound(&mut self.open)).show(
|
||||
ui,
|
||||
|ui, _, v| {
|
||||
Field::new(tl!("Color:")).id_salt("color").show(ui, |ui, _| {
|
||||
let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect();
|
||||
let preset = presets.iter().find(|(_, c)| *c == v.rgb);
|
||||
let chosen = preset.map_or(ChosenColor::Custom, |(name, _)| ChosenColor::Named((*name).to_owned()));
|
||||
let named = presets.iter().map(|&(name, c)| NamedColor::new(name, name.to_string(), Some(srgb(c))));
|
||||
let custom = preset.is_none().then(|| srgb(v.rgb));
|
||||
let out = ColorChoice::new(tl!("Color:"), &chosen).named(named).custom(custom).show(ui);
|
||||
if let Some(ChosenColor::Named(picked)) = out.chosen
|
||||
&& let Some((_, c)) = presets.iter().find(|(name, _)| *name == picked)
|
||||
{
|
||||
v.rgb = *c;
|
||||
}
|
||||
// A second pass of the frame has no press: only a request keeps what the first pass asked for.
|
||||
if let Some(request) = out.pick_color {
|
||||
*requested.borrow_mut() = Some(request);
|
||||
}
|
||||
});
|
||||
if let Some(on) = check(ui, tl!("Draw Dashed Lines as Solid Lines"), v.solid_dashes, true) {
|
||||
v.solid_dashes = on;
|
||||
}
|
||||
true
|
||||
},
|
||||
);
|
||||
if let Some(request) = requested.into_inner() {
|
||||
self.color_request = Some(request);
|
||||
}
|
||||
match (shown.accepted, shown.closed) {
|
||||
(Some(value), _) => Some(DialogResult::Ok(value)),
|
||||
(None, Some(_)) => Some(DialogResult::Cancel),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &egui::Context) -> Option<NavigatorOptionsValue> {
|
||||
Some(self.value.clone())
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
Some(json!({ "color": self.value.color_text(), "solidDashes": self.value.solid_dashes }))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> {
|
||||
let rejects = || FieldRefusal::Rejects(&value).message(field);
|
||||
match field {
|
||||
"color" => self.value.rgb = value.as_str().and_then(resolve).ok_or_else(rejects)?,
|
||||
"solidDashes" => self.value.solid_dashes = value.as_bool().ok_or_else(rejects)?,
|
||||
_ => return Err(FieldRefusal::Unknown.message(field)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take_color_request(&mut self) -> Option<ColorRequest> {
|
||||
self.color_request.take()
|
||||
}
|
||||
|
||||
fn answer_color(&mut self, key: &str, color: Srgba) {
|
||||
if key == ColorChoice::CUSTOM_KEY {
|
||||
self.value.rgb = rgb8(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the options OK confirmed; an error from the command goes to the status line.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let Some(DialogResult::Ok(value)) = dialogs.with(|host| host.take::<NavigatorOptionsDialog>()) else { return };
|
||||
let params = json!({ "color": value.color_text(), "solidDashes": value.solid_dashes });
|
||||
if let Err(e) = app.run("ui.navigatorPanelOptions", params) {
|
||||
app.status(e);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -65,34 +164,49 @@ mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(egui::Context::default());
|
||||
app
|
||||
}
|
||||
|
||||
/// The open dialog's id and fields.
|
||||
fn open_dialog(app: &VectorcraftApp) -> (DialogId, Value) {
|
||||
let open = app.dialogs().unwrap().with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(KEY))).unwrap();
|
||||
(open.id, open.fields.unwrap())
|
||||
}
|
||||
|
||||
/// Sets the dialog's `color` and `solidDashes`, presses OK and runs the host pump.
|
||||
fn apply(app: &mut VectorcraftApp, color: &str, solid: bool) {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let (id, _) = open_dialog(app);
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
dialogs.with(|host| host.set_json_field(&ctx, id, "color", json!(color))).unwrap();
|
||||
dialogs.with(|host| host.set_json_field(&ctx, id, "solidDashes", json!(solid))).unwrap();
|
||||
dialogs.with(|host| host.confirm_by_id(&ctx, id));
|
||||
crate::dialogs::host::pump(app, &ctx);
|
||||
}
|
||||
|
||||
/// The dialog opens on the panel's options (Light Red and solid dashes off by default), and OK
|
||||
/// sets a preset's or a custom color and Draw Dashed Lines as Solid Lines, kept with the UI
|
||||
/// state; a value that is not a color is refused and leaves the options as they were.
|
||||
#[test]
|
||||
fn panel_options_set_the_view_box_color_and_solid_dashes() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let mut app = app();
|
||||
app.run("ui.navigatorPanelOptions", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.kind.as_str(), d.str("color"), d.bool("solidDashes")), (KIND, "#ff3030".to_string(), false));
|
||||
// Drawn headlessly in the shared frame: the preset's name shows.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let set = |app: &mut VectorcraftApp, color: &str, solid: bool| {
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("color".into(), json!(color));
|
||||
d.fields.insert("solidDashes".into(), json!(solid));
|
||||
super::super::confirm(app)
|
||||
};
|
||||
assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true}));
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let f = open_dialog(&app).1;
|
||||
assert_eq!((f["color"].as_str(), f["solidDashes"].as_bool()), (Some("#ff3030"), Some(false)));
|
||||
apply(&mut app, "Green", true);
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_eq!((app.ui.navigator_panel.color.as_str(), app.ui.navigator_panel.solid_dashes), ("#4fff4f", true));
|
||||
app.run("ui.navigatorPanelOptions", json!({})).unwrap();
|
||||
set(&mut app, "#0000FF", true).unwrap();
|
||||
apply(&mut app, "#0000FF", true);
|
||||
assert_eq!(app.ui.navigator_panel.color, "#0000ff");
|
||||
app.run("ui.navigatorPanelOptions", json!({})).unwrap();
|
||||
assert!(set(&mut app, "nope", false).is_err());
|
||||
assert!(app.ui.navigator_panel.solid_dashes && app.ui.navigator_panel.color == "#0000ff", "a refused value changes nothing");
|
||||
let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), open_dialog(&app));
|
||||
let refused = app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, "color", json!("nope")));
|
||||
assert!(refused.is_err());
|
||||
assert_eq!(open_dialog(&app).1["color"], json!("#0000ff"), "a refused value changes nothing");
|
||||
let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
|
||||
assert_eq!(back.navigator_panel, app.ui.navigator_panel, "kept with the UI state");
|
||||
let old: crate::UiState = serde_json::from_value(json!({})).unwrap();
|
||||
|
||||
@@ -7,121 +7,285 @@
|
||||
//! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` |
|
||||
//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`.
|
||||
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::patterns::form_dialogs::FormDialog;
|
||||
use craft::ui::primitives::{Glyph, IconSpec};
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind};
|
||||
use craft::ui::style::{TypeRole, UiTokens};
|
||||
use craft::ui::text::NumberField;
|
||||
use craft::ui::choice::Segmented;
|
||||
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_engine::cmd::newdoc::ArtboardLayout;
|
||||
|
||||
use super::{DialogSpec, form, run_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::layer_options::check;
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// The dialog kind of Rearrange All Artboards.
|
||||
pub const KIND: &str = "rearrangeArtboards";
|
||||
/// The command Rearrange All Artboards runs; the key of its dialog.
|
||||
pub(crate) const CMD: &str = "artboard.rearrange";
|
||||
|
||||
const CMD: &str = "artboard.rearrange";
|
||||
/// A layout toggle's picture: small artboards in the grid cells (column, row), tinted, and over them their order as a
|
||||
/// line from a dot on the first to an arrowhead on the last.
|
||||
struct CellsGlyph(&'static [(u8, u8)]);
|
||||
|
||||
/// Width of the label column.
|
||||
const LABEL_W: f32 = 96.0;
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Rearrange All Artboards").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The fields a fresh dialog starts with.
|
||||
pub fn fields() -> Value {
|
||||
json!({"layout": "gridByRow", "order": "leftToRight", "columns": 2, "spacing": 20, "moveArtwork": true})
|
||||
}
|
||||
|
||||
/// The fields the menu item opens with, retaining the spacing from its last confirmation.
|
||||
pub fn open_fields(app: &VectorcraftApp) -> Value {
|
||||
let mut fields = fields();
|
||||
if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() {
|
||||
fields["spacing"] = json!(spacing);
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
/// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to
|
||||
/// right.
|
||||
fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) {
|
||||
match l {
|
||||
ArtboardLayout::GridByRow => (tl!("Grid by Row"), &[(0, 0), (1, 0), (0, 1), (1, 1)]),
|
||||
ArtboardLayout::GridByColumn => (tl!("Grid by Column"), &[(0, 0), (0, 1), (1, 0), (1, 1)]),
|
||||
ArtboardLayout::Row => (tl!("Arrange by Row"), &[(0, 0), (1, 0), (2, 0)]),
|
||||
ArtboardLayout::Column => (tl!("Arrange by Column"), &[(0, 0), (0, 1), (0, 2)]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `cells` mirrored left to right when `rtl` (the order the layout toggles preview).
|
||||
fn mirrored(cells: &[(u8, u8)], rtl: bool) -> Vec<(u8, u8)> {
|
||||
let last = cells.iter().map(|c| c.0).max().unwrap_or(0);
|
||||
cells.iter().map(|&(x, y)| (if rtl { last - x } else { x }, y)).collect()
|
||||
}
|
||||
|
||||
/// `artboard.rearrange` parameters from the fields.
|
||||
fn params(d: &Dialog) -> Value {
|
||||
json!({
|
||||
"layout": d.str("layout"), "order": d.str("order"), "columns": d.f64("columns", 2.0),
|
||||
"spacing": d.f64("spacing", 20.0), "moveArtwork": d.bool("moveArtwork"),
|
||||
})
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let unit = app.session.general_unit();
|
||||
let n = app.session.active().map_or(0, |doc| doc.doc.artboards.len());
|
||||
let layout = ArtboardLayout::parse(&d.str("layout")).unwrap_or_default();
|
||||
let rtl = d.str("order") == "rightToLeft";
|
||||
widgets::label_row(ui, tl!("Layout:"), LABEL_W, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
for l in ArtboardLayout::ALL {
|
||||
let (tip, cells) = layout_glyph(l);
|
||||
if widgets::layout_button(ui, &mirrored(cells, rtl), layout == l, tip) {
|
||||
d.fields.insert("layout".into(), json!(l.id()));
|
||||
}
|
||||
impl Glyph for CellsGlyph {
|
||||
fn paint(&self, painter: &Painter, _: &UiTokens, rect: Rect, color: Color32, _: bool) {
|
||||
let tiles = self.0;
|
||||
// Cells at most half the square a side: a row's artboards stand tall, a column's lie flat.
|
||||
let side = rect.width().min(rect.height());
|
||||
let scale = side / 20.0;
|
||||
let (cols, rows) = tiles.iter().fold((1u8, 1u8), |(c, r), &(x, y)| (c.max(x.saturating_add(1)), r.max(y.saturating_add(1))));
|
||||
let cell = vec2((side / f32::from(cols)).min(side / 2.0), (side / f32::from(rows)).min(side / 2.0));
|
||||
let origin = rect.center() - vec2(f32::from(cols) * cell.x, f32::from(rows) * cell.y) / 2.0;
|
||||
let centre = |&(x, y): &(u8, u8)| origin + vec2((f32::from(x) + 0.5) * cell.x, (f32::from(y) + 0.5) * cell.y);
|
||||
for tile in tiles {
|
||||
painter.rect_filled(Rect::from_center_size(centre(tile), cell - vec2(2.0, 2.0) * scale), 1.0, color.gamma_multiply(0.35));
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Layout Order:"), LABEL_W, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
// One column reads the same either way.
|
||||
ui.add_enabled_ui(layout != ArtboardLayout::Column, |ui| {
|
||||
for (value, cells, tip) in [
|
||||
("leftToRight", [(0, 0), (1, 0)], tl!("Change to Left-to-Right Layout")),
|
||||
("rightToLeft", [(1, 0), (0, 0)], tl!("Change to Right-to-Left Layout")),
|
||||
] {
|
||||
if widgets::layout_button(ui, &cells, (value == "rightToLeft") == rtl, tip) {
|
||||
d.fields.insert("order".into(), json!(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
// The rows of a grid by column; one row or column has no count to set.
|
||||
let label = if layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") };
|
||||
widgets::label_row(ui, label, LABEL_W, |ui| {
|
||||
let grid = matches!(layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn);
|
||||
ui.add_enabled_ui(grid, |ui| {
|
||||
let most = n.max(1) as f64;
|
||||
if let Some(v) = widgets::spin_plain(ui, "rearrange-columns", d.f64("columns", 2.0), "", 0, 76.0, 1.0, 1.0, &[]) {
|
||||
d.fields.insert("columns".into(), json!(v.round().clamp(1.0, most)));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| {
|
||||
form::length(ui, d, "spacing", unit, 100.0);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| {
|
||||
form::check(ui, d, "moveArtwork", tl!("Move Artwork with Artboard"));
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
widgets::dim_label(ui, &crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &n.to_string())]));
|
||||
false
|
||||
let path: Vec<Pos2> = tiles.iter().map(centre).collect();
|
||||
if let ([first, ..], [.., from, to]) = (path.as_slice(), path.as_slice()) {
|
||||
let (first, from, to) = (*first, *from, *to);
|
||||
let dir = (to - from).normalized();
|
||||
let wing = dir.rot90() * 2.5 * scale;
|
||||
let head = vec![to + dir * 1.5 * scale, to - dir * 2.5 * scale + wing, to - dir * 2.5 * scale - wing];
|
||||
painter.circle_filled(first, 1.6 * scale, color);
|
||||
painter.add(Shape::line(path, Stroke::new(1.2 * scale, color)));
|
||||
painter.add(Shape::convex_polygon(head, color, Stroke::NONE));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let result = run_and_close(app, CMD, params(d))?;
|
||||
app.ui.rearrange_artboards_spacing = json!(d.f64("spacing", 20.0));
|
||||
Ok(result)
|
||||
static GRID_BY_ROW: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0), (0, 1), (1, 1)]);
|
||||
static GRID_BY_ROW_RTL: CellsGlyph = CellsGlyph(&[(1, 0), (0, 0), (1, 1), (0, 1)]);
|
||||
static GRID_BY_COLUMN: CellsGlyph = CellsGlyph(&[(0, 0), (0, 1), (1, 0), (1, 1)]);
|
||||
static GRID_BY_COLUMN_RTL: CellsGlyph = CellsGlyph(&[(1, 0), (1, 1), (0, 0), (0, 1)]);
|
||||
static ROW: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0), (2, 0)]);
|
||||
static ROW_RTL: CellsGlyph = CellsGlyph(&[(2, 0), (1, 0), (0, 0)]);
|
||||
/// One column reads the same either way.
|
||||
static COLUMN: CellsGlyph = CellsGlyph(&[(0, 0), (0, 1), (0, 2)]);
|
||||
static LEFT_TO_RIGHT: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0)]);
|
||||
static RIGHT_TO_LEFT: CellsGlyph = CellsGlyph(&[(1, 0), (0, 0)]);
|
||||
|
||||
/// A layout's toggle: its tooltip and its picture in the order the toggles preview (`rtl`: right to left).
|
||||
fn layout_glyph(l: ArtboardLayout, rtl: bool) -> (&'static str, &'static CellsGlyph) {
|
||||
match (l, rtl) {
|
||||
(ArtboardLayout::GridByRow, false) => (tl!("Grid by Row"), &GRID_BY_ROW),
|
||||
(ArtboardLayout::GridByRow, true) => (tl!("Grid by Row"), &GRID_BY_ROW_RTL),
|
||||
(ArtboardLayout::GridByColumn, false) => (tl!("Grid by Column"), &GRID_BY_COLUMN),
|
||||
(ArtboardLayout::GridByColumn, true) => (tl!("Grid by Column"), &GRID_BY_COLUMN_RTL),
|
||||
(ArtboardLayout::Row, false) => (tl!("Arrange by Row"), &ROW),
|
||||
(ArtboardLayout::Row, true) => (tl!("Arrange by Row"), &ROW_RTL),
|
||||
(ArtboardLayout::Column, _) => (tl!("Arrange by Column"), &COLUMN),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings the dialog edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct RearrangeValues {
|
||||
layout: ArtboardLayout,
|
||||
/// Layout Order is right to left.
|
||||
rtl: bool,
|
||||
columns: f64,
|
||||
spacing: f64,
|
||||
move_artwork: bool,
|
||||
}
|
||||
|
||||
impl Default for RearrangeValues {
|
||||
fn default() -> Self {
|
||||
RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl RearrangeValues {
|
||||
/// `artboard.rearrange` parameters.
|
||||
fn params(&self) -> Value {
|
||||
json!({
|
||||
"layout": self.layout.id(), "order": self.order(), "columns": self.columns,
|
||||
"spacing": self.spacing, "moveArtwork": self.move_artwork,
|
||||
})
|
||||
}
|
||||
|
||||
fn order(&self) -> &'static str {
|
||||
if self.rtl { "rightToLeft" } else { "leftToRight" }
|
||||
}
|
||||
|
||||
/// A grid has a count to set; one row or column has none.
|
||||
fn is_grid(&self) -> bool {
|
||||
matches!(self.layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn)
|
||||
}
|
||||
|
||||
/// One column reads the same either way, so its order is not a choice.
|
||||
fn has_order(&self) -> bool {
|
||||
self.layout != ArtboardLayout::Column
|
||||
}
|
||||
}
|
||||
|
||||
/// The length unit a document unit shows as.
|
||||
fn length_kind(unit: Unit) -> UnitKind {
|
||||
match unit {
|
||||
Unit::Picas => UnitKind::Picas,
|
||||
Unit::Inches => UnitKind::Inches,
|
||||
Unit::Millimeters => UnitKind::Millimetres,
|
||||
Unit::Centimeters => UnitKind::Centimetres,
|
||||
Unit::Pixels => UnitKind::Pixels,
|
||||
Unit::Meters => UnitKind::Metres,
|
||||
Unit::Yards => UnitKind::Yards,
|
||||
Unit::Feet | Unit::FeetInches => UnitKind::Feet,
|
||||
_ => UnitKind::Points,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.menuDialog` for Rearrange All Artboards: opens the dialog on the spacing of its last OK.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let mut values = RearrangeValues::default();
|
||||
if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() {
|
||||
values.spacing = spacing;
|
||||
}
|
||||
let artboards = app.session.active().map_or(0, |doc| doc.doc.artboards.len());
|
||||
let unit = app.session.general_unit();
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, unit }));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The Rearrange All Artboards dialog; its answer is the settings OK confirmed, which [`pump`] runs.
|
||||
pub(crate) struct RearrangeArtboardsDialog {
|
||||
id: DialogId,
|
||||
open: bool,
|
||||
values: RearrangeValues,
|
||||
/// The document's artboard count, which bounds Columns.
|
||||
artboards: usize,
|
||||
/// The unit Spacing shows in.
|
||||
unit: Unit,
|
||||
}
|
||||
|
||||
/// The rows of the dialog for a document of `artboards` artboards, Spacing shown in `unit`.
|
||||
fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, unit: Unit) {
|
||||
Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<ArtboardLayout>> = ArtboardLayout::ALL
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let (tip, glyph) = layout_glyph(l, v.rtl);
|
||||
Entry::new(l, tip).icon(IconSpec::glyph(glyph))
|
||||
})
|
||||
.collect();
|
||||
if let Some(l) = Segmented::new(tl!("Layout:"), Bind::given(v.layout), &entries).show(ui).value().copied() {
|
||||
v.layout = l;
|
||||
}
|
||||
});
|
||||
Field::new(tl!("Layout Order:")).id_salt("order").enabled(v.has_order()).show(ui, |ui, _| {
|
||||
let entries = [
|
||||
Entry::new(false, tl!("Change to Left-to-Right Layout")).icon(IconSpec::glyph(&LEFT_TO_RIGHT)),
|
||||
Entry::new(true, tl!("Change to Right-to-Left Layout")).icon(IconSpec::glyph(&RIGHT_TO_LEFT)),
|
||||
];
|
||||
if let Some(rtl) = Segmented::new(tl!("Layout Order:"), Bind::given(v.rtl), &entries).show(ui).value().copied() {
|
||||
v.rtl = rtl;
|
||||
}
|
||||
});
|
||||
// The rows of a grid by column.
|
||||
let count = if v.layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") };
|
||||
Field::new(count).id_salt("columns").enabled(v.is_grid()).show(ui, |ui, _| {
|
||||
let most = artboards.max(1) as f64;
|
||||
let field = NumberField::new(count, Bind::given(Some(v.columns))).range(1.0..=most).step(1.0).show(ui);
|
||||
if let Some(Some(columns)) = field.edit.value().copied() {
|
||||
v.columns = columns.round().clamp(1.0, most);
|
||||
}
|
||||
});
|
||||
Field::new(tl!("Spacing:")).id_salt("spacing").show(ui, |ui, _| {
|
||||
let units = LengthUnits::new(UnitKind::Points, length_kind(unit), 72.0);
|
||||
let field = NumberField::length(tl!("Spacing:"), Bind::given(Some(v.spacing)), units).show(ui);
|
||||
if let Some(Some(spacing)) = field.edit.value().copied() {
|
||||
v.spacing = spacing;
|
||||
}
|
||||
});
|
||||
Field::new(tl!("Options:")).id_salt("options").show(ui, |ui, _| {
|
||||
if let Some(on) = check(ui, tl!("Move Artwork with Artboard"), v.move_artwork, true) {
|
||||
v.move_artwork = on;
|
||||
}
|
||||
});
|
||||
Text::new(crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui);
|
||||
}
|
||||
|
||||
impl StackDialog for RearrangeArtboardsDialog {
|
||||
type Result = RearrangeValues;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(CMD)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<RearrangeValues>> {
|
||||
let (artboards, unit) = (self.artboards, self.unit);
|
||||
let shown = FormDialog::new(tl!("Rearrange All Artboards"), Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(
|
||||
ui,
|
||||
|ui, _, v| {
|
||||
body(ui, v, artboards, unit);
|
||||
true
|
||||
},
|
||||
);
|
||||
match (shown.accepted, shown.closed) {
|
||||
(Some(value), _) => Some(DialogResult::Ok(value)),
|
||||
(None, Some(_)) => Some(DialogResult::Cancel),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &egui::Context) -> Option<RearrangeValues> {
|
||||
Some(self.values.clone())
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let v = &self.values;
|
||||
Some(json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork}))
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> {
|
||||
let rejects = || FieldRefusal::Rejects(&value).message(field);
|
||||
let inactive = || FieldRefusal::Inactive.message(field);
|
||||
let v = &mut self.values;
|
||||
match field {
|
||||
"layout" => v.layout = value.as_str().and_then(ArtboardLayout::parse).ok_or_else(rejects)?,
|
||||
"order" => {
|
||||
let rtl = match value.as_str() {
|
||||
Some("leftToRight") => false,
|
||||
Some("rightToLeft") => true,
|
||||
_ => return Err(rejects()),
|
||||
};
|
||||
if !v.has_order() {
|
||||
return Err(inactive());
|
||||
}
|
||||
v.rtl = rtl;
|
||||
}
|
||||
"columns" => {
|
||||
let columns = value.as_f64().filter(|c| c.is_finite()).ok_or_else(rejects)?;
|
||||
if !v.is_grid() {
|
||||
return Err(inactive());
|
||||
}
|
||||
v.columns = columns.round().clamp(1.0, self.artboards.max(1) as f64);
|
||||
}
|
||||
"spacing" => v.spacing = value.as_f64().filter(|s| s.is_finite()).ok_or_else(rejects)?,
|
||||
"moveArtwork" => v.move_artwork = value.as_bool().ok_or_else(rejects)?,
|
||||
_ => return Err(FieldRefusal::Unknown.message(field)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `artboard.rearrange` for the settings OK confirmed, and remembers the spacing of a successful one.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::<RearrangeArtboardsDialog>()) else { return };
|
||||
match app.run(CMD, values.params()) {
|
||||
Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
|
||||
Err(e) => app.status(e),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -129,104 +293,80 @@ mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
/// A frame of the open dialog with `events` → the texts painted. The dialog measures itself on
|
||||
/// its first frame, so a fresh context needs two.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<String> {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect()
|
||||
}
|
||||
|
||||
fn context() -> egui::Context {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx
|
||||
fn app(artboards: u32) -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(egui::Context::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": artboards})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn origins(app: &VectorcraftApp) -> Vec<(f64, f64)> {
|
||||
app.session.active().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
|
||||
}
|
||||
|
||||
/// #681: the menu item opens the dialog with the artboard count; Columns reads Rows for a grid
|
||||
/// by column; OK lays the artboards out right to left, as one undo step.
|
||||
#[test]
|
||||
fn opens_from_the_menu_and_rearranges_by_layout_and_order() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
|
||||
// The menu item has no params of its own: it opens this dialog, not the generic one.
|
||||
/// Opens the dialog as the menu item does.
|
||||
fn open_from_menu(app: &mut VectorcraftApp) {
|
||||
let (id, p) = crate::menus::click_target("Rearrange All Artboards…", CMD, &Value::Null);
|
||||
crate::menus::invoke(&mut app, &id, p);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
for want in ["Rearrange All Artboards", "Layout:", "Layout Order:", "Columns:", "Spacing:", "Move Artwork with Artboard", "Artboards: 3"] {
|
||||
assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}");
|
||||
crate::menus::invoke(app, &id, p);
|
||||
}
|
||||
|
||||
fn open_id(app: &VectorcraftApp) -> DialogId {
|
||||
app.dialogs().unwrap().with(|host| host.open_dialogs().last().map(|d| d.id)).unwrap()
|
||||
}
|
||||
|
||||
/// Sets `edits` in the open dialog in order; the first refusal is returned.
|
||||
fn set(app: &VectorcraftApp, edits: &[(&str, Value)]) -> Result<(), String> {
|
||||
let (ctx, id) = (app.ui_ctx.clone().unwrap(), open_id(app));
|
||||
edits.iter().try_for_each(|(field, value)| app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, field, value.clone())))
|
||||
}
|
||||
|
||||
/// Presses OK and runs the host pump, which runs the command.
|
||||
fn ok(app: &mut VectorcraftApp) {
|
||||
let (ctx, id) = (app.ui_ctx.clone().unwrap(), open_id(app));
|
||||
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
|
||||
crate::dialogs::host::pump(app, &ctx);
|
||||
}
|
||||
|
||||
/// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a
|
||||
/// setting the layout makes meaningless is refused.
|
||||
#[test]
|
||||
fn rearrange_fields_reach_the_command() {
|
||||
let cases: [(u32, &[(&str, Value)], &[(f64, f64)]); 2] = [
|
||||
(3, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(10))], &[(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]),
|
||||
(
|
||||
4,
|
||||
&[("layout", json!("gridByColumn")), ("order", json!("rightToLeft")), ("columns", json!(2))],
|
||||
&[(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)],
|
||||
),
|
||||
];
|
||||
for (artboards, edits, want) in cases {
|
||||
let mut app = app(artboards);
|
||||
open_from_menu(&mut app);
|
||||
set(&app, edits).unwrap();
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
ok(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_eq!(origins(&app), want);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("layout".into(), json!("gridByColumn"));
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(texts.iter().any(|t| t == "Rows:") && !texts.iter().any(|t| t == "Columns:"), "{texts:?}");
|
||||
// One row, right to left, 10 pt apart.
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("layout".into(), json!("row"));
|
||||
d.fields.insert("order".into(), json!("rightToLeft"));
|
||||
d.fields.insert("spacing".into(), json!(10));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(origins(&app), [(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let mut app = app(3);
|
||||
open_from_menu(&mut app);
|
||||
assert!(set(&app, &[("layout", json!("column")), ("order", json!("rightToLeft"))]).is_err(), "one column has no order");
|
||||
assert!(set(&app, &[("layout", json!("column")), ("columns", json!(2))]).is_err(), "one column has no count");
|
||||
assert!(set(&app, &[("layout", json!("row")), ("columns", json!(2))]).is_err(), "one row has no count");
|
||||
assert!(set(&app, &[("layout", json!("gridByRow")), ("columns", json!(2))]).is_ok());
|
||||
}
|
||||
|
||||
/// The spacing confirmed last is the one the dialog opens with next time (#4558).
|
||||
#[test]
|
||||
fn keeps_spacing_when_reopening_after_rearranging() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
|
||||
let mut app = app(3);
|
||||
app.run("ui.menuDialog", json!({"command": CMD})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("spacing".into(), json!(37));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
set(&app, &[("spacing", json!(37))]).unwrap();
|
||||
ok(&mut app);
|
||||
|
||||
app.run("ui.menuDialog", json!({"command": CMD})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("spacing", 20.0), 37.0);
|
||||
}
|
||||
|
||||
/// Clicking the layout and order toggles sets the fields (the toggles' rects from the frame).
|
||||
#[test]
|
||||
fn the_toggles_set_layout_and_order() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 4})).unwrap();
|
||||
app.run("ui.menuDialog", json!({ "command": CMD })).unwrap();
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
// The 26-point toggles, left to right then top to bottom: four layouts, then two orders.
|
||||
let toggles: Vec<egui::Rect> = ctx.viewport(|vp| {
|
||||
let mut r: Vec<egui::Rect> = vp
|
||||
.prev_pass
|
||||
.widgets
|
||||
.layers()
|
||||
.flat_map(|(_, w)| w.iter())
|
||||
.filter(|w| w.sense.senses_click() && w.rect.width() == 26.0 && w.rect.height() == 26.0)
|
||||
.map(|w| w.rect)
|
||||
.collect();
|
||||
r.sort_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left())));
|
||||
r
|
||||
});
|
||||
assert_eq!(toggles.len(), 6, "{toggles:?}");
|
||||
for (i, key, want) in [(3, "layout", "column"), (1, "layout", "gridByColumn"), (5, "order", "rightToLeft")] {
|
||||
let at = toggles[i].center();
|
||||
let b = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), b(true)]);
|
||||
frame(&mut app, &ctx, vec![b(false)]);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str(key), want);
|
||||
// A frame for the order toggles to follow the layout (one column greys them).
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
// Two rows (Columns 2 reads Rows for a grid by column), the first column at the right.
|
||||
assert_eq!(origins(&app), [(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)]);
|
||||
let fields = app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap();
|
||||
assert_eq!(fields["spacing"].as_f64(), Some(37.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,52 +2,50 @@
|
||||
//! for the selected artboards. OK runs
|
||||
//! `artboard.rename` as one undo step; with several artboards the name is numbered.
|
||||
//!
|
||||
//! Fields: `name` (the artboard's name with one artboard, empty with several) and `indices` (the
|
||||
//! artboards the dialog opened on).
|
||||
//! Fields: `name` (the artboard's name with one artboard, empty with several). The artboards the
|
||||
//! dialog opened on are held by its OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{DialogResult, DialogSpec, form, run_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
use super::host::open_held;
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// The dialog kind of the artboard Rename dialog.
|
||||
pub const KIND: &str = "renameArtboards";
|
||||
/// The command Rename answers for; the key of its dialog.
|
||||
pub(crate) const CMD: &str = "artboard.rename";
|
||||
|
||||
const CMD: &str = "artboard.rename";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Rename").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The fields the menu item opens with, for the selected artboards.
|
||||
pub fn open_fields(app: &VectorcraftApp) -> Value {
|
||||
let Some(st) = app.session.active() else { return json!({"name": "", "indices": []}) };
|
||||
let indices = crate::panels::artboards::picked(app, st.doc.artboards.len());
|
||||
let name = match indices.as_slice() {
|
||||
[one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()),
|
||||
_ => "",
|
||||
};
|
||||
json!({ "name": name, "indices": indices })
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, tl!("Name:"), 56.0, |ui| {
|
||||
let r = form::text_edit_named(ui, d, "name", tl!("Name:"), 220.0);
|
||||
if ui.memory(|m| m.focused().is_none()) {
|
||||
r.request_focus();
|
||||
}
|
||||
/// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name
|
||||
/// for several.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| {
|
||||
let indices = crate::panels::artboards::picked(app, st.doc.artboards.len());
|
||||
let name = match indices.as_slice() {
|
||||
[one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()),
|
||||
_ => "",
|
||||
};
|
||||
(indices, name.to_owned())
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
/// An empty name keeps the names as they are, as the Artboards panel's name field does.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
|
||||
let name = d.str("name");
|
||||
if name.trim().is_empty() {
|
||||
app.ui.dialog = None;
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let indices = d.fields.get("indices").cloned().unwrap_or(Value::Null);
|
||||
run_and_close(app, CMD, json!({ "indices": indices, "name": name }))
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("name", name);
|
||||
let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| {
|
||||
let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))];
|
||||
ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields))
|
||||
});
|
||||
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
|
||||
let name = result.fields.text("name").unwrap_or_default();
|
||||
// An empty name keeps the names as they are, as the Artboards panel's name field does.
|
||||
if name.trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) {
|
||||
app.status(e);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
open_held(app, dialog, ok).ok_or("no window")?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -57,6 +55,7 @@ mod tests {
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(egui::Context::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
app
|
||||
@@ -66,24 +65,41 @@ mod tests {
|
||||
app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// The open Rename dialog: its id and fields.
|
||||
fn open_rename(app: &VectorcraftApp) -> (craft::ui::dialog::DialogId, Value) {
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
let open = dialogs.with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(CMD))).unwrap();
|
||||
(open.id, open.fields.unwrap())
|
||||
}
|
||||
|
||||
/// Sets `name` in the open dialog, presses OK and runs the host pump, which runs the held OK.
|
||||
fn rename(app: &mut VectorcraftApp, name: &str) {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let (id, _) = open_rename(app);
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
dialogs.with(|host| host.set_json_field(&ctx, id, "name", json!(name))).unwrap();
|
||||
dialogs.with(|host| host.confirm_by_id(&ctx, id));
|
||||
crate::dialogs::host::pump(app, &ctx);
|
||||
dialogs.with(|host| host.confirm_by_id(&ctx, id));
|
||||
}
|
||||
|
||||
/// With one artboard the field starts on its name; with several it starts empty, and OK numbers
|
||||
/// the name in one undo step.
|
||||
#[test]
|
||||
fn the_menu_item_renames_the_selected_artboards() {
|
||||
let mut app = app();
|
||||
crate::menus::invoke(&mut app, CMD, json!({}));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.kind, KIND);
|
||||
assert_eq!(d.str("name"), "Artboard 1");
|
||||
app.ui.dialog = None;
|
||||
assert_eq!(open_rename(&app).1["name"], json!("Artboard 1"));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let (id, _) = open_rename(&app);
|
||||
app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id));
|
||||
|
||||
app.session.set_tool_option("selected", &json!([2, 0]));
|
||||
crate::menus::invoke(&mut app, CMD, json!({}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), "");
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(" Page "));
|
||||
assert_eq!(open_rename(&app).1["name"], json!(""));
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
rename(&mut app, " Page ");
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
}
|
||||
@@ -95,9 +111,8 @@ mod tests {
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
for name in [" ", "Artboard 1"] {
|
||||
crate::menus::invoke(&mut app, CMD, json!({}));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(name));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
rename(&mut app, name);
|
||||
assert!(!app.any_dialog_open());
|
||||
}
|
||||
assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
|
||||
|
||||
Reference in New Issue
Block a user