Skip to content

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

Merge remote-tracking branch 'origin/main' into zydvc26s67-web-paragraph-styles-save-delete

zydvc26s67-web85e3fc879c1c
diff --cc crates/engine/src/cmd/style.rs
index d1ffe2b4f,92641e4b9..948fcdbfc
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -100,9 -100,24 +100,25 @@@ pub fn specs() -> Vec<CommandSpec>
edit_para
),
cmd!("style.paragraph.delete", "Delete Paragraph Style", [], None, "{name, replaceWith?}", has_doc, delete_para),
- cmd!("style.character.create", "New Character Style…", [], None, "{name, basedOn?, chars?: {…}}", has_doc, create_char),
- cmd!("style.character.edit", "Character Style Options…", [], None, "{name, rename?, basedOn?, chars?}", has_doc, edit_char),
+ cmd!(
+ "style.character.create",
+ "New Character Style…",
+ [],
+ None,
+ "{name, basedOn?: style | \"[None]\", chars?: {…}} — the style sets only `chars` → {name} (made unique)",
+ has_doc,
+ create_char
+ ),
+ cmd!(
+ "style.character.edit",
+ "Character Style Options…",
+ [],
+ None,
+ "{name, rename?, basedOn?: style | \"[None]\" | null, chars?: {attr: value | null (no longer set)}} — renaming updates every use",
+ has_doc,
+ edit_char
+ ),
+ cmd!("style.character.delete", "Delete Character Style", [], None, "{name, replaceWith?}", has_doc, delete_char),
cmd!(query "style.list", "List Styles", [], None, "{} → paragraph and character style names", has_doc, |s, _| {
let st = s.doc()?;
Ok(json!({
diff --cc crates/ui-egui/src/dialogs.rs
index 121ab6dec,a2dc5c189..4114162c1
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -50,12 -50,9 +50,12 @@@ impl Dialog
fields.insert("separator".into(), json!(sep.replace('\t', "^t").replace('\u{2003}', "^m").replace('\u{2002}', "^>")));
fields.entry("tab".to_string()).or_insert(json!("numbering"));
}
- if id == "paragraphStyleOptions" {
+ if id == "paragraphStyleOptions" || id == "characterStyleOptions" {
fields.entry("section".to_string()).or_insert(json!("general"));
}
+ if id == "characterStyleOptions" {
+ fields.entry("section".to_string()).or_insert(json!("general"));
+ }
if id == "frameSize" {
for k in ["width", "height"] {
if let Some(v) = fields.get(k).and_then(Value::as_f64) {
@@@ -1513,41 -1522,43 +1529,59 @@@ pub fn confirm(app: &mut DesignApp) ->
}
Ok(r)
}
+ "deleteParagraphStyle" => {
+ let name = d.s("name");
+ let replace = d.s("replaceWith");
+ app.run(
+ "style.paragraph.delete",
+ json!({"name": name, "replaceWith": if replace.is_empty() { json!(designcraft_doc::BASIC_PARAGRAPH) } else { json!(replace) }}),
+ )
+ }
"characterStyleOptions" => {
let name = d.s("name");
- let mut chars = serde_json::Map::new();
+ 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 mut params = json!({"name": name, "chars": chars});
- let based = d.s("basedOn");
- if !based.is_empty() {
- params["basedOn"] = if based == designcraft_doc::NO_CHAR_STYLE { Value::Null } else { json!(based) };
- }
- let rename = d.s("rename");
- if !rename.is_empty() && rename != name {
- params["rename"] = json!(rename);
+ 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);
}
- app.run("style.character.edit", params)
+ r
}
+ "deleteCharacterStyle" => {
+ let name = d.s("name");
+ let replace = d.s("replaceWith");
+ app.run(
+ "style.character.delete",
+ json!({"name": name, "replaceWith": if replace.is_empty() { json!(designcraft_doc::NO_CHAR_STYLE) } else { json!(replace) }}),
+ )
+ }
"colorPicker" => {
let hex = d.s("hex");
app.run("object.color", json!({"color": hex, "target": d.s("target")}))
@@@ -2239,150 -2239,119 +2262,163 @@@ fn paragraph_style_options(app: &mut De
});
}
-/// The section list on the left of the style options dialogs.
+fn delete_paragraph_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let name = d.s("name");
+ ui.set_min_width(380.0);
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(
+ crate::i18n::tr(&app.ui.language, "Delete the paragraph style \"{name}\"?")
+ .replace("{name}", crate::i18n::style_name(&app.ui.language, &name)),
+ )
+ .size(12.5),
+ );
+ ui.add_space(8.0);
+ let Some(st) = app.session.active() else { return };
+ let in_use = st.doc.stories.values().any(|s| s.paras.iter().any(|f| f.style == name));
+ let names: Vec<String> = st.doc.styles.paragraph.iter().map(|p| p.name.clone()).filter(|n| *n != name).collect();
+ if in_use {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "This style is in use. Text using it will be reassigned to:"))
+ .size(11.0)
+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ } else {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace with:")).size(11.0).color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ }
+ ui.add_space(4.0);
+ if !d.fields.contains_key("replaceWith") {
+ d.fields.insert("replaceWith".into(), json!(designcraft_doc::BASIC_PARAGRAPH));
+ }
+ let replace = d.s("replaceWith");
+ egui::ComboBox::from_id_salt("del_para_replace")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &replace)))
+ .width(260.0)
+ .show_ui(ui, |ui| {
+ for n in &names {
+ if ui.selectable_label(*n == replace, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {
+ d.fields.insert("replaceWith".into(), json!(n));
+ }
+ }
+ });
+}
+
+ fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, sections: &[(&str, &str)]) {
+ ui.vertical(|ui| {
+ ui.set_width(170.0);
+ for (id, label) in sections {
+ if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ d.fields.insert("section".into(), json!(id));
+ }
+ }
+ });
+ }
+
+ /// "Paragraph Style n" / "Character Style n": the first name no style has.
+ fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {
+ let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };
+ let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };
+ // Among count + 1 numbers at least one is free.
+ (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))
+ }
+
+ /// Paragraph or Character Style Options for an existing style (a double-click on it in the styles
+ /// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.
+ pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {
+ if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {
+ return;
+ }
+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
+ app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));
+ }
+
+ /// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named
+ /// with the next free "Paragraph Style n" / "Character Style n".
+ pub fn open_new_style(app: &mut DesignApp, para: bool) {
+ let Some(st) = app.session.active() else { return };
+ let name = next_style_name(&st.doc.styles, para);
+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
+ app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));
+ }
+
+ /// Character Style Options: General, then the character sections it shares with Paragraph Style
+ /// Options. A character style sets only some attributes: the fields show those it and its Based
+ /// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied
+ /// on OK; `new` makes the style instead of editing `name`.
fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
let name = d.s("name");
- let Some(st) = app.session.active() else { return };
- let Some(style) = st.doc.styles.char_style(&name).cloned() else {
- ui.label(format!("No style named {name}"));
- return;
+ let new = d.b("new");
+ let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };
+ let styles = &doc.styles;
+ let style = match styles.char_style(&name) {
+ _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },
+ Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),
+ _ => {
+ crate::rtl::label(ui, format!("No style named {name}"));
+ return;
+ }
};
- let names: Vec<String> = st.doc.styles.character.iter().map(|c| c.name.clone()).filter(|n| *n != name).collect();
- let cp = st.doc.styles.resolve_char_style(&name);
- let cv = serde_json::to_value(&cp).unwrap_or_default();
- let cur = |d: &Dialog, k: &str, base: &Value| d.fields.get(k).cloned().unwrap_or_else(|| base.clone());
- ui.set_min_width(480.0);
+ if !d.fields.contains_key("rename") {
+ d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));
+ }
+ let based = d
+ .fields
+ .get("basedOn")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or(style.based_on.clone())
+ .unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());
+ // The fields show the style's own attributes over those its Based On gives it.
+ let mut shown = styles.char_style_attrs(&based);
+ shown.merge(&style.chars);
+ let base = serde_json::to_value(&shown).unwrap_or_default();
+ let cf = CharFields { base: &base, sparse: true };
+ let lang = app.ui.language.clone();
+ ui.set_min_width(560.0);
ui.horizontal_top(|ui| {
- ui.set_min_height(280.0);
- ui.set_max_height(280.0);
- ui.vertical(|ui| {
- ui.set_width(150.0);
- for (id, label) in [("general", "General"), ("chars", "Basic Character Formats"), ("color", "Character Color")] {
- if ui.selectable_label(d.s("section") == id, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {
- d.fields.insert("section".into(), json!(id));
- }
- }
- });
+ // A fixed height: the separator would otherwise stretch the dialog to the window.
+ ui.set_min_height(380.0);
+ ui.set_max_height(380.0);
+ section_list(
+ &lang,
+ ui,
+ d,
+ &[
+ ("general", "General"),
+ ("chars", "Basic Character Formats"),
+ ("advanced", "Advanced Character Formats"),
+ ("color", "Character Color"),
+ ("openType", "OpenType Features"),
+ ("underline", "Underline Options"),
+ ("strikethrough", "Strikethrough Options"),
+ ],
+ );
ui.separator();
ui.vertical(|ui| match d.s("section").as_str() {
- "chars" => {
- let fonts = crate::panels::fonts(app);
- let menu = crate::panels::font_menu(app);
- egui::Grid::new("csc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));
- let fam = cur(d, "c.fontFamily", &cv["fontFamily"]).as_str().unwrap_or("").to_string();
- egui::ComboBox::from_id_salt("csfam").selected_text(crate::panels::font_label(app, &menu, &fam)).width(200.0).show_ui(ui, |ui| {
- if let Some(f) = crate::panels::font_menu_rows(app, ui, &menu, &fam) {
- d.fields.insert("c.fontFamily".into(), json!(f));
- }
- });
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));
- let sty = cur(d, "c.fontStyle", &cv["fontStyle"]).as_str().unwrap_or("").to_string();
- egui::ComboBox::from_id_salt("cssty").selected_text(&sty).width(200.0).show_ui(ui, |ui| {
- for s in fonts.styles(&fam) {
- if ui.selectable_label(s == sty, &s).clicked() {
- d.fields.insert("c.fontStyle".into(), json!(s));
- }
- }
- });
- ui.end_row();
- for (label, key, suffix) in [("Size:", "size", " pt"), ("Tracking:", "tracking", "")] {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
- let v = cur(d, &format!("c.{key}"), &cv[key]).as_f64();
- if let Some(n) = crate::widgets::number(ui, &format!("cs{key}"), v, suffix, 80.0, 2) {
- d.fields.insert(format!("c.{key}"), json!(n));
- }
- ui.end_row();
- }
- });
- }
- "color" => {
- let cur_fill = cur(d, "c.fill", &cv["fill"]).as_str().unwrap_or("").to_string();
- let swatches: Vec<String> = st.doc.swatches.iter().map(|s| s.name.clone()).collect();
- egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| {
- for sw in swatches {
- let (c, g) = crate::widgets::swatch_colors(&st.doc, &sw, 1.0);
- ui.horizontal(|ui| {
- let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());
- crate::widgets::paint_chip(ui.painter(), r, c, g);
- if ui.selectable_label(sw == cur_fill, &sw).clicked() {
- d.fields.insert("c.fill".into(), json!(sw));
- }
- });
- }
- });
- }
+ "chars" => basic_character_formats(app, ui, d, &cf),
+ "advanced" => advanced_character_formats(&lang, ui, d, &cf),
+ "color" => character_color(&lang, ui, d, &cf, &doc),
+ "openType" => open_type_features(&lang, ui, d, &cf),
+ "underline" => line_options(&lang, ui, d, &cf, &doc, "underline"),
+ "strikethrough" => line_options(&lang, ui, d, &cf, &doc, "strikethrough"),
_ => {
egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Style Name:"));
- if !d.fields.contains_key("rename") {
- d.fields.insert("rename".into(), json!(name));
- }
- let mut rn = d.s("rename");
- if ui.add(egui::TextEdit::singleline(&mut rn).desired_width(220.0)).changed() {
- d.fields.insert("rename".into(), json!(rn));
- }
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Style Name:"));
+ text_field(ui, d, "rename", 220.0);
ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Based On:"));
- let based = d
- .fields
- .get("basedOn")
- .and_then(Value::as_str)
- .map(str::to_string)
- .or(style.based_on.clone())
- .unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Based On:"));
egui::ComboBox::from_id_salt("csbased")
- .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &based)))
+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&lang, &based)))
.width(220.0)
.show_ui(ui, |ui| {
- for n in [designcraft_doc::NO_CHAR_STYLE].into_iter().chain(names.iter().map(String::as_str)) {
- if ui.selectable_label(n == based, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {
- d.fields.insert("basedOn".into(), json!(n));
+ // Not itself, nor a style based on it.
+ for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) {
+ if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(&lang, &s.name))).clicked() {
+ d.fields.insert("basedOn".into(), json!(s.name));
}
}
});
@@@ -2399,51 -2382,346 +2449,391 @@@
});
}
+ /// An attribute's name as Style Settings shows it: the field's label where the name reads poorly.
+ fn setting_label(lang: &str, key: &str) -> String {
+ match key {
+ "hScale" => crate::i18n::tr(lang, "Horizontal Scale:").trim_end_matches([':', ':']).to_string(),
+ "vScale" => crate::i18n::tr(lang, "Vertical Scale:").trim_end_matches([':', ':']).to_string(),
+ "capitalization" => crate::i18n::tr(lang, "Case:").trim_end_matches([':', ':']).to_string(),
+ "otfFeatures" => crate::i18n::tr(lang, "OpenType Features").to_string(),
+ _ => crate::i18n::tr(lang, &humanize(key)).to_string(),
+ }
+ }
+
+ /// An attribute value as Style Settings shows it.
+ fn setting_text(v: &Value) -> String {
+ match v {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.as_f64().map_or_else(|| n.to_string(), |x| format!("{}", (x * 1000.0).round() / 1000.0)),
+ Value::Bool(b) => if *b { "on" } else { "off" }.into(),
+ Value::Array(a) => a.iter().map(setting_text).collect::<Vec<_>>().join(", "),
+ Value::Object(o) => o.get("value").or_else(|| o.get("kind")).map(setting_text).unwrap_or_default(),
+ Value::Null => String::new(),
+ }
+ }
+
+ /// Where the character sections of the style options dialogs get the values they show: `base`
+ /// holds them by attribute name (resolved values for a paragraph style; for a character style the
+ /// attributes it sets, the others absent). `sparse` (a character style) lets a field be blank:
+ /// emptying it, or picking the blank entry, unsets the attribute.
+ struct CharFields<'a> {
+ base: &'a Value,
+ sparse: bool,
+ }
+
+ impl CharFields<'_> {
+ /// The value shown for attribute `key`: the dialog's edit, else the base value.
+ fn get(&self, d: &Dialog, key: &str) -> Value {
+ d.fields.get(&format!("c.{key}")).cloned().unwrap_or_else(|| self.base.get(key).cloned().unwrap_or(Value::Null))
+ }
+ fn set(&self, d: &mut Dialog, key: &str, v: Value) {
+ d.fields.insert(format!("c.{key}"), v);
+ }
+ }
+
+ /// A number attribute shown multiplied by `scale` (100 for a fraction shown as a percentage).
+ fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, suffix: &str, scale: f64, range: (f64, f64)) {
+ let v = cf.get(d, key).as_f64().map(|x| x * scale);
+ let field = crate::widgets::NumField::number(key, v, suffix, 2).width(80.0).range(range.0, range.1);
+ let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) };
+ if let Some(n) = edit {
+ cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale)));
+ }
+ }
+
+ /// An attribute chosen from `opts` (value, label); a character style also has a blank entry.
+ fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) {
+ let cur = cf.get(d, key);
+ let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1));
+ egui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {
+ if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {
+ cf.set(d, key, Value::Null);
+ }
+ for (v, label) in opts {
+ if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ cf.set(d, key, v.clone());
+ }
+ }
+ });
+ }
+
+ /// An on/off attribute; for a character style a third, mixed state leaves it unset (clicks go
+ /// unset → on → off → unset).
+ fn char_check(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, label: &str) {
+ let cur = cf.get(d, key);
+ let mut on = cur.as_bool().unwrap_or(false);
+ let unset = cf.sparse && cur.is_null();
+ if ui.add(egui::Checkbox::new(&mut on, crate::rtl::widget(ui, label)).indeterminate(unset)).clicked() {
+ let next = match cur.as_bool() {
+ _ if !cf.sparse => json!(on),
+ None => json!(true),
+ Some(true) => json!(false),
+ Some(false) => Value::Null,
+ };
+ cf.set(d, key, next);
+ }
+ }
+
+ /// A swatch attribute from a menu; `text_color` names the "" entry (the text's own colour).
+ fn char_swatch(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document, key: &str, text_color: Option<&str>) {
+ let mut opts: Vec<(Value, &str)> = text_color.map(|l| (json!(""), l)).into_iter().collect();
+ opts.extend(doc.swatches.iter().map(|w| (json!(w.name), w.name.as_str())));
+ char_choice(lang, ui, d, cf, key, &opts);
+ }
+
+ /// Basic Character Formats: font, size, leading, kerning, tracking, case, position and the
+ /// underline, strikethrough, ligatures and no-break switches.
+ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {
+ let lang = app.ui.language.clone();
+ let lang = lang.as_str();
+ let fonts = crate::panels::fonts(app);
+ let menu = crate::panels::font_menu(app);
+ egui::Grid::new("psc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
+ let fam = cf.get(d, "fontFamily").as_str().unwrap_or("").to_string();
+ let shown = if fam.is_empty() { "—".to_string() } else { crate::panels::font_label(app, &menu, &fam) };
+ egui::ComboBox::from_id_salt("psfam")
+ .selected_text(shown)
+ .width(200.0)
+ .height(440.0)
+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
+ .show_ui(ui, |ui| {
+ if cf.sparse && ui.selectable_label(fam.is_empty(), " ").clicked() {
+ cf.set(d, "fontFamily", Value::Null);
+ }
+ if let Some(f) = crate::panels::font_menu_body(app, ui, &menu, &fam, 200.0) {
+ cf.set(d, "fontFamily", json!(f));
+ }
+ });
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
+ let sty = cf.get(d, "fontStyle").as_str().unwrap_or("").to_string();
+ if cf.sparse && fam.is_empty() {
+ // No family to list styles of: type the style ("Italic" in whatever font the text has).
+ let mut s = sty.clone();
+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).changed() {
+ cf.set(d, "fontStyle", if s.trim().is_empty() { Value::Null } else { json!(s) });
+ }
+ } else {
+ egui::ComboBox::from_id_salt("pssty").selected_text(&sty).width(200.0).show_ui(ui, |ui| {
+ if cf.sparse && ui.selectable_label(sty.is_empty(), " ").clicked() {
+ cf.set(d, "fontStyle", Value::Null);
+ }
+ for s in fonts.styles(&fam) {
+ if ui.selectable_label(s == sty, &s).clicked() {
+ cf.set(d, "fontStyle", json!(s));
+ }
+ }
+ });
+ }
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Size:"));
+ char_number(ui, d, cf, "size", " pt", 1.0, (0.1, 1296.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Leading:"));
+ let lv = match cf.get(d, "leading") {
+ v if v["kind"] == "points" => v["value"].as_f64(),
+ _ => None,
+ };
+ let field = crate::widgets::NumField::number("pslead", lv, " pt", 2).width(80.0).range(0.0, 5000.0);
+ let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) };
+ if let Some(n) = edit {
+ cf.set(d, "leading", n.map_or(Value::Null, |n| json!({"kind": "points", "value": n})));
+ }
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Kerning:"));
+ char_choice(
+ lang,
+ ui,
+ d,
+ cf,
+ "kerning",
+ &[(json!({"kind": "metrics"}), "Metrics"), (json!({"kind": "optical"}), "Optical"), (json!({"kind": "none"}), "0")],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tracking:"));
+ char_number(ui, d, cf, "tracking", "", 1.0, (-1000.0, 10000.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Case:"));
+ char_choice(
+ lang,
+ ui,
+ d,
+ cf,
+ "capitalization",
+ &[
+ (json!("normal"), "Normal"),
+ (json!("allCaps"), "All Caps"),
+ (json!("smallCaps"), "Small Caps"),
+ (json!("openTypeAllSmallCaps"), "OpenType All Small Caps"),
+ ],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Position:"));
+ char_choice(
+ lang,
+ ui,
+ d,
+ cf,
+ "position",
+ &[
+ (json!("normal"), "Normal"),
+ (json!("superscript"), "Superscript"),
+ (json!("subscript"), "Subscript"),
+ (json!("otSuperscript"), "OpenType Superscript"),
+ (json!("otSubscript"), "OpenType Subscript"),
+ (json!("otNumerator"), "OpenType Numerator"),
+ (json!("otDenominator"), "OpenType Denominator"),
+ ],
+ );
+ ui.end_row();
+ });
+ ui.add_space(4.0);
+ egui::Grid::new("pscb").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {
+ char_check(ui, d, cf, "underline", crate::i18n::tr(lang, "Underline"));
+ char_check(ui, d, cf, "ligatures", crate::i18n::tr(lang, "Ligatures"));
+ ui.end_row();
+ char_check(ui, d, cf, "strikethrough", crate::i18n::tr(lang, "Strikethrough"));
+ char_check(ui, d, cf, "noBreak", crate::i18n::tr(lang, "No Break"));
+ ui.end_row();
+ });
+ }
+
+ /// Advanced Character Formats: scaling, baseline shift, skew and language.
+ fn advanced_character_formats(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {
+ egui::Grid::new("csa").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Horizontal Scale:"));
+ char_number(ui, d, cf, "hScale", "%", 100.0, (1.0, 1000.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Vertical Scale:"));
+ char_number(ui, d, cf, "vScale", "%", 100.0, (1.0, 1000.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Baseline Shift:"));
+ char_number(ui, d, cf, "baselineShift", " pt", 1.0, (-5000.0, 5000.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Skew:"));
+ char_number(ui, d, cf, "skew", "°", 1.0, (-85.0, 85.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Language:"));
+ let opts: Vec<(Value, &str)> = crate::panels::properties::LANGUAGES.iter().map(|l| (json!(l), *l)).collect();
+ char_choice(lang, ui, d, cf, "language", &opts);
+ ui.end_row();
+ });
+ }
+
+ /// Character Color: the fill or stroke swatch, its tint and the stroke weight.
+ fn character_color(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document) {
+ let stroke = d.s("colorTarget") == "stroke";
+ ui.horizontal(|ui| {
+ for (target, label) in [("fill", "Fill"), ("stroke", "Stroke")] {
+ if ui.selectable_label((target == "stroke") == stroke, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ d.fields.insert("colorTarget".into(), json!(target));
+ }
+ }
+ });
+ let key = if stroke { "stroke" } else { "fill" };
+ let cur = cf.get(d, key).as_str().unwrap_or("").to_string();
+ egui::ScrollArea::vertical().id_salt(("cscolor", key)).max_height(220.0).show(ui, |ui| {
+ for sw in &doc.swatches {
+ let (c, g) = crate::widgets::swatch_colors(doc, &sw.name, 1.0);
+ ui.horizontal(|ui| {
+ let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());
+ crate::widgets::paint_chip(ui.painter(), r, c, g);
+ if ui.selectable_label(sw.name == cur, &sw.name).clicked() {
+ // A character style's chosen swatch, clicked again, is no longer set.
+ cf.set(d, key, if cf.sparse && sw.name == cur { Value::Null } else { json!(sw.name) });
+ }
+ });
+ }
+ });
+ egui::Grid::new("cscg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));
+ char_number(ui, d, cf, if stroke { "strokeTint" } else { "fillTint" }, "%", 100.0, (0.0, 100.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));
+ char_number(ui, d, cf, "strokeWeight", " pt", 1.0, (0.0, 800.0));
+ ui.end_row();
+ });
+ }
+
+ /// OpenType Features: the feature switches, figure style and stylistic sets (one `otfFeatures`
+ /// list: changing any feature sets the whole list).
+ fn open_type_features(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {
+ use designcraft_doc::otf;
+ let mut list: Vec<String> =
+ cf.get(d, "otfFeatures").as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ let mut changed = false;
+ egui::Grid::new("csot").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {
+ for (i, (tag, label, _)) in otf::TOGGLES.iter().enumerate() {
+ let mut on = otf::is_on(&list, tag);
+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).changed() {
+ otf::set(&mut list, tag, on);
+ changed = true;
+ }
+ if i % 2 == 1 {
+ ui.end_row();
+ }
+ }
+ });
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Figure Style:"));
+ let fig = otf::figures(&list);
+ let shown = otf::FIGURES.iter().find(|f| f.0 == fig).map_or("", |f| f.1);
+ egui::ComboBox::from_id_salt("csfig").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))).width(180.0).show_ui(ui, |ui| {
+ for (id, label, ..) in otf::FIGURES {
+ if ui.selectable_label(fig == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() && otf::set_figures(&mut list, id)
+ {
+ changed = true;
+ }
+ }
+ });
+ });
+ ui.add_space(4.0);
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Stylistic Sets"));
+ let mask = otf::stylistic_sets(&list);
+ egui::Grid::new("csss").num_columns(10).spacing([2.0, 2.0]).show(ui, |ui| {
+ for n in 1..=20u32 {
+ let bit = 1u32 << (n - 1);
+ if ui.add_sized([28.0, 20.0], egui::Button::selectable(mask & bit != 0, format!("{n}"))).clicked() {
+ otf::set_stylistic_sets(&mut list, mask ^ bit);
+ changed = true;
+ }
+ if n % 10 == 0 {
+ ui.end_row();
+ }
+ }
+ });
+ if changed {
+ cf.set(d, "otfFeatures", json!(list));
+ }
+ }
+
+ /// Underline Options / Strikethrough Options (`key` is `underline` or `strikethrough`).
+ fn line_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document, key: &str) {
+ char_check(ui, d, cf, key, crate::i18n::tr(lang, if key == "underline" { "Underline On" } else { "Strikethrough On" }));
+ ui.add_space(4.0);
+ egui::Grid::new(("csline", key)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));
+ char_number(ui, d, cf, &format!("{key}Weight"), " pt", 1.0, (0.0, 800.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:"));
+ char_number(ui, d, cf, &format!("{key}Offset"), " pt", 1.0, (-800.0, 800.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Color:"));
+ char_swatch(lang, ui, d, cf, doc, &format!("{key}Color"), Some("(Text Color)"));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));
+ char_number(ui, d, cf, &format!("{key}Tint"), "%", 100.0, (0.0, 100.0));
+ ui.end_row();
+ });
+ }
+
+fn delete_character_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let name = d.s("name");
+ ui.set_min_width(380.0);
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(
+ crate::i18n::tr(&app.ui.language, "Delete the character style \"{name}\"?")
+ .replace("{name}", crate::i18n::style_name(&app.ui.language, &name)),
+ )
+ .size(12.5),
+ );
+ ui.add_space(8.0);
+ let Some(st) = app.session.active() else { return };
+ let in_use = st.doc.stories.values().any(|s| s.chars.iter().any(|r| r.format.style == name));
+ let names: Vec<String> = st.doc.styles.character.iter().map(|c| c.name.clone()).filter(|n| *n != name).collect();
+ if in_use {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "This style is in use. Text using it will be reassigned to:"))
+ .size(11.0)
+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ } else {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace with:")).size(11.0).color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ }
+ ui.add_space(4.0);
+ if !d.fields.contains_key("replaceWith") {
+ d.fields.insert("replaceWith".into(), json!(designcraft_doc::NO_CHAR_STYLE));
+ }
+ let replace = d.s("replaceWith");
+ egui::ComboBox::from_id_salt("del_char_replace")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &replace)))
+ .width(260.0)
+ .show_ui(ui, |ui| {
+ for n in [designcraft_doc::NO_CHAR_STYLE].into_iter().chain(names.iter().map(String::as_str)) {
+ if ui.selectable_label(n == replace, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {
+ d.fields.insert("replaceWith".into(), json!(n));
+ }
+ }
+ });
+}
+
fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) {
let cur = d.s(key);
let shown = opts.iter().find(|o| o.0 == cur).map_or(cur.as_str(), |o| o.1).to_string();
@@@ -3023,86 -3300,143 +3412,223 @@@ mod tests
}
}
+ fn test_app() -> crate::DesignApp {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", &json!({"pages": 1})).unwrap();
+ app
+ }
+
+ #[test]
+ fn paragraph_style_options_dialog_saves_edits() {
+ let mut app = test_app();
+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap()["name"].as_str().unwrap().to_string();
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": name, "p.align": "center"})));
+ confirm(&mut app).expect("OK saves the style edit");
+ let st = app.session.active().unwrap();
+ assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center));
+ }
+
+ #[test]
+ fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() {
+ let mut app = test_app();
+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();
+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();
+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();
+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ app.session.execute("style.paragraph.apply", &json!({"name": name})).unwrap();
+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH})));
+ confirm(&mut app).expect("OK deletes the style");
+ let st = app.session.active().unwrap();
+ assert!(st.doc.styles.para(&name).is_none(), "style removed");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();
+ assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "text reassigned to the replacement style");
+ }
+
+ #[test]
+ fn delete_paragraph_style_dialog_defaults_replacement_to_basic_paragraph() {
+ let mut app = test_app();
+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();
+ // No `replaceWith` set — the dialog's default field.
+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name})));
+ confirm(&mut app).expect("OK deletes the style with the default replacement");
+ let st = app.session.active().unwrap();
+ assert!(st.doc.styles.para(&name).is_none());
+ }
+
+ #[test]
+ fn character_style_options_dialog_saves_edits() {
+ let mut app = test_app();
+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", json!({"name": name, "c.tracking": 20.0})));
+ confirm(&mut app).expect("OK saves the style edit");
+ let st = app.session.active().unwrap();
+ assert_eq!(st.doc.styles.char_style(&name).unwrap().chars.tracking, Some(20.0));
+ }
+
+ #[test]
+ fn delete_character_style_dialog_removes_the_style_and_reassigns_text() {
+ let mut app = test_app();
+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();
+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();
+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();
+ app.session.execute("style.character.apply", &json!({"name": name})).unwrap();
+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE})));
+ confirm(&mut app).expect("OK deletes the style");
+ let st = app.session.active().unwrap();
+ assert!(st.doc.styles.char_style(&name).is_none(), "style removed");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();
+ assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "text reassigned to the replacement style");
+ }
+
+ #[test]
+ fn delete_character_style_dialog_defaults_replacement_to_none() {
+ let mut app = test_app();
+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ // No `replaceWith` set — the dialog's default field.
+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name})));
+ confirm(&mut app).expect("OK deletes the style with the default replacement");
+ let st = app.session.active().unwrap();
+ assert!(st.doc.styles.char_style(&name).is_none());
+ }
+
+ use designcraft_doc::{CharAttrs, CharacterStyle};
+
+ /// A document with character styles Base (bold) and Emphasis (italic) on the first two letters.
+ fn styled_app() -> DesignApp {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("style.character.create", json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();
+ app.run("style.character.create", json!({"name": "Emphasis", "chars": {"fontStyle": "Italic"}})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap();
+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 2})).unwrap();
+ app.run("style.character.apply", json!({"name": "Emphasis"})).unwrap();
+ app
+ }
+
+ /// One control-channel request, as the control port or MCP would send it.
+ fn ctl(app: &mut DesignApp, method: &str, params: Value) -> Value {
+ let (req, _reply) = crate::control::ControlRequest::new(method, params);
+ match crate::control::handle(app, &egui::Context::default(), &req) {
+ crate::control::Outcome::Done(v) => v,
+ crate::control::Outcome::Screenshot { .. } => Value::Null,
+ }
+ }
+
+ fn char_style(app: &DesignApp, name: &str) -> Option<CharacterStyle> {
+ app.session.active().and_then(|st| st.doc.styles.char_style(name).cloned())
+ }
+
+ #[test]
+ fn character_style_options_set_exactly_the_edited_attributes() {
+ let mut app = styled_app();
+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}))["ok"], true);
+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 14}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fill", "value": "[Paper]"}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": "Base"}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ assert!(app.ui.dialog.is_none());
+ let st = char_style(&app, "Emphasis").unwrap();
+ assert_eq!(st.based_on.as_deref(), Some("Base"));
+ assert_eq!(st.chars, CharAttrs { font_style: Some("Italic".into()), size: Some(14.0), fill: Some("[Paper]".into()), ..Default::default() });
+ }
+
+ #[test]
+ fn character_style_options_unset_cleared_fields_and_rename_every_use() {
+ let mut app = styled_app();
+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fontStyle", "value": null}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Strong"}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ assert!(char_style(&app, "Emphasis").is_none());
+ assert!(char_style(&app, "Strong").unwrap().chars.is_empty());
+ let st = app.session.active().unwrap();
+ let story = st.doc.stories.values().next().unwrap();
+ assert!(story.chars.iter().any(|r| r.format.style == "Strong"));
+ // A taken name keeps the dialog open with the reason.
+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Strong"}}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Base"}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);
+ assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.s("status").is_empty()));
+ assert!(char_style(&app, "Strong").is_some());
+ }
+
+ #[test]
+ fn new_character_style_opens_its_options_and_creates_the_style() {
+ let mut app = styled_app();
+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("characterStyleOptions", true, "Character Style 1"));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ let st = char_style(&app, "Character Style 1").unwrap();
+ assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), ..Default::default() }));
+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2");
+ }
+
+ #[test]
+ fn new_paragraph_style_opens_its_options_and_creates_the_style() {
+ let mut app = styled_app();
+ crate::menus::activate(&mut app, "style.paragraph.create", &Value::Null);
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("paragraphStyleOptions", true, "Paragraph Style 1"));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 20}));
+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": designcraft_doc::BASIC_PARAGRAPH}));
+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);
+ let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap();
+ assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH));
+ assert_eq!(st.chars, CharAttrs { size: Some(20.0), ..Default::default() });
+ }
+
+ #[test]
+ fn style_rows_open_their_options_except_none() {
+ let mut app = styled_app();
+ open_style_options(&mut app, false, "Emphasis");
+ let d = app.ui.dialog.take().unwrap();
+ assert_eq!((d.id.as_str(), d.s("name").as_str()), ("characterStyleOptions", "Emphasis"));
+ open_style_options(&mut app, false, designcraft_doc::NO_CHAR_STYLE);
+ assert!(app.ui.dialog.is_none());
+ open_style_options(&mut app, true, designcraft_doc::BASIC_PARAGRAPH);
+ assert_eq!(app.ui.dialog.take().unwrap().id, "paragraphStyleOptions");
+ }
+
+ #[test]
+ fn style_options_sections_draw() {
+ let mut app = styled_app();
+ let ctx = egui::Context::default();
+ let frame = |app: &mut DesignApp| {
+ for _ in 0..2 {
+ let raw = egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),
+ max_texture_side: Some(8192),
+ ..Default::default()
+ };
+ let mut out = ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ }
+ };
+ for lang in ["", "ar"] {
+ app.run("app.language", json!({"lang": lang})).unwrap();
+ for fields in [json!({"name": "Emphasis"}), json!({"new": true}), json!({"name": "Emphasis", "c.size": null, "c.underline": false})] {
+ for section in ["general", "chars", "advanced", "color", "openType", "underline", "strikethrough"] {
+ let mut f = fields.clone();
+ f["section"] = json!(section);
+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", f));
+ frame(&mut app);
+ assert!(app.ui.dialog.is_some(), "{section} stays open");
+ }
+ }
+ for section in ["general", "chars", "color"] {
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"new": true, "section": section})));
+ frame(&mut app);
+ }
+ }
+ }
+
#[test]
fn shortcut_recorder_waits_for_the_key_after_its_modifiers() {
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
diff --cc crates/ui-egui/src/panels/styles.rs
index c44ff4886,82dc1282a..b5610cc84
--- a/crates/ui-egui/src/panels/styles.rs
+++ b/crates/ui-egui/src/panels/styles.rs
@@@ -154,27 -148,5 +148,19 @@@ fn style_row(app: &mut DesignApp, ui: &
ui.data_mut(|d| d.insert_temp(id, name));
});
}
+ if para && !n.starts_with('[') {
+ ui.separator();
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Edit Paragraph Style…"))).clicked() {
- app.ui.dialog = Some(crate::dialogs::Dialog::new("paragraphStyleOptions", json!({"name": n})));
- ui.close();
- }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Paragraph Style…"))).clicked() {
+ app.ui.dialog = Some(crate::dialogs::Dialog::new("deleteParagraphStyle", json!({"name": n})));
+ ui.close();
+ }
+ }
+ if !para && !n.starts_with('[') {
+ ui.separator();
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Edit Character Style…"))).clicked() {
- app.ui.dialog = Some(crate::dialogs::Dialog::new("characterStyleOptions", json!({"name": n})));
- ui.close();
- }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Character Style…"))).clicked() {
+ app.ui.dialog = Some(crate::dialogs::Dialog::new("deleteCharacterStyle", json!({"name": n})));
+ ui.close();
+ }
+ }
});
}