Skip to content

Draw only the lines of a long text document that are in view - #5061

Merged
max-sixty merged 11 commits into
mainfrom
grind/text-document-large-draw
Nov 2, 2026
Merged

max-sixty merged 11 commits into
mainfrom
grind/text-document-large-draw

Conversation

@max-sixty

@max-sixty max-sixty commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

A long text document now draws only the runs of lines near the view. #5063 fixed the selector that made restyling a long run of siblings quadratic; this change takes the rest. With that fix, a text document bound to 1 MB of text still spent 4 s of main-thread time drawing and peaked at 2 GB in the renderer, and 4 MB spent 16 s and 6.5 GB. They now draw in 0.4 s and 1.0 s, peaking at 310 MB and 650 MB. The work on #4781 (export performance, #5053) found the slow draw.

Before and after

Main-thread CPU (thread ticks from Performance.getMetrics), wall time to drawn, and the peak resident memory of the renderer, one run each. The first column is main (b299fe0) with #5063's fix applied; the second is this branch at its head. The host was loaded, so the CPU column is the reading to trust.

Page after #5063 this change
1 MB plain text 4.0 s CPU, 5.3 s, 2.0 GB 0.37 s, 0.7 s, 310 MB
4 MB plain text 15.8 s, 17 s, 6.5 GB 0.96 s, 1.3 s, 650 MB
1 MB Python 6.6 s, 8.1 s, 3.1 GB 0.8 s, 2.0 s, 490 MB
4 MB Python 26.3 s, 28 s, 8.2 GB 2.5 s, 2.8 s, 1.2 GB
1 MB Markdown, preview="markdown" 4.0 s, 5.2 s, 1.6 GB 1.7 s, 5.5 s, 640 MB
4 MB Markdown, preview="markdown" 21.5 s, 23 s, 5.6 GB 11.5 s, 13 s, 2.1 GB

On the reviewer's 1 MB fixture, 12,407 lines of up to 407 characters, so most rows wrap, read in Chromium 156 and Firefox 157 (Playwright's builds). "Before" is this branch's previous head, 056c047, merged with main:

Reading before, Chromium before, Firefox now, Chromium now, Firefox
Drag to the bottom, first try 1,580 px short 980 px short at the end at the end
End on the focused listing at the end 2,440 px short at the end at the end, once the face has settled (below)
t to line 11,000 after a reload line at 214 px, after a second landing line reported at 214 px, but elementFromPoint there found line 11,041 and its run was still skipped line at 214 px, one jump line at 214 px, one jump, the hit-test finds line 11,000
End after narrowing from 718 to 460 px, last runs drawn before 240 px short (b57ae94) 1,700 px short (b57ae94) at the end at the end
Wheel step, 4 MB plain / 4 MB Python, median 110 ms / 475 ms (review) 8.5 ms / 19 ms

Causes

Every row was styled several times per load. With the selector fixed, a load still restyled every element three times. The first pass ran inside a layout, after @property registrations marked the whole document. Marking the listing's scroller (data-lf-scrolls) changed an inherited property on it. The body's data-lf-presented stamp ended transition: none on everything in main. At about 17 µs per element per pass, a 280,000-element listing took 15 s. The listing's rows now stand in runs of 128 rows, each content-visibility: auto (lf-text-document.js, inRuns). The browser styles and lays out only the runs near the view, so each of those passes covers a few hundred elements. The text stays in the DOM: find-in-page, selection, copy and comment anchoring work on all of it. A lone run stays drawn, so a short text draws as before, and a log that grows past one run keeps its rows and a selection in them.

Each run lays out Pierre's two columns as its own grid. The run sizes its number column to its own numbers, so a number takes the width of the text's widest one (--diffs-min-number-column-width-default), and every run's lines start at the same x.

