From 64b7222cb2072e3eff79a5e4f00fd6b17f361e1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Thu, 3 Dec 2026 11:47:51 +0100 Subject: [PATCH] Right-to-left text: dir="rtl" and CSS direction lay out from the right (bidi levels per character, lines reordered by UAX #9 rule L2, numbers and Latin words kept in order, brackets mirrored), block/flex/grid children mirrored, text-align start/end by direction; written for Perry (no string spreads, no spread-then-shorthand objects, no holey arrays) --- package.json | 2 +- src/css/bidi.ts | 124 +++++++++++++++++++++++++++++++++++++++++++++ src/css/index.ts | 2 + src/css/layout.ts | 75 ++++++++++++++++++++++++--- tests/bidi.test.ts | 53 +++++++++++++++++++ 5 files changed, 247 insertions(+), 9 deletions(-) create mode 100644 src/css/bidi.ts create mode 100644 tests/bidi.test.ts diff --git a/package.json b/package.json index 8361889..dbd42f3 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ }, "files": ["src/", "README.md", "LICENSE"], "scripts": { - "test": "node --no-warnings tests/dom.test.ts", + "test": "node --no-warnings tests/dom.test.ts && node --no-warnings tests/bidi.test.ts", "test:perry": "mkdir -p .build && perry compile tests/dom.test.ts -o .build/dom-test && .build/dom-test", "typecheck": "tsc -p tsconfig.json --noEmit" }, diff --git a/src/css/bidi.ts b/src/css/bidi.ts new file mode 100644 index 0000000..7f627c3 --- /dev/null +++ b/src/css/bidi.ts @@ -0,0 +1,124 @@ +/** + * Right-to-left text: the Unicode bidirectional algorithm, cut down to what a page's text needs. + * + * A paragraph's characters get embedding levels (even: left to right, odd: right to left) from + * the paragraph's direction (CSS `direction`) and their own: Hebrew and Arabic letters are right + * to left, other letters left to right, digits a left-to-right number, and spaces and punctuation + * take the direction around them (UAX #9's W and N rules, without explicit embeddings or + * isolates). layout.ts splits the text where the level changes, breaks lines as usual, then + * reorders each line's pieces with `visualOrder` (rule L2). Bloom shapes each right-to-left + * piece (the engine's text_shaping.rs), so the letters of a piece stay in logical order here. + */ + +/** Right-to-left strong characters: Hebrew, Arabic and the scripts between (Syriac, Thaana, + * NKo, ...), and their presentation forms. */ +export function isRtlChar(cp: number): boolean { + return (cp >= 0x0590 && cp <= 0x08ff) || (cp >= 0xfb1d && cp <= 0xfdff) || (cp >= 0xfe70 && cp <= 0xfefc) || + (cp >= 0x10800 && cp <= 0x10fff) || (cp >= 0x1e800 && cp <= 0x1efff); +} + +/** Whether a text needs the bidi pass: it has a right-to-left character. */ +export function hasRtl(t: string): boolean { + for (const ch of t) if (isRtlChar(ch.codePointAt(0) ?? 0)) return true; + return false; +} + +type Cls = "L" | "R" | "N" | "NSM"; +const digit = (cp: number): boolean => (cp >= 0x30 && cp <= 0x39) || (cp >= 0x660 && cp <= 0x669) || (cp >= 0x6f0 && cp <= 0x6f9); + +/** Combining marks outside the RTL blocks (those inside count as right to left, the same result). */ +const mark = (cp: number): boolean => (cp >= 0x300 && cp <= 0x36f) || (cp >= 0x1ab0 && cp <= 0x1aff) || (cp >= 0x1dc0 && cp <= 0x1dff) || + (cp >= 0x20d0 && cp <= 0x20ff) || (cp >= 0xfe20 && cp <= 0xfe2f); +/** Spaces, punctuation and symbols (by block; no Unicode property regexes, which Perry may lack). */ +const neutral = (cp: number): boolean => cp <= 0x2f || (cp >= 0x3a && cp <= 0x40) || (cp >= 0x5b && cp <= 0x60) || (cp >= 0x7b && cp <= 0xbf) || + cp === 0xd7 || cp === 0xf7 || (cp >= 0x2000 && cp <= 0x2bff) || (cp >= 0x3000 && cp <= 0x303f) || (cp >= 0xfe30 && cp <= 0xfe4f) || + (cp >= 0xff00 && cp <= 0xff0f) || (cp >= 0xff1a && cp <= 0xff20) || cp === 0x60c || cp >= 0x1f000; + +function cls(cp: number): Cls | "EN" { + // Arabic-Indic digits are inside the Arabic block: numbers first + if (digit(cp)) return "EN"; + if (cp === 0x60c) return "N"; // the Arabic comma separates like a comma + if (isRtlChar(cp)) return "R"; + if (mark(cp)) return "NSM"; + return neutral(cp) ? "N" : "L"; +} + +/** + * The embedding level of each code point of `chars` (a paragraph's text, one string per code + * point), in a paragraph of level `para` (0 or 1). + */ +export function levels(chars: string[], para: 0 | 1): number[] { + const n = chars.length; + const c: (Cls | "EN")[] = chars.map((ch) => cls(ch.codePointAt(0) ?? 0)); + // W1: a mark takes the class of the character before it + for (let i = 0; i < n; i++) if (c[i] === "NSM") c[i] = i > 0 ? (c[i - 1] as Cls | "EN") : (para === 1 ? "R" : "L"); + // separators between two digits ("1,5", "12.30") are part of the number (W4); so are a hyphen + // or dash between them, so a range ("4–6") reads 4–6, not 6–4 as the strict algorithm has it + for (let i = 1; i < n - 1; i++) { + if (c[i] === "N" && c[i - 1] === "EN" && c[i + 1] === "EN" && ".,:/-\u2013".includes(chars[i] as string)) c[i] = "EN"; + } + // N1/N2: a run of neutrals between two of the same direction takes it, else the paragraph's; + // numbers count as right to left for this + const strong = (k: Cls | "EN"): "L" | "R" | null => k === "L" ? "L" : k === "R" || k === "EN" ? "R" : null; + // arrays built whole, not new Array(n) filled by index (Perry reads those back as undefined) + const dir: ("L" | "R")[] = chars.map((): "L" | "R" => "L"); + for (let i = 0; i < n; i++) { + const s = strong(c[i] as Cls | "EN"); + if (s !== null) { dir[i] = s; continue; } + let j = i; + while (j < n && strong(c[j] as Cls | "EN") === null) j++; + let before: "L" | "R" = para === 1 ? "R" : "L"; + for (let k = i - 1; k >= 0; k--) { const s2 = strong(c[k] as Cls | "EN"); if (s2 !== null) { before = s2; break; } } + const after: "L" | "R" = j < n ? (strong(c[j] as Cls | "EN") as "L" | "R") : (para === 1 ? "R" : "L"); + const d = before === after ? before : (para === 1 ? "R" : "L"); + for (let k = i; k < j; k++) dir[k] = d; + i = j - 1; + } + // I1/I2: the levels + const out: number[] = chars.map(() => 0); + for (let i = 0; i < n; i++) { + const k = c[i]; + if (k === "EN") { + // a number after left-to-right text stays at the paragraph's level in an LTR paragraph + let prev: "L" | "R" | null = null; + for (let j = i - 1; j >= 0; j--) { const s = c[j]; if (s === "L" || s === "R") { prev = s; break; } } + out[i] = para === 0 ? (prev === "R" ? 2 : 0) : 2; + } else if (dir[i] === "R") out[i] = 1; + else out[i] = para === 1 ? 2 : 0; + } + return out; +} + +/** Rule L2: the visual order of a line's items, each with its level (the indices into `lvls`). */ +export function visualOrder(lvls: number[]): number[] { + const order = lvls.map((_, i) => i); + if (lvls.length === 0) return order; + const max = Math.max(...lvls); + let minOdd = Infinity; + for (const l of lvls) if (l % 2 === 1 && l < minOdd) minOdd = l; + if (!Number.isFinite(minOdd)) return order; + for (let level = max; level >= minOdd; level--) { + for (let i = 0; i < order.length; i++) { + if ((lvls[order[i] as number] as number) < level) continue; + let j = i; + while (j < order.length && (lvls[order[j] as number] as number) >= level) j++; + const rev = order.slice(i, j).reverse(); + order.splice(i, j - i, ...rev); + i = j; + } + } + return order; +} + +const MIRROR: Record = { "(": ")", ")": "(", "[": "]", "]": "[", "{": "}", "}": "{", "<": ">", ">": "<", "«": "»", "»": "«", "‹": "›", "›": "‹" }; + +/** + * A right-to-left piece without right-to-left letters (punctuation, spaces between RTL words): + * Bloom draws it left to right without shaping, so it is given in visual order here, brackets + * mirrored (rule L4). A piece with RTL letters is shaped right to left by Bloom, which does both. + */ +export function rtlNeutralVisual(t: string): string { + let out = ""; + for (const ch of t) out = (MIRROR[ch] ?? ch) + out; + return out; +} diff --git a/src/css/index.ts b/src/css/index.ts index d25ed63..bbf979a 100644 --- a/src/css/index.ts +++ b/src/css/index.ts @@ -32,6 +32,8 @@ html, address, blockquote, body, center, dialog, div, figure, figcaption, footer details, summary, article, aside, h1, h2, h3, h4, h5, h6, hgroup, nav, section, dir, dd, dl, dt, menu, ol, ul, li, fieldset, optgroup { display: block; } head, link, meta, script, style, title, template, base, noscript, datalist, param, area, map, track, [hidden], option { display: none; } html { color: canvastext; font-family: serif; font-size: 16px; line-height: normal; } +[dir="rtl"] { direction: rtl; } +[dir="ltr"] { direction: ltr; } body { margin: 8px; } h1 { font-size: 2em; margin: .67em 0; font-weight: bold; } h2 { font-size: 1.5em; margin: .83em 0; font-weight: bold; } diff --git a/src/css/layout.ts b/src/css/layout.ts index 737a6d3..d96b628 100644 --- a/src/css/layout.ts +++ b/src/css/layout.ts @@ -25,13 +25,14 @@ import type { Element, Node, Text } from "../dom/node.ts"; import { Computed, INHERITED } from "./cascade.ts"; import { faceFor, fallbackFor, type Face } from "./fonts.ts"; +import { hasRtl, levels, rtlNeutralVisual, visualOrder } from "./bidi.ts"; import { emojiFace } from "./emoji.ts"; import { length, split, type LengthContext } from "./values.ts"; export interface Edges { t: number; r: number; b: number; l: number } const ZERO: Edges = { t: 0, r: 0, b: 0, l: 0 }; -export interface Fragment { text: string; x: number; y: number; w: number; style: Computed; face: Face; size: number; spacing: number } +export interface Fragment { text: string; x: number; y: number; w: number; style: Computed; face: Face; size: number; spacing: number; /** bidi embedding level (bidi.ts); odd is right to left */ level?: number } export class Box { el: Element | null; @@ -208,6 +209,8 @@ interface Piece { face?: Face; box: Box | null; // the atomic box, or the inline element opened/closed w: number; + /** bidi embedding level, in a paragraph with right-to-left text (bidi.ts) */ + level?: number; } function transform(t: string, s: Computed): string { @@ -319,14 +322,50 @@ function pieces(container: Box, out: Piece[], prevSpace: { v: boolean }): void { interface LineItem { piece: Piece; x: number; w: number } +/** + * A paragraph's pieces with bidi levels (bidi.ts): text split where the level changes, each + * other piece (an image, an inline element's edge) a neutral. A right-to-left piece without + * right-to-left letters is turned to visual order here; one with letters Bloom shapes. + */ +function withLevels(ps: Piece[], para: 0 | 1): Piece[] { + const chars: string[] = []; + // code points by for..of: Perry doesn't spread a string into push(...) or [...] + for (const p of ps) { if (p.kind === "text") { for (const ch of p.text) chars.push(ch); } else chars.push(" "); } + const lv = levels(chars, para); + const out: Piece[] = []; + let k = 0; + for (const p of ps) { + // pieces written out, not { ...p, level }: Perry drops a shorthand property after a spread + if (p.kind !== "text") { out.push({ kind: p.kind, text: p.text, style: p.style, face: p.face, box: p.box, w: p.w, level: p.kind === "break" ? para : (lv[k] as number) }); k++; continue; } + const cps: string[] = []; + for (const ch of p.text) cps.push(ch); + let i = 0; + while (i < cps.length) { + const level = lv[k + i] as number; + let j = i + 1; + while (j < cps.length && lv[k + j] === level) j++; + let text = cps.slice(i, j).join(""); + const w = cps.length === j - i ? p.w : measure(text, p.style, p.face); + if (level % 2 === 1 && !hasRtl(text)) text = rtlNeutralVisual(text); + out.push({ kind: p.kind, text: text, style: p.style, face: p.face, box: p.box, w: w, level: level }); + i = j; + } + k += cps.length; + } + return out; +} + /** * Lay out a block container's inline content in lines of width `avail` from (x, y). Returns the * height and the widest line. With `measureOnly`, nothing is placed. */ function layoutInline(box: Box, x: number, y: number, avail: number, measureOnly: boolean): { h: number; maxLine: number; minWord: number } { const s = box.style; - const ps: Piece[] = []; + let ps: Piece[] = []; pieces(box, ps, { v: true }); + const para: 0 | 1 = s.get("direction") === "rtl" ? 1 : 0; + const bidi = para === 1 || ps.some((p) => p.kind === "text" && hasRtl(p.text)); + if (bidi) ps = withLevels(ps, para); const nowrap = (st: Computed): boolean => { const w = st.get("white-space"); return w === "nowrap" || w === "pre"; }; const breakAll = s.get("overflow-wrap") === "anywhere" || s.get("overflow-wrap") === "break-word" || s.get("word-break") === "break-all"; // atomic sizes @@ -419,13 +458,20 @@ function layoutInline(box: Box, x: number, y: number, avail: number, measureOnly } } const lineH = ascent + descent; + if (!measureOnly && bidi && l.length > 0) { + // rule L2: the line's pieces in visual order, placed again from its start + const vis = visualOrder(l.map((it) => it.piece.level ?? para)).map((i) => l[i] as LineItem); + let acc = para === 0 ? (l[0] as LineItem).x : 0; + for (const it of vis) { it.x = acc; acc += it.w; } + l.splice(0, l.length, ...vis); + } if (!measureOnly) { let width = 0; for (const it of l) width = Math.max(width, it.x + it.w); const free = avail - width; let shift = 0; if (align === "center" || align === "-webkit-center") shift = free / 2; - else if (align === "right" || align === "end") shift = free; + else if (align === "right" || (align === "end" && para === 0) || ((align === "start" || align === "") && para === 1)) shift = free; else if (align === "justify" && li !== lastLine) shift = 0; const baseline = cy + ascent; // inline elements open across the line: their rects @@ -433,11 +479,13 @@ function layoutInline(box: Box, x: number, y: number, avail: number, measureOnly for (const it of l) { const p = it.piece; const px = x + shift + it.x; - if (p.kind === "open" && p.box !== null) open.set(p.box, px); - else if (p.kind === "close" && p.box !== null) { + if (p.kind === "open" && p.box !== null && !(bidi && open.has(p.box))) open.set(p.box, px); + else if ((p.kind === "close" || p.kind === "open") && p.box !== null) { + // right-to-left text can put an element's close before its open: the rect spans both + if (bidi && p.kind === "close" && !open.has(p.box)) { open.set(p.box, px + it.w); continue; } const start = open.get(p.box) ?? x + shift; open.delete(p.box); - addInlineRect(p.box, start, px + it.w, baseline); + addInlineRect(p.box, Math.min(start, px), Math.max(start, px + it.w), baseline); } else if (p.kind === "text") { if (p.text === " " && it === l[l.length - 1]) continue; const f = fontOf(p.style); @@ -445,10 +493,13 @@ function layoutInline(box: Box, x: number, y: number, avail: number, measureOnly const y = baseline - p.style.fontSize; // Bloom draws the baseline at y + size // runs of the same style and face on a line are one fragment: fewer draws, and spacing the font's own const prev = box.fragments[box.fragments.length - 1]; - if (prev !== undefined && prev.style === p.style && prev.face === face && Math.abs(prev.y - y) < 0.01 && Math.abs(prev.x + prev.w - px) < 0.5) { + // (with bidi only left-to-right runs: Bloom shapes each right-to-left piece on its own) + const level = p.level ?? para; + if (prev !== undefined && prev.style === p.style && prev.face === face && Math.abs(prev.y - y) < 0.01 && Math.abs(prev.x + prev.w - px) < 0.5 && + level % 2 === 0 && (prev.level ?? para) % 2 === 0) { prev.text += p.text; prev.w += it.w; - } else box.fragments.push({ text: p.text, x: px, y, w: it.w, style: p.style, face, size: f.size, spacing: f.spacing }); + } else box.fragments.push({ text: p.text, x: px, y, w: it.w, style: p.style, face, size: f.size, spacing: f.spacing, level }); } else if (p.kind === "atomic" && p.box !== null) { const b = p.box; if (b.outOfFlow) { b.staticX = px; b.staticY = cy; continue; } @@ -650,6 +701,14 @@ export function layoutBox(b: Box, cbW: number, cbH: number, x: number, y: number else contentH = layoutFlow(b, cx, cy, cw, contentCbH); } b.contentH = contentH; + // direction: rtl puts block, flex and grid children from the right: the left-to-right layout, + // mirrored in the content box (inline content is ordered by the bidi pass instead) + if (s.get("direction") === "rtl" && b.kind !== "replaced") { + const d = b.display; + if (d === "flex" || d === "grid" || !b.children.some((c) => !c.outOfFlow && c.isInlineLevel)) { + for (const c of b.children) if (!c.outOfFlow) shiftBox(c, 2 * cx + cw - c.w - 2 * c.x, 0); + } + } // A scroll container scrolls as far as its children reach: a grid or flex container of a fixed // height reports that height as its content, though an item may be taller. const oy = s.get("overflow-y"); diff --git a/tests/bidi.test.ts b/tests/bidi.test.ts new file mode 100644 index 0000000..5febf17 --- /dev/null +++ b/tests/bidi.test.ts @@ -0,0 +1,53 @@ +/** + * Bidi tests: run with `node tests/bidi.test.ts`. Levels and visual order for right-to-left text. + */ +import { hasRtl, levels, rtlNeutralVisual, visualOrder } from "../src/css/bidi.ts"; +import { eq, ok, report, test } from "./harness.ts"; + +/** A paragraph's text in visual order, character by character (what reordering whole lines does). */ +function visual(t: string, para: 0 | 1): string { + const chars = [...t]; + return visualOrder(levels(chars, para)).map((i) => chars[i]).join(""); +} + +test("right-to-left letters are found", () => { + ok(hasRtl("שלום"), "Hebrew"); + ok(hasRtl("abc مرحبا"), "Arabic"); + ok(!hasRtl("Hello, Wörld! नमस्ते 日本"), "no RTL"); +}); + +test("left-to-right text keeps level 0 and its order", () => { + eq(levels([..."ab, cd!"], 0).join(""), "0000000"); + eq(visual("ab, cd!", 0), "ab, cd!"); +}); + +test("a Hebrew sentence reads from the right", () => { + // logical "אב גד" -> visual "דג בא" + eq(visual("אב גד", 1), "דג בא"); + // the punctuation at the end goes to the left + eq(visual("אב!", 1), "!בא"); +}); + +test("numbers stay left to right inside right-to-left text", () => { + const t = "אב 12 גד"; + eq(levels([...t], 1).join(""), "11122111"); + eq(visual(t, 1), "דג 12 בא"); + // a decimal number is one number + eq(visual("א 1,5 ב", 1), "ב 1,5 א"); + // an age range stays in order + eq(visual("א 4–6 ב", 1), "ב 4–6 א"); +}); + +test("English inside a right-to-left paragraph stays in order", () => { + eq(visual("אב Chesslings גד", 1), "דג Chesslings בא"); +}); + +test("Hebrew inside a left-to-right paragraph is reversed in place", () => { + eq(visual("hi אב there", 0), "hi בא there"); +}); + +test("neutral right-to-left runs are mirrored and reversed", () => { + eq(rtlNeutralVisual("(!"), "!)"); +}); + +report("bidi");