DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Convert Text to Table: resolved separators, the count as given, Insert's column limit
moppeeer713579a7b8bf
diff --cc crates/doc/src/table.rsindex c1b57d310,d80b1d475..a7101a052--- a/crates/doc/src/table.rs+++ b/crates/doc/src/table.rs@@@ -417,12 -417,12 +417,15 @@@ impl Tablepub fn from_strings(id: u64, data: &[Vec<String>], width: f64, para: &ParaFormat, fmt: &CharFormat) -> Table {let cols = data.iter().map(Vec::len).max().unwrap_or(1).max(1);let mut t = Table::new(id, data.len().max(1), cols, 0, 0, width);-- for (r, row) in data.iter().enumerate() {-- for (c, s) in row.iter().enumerate() {++ // Every cell takes the text's format, the padding of a short row too.++ for r in 0..t.nrows() {++ for c in 0..t.ncols() {let Some(cell) = t.cell_mut(r, c) else { continue };cell.text = Story::with_text(StoryId(0), "", ParaFormat { table: None, ..para.clone() });cell.text.chars[0].format = fmt.clone();-- cell.text.insert(0, s);++ if let Some(s) = data.get(r).and_then(|row| row.get(c)) {++ cell.text.insert(0, s);++ }}}t@@@ -1324,6 -1319,6 +1327,19 @@@ mod testsassert_eq!(right.selected_owners(CellRange::new(1, 0, 1, 1)), vec![(0, 1), (1, 0)], "owner order, not encounter order");}++ /// A short last row's padding cells take the converted text's paragraph and character format,++ /// like the cells with text.++ #[test]++ fn from_strings_formats_the_padding_cells_too() {++ let data = vec![vec!["a".to_string(), "b".to_string()], vec!["c".to_string()]];++ let para = ParaFormat { style: "Body".into(), ..Default::default() };++ let fmt = CharFormat { style: "Strong".into(), ..Default::default() };++ let t = Table::from_strings(1, &data, 200.0, ¶, &fmt);++ let pad = &t.cell(1, 1).unwrap().text;++ assert_eq!((pad.paras[0].style.as_str(), pad.chars[0].format.style.as_str()), ("Body", "Strong"));++ assert_eq!(pad.text, "");++ }++#[test]fn insert_table_gets_own_paragraph() {let mut s = story("before after");diff --cc crates/engine/src/cmd/table.rsindex b63cd5d22,270f8bcaa..542e428c6--- a/crates/engine/src/cmd/table.rs+++ b/crates/engine/src/cmd/table.rs@@@ -99,7 -99,7 +99,7 @@@ fn table_specs() -> Vec<CommandSpec>"Convert Text to Table",["Table"],None,- "{columnSeparator?: tab|comma|paragraph|text (tab), rowSeparator?: paragraph|tab|comma|text (paragraph), columns?: number of columns when both separators are the same (1), tableStyle?: name, width?: table width (default: the column)} — the selected paragraphs become a table, as InDesign's Convert Text to Table",- "{columnSeparator?: tab|comma, width?: table width (default: the column)} — selected paragraphs become rows",++ "{columnSeparator?: tab|comma|paragraph|text (tab), rowSeparator?: paragraph|tab|comma|text (paragraph), columns?: number of columns when both separators are the same (1, at most 200), tableStyle?: name, width?: table width (default: the column)} — the selected paragraphs become a table, as InDesign's Convert Text to Table; the words tab, comma and paragraph name those separators, any other text is the separator itself",has_text,convert_from_text),@@@ -620,40 -620,12 +620,41 @@@ 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- }++ Some(v) => v++ .as_u64()++ .filter(|n| (1..=MAX_COLUMNS).contains(n))++ .ok_or_else(|| bad(ID, format!("`columns` must be a whole number from 1 to {MAX_COLUMNS}")))? as usize,+ };+ 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.rsindex 9aac27c52,c34b18506..cb2519e1e--- a/crates/engine/src/tests_table.rs+++ b/crates/engine/src/tests_table.rs@@@ -464,56 -464,6 +464,62 @@@ 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");++ // A short last row: its padding cell takes the text's format too.++ let r = convert(&mut s, "a\nb\nc", json!({"columnSeparator": "paragraph", "rowSeparator": "paragraph", "columns": 2})).unwrap();++ let t = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().tables[&r["table"].as_u64().unwrap()].clone();++ let fmt = |c: usize| t.cell(1, c).unwrap().text.chars[0].format.clone();++ assert_eq!(fmt(1), fmt(0), "the padding cell's format is the text's");+ for bad in [+ json!({"columnSeparator": ""}),+ json!({"rowSeparator": 3}),+ json!({"columns": 0}),++ json!({"columns": crate::cmd::table::MAX_COLUMNS + 1}),+ 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.rsindex b2e3bd714,0d201619d..71f515bee--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -139,75 -137,11 +139,97 @@@ fn text_field(ui: &mut egui::Ui, d: &mu}}+/// Separators the Convert dialogs offer by name; anything else typed in the field is the+/// separator's own characters.+const SEPARATORS: [(&str, &str); 3] = [("tab", "Tab"), ("comma", "Comma"), ("paragraph", "Paragraph")];+++/// The characters a separator field stands for (`table.convertFromText` resolves it the same++/// way), so "comma" and a typed "," are the same separator.++fn resolved_separator(v: &str) -> &str {++ match v {++ "tab" => "\t",++ "comma" => ",",++ "paragraph" => "\n",++ other => other,++ }++}++++/// Whether the Convert dialog's two separators are the same (Number of Columns then applies).++fn same_separators(d: &Dialog) -> bool {++ resolved_separator(&d.s("columnSeparator")) == resolved_separator(&d.s("rowSeparator"))++}+++/// A separator field, as InDesign's: type any characters, or pick Tab, Comma or Paragraph from+/// its menu. Stored as `tab`/`comma`/`paragraph` or the typed text.+fn separator_field(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str) {+ let cur = d.s(key);+ let name = |v: &str| SEPARATORS.iter().find(|s| s.0 == v).map(|s| crate::i18n::tr(lang, s.1).to_string());+ let mut shown = name(&cur).unwrap_or_else(|| cur.clone());+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ if ui.add(egui::TextEdit::singleline(&mut shown).id_salt(("sep", key)).desired_width(150.0)).changed() {+ let v = SEPARATORS.iter().find(|s| crate::i18n::tr(lang, s.1) == shown).map_or(shown.clone(), |s| s.0.to_string());+ d.fields.insert(key.into(), json!(v));+ }+ ui.menu_button("▾", |ui| {+ for (v, label) in SEPARATORS {+ if ui.selectable_label(cur == v, crate::i18n::tr(lang, label)).clicked() {+ d.fields.insert(key.into(), json!(v));+ ui.close();+ }+ }+ });+ });+}++/// Table › Convert Text to Table and Convert Table to Text, laid out as InDesign's: Column and+/// Row Separator; converting text to a table also has Number of Columns (only when both+/// separators are the same: the cells then fill rows of that many) and Table Style.+fn convert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let lang = &app.ui.language;+ let to_table = d.id == "convertTextToTable";+ let label = |ui: &mut egui::Ui, text: &str, on: bool| {+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.add_enabled(on, egui::Label::new(crate::rtl::widget(ui, format!("{}:", crate::i18n::tr(lang, text)))));+ });+ };+ egui::Grid::new(("convert_table", to_table)).num_columns(2).min_col_width(120.0).spacing([8.0, 6.0]).show(ui, |ui| {+ label(ui, "Column Separator", true);+ separator_field(lang, ui, d, "columnSeparator");+ ui.end_row();+ label(ui, "Row Separator", true);+ separator_field(lang, ui, d, "rowSeparator");+ ui.end_row();+ if !to_table {+ return;+ }- let same = d.s("columnSeparator") == d.s("rowSeparator");++ let same = same_separators(d);+ label(ui, "Number of Columns", same);- let field = crate::widgets::NumField::number("columns", d.n("columns"), "", 0).width(70.0).range(1.0, 10_000.0).spinner().enabled(same);++ let max = designcraft_engine::cmd::table::MAX_COLUMNS as f64;++ let field = crate::widgets::NumField::number("columns", d.n("columns"), "", 0).width(70.0).range(1.0, max).spinner().enabled(same);+ if let Some(v) = field.show(ui) {+ d.fields.insert("columns".into(), json!(v.round()));+ }+ ui.end_row();+ label(ui, "Table Style", true);+ let names: Vec<String> = app.session.active().map(|st| st.doc.styles.table.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();- let cur = Some(d.s("tableStyle")).filter(|s| !s.is_empty()).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.to_string());++ let cur = table_style_field(d).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.to_string());+ egui::ComboBox::from_id_salt("convert_table_style").selected_text(&cur).width(170.0).show_ui(ui, |ui| {+ for n in &names {+ if ui.selectable_label(*n == cur, n).clicked() {+ d.fields.insert("tableStyle".into(), json!(n));+ }+ }+ });+ ui.end_row();+ });+}++ /// The dialog's chosen table style: none when unset, null or empty (a new table's [Basic Table]).+ fn table_style_field(d: &Dialog) -> Option<String> {+ d.fields.get("tableStyle").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string)+ }+/// Table › Insert Table, laid out as InDesign's: Table Dimensions (body rows and columns, then/// header and footer rows, each a number with a spinner, labels on the right edge of their/// column) and the Table Style to apply.@@@ -3210,25 -3139,6 +3232,25 @@@ pub fn confirm(app: &mut DesignApp) ->None => Err(format!("no page \"{typed}\"")),}}+ "convertTextToTable" | "convertTableToText" => {+ let r = if d.id == "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);++ let same = same_separators(&d);++ let style = table_style_field(&d).filter(|s| 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}),++ "columns": if same { d.fields.get("columns").cloned().unwrap_or(json!(1)) } else { Value::Null }, "tableStyle": style}),+ )+ } else {+ app.run("table.convertToText", json!({"columnSeparator": d.s("columnSeparator"), "rowSeparator": d.s("rowSeparator")}))+ };+ // On an error (an emptied separator field) the dialog stays open to be corrected.+ if let Err(e) = &r {+ app.status(e.clone());+ app.ui.dialog = Some(d);+ }+ r+ }"insertTable" => {// The table and its style in one step; a style that is gone leaves the document alone,// and the dialog stays open to be corrected.@@@ -9852,42 -9769,6 +9881,50 @@@ mod testsassert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string()));}+ /// 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"));++ // "comma" and a typed "," are the same separator, so Number of Columns applies; a count of++ // 0 is refused, not taken as 1, and the dialog stays open.++ ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": "comma"}));++ ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ","}));++ assert!(same_separators(app.ui.dialog.as_ref().unwrap()));++ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": 0}));++ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);++ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable"));+ // An emptied separator: the command refuses it and the dialog stays open, as typed.+ ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ""}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert_eq!(app.ui.dialog.as_ref().map(|d| (d.id.as_str(), d.s("rowSeparator"))), Some(("convertTextToTable", String::new())));+ 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();