A row that lines added above it carried into another run was drawn anew. Reconciled run by run, each run was the identity boundary for its rows. One line prepended above the last row of a run grew a selection there to take in the row before it in Chromium, and cleared it in Firefox; two hundred cleared it in both. The rows are now reconciled across the whole listing (reconcileRuns). Which old line each new line stands for comes from a walk over whole lines private to the widget (keptLines, jsdiff's diffArrays capped at 1,000 edits, as the runtime's text alignment is); a run of lines replaced by as many others stands for them one for one, so an edited row is kept and its text patched in place. The kept rows move into the runs the new text puts them in with setChildLists, and each run then reconciles its rows with setRenderedChildren, finding its kept rows in place. A run's numbers stay with it, since they count its places. Where a rewrite runs past the walk's cap of 1,000 edits, nothing moves and each run reconciles its own rows, as before: walked to the end, every line of 4 MB rewritten took 285 s in review.

Moving a node lost a selection in it. The DOM's move algorithm runs the live range pre-remove steps, so a selection with an end inside a moved node is reset, moveBefore included, in Chromium and Firefox. setChildLists now holds the page selection where an end lies inside a node it places, and puts it back through selectEnds once the nodes have landed and before the caller edits any text (holdSelection in native-selection.js, which leaf.js installs into dom-move.js before the boot draws anything, so the portable mover still loads off Leaf). It installs there rather than beside installMoveFocus in move-focus.js: native-selection.js reaches context.js through shadow.js, and imported from move-focus.js, which framework.js imports first, it left readPart uninitialized when a module read it. An end inside a shadow tree stays its editor's. lf-call-diff, which reorders its rows with setChildLists, keeps a selection on a reordered row too; without the hold it was cleared in both engines.

A skipped run is sized by estimate, and the estimate was a line a row. On wrapped text that fell thousands of pixels short. End, a drag to the bottom and travel to a line each stopped short as the runs they passed took their real heights. Each run's contain-intrinsic-block-size now counts the lines its rows fill (sizeRuns): a row's characters broken as pre-wrap breaks them, at the line length read off the drawn first run. On the 1 MB wrapped fixture and a 1 MB Python file the estimate matches the drawn height to the pixel, in Chromium and in Firefox once its face settles. The runs are sized again when the listing's width changes or a drawn run changes height, as when a freshly started Firefox swaps its fallback face for its real one. That swap comes seconds after launch: before it, Firefox's estimate was 80 px off the drawn height on prose and 3.9% off on highlighted Python. End pressed in those seconds still ends up to 600 px short, since the run on screen grows when the face arrives; on main the same window left the fourth drag to the bottom 59,400 px short.

A run drawn at one width kept that height at another. Chromium, Firefox and WebKit keep a skipped run's drawn height, whether or not contain-intrinsic-size says auto, until its style resolves with neither auto nor content-visibility: auto; writing the size without auto, for frames on end, changed nothing. css-sizing-4 says the height goes at ResizeObserver timing once auto is gone, and no engine does that, so the forgetting below rests on uniform but unspecified behaviour: notes/browser-support.md records it, and the drag after narrowing in the long-document test is its tripwire. WebKit, measured in review: End and the drag 1,834 px short without the forgetting, at the end with it. Narrowed after the last runs were drawn, End stopped short (the table above). When the line length changes, each run drawn since it last forgot a height (contentvisibilityautostatechange) that is skipped now resolves its style once as hidden without auto, then takes both back in the same task, before anything is drawn. Only such runs go through it: the resolution cost Firefox about 60 ms on 4 MB, and 426 ms when every skipped run whose size changed went through it. Firefox's first refit after a narrowing on 4 MB now takes 85 ms against 27 ms without forgetting; Chromium's 29 ms against 24 ms. The refit also runs in the frame after the ResizeObserver's delivery: inside it, when Firefox's face arrived, it resized the code the observer watches, and Firefox reported "ResizeObserver loop completed with undelivered notifications".

Asking about skipped content restyled it. skipped() (shown-box.js) called checkVisibility() without contentVisibilityAuto, and for content an off-screen auto box skips, the browser styles that content to answer. The reading-place walk asks it of every line, so the first scroll restyled every run. skipped() now climbs with checkVisibility({contentVisibilityAuto: true}) alone, and skipper() names the box that skips an element, so the reading-place walk asks once per run and passes over the rest of its lines. The live view's scrollbar check (render-checks/scrollbars.js) had the same problem and now passes over skipped content too, so it can't see the end of a long document while the reader is away from it. Runs alone made the first scroll inside a 1 MB listing take 1.3 s and the live view's first report 1.4 s; they now take 57 ms and 25 ms.

Travel jumps into skipped content, and draws where it lands. A thread or datum travel into a content-visibility: auto box lands at once (anchor-travel.js): a glide across the runs drew each one it passed, which took 2.4 s on a long text. The jump computed its landing from the skipped run's estimated layout, and Firefox keeps a run skipped until it meets the view at an update. Where the estimate is short, as over long tokens, which Firefox also breaks after a slash, the landing was off: on the review fixture Firefox drew lines 26 past the destination, and in the long-document test the jump stopped 104 px short and a second scroll followed. Travel now draws the run holding the destination for the jump and releases it two frames later (drawForLanding), so the landing no longer depends on the estimate; notes/browser-support.md records the Firefox gap. A run a landing holds drawn still counts as skippable (skippableBox), though its computed style reads visible: read from the style alone, a second t within those two frames, as a held key repeats, glided, and in Chromium on the base64 fixture left line 1148 1,220 px out of view, and Forward missed too.

Remaining costs

  • The first wheel step. It builds the page's reading of passages, 181 ms on 4 MB of plain text and 549 ms on 4 MB of Python; later steps take 8.5 ms and 19 ms.
  • Select-all. A selection over the whole listing draws every run: 13.7 s on 4 MB of plain text, and 34 s and 7.8 GB on 4 MB of Python (review).
  • Markdown preview. A 4 MB Markdown preview still takes 11.5 s. The preview's blocks are restyled three times, as the rows were, and grouping them into runs would change how margins collapse at each run's edge.
  • lf-code and lf-diff. They draw their own rows, so runs would be a change in each. At 22,000 lines, with Restyle long runs of siblings in linear time #5063, they take 9 s and 4.6 s.
  • Full restyles at load. The three passes above cost every page a full restyle per load. On ordinary pages that is tens of milliseconds.

Calls Max may reverse

  • Travel jumps. A thread or datum travel into a long text document's lines, or any content-visibility: auto content, jumps rather than glides.
  • Text whose lines break other than as the estimate assumes ends short. On CJK or base64-heavy text, End or a drag to the bottom can stop short (Chromium on CJK about 1.7k px, Firefox End on base64 about 19.5k px), and a second press reaches the end. My call is to accept that rather than add per-character-class break rules. In Firefox, End scrolls smoothly and draws each run it passes; where those runs draw taller than their estimate, the code grows during Firefox's ResizeObserver loop and it logs "ResizeObserver loop completed with undelivered notifications".

