Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge branch 'table-menu-insert' into table-convert-dialogs

moppeeerbc7e4bb0c658
diff --cc crates/engine/src/cmd/table.rs
index 9b6e551a9,be6dab3bb..b75881722
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@@ -594,49 -620,12 +620,40 @@@ fn insert(s: &mut Session, p: &Value) -
})
}
+/// A Convert Text to Table / Convert Table to Text separator: `tab`, `comma`, `paragraph` or the
+/// separator's own text (InDesign's fields take any characters).
+fn separator(p: &Value, key: &str, default: &str, cmd: &str) -> Result<String> {
+ let sep = match p.get(key) {
+ None | Some(Value::Null) => return Ok(default.to_string()),
+ Some(Value::String(s)) => match s.as_str() {
+ "tab" => "\t",
+ "comma" => ",",
+ "paragraph" => "\n",
+ other => other,
+ },
+ Some(_) => "",
+ };
+ if sep.is_empty() {
+ return Err(bad(cmd, format!("`{key}` must be tab, comma, paragraph or the separator's characters")));
+ }
+ Ok(sep.to_string())
+}
+
fn convert_from_text(s: &mut Session, p: &Value) -> Result<Value> {
- let t = s.doc()?.selection.text.ok_or_else(|| bad("table.convertFromText", "no text selected"))?;
+ const ID: &str = "table.convertFromText";
+ let t = s.doc()?.selection.text.ok_or_else(|| bad(ID, "no text selected"))?;
if t.cell.is_some() {
- return Err(bad("table.convertFromText", "select text outside tables"));
+ return Err(bad(ID, "select text outside tables"));
}
- let sep = if str_param(p, "columnSeparator") == Some("comma") { ',' } else { '\t' };
+ let (col_sep, row_sep) = (separator(p, "columnSeparator", "\t", ID)?, separator(p, "rowSeparator", "\n", ID)?);
+ // With one separator for both, InDesign fills rows of Number of Columns cells.
+ let per_row = match p.get("columns") {
+ None | Some(Value::Null) => 1,
+ Some(v) => {
+ v.as_u64().filter(|n| (1..=10_000).contains(n)).ok_or_else(|| bad(ID, "`columns` must be a whole number from 1 to 10000"))? as usize
+ }
+ };
- let style = match str_param(p, "tableStyle").filter(|n| *n != designcraft_doc::BASIC_TABLE) {
- Some(name) => {
- let styles = &s.doc()?.doc.styles;
- if !styles.table.iter().any(|x| x.name == name) {
- return Err(bad(ID, format!("no table style `{name}`")));
- }
- Some((styles.resolve_table_style(name), styles.cell.clone()))
- }
- None => None,
- };
++ let style = table_style_param(s, p, ID)?;
let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t));
s.edit(|d, sel| {
let id = d.alloc();
diff --cc crates/engine/src/tests_table.rs
index 8c5c98e76,a2a9cd824..844d47298
--- a/crates/engine/src/tests_table.rs
+++ b/crates/engine/src/tests_table.rs
@@@ -444,50 -464,6 +464,50 @@@ fn convert_text_to_table_and_back()
assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "Ink\tCoverage\nPlum\t80%\nSunset\t45%\nAfter");
}
+/// InDesign's Convert Text to Table and Convert Table to Text separators: tab, comma, paragraph or
+/// any characters; with one separator for both, rows of Number of Columns cells; a Table Style.
+#[test]
+fn convert_text_to_table_with_indesigns_separators() {
+ let (mut s, sid, _) = session_with_frame();
+ let convert = |s: &mut Session, text: &str, p: Value| -> Result<Value> {
+ s.execute("story.setText", &json!({"story": sid, "text": format!("{text}\nAfter")})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap();
+ s.execute("table.convertFromText", &p)
+ };
+ let cells = |s: &mut Session, r: &Value| -> (usize, Vec<String>) {
+ let t = s.execute("table.get", &json!({"table": r["table"]})).unwrap();
+ let texts = t["cells"].as_array().unwrap().iter().map(|c| c["text"].as_str().unwrap().to_string()).collect();
+ (t["columns"].as_array().unwrap().len(), texts)
+ };
+ // Comma-separated columns, paragraphs for rows.
+ let r = convert(&mut s, "Ink, Coverage\nPlum, 80%", json!({"columnSeparator": "comma"})).unwrap();
+ assert_eq!(cells(&mut s, &r), (2, vec!["Ink".into(), "Coverage".into(), "Plum".into(), "80%".into()]));
+ check(&s);
+ // The lesson's list: one paragraph per cell; with two columns, two cells a row.
+ let list = "Name:\nAddress:\nCity:\nState:";
+ let r = convert(&mut s, list, json!({"columnSeparator": "paragraph", "rowSeparator": "paragraph", "columns": 2})).unwrap();
+ assert_eq!(r["rows"], 2);
+ assert_eq!(cells(&mut s, &r).0, 2);
+ let r = convert(&mut s, list, json!({"columnSeparator": "tab"})).unwrap();
+ assert_eq!((r["rows"].as_u64(), cells(&mut s, &r).0), (Some(4), 1), "a column of paragraphs");
+ // Any characters separate: here " | " between columns and ";" between rows.
+ let r = convert(&mut s, "a | b;c | d", json!({"columnSeparator": " | ", "rowSeparator": ";"})).unwrap();
+ assert_eq!(cells(&mut s, &r), (2, vec!["a".into(), "b".into(), "c".into(), "d".into()]));
+ // A table style is applied to the new table.
+ s.execute("style.table.create", &json!({"name": "Grid"})).unwrap();
+ let r = convert(&mut s, "x\ty", json!({"tableStyle": "Grid"})).unwrap();
+ assert_eq!(s.execute("table.get", &json!({"table": r["table"]})).unwrap()["style"], "Grid");
- for bad in [json!({"columnSeparator": ""}), json!({"rowSeparator": 3}), json!({"columns": 0}), json!({"tableStyle": "Missing"})] {
++ for bad in [json!({"columnSeparator": ""}), json!({"rowSeparator": 3}), json!({"columns": 0}), json!({"tableStyle": "Missing"}), json!({"tableStyle": 123})] {
+ assert!(convert(&mut s, "p\tq", bad.clone()).is_err(), "{bad}");
+ }
+ check(&s);
+ // Back to text with a comma between columns and a tab between rows.
+ let r = convert(&mut s, "Plum\t80%\nSunset\t45%", json!({})).unwrap();
+ s.execute("table.convertToText", &json!({"table": r["table"], "columnSeparator": "comma", "rowSeparator": "tab"})).unwrap();
+ check(&s);
+ assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "Plum,80%\tSunset,45%\nAfter");
+}
+
#[test]
fn caret_placement_in_cells_and_cell_formatting() {
let (mut s, sid, fid) = session_with_frame();
diff --cc crates/ui-egui/src/dialogs.rs
index ee462ea48,b23287579..2fa40794f
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -2159,8 -2090,6 +2161,9 @@@ pub fn show(app: &mut DesignApp, ctx: &
"frameSize" => crate::i18n::tr(&app.ui.language, "Rectangle"),
"goToPage" => crate::i18n::tr(&app.ui.language, "Go to Page"),
"insertTable" => crate::i18n::tr(&app.ui.language, "Insert Table…").trim_end_matches('…').trim_end(),
- "convertTextToTable" => crate::i18n::tr(&app.ui.language, "Convert Text to Table"),
- "convertTableToText" => crate::i18n::tr(&app.ui.language, "Convert Table to Text"),
++ // The menu items' translations (every language has them), without the ellipsis.
++ "convertTextToTable" => crate::i18n::tr(&app.ui.language, "Convert Text to Table…").trim_end_matches('…').trim_end(),
++ "convertTableToText" => crate::i18n::tr(&app.ui.language, "Convert Table to Text…").trim_end_matches('…').trim_end(),
"cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"),
"createGuides" => crate::i18n::tr(&app.ui.language, "Create Guides"),
"marginsAndColumns" => crate::i18n::tr(&app.ui.language, "Margins and Columns"),
@@@ -3203,32 -3130,16 +3206,28 @@@ pub fn confirm(app: &mut DesignApp) ->
None => Err(format!("no page \"{typed}\"")),
}
}
+ "convertTextToTable" => {
+ let same = d.s("columnSeparator") == d.s("rowSeparator");
+ let style = Some(d.s("tableStyle")).filter(|s| !s.is_empty() && s != designcraft_doc::BASIC_TABLE);
+ app.run(
+ "table.convertFromText",
+ json!({"columnSeparator": d.s("columnSeparator"), "rowSeparator": d.s("rowSeparator"),
+ "columns": if same { json!(d.n("columns").unwrap_or(1.0).max(1.0) as u64) } else { Value::Null }, "tableStyle": style}),
+ )
+ }
+ "convertTableToText" => {
+ app.run("table.convertToText", json!({"columnSeparator": d.s("columnSeparator"), "rowSeparator": d.s("rowSeparator")}))
+ }
- "insertTable" => app
- .run(
+ "insertTable" => {
+ // The table and its style in one step; a style that is gone leaves the document alone.
+ let style = Some(d.s("tableStyle")).filter(|s| !s.is_empty());
+ app.run(
"table.insert",
json!({"rows": d.n("bodyRows").unwrap_or(4.0).max(1.0) as u64, "cols": d.n("columns").unwrap_or(4.0).max(1.0) as u64,
- "headerRows": d.n("headerRows").unwrap_or(0.0).max(0.0) as u64, "footerRows": d.n("footerRows").unwrap_or(0.0).max(0.0) as u64}),
+ "headerRows": d.n("headerRows").unwrap_or(0.0).max(0.0) as u64, "footerRows": d.n("footerRows").unwrap_or(0.0).max(0.0) as u64,
+ "tableStyle": style}),
)
- .and_then(|r| {
- // A table style other than [Basic Table] (which a new table has) is applied after.
- let style = d.s("tableStyle");
- if style.is_empty() || style == designcraft_doc::BASIC_TABLE {
- return Ok(r);
- }
- app.run("style.table.apply", json!({"name": style, "story": r["story"], "table": r["table"]})).map(|_| r)
- }),
+ }
"numberingSection" => {
// On an error the dialog stays open to be corrected.
let r = crate::section_options::confirm(app, &d);
@@@ -9751,41 -9662,19 +9750,51 @@@ mod tests
let len = |k: &str| t[k].as_array().map_or(0, Vec::len);
assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}");
assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}");
- }
+ // One Insert Table, one undo.
+ app.run("edit.undo", json!({})).unwrap();
+ assert!(app.run("table.get", json!({})).is_err(), "the table is gone");
+ }
+ // A style that no longer exists changes nothing.
+ let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::<usize>();
+ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();
+ app.run("app.insertTableDialog", json!({})).unwrap();
+ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);
+ assert_eq!(tables(&app), 0);
}
+ /// Convert Text to Table: available with text selected (not with a caret alone); its
+ /// separators and Number of Columns shape the table. Convert Table to Text takes it back with
+ /// the separators chosen there.
+ #[test]
+ fn convert_dialogs_use_their_separators() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let text = "Name:\nAddress:\nCity:\nState:";
+ let sid = app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text", "text": text})).unwrap()["story"].clone();
+ app.run("text.select", json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ assert!(!crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"), "a caret alone");
+ assert!(!crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"), "no table");
+ app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap();
+ assert!(crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"));
+ app.run("app.convertTextToTableDialog", json!({})).unwrap();
+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable"));
+ for (field, value) in [("columnSeparator", json!("paragraph")), ("rowSeparator", json!("paragraph")), ("columns", json!(2))] {
+ ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ let t = app.run("table.get", json!({})).unwrap();
+ let len = |k: &str| t[k].as_array().map_or(0, Vec::len);
+ assert_eq!((len("rows"), len("columns")), (2, 2), "{t}");
+ assert!(crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"));
+ app.run("app.convertTableToTextDialog", json!({})).unwrap();
+ ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": ", "}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ let story = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid.as_u64().unwrap())).unwrap().text.clone();
+ // (The empty paragraph after a table that ends its story stays after the text.)
+ assert_eq!(story.trim_end(), "Name:, Address:\nCity:, State:");
+ }
+
#[test]
fn character_style_options_set_exactly_the_edited_attributes() {
let mut app = styled_app();