DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
TUT4.3: redefine text styles from local formatting
moppeeer8fb944fe06ea
diff --git a/ROADMAP.md b/ROADMAP.mdindex d60a6bf49..e7ca95e7b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -343,6 +343,9 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m## Progress log+- **2026-10-15** · Redefine paragraph and character styles from local formatting, including the+ Styles panel context menu, global updates and one-step undo.+- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.Newest first.diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex 1cccc7fd1..41fefef16 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -1,5 +1,82 @@//! Paragraph / character styles and swatches.+#[cfg(test)]+mod redefine_tests {+ use super::*;++ fn sample() -> (Session, Value, Value) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"First header"})).unwrap();+ let b = s.execute("frame.create", &json!({"rect":[36,240,300,400],"content":"text","text":"Second header"})).unwrap();+ s.execute("style.paragraph.create", &json!({"name":"Header","chars":{"size":18,"fill":"[Paper]"}})).unwrap();+ for story in [&a["story"], &b["story"]] {+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();+ s.execute("style.paragraph.apply", &json!({"name":"Header"})).unwrap();+ }+ s.execute("text.select", &json!({"story":a["story"],"anchor":0,"focus":5})).unwrap();+ (s, a["story"].clone(), b["story"].clone())+ }++ #[test]+ fn redefine_paragraph_updates_other_stories_and_clears_the_source_overrides() {+ let (mut s, a, b) = sample();+ s.execute("style.character.create", &json!({"name":"Emphasis","chars":{"underline":true}})).unwrap();+ s.execute("style.character.apply", &json!({"name":"Emphasis"})).unwrap();+ s.execute("type.char", &json!({"size":20,"fill":"[Black]"})).unwrap();+ s.execute("type.para", &json!({"spaceAfter":9})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ let undo = s.doc().unwrap().history.undo.len();+ s.execute("style.paragraph.redefine", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);+ assert!(s.doc().unwrap().doc.styles.para("Header").unwrap().chars.underline.is_none());+ for story in [&a, &b] {+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();+ let attrs = s.execute("type.selectionAttrs", &json!({})).unwrap();+ assert_eq!(attrs["chars"]["size"], 20.0);+ assert_eq!(attrs["chars"]["fill"], "[Black]");+ assert_eq!(attrs["para"]["spaceAfter"], 9.0);+ assert_eq!(attrs["chars"]["underline"], story == &a);+ }+ s.execute("style.paragraph.edit", &json!({"name":"Header","chars":{"size":22}})).unwrap();+ s.execute("text.select", &json!({"story":a,"anchor":0,"focus":5})).unwrap();+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], 22.0);+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc, before);+ }++ #[test]+ fn redefine_character_does_not_capture_paragraph_font_size() {+ let (mut s, a, b) = sample();+ s.execute("style.character.create", &json!({"name":"Underline","chars":{"underline":true}})).unwrap();+ for story in [&a, &b] {+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();+ s.execute("style.character.apply", &json!({"name":"Underline"})).unwrap();+ }+ s.execute("type.char", &json!({"fill":"[Black]"})).unwrap();+ s.execute("style.character.redefine", &json!({"name":"Underline"})).unwrap();+ let style = s.doc().unwrap().doc.styles.char_style("Underline").unwrap();+ assert!(style.chars.size.is_none());+ assert_eq!(style.chars.underline, Some(true));+ for story in [&a, &b] {+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], "[Black]");+ }+ }++ #[test]+ fn redefine_rejects_the_wrong_style_and_the_none_entry_atomically() {+ let (mut s, _, _) = sample();+ let before = s.doc().unwrap().doc.clone();+ let undo = s.doc().unwrap().history.undo.len();+ assert!(s.execute("style.paragraph.redefine", &json!({"name":"Other"})).is_err());+ assert!(s.execute("style.character.redefine", &json!({})).is_err());+ assert_eq!(s.doc().unwrap().doc, before);+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ }+}+use designcraft_color::{Swatch, SwatchValue};use designcraft_doc::{CharAttrs, CharacterStyle, ParaAttrs, ParagraphStyle, Styles};use serde_json::{Value, json};@@ -81,6 +158,24 @@ pub fn specs() -> Vec<CommandSpec> {),cmd!("style.paragraph.apply", "Apply Paragraph Style", [], None, "{name, clearOverrides?: bool}", has_text_or_frames, apply_para),cmd!("style.character.apply", "Apply Character Style", [], None, "{name}", has_text_or_frames, apply_char),+ cmd!(+ "style.paragraph.redefine",+ "Redefine Paragraph Style",+ [],+ None,+ "{name?} — incorporate the first selected paragraph/character's local formatting into its paragraph style; retain character styles; one undo step",+ has_text_or_frames,+ |s, p| redefine(s, p, true)+ ),+ cmd!(+ "style.character.redefine",+ "Redefine Character Style",+ [],+ None,+ "{name?} — incorporate the first selected character's local formatting into its character style without capturing paragraph attributes; one undo step",+ has_text_or_frames,+ |s, p| redefine(s, p, false)+ ),cmd!("style.paragraph.create","New Paragraph Style…",@@ -397,6 +492,79 @@ fn attrs<T: Default>(cmd: &str, group: &str, p: &Value, set: impl Fn(&mut T, &stOk(a)}+fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {+ let command = if paragraph { "style.paragraph.redefine" } else { "style.character.redefine" };+ let targets = super::text::format_targets_pub(s);+ let target = targets.first().ok_or_else(|| bad(command, "select text using the style to redefine"))?;+ let state = s.doc()?;+ let story = state.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;+ let pf = story.paras.get(story.para_at(target.range.start)).ok_or_else(|| bad(command, "no paragraph at the selection"))?;+ let cf = super::text::effective_char_format(s, target)?;+ let selected = if paragraph { &pf.style } else { &cf.style };+ let name = str_param(p, "name").unwrap_or(selected).to_string();+ if name != *selected || name == if paragraph { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {+ return Err(bad(command, "select text using the named style; the no-style entry cannot be redefined"));+ }+ let (base_para, base_chars) = state.doc.styles.resolve_para_style(&pf.style);+ let (resolved_para, paragraph_chars) = state.doc.styles.resolve_para(pf);+ let para_changes = base_para.delta(&resolved_para);+ let mut current = if paragraph {+ paragraph_chars.clone()+ } else {+ state.doc.styles.resolve_char(¶graph_chars, &designcraft_doc::CharFormat { style: name.clone(), over: CharAttrs::default() })+ };+ let inherited = if paragraph { base_chars } else { current.clone() };+ // A named character style is an intentional layer, not a paragraph override to absorb.+ current.apply(&cf.over);+ let char_changes = inherited.delta(¤t);+ let result = s.edit(|d, _| {+ if paragraph {+ let style = d.styles_mut().para_mut(&name).ok_or_else(|| bad(command, "paragraph style no longer exists"))?;+ style.para.merge(¶_changes);+ style.chars.merge(&char_changes);+ } else {+ let style =+ d.styles_mut().character.iter_mut().find(|st| st.name == name).ok_or_else(|| bad(command, "character style no longer exists"))?;+ style.chars.merge(&char_changes);+ }+ let styles = d.styles.clone();+ for target in &targets {+ let Some(story) = d.text_story_mut(target.story, target.cell) else { continue };+ let end = if target.range.is_empty() { target.range.start } else { target.range.end.saturating_sub(1) };+ let (first, last) = (story.para_at(target.range.start), story.para_at(end));+ for (index, range) in story.para_ranges().into_iter().enumerate().take(last.saturating_add(1)).skip(first) {+ let Some(pf) = story.paras.get_mut(index) else { continue };+ if paragraph && pf.style != name {+ continue;+ }+ if paragraph {+ let (pp, cp) = styles.resolve_para(pf);+ let (base_p, base_c) = styles.resolve_para_style(&name);+ pf.para = base_p.delta(&pp);+ pf.chars = base_c.delta(&cp);+ }+ let (_, base) = styles.resolve_para(pf);+ let end = range.end.saturating_add(1).min(story.len());+ let range = if paragraph { range.start..end } else { range.start.max(target.range.start)..end.min(target.range.end) };+ story.format_chars(range, |format| {+ if !paragraph && format.style != name {+ return;+ }+ let mut inherited = base.clone();+ inherited.apply(&styles.char_style_attrs(&format.style));+ let resolved = styles.resolve_char(&base, format);+ format.over = inherited.delta(&resolved);+ });+ }+ }+ Ok(json!({"name":name}))+ });+ if result.is_ok() {+ s.typing_format = None;+ }+ result+}+fn apply_para(s: &mut Session, p: &Value) -> Result<Value> {let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.apply", "missing name"))?.to_string();let clear = p.get("clearOverrides").and_then(Value::as_bool).unwrap_or(false);diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rsindex fb080c79b..55555f666 100644--- a/crates/ui-egui/src/panels/styles.rs+++ b/crates/ui-egui/src/panels/styles.rs@@ -116,6 +116,11 @@ fn style_row(app: &mut DesignApp, ui: &mut egui::Ui, para: bool, n: &str, currenlet _ = app.run(cmd, json!({"name": n}));ui.close();}+ if editable && current == Some(n) && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Redefine Style"))).clicked() {+ let command = if para { "style.paragraph.redefine" } else { "style.character.redefine" };+ let _ = app.run(command, json!({"name":n}));+ ui.close();+ }if current == Some(n) && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Break Link to Style"))).clicked() {let _ = app.run("style.breakLink", json!({"kind": kind}));ui.close();@@ -171,6 +176,34 @@ mod tests {use super::*;+ #[test]+ fn selected_style_context_menu_redefines_its_format() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Headline"})).unwrap();+ app.run("text.select", json!({"story":frame["story"],"anchor":0,"focus":8})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Header","chars":{"size":18}})).unwrap();+ app.run("style.paragraph.apply", json!({"name":"Header"})).unwrap();+ app.run("type.char", json!({"size":24})).unwrap();+ let mut h = Harness::builder().with_size(vec2(360.0, 240.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let tokens = Tokens::get(ui.ctx());+ style_row(app, ui, true, "Header", Some("Header"), &[], &tokens);+ },+ app,+ );+ h.run_steps(3);+ let at = egui::pos2(30.0, 15.0);+ h.event(egui::Event::PointerMoved(at));+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });+ h.run_steps(2);+ }+ h.get_by_label("Redefine Style").click();+ h.run_steps(3);+ assert_eq!(h.state().session.doc().unwrap().doc.styles.para("Header").unwrap().chars.size, Some(24.0));+ }+#[test]fn character_style_plus_captures_selection_for_reuse() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 30512bdf9..76e77c8ca 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -61,6 +61,13 @@ context menus, typing at a caret) are things a layout artist does every minute,## Remaining effort+The selected style's context menu now offers Redefine Style for paragraph and character styles.+It incorporates the source text's local changes, updates every use, and removes matching source+overrides in one undo step. Named character styles remain separate when redefining a paragraph+style. Commands: `style.paragraph.redefine` and `style.character.redefine` (optional `name`,+which must match the source). This implements the global color, size and spacing updates at+about 5:10–6:00 in [Jessica Garrity's styles tutorial](https://www.youtube.com/watch?v=pG9JkAPLgs8).+| Work | Opus 5.5 h ||---|---|| Copy/paste, context menus, threading clicks, caret formatting on every platform, with control-channel regression tests | 30–50 |