What I ran

  • The reviewer's journeys on their fixtures (.tmp/review/ in the review worktree): End and the drag, travel after a reload with and without a wheel during the landing, the Firefox hit-test, growth past one run, and the wheel-step profile. Estimate accuracy: each run's estimated height against its drawn height on the 1 MB wrapped and Python fixtures, in both engines. Draw cost: a Playwright script that reads Performance.getMetrics in thread ticks and samples the renderer's RSS.
  • test_a_long_text_document_draws_the_lines_in_view_and_keeps_the_rest_whole, in Chromium and Firefox, on wrapped text with base64 lines in every run but the last: a drag to the bottom after the window narrows reaches the last line, two travels back to back into one run, the second while frames are held so the first still holds the run drawn, take one scroll each, and elementFromPoint at the second line's reported place finds it. Sized a line a row, it fails in Firefox at the skip check after the reload, and passes in Chromium. Without drawForLanding, it fails in Firefox with an extra scroll. Without the forgetting, the drag stops 672 px short in Chromium and 32 px in Firefox. Without the skippableBox fix, the second travel glides: 48 scroll steps in Chromium and 31 in Firefox.
  • End after narrowing on the 1 MB fixture (j_end_narrow.py), fresh and with the last runs drawn before, in both engines: at the end in all four.
  • test_a_text_document_update_keeps_a_selection_it_carries_into_another_run, in Chromium and Firefox: a selection on the last row of a run in a 278-line text survives one line prepended, its own line edited in place, and 200 lines prepended with its line edited again, and the numbers count every row in order. At 1e10ee2, and without the hold, it fails at the first insertion: Chromium's selection reads line 127\nselected passage\n, Firefox's is empty. Without pairing replaced lines, it fails at the edits.
  • tests/runtime/text-document-lines.test.mjs, importing the widget's keptLines: it shifts lines past an insertion, pairs a same-length replacement, and gives up (null) on a full rewrite or every other line edited of 2,000 lines, so the widget takes the per-run path. Without the cap it fails in 0.25 s; without the pairing it fails too.
  • An lf-call-diff check (not committed): a selection on a row a data update reorders stays, in Chromium and Firefox; without the hold it is cleared.
  • The selection and call-diff tests that setChildLists reaches, in test_render_semantic_selection.py, navigation/test_commenting.py, drafts/test_comment_targets.py, test_render_aim.py, widgets/test_diffs.py and test_render_diff_controls.py (68 passed, 3 failed). The three fail the same way with main's copy of every file this branch changes: test_borrowed_scroll_stops_leave_code_selection_and_marks_with_their_owners[None|-1] (no dialog on the marked code) and test_a_diff_refresh_keeps_a_selection_in_unchanged_lines (its gutter read finds no lines on the diff's file entry, after the selection check passes).
  • The update cost, main-thread task time from cmd_data_set to the drawn update (Performance.getMetrics in thread ticks), two runs each, 1e10ee2 → this head: 4 MB one line prepended 1.41 → 1.29 s; 200 more prepended 2.08 → 2.27 s; every line rewritten 1.74 → 1.61 s; 1 MB every tenth line edited 0.37 → 0.37 s; every line rewritten 0.44 → 0.42 s. Main took 4.31 s and 4.68 s for the two prepends. The 4 MB load is unchanged: 0.75 s of task time, 0.86 to 1.04 s to drawn, 554 to 572 MB, on both.
  • uv run pytest tests/browser/widgets/test_code_and_documents.py -k document (18 passed); earlier, the travel tests in navigation/test_reading_place.py and test_render_anchors.py (12 passed; 4 failed and 3 errors, the inherited bottom-clearance and deferred-diff failures below). The text-document, scrollbar-clearance, state-wait, parts, tabs, travel and skipped-content tests in test_render_pages.py, widgets/test_tabs.py, test_geometry.py, navigation/test_threads.py, test_render_anchors.py, navigation/test_reading_place.py, threads/test_targets.py, projection/test_code_review.py, startup/test_projected_data.py, controls/test_rings.py, widgets/test_workspaces_and_bounds.py and test_render_gate.py (87 passed, 5 failed, 3 errors, all inherited).
  • pnpm run test:runtime (749 passed), pnpm run check (passed), pnpm run build:browser (kernel rebuilt), and uv run pre-commit run --files on every file this branch changes.

