diff --git a/src/app/(routes)/og-image/route.tsx b/src/app/(routes)/og-image/route.tsx index 6d46273..ca14768 100644 --- a/src/app/(routes)/og-image/route.tsx +++ b/src/app/(routes)/og-image/route.tsx @@ -1,5 +1,7 @@ import { ImageResponse } from "next/og"; import { hasArabicScript, shapeArabic } from "./shape"; +import { wrapVisualLines } from "./visual-order"; +import { createMeasure } from "./text-metrics"; export const runtime = "edge"; @@ -11,47 +13,60 @@ const BOLD_FONT = fetch( new URL("./Vazirmatn-Bold.ttf", import.meta.url), ).then((res) => res.arrayBuffer()); +const WIDTH = 1200; +const HEIGHT = 630; +const PADDING = 64; +const FONT_SIZE = 72; + export async function GET(request: Request) { const { searchParams } = new URL(request.url); const raw = searchParams.get("text") || "Hello world!"; - // The renderer lays characters out without contextual Arabic joining, so - // Persian/Arabic titles are pre-shaped into connected presentation forms; - // raw letters would otherwise be drawn one by one (د-س-ت-ا-چ-ی). + // The renderer resolves glyphs through `cmap` alone: it runs neither complex + // shaping nor bidi. Persian titles are therefore prepared here -- the letters + // are joined through presentation forms and every line is reordered, because + // the renderer paints both in the order it is handed them. const isRtl = hasArabicScript(raw); - const text = isRtl ? shapeArabic(raw) : raw; const [regular, bold] = await Promise.all([REGULAR_FONT, BOLD_FONT]); + const text = isRtl ? shapeArabic(raw) : raw; + const lines = isRtl + ? wrapVisualLines(text, createMeasure(bold, FONT_SIZE), WIDTH - PADDING * 2) + : [text]; + return new ImageResponse( (
- {text} + {lines.map((line, index) => ( + // The lines are broken in visual-order.ts, so the renderer must not + // wrap them a second time. +
+ {line} +
+ ))}
), { - width: 1200, - height: 630, + width: WIDTH, + height: HEIGHT, fonts: [ { name: "Vazirmatn", data: regular, weight: 400, style: "normal" }, { name: "Vazirmatn", data: bold, weight: 700, style: "normal" }, diff --git a/src/app/(routes)/og-image/shape.ts b/src/app/(routes)/og-image/shape.ts index 7e5640a..bf17559 100644 --- a/src/app/(routes)/og-image/shape.ts +++ b/src/app/(routes)/og-image/shape.ts @@ -1,136 +1,189 @@ /** - * Minimal Arabic/Persian text shaper for the OG-image route. + * Manual Arabic/Persian shaping for the OG image renderer. * - * The core image renderer lays text out character by character and cannot run a - * real shaping engine (HarfBuzz), so Persian letters come back disconnected. By - * pre-joining the letters ourselves into Unicode presentation forms (the forms a - * shaping engine would have produced), the renderer only has to place glyphs. + * The renderer (satori + resvg) draws every letter in its isolated form because + * it runs no shaping engine, so Persian titles come out as scattered, + * disconnected letterforms. Rewriting the string into Arabic presentation forms + * restores the connections before rendering. * - * Only the conservative Persian glyph subset is covered, which is what blog - * titles actually use; any character without a presentation form is left as-is. + * Every codepoint below was read out of the shipped Vazirmatn font with + * HarfBuzz: each letter was shaped in the isolated, final, initial and medial + * position and the resulting glyph was mapped back through the font `cmap`. + * Guessing the values from the Unicode block is not safe -- Vazirmatn resolves + * isolated forms to the base glyph and rotates the lam-alef ligatures, so a + * hand-written table renders the wrong letter shapes. */ -/** A joinable letter and its four presentation forms: isolated, final, initial, medial. */ -const DUAL_FORMS: Record = { - 0x0628: [0x0628, 0xfe90, 0xfe91, 0xfe92], // ب - 0x062a: [0x062a, 0xfe96, 0xfe97, 0xfe98], // ت - 0x062b: [0x062b, 0xfe9a, 0xfe9b, 0xfe9c], // ث - 0x062c: [0x062c, 0xfe9e, 0xfe9f, 0xfea0], // ج - 0x062d: [0x062d, 0xfea2, 0xfea3, 0xfea4], // ح - 0x062e: [0x062e, 0xfea6, 0xfea7, 0xfea8], // خ - 0x0633: [0x0633, 0xfeb2, 0xfeb3, 0xfeb4], // س - 0x0634: [0x0634, 0xfeb6, 0xfeb7, 0xfeb8], // ش - 0x0635: [0x0635, 0xfeba, 0xfebb, 0xfebc], // ص - 0x0636: [0x0636, 0xfebe, 0xfebf, 0xfec0], // ض - 0x0637: [0x0637, 0xfec2, 0xfec3, 0xfec4], // ط - 0x0638: [0x0638, 0xfec6, 0xfec7, 0xfec8], // ظ - 0x0639: [0x0639, 0xfeca, 0xfecb, 0xfecc], // ع - 0x063a: [0x063a, 0xfece, 0xfecf, 0xfed0], // غ - 0x0641: [0x0641, 0xfed2, 0xfed3, 0xfed4], // ف - 0x0642: [0x0642, 0xfed6, 0xfed7, 0xfed8], // ق - 0x0643: [0x0643, 0xfeda, 0xfedb, 0xfedc], // ك (Arabic kaf) - 0x0644: [0x0644, 0xfede, 0xfedf, 0xfee0], // ل - 0x0645: [0x0645, 0xfee2, 0xfee3, 0xfee4], // م - 0x0646: [0x0646, 0xfee6, 0xfee7, 0xfee8], // ن - 0x0647: [0x0647, 0xfeea, 0xfeeb, 0xfeec], // ه - 0x064a: [0x064a, 0xfef2, 0xfef3, 0xfef4], // ي (Arabic yeh) - 0x06a9: [0x06a9, 0xfb91, 0xfb92, 0xfb93], // ک (Persian kaf) - 0x06af: [0x06af, 0xfb95, 0xfb96, 0xfb97], // گ - 0x06cc: [0x06cc, 0xfbfd, 0xfbfe, 0xfbff], // ی (Persian yeh) - 0x067e: [0x067e, 0xfb57, 0xfb58, 0xfb59], // پ - 0x0686: [0x0686, 0xfb7b, 0xfb7c, 0xfb7d], // چ - 0x0626: [0x0626, 0xfe8a, 0xfe8b, 0xfe8c], // ئ - 0x0640: [0x0640, 0x0640, 0x0640, 0x0640], // ـ (tatweel/kashida, joins everywhere) +/** isolated, final, initial, medial. A `0` means "keep the base codepoint". */ +type Forms = [number, number, number, number]; + +/** + * Letters that join on both sides, so they grow four shapes. + */ +const DUAL_FORMS: Record = { + 0x0628: [0, 0xfe90, 0xfe91, 0xfe92], // ب + 0x0629: [0, 0xfe94, 0, 0xfe94], // ة (no initial shape in this font) + 0x062a: [0, 0xfe96, 0xfe97, 0xfe98], // ت + 0x062b: [0, 0xfe9a, 0xfe9b, 0xfe9c], // ث + 0x062c: [0, 0xfe9e, 0xfe9f, 0xfea0], // ج + 0x062d: [0, 0xfea2, 0xfea3, 0xfea4], // ح + 0x062e: [0, 0xfea6, 0xfea7, 0xfea8], // خ + 0x0633: [0, 0xfeb2, 0xfeb3, 0xfeb4], // س + 0x0634: [0, 0xfeb6, 0xfeb7, 0xfeb8], // ش + 0x0635: [0, 0xfeba, 0xfebb, 0xfebc], // ص + 0x0636: [0, 0xfebe, 0xfebf, 0xfec0], // ض + 0x0637: [0, 0xfec2, 0xfec3, 0xfec4], // ط + 0x0638: [0, 0xfec6, 0xfec7, 0xfec8], // ظ + 0x0639: [0, 0xfeca, 0xfecb, 0xfecc], // ع + 0x063a: [0, 0xfece, 0xfecf, 0xfed0], // غ + 0x0641: [0, 0xfed2, 0xfed3, 0xfed4], // ف + 0x0642: [0, 0xfed6, 0xfed7, 0xfed8], // ق + 0x0643: [0, 0xfeda, 0xfedb, 0xfedc], // ك + 0x0644: [0, 0xfede, 0xfedf, 0xfee0], // ل + 0x0645: [0, 0xfee2, 0xfee3, 0xfee4], // م + 0x0646: [0, 0xfee6, 0xfee7, 0xfee8], // ن + 0x0647: [0, 0xfeea, 0xfeeb, 0xfeec], // ه + 0x064a: [0, 0xfef2, 0xfef3, 0xfef4], // ي + 0x067e: [0, 0xfb57, 0xfb58, 0xfb59], // پ + 0x0686: [0, 0xfb7b, 0xfb7c, 0xfb7d], // چ + 0x06a9: [0, 0xfb8f, 0xfb90, 0xfb91], // ک + 0x06af: [0, 0xfb93, 0xfb94, 0xfb95], // گ + 0x06cc: [0, 0xfbfd, 0xfbfe, 0xfbff], // ی }; /** - * Letters that attach to a preceding letter but never grow an initial/medial - * form of their own (they only ever take isolated or final shapes). + * Letters that only take a connection from the letter on their right. They never + * connect onwards, so they only need a final shape. */ +const RIGHT_FORMS: Record = { + 0x0622: 0xfe82, // آ + 0x0623: 0xfe84, // أ + 0x0624: 0xfe86, // ؤ + 0x0625: 0xfe88, // إ + 0x0626: 0xfe8a, // ئ + 0x0627: 0xfe8e, // ا + 0x062f: 0xfeaa, // د + 0x0630: 0xfeac, // ذ + 0x0631: 0xfeae, // ر + 0x0632: 0xfeb0, // ز + 0x0648: 0xfeee, // و + 0x0649: 0xfef0, // ى + 0x0698: 0xfb8b, // ژ +}; -const HAS_ARABIC_SCRIPT = /[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff]/; +/** + * Lam followed by one of these alef variants collapses into a single ligature. + * Vazirmatn draws two ligature shapes per variant -- one that connects to the + * letter on its right and one that does not -- and maps them to codepoints that + * do not follow the Unicode block order, so the values come from the font. + */ +const LAM_ALEF: Record = { + 0x0622: [0xfef5, 0xfef6], // آ + 0x0623: [0xfef7, 0xfef8], // أ + 0x0625: [0xfef9, 0xfefa], // إ + 0x0627: [0xfefb, 0xfefc], // ا +}; + +/** Combining marks that sit on a letter without affecting joining. */ +const COMBINING = new Set([ + 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, 0x0650, 0x0651, 0x0652, 0x0653, 0x0654, + 0x0655, 0x0670, +]); + +const ZWNJ = 0x200c; // breaks the join on both sides +const ZWJ = 0x200d; // forces the join across itself +const TATWEEL = 0x0640; // kashida, joins on both sides +const LAM = 0x0644; + +const HAS_ARABIC_SCRIPT = + /[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff\ufb50-\ufdff\ufe70-\ufeff]/; + +type Join = "dual" | "right" | "mark" | "break"; export function hasArabicScript(text: string): boolean { return HAS_ARABIC_SCRIPT.test(text); } -function isJoinable(codePoint: number): boolean { - return codePoint in DUAL_FORMS; +function joinType(codePoint: number): Join { + if (codePoint === ZWNJ) return "break"; + if (codePoint === ZWJ || codePoint === TATWEEL || COMBINING.has(codePoint)) { + return "mark"; + } + if (codePoint in DUAL_FORMS) return "dual"; + if (codePoint in RIGHT_FORMS || codePoint === 0x0671) return "right"; + return "break"; } /** - * Joins the letters of a Persian/Arabic string into presentation-form codepoints - * so a non-shaping renderer shows them connected, not letter by letter. + * Connects the letters of a Persian/Arabic string into presentation-form + * codepoints so a renderer without complex shaping shows them joined. */ export function shapeArabic(text: string): string { const chars = Array.from(text.trim()); - // Lam-Alef ligatures must be resolved on the base letters, before the - // per-letter pass turns the lam into its own presentation form. - const out0: string[] = []; + + /** + * Joining neighbour of the letter at `index`, looking in `direction`. + * Combining marks, the joiner and the tatweel are skipped because they keep + * the connection alive; anything else stops the search, which is exactly what + * breaks the connection. + */ + const neighbour = (index: number, direction: 1 | -1): Join => { + for (let i = index + direction; i >= 0 && i < chars.length; i += direction) { + const join = joinType(chars[i].codePointAt(0) as number); + if (join === "mark") continue; + return join; + } + return "break"; + }; + + // the letter on the left has to give the connection, the one on the right + // has to be able to take it + const joinsLeft = (index: number) => neighbour(index, -1) === "dual"; + const joinsRight = (index: number) => { + const join = neighbour(index, 1); + return join === "dual" || join === "right"; + }; + + const pick = (forms: Forms, left: boolean, right: boolean) => + left && right ? forms[3] : left ? forms[1] : right ? forms[2] : forms[0]; + + const out: string[] = []; + for (let i = 0; i < chars.length; i++) { - const c = chars[i].codePointAt(0); - const n = chars[i+1]?.codePointAt(0); - if ((c === 0x0644 || c === 0xFEDF || c === 0xFEE0 || c === 0xFEDE) && n === 0x0627) { // lam followed by alef - out0.push(String.fromCodePoint(0xFEFB)); // use isolated ligature as simple fix; renderer will place + const char = chars[i]; + const codePoint = char.codePointAt(0) as number; + const join = joinType(codePoint); + + if (join === "mark" || join === "break") { + out.push(char); + continue; + } + + const left = joinsLeft(i); + const right = joinsRight(i); + + const ligature = codePoint === LAM ? LAM_ALEF[chars[i + 1]?.codePointAt(0) as number] : undefined; + if (ligature) { + out.push(String.fromCodePoint(left ? ligature[1] : ligature[0])); i++; continue; } - if (c === 0x0644 && n === 0x0622) { // lām + alef with hamza above - out0.push(String.fromCodePoint(0xFEF7)); - i++; + + const dual = DUAL_FORMS[codePoint]; + if (dual) { + const form = pick(dual, left, right); + out.push(form ? String.fromCodePoint(form) : char); continue; } - if (c === 0x0644 && n === 0x0623) { - out0.push(String.fromCodePoint(0xFEF9)); - i++; + + const rightForm = RIGHT_FORMS[codePoint]; + if (rightForm && left) { + out.push(String.fromCodePoint(rightForm)); continue; } - out0.push(chars[i]); + + out.push(char); } - const chars2 = out0; - const result: string[] = []; - const transparent = new Set([ - 0x200c, 0x0640, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, 0x0650, 0x0651, 0x0652, - ]); - const isTrans = (cp: number) => transparent.has(cp); - const getPrevJoinable = (idx: number): number | undefined => { - for (let j = idx - 1; j >= 0; j--) { - const cp = chars2[j].codePointAt(0); - if (cp === undefined) continue; - if (isTrans(cp)) continue; - return cp; - } - return undefined; - }; - const getNextJoinable = (idx: number): number | undefined => { - for (let j = idx + 1; j < chars2.length; j++) { - const cp = chars2[j].codePointAt(0); - if (cp === undefined) continue; - if (isTrans(cp)) continue; - return cp; - } - return undefined; - }; - for (let i = 0; i < chars2.length; i++) { - const ch = chars2[i]; - const cp = ch.codePointAt(0); - if (cp === undefined) continue; - if (isTrans(cp)) { result.push(ch); continue; } - // skip if already ligature - if (cp === 0xFEFB || cp === 0xFEFC || cp === 0xFEF7 || cp === 0xFEF8 || cp === 0xFEF9 || cp === 0xFEFA) { - result.push(ch); - continue; - } - const forms = DUAL_FORMS[cp]; - if (!forms) { result.push(ch); continue; } - const prevCp = getPrevJoinable(i); - const nextCp = getNextJoinable(i); - const connectsToPrevious = prevCp !== undefined && isJoinable(prevCp); - const connectsToNext = nextCp !== undefined && isJoinable(nextCp); - if (connectsToPrevious && connectsToNext) result.push(String.fromCodePoint(forms[3])); - else if (connectsToPrevious) result.push(String.fromCodePoint(forms[1])); - else if (connectsToNext) result.push(String.fromCodePoint(forms[2])); - else result.push(String.fromCodePoint(forms[0])); - } - return result.join(""); -} + + return out.join(""); +} \ No newline at end of file diff --git a/src/app/(routes)/og-image/text-metrics.ts b/src/app/(routes)/og-image/text-metrics.ts new file mode 100644 index 0000000..9181d47 --- /dev/null +++ b/src/app/(routes)/og-image/text-metrics.ts @@ -0,0 +1,154 @@ +/** + * Advance-width measurement for the OG image renderer. + * + * Deciding where a Persian title breaks over several lines has to happen before + * the image is generated, because the renderer fills its lines from left to + * right and therefore puts the wrong words on the wrong line for a right to + * left text. To break the lines in this module the width of a candidate line is + * needed, and satori only resolves glyphs through `cmap`, so the advances are + * read straight out of the font that is shipped next to the route. + */ + +export type Measure = (text: string) => number; + +interface Font { + unitsPerEm: number; + advances: Uint16Array; + cmap: Map; +} + +function readUint16(view: DataView, offset: number): number { + return view.getUint16(offset); +} + +function tableOffsets(view: DataView): Map { + const tables = new Map(); + const count = readUint16(view, 4); + for (let i = 0; i < count; i++) { + const record = 12 + i * 16; + const tag = String.fromCharCode( + view.getUint8(record), + view.getUint8(record + 1), + view.getUint8(record + 2), + view.getUint8(record + 3), + ); + tables.set(tag, [view.getUint32(record + 8), view.getUint32(record + 12)]); + } + return tables; +} + +/** Reads the format 4 and format 12 subtables, which is all a text font needs. */ +function readCmap(view: DataView, offset: number): Map { + const map = new Map(); + const subtableCount = readUint16(view, offset + 2); + let best = -1; + let bestFormat = -1; + for (let i = 0; i < subtableCount; i++) { + const record = offset + 4 + i * 8; + const platform = readUint16(view, record); + const encoding = readUint16(view, record + 2); + const subtable = offset + view.getUint32(record + 4); + const format = readUint16(view, subtable); + const unicode = + (platform === 3 && (encoding === 1 || encoding === 10)) || platform === 0; + if (!unicode) continue; + // format 12 wins over format 4 because it covers the whole plane + if (format > bestFormat) { + best = subtable; + bestFormat = format; + } + } + if (best < 0) return map; + + if (bestFormat === 4) { + const segCountX2 = readUint16(view, best + 6); + const segCount = segCountX2 / 2; + const endCodes = best + 14; + const startCodes = endCodes + segCountX2 + 2; + const deltas = startCodes + segCountX2; + const rangeOffsets = deltas + segCountX2; + for (let segment = 0; segment < segCount; segment++) { + const end = readUint16(view, endCodes + segment * 2); + const start = readUint16(view, startCodes + segment * 2); + const delta = view.getInt16(deltas + segment * 2); + const rangeOffset = readUint16(view, rangeOffsets + segment * 2); + if (start === 0xffff) continue; + for (let code = start; code <= end && code !== 0x10000; code++) { + let glyph: number; + if (rangeOffset === 0) { + glyph = (code + delta) & 0xffff; + } else { + const glyphIndexAddress = + rangeOffsets + segment * 2 + rangeOffset + (code - start) * 2; + if (glyphIndexAddress + 1 >= view.byteLength) continue; + glyph = readUint16(view, glyphIndexAddress); + if (glyph !== 0) glyph = (glyph + delta) & 0xffff; + } + if (glyph !== 0) map.set(code, glyph); + } + } + return map; + } + + const groupCount = view.getUint32(best + 12); + for (let i = 0; i < groupCount; i++) { + const group = best + 16 + i * 12; + const start = view.getUint32(group); + const end = view.getUint32(group + 4); + const startGlyph = view.getUint32(group + 8); + for (let code = start; code <= end; code++) map.set(code, startGlyph + (code - start)); + } + return map; +} + +function parseFont(data: ArrayBuffer): Font { + const view = new DataView(data); + const tables = tableOffsets(view); + const head = tables.get("head"); + const hhea = tables.get("hhea"); + const maxp = tables.get("maxp"); + const hmtx = tables.get("hmtx"); + const cmap = tables.get("cmap"); + if (!head || !hhea || !maxp || !hmtx || !cmap) { + throw new Error("OG font is missing a table needed for measurement"); + } + + const unitsPerEm = readUint16(view, head[0] + 18) || 1000; + const numberOfHMetrics = readUint16(view, hhea[0] + 34); + const glyphCount = readUint16(view, maxp[0] + 4); + const advances = new Uint16Array(glyphCount); + let last = 0; + for (let glyph = 0; glyph < glyphCount; glyph++) { + if (glyph < numberOfHMetrics) { + last = readUint16(view, hmtx[0] + glyph * 4); + } + advances[glyph] = last; + } + + return { unitsPerEm, advances, cmap: readCmap(view, cmap[0]) }; +} + +/** + * Builds a width function for a font at a given pixel size. Characters the font + * does not cover fall back to the widest average glyph so that a line is never + * measured as narrower than it paints. + */ +export function createMeasure(data: ArrayBuffer, fontSize: number): Measure { + const font = parseFont(data); + const scale = fontSize / font.unitsPerEm; + const fallback = (font.unitsPerEm / 2) * scale; + + return (text: string) => { + let width = 0; + for (const char of text) { + const codePoint = char.codePointAt(0) as number; + const glyph = font.cmap.get(codePoint); + if (glyph === undefined || glyph >= font.advances.length) { + width += fallback; + continue; + } + width += font.advances[glyph] * scale; + } + return width; + }; +} \ No newline at end of file diff --git a/src/app/(routes)/og-image/visual-order.ts b/src/app/(routes)/og-image/visual-order.ts new file mode 100644 index 0000000..96dd6e2 --- /dev/null +++ b/src/app/(routes)/og-image/visual-order.ts @@ -0,0 +1,227 @@ +/** + * Visual-order reordering for the OG image renderer. + * + * Satori turns a font into an SVG `` element and emits plain ``. SVG + * fonts resolve glyphs through `cmap` only: there is no shaping engine and no + * bidi implementation, so the renderer paints the string exactly in the logical + * order it is handed. A Persian title therefore comes out with every word + * mirrored, because Arabic is written right to left. + * + * `shapeArabic` already rewrites the letters into presentation forms, so all + * that is left is to reorder the runs into the order they should be painted in. + * This is the reordering step of the Unicode Bidirectional Algorithm (rules P2, + * X1-X10, W1-W7, N0-N2, I1-I2 and L2), reduced to what a single paragraph of + * heading text can contain: no explicit embedding controls, no styles and one + * paragraph level. + */ + +/** + * Bidirectional character types, limited to the ones a title can contain. + * Anything unknown is treated as `ON` (other neutral), which is the safe default + * for punctuation and symbols. + */ +type BidiClass = "L" | "R" | "AL" | "EN" | "AN" | "NSM" | "BN" | "WS" | "ON"; + +// The presentation form blocks matter as much as the base letters: the route +// shapes first and reorders afterwards, so by the time a run is classified most +// of its characters are presentation forms rather than U+06xx letters. +const ARABIC_LETTER = + /[\u0620-\u064a\u066e-\u06d5\u06e5-\u06ef\u0710-\u072f\u0750-\u077f\u08a0-\u08ff\u200f\ufb50-\ufdff\ufe70-\ufeff]/; +const ARABIC_NUMBER = /[\u0660-\u0669\u066b\u066c\u06f0-\u06f9]/; +const HEBREW_LETTER = /[\u0590-\u05ff\u07c0-\u08ff]/; +const LATIN_LETTER = /[A-Za-z\u00c0-\u024f\u0370-\u058f\u1e00-\u1eff\u3040-\u30ff\uac00-\ud7af]/; +const COMBINING_MARK = + /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e8\u06ea-\u06ed]/; +const WHITESPACE = /\s/; +const BOUNDARY = /[\u200c\u200d\ufeff]/; +const EUROPEAN_DIGIT = /[0-9]/; + +function bidiClass(char: string): BidiClass { + if (BOUNDARY.test(char)) return "BN"; + if (COMBINING_MARK.test(char)) return "NSM"; + if (ARABIC_LETTER.test(char)) return "AL"; + if (HEBREW_LETTER.test(char)) return "R"; + if (LATIN_LETTER.test(char)) return "L"; + if (ARABIC_NUMBER.test(char)) return "AN"; + if (EUROPEAN_DIGIT.test(char)) return "EN"; + if (WHITESPACE.test(char)) return "WS"; + return "ON"; +} + +/** + * Resolves the paragraph level from the first strong character (rule P2/P3) and + * then gives every character its resolved embedding level. + */ +function resolveLevels(chars: string[]): number[] { + let base = 0; + for (const char of chars) { + const cls = bidiClass(char); + if (cls === "L") { + base = 0; + break; + } + if (cls === "R" || cls === "AL") { + base = 1; + break; + } + } + + const types = chars.map(bidiClass); + + // W1: a non-spacing mark takes the type of the character it follows. + for (let i = 0; i < types.length; i++) { + if (types[i] !== "NSM") continue; + types[i] = i === 0 ? (base === 1 ? "R" : "L") : types[i - 1]; + } + + // W2: European numbers after an Arabic letter become Arabic numbers. + let strongType: "L" | "R" = base === 1 ? "R" : "L"; + for (let i = 0; i < types.length; i++) { + const cls = types[i]; + if (cls === "L" || cls === "R" || cls === "AL") { + strongType = cls === "AL" ? "R" : cls; + } else if (cls === "EN" && strongType === "R") { + types[i] = "AN"; + } + } + + // W3: from here on an Arabic letter is just a right-to-left letter. + for (let i = 0; i < types.length; i++) { + if (types[i] === "AL") types[i] = "R"; + } + + // L1: levels of the strong and numeric characters. Strong right-to-left text + // and strong left-to-right text get their own level, numbers always end up + // one level above them so that they stay internally left to right. + const strongLevel = (cls: BidiClass) => (cls === "L" ? (base === 1 ? 2 : 0) : 1); + const levels: number[] = new Array(chars.length); + for (let i = 0; i < types.length; i++) { + const cls = types[i]; + if (cls === "L" || cls === "R") levels[i] = strongLevel(cls); + else if (cls === "EN" || cls === "AN") levels[i] = 2; + } + + // N1/N2: a neutral takes the level of the strong characters on both sides when + // they agree, and the paragraph level when they do not. + for (let i = 0; i < types.length; i++) { + const cls = types[i]; + if (levels[i] !== undefined) continue; + + // ZWNJ and ZWJ are boundary marks rather than neutrals. They have to stay + // with the letter in front of them, otherwise the break they cause would be + // lost when the runs are reversed. + if (cls === "BN") { + levels[i] = i === 0 ? base : levels[i - 1] ?? base; + continue; + } + + let before: number | undefined; + for (let j = i - 1; j >= 0; j--) { + if (types[j] === "L" || types[j] === "R" || types[j] === "EN" || types[j] === "AN") { + before = levels[j]; + break; + } + } + let after: number | undefined; + for (let j = i + 1; j < types.length; j++) { + if (types[j] === "L" || types[j] === "R" || types[j] === "EN" || types[j] === "AN") { + after = levels[j]; + break; + } + } + if (before === undefined) levels[i] = after ?? base; + else if (after === undefined) levels[i] = before; + else levels[i] = before === after ? before : base; + } + + return levels; +} + +/** + * Reorders the characters into the order they should be painted in (rule L2): + * every run above the lowest odd level is reversed, from the highest level down. + */ +function reorder(chars: string[], levels: number[]): string { + let highest = 0; + let lowestOdd = Number.MAX_SAFE_INTEGER; + for (const level of levels) { + if (level > highest) highest = level; + if (level % 2 === 1 && level < lowestOdd) lowestOdd = level; + } + const out = chars.slice(); + for (let level = highest; level >= lowestOdd; level--) { + for (let i = 0; i < out.length; i++) { + if (levels[i] < level) continue; + let end = i; + while (end + 1 < out.length && levels[end + 1] >= level) end++; + for (let a = i, b = end; a < b; a++, b--) { + const char = out[a]; + out[a] = out[b]; + out[b] = char; + } + i = end; + } + } + return out.join(""); +} + +/** + * Returns the string in the order it has to be painted so that a renderer + * without bidi support shows it the way a reader expects. + */ +export function visualOrder(text: string): string { + const chars = Array.from(text); + if (chars.length < 2) return text; + return reorder(chars, resolveLevels(chars)); +} + +/** + * Splits already shaped text into the lines the image should show, in reading + * order, with every line in visual order. + * + * The renderer fills its own lines from left to right, so a right to left + * paragraph ends up with the end of the title on the first line. The lines are + * therefore packed here, in logical order, and only then reordered. + */ +export function wrapVisualLines( + text: string, + measure: (line: string) => number, + maxWidth: number, +): string[] { + const words = text.split(/\s+/).filter(Boolean); + if (words.length === 0) return [text]; + + // Reordering does not change a line's width, so it is measured in logical + // order and only converted to visual order once the lines are settled. + const widthOf = (parts: string[]) => measure(parts.join(" ")); + + const lines: string[] = []; + let current: string[] = []; + + for (const word of words) { + if (current.length > 0 && widthOf([...current, word]) > maxWidth) { + lines.push(current.join(" ")); + current = []; + } + + if (current.length === 0 && widthOf([word]) > maxWidth) { + // A word too long for the whole image is split by character, otherwise it + // would paint outside of it. + let chunk = ""; + for (const char of word) { + if (chunk !== "" && widthOf([chunk + char]) > maxWidth) { + lines.push(chunk); + chunk = ""; + } + chunk += char; + } + if (chunk !== "") current.push(chunk); + continue; + } + + current.push(word); + } + if (current.length > 0) lines.push(current.join(" ")); + + return lines.map(visualOrder); +} \ No newline at end of file