diff --git a/ROADMAP.md b/ROADMAP.md index 98f052f69..3466cdcfc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -177,6 +177,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-19 | Long flat operator chains (`=A1+A2+…`) up to Excel's 8,192-character limit (4,096 operands): entering, filling, inserting rows, undo, Evaluate Formula and XLSX save no longer overflow the stack; chains past 64 operands are saved as plain formulas, not dynamic arrays; Spanish formula entry accepts chains past 256 operands (#916) | | 2026-10-19 | Linux: "Use system setting" for the theme keeps following the desktop when the XDG Desktop Portal stops answering: each read gives up after 2 s and the next poll reconnects, where one unanswered call stalled the watcher for the rest of the session | | 2026-10-16 | Memory: undo steps share a sheet's picture bytes and the workbook's VBA project instead of copying them: 50 edits on a sheet with a 20 MB picture keep 22 MB instead of 992 MB | +| 2026-10-16 | Custom Sort dialog: header-named column dropdowns, smart Order labels, add/delete/copy/move levels, resizable window, selection follows the headers checkbox and returns on close; a selected block (such as a table's totals row) is sorted as selected | | 2026-10-16 | Memory: floating pictures are decoded at about the size they are drawn, with limits, into a cache bounded by bytes and dropped with their workbook, instead of at full size into one that never let go; two open workbooks no longer show each other's picture. 12 large pictures scrolled through keep 40 MB of textures instead of 258 MB, and none once the workbook closes | | 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change | | 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS | diff --git a/contributors/people.toml b/contributors/people.toml index 395aecf6e..442780af7 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -26,6 +26,11 @@ sync_github_name = false [people.edurbs] sync_github_name = true +[people.Cheejyg] +real_name = "Glenn Chee" +display_name = "Cheejyg" +sync_github_name = false + [people.arcanii] real_name = "Bryan Mark" display_name = "Arcanii" diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index c87906dee..b4588edce 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -27,6 +27,7 @@ pub use filter::filter_values; pub(crate) use filter::{apply_filter, grow_autofilter}; use filter::{clear_filter, filter_by, reapply, toggle_filter}; use grouping::{detail, group, outline_settings, show_levels, subtotal}; +pub use sort::sort_context; use sort::{quick_sort, sort}; #[cfg(test)] use tools::split_delimited; @@ -212,7 +213,7 @@ fn data_target(s: &Session, p: &Json, cmd: &str) -> Result<(usize, RangeRef)> { /// Excel's header guess: the first row is text over a column of numbers, or is bold. fn guess_header(wb: &Workbook, sh: &Sheet, r: RangeRef) -> bool { if let Some(t) = sh.table_at(r.start) { - return t.header_row; + return t.header_row && r.start.row == t.range.start.row; } if r.height() < 2 { return false; diff --git a/crates/engine/src/cmd/data/sort.rs b/crates/engine/src/cmd/data/sort.rs index f4adf49ac..1ee850490 100644 --- a/crates/engine/src/cmd/data/sort.rs +++ b/crates/engine/src/cmd/data/sort.rs @@ -28,6 +28,21 @@ fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> { Ok((sheet, data_range(s, p)?)) } +/// The worksheet (index), range and header guess the Custom Sort dialog works on: the sheet named by +/// `sheet` or a `Sheet!` prefix on `range`, else the active one. +pub fn sort_context(s: &Session, p: &Json) -> Result<(usize, RangeRef, bool)> { + let (sheet, explicit) = sort_target(s, p)?; + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + let sel = d.selection.current(); + // An explicit block wins over the table range, so a selected totals row can be sorted. + let r = match sh.used_range() { + Some(used) if p.get("range").is_none() && !sel.is_single() => sel.intersection(&used).unwrap_or(sel), + _ => explicit, + }; + Ok((sheet, r, bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r)))) +} + pub(super) fn quick_sort(s: &mut Session, p: &Json, asc: bool) -> Result { let (sheet, r) = sort_target(s, p)?; let col = col_param(p.get("column"), r.start.col).unwrap_or(s.doc()?.selection.active.col).clamp(r.start.col, r.end.col); @@ -68,7 +83,9 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result { }); } if keys.is_empty() { - s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header}))); + let (sheet, r, header) = sort_context(s, p)?; + let name = s.doc()?.wb.sheet(sheet).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?; + s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header, "sheet": name}))); return ok(); } if keys.len() > 64 { diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index e9f3eb220..a4c4f63d8 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1078,16 +1078,50 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> { if let Some(p) = &prior { let _ = f.set_permissions(p.clone()); } - f.write_all(bytes).and_then(|()| f.flush()).map_err(|e| { + // `sync_all` before the rename: without it a power loss right after the rename can leave + // the new name pointing at an empty or truncated file while the old workbook is gone. + // A file system that cannot flush at all (some network mounts; on Apple targets std asks + // for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename. + let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) }); + f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| { let _ = std::fs::remove_file(&tmp); EngineError::Other(format!("{path}: {e}")) })?; + drop(f); std::fs::rename(&tmp, path).map_err(|e| { // A write or rename that fails (full disk, the workbook locked by another app) leaves // no temporary file beside the user's workbook. let _ = std::fs::remove_file(&tmp); EngineError::Other(format!("{path}: {e}")) - }) + })?; + // Make the rename itself durable. Best effort: the workbook is already in place, so a + // directory that can't be opened or synced (some file systems) is not a failed save. + #[cfg(unix)] + { + let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new(".")); + if let Ok(d) = std::fs::File::open(dir) { + let _ = d.sync_all(); + } + } + Ok(()) +} + +/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what +/// `fcntl(F_FULLFSYNC)` returns on such volumes; on Windows 25 is ERROR_SEEK, a real failure), on +/// Apple targets ENOTSUP (45, which std leaves uncategorized there), or an unsupported-operation +/// error (EOPNOTSUPP/ENOSYS, and ENOTSUP where it equals EOPNOTSUPP). Any other error is a real +/// failure. +#[cfg(not(target_arch = "wasm32"))] +fn full_sync_unsupported(e: &std::io::Error) -> bool { + flush_unsupported_on(e, cfg!(unix), cfg!(target_vendor = "apple")) +} + +/// [`full_sync_unsupported`] for a given platform, so each platform's raw codes can be tested +/// on any host. +#[cfg(not(target_arch = "wasm32"))] +fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool { + let raw = e.raw_os_error(); + (unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported } /// The mode a saved file gets from the file it replaces (`old`): all of it when its group was diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index 58bdfba77..d2a4c0888 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -344,6 +344,65 @@ fn failed_save_leaves_no_temporary_file() { let _ = std::fs::remove_dir_all(&dir); } +/// A save replaces an existing workbook with exactly the new bytes, and a save into a folder +/// that doesn't exist fails without creating anything. The flush to disk before the rename is +/// not covered: a power loss can't be simulated in a unit test. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn save_writes_exact_bytes_and_fails_cleanly_without_a_folder() { + let dir = std::env::temp_dir().join(format!("gridcraft-write-exact-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let dest = dir.join("Book.xlsx"); + std::fs::write(&dest, b"old workbook that is longer than the new one").unwrap(); + let bytes: Vec = (0..=255u8).cycle().take(100_000).collect(); + write_file(dest.to_str().unwrap(), &bytes).unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), bytes); + assert!(!dir.join("Book.xlsx.sctmp").exists()); + let missing = dir.join("no-such-folder").join("Book.xlsx"); + assert!(write_file(missing.to_str().unwrap(), b"x").is_err()); + assert!(!dir.join("no-such-folder").exists()); + assert_eq!(std::fs::read(&dest).unwrap(), bytes, "the existing workbook is untouched"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Only "this file system cannot flush" errors are tolerated when syncing a saved file. +/// The fallback on a real network mount is not tested. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn full_sync_tolerates_only_unsupported_errors() { + use std::io::{Error, ErrorKind}; + assert_eq!(full_sync_unsupported(&Error::from_raw_os_error(25)), cfg!(unix)); + assert!(full_sync_unsupported(&Error::from(ErrorKind::Unsupported))); + assert!(!full_sync_unsupported(&Error::from(ErrorKind::PermissionDenied))); + assert!(!full_sync_unsupported(&Error::from(ErrorKind::StorageFull))); + assert!(!full_sync_unsupported(&Error::from_raw_os_error(28)), "ENOSPC on Linux"); + assert!(!full_sync_unsupported(&Error::from_raw_os_error(5)), "EIO"); +} + +/// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to +/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is +/// another error (EL2NSYNC on Linux) and stays a failed save. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn full_sync_tolerates_apple_enotsup() { + use std::io::Error; + let enotsup = Error::from_raw_os_error(45); + assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple"); + assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix"); + assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows"); + assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple"); + assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple"); + assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple"); +} + +/// The real helper on an Apple host: a raw ENOTSUP from F_FULLFSYNC is tolerated. +#[cfg(target_vendor = "apple")] +#[test] +fn full_sync_tolerates_raw_enotsup_on_apple() { + assert!(full_sync_unsupported(&std::io::Error::from_raw_os_error(45))); +} + /// While a script runs (#2178), file reads and writes are refused whatever command or /// parameter asked for them; nesting and dropping the sandbox restore access. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1963e7054..aa0c81508 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -26,6 +26,9 @@ impl SheetApp { if matches!(id, "file.save" | "file.saveAs" | "file.saveBytes") { self.store_view_state(); } + if let Some(refused) = dialogs::refuse_sheet_change(self, id) { + return Err(refused); + } if matches!( id, "sheet.activate" diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e5d157e88..6d11a2d6c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -26,6 +26,7 @@ mod names; mod paste; mod ref_edit; mod show; +mod sort_dialog; mod spelling; mod zoom; @@ -38,6 +39,7 @@ use names::pasteable_names; pub(crate) use ref_edit::SHEET_DELETED; pub(crate) use show::build_params; pub use show::show; +pub(crate) use sort_dialog::{grid_sense, refuse_sheet_change}; use zoom::zoom_preset; /// A form field. `Ref` is a range reference that can also be picked by selecting on the grid @@ -64,6 +66,8 @@ pub struct Dialog { pub tab: String, pub search: String, pub list_index: usize, + /// Custom Sort's own state: the selection to restore and the column choices. + sort: sort_dialog::State, pub result: Option, /// "Show password" is ticked: password fields show their text. pub show_password: bool, @@ -233,6 +237,7 @@ impl Dialog { tab: String::new(), search: String::new(), list_index: 0, + sort: Default::default(), result: None, show_password: false, focus_first_field: true, @@ -258,6 +263,7 @@ impl Dialog { tab: String::new(), search: String::new(), list_index: 0, + sort: Default::default(), result: None, show_password: false, focus_first_field: false, @@ -989,11 +995,7 @@ impl Dialog { }], json!({"kind": "blanks"}), ), - "sort" => { - // Seed "Sort by" from the column the user is actually in (#1906). - let col = app.session.active().map(|d| gridcraft_engine::core::col_to_letters(d.selection.active.col)).unwrap_or_else(|| "A".into()); - Dialog::custom("sort", "Sort", json!({"header": true, "levels": [{"column": col, "order": "asc"}]})) - } + "sort" => sort_dialog::open(app, ¶ms)?, "nameManager" => Dialog::custom("nameManager", "Name Manager", json!({})), "pasteName" => { // F3 opens it only when the workbook has names to paste, as in Excel. diff --git a/crates/ui-egui/src/dialogs/data.rs b/crates/ui-egui/src/dialogs/data.rs index e57a90c4e..103160fe4 100644 --- a/crates/ui-egui/src/dialogs/data.rs +++ b/crates/ui-egui/src/dialogs/data.rs @@ -1,7 +1,7 @@ #[cfg(test)] use super::show::build_params; use super::show::{form_fields, ok_cancel}; -use super::{Dialog, Field, Icon, Json, SheetApp, json, vec2}; +use super::{Dialog, Field, Json, SheetApp, json, vec2}; /// Initial values of the Data Validation form: the rule stored on the active cell, so OK without /// edits keeps it; a plain list rule when the cell has none. @@ -180,109 +180,8 @@ pub(super) fn advanced_filter_form(app: &SheetApp, ui: &mut egui::Ui, d: &mut Di ui.allocate_ui(vec2(ui.available_width(), ui.spacing().interact_size.y + 8.0), |ui| ok_cancel(ui, confirm, open)); } -/// Draws the sort-level editor: header toggle, column/by/order controls, add/remove level, and `data.sort` on confirmation. -pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) { - let lang = app.ui.language; - let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true); - ui.checkbox(&mut header, "My list has headers"); - d.values.insert("header".into(), json!(header)); - let mut levels: Vec = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default(); - // Columns of the region around the active cell, labelled with their header (or first value). - let columns: Vec<(String, String)> = app - .session - .active() - .and_then(|d| { - let sh = d.wb.active()?; - let region = gridcraft_engine::selection::current_region(sh, d.selection.active); - Some( - (region.start.col..=region.end.col) - .map(|c| { - let letter = gridcraft_engine::core::col_to_letters(c); - // The region starts at the header row when one is present, so the - // label always comes from start.row: header text with headers on, - // first data value with them off. - let label_row = region.start.row; - let text = gridcraft_engine::display::cell_text(&d.wb, sh, gridcraft_engine::core::CellRef::new(label_row, c)); - let text: String = text.chars().take(24).collect(); - (letter.clone(), if text.is_empty() { letter } else { format!("{letter}: {text}") }) - }) - .collect(), - ) - }) - .unwrap_or_default(); - let mut remove = None; - for (i, lv) in levels.iter_mut().enumerate() { - ui.horizontal(|ui| { - let label = ui.label(lang.tr(if i == 0 { "Sort by" } else { "Then by" })); - let mut col = lv["column"].as_str().unwrap_or("A").to_string(); - if columns.is_empty() { - ui.add(egui::TextEdit::singleline(&mut col).desired_width(50.0)).labelled_by(label.id); - } else { - // The closed box shows the same "B: Revenue" label as the list, not the bare letter (#3446). - let shown = - columns.iter().find(|(letter, _)| letter.eq_ignore_ascii_case(&col)).map_or_else(|| col.clone(), |(_, label)| label.clone()); - craft_ui::ComboBox::from_id_salt(("sort_col", i)) - .selected_text(shown) - .show_ui(ui, |ui| { - for (letter, label) in &columns { - ui.selectable_value(&mut col, letter.clone(), label.as_str()); - } - }) - .response - .labelled_by(label.id); - } - lv["column"] = json!(col.to_ascii_uppercase()); - let mut by = lv["by"].as_str().unwrap_or("values").to_string(); - craft_ui::ComboBox::from_id_salt(("by", i)) - .selected_text(match by.as_str() { - "cellColor" => "Cell Color", - "fontColor" => "Font Color", - _ => "Cell Values", - }) - .show_ui(ui, |ui| { - ui.selectable_value(&mut by, "values".into(), "Cell Values"); - ui.selectable_value(&mut by, "cellColor".into(), "Cell Color"); - ui.selectable_value(&mut by, "fontColor".into(), "Font Color"); - }) - .response - .accessible_name(lang.tr("Sort On")); - lv["by"] = json!(by); - let mut desc = lv["order"].as_str() == Some("desc"); - ui.radio_value(&mut desc, false, "A to Z"); - ui.radio_value(&mut desc, true, "Z to A"); - lv["order"] = json!(if desc { "desc" } else { "asc" }); - if crate::widgets::icon_button(ui, Icon::Close, crate::theme::Tokens::get(ui.ctx()).text_dim, "Remove level", vec2(18.0, 18.0)).clicked() - { - remove = Some(i); - } - }); - } - if let Some(i) = remove - && levels.len() > 1 - { - levels.remove(i); - } - if ui.button("+ Add Level").clicked() { - let used: Vec = levels.iter().filter_map(|l| l.get("column").and_then(Json::as_str).map(str::to_string)).collect(); - let next = columns - .iter() - .map(|(l, _)| l) - .find(|l| !used.contains(l)) - .cloned() - .or_else(|| columns.last().map(|(l, _)| l.clone())) - .unwrap_or_else(|| "B".into()); - levels.push(json!({"column": next, "order": "asc"})); - } - d.values.insert("levels".into(), Json::Array(levels.clone())); - let mut open = true; - ok_cancel(ui, confirm, &mut open); - if *confirm { - app.run_or_alert("data.sort", json!({"header": header, "keys": levels})); - } - if !open { - *confirm = true; - } -} +// Custom Sort lives in its own module; `show` reaches it from here. +pub(super) use super::sort_dialog::sort; #[cfg(test)] mod data_validation_tests { diff --git a/crates/ui-egui/src/dialogs/ref_edit.rs b/crates/ui-egui/src/dialogs/ref_edit.rs index 3aa22dcff..30dc899d3 100644 --- a/crates/ui-egui/src/dialogs/ref_edit.rs +++ b/crates/ui-egui/src/dialogs/ref_edit.rs @@ -326,6 +326,8 @@ fn active_sheet_name(app: &SheetApp) -> String { /// dialog about to run its command must not, since references without a sheet name would be /// read against the sheet still shown. pub(super) fn end_pick(app: &mut SheetApp, d: &mut Dialog) -> Result<(), String> { + // Custom Sort puts back the selection it changed whenever it lets go of the grid. + super::sort_dialog::restore_selection(app, d); d.refs.target = None; d.refs.collapsed = None; let Some(home) = d.refs.home.as_mut() else { return Ok(()) }; diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index e4cd5bb24..df57d3f76 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -174,6 +174,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { "advancedFilter" => window.default_height(0.0), _ => window, }; + let window = super::sort_dialog::window(window, &d.name, ctx, app.ui.language); let (window, collapsed) = place_window(app, ctx, &mut d, window, window_id); let shown = window.show(ctx, |ui| { if let Some(key) = &collapsed { diff --git a/crates/ui-egui/src/dialogs/sort_dialog.rs b/crates/ui-egui/src/dialogs/sort_dialog.rs new file mode 100644 index 000000000..6ad2fa936 --- /dev/null +++ b/crates/ui-egui/src/dialogs/sort_dialog.rs @@ -0,0 +1,416 @@ +//! Custom Sort (Data › Sort): sort levels with column, sort-on and order pickers. +//! +//! The dialog restores the grid selection it changed when it lets go of the grid (see +//! [`restore_selection`], called from `ref_edit::end_pick`) and keeps the worksheet it opened on. + +use gridcraft_engine::Selection; +use gridcraft_engine::core::{CellRef, RangeRef, Value, col_to_letters}; + +use super::show::ok_cancel; +use super::{Dialog, Json, Sense, SheetApp, json, vec2}; +use crate::i18n::Language; +use crate::icons::Icon; +use crate::theme::Tokens; + +/// Commands that change which worksheet is shown or which worksheets exist: refused while Sort is +/// open, so Sort always acts on the worksheet it opened on. +const SHEET_COMMANDS: [&str; 8] = + ["sheet.activate", "sheet.next", "sheet.previous", "sheet.move", "sheet.hide", "sheet.unhide", "home.insertSheet", "home.deleteSheet"]; + +/// What the dialog keeps besides its field values. +#[derive(Clone, Debug, Default)] +pub(super) struct State { + /// The exact selection to restore when Sort closes, including ranges and the shift anchor. + restore: Option, + /// The workbook and worksheet Sort opened on, by identity: the only one it may sort. A sheet's + /// position changes when sheets are inserted, deleted, moved or undone, its [`SheetUid`] does not. + home: Option<(u64, u64)>, + choices: Option, +} + +/// The column choices for one sheet revision, range, header setting and language. +#[derive(Clone, Debug)] +struct ChoicesCache { + language: Language, + doc_uid: Option, + sheet_index: Option, + revision: Option, + range: Option, + header: bool, + choices: Vec, +} + +/// A column of the sorted range: its letters, its label and whether its values are numbers. +type Choice = (String, String, bool); + +/// Opens Custom Sort on the range, worksheet and header guess of `data.sort`, seeding "Sort by" from the +/// active column (#1906). A request that can't be resolved is reported and opens nothing. +pub(super) fn open(app: &mut SheetApp, params: &Json) -> Option { + let (sheet, range, header) = match gridcraft_engine::cmd::data::sort_context(&app.session, params) { + Ok(context) => context, + Err(e) => { + app.message = Some(("Sort".into(), crate::clean_error(&e.to_string()))); + return None; + } + }; + // Sort works on the worksheet shown, so a request for another one shows it first. + if app.session.active().is_some_and(|doc| doc.wb.active_sheet() != sheet) + && let Err(e) = app.run("sheet.activate", json!({"sheet": sheet})) + { + app.message = Some(("Sort".into(), crate::clean_error(&e))); + return None; + } + // An open filter menu would take the Enter that confirms Sort (and apply its filter). + app.grid.filter_menu = None; + let restore = app.session.active().map(|doc| doc.selection.clone()); + let home = sheet_key(app); + let active_col = app.session.active().map(|doc| doc.selection.active.col); + let first = col_to_letters(active_col.filter(|c| (range.start.col..=range.end.col).contains(c)).unwrap_or(range.start.col)); + if header && range.height() > 1 { + let _ = app.run("selection.set", json!({"range": body_of(range).a1()})); + } + let mut d = Dialog::custom("sort", "Sort", json!({"header": header, "range": range.a1(), "levels": [{"column": first, "order": "asc"}]})); + d.sort.restore = restore; + d.sort.home = home; + Some(d) +} + +/// `r` without its header row. +fn body_of(r: RangeRef) -> RangeRef { + RangeRef::new(CellRef::new(r.start.row.saturating_add(1), r.start.col), r.end) +} + +/// The active workbook and worksheet by identity (document uid, [`SheetUid`]). +/// +/// [`SheetUid`]: gridcraft_engine::model::SheetUid +fn sheet_key(app: &SheetApp) -> Option<(u64, u64)> { + let doc = app.session.active()?; + Some((doc.uid, doc.wb.active()?.uid.get())) +} + +/// Puts back the selection from before Sort opened (once) on the worksheet it opened on: the +/// selection shown while that sheet is active, else the one the sheet keeps for when it is shown +/// again. Nothing is restored once that sheet is gone. Runs whenever a dialog lets go of the grid. +pub(super) fn restore_selection(app: &mut SheetApp, d: &mut Dialog) { + let Some((doc_uid, sheet_uid)) = d.sort.home.filter(|_| d.name == "sort") else { return }; + let Some(doc) = app.session.active_mut().filter(|doc| doc.uid == doc_uid) else { return }; + let Some(index) = doc.wb.sheets.iter().position(|s| s.uid.get() == sheet_uid) else { return }; + let Some(selection) = d.sort.restore.take() else { return }; + if index == doc.wb.active_sheet() { + doc.selection = selection; + } else { + if doc.sheet_selections.len() < doc.wb.sheets.len() { + doc.sheet_selections.resize(doc.wb.sheets.len(), Selection::default()); + } + if let Some(slot) = doc.sheet_selections.get_mut(index) { + *slot = selection; + } + } +} + +/// The reason `id` is refused while Sort is open, if it is. +pub(crate) fn refuse_sheet_change(app: &SheetApp, id: &str) -> Option { + (app.dialog.as_ref().is_some_and(|d| d.name == "sort") && SHEET_COMMANDS.contains(&id)) + .then(|| "Close the Sort dialog before switching or changing worksheets.".into()) +} + +/// The grid ignores the mouse while Sort is open, so the selection cannot change under the dialog. +pub(crate) fn grid_sense(app: &SheetApp) -> Sense { + if app.dialog.as_ref().is_some_and(|d| d.name == "sort") { Sense::hover() } else { Sense::click_and_drag() } +} + +/// Sort moves and resizes. Its minimum width fits the whole toolbar row (the level buttons and the +/// headers checkbox) in the interface language, so a longer translation widens the window instead +/// of overlapping or wrapping the row. +pub(super) fn window<'a>(window: egui::Window<'a>, name: &str, ctx: &egui::Context, lang: Language) -> egui::Window<'a> { + if name != "sort" { + return window; + } + let width = toolbar_width(ctx, lang).max(480.0); + window.resizable(true).min_width(width).min_height(260.0).default_width(width.max(500.0)).default_height(320.0) +} + +/// The width of the toolbar row of [`sort`] with its labels on one line, plus the window frame. +fn toolbar_width(ctx: &egui::Context, lang: Language) -> f32 { + let style = ctx.global_style(); + let painter = ctx.layer_painter(egui::LayerId::background()); + let text = |font: egui::FontId, key: &str| painter.layout_no_wrap(lang.tr(key).to_string(), font, egui::Color32::PLACEHOLDER).size().x; + let button_font = crate::theme::ui_font(12.5); + // Mirrors `small_button_accent`: a 24px icon cell and the label plus 6px. + let buttons: f32 = ["Add Level", "Delete Level", "Copy Level"].iter().map(|key| 24.0 + text(button_font.clone(), key) + 6.0).sum(); + let arrows = 2.0 * 24.0; + let spacing = &style.spacing; + let checkbox = spacing.icon_width + spacing.icon_spacing + text(egui::TextStyle::Body.resolve(&style), "My list has headers"); + // Five buttons and the checkbox, with the gaps between them, and the window's inner margin. + (buttons + arrows + checkbox + 6.0 * spacing.item_spacing.x + 2.0 * style.spacing.window_margin.left as f32 + 16.0).ceil() +} + +/// The label of a column that has no header text: `Column A`, in the interface language. +fn column_label(lang: Language, letters: &str) -> String { + lang.tr("Column {letters}").replace("{letters}", letters) +} + +/// The columns of `range` with their labels: header text, or `Column A`, `Column B`… without headers. +fn column_choices(app: &SheetApp, range: Option, header: bool) -> Vec { + let Some(r) = range else { return Vec::new() }; + let lang = app.ui.language; + let sh = app.session.active().and_then(|doc| doc.wb.active()); + let body_start = r.start.row.saturating_add(u32::from(header)); + let cols = r.end.col.saturating_sub(r.start.col).saturating_add(1).max(1) as usize; + // Total sampled cells are bounded across all columns, not per column. + let rows_per_col = (200_000 / cols).max(1); + (r.start.col..=r.end.col) + .map(|c| { + let letters = col_to_letters(c); + let text = match (header, sh) { + (true, Some(sh)) => sh.value(CellRef::new(r.start.row, c)).display().trim().to_string(), + _ => String::new(), + }; + let label = if text.is_empty() { column_label(lang, &letters) } else { text }; + let numeric = + sh.is_some_and(|sh| values_are_numeric((body_start..=r.end.row).take(rows_per_col).map(|row| sh.value(CellRef::new(row, c))))); + (letters, label, numeric) + }) + .collect() +} + +/// The column choices, recomputed only when the sheet, range, header setting or language changed. +fn cached_choices(app: &SheetApp, d: &mut Dialog, range: Option, header: bool) -> Vec { + let language = app.ui.language; + let (doc_uid, sheet_index, revision) = + app.session.active().map(|doc| (Some(doc.uid), Some(doc.wb.active_sheet()), Some(doc.revision))).unwrap_or_default(); + let range_key = range.map(|r| r.a1()); + if let Some(cache) = &d.sort.choices + && cache.language == language + && cache.doc_uid == doc_uid + && cache.sheet_index == sheet_index + && cache.revision == revision + && cache.range == range_key + && cache.header == header + { + return cache.choices.clone(); + } + let choices = column_choices(app, range, header); + d.sort.choices = Some(ChoicesCache { language, doc_uid, sheet_index, revision, range: range_key, header, choices: choices.clone() }); + choices +} + +/// The column a new level starts on: the first column no level uses, and once every column is used +/// the selected level's column (as Copy Level would give), so more levels can always be added. +fn next_level_column(choices: &[Choice], levels: &[Json], selected: usize) -> Option { + let used: Vec<&str> = levels.iter().filter_map(|l| l["column"].as_str()).collect(); + choices + .iter() + .map(|(l, _, _)| l.as_str()) + .find(|l| !used.contains(l)) + .or_else(|| levels.get(selected).and_then(|l| l["column"].as_str())) + .or_else(|| choices.first().map(|(l, _, _)| l.as_str())) + .map(str::to_string) +} + +/// Draws the sort-level editor: header toggle, level actions, the level rows and OK/Cancel; OK runs `data.sort`. +pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) { + let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true); + let was_header = header; + let range = d.values.get("range").and_then(Json::as_str).and_then(RangeRef::parse); + let lang = app.ui.language; + let choices = cached_choices(app, d, range, header); + let mut levels: Vec = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default(); + let mut selected = d.list_index.min(levels.len().saturating_sub(1)); + let t = Tokens::get(ui.ctx()); + ui.horizontal_wrapped(|ui| { + // Levels are not limited by the columns, allow the same column twice (up to 64 levels). + let next_column = next_level_column(&choices, &levels, selected); + if text_icon_button(ui, Icon::Plus, t.accent, "Add Level", levels.len() < 64 && next_column.is_some()).clicked() + && let Some(next) = next_column + { + levels.push(json!({"column": next, "order": "asc"})); + selected = levels.len() - 1; + } + if text_icon_button(ui, Icon::Close, t.danger, "Delete Level", !levels.is_empty()).clicked() && selected < levels.len() { + levels.remove(selected); + selected = selected.saturating_sub(1); + } + if text_icon_button(ui, Icon::Copy, t.text, "Copy Level", !levels.is_empty() && levels.len() < 64).clicked() + && let Some(lv) = levels.get(selected).cloned() + { + levels.insert(selected + 1, lv); + selected += 1; + } + if icon_button(ui, Icon::ChevronUp, t.text, "Move Up", selected > 0).clicked() { + levels.swap(selected, selected - 1); + selected -= 1; + } + if icon_button(ui, Icon::Chevron, t.text, "Move Down", selected + 1 < levels.len()).clicked() { + levels.swap(selected, selected + 1); + selected += 1; + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.checkbox(&mut header, lang.tr("My list has headers")); + }); + }); + d.values.insert("header".into(), json!(header)); + if header != was_header + && let Some(r) = range + { + let shown = if header && r.height() > 1 { body_of(r) } else { r }; + let _ = app.run("selection.set", json!({"range": shown.a1()})); + } + ui.add_space(4.0); + let table_height = (ui.available_height() - 48.0).max(60.0); + egui::ScrollArea::vertical().max_height(table_height).min_scrolled_height(table_height).auto_shrink([false, false]).show(ui, |ui| { + levels_table(ui, &mut levels, &mut selected, &choices, lang); + }); + d.list_index = selected; + d.values.insert("levels".into(), Json::Array(levels.clone())); + let mut open = true; + ok_cancel(ui, confirm, &mut open); + if *confirm && !levels.is_empty() { + let mut p = json!({"header": header, "keys": levels}); + if let Some(r) = d.values.get("range").and_then(Json::as_str) { + p["range"] = json!(r); + } + // The range has no sheet name, so it must not be read against another worksheet. + let failure = if sheet_key(app) != d.sort.home { + Some("Return to the original worksheet to sort, or cancel.".to_string()) + } else { + app.run("data.sort", p).err().map(|e| crate::clean_error(&e)) + }; + if let Some(message) = failure { + app.message = Some((d.title.clone(), message)); + *confirm = false; + } + } + if !open { + *confirm = true; + } +} + +/// The selectable level rows: "Sort by"/"Then by" with the column, sort-on and order pickers. +fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, choices: &[Choice], lang: Language) { + let gap = ui.spacing().item_spacing.x; + // The row label column grows with the translated words, so a longer one is never wrapped or cut. + let font = egui::TextStyle::Body.resolve(ui.style()); + let label_w = ["Sort by", "Then by"] + .iter() + .map(|key| ui.painter().layout_no_wrap(lang.tr(key).to_string(), font.clone(), egui::Color32::PLACEHOLDER).size().x.ceil() + 4.0) + .fold(64.0, f32::max); + let row_h = 26.0; + let rest = (ui.available_width() - 16.0 - label_w - 3.0 * gap).max(300.0); + let w = rest / 3.0; + let cell = |ui: &mut egui::Ui, w: f32, h: f32, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.allocate_ui_with_layout(vec2(w, h), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_size(vec2(w, h)); + add(ui); + }); + }; + ui.horizontal(|ui| { + cell(ui, label_w + gap + w, 18.0, &mut |ui| { + ui.strong(lang.tr("Sort|Column")); + }); + cell(ui, w, 18.0, &mut |ui| { + ui.strong(lang.tr("Sort On")); + }); + cell(ui, w, 18.0, &mut |ui| { + ui.strong(lang.tr("Order")); + }); + }); + let accent = Tokens::get(ui.ctx()).accent; + for (i, lv) in levels.iter_mut().enumerate() { + let row_rect = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), row_h)); + let row = ui.interact(row_rect, ui.scope_id().with(("sortRow", i)), Sense::click()); + if i == *selected { + ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.18)); + } else if row.hovered() { + ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.07)); + } + if row.clicked() { + *selected = i; + } + ui.allocate_ui_with_layout(row_rect.size(), egui::Layout::left_to_right(egui::Align::Center), |ui| { + cell(ui, label_w, row_h, &mut |ui| { + ui.add(egui::Label::new(lang.tr(if i == 0 { "Sort by" } else { "Then by" })).selectable(false)); + }); + let mut col = lv["column"].as_str().unwrap_or("A").to_string(); + // The closed box names the column as its open list does (#3446), whatever the case of the stored letter. + let shown = choices + .iter() + .find(|(l, _, _)| l.eq_ignore_ascii_case(&col)) + .map_or_else(|| column_label(lang, &col.to_ascii_uppercase()), |(_, t, _)| t.clone()); + let r = craft_ui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| { + for (letters, label, _) in choices { + ui.selectable_value(&mut col, letters.clone(), label); + } + }); + r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort|Column"))); + if r.response.clicked() { + *selected = i; + } + lv["column"] = json!(col.to_ascii_uppercase()); + let mut by = lv["by"].as_str().unwrap_or("values").to_string(); + let by_label = lang.tr(match by.as_str() { + "cellColor" => "Cell Color", + "fontColor" => "Font Color", + _ => "Cell Values", + }); + let r = craft_ui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| { + ui.selectable_value(&mut by, "values".into(), lang.tr("Cell Values")); + ui.selectable_value(&mut by, "cellColor".into(), lang.tr("Cell Color")); + ui.selectable_value(&mut by, "fontColor".into(), lang.tr("Font Color")); + }); + r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort On"))); + if r.response.clicked() { + *selected = i; + } + lv["by"] = json!(by); + let numeric = choices.iter().find(|(l, _, _)| lv["column"].as_str() == Some(l.as_str())).is_some_and(|(_, _, n)| *n); + let (asc_label, desc_label) = if numeric { ("Smallest to Largest", "Largest to Smallest") } else { ("A to Z", "Z to A") }; + let (asc_label, desc_label) = (lang.tr(asc_label), lang.tr(desc_label)); + let mut desc = lv["order"].as_str() == Some("desc"); + let order_label = if desc { desc_label } else { asc_label }; + let r = craft_ui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| { + ui.selectable_value(&mut desc, false, asc_label); + ui.selectable_value(&mut desc, true, desc_label); + }); + r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Order"))); + if r.response.clicked() { + *selected = i; + } + lv["order"] = json!(if desc { "desc" } else { "asc" }); + }); + } +} + +/// A bordered icon-only button with a tooltip, greyed out when disabled. +fn icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, tip: &str, enabled: bool) -> egui::Response { + let color = if enabled { color } else { Tokens::get(ui.ctx()).text_disabled }; + let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::icon_button(ui, icon, color, tip, vec2(24.0, 24.0))).inner; + button_border(ui, response.rect); + response +} + +/// A bordered button with a coloured icon and a text label, greyed out when disabled. +fn text_icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, label: &str, enabled: bool) -> egui::Response { + let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::small_button_accent(ui, icon, Some(color), label, label, false)).inner; + button_border(ui, response.rect); + response +} + +/// Draws the visible border around a button's `rect`. +fn button_border(ui: &egui::Ui, rect: egui::Rect) { + let t = Tokens::get(ui.ctx()); + ui.painter().rect_stroke(rect, 4.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside); +} + +/// Whether the values are numbers (blanks aside), which picks "Smallest to Largest" over "A to Z". +fn values_are_numeric(values: impl IntoIterator) -> bool { + let mut has_number = false; + for value in values { + match value { + Value::Empty => {} + Value::Number(_) => has_number = true, + _ => return false, + } + } + has_number +} diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 34b76c982..97a1d9de6 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -53,7 +53,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) { } else { Rect::from_min_max(available.min, pos2(available.right() - bar, available.bottom())) }; - let resp = ui.allocate_rect(rect, Sense::click_and_drag()); + let resp = ui.allocate_rect(rect, crate::dialogs::grid_sense(app)); app.grid.rect = Some(rect); let Some(d) = app.session.active() else { return }; let wb: Arc = d.wb.clone(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2a331bb85..6f5036c80 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -493,6 +493,45 @@ mod tests { } } + /// The Custom Sort dialog's own strings have a row in every catalog (no silent English + /// fallback), keep the `{letters}` placeholder, and read as plain English in English. + #[test] + fn custom_sort_strings_are_translated_in_every_catalog() { + let keys = [ + "Sort by", + "Then by", + "My list has headers", + "Cell Values", + "Cell Color", + "Font Color", + "A to Z", + "Z to A", + "Add Level", + "Delete Level", + "Copy Level", + "Move Up", + "Move Down", + "Order", + "Sort On", + "Sort|Column", + "Column {letters}", + "Smallest to Largest", + "Largest to Smallest", + "Close the Sort dialog before switching or changing worksheets.", + "Return to the original worksheet to sort, or cancel.", + ]; + for key in keys { + let english = key.rsplit_once('|').map_or(key, |(_, label)| label); + assert_eq!(Language::En.tr(key), english); + for language in Language::ALL.into_iter().filter(|l| *l != Language::En) { + let code = language.code(); + let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}")); + assert!(!shown.trim().is_empty() && !shown.contains('|'), "{code}: bad translation of {key:?}: {shown:?}"); + assert_eq!(shown.contains("{letters}"), key.contains("{letters}"), "{code}: placeholder of {key:?}: {shown:?}"); + } + } + } + #[test] fn fill_puts_each_value_in_once() { // A value holding a placeholder (a macro named `{steps}`) is shown as it is. diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 390558e4c..a7464598a 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -600,6 +600,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Zobrazit", "Collapse dialog" => "Sbalit dialogové okno", "Expand dialog" => "Rozbalit dialogové okno", + "My list has headers" => "Data obsahují záhlaví", + "Sort by" => "Seřadit podle", + "Then by" => "Potom podle", + "Cell Values" => "Hodnoty buněk", + "Cell Color" => "Barva buňky", + "A to Z" => "Od A do Z", + "Z to A" => "Od Z do A", + "Add Level" => "Přidat úroveň", + "Delete Level" => "Odstranit úroveň", + "Copy Level" => "Kopírovat úroveň", + "Move Up" => "Posunout nahoru", + "Move Down" => "Posunout dolů", + "Order" => "Pořadí", + "Sort On" => "Seřadit podle", + "Sort|Column" => "Sloupec", + "Column {letters}" => "Sloupec {letters}", + "Smallest to Largest" => "Od nejmenšího po největší", + "Largest to Smallest" => "Od největšího po nejmenší", + "Close the Sort dialog before switching or changing worksheets." => "Před přepnutím nebo změnou listů zavřete dialogové okno Seřadit.", + "Return to the original worksheet to sort, or cancel." => "Chcete-li řadit, vraťte se na původní list, nebo akci zrušte.", "Numerical Count" => "Počet čísel", "Minimum" => "Minimum", "Maximum" => "Maximum", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ccd722959..300cc4969 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -520,6 +520,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Anzeigen", "Collapse dialog" => "Dialogfeld reduzieren", "Expand dialog" => "Dialogfeld erweitern", + "My list has headers" => "Daten haben Überschriften", + "Sort by" => "Sortieren nach", + "Then by" => "Anschließend nach", + "Cell Values" => "Zellenwerte", + "Cell Color" => "Zellenfarbe", + "A to Z" => "A bis Z", + "Z to A" => "Z bis A", + "Add Level" => "Ebene hinzufügen", + "Delete Level" => "Ebene löschen", + "Copy Level" => "Ebene kopieren", + "Move Up" => "Nach oben", + "Move Down" => "Nach unten", + "Order" => "Reihenfolge", + "Sort On" => "Sortieren nach", + "Sort|Column" => "Spalte", + "Column {letters}" => "Spalte {letters}", + "Smallest to Largest" => "Vom Kleinsten zum Größten", + "Largest to Smallest" => "Vom Größten zum Kleinsten", + "Close the Sort dialog before switching or changing worksheets." => { + "Schließen Sie das Dialogfeld „Sortieren“, bevor Sie das Blatt wechseln oder Blätter ändern." + } + "Return to the original worksheet to sort, or cancel." => "Kehren Sie zum ursprünglichen Blatt zurück, um zu sortieren, oder brechen Sie ab.", "Numerical Count" => "Numerische Zählung", "Minimum" => "Minimum", "Maximum" => "Maximum", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 8b08bb2de..1287ad6a0 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -884,7 +884,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Cell Color" => "Χρώμα κελιού", "A to Z" => "Α έως Ω", "Z to A" => "Ω έως Α", - "+ Add Level" => "+ Προσθήκη επιπέδου", + "Add Level" => "Προσθήκη επιπέδου", + "Delete Level" => "Διαγραφή επιπέδου", + "Copy Level" => "Αντιγραφή επιπέδου", + "Move Up" => "Μετακίνηση πάνω", + "Move Down" => "Μετακίνηση κάτω", + "Order" => "Σειρά", + "Sort On" => "Ταξινόμηση ως προς", + "Sort|Column" => "Στήλη", + "Column {letters}" => "Στήλη {letters}", + "Smallest to Largest" => "Από το μικρότερο στο μεγαλύτερο", + "Largest to Smallest" => "Από το μεγαλύτερο στο μικρότερο", + "Close the Sort dialog before switching or changing worksheets." => { + "Κλείστε το παράθυρο διαλόγου Ταξινόμηση πριν αλλάξετε ή τροποποιήσετε φύλλα εργασίας." + } + "Return to the original worksheet to sort, or cancel." => "Επιστρέψτε στο αρχικό φύλλο εργασίας για να ταξινομήσετε ή ακυρώστε.", "New…" => "Νέο…", "Edit…" => "Επεξεργασία…", "Name" => "Όνομα", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 615a611a6..d0df42c8b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -526,6 +526,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostrar", "Collapse dialog" => "Contraer diálogo", "Expand dialog" => "Expandir diálogo", + "My list has headers" => "Mis datos tienen encabezados", + "Sort by" => "Ordenar por", + "Then by" => "Luego por", + "Cell Values" => "Valores de celda", + "Cell Color" => "Color de celda", + "A to Z" => "De A a Z", + "Z to A" => "De Z a A", + "Add Level" => "Agregar nivel", + "Delete Level" => "Eliminar nivel", + "Copy Level" => "Copiar nivel", + "Move Up" => "Subir", + "Move Down" => "Bajar", + "Order" => "Orden", + "Sort On" => "Ordenar según", + "Sort|Column" => "Columna", + "Column {letters}" => "Columna {letters}", + "Smallest to Largest" => "De menor a mayor", + "Largest to Smallest" => "De mayor a menor", + "Close the Sort dialog before switching or changing worksheets." => { + "Cierre el cuadro de diálogo Ordenar antes de cambiar de hoja o modificar las hojas." + } + "Return to the original worksheet to sort, or cancel." => "Vuelva a la hoja original para ordenar o cancele.", "Numerical Count" => "Recuento numérico", "Minimum" => "Mínimo", "Maximum" => "Máximo", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 880717020..104edcd16 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -486,6 +486,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Afficher", "Collapse dialog" => "Réduire la boîte de dialogue", "Expand dialog" => "Développer la boîte de dialogue", + "My list has headers" => "Mes données ont des en-têtes", + "Sort by" => "Trier par", + "Then by" => "Puis par", + "Cell Values" => "Valeurs de cellule", + "Cell Color" => "Couleur de cellule", + "A to Z" => "De A à Z", + "Z to A" => "De Z à A", + "Add Level" => "Ajouter un niveau", + "Delete Level" => "Supprimer le niveau", + "Copy Level" => "Copier le niveau", + "Move Up" => "Monter", + "Move Down" => "Descendre", + "Order" => "Ordre", + "Sort On" => "Trier sur", + "Sort|Column" => "Colonne", + "Column {letters}" => "Colonne {letters}", + "Smallest to Largest" => "Du plus petit au plus grand", + "Largest to Smallest" => "Du plus grand au plus petit", + "Close the Sort dialog before switching or changing worksheets." => { + "Fermez la boîte de dialogue Trier avant de changer de feuille ou de modifier les feuilles." + } + "Return to the original worksheet to sort, or cancel." => "Revenez à la feuille d’origine pour trier, ou annulez.", "Numerical Count" => "Nombre de valeurs numériques", "Minimum" => "Minimum", "Maximum" => "Maximum", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e4557afb8..1ca07d34b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -770,7 +770,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Cell Color" => "Colore cella", "A to Z" => "Dalla A alla Z", "Z to A" => "Dalla Z alla A", - "+ Add Level" => "+ Aggiungi livello", + "Add Level" => "Aggiungi livello", + "Delete Level" => "Elimina livello", + "Copy Level" => "Copia livello", + "Move Up" => "Sposta su", + "Move Down" => "Sposta giù", + "Order" => "Ordine", + "Sort On" => "Ordina in base a", + "Sort|Column" => "Colonna", + "Column {letters}" => "Colonna {letters}", + "Smallest to Largest" => "Dal più piccolo al più grande", + "Largest to Smallest" => "Dal più grande al più piccolo", + "Close the Sort dialog before switching or changing worksheets." => { + "Chiudi la finestra di dialogo Ordina prima di cambiare o modificare i fogli di lavoro." + } + "Return to the original worksheet to sort, or cancel." => "Torna al foglio di lavoro originale per ordinare oppure annulla.", "New…" => "Nuovo…", "Edit…" => "Modifica…", "Name" => "Nome", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 94ef0f613..f5d9baa2a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -786,7 +786,22 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Cell Color", "セルの色"), ("A to Z", "昇順"), ("Z to A", "降順"), - ("+ Add Level", "+ レベルの追加"), + ("Add Level", "レベルの追加"), + ("Delete Level", "レベルの削除"), + ("Copy Level", "レベルのコピー"), + ("Move Up", "上へ移動"), + ("Move Down", "下へ移動"), + ("Order", "順序"), + ("Sort On", "並べ替えのキー"), + ("Sort|Column", "列"), + ("Column {letters}", "列 {letters}"), + ("Smallest to Largest", "小さい順"), + ("Largest to Smallest", "大きい順"), + ( + "Close the Sort dialog before switching or changing worksheets.", + "シートを切り替えたり変更したりする前に、並べ替えダイアログを閉じてください。", + ), + ("Return to the original worksheet to sort, or cancel.", "並べ替えるには元のシートに戻るか、キャンセルしてください。"), ("New…", "新規作成…"), ("Edit…", "編集…"), ("Name", "名前"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index e2dce4345..880f97ac8 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -490,6 +490,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "표시", "Collapse dialog" => "대화 상자 축소", "Expand dialog" => "대화 상자 확장", + "My list has headers" => "내 데이터에 머리글 표시", + "Sort by" => "정렬 기준", + "Then by" => "다음 기준", + "Cell Values" => "셀 값", + "Cell Color" => "셀 색", + "A to Z" => "A에서 Z", + "Z to A" => "Z에서 A", + "Add Level" => "기준 추가", + "Delete Level" => "기준 삭제", + "Copy Level" => "기준 복사", + "Move Up" => "위로 이동", + "Move Down" => "아래로 이동", + "Order" => "정렬", + "Sort On" => "정렬 기준", + "Sort|Column" => "열", + "Column {letters}" => "{letters} 열", + "Smallest to Largest" => "가장 작은 값에서 가장 큰 값으로", + "Largest to Smallest" => "가장 큰 값에서 가장 작은 값으로", + "Close the Sort dialog before switching or changing worksheets." => "시트를 전환하거나 변경하기 전에 정렬 대화 상자를 닫으세요.", + "Return to the original worksheet to sort, or cancel." => "정렬하려면 원래 시트로 돌아가거나 취소하세요.", "Numerical Count" => "숫자 셀 수", "Minimum" => "최소값", "Maximum" => "최대값", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index a99caf0af..ea0352af3 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -561,6 +561,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Weergeven", "Collapse dialog" => "Dialoogvenster samenvouwen", "Expand dialog" => "Dialoogvenster uitvouwen", + "My list has headers" => "Mijn gegevens bevatten kopteksten", + "Sort by" => "Sorteren op", + "Then by" => "Vervolgens op", + "Cell Values" => "Celwaarden", + "Cell Color" => "Celkleur", + "A to Z" => "A tot Z", + "Z to A" => "Z tot A", + "Add Level" => "Niveau toevoegen", + "Delete Level" => "Niveau verwijderen", + "Copy Level" => "Niveau kopiëren", + "Move Up" => "Omhoog", + "Move Down" => "Omlaag", + "Order" => "Volgorde", + "Sort On" => "Sorteren op", + "Sort|Column" => "Kolom", + "Column {letters}" => "Kolom {letters}", + "Smallest to Largest" => "Van klein naar groot", + "Largest to Smallest" => "Van groot naar klein", + "Close the Sort dialog before switching or changing worksheets." => { + "Sluit het dialoogvenster Sorteren voordat u van blad wisselt of bladen wijzigt." + } + "Return to the original worksheet to sort, or cancel." => "Ga terug naar het oorspronkelijke blad om te sorteren, of annuleer.", "Numerical Count" => "Numerieke telling", "Minimum" => "Minimum", "Maximum" => "Maximum", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 762bb815c..b7b588205 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -761,7 +761,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Cell Color" => "Kolor komórki", "A to Z" => "Od A do Z", "Z to A" => "Od Z do A", - "+ Add Level" => "+ Dodaj poziom", + "Add Level" => "Dodaj poziom", + "Delete Level" => "Usuń poziom", + "Copy Level" => "Kopiuj poziom", + "Move Up" => "Przesuń w górę", + "Move Down" => "Przesuń w dół", + "Order" => "Kolejność", + "Sort On" => "Sortuj na podstawie", + "Sort|Column" => "Kolumna", + "Column {letters}" => "Kolumna {letters}", + "Smallest to Largest" => "Od najmniejszych do największych", + "Largest to Smallest" => "Od największych do najmniejszych", + "Close the Sort dialog before switching or changing worksheets." => { + "Zamknij okno dialogowe Sortowanie przed przełączeniem lub zmianą arkuszy." + } + "Return to the original worksheet to sort, or cancel." => "Wróć do oryginalnego arkusza, aby posortować, lub anuluj.", "New…" => "Nowy…", "Edit…" => "Edytuj…", "Name" => "Nazwa", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 6c96e8528..168450222 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -795,7 +795,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Cell Color" => "Cor da Célula", "A to Z" => "De A a Z", "Z to A" => "De Z a A", - "+ Add Level" => "+ Adicionar Nível", + "Add Level" => "Adicionar Nível", + "Delete Level" => "Excluir Nível", + "Copy Level" => "Copiar Nível", + "Move Up" => "Mover para Cima", + "Move Down" => "Mover para Baixo", + "Order" => "Ordem", + "Sort On" => "Classificar em", + "Sort|Column" => "Coluna", + "Column {letters}" => "Coluna {letters}", + "Smallest to Largest" => "Do Menor para o Maior", + "Largest to Smallest" => "Do Maior para o Menor", + "Close the Sort dialog before switching or changing worksheets." => { + "Feche a caixa de diálogo Classificar antes de alternar ou alterar planilhas." + } + "Return to the original worksheet to sort, or cancel." => "Volte para a planilha original para classificar ou cancele.", "New…" => "Novo…", "Edit…" => "Editar…", "Name" => "Nome", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 30ecc4936..ad47d7011 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -767,7 +767,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Cell Color" => "Culoare celulă", "A to Z" => "De la A la Z", "Z to A" => "De la Z la A", - "+ Add Level" => "+ Adăugare nivel", + "Add Level" => "Adăugare nivel", + "Delete Level" => "Ștergere nivel", + "Copy Level" => "Copiere nivel", + "Move Up" => "Mutare în sus", + "Move Down" => "Mutare în jos", + "Order" => "Ordine", + "Sort On" => "Sortare pe baza", + "Sort|Column" => "Coloană", + "Column {letters}" => "Coloană {letters}", + "Smallest to Largest" => "De la cel mai mic la cel mai mare", + "Largest to Smallest" => "De la cel mai mare la cel mai mic", + "Close the Sort dialog before switching or changing worksheets." => { + "Închideți caseta de dialog Sortare înainte de a comuta sau a modifica foile de lucru." + } + "Return to the original worksheet to sort, or cancel." => "Reveniți la foaia de lucru inițială pentru a sorta sau anulați.", "New…" => "Nou…", "Edit…" => "Editare…", "Name" => "Nume", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 67ebbf82e..77a387442 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -494,6 +494,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Показать", "Collapse dialog" => "Свернуть диалоговое окно", "Expand dialog" => "Развернуть диалоговое окно", + "My list has headers" => "Мои данные содержат заголовки", + "Sort by" => "Сортировать по", + "Then by" => "Затем по", + "Cell Values" => "Значения ячеек", + "Cell Color" => "Цвет ячейки", + "A to Z" => "От А до Я", + "Z to A" => "От Я до А", + "Add Level" => "Добавить уровень", + "Delete Level" => "Удалить уровень", + "Copy Level" => "Копировать уровень", + "Move Up" => "Вверх", + "Move Down" => "Вниз", + "Order" => "Порядок", + "Sort On" => "Сортировка", + "Sort|Column" => "Столбец", + "Column {letters}" => "Столбец {letters}", + "Smallest to Largest" => "От наименьшего к наибольшему", + "Largest to Smallest" => "От наибольшего к наименьшему", + "Close the Sort dialog before switching or changing worksheets." => { + "Закройте диалоговое окно «Сортировка», прежде чем переключать или изменять листы." + } + "Return to the original worksheet to sort, or cancel." => "Вернитесь на исходный лист, чтобы выполнить сортировку, или отмените действие.", "Numerical Count" => "Количество чисел", "Minimum" => "Минимум", "Maximum" => "Максимум", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index fad0524d8..4b65ab8be 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -481,6 +481,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Prikaži", "Collapse dialog" => "Skupi dijalog", "Expand dialog" => "Proširi dijalog", + "My list has headers" => "Moji podaci imaju zaglavlja", + "Sort by" => "Sortiraj po", + "Then by" => "Zatim po", + "Cell Values" => "Vrednosti ćelija", + "Cell Color" => "Boja ćelije", + "A to Z" => "Od A do Z", + "Z to A" => "Od Z do A", + "Add Level" => "Dodaj nivo", + "Delete Level" => "Izbriši nivo", + "Copy Level" => "Kopiraj nivo", + "Move Up" => "Pomeri nagore", + "Move Down" => "Pomeri nadole", + "Order" => "Redosled", + "Sort On" => "Sortiraj po", + "Sort|Column" => "Kolona", + "Column {letters}" => "Kolona {letters}", + "Smallest to Largest" => "Od najmanjeg do najvećeg", + "Largest to Smallest" => "Od najvećeg do najmanjeg", + "Close the Sort dialog before switching or changing worksheets." => { + "Zatvorite dijalog Sortiranje pre nego što promenite ili izmenite radne listove." + } + "Return to the original worksheet to sort, or cancel." => "Vratite se na prvobitni radni list da biste sortirali, ili otkažite.", "Numerical Count" => "Broj numeričkih vrednosti", "Minimum" => "Minimum", "Maximum" => "Maksimum", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index d6f63b7f1..e2d27fbf0 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -451,6 +451,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Göster", "Collapse dialog" => "İletişim kutusunu daralt", "Expand dialog" => "İletişim kutusunu genişlet", + "My list has headers" => "Verilerimde üst bilgi var", + "Sort by" => "Sıralama ölçütü", + "Then by" => "Sonra", + "Cell Values" => "Hücre Değerleri", + "Cell Color" => "Hücre Rengi", + "A to Z" => "A'dan Z'ye", + "Z to A" => "Z'den A'ya", + "Add Level" => "Düzey Ekle", + "Delete Level" => "Düzeyi Sil", + "Copy Level" => "Düzeyi Kopyala", + "Move Up" => "Yukarı Taşı", + "Move Down" => "Aşağı Taşı", + "Order" => "Sıra", + "Sort On" => "Sıralama Ölçütü", + "Sort|Column" => "Sütun", + "Column {letters}" => "Sütun {letters}", + "Smallest to Largest" => "En Küçükten En Büyüğe", + "Largest to Smallest" => "En Büyükten En Küçüğe", + "Close the Sort dialog before switching or changing worksheets." => { + "Çalışma sayfaları arasında geçiş yapmadan veya sayfaları değiştirmeden önce Sırala iletişim kutusunu kapatın." + } + "Return to the original worksheet to sort, or cancel." => "Sıralamak için özgün çalışma sayfasına dönün veya iptal edin.", "Numerical Count" => "Sayısal Sayım", "Minimum" => "En Küçük", "Maximum" => "En Büyük", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 3fa3550c8..185a21c1d 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -757,14 +757,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "{count} cell(s) found" => "{count} cell(s) found", "Reference:" => "Reference:", "Special…" => "Special…", - "My list has headers" => "My list has headers", - "Sort by" => "Sort by", - "Then by" => "Then by", - "Cell Values" => "Cell Values", - "Cell Color" => "Cell Color", - "A to Z" => "A to Z", - "Z to A" => "Z to A", - "+ Add Level" => "+ Add Level", + "My list has headers" => "Мої дані містять заголовки", + "Sort by" => "Сортувати за", + "Then by" => "Потім за", + "Cell Values" => "Значення клітинок", + "Cell Color" => "Колір клітинки", + "A to Z" => "Від А до Я", + "Z to A" => "Від Я до А", + "Add Level" => "Додати рівень", + "Delete Level" => "Видалити рівень", + "Copy Level" => "Копіювати рівень", + "Move Up" => "Вгору", + "Move Down" => "Вниз", + "Order" => "Порядок", + "Sort On" => "Сортування", + "Sort|Column" => "Стовпець", + "Column {letters}" => "Стовпець {letters}", + "Smallest to Largest" => "Від найменшого до найбільшого", + "Largest to Smallest" => "Від найбільшого до найменшого", + "Close the Sort dialog before switching or changing worksheets." => { + "Закрийте діалогове вікно «Сортування», перш ніж перемикати або змінювати аркуші." + } + "Return to the original worksheet to sort, or cancel." => "Поверніться на вихідний аркуш, щоб виконати сортування, або скасуйте дію.", "New…" => "New…", "Edit…" => "Edit…", "Name" => "Name", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 1789fd5bd..93dd95937 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -451,6 +451,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Hiện", "Collapse dialog" => "Thu gọn hộp thoại", "Expand dialog" => "Mở rộng hộp thoại", + "My list has headers" => "Dữ liệu của tôi có tiêu đề", + "Sort by" => "Sắp xếp theo", + "Then by" => "Sau đó theo", + "Cell Values" => "Giá trị ô", + "Cell Color" => "Màu ô", + "A to Z" => "A đến Z", + "Z to A" => "Z đến A", + "Add Level" => "Thêm cấp", + "Delete Level" => "Xóa cấp", + "Copy Level" => "Sao chép cấp", + "Move Up" => "Di chuyển lên", + "Move Down" => "Di chuyển xuống", + "Order" => "Thứ tự", + "Sort On" => "Sắp xếp theo", + "Sort|Column" => "Cột", + "Column {letters}" => "Cột {letters}", + "Smallest to Largest" => "Nhỏ nhất đến lớn nhất", + "Largest to Smallest" => "Lớn nhất đến nhỏ nhất", + "Close the Sort dialog before switching or changing worksheets." => "Hãy đóng hộp thoại Sắp xếp trước khi chuyển hoặc thay đổi trang tính.", + "Return to the original worksheet to sort, or cancel." => "Hãy quay lại trang tính ban đầu để sắp xếp, hoặc hủy.", "Numerical Count" => "Số đếm số", "Minimum" => "Tối thiểu", "Maximum" => "Tối đa", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index b2370c2bb..b57d3292d 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -482,6 +482,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "显示", "Collapse dialog" => "折叠对话框", "Expand dialog" => "展开对话框", + "My list has headers" => "数据包含标题", + "Sort by" => "主要关键字", + "Then by" => "次要关键字", + "Cell Values" => "单元格值", + "Cell Color" => "单元格颜色", + "A to Z" => "A 到 Z", + "Z to A" => "Z 到 A", + "Add Level" => "添加条件", + "Delete Level" => "删除条件", + "Copy Level" => "复制条件", + "Move Up" => "上移", + "Move Down" => "下移", + "Order" => "次序", + "Sort On" => "排序依据", + "Sort|Column" => "列", + "Column {letters}" => "列 {letters}", + "Smallest to Largest" => "从小到大", + "Largest to Smallest" => "从大到小", + "Close the Sort dialog before switching or changing worksheets." => "切换或更改工作表之前,请先关闭“排序”对话框。", + "Return to the original worksheet to sort, or cancel." => "请返回原工作表后再排序,或取消。", "Numerical Count" => "数值计数", "Minimum" => "最小值", "Maximum" => "最大值", diff --git a/crates/ui-egui/tests/it/sort_dialog_columns.rs b/crates/ui-egui/tests/it/sort_dialog_columns.rs index 098f9c3e6..18cf47743 100644 --- a/crates/ui-egui/tests/it/sort_dialog_columns.rs +++ b/crates/ui-egui/tests/it/sort_dialog_columns.rs @@ -9,6 +9,7 @@ use serde_json::json; type Harness = egui_kittest::Harness<'static, SheetApp>; +/// A harness around the app with `session` loaded. fn harness(session: Session) -> Harness { crate::support::harness(session, 4) } @@ -22,10 +23,12 @@ fn sales() -> Session { s } +/// The column of the first sort level in the open dialog. fn col(h: &Harness) -> String { h.state().dialog.as_ref().unwrap().values["levels"][0]["column"].as_str().unwrap_or("").to_string() } +/// Sort by starts on the column the cursor is in. #[test] fn sort_dialog_seeds_the_active_column() { let mut h = harness(sales()); @@ -34,8 +37,8 @@ fn sort_dialog_seeds_the_active_column() { assert_eq!(col(&h), "B", "Sort by starts on the column the cursor is in, not A"); } -/// #3446: the closed "Sort by" box shows the column's name next to its letter, -/// as the open list does ("B: Revenue", not just "B"). +/// #3446: the closed "Sort by" box shows the column's name, as the open list does +/// ("Revenue", not just the letter "B"). #[test] fn closed_column_box_shows_the_column_name() { use egui::accesskit::Role; @@ -43,17 +46,18 @@ fn closed_column_box_shows_the_column_name() { h.state_mut().open_dialog("sort", json!({})); h.run_steps(2); let shown: Vec = h.get_all_by_role(Role::ComboBox).filter_map(|n| n.value()).collect(); - assert!(shown.iter().any(|v| v == "B: Revenue"), "the Sort by box shows the column name: {shown:?}"); + assert!(shown.iter().any(|v| v == "Revenue"), "the Sort by box shows the column name: {shown:?}"); } +/// Add Level picks a column no other level uses. #[test] fn add_level_picks_a_column_no_level_uses_yet() { let mut h = harness(sales()); h.state_mut().open_dialog("sort", json!({})); h.run_steps(2); - // Level 1 seeded B; clicking "+ Add Level" must not default level 2 to B too (#1906 review). + // Level 1 seeded B; clicking "Add Level" must not default level 2 to B too (#1906 review). h.run_steps(6); - h.get_by_label("+ Add Level").click(); + h.get_by_label("Add Level").click(); h.run_steps(6); let cols: Vec = h.state().dialog.as_ref().unwrap().values["levels"] .as_array() @@ -63,6 +67,102 @@ fn add_level_picks_a_column_no_level_uses_yet() { assert_ne!(cols[0], cols[1], "the second level defaults to a different column: {cols:?}"); } +/// Add Level is not limited by the number of columns (Excel allows many levels): with every +/// column in use it adds a level on the selected level's column, and never one outside the range. +#[test] +fn add_level_keeps_adding_levels_when_every_column_is_used() { + let mut s = sales(); + s.execute("selection.set", json!({"range": "A1:A4", "active": "A2"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + for _ in 0..2 { + h.get_by_label("Add Level").click(); + h.run_steps(4); + } + let levels = h.state().dialog.as_ref().unwrap().values["levels"].as_array().unwrap(); + assert_eq!(levels.len(), 3, "Add Level stays available with one column"); + assert!(levels.iter().all(|l| l["column"] == "A"), "no level uses a column outside A: {levels:?}"); +} + +/// In the interface languages whose scripts the bundled fonts cover (CJK and Vietnamese need the +/// optional font repo), the toolbar (level buttons and the headers checkbox) stays on one row without +/// overlapping: the window widens for a longer translation. +#[test] +fn toolbar_fits_without_overlap_in_every_language() { + use gridcraft_ui_egui::i18n::Language; + for language in Language::ALL.into_iter().filter(|l| !matches!(l, Language::Ja | Language::Ko | Language::Zh | Language::Vi)) { + let mut app = crate::common::app(sales()); + app.ui.language = language; + let mut h = crate::support::app_harness(app, 4); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(6); + let rects: Vec = ["Add Level", "Delete Level", "Copy Level", "Move Up", "Move Down", "My list has headers"] + .iter() + .map(|key| h.get_by_label(language.tr(key)).rect()) + .collect(); + let code = language.code(); + for (i, a) in rects.iter().enumerate() { + for b in &rects[i + 1..] { + assert!(!a.intersects(*b), "{code}: toolbar items overlap: {a:?} {b:?}"); + } + assert!((a.center().y - rects[0].center().y).abs() < 12.0, "{code}: the toolbar wrapped: {rects:?}"); + } + } +} + +/// Escape restores every selected area and the active cell. +#[test] +fn sort_dialog_restores_all_selected_areas_and_the_active_cell() { + let mut s = sales(); + s.execute("selection.set", json!({"range": "A1:A4,B1:B4", "active": "B2"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.input_mut().events.push(egui::Event::Key { + key: Key::Escape, + physical_key: Some(Key::Escape), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }); + h.run_steps(2); + let selection = &h.state().session.active().unwrap().selection; + assert_eq!(selection.a1(), "A1:A4,B1:B4"); + assert_eq!(selection.active.a1(), "B2"); +} + +/// Cancel after toggling headers restores the original selection. +#[test] +fn sort_dialog_restores_initial_selection_after_header_toggle() { + let mut h = harness(sales()); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.get_by_label("My list has headers").click(); + h.run_steps(2); + h.get_by_label(" Cancel ").click(); + h.run_steps(2); + let selection = &h.state().session.active().unwrap().selection; + assert_eq!(selection.a1(), "B2"); + assert_eq!(selection.active.a1(), "B2"); +} + +/// OK after toggling headers restores the original selection. +#[test] +fn sort_dialog_restores_initial_selection_after_confirming_with_header_toggle() { + let mut h = harness(sales()); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.get_by_label("My list has headers").click(); + h.run_steps(2); + h.get_by_label(" OK ").click(); + h.run_steps(2); + let selection = &h.state().session.active().unwrap().selection; + assert_eq!(selection.a1(), "B2"); + assert_eq!(selection.active.a1(), "B2"); +} + +/// OK sorts the rows by the seeded column. #[test] fn sorting_by_the_seeded_column_orders_the_rows() { let mut h = harness(sales()); @@ -82,3 +182,171 @@ fn sorting_by_the_seeded_column_orders_the_rows() { let nums: Vec = (1..4).map(|r| sh.value(gridcraft_engine::core::CellRef::new(r, 1))).filter_map(|v| v.as_f64().map(|n| n as i64)).collect(); assert_eq!(nums, vec![10, 20, 30], "sort ran on the seeded column B"); } + +/// A request whose range cannot be read opens nothing, so OK cannot sort the selection instead. +#[test] +fn sort_dialog_rejects_an_invalid_range_instead_of_sorting_the_selection() { + let mut h = harness(sales()); + h.state_mut().open_dialog("sort", json!({"range": "not a range"})); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "no dialog opens for a range that cannot be read"); + assert!(h.state().message.is_some(), "the rejection is explained"); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "nothing was sorted"); +} + +/// A range on another worksheet is sorted there, not on the worksheet that happened to be active. +#[test] +fn sort_dialog_keeps_the_worksheet_the_range_names() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("range.setValues", json!({"range": "Other!A1", "values": [["Item", "Qty"], ["z", 3], ["x", 1], ["y", 2]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let mut h = harness(s); + h.state_mut().run("data.sort", json!({"range": "Other!A1:B4"})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("sort")); + assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Other", "the dialog shows the worksheet it sorts"); + assert_eq!(col(&h), "A"); + h.get_by_label(" OK ").click(); + h.run_steps(2); + let doc = h.state().session.active().unwrap(); + let qty = + |sheet: &str, row| doc.wb.sheet(doc.wb.sheet_index(sheet).unwrap()).unwrap().value(gridcraft_engine::core::CellRef::new(row, 1)).as_f64(); + assert_eq!((1..4).map(|r| qty("Other", r)).collect::>(), [Some(1.0), Some(2.0), Some(3.0)]); + assert_eq!((1..4).map(|r| qty("Sheet1", r)).collect::>(), [Some(30.0), Some(10.0), Some(20.0)], "the other worksheet is untouched"); +} + +/// An open filter menu closes when Sort opens, so it cannot take the Enter that confirms Sort. +#[test] +fn sort_dialog_closes_an_open_filter_menu() { + let mut h = harness(sales()); + h.state_mut().grid.filter_menu = Some((1, 0, egui::pos2(100.0, 100.0))); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + assert!(h.state().grid.filter_menu.is_none()); + h.input_mut().events.push(egui::Event::Key { + key: Key::Enter, + physical_key: Some(Key::Enter), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }); + h.run_steps(2); + assert!(h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "Enter confirmed Sort"); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.filterBy"), "and applied no filter"); +} + +/// Worksheet-changing commands are refused while Sort is open. +#[test] +fn sheet_tabs_cannot_switch_while_sort_is_open() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + for id in ["sheet.activate", "sheet.next", "sheet.previous", "sheet.move", "sheet.hide", "sheet.unhide", "home.insertSheet", "home.deleteSheet"] { + assert!(h.state_mut().run(id, json!({"sheet": 1})).is_err(), "{id} is refused while Sort is open"); + } + assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 0); + assert!(h.state().dialog.is_some()); +} + +/// OK on another worksheet than the one Sort opened on refuses to sort and keeps the dialog open. +#[test] +fn sort_refuses_to_run_on_another_worksheet_and_stays_open() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.state_mut().session.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + h.run_steps(2); + h.get_by_label(" OK ").click(); + h.run_steps(2); + let state = h.state(); + assert_eq!(state.dialog.as_ref().map(|d| d.name.as_str()), Some("sort"), "the dialog stays open with its levels"); + assert!(state.message.is_some(), "the refusal is explained"); + h.state_mut().session.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let doc = h.state().session.active().unwrap(); + let first = doc.wb.active().unwrap().value(gridcraft_engine::core::CellRef::new(1, 1)).as_f64(); + assert_eq!(first, Some(30.0), "the original worksheet was not sorted"); +} + +/// The dialog follows its worksheet by identity: moving the tab keeps Sort working on it. +#[test] +fn sort_still_runs_after_its_worksheet_moves_to_another_position() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.state_mut().session.execute("sheet.move", json!({"sheet": 0, "to": 1})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 1); + h.get_by_label(" OK ").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "the sort ran and the dialog closed"); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + let revenue: Vec<_> = (1..4).map(|r| sh.value(gridcraft_engine::core::CellRef::new(r, 1)).as_f64()).collect(); + assert_eq!(revenue, [Some(10.0), Some(20.0), Some(30.0)], "the moved worksheet was sorted"); +} + +/// A different worksheet that takes the opening worksheet's position is not the opening worksheet. +#[test] +fn sort_refuses_a_different_worksheet_at_the_same_position() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.state_mut().session.execute("home.deleteSheet", json!({"sheet": 0})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 0); + h.get_by_label(" OK ").click(); + h.run_steps(2); + assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("sort")); + assert!(h.state().message.is_some(), "the refusal is explained"); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "nothing was sorted"); +} + +/// Cancelling while another worksheet is active still restores the opening worksheet's selection. +#[test] +fn sort_cancel_restores_the_selection_of_the_opening_worksheet() { + let mut s = sales(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + h.state_mut().session.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + h.run_steps(2); + let other = h.state().session.active().unwrap().selection.a1(); + let done = gridcraft_ui_egui::control::handle(h.state_mut(), &egui::Context::default(), "ui.dialog.cancel", &json!({})); + assert!(matches!(done, gridcraft_ui_egui::control::Outcome::Done(_))); + assert_eq!(h.state().session.active().unwrap().selection.a1(), other, "the active worksheet's selection is left alone"); + h.state_mut().session.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + assert_eq!(h.state().session.active().unwrap().selection.a1(), "B2", "the opening worksheet got its selection back"); +} + +/// Control cancel and dialog replacement restore the selection. +#[test] +fn sort_selection_is_restored_when_control_cancels_or_replaces_the_dialog() { + let mut cancelled = harness(sales()); + cancelled.state_mut().open_dialog("sort", json!({})); + let done = gridcraft_ui_egui::control::handle(cancelled.state_mut(), &egui::Context::default(), "ui.dialog.cancel", &json!({})); + assert!(matches!(done, gridcraft_ui_egui::control::Outcome::Done(_))); + assert!(cancelled.state().dialog.is_none()); + assert_eq!(cancelled.state().session.active().unwrap().selection.a1(), "B2"); + + let mut replaced = harness(sales()); + replaced.state_mut().open_dialog("sort", json!({})); + replaced.state_mut().open_dialog("zoom", json!({})); + assert_eq!(replaced.state().dialog.as_ref().unwrap().name, "zoom"); + assert_eq!(replaced.state().session.active().unwrap().selection.a1(), "B2"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f5996328e..2c1e24a0c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -335,6 +335,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-17 | minor | A Ctrl+Alt+letter key that types a character (a user-defined Windows hotkey such as Ctrl+Alt+A for `ä`) types it instead of running the Ctrl+letter shortcut, e.g. Select All (#1530) | | 2026-10-16 | minor | Right-drag on the fill handle opens the fill menu on release: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…; Esc cancels the drag or closes the menu without filling | | 2026-10-16 | minor | With the active cell in a Table whose header row is scrolled out of view, the column headings show the header names and their filter buttons in place of the letters (#1423) | +| 2026-10-16 | minor | Custom Sort dialog: Sort by columns are a dropdown of the header names (Column A, B… without headers), Order follows the data (A to Z or Smallest to Largest), levels can be added, deleted, copied and reordered, the window moves and resizes, the grid selection follows "My list has headers" and is restored on close | | 2026-10-16 | minor | Ctrl+6 hides every object (charts, pictures, shapes, slicers) and shows them again; hidden objects are not drawn, take no clicks and drop their selection, and the setting is saved with the workbook (`workbookPr showObjects`) | | 2026-10-16 | minor | Ctrl+Shift+A (Control+Shift+A on a Mac) after a function name, or after its `(`, inserts the argument names and the closing parenthesis, as in Excel; one Undo in the editor takes them back | | 2026-10-16 | minor | Advanced Filter ribbon dialog, optional criteria for unique-only extraction (#1622); safe copy-to output (#1031) |