Inherited failures, which fail the same way with main's own files in place of this branch's: test_thread_travel_keeps_its_passage_above_the_bottom_reading_clearance, test_datum_travel_resolves_the_destination_after_reveal, test_thread_travel_into_a_bounded_log_scrolls_the_log_and_the_page_no_more[named|anonymous], and test_a_deferred_diff_renders_only_opened_files_and_hydrates_comment_travel (lf-diff's loadEntry reads path of null).

Not verified: the browser's own find-in-page bar, which a headless browser can't open; Safari on a device; Firefox on a machine other than this Mac, where the listing's face may arrive at another time.

This was written by Claude Code on behalf of max-sixty

A text document bound to 1 MB of 80-character lines took 42 s of
main-thread time to draw on main, and 4 MB hadn't drawn after 300 s.
Both now draw in about a second of main-thread time (0.4 s and 1.1 s),
with renderer peaks of 330 MB and 640 MB.

A selector in layouts.css made restyling a long run of siblings
quadratic. The parts title rule has no class or tag in its subject and
tested `:has(~ [data-lf-views="parts"])` first, which reads every later
sibling of every element. `:where(main > *)` now comes first. lf-code at
22,000 lines went from 78 s to 9 s on that change alone.

Each page load still restyled every row three times. A long text
document's rows now stand in runs of 128 rows, each
`content-visibility: auto`, so the browser styles and lays out only the
runs near the view. The text stays in the DOM for find-in-page,
selection, copy and comments. Each run sizes its number column to its own
numbers, so a number takes the width of the text's widest one.

Asking whether skipped content is drawn restyled it: `skipped()` and the
live view's scrollbar check called `checkVisibility()` without
`contentVisibilityAuto`. The first scroll of a 1 MB listing took 1.3 s
and the live view's first report 1.4 s; they now take 57 ms and 25 ms.

Travel into skipped content now jumps, since a glide aims at estimated
sizes and stopped thousands of pixels short. Until the user's next input,
it also lands again each time the boxes around the destination resize as
they are drawn.

Behavior changes: travel into content-visibility: auto content jumps
rather than glides; a long text document's DOM is grouped in runs, and a
row that a change above it moves into the next run is rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The landing watch bypasses Leaf’s rendering coordinator. uv run pre-commit run eslint --files browser/runtime/anchor-travel.js fails at line 532 with no-restricted-globals: size observations must use sizeObserver so the settled reading counts their work. Using that owner also keeps landing corrections in the same readiness accounting as the other geometry observers.

Comment thread browser/runtime/anchor-travel.js Resolved
Comment thread browser/runtime/anchor-travel.js Resolved
The rule that places what a page writes before its parts (layouts.css)
has no class or tag in its subject, so the browser tests it against
every element on every style pass. Its first condition was
`:has(~ [data-lf-views="parts"])`, which reads every later sibling of
the element tested. On a long run of siblings, such as the 18,000 rows
of a 1 MB text document or the lines of a long lf-code block, each pass
cost time in the square of the row count.

`:where(main > *)` now stands first in that compound, in all three
copies of the rule. An element outside `main` fails it at once, before
any sibling is read. The rule's subject already sits under
`body > main:not(...)`, so the guard changes no match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o HEAD

# Conflicts:
#	dist/kernel/kernel.json
@max-sixty
max-sixty changed the base branch from main to grind/sibling-selector-cost November 2, 2026 07:08
@max-sixty max-sixty changed the title Draw a megabyte text document in a fraction of a second, not minutes Draw only the lines of a long text document that are in view Nov 2, 2026
max-sixty added a commit that referenced this pull request Nov 2, 2026
Pages with a long run of sibling elements now restyle in linear time. On
`main`, a 1 MB text document spent 44 s of main-thread time drawing,
almost all of it in style; with this change it spends 3.9 s. Part of
#4781, whose export work (#5053) found the slow draw.

### Cause

The rule in `layouts.css` that places what a page writes before its
parts (the title column beside `[data-lf-views="parts"]`) has no class
or tag in its subject, so the browser tests it against every element on
every style pass. The browser checks a compound's conditions in the
order written, and the first was `:has(~ [data-lf-views="parts"])`,
which reads every later sibling of the element tested. On an element
with thousands of later siblings, such as a row of a long text document
or a line of a long `lf-code` block, each test read them all, so a pass
over n siblings cost n². Selector statistics and ablation located it:
removing these three rules cut a 300 KB listing's restyle from 1,448 ms
to 406 ms.

### Change

`:where(main > *)` now stands first in the compound, in all three copies
of the rule, so an element outside `main` fails at once and no sibling
is read. The rule's subject already sits under `body > main:not(...) >`,
so the condition matches every element the rule matched before and no
other.

### What every page gains

Main-thread CPU (thread ticks from `Performance.getMetrics`), from
navigation until the page is drawn. The host was loaded (one-minute load
5–17), so the CPU column is the reading to trust.

| Page | `main` | this change |
| --- | --- | --- |
| `lf-text-document` bound to 1 MB of text (18,000 lines) | 44.1 s CPU
(43.4 s style), 44 s wall | 3.9 s CPU (3.3 s style), 4.9 s wall |
| `lf-code`, 22,000 lines | 64.0 s CPU (62.8 s style), 64 s wall | 9.0 s
CPU (7.9 s style), 10 s wall |
| `review-a-plan`, median of 7 interleaved loads | 141 ms CPU (35 ms
style) | 143 ms CPU (36 ms style) |
| the corpus page, median of 5 interleaved loads | 24.8 s CPU (2.59 s
style) | 24.0 s CPU (2.37 s style) |

An ordinary page has no long run of siblings, so it gains nothing
measurable: the `review-a-plan` difference is noise, and the corpus
page's style time moved by less than its script time did, which this
change can't touch. Peak renderer memory is not lower: the 1 MB page
peaked at 1.3 GB on `main` and 2.0 GB here, since the same styles are
built in a shorter burst. #5061 addresses the memory.

### Evidence that it changes no style

- `uv run leaf-dev stills 5a16ff0` over 15 states: the corpus
(`on-me`, `on-me-dark`, `on-agent`), the feature gallery
(`gallery-tabs`, `gallery-theme`, `gallery-theme-dark`), the side-list
workspace (`side-tab-focus`, `alert-queue`), `native-code`,
`walkthrough`, `plan`, `triage`, `hub`, `page-about` and
`markdown-preview-scrolled`. Thirteen states were unchanged.
`page-about` differed in pixels with no computed-style difference, as
its states always do. One corpus state differed in 20 computed
properties on one element, the preview of the widget builder's generated
request document, which sits in `main.layout-column`, where the rule
can't match. A second run moved that difference from `on-me-dark` to
`on-me`, so it varies from load to load.
- The rule's only target is a `main` with no Layout whose children
include a parts holder after other content.
`tests/fixtures/pages/root-parts.html` is that page: a header before
`lf-parts`. Every computed property of all 452 elements, in the document
and its open shadow trees, matched between `main` and this change
(`leaf-dev probe --base` with reduced motion), apart from one
`mask-image` whose URL names each arm's own revision path. The header
kept `position: fixed`, `grid-column: 1` and `anchor-name:
--lf-parts-title`.
- The rule lives in the `lf-layouts` layer every page composes, whatever
its theme, and the condition it adds reads no theme value.

### What I ran

- The tests that read the parts layout:
`test_each_part_of_a_page_of_parts_is_laid_out_as_a_page_of_its_own`,
the parts, side-list, strip and workspace-part tests in
`widgets/test_tabs.py`,
`test_a_page_read_from_its_top_stays_at_its_top_as_the_window_narrows`
and the part ring tests in `controls/test_rings.py` (20 passed).
- `pnpm run check` (passed).
- Timing: a Playwright script serves each page from an extracted `main`
arm and from this tree (`leaf_dev.arms.serving_source`), reads
`Performance.getMetrics` in thread ticks, and samples the renderer's
RSS. The 1 MB and `lf-code` pages are generated fixtures of 80-character
lines.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 <[email protected]>
Base automatically changed from grind/sibling-selector-cost to main November 2, 2026 07:25
max-sixty and others added 4 commits November 2, 2026 00:02
# Conflicts:
#	dist/kernel/kernel.json
Runs were sized a line a row until drawn, so on wrapped text the estimate
fell thousands of pixels short. End, a drag to the bottom and travel to a
line each stopped short as the runs they passed took their real heights,
and in Firefox travel left a skipped run on screen, where another line was
drawn.

Each run's `contain-intrinsic-block-size` now counts the lines its rows
fill: a row's characters broken as `pre-wrap` breaks them, at the line
length read off the drawn first run. On a 1 MB wrapped text the estimate
matches the drawn height to the pixel in Chromium, and in Firefox once
its face settles. The runs are sized again when the listing's width
changes or a drawn run changes height, as when a freshly started Firefox
swaps its fallback face for the real one.

With the runs sized, a single jump lands: the landing that re-landed on
each resize until the next input is gone, with its ResizeObserver. Travel
into a box the browser skips still jumps, since a glide across the runs
took over two seconds.

Every text now builds runs, and a lone run stays drawn, so a short log
that grows past one run keeps its rows and a selection in them.

The reading-place walk asks once per skipped run rather than once per
line (`shown-box.js`, `skipper`): a wheel step on a 4 MB text took
110 ms and now takes 8.5 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Travel into a skipped run computed its landing from the run's estimated
layout. Where the estimate is short, as over long tokens, which Firefox
also breaks after a slash, the jump stopped short: 104 px past base64
lines in the long-document test, followed by a second scroll, and on the
review fixture Firefox drew lines 26 past the destination. Travel now
draws the run holding the destination for the jump and releases it two
frames later (`anchor-travel.js`, `drawForLanding`).

A run drawn at one line length kept that height at another, since
Chromium and Firefox keep a skipped run's remembered height until its
style resolves with neither `auto` nor `content-visibility: auto`;
writing the size without `auto`, for frames on end, changed nothing.
Narrowed from 718 to 460 px after the last runs were drawn, End stopped
240 px short in Chromium and 1,700 px in Firefox. When the line length
changes, each run drawn since it last forgot (`contentvisibilityautostatechange`)
that is skipped now resolves its style once as `hidden` without `auto`,
then takes both back in the same task. End after that narrowing lands in
both engines. Forgetting only those runs keeps Firefox's first refit on
4 MB at 85 ms; forgetting every skipped run whose size changed took
426 ms.

The refit moves to the next frame: run inside the ResizeObserver's
delivery when Firefox's face arrived, it resized the code the observer
watches, and Firefox reported "ResizeObserver loop completed with
undelivered notifications".

The long-document test gains base64 lines in every run but the last, a
target in the run before the last, and a drag to the bottom after the
window narrows. Its docstring now says where each regression shows:
sized a line a row, Firefox draws the far run for a returning reader;
without the drawn landing, Firefox scrolls twice; without the
forgetting, the drag stops short in both engines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`skippableBox` read the computed `content-visibility`, which is `visible`
while `drawForLanding` holds the run for the two frames after a jump. A
second travel into the same run within those frames, as a held `t`
repeats, took the glide: in Chromium on the base64 fixture it left line
1148 1,220 px below the box top, and Forward missed too. A box the
landing holds now counts as skippable, so the second travel jumps.

The long-document test comments on two lines in one run and travels to
both back to back, holding frames between the presses so the first
landing still holds the run: without the fix the second travel glides,
48 scroll steps in Chromium and 31 in Firefox, against one each.

`notes/browser-support.md` records the remembered height the forgetting
in `sizeRuns` relies on: Chromium, Firefox and WebKit keep a skipped
box's drawn height whatever `contain-intrinsic-size` says, and drop it
only when its style resolves with neither `auto` nor
`content-visibility: auto`, where css-sizing-4 drops it at
ResizeObserver timing once `auto` is gone. The drag after narrowing in
the test is its tripwire. The `sizeRuns` comment points there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@max-sixty
max-sixty marked this pull request as ready for review November 2, 2026 10:49

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve selections when unchanged rows cross a run boundary. Grouping rows before setRenderedChildren makes each run a separate matching boundary, so a source update can replace an unchanged selected row merely because its line number crosses a multiple of 128. In Chromium I selected selected passage on line 128 of a 278-line document, then prepended one line through cmd_data_set: after told and rendered, the selection became line 126\nselected passage\n instead of selected passage\n. The same probe passes on the merge base. A larger insertion cleared the selection entirely. This changes what a subsequent copy or comment acts on during an ordinary live update; the existing retention test covers only a two-line document.

The performance gain is worth keeping, but the run structure should remain a rendering boundary rather than become the identity boundary for source rows. Reconcile unchanged rows across the whole listing and retain them when distributing them among runs (the existing setChildLists owner supports moving retained nodes between parents), or otherwise preserve the native selection across regrouping. Documenting the loss in the module header does not preserve the selection guarantee in root AGENTS.md, The document starts state; the log changes it.

Each run was reconciled on its own, so a run was the identity boundary
for its rows: a row that lines added above it carried across a run's
edge was drawn anew. With a selection on the last row of a run in a
278-line text, one prepended line grew Chromium's selection to take in
the row before it and cleared Firefox's; two hundred cleared both.

The runs are now a drawing boundary only (`reconcileRuns`). The lines the
new text keeps, read off a diff of the old and new lines (jsdiff's
`diffArrays`, as the reconciler uses), move into the runs the new text
puts them in with `setChildLists`, and each run then reconciles its rows
with `setRenderedChildren`, finding its kept rows in place. A run's
numbers stay with it, since they count its places; moved with their rows,
a number left a run and an equal one arrived, an unchanged write.

Moving a node resets any live range inside it, `moveBefore` included, in
Chromium and Firefox: the DOM's move algorithm runs the live range
pre-remove steps. So the selection's ends, still in the same nodes, go
back once the rows have landed; without that, the test fails as before.
After an update, the runs are sized again with the drawn ones forgetting
their heights, since their rows may have changed.

Updating 4 MB of plain text after one line is prepended takes 1.29 s of
main-thread task time, against 1.41 s before and 4.31 s on main; after
200 more, 2.29 s against 2.12 s and 4.68 s.

`test_a_text_document_update_keeps_a_selection_it_carries_into_another_run`
covers both insertions in Chromium and Firefox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Bound the whole-list alignment before a large rewrite freezes the page. reconcileRuns now runs an unrestricted Myers diff over every old and new line synchronously. Replacing a long document with substantially different text therefore adds quadratic main-thread work before any updated content can draw. Using this checkout's diffArrays on 8,000 unique old lines and 8,000 unique replacement lines took 10,037 ms in Node; comparing those arrays in the former 128-line runs took 170 ms. Larger documents are the case this PR is meant to improve.

Keep the whole-list matching for small edits, but bound its edit search and fall back to replacement when the bound is exceeded, as the existing alignText owner in browser/runtime/text-alignment.js does. A 1,000-edit bound stopped the same reproduction in 83 ms. The inline suggestion shows that approach; the appropriate bound can be chosen independently.

@max-sixty
max-sixty marked this pull request as draft November 2, 2026 11:52
max-sixty and others added 3 commits November 2, 2026 03:54
…hildLists

The whole-listing reconcile walked a diff of every line with no bound, so
a full rewrite froze the tab: every line of 4 MB rewritten took 285 s.
`keptLines` (text-alignment.js) now gives the correspondence from the
same capped jsdiff walk the runtime's text alignment uses, 1,000 edits,
and returns null past it; the widget then moves nothing and lets each
run reconcile its own rows, as before the whole-listing reconcile. Every
line of 4 MB rewritten now takes 1.61 s of task time (1.74 s at
1e10ee2).

The line walk took an edited line for a removed line and an added one, so
a selected row edited in place was rebuilt and lost its selection. A run
of lines replaced by as many others now stands for them one for one, so
the edited row is kept and its text patched in place.

The selection hold moves out of the widget into `setChildLists`, which
calls the mover that resets it: the DOM's move algorithm resets a live
range with an end inside a moved node, `moveBefore` included. It reads
the page selection where an end lies inside a node it places and puts it
back through `selectEnds`, the one endpoint writer, once the nodes have
landed and before the caller edits their text, so the DOM's own range
adjustment for an edit stands. `native-selection.js` installs the hold
in `dom-move.js`, which keeps the portable mover loadable off Leaf.
`lf-call-diff`, which reorders rows with `setChildLists`, keeps a
selection on a reordered row too.

`keptLines` is public through the widget API and documented in
module-reading.md. A Node test pins its pairing and that a full rewrite
or every tenth line edited of 20,000 lines gives up. The run-edge
selection test adds the selected row edited in place and edited as it
moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`keptLines` leaves the widget API, module-reading.md and text-alignment.js:
one caller and one row-reuse rule are no contract for packages across Leaf
versions, and text-alignment.js explains how a text changed rather than
which drawn node to keep. The walk is private to lf-text-document.js
again, on jsdiff's `diffArrays` capped at 1,000 edits, and exported only
for its Node test, which now imports the widget module. The test's
rewrite cases shrink to 2,000 lines so that, without the cap, it fails in
a quarter of a second rather than walking for minutes.

The selection hold was installed as a side effect of native-selection.js
loading. leaf.js now installs it before the boot draws anything. It
stays out of move-focus.js, beside `installMoveFocus`: native-selection.js
reaches context.js through shadow.js, and imported from move-focus.js,
which framework.js imports first, it ran a module before `readPart`
(semantic-state.js) was initialized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@max-sixty
max-sixty marked this pull request as ready for review November 2, 2026 12:45
@max-sixty
max-sixty merged commit 0bc46e0 into main Nov 2, 2026
5 checks passed
@max-sixty
max-sixty deleted the grind/text-document-large-draw branch November 2, 2026 13:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants