mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 10:46:27 +00:00
Paragraph Styles: Style Options edits a style's tab stops
Paragraph Style Options and New Paragraph Style gain a Tabs section. It lists the style's stops and edits the selected stop's Alignment, position (X:, or Y: for vertical type), Leader and Align On character. Add puts a left stop 36 pt past the furthest one, Delete Tab removes the selected stop, and Clear All Tabs leaves the style with no stops. OK sorts the stops by position and keeps the stop edited last when two share one position. Reset Panel removes the style's tabs. paraStyle.new, paraStyle.setAttrs and paraStyle.edit check changed tabs stop by stop: at most 256 stops, and each changed stop's position from 0 to 100000 pt and leader of at most 8 characters. Stops the style already has are kept as they are. Changed tabs are sorted by position, keeping the first of stops at one position. text.tabs.set rejects a leader longer than 8 characters, an Align On value of more than one character and more than 256 stops. Loading paragraph styles skips a style whose indents, spacing, hyphenation, justification or tabs are out of range. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Tab Stops",
|
||||
["Window", "Tabs"],
|
||||
None,
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); at most 256 stops, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept",
|
||||
has_selection,
|
||||
set
|
||||
),
|
||||
@@ -38,10 +38,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
const C: &str = "text.tabs.set";
|
||||
let arr = p.get("stops").and_then(Value::as_array).ok_or_else(|| bad(C, "missing stops"))?;
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if arr.len() > max {
|
||||
return Err(bad(C, format!("at most {max} tab stops")));
|
||||
}
|
||||
let mut stops = vec![];
|
||||
for s in arr {
|
||||
let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?;
|
||||
if !(0.0..=100_000.0).contains(&position) {
|
||||
if !(0.0..=TabStop::MAX_POSITION).contains(&position) {
|
||||
return Err(bad(C, "positions must be between 0 and 100000 pt"));
|
||||
}
|
||||
let align = match s.get("align") {
|
||||
@@ -60,16 +64,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
None | Some(Value::Null) => "",
|
||||
Some(Value::String(value)) => value.as_str(),
|
||||
Some(_) => return Err(bad(C, "`leader` must be a string")),
|
||||
};
|
||||
let (label, max) = ("`leader`", TabStop::MAX_LEADER);
|
||||
if leader.chars().count() > max {
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
.chars()
|
||||
.take(8)
|
||||
.collect();
|
||||
let align_on = match s.get("alignOn") {
|
||||
None | Some(Value::Null) => '.',
|
||||
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
|
||||
Some(Value::String(value)) => {
|
||||
let mut chars = value.chars();
|
||||
let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?;
|
||||
if chars.next().is_some() {
|
||||
let label = "`alignOn`";
|
||||
return Err(bad(C, format!("{label} must be one character")));
|
||||
}
|
||||
c
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
|
||||
};
|
||||
stops.push(TabStop { position, align, leader, align_on });
|
||||
stops.push(TabStop { position, align, leader: leader.to_string(), align_on });
|
||||
}
|
||||
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
@@ -128,7 +141,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -139,6 +152,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A leader of more than eight characters, an `alignOn` of more than one character and a list
|
||||
/// of more than 256 stops are errors, not cut short.
|
||||
#[test]
|
||||
fn long_leaders_long_align_on_and_too_many_stops_are_errors() {
|
||||
let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string();
|
||||
assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters"));
|
||||
assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character"));
|
||||
let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect();
|
||||
assert!(err(Value::from(many.clone())).contains("at most 256 tab stops"));
|
||||
let ok = super::parse_stops(&json!({ "stops": &many[..256] })).unwrap();
|
||||
assert_eq!(ok.len(), 256);
|
||||
let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap();
|
||||
assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_get_clear_tabs() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef};
|
||||
|
||||
use super::clipboard::resources::import_text_styles;
|
||||
use super::typecmd::{refresh_bounds, text_targets};
|
||||
@@ -125,7 +125,7 @@ macro_rules! style_cmds {
|
||||
}
|
||||
|
||||
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -148,13 +148,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"paraStyle",
|
||||
"Paragraph Styles",
|
||||
"Paragraph",
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position"
|
||||
));
|
||||
v.push(spec(
|
||||
"paraStyle.edit",
|
||||
"Edit Paragraph Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
|
||||
|s, p| edit_style(s, p, Kind::Para),
|
||||
true,
|
||||
));
|
||||
@@ -569,8 +569,9 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => {
|
||||
let st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
}
|
||||
};
|
||||
@@ -587,7 +588,8 @@ const PARA_DISTANCE: f64 = 1296.0;
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
@@ -644,18 +646,37 @@ fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<Str
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs: Vec<f64> = kept
|
||||
.and_then(|k| k.get("tabs"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
|
||||
.unwrap_or_default();
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
|
||||
within("tabs.position", stop.position, 0.0, 100_000.0)?;
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> {
|
||||
let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array);
|
||||
stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect()
|
||||
}
|
||||
|
||||
/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other,
|
||||
/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`.
|
||||
fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) {
|
||||
if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") {
|
||||
st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
@@ -1011,10 +1032,29 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name
|
||||
/// is empty, which are skipped. → (the styles, the names in `src` of those skipped)
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"];
|
||||
const RANGED: [&str; 16] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"baseline_shift",
|
||||
"tcyUpDown",
|
||||
"tcyLeftRight",
|
||||
"stroke_width",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
"space_before",
|
||||
"space_after",
|
||||
"hyphenation",
|
||||
"justification",
|
||||
"tabs",
|
||||
];
|
||||
let (mut defs, mut skipped) = (vec![], vec![]);
|
||||
for def in kind.defs(src) {
|
||||
let name = def.name.as_str();
|
||||
|
||||
@@ -1729,3 +1729,77 @@ fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
|
||||
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept
|
||||
/// as it is, and a stop at a held position with another alignment is a changed stop. A changed
|
||||
/// stop's leader has at most eight characters and its Align On one character, a changed list has
|
||||
/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position,
|
||||
/// keeping the first of stops at one position.
|
||||
#[test]
|
||||
fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
|
||||
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let held: Vec<Value> =
|
||||
(0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect();
|
||||
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone()));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let mut moved = held.clone();
|
||||
moved[0]["align"] = json!("right");
|
||||
for (stops, why) in [
|
||||
(Value::from(moved), "`tabs.position`"),
|
||||
(json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"),
|
||||
(Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"),
|
||||
(json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"),
|
||||
] {
|
||||
for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] {
|
||||
let params = match cmd {
|
||||
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}),
|
||||
_ => json!({"name": "Body", "attrs": {"tabs": stops}}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(why), "{cmd}: {error}");
|
||||
}
|
||||
}
|
||||
let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>());
|
||||
let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string();
|
||||
assert!(error.contains("at most 256 tab stops"), "{error}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// The held stops stay while one is dropped and another attribute changes.
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299));
|
||||
let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap();
|
||||
assert_eq!(
|
||||
def(&s)["tabs"],
|
||||
json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."},
|
||||
{"position": 72.0, "align": "right", "alignOn": "."}])
|
||||
);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set");
|
||||
}
|
||||
|
||||
/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing,
|
||||
/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes,
|
||||
/// and load the others with their stops.
|
||||
#[test]
|
||||
fn loading_skips_paragraph_styles_out_of_range() {
|
||||
let file = [
|
||||
("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})),
|
||||
("Indent", json!({"left_indent": 2000.0})),
|
||||
("Space", json!({"space_after": -1300.0})),
|
||||
("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})),
|
||||
("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})),
|
||||
("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})),
|
||||
];
|
||||
let data = styles_file(&[], &file);
|
||||
for cmd in ["paraStyle.load", "textStyle.loadAll"] {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r };
|
||||
assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}");
|
||||
let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap();
|
||||
assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user