mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-09 00:17:58 +00:00
M4: a paragraph's base direction can be forced: Text ▸ Text direction (#1830)
Direction came from the letters only; Add right-to-left text says controls override it per paragraph (Text > Text direction, Left to right or Right to left). `TextDirection` on `ParaList`, `Bidi::of` with a base level per paragraph, `text.direction` and the three menu commands (the edited paragraphs while editing), `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect `textDirection` / `lineDirections`, the CSS `direction`, and the `.fig` lines' `sourceDirectionality` in and out. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
f05e568498
commit
cd5c9aeb09
@@ -132,6 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-11-05** · M4, #1830: a paragraph's base direction can be forced (Text ▸ Text direction: Auto, Left to right, Right to left) as Add right-to-left text says ("controls are available to override text direction per paragraph"). `ParaList::direction`, `text.direction {direction, ids?}` and the three menu commands (the edited paragraphs while editing, else the layer's), `node.set textDirection`, the Type settings control once a right-to-left script is in the text, `textDirection` / `lineDirections` in inspect, the CSS `direction`, and the `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` per paragraph). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests`.
|
||||
- **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged.
|
||||
- **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged.
|
||||
- **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged.
|
||||
|
||||
+23
-6
@@ -259,10 +259,24 @@ pub enum ListStyle {
|
||||
Numbered,
|
||||
}
|
||||
|
||||
/// A paragraph's base direction: by its letters, or forced ("controls are available to override
|
||||
/// text direction per paragraph", Add right-to-left text).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextDirection {
|
||||
/// The first letter with a direction decides (Unicode rules P2 and P3).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Left to right, whatever the letters.
|
||||
Ltr,
|
||||
/// Right to left, whatever the letters.
|
||||
Rtl,
|
||||
}
|
||||
|
||||
/// Deepest list nesting (levels 0..=MAX_LIST_INDENT).
|
||||
pub const MAX_LIST_INDENT: u8 = 8;
|
||||
|
||||
/// One paragraph's list settings.
|
||||
/// One paragraph's list settings and base direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct ParaList {
|
||||
@@ -276,6 +290,9 @@ pub struct ParaList {
|
||||
/// (items that go on counting ignore it; other paragraphs are always 0).
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub start_offset: u32,
|
||||
/// The paragraph's base direction (Text ▸ Text direction); `Auto` follows its letters.
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub direction: TextDirection,
|
||||
}
|
||||
|
||||
/// Character style. In runs, every field is an override; `None` means "inherit the base".
|
||||
@@ -991,20 +1008,20 @@ mod case_tests {
|
||||
// Files written before start numbers load with none, and write the same bytes.
|
||||
let old = r#"{"list":"numbered","indent":1}"#;
|
||||
let pl: ParaList = serde_json::from_str(old).unwrap();
|
||||
assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 });
|
||||
assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0, ..ParaList::default() });
|
||||
assert_eq!(serde_json::to_string(&pl).unwrap(), old);
|
||||
// One numbered paragraph with a start keeps it (it doesn't fold into `list`).
|
||||
let mut t = TextData { characters: "Next".into(), ..Default::default() };
|
||||
t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 });
|
||||
assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 });
|
||||
t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() });
|
||||
assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() });
|
||||
// Enter copies it to the new item; different starts don't make the list mixed.
|
||||
t.replace_range(4, 4, "\nMore");
|
||||
assert_eq!(t.para_list(1).start_offset, 1);
|
||||
t.set_para_lists(5, 5, |p| p.start_offset = 0);
|
||||
assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N));
|
||||
// Bullets have no number, so no start.
|
||||
t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 });
|
||||
assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 });
|
||||
t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4, ..ParaList::default() });
|
||||
assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0, ..ParaList::default() });
|
||||
// A plain paragraph has none.
|
||||
t.set_para_lists(0, 0, |p| p.list = P);
|
||||
assert_eq!(t.para_list(0), ParaList::default());
|
||||
|
||||
@@ -53,6 +53,7 @@ pub const NODE_KEYS: &[&str] = &[
|
||||
"layout",
|
||||
"leadingTrim",
|
||||
"letterSpacing",
|
||||
"lineDirections",
|
||||
"lineHeight",
|
||||
"lineIndentations",
|
||||
"lineTypes",
|
||||
@@ -96,6 +97,7 @@ pub const NODE_KEYS: &[&str] = &[
|
||||
"textDecorationSkipInk",
|
||||
"textDecorationStyle",
|
||||
"textDecorationThickness",
|
||||
"textDirection",
|
||||
"textPath",
|
||||
"textStyleRanges",
|
||||
"type",
|
||||
@@ -432,6 +434,16 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
|
||||
insert_prop(o, options, "listStartOffsets", || t.paragraphs.iter().map(|p| json!(p.start_offset)).collect());
|
||||
}
|
||||
}
|
||||
// The paragraphs' base direction: one for the layer when they agree, else each one's (Auto
|
||||
// throughout says nothing).
|
||||
let dirs: Vec<figcraft_doc::TextDirection> = t.paragraphs.iter().map(|p| p.direction).collect();
|
||||
if let Some(first) = dirs.first().copied().filter(|d| *d != figcraft_doc::TextDirection::Auto)
|
||||
&& dirs.iter().all(|d| *d == first)
|
||||
{
|
||||
insert_prop(o, options, "textDirection", || json!(first));
|
||||
} else if dirs.iter().any(|d| *d != figcraft_doc::TextDirection::Auto) {
|
||||
insert_prop(o, options, "lineDirections", || dirs.iter().map(|d| json!(d)).collect());
|
||||
}
|
||||
if t.list_spacing != 0.0 {
|
||||
insert_prop(o, options, "listSpacing", || json!(t.list_spacing));
|
||||
}
|
||||
|
||||
@@ -216,6 +216,11 @@ pub static MENU: &[MenuItem] = &[
|
||||
m!("Text/Case", "Uppercase", "text.caseUpper"),
|
||||
m!("Text/Case", "Lowercase", "text.caseLower"),
|
||||
m!("Text/Case", "Title case", "text.caseTitle"),
|
||||
// "Go to Text > Text direction. Select Left to right or Right to left." (Add right-to-left
|
||||
// text); Auto, the way back to detection, is FigCraft's own (in `OWN`).
|
||||
m!("Text/Text direction", "Auto", "text.directionAuto"),
|
||||
m!("Text/Text direction", "Left to right", "text.directionLtr"),
|
||||
m!("Text/Text direction", "Right to left", "text.directionRtl"),
|
||||
m!("Text", SEP, ""),
|
||||
m!("Text", "Missing fonts…", "text.missingFonts"),
|
||||
// Arrange
|
||||
@@ -292,7 +297,7 @@ pub fn items() -> impl Iterator<Item = &'static MenuItem> {
|
||||
}
|
||||
|
||||
/// Items of FigCraft's own that the parity count leaves out (as it does the `collab.` ones).
|
||||
const OWN: [&str; 5] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop"];
|
||||
const OWN: [&str; 6] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop", "text.directionAuto"];
|
||||
|
||||
/// Coverage: (implemented, total, missing ids). `extra` lists ids implemented by the UI layer.
|
||||
pub fn parity(extra: &[&str]) -> (usize, usize, Vec<&'static str>) {
|
||||
|
||||
@@ -956,6 +956,12 @@ fn apply_text(cmd: &str, doc: &mut Document, id: NodeId, props: &Map<String, Val
|
||||
t.set_para_lists(start, end, |p| p.indent = d.clamp(0.0, f64::from(MAX_LIST_INDENT)) as u8);
|
||||
}
|
||||
}
|
||||
"textDirection" | "direction" => {
|
||||
let d: figcraft_doc::TextDirection = enum_of(v).ok_or_else(|| bad(cmd, "textDirection: auto|ltr|rtl"))?;
|
||||
let t = text_mut(cmd, doc.get_mut(id)?)?;
|
||||
let (start, end) = range_of(props, t.char_count());
|
||||
t.set_para_lists(start, end, |p| p.direction = d);
|
||||
}
|
||||
"listSpacing" => text_mut(cmd, doc.get_mut(id)?)?.list_spacing = f64_of(v).filter(|s| s.is_finite()).unwrap_or(0.0).clamp(0.0, 10_000.0),
|
||||
"hangingPunctuation" | "hangingList" => {
|
||||
let on = v.as_bool().ok_or_else(|| bad(cmd, format!("`{k}` must be true or false")))?;
|
||||
@@ -1210,7 +1216,7 @@ pub fn override_group(k: &str) -> &'static str {
|
||||
"name" => "name",
|
||||
"characters" | "text" => "characters",
|
||||
"features" | "fontFeatures" | "openTypeFeatures" | "listStyle" | "indentation" | "listSpacing" | "maxLines" | "variationSettings"
|
||||
| "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" => "textStyle",
|
||||
| "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" | "textDirection" | "direction" => "textStyle",
|
||||
"cornerRadius" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "corners",
|
||||
"width" | "height" | "w" | "h" => "size",
|
||||
"sizingH" | "sizingV" | "layoutSizingHorizontal" | "layoutSizingVertical" | "minWidth" | "maxWidth" | "minHeight" | "maxHeight" => "resizing",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Text menu and text editing commands.
|
||||
|
||||
use figcraft_doc::{
|
||||
LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, TextPath, TextStyle,
|
||||
VariableId,
|
||||
LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextPath,
|
||||
TextStyle, VariableId,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -91,6 +91,13 @@ fn set_list(s: &mut Session, p: &Value, l: ListStyle, toggle: bool) -> Result<Va
|
||||
para_range(s, p, |t, a, b| t.set_para_lists(a, b, |pl| pl.list = l))
|
||||
}
|
||||
|
||||
/// The base direction of the targeted paragraphs: the edited ones while editing, else every
|
||||
/// paragraph of the targeted texts ("controls are available to override text direction per
|
||||
/// paragraph", Add right-to-left text, #1830).
|
||||
fn set_direction(s: &mut Session, p: &Value, d: TextDirection) -> Result<Value> {
|
||||
para_range(s, p, |t, a, b| t.set_para_lists(a, b, |pl| pl.direction = d))
|
||||
}
|
||||
|
||||
/// Whether every targeted char has `pred` (to decide toggle direction).
|
||||
fn all_have(s: &Session, p: &Value, pred: impl Fn(&TextStyle) -> bool) -> bool {
|
||||
let Ok(doc) = s.doc() else { return false };
|
||||
@@ -319,6 +326,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
para(s, p, |t| t.wrap_style = w)
|
||||
}
|
||||
),
|
||||
spec!(
|
||||
"text.direction",
|
||||
"Text direction",
|
||||
"{direction: auto|ltr|rtl, ids?} the base direction of the paragraphs (while editing: the selected ones): auto goes by the first letter with a direction, ltr runs them left to right and rtl right to left whatever their letters (Text ▸ Text direction)",
|
||||
true,
|
||||
|s, p| {
|
||||
let d: TextDirection =
|
||||
get(p, "direction").and_then(super::props::enum_of).ok_or_else(|| bad("text.direction", "`direction`: auto|ltr|rtl"))?;
|
||||
set_direction(s, p, d)
|
||||
}
|
||||
),
|
||||
spec!("text.directionAuto", "Text direction: auto", "{ids?} while editing: the selected paragraphs", true, |s, p| {
|
||||
set_direction(s, p, TextDirection::Auto)
|
||||
}),
|
||||
spec!("text.directionLtr", "Text direction: left to right", "{ids?} while editing: the selected paragraphs", true, |s, p| {
|
||||
set_direction(s, p, TextDirection::Ltr)
|
||||
}),
|
||||
spec!("text.directionRtl", "Text direction: right to left", "{ids?} while editing: the selected paragraphs", true, |s, p| {
|
||||
set_direction(s, p, TextDirection::Rtl)
|
||||
}),
|
||||
spec!("text.paragraphIndent", "Paragraph indent", "{indent (px), ids?}", true, |s, p| {
|
||||
let v = finite(req_num("text.paragraphIndent", p, "indent")?).clamp(0.0, 10_000.0);
|
||||
para(s, p, |t| t.paragraph_indent = v)
|
||||
|
||||
@@ -307,6 +307,13 @@ fn text_decls(doc: &Document, n: &Node, tx: &figcraft_doc::TextData, t: &mut Tok
|
||||
figcraft_doc::WrapStyle::Balance => put("text-wrap", "balance".into()),
|
||||
figcraft_doc::WrapStyle::Pretty => put("text-wrap", "pretty".into()),
|
||||
}
|
||||
// A base direction forced on every paragraph (CSS has one per element).
|
||||
let dir = tx.paragraphs.first().map(|p| p.direction).filter(|d| tx.paragraphs.iter().all(|p| p.direction == *d));
|
||||
match dir {
|
||||
Some(figcraft_doc::TextDirection::Ltr) => put("direction", "ltr".into()),
|
||||
Some(figcraft_doc::TextDirection::Rtl) => put("direction", "rtl".into()),
|
||||
_ => {}
|
||||
}
|
||||
match s.case {
|
||||
TextCase::Original => {}
|
||||
TextCase::Upper => put("text-transform", "uppercase".into()),
|
||||
|
||||
@@ -371,6 +371,57 @@ fn max_lines_on_auto_height_text_hugs_that_many_lines() {
|
||||
assert_eq!(resize_mode(&s, fixed), TextAutoResize::Truncate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_direction_is_forced_per_paragraph() {
|
||||
// Add right-to-left text: "By default, Figma automatically handles text direction based on
|
||||
// language detection. However, controls are available to override text direction per
|
||||
// paragraph" ("Go to Text > Text direction. Select Left to right or Right to left.").
|
||||
let font = test_mono_font();
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, "abc def\nghi\njkl", json!({"fontFamily": font, "fontSize": 16, "lineHeight": 24}));
|
||||
let rtl = |s: &Session| -> Vec<bool> {
|
||||
let (l, _) = figcraft_text::layout_node(s.doc().unwrap().node(t).unwrap()).unwrap();
|
||||
l.lines.iter().map(|l| l.rtl).collect()
|
||||
};
|
||||
let inspect = |s: &Session| crate::inspect::node_json(s.doc().unwrap(), t, 0);
|
||||
assert_eq!(rtl(&s), [false, false, false], "Latin letters read left to right");
|
||||
assert!(inspect(&s).get("textDirection").is_none() && inspect(&s).get("lineDirections").is_none());
|
||||
// The layer's paragraphs at once, by the command or `node.set`; inspect reports the one
|
||||
// direction they share, and Dev Mode's CSS has it.
|
||||
s.execute("text.direction", &json!({"ids": [t], "direction": "rtl"})).unwrap();
|
||||
assert_eq!(rtl(&s), [true, true, true], "forced right to left whatever the letters");
|
||||
assert_eq!(inspect(&s)["textDirection"], json!("rtl"));
|
||||
let css = |s: &mut Session| s.execute("inspect.code", &json!({"id": t})).unwrap()["code"].as_str().unwrap().to_string();
|
||||
assert!(css(&mut s).contains("direction: rtl;"), "{}", css(&mut s));
|
||||
s.execute("node.set", &json!({"id": t, "props": {"textDirection": "ltr"}})).unwrap();
|
||||
assert_eq!(rtl(&s), [false, false, false]);
|
||||
assert_eq!(inspect(&s)["textDirection"], json!("ltr"));
|
||||
assert!(css(&mut s).contains("direction: ltr;"));
|
||||
s.execute("text.directionAuto", &json!({"ids": [t]})).unwrap();
|
||||
assert!(inspect(&s).get("textDirection").is_none(), "auto throughout says nothing");
|
||||
assert!(!css(&mut s).contains("direction:"));
|
||||
// While editing, the caret's paragraph alone (the menu's Right to left); inspect lists each
|
||||
// paragraph's direction when they differ, and the CSS stays quiet.
|
||||
s.execute("text.edit.begin", &json!({"id": t, "caret": 9})).unwrap();
|
||||
s.execute("text.directionRtl", &json!({})).unwrap();
|
||||
s.execute("text.edit.end", &json!({})).unwrap();
|
||||
assert_eq!(rtl(&s), [false, true, false], "the second paragraph only");
|
||||
assert_eq!(inspect(&s)["lineDirections"], json!(["auto", "rtl", "auto"]));
|
||||
assert!(!css(&mut s).contains("direction:"));
|
||||
// Enter inside a forced paragraph keeps the direction for the new one, as list settings carry.
|
||||
s.execute("text.edit.begin", &json!({"id": t, "caret": 10})).unwrap();
|
||||
s.execute("text.edit.insert", &json!({"text": "\n"})).unwrap();
|
||||
s.execute("text.edit.end", &json!({})).unwrap();
|
||||
assert_eq!(rtl(&s), [false, true, true, false]);
|
||||
// A direction the document has words for; junk is refused.
|
||||
s.execute("node.set", &json!({"id": t, "props": {"characters": "\u{05E9}\u{05DC}\u{05D5}\u{05DD} abc", "textDirection": "auto"}})).unwrap();
|
||||
assert_eq!(rtl(&s), [true], "Hebrew first: right to left by detection");
|
||||
s.execute("node.set", &json!({"id": t, "props": {"textDirection": "ltr"}})).unwrap();
|
||||
assert_eq!(rtl(&s), [false], "forced left to right");
|
||||
assert!(s.execute("node.set", &json!({"id": t, "props": {"textDirection": "sideways"}})).is_err());
|
||||
assert!(s.execute("text.direction", &json!({"ids": [t], "direction": "up"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_and_pretty_wrap_styles_break_lines_as_documented() {
|
||||
// Explore text properties: "Auto: Figma fits as many words as possible on each line before
|
||||
|
||||
@@ -64,7 +64,7 @@ fn a_list_with_a_start_number_toggles_off() {
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, "two\nthree\nfour");
|
||||
if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind {
|
||||
let n = |start_offset| ParaList { list: N, indent: 0, start_offset };
|
||||
let n = |start_offset| ParaList { list: N, indent: 0, start_offset, ..ParaList::default() };
|
||||
td.paragraphs = vec![n(1), n(0), n(0)];
|
||||
}
|
||||
let j = crate::inspect::node_json(s.doc().unwrap(), t, 0);
|
||||
@@ -157,7 +157,8 @@ fn list_keys_at_list_items() {
|
||||
for (chars, before, caret, k, shift, after, want, why) in cases {
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, chars);
|
||||
let ps: Vec<ParaList> = before.iter().map(|(list, indent)| ParaList { list: *list, indent: *indent, start_offset: 0 }).collect();
|
||||
let ps: Vec<ParaList> =
|
||||
before.iter().map(|(list, indent)| ParaList { list: *list, indent: *indent, start_offset: 0, ..ParaList::default() }).collect();
|
||||
if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind {
|
||||
td.paragraphs = ps;
|
||||
}
|
||||
@@ -181,7 +182,11 @@ fn paragraph_lists_follow_edits() {
|
||||
// A paragraph's list stays with it as text is typed, pasted and deleted: new paragraphs copy
|
||||
// the one they split from; joined paragraphs keep the first one's.
|
||||
let mut t = TextData::new("ab\ncd\nef");
|
||||
t.paragraphs = vec![ParaList { list: B, indent: 1, start_offset: 0 }, ParaList::default(), ParaList { list: N, indent: 0, start_offset: 0 }];
|
||||
t.paragraphs = vec![
|
||||
ParaList { list: B, indent: 1, start_offset: 0, ..ParaList::default() },
|
||||
ParaList::default(),
|
||||
ParaList { list: N, indent: 0, start_offset: 0, ..ParaList::default() },
|
||||
];
|
||||
let get = |t: &TextData| (0..t.paragraph_count()).map(|p| (t.para_list(p).list, t.para_list(p).indent)).collect::<Vec<_>>();
|
||||
t.replace_range(1, 1, "x\ny");
|
||||
assert_eq!(get(&t), [(B, 1), (B, 1), (P, 0), (N, 0)], "a pasted newline: a new item like it");
|
||||
@@ -196,7 +201,7 @@ fn paragraph_lists_follow_edits() {
|
||||
(seed >> 33) as usize % n.max(1)
|
||||
};
|
||||
let mut t = TextData::new("a\nb\nc\nd");
|
||||
t.paragraphs = vec![ParaList { list: B, indent: 2, start_offset: 0 }; 4];
|
||||
t.paragraphs = vec![ParaList { list: B, indent: 2, start_offset: 0, ..ParaList::default() }; 4];
|
||||
for _ in 0..500 {
|
||||
let n = t.char_count();
|
||||
let (a, b) = (rnd(n + 2), rnd(n + 2));
|
||||
|
||||
@@ -27,8 +27,8 @@ use figcraft_doc::proto::{
|
||||
use figcraft_doc::{
|
||||
AutoLayout, BoolOp, ContentAlign, CrossAlign, Document, EffectKind, ExportSize, GridAlign, GridKind, GridTrack, HConstraint, LayoutMode,
|
||||
LetterSpacing, LineHeight, ListStyle, MainAlign, MaskType, Node, NodeId, NodeKind, NoiseMode, PropDef, Sizing, StrokeAlign, StrokeCap,
|
||||
StrokeJoin, StyleKind, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, VariableType,
|
||||
VariableValue, VectorNetwork, WindingRule,
|
||||
StrokeJoin, StyleKind, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextStyle, VConstraint,
|
||||
VariableType, VariableValue, VectorNetwork, WindingRule,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use sha1::Digest;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::common::{style_fields, unsupported_decoration_look};
|
||||
use super::{
|
||||
Affine, BezPath, Bound, Exporter, Fields, Kv, ListStyle, MAX_CANVAS, MAX_CHARS, MAX_NETWORK, Node, NodeKind, Paint, StrokeAlign, StrokeCap,
|
||||
StrokeJoin, TextAlignH, TextAlignV, TextAutoResize, TextData, TextStyle, VectorNetwork, WindingRule, arr, b, cap_name, e, finite, fl, int,
|
||||
join_name, network, o, path_blob, s, u, xy,
|
||||
StrokeJoin, TextAlignH, TextAlignV, TextAutoResize, TextData, TextDirection, TextStyle, VectorNetwork, WindingRule, arr, b, cap_name, e, finite,
|
||||
fl, int, join_name, network, o, path_blob, s, u, xy,
|
||||
};
|
||||
|
||||
impl<'d> Exporter<'d> {
|
||||
@@ -128,11 +128,16 @@ impl<'d> Exporter<'d> {
|
||||
let listed = *l != ListStyle::None;
|
||||
let begins = first(i, l);
|
||||
let start = starts.get(i).copied().unwrap_or(0);
|
||||
let direction = match td.para_list(i).direction {
|
||||
TextDirection::Auto => "AUTO",
|
||||
TextDirection::Ltr => "LTR",
|
||||
TextDirection::Rtl => "RTL",
|
||||
};
|
||||
o(vec![
|
||||
("lineType", e(ty)),
|
||||
("styleId", int(0)),
|
||||
("indentationLevel", int(i64::from(listed))),
|
||||
("sourceDirectionality", e("AUTO")),
|
||||
("sourceDirectionality", e(direction)),
|
||||
("listStartOffset", int(i64::from(start))),
|
||||
("isFirstLineOfList", b(begins)),
|
||||
])
|
||||
|
||||
@@ -130,6 +130,18 @@ impl<'a> Mapper<'a> {
|
||||
if lines.iter().any(|l| *l != "NONE") {
|
||||
o.insert("lineTypes".into(), json!(lines));
|
||||
}
|
||||
// A forced base direction per paragraph (`sourceDirectionality`; not a REST field).
|
||||
let dirs: Vec<&str> = raw
|
||||
.iter()
|
||||
.map(|l| match l.get("sourceDirectionality").and_then(Kv::str) {
|
||||
Some("LTR") => "LTR",
|
||||
Some("RTL") => "RTL",
|
||||
_ => "AUTO",
|
||||
})
|
||||
.collect();
|
||||
if dirs.iter().any(|d| *d != "AUTO") {
|
||||
o.insert("lineDirections".into(), json!(dirs));
|
||||
}
|
||||
// Where a numbered list starts counting, less one (not a REST field).
|
||||
let starts: Vec<u32> =
|
||||
raw.iter().map(|l| num(l, "listStartOffset").filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32)).collect();
|
||||
|
||||
@@ -1491,6 +1491,9 @@ mod image_filters;
|
||||
#[path = "text_list_tests.rs"]
|
||||
mod text_list;
|
||||
|
||||
#[path = "text_direction_tests.rs"]
|
||||
mod text_direction;
|
||||
|
||||
/// `.fig` files in the folder `FIGCRAFT_FIG_SAMPLES` names (none when it's unset).
|
||||
pub(super) fn samples() -> Vec<std::path::PathBuf> {
|
||||
let Some(dir) = std::env::var_os("FIGCRAFT_FIG_SAMPLES") else { return Vec::new() };
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! A paragraph's forced base direction (#1830): each text line's `sourceDirectionality` (AUTO,
|
||||
//! LTR or RTL) comes in as the paragraph's direction and goes back out. Fixtures built in code with
|
||||
//! the parent module's helpers.
|
||||
|
||||
use figcraft_doc::{NodeKind, TextDirection};
|
||||
|
||||
use super::*;
|
||||
|
||||
const DIRECTION_SCHEMA: &str = "
|
||||
enum NodeType NONE DOCUMENT CANVAS TEXT
|
||||
enum LineType PLAIN ORDERED_LIST UNORDERED_LIST
|
||||
enum SourceDirectionality AUTO LTR RTL
|
||||
struct GUID uint sessionID, uint localID
|
||||
struct Vector float x, float y
|
||||
struct Matrix float m00, float m01, float m02, float m10, float m11, float m12
|
||||
message ParentIndex GUID guid, string position
|
||||
message TextLineData LineType lineType, int indentationLevel, SourceDirectionality sourceDirectionality, int listStartOffset, bool isFirstLineOfList
|
||||
message TextData string characters, TextLineData[] lines
|
||||
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, float fontSize, TextData textData
|
||||
message Message NodeChange[] nodeChanges
|
||||
";
|
||||
|
||||
/// A plain line with a base direction.
|
||||
fn line(direction: &'static str) -> Kv<'static> {
|
||||
o(vec![
|
||||
("lineType", e("PLAIN")),
|
||||
("indentationLevel", Kv::Int(0)),
|
||||
("sourceDirectionality", e(direction)),
|
||||
("listStartOffset", Kv::Int(0)),
|
||||
("isFirstLineOfList", Kv::Bool(false)),
|
||||
])
|
||||
}
|
||||
|
||||
fn text_node(id: u64, name: &str, chars: &str, lines: Vec<Kv<'static>>) -> Kv<'static> {
|
||||
let pos = ["!", "\"", "#", "$"][id as usize % 4];
|
||||
node(
|
||||
id,
|
||||
Some((1, pos)),
|
||||
"TEXT",
|
||||
name,
|
||||
vec![
|
||||
("size", xy(200.0, 60.0)),
|
||||
("transform", at(0.0, 0.0)),
|
||||
("fontSize", f(16.0)),
|
||||
("textData", o(vec![("characters", s(chars)), ("lines", arr(lines))])),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn directions(doc: &figcraft_doc::Document, name: &str) -> Vec<TextDirection> {
|
||||
let NodeKind::Text(t) = &named(doc, name).kind else { panic!("{name} is no text") };
|
||||
(0..t.paragraph_count()).map(|p| t.para_list(p).direction).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lines_source_directionality_is_its_paragraphs_direction_both_ways() {
|
||||
use TextDirection::{Auto as A, Ltr as L, Rtl as R};
|
||||
let nodes = vec![
|
||||
node(0, None, "DOCUMENT", "Document", vec![]),
|
||||
node(1, Some((0, "!")), "CANVAS", "Page", vec![]),
|
||||
text_node(2, "Detected", "abc\ndef", vec![line("AUTO"), line("AUTO")]),
|
||||
text_node(3, "Forced", "abc\ndef\nghi", vec![line("RTL"), line("AUTO"), line("LTR")]),
|
||||
];
|
||||
let sc = Schema::parse(DIRECTION_SCHEMA).unwrap();
|
||||
let (doc, warnings) = import(&canvas(&sc, &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert_eq!(directions(&doc, "Detected"), [A, A]);
|
||||
let NodeKind::Text(t) = &named(&doc, "Detected").kind else { panic!() };
|
||||
assert!(t.paragraphs.is_empty(), "AUTO throughout keeps the paragraphs folded");
|
||||
assert_eq!(directions(&doc, "Forced"), [R, A, L]);
|
||||
// Out again: every line says its direction, and a reader gets the same paragraphs back.
|
||||
let (bytes, _) = super::super::export(&doc, None).unwrap();
|
||||
let a = Archive::open(&bytes).unwrap();
|
||||
let (schema, message) = decode_canvas(&a.canvas).unwrap();
|
||||
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
|
||||
let text = msg.get("nodeChanges").unwrap().list().iter().find(|n| n.get("name").and_then(Kv::str) == Some("Forced")).unwrap();
|
||||
let lines = text.get("textData").and_then(|d| d.get("lines")).map(Kv::list).unwrap();
|
||||
let out: Vec<&str> = lines.iter().map(|l| l.get("sourceDirectionality").and_then(Kv::str).unwrap()).collect();
|
||||
assert_eq!(out, ["RTL", "AUTO", "LTR"]);
|
||||
let (back, _) = import(&bytes, "x").unwrap();
|
||||
assert_eq!(directions(&back, "Forced"), [R, A, L]);
|
||||
assert_eq!(directions(&back, "Detected"), [A, A]);
|
||||
}
|
||||
@@ -75,7 +75,7 @@ fn the_export_writes_where_a_list_starts() {
|
||||
let page = doc.first_page().unwrap();
|
||||
use ListStyle::{Bulleted as B, None as P, Numbered as N};
|
||||
let mut td = figcraft_doc::TextData::new("two\nthree\nplain\nsix\ndot");
|
||||
let pl = |list, start_offset| ParaList { list, indent: 0, start_offset };
|
||||
let pl = |list, start_offset| ParaList { list, indent: 0, start_offset, ..ParaList::default() };
|
||||
td.paragraphs = vec![pl(N, 1), pl(N, 0), pl(P, 0), pl(N, 5), pl(B, 4)];
|
||||
doc.create(page, NodeKind::Text(td), "List", 0.0, 0.0, 200.0, 80.0).unwrap();
|
||||
let (bytes, _) = super::super::export(&doc, None).unwrap();
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use figcraft_doc::{
|
||||
DecorationLength, DecorationStyle, LetterSpacing, LineHeight, ListStyle, ParaList, StyleRun, TextAlignH, TextAlignV, TextAutoResize, TextCase,
|
||||
TextData, TextDecoration, TextPath, TextStyle,
|
||||
TextData, TextDecoration, TextDirection, TextPath, TextStyle,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -256,23 +256,27 @@ fn runs(cx: &mut Ctx, v: &Value, td: &TextData) -> Vec<StyleRun> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Each paragraph's list type, nesting level and start number from `lineTypes`,
|
||||
/// `lineIndentations` and (from `.fig` files) `listStartOffsets`.
|
||||
/// Each paragraph's list type, nesting level, start number and base direction from `lineTypes`,
|
||||
/// `lineIndentations` and (from `.fig` files) `listStartOffsets` and `lineDirections`.
|
||||
fn lists(v: &Value, td: &mut TextData) {
|
||||
let types = list(v, "lineTypes");
|
||||
let indents = list(v, "lineIndentations");
|
||||
let starts = list(v, "listStartOffsets");
|
||||
td.paragraphs = types
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| ParaList {
|
||||
list: match t.as_str() {
|
||||
let dirs = list(v, "lineDirections");
|
||||
td.paragraphs = (0..types.len().max(dirs.len()))
|
||||
.map(|i| ParaList {
|
||||
list: match types.get(i).and_then(Value::as_str) {
|
||||
Some("UNORDERED") => ListStyle::Bulleted,
|
||||
Some("ORDERED") => ListStyle::Numbered,
|
||||
_ => ListStyle::None,
|
||||
},
|
||||
indent: indents.get(i).and_then(Value::as_f64).filter(|d| d.is_finite()).map_or(0, |d| d.clamp(0.0, 255.0) as u8),
|
||||
start_offset: starts.get(i).and_then(Value::as_f64).filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32),
|
||||
direction: match dirs.get(i).and_then(Value::as_str) {
|
||||
Some("LTR") => TextDirection::Ltr,
|
||||
Some("RTL") => TextDirection::Rtl,
|
||||
_ => TextDirection::Auto,
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
// Clamp the levels and fold one style for all back into the layer's list style.
|
||||
|
||||
@@ -109,7 +109,7 @@ fn a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does() {
|
||||
if face().is_none() {
|
||||
return;
|
||||
}
|
||||
let level = |list: ListStyle, indent: u8| ParaList { list, indent, start_offset: 0 };
|
||||
let level = |list: ListStyle, indent: u8| ParaList { list, indent, start_offset: 0, ..ParaList::default() };
|
||||
let mut t = text("a\nb\nc", TextAutoResize::WidthAndHeight);
|
||||
t.paragraphs = vec![level(ListStyle::Bulleted, 1), level(ListStyle::None, 1), level(ListStyle::None, 0)];
|
||||
let l = layout(&t, None, None);
|
||||
|
||||
+33
-13
@@ -6,7 +6,7 @@ use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::{
|
||||
DecorationLength, DecorationStyle, LeadingTrim, LetterSpacing, LineHeight, ListStyle, ParaList, TextAlignH, TextAutoResize, TextCase, TextData,
|
||||
TextDecoration, TextStyle, WrapStyle, color::PaintKind, valid_feature_tag,
|
||||
TextDecoration, TextDirection, TextStyle, WrapStyle, color::PaintKind, valid_feature_tag,
|
||||
};
|
||||
use figcraft_geom::{Affine, BezPath, Rect};
|
||||
use harfrust::{Direction, Feature, ShapeOptions, ShaperInstance, Tag, UnicodeBuffer, Variation};
|
||||
@@ -272,21 +272,29 @@ pub(crate) struct Bidi {
|
||||
}
|
||||
|
||||
impl Bidi {
|
||||
/// None when the text has nothing right to left (the common case costs one scan).
|
||||
pub(crate) fn of(text: &str) -> Option<Bidi> {
|
||||
if !text.chars().any(is_rtl_char) {
|
||||
/// None when the text has nothing right to left and no paragraph forces its direction (the
|
||||
/// common case costs one scan). `forced`, by paragraph: `Some(true)` runs right to left and
|
||||
/// `Some(false)` left to right whatever the letters, `None` goes by the first letter with a
|
||||
/// direction (Text ▸ Text direction, #1830).
|
||||
pub(crate) fn of(text: &str, forced: &[Option<bool>]) -> Option<Bidi> {
|
||||
if forced.iter().all(Option::is_none) && !text.chars().any(is_rtl_char) {
|
||||
return None;
|
||||
}
|
||||
let info = unicode_bidi::BidiInfo::new(text, None);
|
||||
let mut paras = info.paragraphs.iter().peekable();
|
||||
let n = text.chars().count();
|
||||
let (mut levels, mut rtl_para) = (Vec::with_capacity(n), Vec::with_capacity(n));
|
||||
for (b, _) in text.char_indices() {
|
||||
while paras.peek().is_some_and(|p| p.range.end <= b) {
|
||||
paras.next();
|
||||
// Paragraph by paragraph (the algorithm starts over at each one), so each can be given its
|
||||
// base level.
|
||||
for (p, para) in text.split_inclusive('\n').enumerate() {
|
||||
let base = forced.get(p).copied().flatten().map(|rtl| if rtl { unicode_bidi::Level::rtl() } else { unicode_bidi::Level::ltr() });
|
||||
let info = unicode_bidi::BidiInfo::new(para, base);
|
||||
let mut paras = info.paragraphs.iter().peekable();
|
||||
for (b, _) in para.char_indices() {
|
||||
while paras.peek().is_some_and(|q| q.range.end <= b) {
|
||||
paras.next();
|
||||
}
|
||||
levels.push(info.levels.get(b).map(|l| l.number()).unwrap_or(0));
|
||||
rtl_para.push(paras.peek().is_some_and(|q| q.level.is_rtl()));
|
||||
}
|
||||
levels.push(info.levels.get(b).map(|l| l.number()).unwrap_or(0));
|
||||
rtl_para.push(paras.peek().is_some_and(|p| p.level.is_rtl()));
|
||||
}
|
||||
Some(Bidi { levels, rtl_para })
|
||||
}
|
||||
@@ -479,8 +487,20 @@ fn shape_text(text: &TextData) -> ShapedText {
|
||||
.filter_map(|(k, on)| <[u8; 4]>::try_from(k.as_bytes()).ok().map(|t| Feature::new(Tag::new(&t), u32::from(*on), ..)))
|
||||
.collect();
|
||||
|
||||
// Shape each span, split by paragraph, bidi run and fallback face.
|
||||
let bidi = Bidi::of(&text.characters);
|
||||
// Shape each span, split by paragraph, bidi run and fallback face. A paragraph's direction is
|
||||
// its letters' unless forced (Text ▸ Text direction).
|
||||
let forced: Vec<Option<bool>> = if text.paragraphs.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
(0..text.paragraph_count())
|
||||
.map(|p| match text.para_list(p).direction {
|
||||
TextDirection::Auto => None,
|
||||
TextDirection::Ltr => Some(false),
|
||||
TextDirection::Rtl => Some(true),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let bidi = Bidi::of(&text.characters, &forced);
|
||||
let level_at = |i: usize| bidi.as_ref().and_then(|b| b.levels.get(i)).copied().unwrap_or(0);
|
||||
// A grapheme cluster (emoji sequence, letter with marks) is shaped with one face.
|
||||
let cluster_start = crate::breaks::grapheme_starts(&text.characters);
|
||||
|
||||
@@ -43,11 +43,11 @@ fn starts(l: &TextLayout) -> Vec<(f64, Option<f64>)> {
|
||||
}
|
||||
|
||||
fn pl(list: ListStyle, indent: u8) -> ParaList {
|
||||
ParaList { list, indent, start_offset: 0 }
|
||||
ParaList { list, indent, start_offset: 0, ..ParaList::default() }
|
||||
}
|
||||
|
||||
fn from(list: ListStyle, indent: u8, start_offset: u32) -> ParaList {
|
||||
ParaList { list, indent, start_offset }
|
||||
ParaList { list, indent, start_offset, ..ParaList::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -406,14 +406,36 @@ fn bidi_visual_order_follows_levels() {
|
||||
assert_eq!(crate::layout::visual_order(&[0, 0, 0]), vec![0, 1, 2]);
|
||||
assert!(crate::layout::visual_order(&[]).is_empty());
|
||||
// Plain left-to-right text skips the analysis.
|
||||
assert!(crate::layout::Bidi::of("Hello, world 123").is_none());
|
||||
let b = crate::layout::Bidi::of("abc \u{5D0}\u{5D1}\u{5D2}\n\u{5D3} x").unwrap();
|
||||
assert!(crate::layout::Bidi::of("Hello, world 123", &[]).is_none());
|
||||
assert!(crate::layout::Bidi::of("Hello, world 123", &[None, None]).is_none());
|
||||
let b = crate::layout::Bidi::of("abc \u{5D0}\u{5D1}\u{5D2}\n\u{5D3} x", &[]).unwrap();
|
||||
assert_eq!(b.levels.get(..4), Some(&[0, 0, 0, 0][..]));
|
||||
assert!(b.levels.get(4..7).unwrap().iter().all(|l| l % 2 == 1));
|
||||
// Paragraph direction comes from each paragraph's first strong char.
|
||||
assert!(!b.rtl_para[0] && b.rtl_para[8]);
|
||||
}
|
||||
|
||||
/// A paragraph's forced base direction (Text ▸ Text direction, #1830): the base level is given,
|
||||
/// the letters' own levels still follow the rules, and the other paragraphs keep theirs.
|
||||
#[test]
|
||||
fn forced_direction_sets_a_paragraphs_base_level() {
|
||||
use crate::layout::Bidi;
|
||||
// Latin letters forced right to left: an embedded left-to-right run (level 2) in a
|
||||
// right-to-left paragraph; the next paragraph, unforced, stays left to right.
|
||||
let b = Bidi::of("ab\ncd", &[Some(true), None]).unwrap();
|
||||
assert_eq!(b.rtl_para, [true, true, true, false, false]);
|
||||
assert_eq!((b.levels.get(..2), b.levels.get(3..)), (Some(&[2, 2][..]), Some(&[0, 0][..])));
|
||||
// Hebrew forced left to right: a right-to-left run (level 1) in a left-to-right paragraph.
|
||||
let b = Bidi::of("\u{5D0}\u{5D1}", &[Some(false)]).unwrap();
|
||||
assert_eq!(b.rtl_para, [false, false]);
|
||||
assert_eq!(b.levels, [1, 1]);
|
||||
// Forcing what the letters already say changes nothing; a paragraph past the forced list is
|
||||
// detected.
|
||||
let b = Bidi::of("\u{5D0}\n\u{5D1}", &[Some(true)]).unwrap();
|
||||
assert_eq!(b.rtl_para, [true, true, true]);
|
||||
assert_eq!((b.levels.first(), b.levels.last()), (Some(&1), Some(&1)));
|
||||
}
|
||||
|
||||
/// The x of the glyph for char `i`.
|
||||
fn glyph_x(l: &TextLayout, i: usize) -> f64 {
|
||||
l.glyphs.iter().find(|g| g.char_start == i && g.char_end > i).map(|g| g.x).unwrap()
|
||||
|
||||
@@ -407,6 +407,10 @@ name = "English"
|
||||
"Decoration" = "Decoration"
|
||||
"Deep select" = "Deep select"
|
||||
"Wrap style" = "Wrap style"
|
||||
"Text direction" = "Text direction"
|
||||
"Auto: by the first letter with a direction" = "Auto: by the first letter with a direction"
|
||||
"Left to right" = "Left to right"
|
||||
"Right to left" = "Right to left"
|
||||
"Balance" = "Balance"
|
||||
"Pretty" = "Pretty"
|
||||
"Auto: as many words as fit on each line" = "Auto: as many words as fit on each line"
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
use egui::{Align2, Color32, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use figcraft_doc::{
|
||||
DecorationLength, Document, LeadingTrim, LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAlignV, TextAutoResize,
|
||||
TextCase, TextData, TextDecoration, TextStyle, VariableType, trim_num,
|
||||
TextCase, TextData, TextDecoration, TextDirection, TextStyle, VariableType, trim_num,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@ use super::picker::{font_picker, remember_family};
|
||||
use super::spacing::{SpacingField, commit_spacing, parse_letter_spacing, parse_line_height, spacing_field, spacing_input};
|
||||
use super::{
|
||||
Arc, DecorationLength, Document, FEATURES, FIELD_H, FieldEdit, FigApp, Icon, Id, Lead, LeadingTrim, ListStyle, MIXED, NodeId, SIZES, Sense, TABS,
|
||||
TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, Tokens, Ui, Value, VariableType, common, field_row, icons,
|
||||
json, live, menu_item, menu_popup, regular, row, semibold, text_style_params, tr, tr_noop, trf, trim_num, uniform, vec2, widgets,
|
||||
TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextStyle, Tokens, Ui, Value, VariableType, common,
|
||||
field_row, icons, json, live, menu_item, menu_popup, regular, row, semibold, text_style_params, tr, tr_noop, trf, trim_num, uniform, vec2,
|
||||
widgets,
|
||||
};
|
||||
|
||||
/// The font rows: family, style and size, line height and letter spacing.
|
||||
@@ -397,6 +398,31 @@ fn type_settings(
|
||||
let style = ["auto", "balance", "pretty"].get(i).copied().unwrap_or("auto");
|
||||
app.set_props(ids, json!({"wrapStyle": style}));
|
||||
}
|
||||
// The paragraphs' base direction, once a right-to-left script is in the text or a direction
|
||||
// is forced ("controls are available to override text direction per paragraph", Add
|
||||
// right-to-left text). While editing: the selected paragraphs.
|
||||
let has_direction =
|
||||
|t: &TextData| figcraft_text::display::has_rtl(&t.characters) || t.paragraphs.iter().any(|p| p.direction != TextDirection::Auto);
|
||||
if ids.iter().any(|i| doc.node(*i).and_then(|n| n.kind.text()).is_some_and(has_direction)) {
|
||||
caption(ui, tr("Text direction"));
|
||||
let dir = common(doc, ids, |n| {
|
||||
n.kind.text().and_then(|t| {
|
||||
let (a, b) = range.filter(|r| r.0 == n.id).map_or((0, t.char_count()), |(_, a, b)| (a, b));
|
||||
let (p0, p1) = t.para_span(a, b);
|
||||
let first = t.para_list(p0).direction;
|
||||
(p0..=p1).all(|p| t.para_list(p).direction == first).then_some(first as usize)
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
let items = [
|
||||
(tr("Auto"), tr_noop("Auto: by the first letter with a direction")),
|
||||
("→", tr_noop("Left to right")),
|
||||
("←", tr_noop("Right to left")),
|
||||
];
|
||||
if let Some(i) = text_seg(ui, "direction", &items, dir, w) {
|
||||
app.run("text.direction", json!({"ids": ids, "direction": (["auto", "ltr", "rtl"].get(i).copied().unwrap_or("auto"))}));
|
||||
}
|
||||
}
|
||||
let resize = common(doc, ids, |n| n.kind.text().map(|t| t.auto_resize)).flatten();
|
||||
// Auto-height text with a line limit truncates too.
|
||||
let truncating = common(doc, ids, |n| n.kind.text().map(TextData::truncates)).flatten();
|
||||
|
||||
@@ -57,7 +57,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v
|
||||
Portuguese take the singular for 0 as well; Japanese, Korean, Chinese and Vietnamese have one form;
|
||||
CLDR's "many" for millions in French, Spanish and Portuguese reads as the plural).
|
||||
- **Script support in documents:** Unicode bidi with Arabic shaping and mirrored brackets in text
|
||||
layers; right-to-left list markers and indents; right-to-left names in the layers panel, tabs
|
||||
layers; a paragraph's base direction forced with Text ▸ Text direction (#1830); right-to-left
|
||||
list markers and indents; right-to-left names in the layers panel, tabs
|
||||
and canvas labels (visual order, joined Arabic); inline IME composition with the candidate window
|
||||
at the caret; system-font fallback for scripts the UI fonts lack. Devanagari shapes through
|
||||
harfrust. No vertical text (Figma has none either).
|
||||
@@ -125,6 +126,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-05 | minor | Documents: a paragraph's base direction can be forced left to right or right to left (Text ▸ Text direction, `text.direction`, `node.set textDirection`, the Type settings control, the `.fig` lines' `sourceDirectionality`), as Add right-to-left text says (#1830); detection stays the default. Four new UI strings (English only; other catalogs fall back). |
|
||||
| 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) |
|
||||
| 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged |
|
||||
| 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed |
|
||||
|
||||
+3
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user