DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #263: Paragraph Rules: a dialog for the selected paragraphs and a section in Paragraph Style Options
aiongge1cc16325a00
diff --cc ROADMAP.mdindex 30260d1d9,47435fb29..c065fe68f--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -49,7 -23,7 +49,8 @@@ DesignCraft aims at full Adobe InDesig- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).- Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.- Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.+- IDML1: embedded text frames and groups retain forward story references in body text, footnotes and table cells; anonymous composed stories retain anchored artwork for screen/PDF rendering. Filled compound outlines retain open contours; object-only inline lines use geometric extents, preflight distinguishes unplaced stories and locates embedded overflow at its page frame, and cyclic frame references are rejected.+ - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named.- Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.- Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands.- Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus.diff --cc crates/compose/src/lib.rsindex a6365309a,5c9cd2bc5..2eb94d21e--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1098,9 -939,17 +1098,14 @@@ fn compose_with_db(doc: &Document, storif pp.rule_above.on {let r = &pp.rule_above;let y = bl - asc - r.offset;- let col = ft.lines.iter().rev().find(|l| l.para == pi).map(|l| (l.x0, l.x1)).unwrap_or((0.0, 0.0));+ let col = ft+ .lines+ .iter()+ .find(|l| l.para == pi && l.first_in_para)+ .map(|l| if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) })+ .unwrap_or((0.0, 0.0));- ft.decos.push(Deco {- rect: Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y),- color: r.color.clone(),- tint: r.tint,- });+ let (color, tint) = rule_color(r, &above);+ ft.decos.push(Deco { rect: Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y), color, tint });}}para_box_decos(&mut out, pi, &pp);diff --cc crates/engine/src/cmd/text.rsindex a428962fa,af98fe140..920c2de8c--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -138,7 -135,7 +138,7 @@@ pub fn specs() -> Vec<CommandSpec>"Paragraph Formatting",[],None,- "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?, composer?, tabs?, …}}",- "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, hyphenate?, composer?, tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",++ "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?, composer?, tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",has_text_or_frames,|s, p| format_paras(s, p.get("attrs").unwrap_or(p))),@@@ -888,41 -771,20 +888,44 @@@ pub(crate) fn format_chars(s: &mut Sess})}+/// Character attributes `a` (and the overrides `cleared` removed) over each target's text.+pub(crate) fn apply_char_attrs(d: &mut designcraft_doc::Document, targets: &[Target], a: &CharAttrs, cleared: &[String]) {+ for t in targets {+ let r = &t.range;+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };+ if r.is_empty() {+ // An empty story: its one (empty) run is the format typing takes.+ if st.is_empty()+ && let Some(run) = st.chars.first_mut()+ {+ run.format.over.merge(a);+ st.rev += 1;+ }+ continue;+ }+ st.format_chars(r.clone(), |f| {+ f.over.merge(a);+ for k in cleared {+ let _ = f.over.set_json(k, &Value::Null);+ }+ });+ }+}+pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {+ let empty = serde_json::Map::new();+ let obj = attrs.as_object().unwrap_or(&empty);+ // A rule object changes only the rule fields it names, so each paragraph gets its own attrs+ // over its resolved rule; this pass validates them.let mut a = ParaAttrs::default();- if let Some(o) = attrs.as_object() {- for (k, v) in o {- a.set_json(k, v).map_err(|e| bad("type.para", e))?;- }+ for (k, v) in obj {+ a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?;}// `null` removes the override (back to the style's value).- let cleared: Vec<String> = attrs.as_object().map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect()).unwrap_or_default();+ let cleared: Vec<String> = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect();let targets = format_targets(s);s.edit(|d, _| {+ let styles = d.styles.clone();for t in &targets {if let Some(st) = d.text_story_mut(t.story, t.cell) {st.format_paras(t.range.clone(), |p| {diff --cc crates/ui-egui/src/dialogs.rsindex 7b0e0b17f,0665288f8..a671fa21d--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -815,8 -813,8 +815,9 @@@ pub fn show(app: &mut DesignApp, ctx: &"documentSetup" => crate::i18n::tr(&app.ui.language, "Document Setup"),"findChange" => crate::i18n::tr(&app.ui.language, "Find/Change"),"paragraphStyleOptions" => crate::i18n::tr(&app.ui.language, "Paragraph Style Options"),+ "characterStyleOptions" => crate::i18n::tr(&app.ui.language, "Character Style Options"),"footnoteOptions" => crate::i18n::tr(&app.ui.language, "Footnote Options"),+ "paragraphRules" => crate::i18n::tr(&app.ui.language, "Paragraph Rules"),"insertXref" => crate::i18n::tr(&app.ui.language, "New Cross-Reference"),"findFont" => crate::i18n::tr(&app.ui.language, "Find/Replace Font"),"polygonSettings" => crate::i18n::tr(&app.ui.language, "Polygon Settings"),@@@ -1062,8 -1054,11 +1063,12 @@@}}"paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),+ "characterStyleOptions" => character_style_options(app, ui, &mut d),"footnoteOptions" => footnote_options(app, ui, &mut d),+ "paragraphRules" => {+ let current = d.fields.get("current").cloned().unwrap_or_default();+ paragraph_rules(app, ui, &mut d, "", ¤t);+ }"insertXref" => insert_xref(app, ui, &mut d),"findFont" => find_font(app, ui, &mut d),"colorPicker" => color_picker(ui, &mut d),@@@ -1531,46 -1497,16 +1546,53 @@@ pub fn confirm(app: &mut DesignApp) ->}Ok(r)}+ "characterStyleOptions" => {+ let name = d.s("name");+ let mut chars = Map::new();+ for (k, v) in &d.fields {+ if let Some(a) = k.strip_prefix("c.") {+ chars.insert(a.into(), v.clone());+ }+ }+ let rename = d.s("rename").trim().to_string();+ let based = d.fields.get("basedOn").and_then(Value::as_str).map(str::to_string);+ let r = if d.b("new") {+ // A new style sets only what was filled in.+ chars.retain(|_, v| !v.is_null());+ let mut params = json!({"name": if rename.is_empty() { "Character Style 1" } else { rename.as_str() }, "chars": chars});+ if let Some(b) = based.filter(|b| b != designcraft_doc::NO_CHAR_STYLE) {+ params["basedOn"] = json!(b);+ }+ app.run("style.character.create", params)+ } else {+ let mut params = json!({"name": name, "chars": chars});+ if let Some(b) = based {+ params["basedOn"] = if b == designcraft_doc::NO_CHAR_STYLE { Value::Null } else { json!(b) };+ }+ if !rename.is_empty() && rename != name {+ params["rename"] = json!(rename);+ }+ app.run("style.character.edit", params)+ };+ if let Err(e) = &r {+ // Keep the dialog open with the reason (a taken name, a based-on loop).+ let mut d = d.clone();+ d.fields.insert("status".into(), json!(e));+ d.fields.insert("section".into(), json!("general"));+ app.ui.dialog = Some(d);+ }+ r+ }+ "paragraphRules" => {+ let attrs = rule_edits(&d, "");+ if attrs.is_empty() {+ return Ok(Value::Null);+ }+ app.run("type.para", json!({"attrs": attrs}))+ }"colorPicker" => {let hex = d.s("hex");- app.run("object.color", json!({"color": hex, "target": d.s("target")}))+ app.run("object.color", json!({"color": hex, "target": d.s("target"), "text": d.b("text")}))}"layerOptions" => {let hidden: Vec<Value> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect()).unwrap_or_default();@@@ -3331,73 -2803,79 +3480,146 @@@ fn find_font(app: &mut DesignApp, ui: &mod tests {use super::*;+ fn command_app(id: &str, fields: Value) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));+ app+ }++ #[test]+ fn generic_new_document_preserves_typed_values_and_text_entry() {+ for pages in [json!(2), json!(" 2 ")] {+ let mut app = command_app(+ "file.new",+ json!({+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},+ "title": " ", "status": "internal", "primaryTextFrame": true+ }),+ );+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.page_count(), 2);+ assert!(!doc.settings.facing_pages);+ assert!(doc.title.starts_with("Untitled-"));+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {+ assert!((page.width - 595.2755905511812).abs() < 0.01);+ assert!((page.height - 841.8897637795277).abs() < 0.01);+ assert_eq!(page.columns.gutter, 0.0);+ assert_eq!(page.margins.top, 10.0);+ assert_eq!(page.margins.outside, 40.0);+ }+ assert!(doc.spreads.iter().all(|s| s.items.is_empty()), "undocumented fields stay excluded");+ assert!(app.ui.dialog.is_none());+ }+ }++ #[test]+ fn generic_command_preserves_array_geometry() {+ let mut app = command_app("file.new", json!({}));+ confirm(&mut app).unwrap();+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));+ }++ #[test]+ fn generic_explicit_null_uses_the_commands_existing_semantics() {+ // file.new accepts null width by using the selected preset's width.+ for width in [Value::Null, json!("null")] {+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.title, "Sample layout");+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);+ }+ }++ #[test]+ fn generic_invalid_number_retains_dialog_without_creating_document() {+ let mut app = command_app("file.new", json!({"width": 0}));+ assert!(confirm(&mut app).is_err());+ assert!(app.session.active().is_none());+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.fields["width"], 0);+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));+ }++ fn draw(app: &mut DesignApp, ctx: &egui::Context) {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }++ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".+ fn ruled_paragraph() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();+ (app, rule)+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())+ }++ #[test]+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "paragraphRules");+ let current = d.fields["current"].clone();+ assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule");+ assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false);+ // Pick a colour, as the Color menu does.+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["color"] = json!("[Registration]");+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);+ }++ #[test]+ fn paragraph_style_options_edit_one_rule_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ draw(&mut app, &ctx);+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["weight"] = json!(1.5);+ assert_eq!(resolved(&app)["ruleBelow"], want);+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(resolved(&app)["ruleBelow"], rule);+ }+#[test]fn parses_command_params() {let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates");