Skip to content

Commit 43ada1a

Browse files
committed
Extract whole-text alignment
Move the dependency-free alignment engine out of the DOM passage runtime and point core and widget consumers at its concrete owner. Preserve the algorithm verbatim while removing its unnecessary boot-time proxy.
1 parent ac8fe9e commit 43ada1a

9 files changed

Lines changed: 117 additions & 112 deletions

File tree

‎plugins/leaf/skills/leaf/CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ dynamic widget imports, and initial settlement;
8585
`runtime/storage.js` owns page addressing and browser-backed stores;
8686
`runtime/syntax.js` owns code tokenization and highlighting;
8787
`runtime/passages.js` owns the DOM reading and quote resolver;
88+
`runtime/text-alignment.js` owns lossless, language-aware whole-text alignment;
8889
`runtime/pointer.js` owns the shared unrounded pointer position;
8990
`runtime/geometry.js` owns the shared readings of visible boxes and clipping;
9091
`runtime/navigation.js` owns reader travel and scroller selection;

‎plugins/leaf/skills/leaf/assets/leaf.js‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,6 @@ import {
258258
startsAt,
259259
} from "./runtime/geometry.js";
260260
import {
261-
alignText,
262261
createPassages,
263262
inChrome,
264263
inUi,
@@ -268,6 +267,7 @@ import {
268267
uiInside,
269268
wrote,
270269
} from "./runtime/passages.js";
270+
import { textUnits } from "./runtime/text-alignment.js";
271271
import {
272272
ago,
273273
createPresence,
@@ -3329,7 +3329,6 @@ const {
33293329
COLLAPSE,
33303330
quoteFrom,
33313331
cut,
3332-
textUnits,
33333332
rangeOf,
33343333
holds,
33353334
neighbourhood,

‎plugins/leaf/skills/leaf/assets/runtime/passages.js‎

Lines changed: 0 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
/* The page's one DOM reading and quote resolver. */
22
let publishedPassages;
3-
export const alignText = (...args) => publishedPassages.alignText(...args);
43
export const closestAcross = (...args) => publishedPassages.closestAcross(...args);
54
export const inChrome = (...args) => publishedPassages.inChrome(...args);
65
export const inUi = (...args) => publishedPassages.inUi(...args);
@@ -508,112 +507,6 @@ export function createPassages(dependencies) {
508507
// pair is a character no UTF-8 file can hold, and a quote is written to one.
509508
const cut = (text, from, to) => [...text].slice(from, to).join("");
510509

511-
// One lossless text alignment for every widget that needs to explain a sequence of
512-
// whole-text states. Segmenter keeps words and punctuation in the language-aware
513-
// units this runtime already assumes; a linear-space Hirschberg walk supplies the
514-
// ordered shared spine. Its quadratic *time* is capped: after stripping a common
515-
// prefix and suffix, a very large divergent middle is one replacement instead of a
516-
// page-freezing attempt at fine-grained alignment. Joining same+delete reconstructs
517-
// `before`, and joining same+insert reconstructs `after`, exactly.
518-
const textUnits = new Intl.Segmenter(undefined, { granularity: "word" });
519-
const ALIGN_CELLS = 1_000_000;
520-
521-
function lcsRow(left, lo, hi, right, rlo, rhi, reverse) {
522-
const width = rhi - rlo;
523-
let previous = new Uint32Array(width + 1);
524-
for (let at = 0; at < hi - lo; at++) {
525-
const current = new Uint32Array(width + 1);
526-
const word = reverse ? left[hi - at - 1] : left[lo + at];
527-
for (let across = 1; across <= width; across++) {
528-
const other = reverse ? right[rhi - across] : right[rlo + across - 1];
529-
current[across] =
530-
word === other
531-
? previous[across - 1] + 1
532-
: Math.max(previous[across], current[across - 1]);
533-
}
534-
previous = current;
535-
}
536-
return previous;
537-
}
538-
539-
function lcsMatches(left, lo, hi, right, rlo, rhi, matches) {
540-
if (lo === hi || rlo === rhi) return;
541-
if (hi - lo === 1) {
542-
for (let at = rlo; at < rhi; at++)
543-
if (left[lo] === right[at]) {
544-
matches.push([lo, at]);
545-
break;
546-
}
547-
return;
548-
}
549-
550-
const middle = lo + Math.floor((hi - lo) / 2);
551-
let split = 0;
552-
{
553-
const forward = lcsRow(left, lo, middle, right, rlo, rhi, false);
554-
const backward = lcsRow(left, middle, hi, right, rlo, rhi, true);
555-
let best = -1;
556-
const width = rhi - rlo;
557-
for (let at = 0; at <= width; at++) {
558-
const score = forward[at] + backward[width - at];
559-
if (score > best) {
560-
best = score;
561-
split = at;
562-
}
563-
}
564-
}
565-
lcsMatches(left, lo, middle, right, rlo, rlo + split, matches);
566-
lcsMatches(left, middle, hi, right, rlo + split, rhi, matches);
567-
}
568-
569-
function alignText(before, after) {
570-
const left = [...textUnits.segment(before)].map((part) => part.segment);
571-
const right = [...textUnits.segment(after)].map((part) => part.segment);
572-
const runs = [];
573-
const push = (kind, text) => {
574-
if (!text) return;
575-
const last = runs.at(-1);
576-
if (last?.kind === kind) last.text += text;
577-
else runs.push({ kind, text });
578-
};
579-
580-
let prefix = 0;
581-
while (
582-
prefix < left.length &&
583-
prefix < right.length &&
584-
left[prefix] === right[prefix]
585-
)
586-
prefix++;
587-
let suffix = 0;
588-
while (
589-
prefix + suffix < left.length &&
590-
prefix + suffix < right.length &&
591-
left[left.length - suffix - 1] === right[right.length - suffix - 1]
592-
)
593-
suffix++;
594-
595-
push("same", left.slice(0, prefix).join(""));
596-
const leftEnd = left.length - suffix;
597-
const rightEnd = right.length - suffix;
598-
const matches = [];
599-
if ((leftEnd - prefix) * (rightEnd - prefix) <= ALIGN_CELLS)
600-
lcsMatches(left, prefix, leftEnd, right, prefix, rightEnd, matches);
601-
602-
let i = prefix;
603-
let j = prefix;
604-
for (const [li, rj] of matches) {
605-
push("delete", left.slice(i, li).join(""));
606-
push("insert", right.slice(j, rj).join(""));
607-
push("same", left[li]);
608-
i = li + 1;
609-
j = rj + 1;
610-
}
611-
push("delete", left.slice(i, leftEnd).join(""));
612-
push("insert", right.slice(j, rightEnd).join(""));
613-
push("same", left.slice(leftEnd).join(""));
614-
return runs;
615-
}
616-
617510
// What an element says, read the way this file reads the page everywhere else. A widget
618511
// wanting the words in one of its own slots asks for them here rather than through
619512
// `textContent`, because the two differ: the paint pass writes a hidden line into any text
@@ -919,8 +812,6 @@ export function createPassages(dependencies) {
919812
COLLAPSE,
920813
quoteFrom,
921814
cut,
922-
textUnits,
923-
alignText,
924815
says,
925816
wrote,
926817
rangeOf,
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/* Lossless, language-aware alignment of whole-text states. */
2+
3+
// One lossless text alignment for every widget that needs to explain a sequence of
4+
// whole-text states. Segmenter keeps words and punctuation in the language-aware
5+
// units this runtime already assumes; a linear-space Hirschberg walk supplies the
6+
// ordered shared spine. Its quadratic *time* is capped: after stripping a common
7+
// prefix and suffix, a very large divergent middle is one replacement instead of a
8+
// page-freezing attempt at fine-grained alignment. Joining same+delete reconstructs
9+
// `before`, and joining same+insert reconstructs `after`, exactly.
10+
export const textUnits = new Intl.Segmenter(undefined, { granularity: "word" });
11+
const ALIGN_CELLS = 1_000_000;
12+
13+
function lcsRow(left, lo, hi, right, rlo, rhi, reverse) {
14+
const width = rhi - rlo;
15+
let previous = new Uint32Array(width + 1);
16+
for (let at = 0; at < hi - lo; at++) {
17+
const current = new Uint32Array(width + 1);
18+
const word = reverse ? left[hi - at - 1] : left[lo + at];
19+
for (let across = 1; across <= width; across++) {
20+
const other = reverse ? right[rhi - across] : right[rlo + across - 1];
21+
current[across] =
22+
word === other
23+
? previous[across - 1] + 1
24+
: Math.max(previous[across], current[across - 1]);
25+
}
26+
previous = current;
27+
}
28+
return previous;
29+
}
30+
31+
function lcsMatches(left, lo, hi, right, rlo, rhi, matches) {
32+
if (lo === hi || rlo === rhi) return;
33+
if (hi - lo === 1) {
34+
for (let at = rlo; at < rhi; at++)
35+
if (left[lo] === right[at]) {
36+
matches.push([lo, at]);
37+
break;
38+
}
39+
return;
40+
}
41+
42+
const middle = lo + Math.floor((hi - lo) / 2);
43+
let split = 0;
44+
{
45+
const forward = lcsRow(left, lo, middle, right, rlo, rhi, false);
46+
const backward = lcsRow(left, middle, hi, right, rlo, rhi, true);
47+
let best = -1;
48+
const width = rhi - rlo;
49+
for (let at = 0; at <= width; at++) {
50+
const score = forward[at] + backward[width - at];
51+
if (score > best) {
52+
best = score;
53+
split = at;
54+
}
55+
}
56+
}
57+
lcsMatches(left, lo, middle, right, rlo, rlo + split, matches);
58+
lcsMatches(left, middle, hi, right, rlo + split, rhi, matches);
59+
}
60+
61+
export function alignText(before, after) {
62+
const left = [...textUnits.segment(before)].map((part) => part.segment);
63+
const right = [...textUnits.segment(after)].map((part) => part.segment);
64+
const runs = [];
65+
const push = (kind, text) => {
66+
if (!text) return;
67+
const last = runs.at(-1);
68+
if (last?.kind === kind) last.text += text;
69+
else runs.push({ kind, text });
70+
};
71+
72+
let prefix = 0;
73+
while (
74+
prefix < left.length &&
75+
prefix < right.length &&
76+
left[prefix] === right[prefix]
77+
)
78+
prefix++;
79+
let suffix = 0;
80+
while (
81+
prefix + suffix < left.length &&
82+
prefix + suffix < right.length &&
83+
left[left.length - suffix - 1] === right[right.length - suffix - 1]
84+
)
85+
suffix++;
86+
87+
push("same", left.slice(0, prefix).join(""));
88+
const leftEnd = left.length - suffix;
89+
const rightEnd = right.length - suffix;
90+
const matches = [];
91+
if ((leftEnd - prefix) * (rightEnd - prefix) <= ALIGN_CELLS)
92+
lcsMatches(left, prefix, leftEnd, right, prefix, rightEnd, matches);
93+
94+
let i = prefix;
95+
let j = prefix;
96+
for (const [li, rj] of matches) {
97+
push("delete", left.slice(i, li).join(""));
98+
push("insert", right.slice(j, rj).join(""));
99+
push("same", left[li]);
100+
i = li + 1;
101+
j = rj + 1;
102+
}
103+
push("delete", left.slice(i, leftEnd).join(""));
104+
push("insert", right.slice(j, rightEnd).join(""));
105+
push("same", left.slice(leftEnd).join(""));
106+
return runs;
107+
}

‎plugins/leaf/skills/leaf/assets/runtime/widget-api.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ export { keys, paintKeys, saying } from "./keyboard/scopes.js";
1212
export { scrollerFor } from "./navigation.js";
1313
export { announce, toast } from "./notifications.js";
1414
export { actionAvailable, actionStands, sendAction } from "./outbox.js";
15+
export { alignText } from "./text-alignment.js";
1516
export {
16-
alignText,
1717
inChrome,
1818
inUi,
1919
renderRetired,

‎plugins/leaf/skills/leaf/scripts/leaf/render_gate/models.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class _SchemeContext:
1919
replayed: bool
2020
unsettled: list
2121

22+
2223
@dataclass(frozen=True, slots=True)
2324
class _SchemeReadings:
2425
failsoft: list

‎plugins/leaf/skills/leaf/scripts/leaf/render_gate/preview.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ def preview_server(
4949
finally:
5050
httpd.shutdown()
5151

52+
5253
@contextlib.contextmanager
5354
def preview_source_server(
5455
page_dir: Path,

‎plugins/leaf/skills/leaf/scripts/leaf/render_gate/scheme.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ def served(page, url: str, path: str, timeout_ms: int | None = None):
3030
timeout_ms = SERVED_TIMEOUT_MS if timeout_ms is None else timeout_ms
3131
return page.request.get(urljoin(url, path), timeout=timeout_ms)
3232

33+
3334
def previous_stamp(revision: int, versions: list[dict]) -> dict | None:
3435
"""The newest stamped revision before ``revision``, if one exists."""
3536
earlier = [version for version in versions if version["revision"] < revision]
3637
return max(earlier, key=lambda version: version["revision"]) if earlier else None
3738

39+
3840
def rendered_revision(url: str, state: dict) -> int:
3941
"""Resolve the immutable revision shown at ``url`` from the public state."""
4042
name = Path(urlsplit(url).path).name
@@ -54,9 +56,11 @@ def rendered_revision(url: str, state: dict) -> int:
5456
def resize_observer_error(text: str) -> bool:
5557
return text.startswith(RESIZE_OBSERVER_ERROR)
5658

59+
5760
def recurring_resize_observer_error(unit: str) -> str:
5861
return f"{RESIZE_OBSERVER_ERROR} notice recurred on the confirming {unit}"
5962

63+
6064
def _render_scheme(browser, url, scheme, served_timeout_ms, opened_pages):
6165
"""Read and report the browser gate for one color scheme."""
6266
from playwright.sync_api import Error as PlaywrightError

‎plugins/leaf/skills/leaf/scripts/leaf/render_gate/version.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def _render_version_attempt(
6262
light_complete and dark_complete,
6363
)
6464

65+
6566
def render_version(browser, url: str, served_timeout_ms: int | None = None) -> list:
6667
"""Read a version, confirming a complete attempt that reports a ResizeObserver
6768
loop notice.

0 commit comments

Comments
 (0)