Batch: Paste Name lists the names once, finds local names by hash and refuses a name it doesn't list (#2410)

This commit is contained in:
aiongg committed 2026-10-25 03:56:45 +00:00
1 parent 77b37df655
commit 87a649c763
4 files changed
+47 -23

No files matched your search

+11 -4
View File
@@ -60,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste Names…",
["Formulas", "Defined Names"],
Some("F3"),
"{name?: \"Sales\" (OK: puts the name at the caret of the cell being edited, or starts `=Sales` in the active cell), list?: true (Paste List: writes each name and what it refers to in two columns, from `at`), at?: cell (default the active cell)} → {names: [{name, refersTo}]}: the names the Paste Name dialog lists (workbook names and the active sheet's own, hidden names left out, in alphabetical order). With neither nothing changes; the menu opens the dialog.",
"{name?: \"Sales\" (one of the names listed; OK: puts the name at the caret of the cell being edited, or starts `=Sales` in the active cell), list?: true (Paste List: writes each name and what it refers to in two columns, from `at`), at?: cell (default the active cell)} → {names: [{name, refersTo}]}: the names the Paste Name dialog lists (workbook names and the active sheet's own, hidden names left out, in alphabetical order). With neither nothing changes; the menu opens the dialog.",
has_doc,
paste_name
),
@@ -525,10 +525,10 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
pub fn pasteable_names(wb: &Workbook) -> Vec<(String, String)> {
let sheet = wb.active_sheet;
let shown = |local: bool| wb.names.iter().filter(move |n| !n.hidden && n.scope.is_some() == local && n.scope.is_none_or(|i| i == sheet));
let local: Vec<&str> = shown(true).map(|n| n.name.as_str()).collect();
let local: std::collections::HashSet<String> = shown(true).map(|n| gridcraft_formula::fold_name(&n.name)).collect();
let mut out: Vec<(String, String)> = shown(true).map(|n| (n.name.clone(), format!("={}", n.formula))).collect();
for n in shown(false) {
if !local.iter().any(|x| gridcraft_formula::same_name(x, &n.name)) {
if !local.contains(&gridcraft_formula::fold_name(&n.name)) {
out.push((n.name.clone(), format!("={}", n.formula)));
}
}
@@ -542,7 +542,10 @@ fn paste_name(s: &mut Session, p: &Json) -> Result<Json> {
let listed: Vec<Json> = names.iter().map(|(n, r)| json!({"name": n, "refersTo": r})).collect();
if !bool_param(p, "list").unwrap_or(false) {
if let Some(name) = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
s.ui_requests.push(crate::UiRequest::InsertName(name.to_string()));
let Some((listed_name, _)) = names.iter().find(|(n, _)| gridcraft_formula::same_name(n, name)) else {
return Err(EngineError::Other(format!("There's no name \"{name}\" to paste.")));
};
s.ui_requests.push(crate::UiRequest::InsertName(listed_name.clone()));
}
return Ok(json!({"names": listed}));
}
@@ -993,6 +996,10 @@ mod tests {
s.execute("formulas.useInFormula", json!({"name": "rate"})).unwrap();
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::InsertName("Sales".into()), crate::UiRequest::InsertName("rate".into())]);
assert_eq!(text_at(&s, "A1"), Value::Empty, "the cell changes only when the edit is entered");
// A name Paste Name doesn't list is refused; one typed in another case is pasted as listed.
assert!(s.execute("formulas.pasteName", json!({"name": "NoSuchName"})).is_err());
s.execute("formulas.pasteName", json!({"name": "SALES"})).unwrap();
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::InsertName("Sales".into())]);
}
#[test]
+14 -12
View File
@@ -23,18 +23,20 @@ pub fn same_name(a: &str, b: &str) -> bool {
if a.is_ascii() && b.is_ascii() {
return a.eq_ignore_ascii_case(b);
}
let fold = |s: &str| -> String {
s.chars()
.flat_map(char::to_lowercase)
.flat_map(|c| match c {
'ß' => ['s', 's'].into_iter().take(2),
'ſ' => ['s', 's'].into_iter().take(1),
'ς' => ['σ', 'σ'].into_iter().take(1),
c => [c, c].into_iter().take(1),
})
.collect()
};
a == b || fold(a) == fold(b)
a == b || fold_name(a) == fold_name(b)
}
/// The case-folded form of a name: two names are [`same_name`] when their folded forms are equal.
pub fn fold_name(s: &str) -> String {
s.chars()
.flat_map(char::to_lowercase)
.flat_map(|c| match c {
'ß' => ['s', 's'].into_iter().take(2),
'ſ' => ['s', 's'].into_iter().take(1),
'ς' => ['σ', 'σ'].into_iter().take(1),
c => [c, c].into_iter().take(1),
})
.collect()
}
#[cfg(test)]
+4 -1
View File
@@ -847,6 +847,8 @@ impl Dialog {
// OK runs `formulas.pasteName` with the selected `name`, so `ui.dialog.confirm` does too.
let mut dialog = Dialog::custom("pasteName", "Paste Name", json!({"name": names.first()}));
dialog.command = Some("formulas.pasteName");
// Listed once, when the dialog opens.
dialog.result = Some(json!(names));
dialog
}
"manageRules" => Dialog::custom("manageRules", "Conditional Formatting Rules Manager", json!({})),
@@ -2557,7 +2559,8 @@ pub(crate) fn insert_name(app: &mut SheetApp, name: &str) {
/// selected name (`formulas.pasteName` with `name`); Paste List writes every name and what it
/// refers to from the active cell.
fn paste_name(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
let names = pasteable_names(app);
let names: Vec<String> =
d.result.as_ref().and_then(Json::as_array).map(|a| a.iter().filter_map(Json::as_str).map(str::to_owned).collect()).unwrap_or_default();
// The `name` value is the selection, so `ui.dialog.set` can choose one too.
if let Some(i) = d.values.get("name").and_then(Json::as_str).and_then(|n| names.iter().position(|x| x == n)) {
d.list_index = i;
+18 -6
View File
@@ -2086,12 +2086,24 @@ fn formulas(app: &mut SheetApp, ui: &mut Ui) {
anchor_keytip(app, ui, &use_in, &["dialog:pasteName"]);
egui::Popup::menu(&use_in).show(|ui| {
// The menu lists the names Paste Names lists; clicking one runs `formulas.useInFormula`, which puts it at the caret.
let names: Vec<String> = app
.session
.active()
.map(|d| gridcraft_engine::cmd::formulas::pasteable_names(&d.wb).into_iter().map(|(n, _)| n).collect())
.unwrap_or_default();
for n in &names {
// Listed when the menu opens, and again only after the workbook changes.
let cache = egui::Id::new("gridcraft.use_in_formula_names");
let key = app.session.active().map(|d| (d.uid, d.revision, d.wb.active_sheet));
let cached = ui.ctx().data(|m| m.get_temp::<(Option<(u64, u64, usize)>, std::sync::Arc<Vec<String>>)>(cache)).filter(|(k, _)| *k == key);
let names = match cached {
Some((_, names)) => names,
None => {
let names: std::sync::Arc<Vec<String>> = std::sync::Arc::new(
app.session
.active()
.map(|d| gridcraft_engine::cmd::formulas::pasteable_names(&d.wb).into_iter().map(|(n, _)| n).collect())
.unwrap_or_default(),
);
ui.ctx().data_mut(|m| m.insert_temp(cache, (key, names.clone())));
names
}
};
for n in names.iter() {
if ui.button(n).clicked() {
app.run_or_alert("formulas.useInFormula", json!({"name": n}));
}