diff --git a/ROADMAP.md b/ROADMAP.md index b5df85b253..2141778977 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -235,7 +235,6 @@ And alongside it: - Traverse closure for `edit.traverse`: a misclosure report, an optional compass-rule adjustment, curve legs and a form. - Editor tracking fields (created/edited by and at). -- Attribute table columns: rename (hide and reorder are done) _(open)_. - Attribute forms: widgets, constraints and conditional visibility, on top of domains and subtypes. diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 21a5dd846a..5e31062e75 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -55,6 +55,17 @@ impl Field { pub fn display(&self) -> &str { self.alias.as_deref().unwrap_or(&self.name) } + + /// Gives each of the `fresh` fields (a source read again) the alias its namesake in `was` + /// had, where it had one: a column renamed in RustGIS keeps its name for display when its data + /// is reloaded. A field without a namesake, or whose namesake had no alias, keeps its own. + pub fn keep_aliases(fresh: &mut [Field], was: &[Field]) { + for field in fresh { + if let Some(alias) = was.iter().find(|w| w.name == field.name).and_then(|w| w.alias.as_ref()) { + field.alias = Some(alias.clone()); + } + } + } } #[derive(Clone, Debug, Default, PartialEq, Deserialize)] @@ -757,6 +768,18 @@ pub fn sort_class_values(values: &mut Vec) { mod tests { use super::*; + /// A reloaded source's fields take the aliases their namesakes had; a new field, and one + /// whose namesake had none, keep the source's own. + #[test] + fn reloaded_fields_keep_their_aliases() { + let aliased = |name: &str, alias: Option<&str>| Field { name: name.into(), ty: FieldType::Text, alias: alias.map(String::from) }; + let was = [aliased("a", Some("Renamed")), aliased("b", None), aliased("gone", Some("Gone"))]; + let mut fresh = [aliased("a", None), aliased("b", Some("From file")), aliased("new", None), aliased("A", None)]; + Field::keep_aliases(&mut fresh, &was); + let shown: Vec<&str> = fresh.iter().map(Field::display).collect(); + assert_eq!(shown, ["Renamed", "From file", "new", "A"]); + } + /// Whole numbers order exactly against whole numbers and against decimals, so values equal to /// one another stay equal to the same things: a sort by this order never sees a contradiction. #[test] diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2b08e43ad5..193ea0d7ab 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -98,6 +98,7 @@ edit.deleteField layer? table? field edit.elevation mode z? units? surface? edit.enable on? edit.explode +edit.fieldAlias layer? table? field alias? edit.flip edit.groundToGrid on? scale? rotation? edit.merge diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 540e117911..adc57c1e24 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -38,6 +38,9 @@ pub fn commands() -> Vec { C::new("edit.deleteField", "Delete Field", "Data › Data Design › Fields", delete_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layer_or_table) .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused)}"#), + C::new("edit.fieldAlias", "Rename Column", "Attribute Table", field_alias).roles(&[]).effects(crate::policy::Effects::NONE) + .when(need_layer_or_table) + .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "alias"?: string|null (the column's display name, at most 255 characters; the field keeps its name; empty, null or left out shows the name again)}"#), C::new("edit.convertField", "Convert Field to Dates", "Attribute Table", convert_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layer_or_table) .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "type": "date"|"datetime", "format"?: "iso" (default)|strftime numeric pattern|"excel1900"|"excel1904", "pivotYear"?: first year of the 100-year window for %y}"#), @@ -1312,6 +1315,33 @@ fn to_dates(ds: &mut Dataset, fi: usize, ty: FieldType, reader: &rustgis_data::d Ok(out) } +/// The longest field alias `edit.fieldAlias` takes, in characters (GeoPackage's and the File +/// Geodatabase's alias columns hold 255). +const ALIAS_MAX: usize = 255; + +/// `edit.fieldAlias`: names the field's column for display (the attribute table's header, layout +/// tables, search results) without renaming the field, so expressions, symbology, labels and the +/// file keep reading it by its name. An empty alias, null, or the field's own name shows the name +/// again. Only the field list changes, so a table's rows are never scanned and the edit runs on +/// the frame for every caller. +fn field_alias(s: &mut Session, p: &Json) -> CmdResult { + let t = target(s, p)?; + let fi = field_of(s, t, ps(p, "field").ok_or("field is required")?)?; + let alias = match p.get("alias") { + None | Some(Json::Null) => None, + Some(Json::String(a)) => Some(a.trim()), + Some(_) => return Err("alias is text, or null to show the field's name".into()), + }; + if let Some(a) = alias + && a.chars().count() > ALIAS_MAX + { + return Err(format!("an alias is at most {ALIAS_MAX} characters")); + } + let field = data_mut(s, t)?.fields.get_mut(fi).ok_or("no such field")?; + field.alias = alias.filter(|a| !a.is_empty() && *a != field.name).map(str::to_string); + Ok(json!({"field": field.name, "alias": field.alias})) +} + /// `edit.deleteField`: removes a field and the references to it (symbology and its expressions /// by feature, labels and their expressions by feature, the data design, diagrams, the /// extrusion's height and base, the marker rotation), or refuses while the definition query, a @@ -2650,6 +2680,76 @@ mod tests { } } + /// A column renamed by `edit.fieldAlias` shows its alias while the field keeps its name, on a + /// layer and a standalone table; an empty alias, null or the field's own name shows the name + /// again; Undo and Redo take it back and forth; it is saved with the project; and a bad call + /// changes nothing. + #[test] + fn a_renamed_column_keeps_its_field_name() { + for table in [false, true] { + let mut s = Session::new(crate::Project::default()); + let fields = + vec![Field::new("pop", FieldType::Integer), Field::new("Name", FieldType::Text), Field::new("name", FieldType::Text)]; + let mut ds = Dataset::new("towns", GeometryType::None, fields); + ds.push(None, vec![Value::Int(5), Value::Text("a".into()), Value::Text("b".into())]); + let target = if table { json!({"table": s.project.add_table(ds)}) } else { json!({"layer": s.map_mut().add_dataset(ds)}) }; + let t = super::target(&s, &target).unwrap(); + let with = |extra: Json| { + let mut p = target.clone(); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let shown = |s: &Session| -> Vec { data(s, t).unwrap().fields.iter().map(|f| f.display().to_string()).collect() }; + let names = |s: &Session| -> Vec { data(s, t).unwrap().fields.iter().map(|f| f.name.clone()).collect() }; + + let answer = s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": " Population "}))).unwrap(); + assert_eq!(answer, json!({"field": "pop", "alias": "Population"}), "table {table}"); + assert_eq!(shown(&s), ["Population", "Name", "name"], "table {table}"); + assert_eq!(names(&s), ["pop", "Name", "name"], "table {table}"); + + // Saved with the project, and read back. + let saved = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap(); + let reopened = match t { + Target::Layer(id) => saved.maps[0].layer(id).map(|l| l.dataset.fields[0].display().to_string()), + Target::Table(i) => saved.tables.get(i).map(|t| t.dataset.fields[0].display().to_string()), + }; + assert_eq!(reopened.as_deref(), Some("Population"), "table {table}"); + + // Undo shows the name again; Redo the alias. + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(shown(&s), ["pop", "Name", "name"], "undo, table {table}"); + s.run("edit.redo", &json!({})).unwrap(); + assert_eq!(shown(&s), ["Population", "Name", "name"], "redo, table {table}"); + + // An empty alias, null, a missing alias or the field's own name clears it. + for clear in [json!({"alias": " "}), json!({"alias": null}), json!({}), json!({"alias": "pop"})] { + s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": "Population"}))).unwrap(); + let mut p = with(clear.clone()); + p["field"] = json!("pop"); + s.run("edit.fieldAlias", &p).unwrap(); + assert_eq!(data(&s, t).unwrap().fields[0].alias, None, "{clear}, table {table}"); + } + + // The exact case twin is renamed; one matching neither exactly, an unknown field, an + // alias that isn't text or one too long are refused, changing nothing. + s.run("edit.fieldAlias", &with(json!({"field": "name", "alias": "Second"}))).unwrap(); + assert_eq!(shown(&s), ["pop", "Name", "Second"], "twin, table {table}"); + for bad in [ + json!({"field": "NAME", "alias": "X"}), + json!({"field": "nothing", "alias": "X"}), + json!({"field": "pop", "alias": 5}), + json!({"field": "pop", "alias": "x".repeat(ALIAS_MAX + 1)}), + json!({"alias": "X"}), + ] { + assert!(s.run("edit.fieldAlias", &with(bad.clone())).is_err(), "{bad}, table {table}"); + assert_eq!(shown(&s), ["pop", "Name", "Second"], "{bad}, table {table}"); + } + s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": "é".repeat(ALIAS_MAX)}))).unwrap(); + } + } + /// Converting and calculating geometry into a field named the same as another but for case /// work on the field named; the design guard follows the field design applies to; and design /// is refused on twins, which it couldn't tell apart (#1955). diff --git a/crates/engine/src/cmd/repair.rs b/crates/engine/src/cmd/repair.rs index 64d80bfb00..a581983fba 100644 --- a/crates/engine/src/cmd/repair.rs +++ b/crates/engine/src/cmd/repair.rs @@ -394,6 +394,7 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> { l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(dataset.geometry_type, seed)); } dataset.name.clone_from(&l.dataset.name); + rustgis_data::Field::keep_aliases(&mut dataset.fields, &l.dataset.fields); l.dataset = dataset; l.touch_replacement(); l.gpkg = Some(edit); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6e89ff2c04..c480f70f22 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -585,7 +585,8 @@ impl Layer { }) } - /// Installs a fresh source, retaining styling except an untouched no-geometry default. + /// Installs a fresh source, retaining styling except an untouched no-geometry default, and + /// the aliases of columns the new source still has ([`rustgis_data::Field::keep_aliases`]). /// Clears feature-specific state whose ids may identify different features, returning the /// number of saved label moves reset for a notice. pub fn replace_source(&mut self, mut src: source::SourceLayer) -> usize { @@ -603,7 +604,9 @@ impl Layer { self.renderer = Renderer::Single(Symbol::default_for(info.geometry_type, seed)); } self.dataset.geometry_type = info.geometry_type; - self.dataset.fields = info.fields.clone(); + let mut fields = info.fields.clone(); + rustgis_data::Field::keep_aliases(&mut fields, &self.dataset.fields); + self.dataset.fields = fields; self.dataset.crs = info.coordinate_system(); // The new source's Z and M, which reading it drops (see `Dataset::zm_dropped`). self.dataset.zm_dropped = info.zm_dropped; diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index 3afee6024c..62fc2c69a4 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -28,7 +28,9 @@ pub struct TableState { sort_schema: Option<(ViewKey, Vec)>, selected_only: bool, editing: Option, - /// The pass the cell editor last had the focus in (see [`had_focus`]). + /// The column header being renamed (Rename Column…), typed in where its name is shown. + renaming: Option, + /// The pass the cell editor or the rename box last had the focus in (see [`had_focus`]). focus_pass: Option, filter: String, /// The sorted or filtered row indices for the table on screen. @@ -192,6 +194,7 @@ pub(crate) fn prune_views(app: &mut RustGisApp) { app.table.views.clear(); app.table.stats = None; app.table.editing = None; + app.table.renaming = None; app.table.sort = None; app.table.sort_schema = None; app.table.row_order = None; @@ -209,18 +212,31 @@ pub(crate) fn prune_views(app: &mut RustGisApp) { app.table.views.retain(|key, view| fields_for(*key).map(|fields| view.repair(fields)).is_some()); if let Some((key, schema)) = &app.table.sort_schema { let current = fields_for(*key); - if current.is_none_or(|fields| fields != schema) { + if current.is_none_or(|fields| !same_columns(fields, schema)) { let key = *key; app.table.sort = None; app.table.sort_schema = current.map(|fields| (key, fields.clone())); } } if app.table.editing.as_ref().is_some_and(|edit| { - fields_for(edit.view).is_none_or(|fields| fields != &edit.schema) + // By the columns alone: a column renamed (its alias) keeps the draft typed in it. + fields_for(edit.view).is_none_or(|fields| !same_columns(fields, &edit.schema)) || matches!(edit.view, ViewKey::Table(id) if project.table(id).is_none_or(|t| Some(t.instance_id()) != edit.table_instance)) }) { app.table.editing = None; } + // The column being renamed is gone, or another field took its place. + if app.table.renaming.as_ref().is_some_and(|r| fields_for(r.view).and_then(|fields| fields.get(r.col)).is_none_or(|f| f.name != r.name)) + { + app.table.renaming = None; + } +} + +/// Whether two schemas have the same columns: the same fields, of the same types, in the same +/// order. An alias is only the name a column is shown by, so renaming a column (Rename Column…) +/// keeps the rows sorted by it. +fn same_columns(a: &[Field], b: &[Field]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.name == b.name && a.ty == b.ty) } #[cfg(test)] @@ -346,6 +362,18 @@ pub fn had_focus(st: &TableState, pass: u64) -> bool { st.focus_pass.is_some_and(|p| p + 1 == pass) } +/// A column's new display name being typed into its header (Rename Column…), set with +/// `edit.fieldAlias`: Enter or a click elsewhere keeps it, Escape leaves the column as it was. +struct ColumnRename { + view: ViewKey, + col: usize, + /// The field's name, which the command finds it by. + name: String, + text: String, + /// Whether the box still has to take the focus (on the frame it first shows). + focus: bool, +} + /// A value being typed into a cell. struct CellEdit { /// The layer or table the view showed: shown another (Ctrl+T), the edit is dropped. @@ -423,7 +451,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } }, }; - if app.table.sort_schema.as_ref().is_none_or(|(view, fields)| *view != key || *fields != ds.fields) { + if app.table.sort_schema.as_ref().is_none_or(|(view, fields)| *view != key || !same_columns(fields, &ds.fields)) { app.table.sort = None; app.table.sort_schema = Some((key, ds.fields.clone())); } @@ -563,6 +591,10 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let mut statistics: Option = None; // A field to delete. let mut delete_field: Option = None; + // A column to start renaming; and the rename box closed: with the field and the name + // typed, or `None` when Escape left it as it was. + let mut rename_column: Option = None; + let mut renamed: Option> = None; // A cell double-clicked in a column whose name finds another field. let mut by_other_name = false; // The row right-clicked, or whose menu is open. @@ -593,6 +625,31 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { h.col(|ui| { reveal_column(ui, Some(i)); let Some(fd) = ds.fields.get(i) else { return }; + if let Some(r) = app.table.renaming.as_mut().filter(|r| r.view == key && r.col == i) { + // Hinted with the field's name (a screen reader says what it renames). + let mut edit = egui::TextEdit::singleline(&mut r.text) + .hint_text(fd.name.as_str()) + .font(semibold(11.5)) + .desired_width(f32::INFINITY) + .show(ui); + // Opened with the name selected, so typing replaces it. + if std::mem::take(&mut r.focus) { + edit.response.response.request_focus(); + let end = edit.galley.text().chars().count(); + let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(end)); + edit.state.cursor.set_char_range(Some(all)); + edit.state.store(ui.ctx(), edit.response.id); + } + let te = edit.response.response; + if te.has_focus() { + app.table.focus_pass = Some(pass); + } + if te.lost_focus() { + let escaped = ui.input(|i| i.key_pressed(egui::Key::Escape)); + renamed = Some((!escaped).then(|| (r.name.clone(), r.text.clone()))); + } + return; + } let arrow = match app.table.sort { Some((c, true)) if c == i => " ↑", Some((c, false)) if c == i => " ↓", @@ -602,10 +659,17 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { egui::Label::new(egui::RichText::new(format!("{}{arrow}", fd.display())).font(semibold(11.5))) .sense(Sense::click()), ); - let r = r.on_hover_text(crate::i18n::fmt( - "{field} ({type}) · click to sort, right-click for columns", - &[("field", &fd.name), ("type", tl_raw!(fd.ty.label()))], - )); + let r = r.on_hover_text(match &fd.alias { + // The field's own name, which expressions read it by. + Some(alias) => crate::i18n::fmt( + "{alias}: field {field} ({type}) · click to sort, right-click for columns", + &[("alias", alias), ("field", &fd.name), ("type", tl_raw!(fd.ty.label()))], + ), + None => crate::i18n::fmt( + "{field} ({type}) · click to sort, right-click for columns", + &[("field", &fd.name), ("type", tl_raw!(fd.ty.label()))], + ), + }); if r.clicked() { sort_click = Some(i); } @@ -623,6 +687,16 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { column_action = Some((i, ColumnAction::Right)); ui.close(); } + // Found by the field's name, as Convert and Delete are. + if ui + .add_enabled(ds.field_index(&fd.name) == Some(i), egui::Button::new(tl!("Rename Column…"))) + .on_hover_text(tl!("Show the column by another name; the field keeps its own.")) + .on_disabled_hover_text(shadowed()) + .clicked() + { + rename_column = Some(i); + ui.close(); + } ui.separator(); if ui.add_enabled(hidden_n > 0, egui::Button::new(tl!("Show All Columns"))).clicked() { show_all = true; @@ -842,6 +916,15 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { // Only the dialog's background scan takes a copy, and only when it opens. let convert = convert.and_then(|(i, ty)| field_name(i).map(|name| (i, ty, name, (!streamed).then(|| ds.clone())))); let delete_field = delete_field.and_then(field_name); + let rename_column = rename_column.and_then(|i| ds.fields.get(i).map(|fd| (i, fd.name.clone(), fd.display().to_string()))); + // A rename kept with the column shown as it was runs nothing: no Undo step for it. + let rename = renamed.map(|kept| { + kept.filter(|(name, text)| { + // Left empty, the column is shown by the field's name. + let wanted = Some(text.trim()).filter(|t| !t.is_empty()).unwrap_or(name.as_str()); + ds.fields.iter().find(|f| f.name == *name).is_some_and(|f| f.display() != wanted) + }) + }); let clicked = clicked.filter(|_| is_layer).map(|(r, add)| { let mode = if add { if selection.contains(&r) { "remove" } else { "add" } } else { "new" }; (r, mode) @@ -875,6 +958,22 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { if by_other_name { app.session.notify(shadowed().to_string(), true); } + if let Some(rename) = rename { + app.table.renaming = None; + if let Some((name, text)) = rename { + // Refused (an alias too long): said, unless the command said so. + let mark = app.session.notice_mark(); + if let Err(e) = app.run("edit.fieldAlias", target(json!({"field": name, "alias": text}))) + && app.session.notices_since(mark).is_empty() + { + app.session.notify(e, true); + } + } + } + if let Some((col, name, text)) = rename_column { + app.table.editing = None; + app.table.renaming = Some(ColumnRename { view: key, col, name, text, focus: true }); + } if let Some(name) = delete_field { // Refused (a definition query reading it): said, unless the command said so. let mark = app.session.notice_mark(); @@ -2145,6 +2244,86 @@ mod tests { } } + /// Rename Column… in a header's menu opens its name for typing: Enter shows the column by the + /// new name, the field and the sort by it kept; Undo shows the field's name again; Escape and + /// a rename left as it was change nothing and leave no Undo step. + #[test] + fn renaming_a_column_from_its_menu() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let added = app.run("layer.addDataText", json!({"fileName": "columns.csv", "text": "alpha,beta\n1,8\n2,7\n"})).unwrap(); + app.session.table_standalone = Some(added["id"].as_u64().unwrap() as u32); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1000.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + app.logic(&ui.ctx().clone()); + show(app, ui); + }, + app, + ); + let field = |h: &egui_kittest::Harness| h.state().session.project.tables[0].dataset.fields[0].clone(); + let undo_steps = |h: &egui_kittest::Harness| h.state().session.undo_depth(); + h.run_steps(4); + h.state_mut().table.sort = Some((0, false)); + h.run_steps(2); + let before = undo_steps(&h); + + // Escape: typed, then left as it was. + h.get_by_label("alpha ↓").click_secondary(); + h.run_steps(2); + h.get_by_label("Rename Column…").click(); + h.run_steps(2); + assert!(h.state().table.renaming.is_some(), "the header opened for typing"); + h.event(egui::Event::Text("Nope".into())); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().table.renaming.is_none()); + assert_eq!(field(&h).alias, None); + // Kept as it was: nothing runs. + h.get_by_label("alpha ↓").click_secondary(); + h.run_steps(2); + h.get_by_label("Rename Column…").click(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(field(&h).alias, None); + assert_eq!(undo_steps(&h), before, "no Undo step for a rename that changed nothing"); + + // Typing replaces the name, which was selected; Enter keeps it. + h.get_by_label("alpha ↓").click_secondary(); + h.run_steps(2); + h.get_by_label("Rename Column…").click(); + h.run_steps(2); + h.event(egui::Event::Text("Alpha count".into())); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().table.renaming.is_none()); + assert_eq!((field(&h).name.as_str(), field(&h).alias.as_deref()), ("alpha", Some("Alpha count"))); + assert_eq!(h.state().table.sort, Some((0, false)), "still sorted by the renamed column"); + h.get_by_label("Alpha count ↓"); + + // Undo shows the field's name again. + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(field(&h).alias, None); + h.get_by_label("alpha ↓"); + + // A value being typed in a cell stays through a rename (a script's, Undo's): the column + // is the same field. A field added after it is another schema, and the draft goes. + let table = h.state().session.project.tables[0].id; + let (fid, schema, instance) = { + let t = &h.state().session.project.tables[0]; + (t.dataset.features.row(0).unwrap().id(), t.dataset.fields.clone(), Some(t.instance_id())) + }; + h.state_mut().table.editing = Some(CellEdit::new(ViewKey::Table(table), fid, 1, "draft".into(), &schema, instance)); + h.state_mut().run("edit.fieldAlias", json!({"table": table, "field": "beta", "alias": "Beta"})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().table.editing.as_ref().map(|e| e.text.as_str()), Some("draft"), "kept through a rename"); + h.state_mut().run("edit.addField", json!({"table": table, "name": "gamma", "type": "text"})).unwrap(); + h.run_steps(2); + assert!(h.state().table.editing.is_none(), "dropped when the fields change"); + } + /// Typing into a cell of a reordered table, with a column hidden before it, writes the field /// shown there, not the one at that position in the dataset. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 075158fbaa..56e46821db 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -64,6 +64,13 @@ map are unchanged. The toolbar says how many columns are hidden, and clicking it Hiding the column the rows are sorted by clears the sort. The order and hidden columns are kept per table until another project is opened, and are not saved in the project. +**Rename Column…** in the same menu opens the column's name for typing: press Enter to show the +column by the new name, or Escape to leave it as it was. Only the name shown changes (the field's +alias): expressions, symbology, labels and exported files still use the field's own name, which +the header's tooltip gives. Clear the name and press Enter to show the field's name again. A +renamed column is saved with the project and kept when Reload Data reads the layer again, and +Undo takes the rename back. Scripts and the Assistant rename a column with `edit.fieldAlias`. + **Statistics…** in the same menu shows the count, sum, mean, minimum, maximum and standard deviation of a number column in a small window, without making a table. With **Selected only** on it covers the selected rows, otherwise every row; the window says which. Empty values are counted