Files
museion/docs/devlog/20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md
T
AlexKucera cc317b65b9
CI / ci (push) Canceled after 0s
perf(editor): scope fold re-key to the edit (#142)
With a fold open, every keystroke re-scanned the buffer, rebuilt the
full attributed string through setAttributedString (invalidating
TextKit layout for the ENTIRE document — O(n²) typing on folded
documents), and rasterized a chrome image the size of the document
(~35M pixels on a 700×50,000pt doc) to paint a handful of chevrons.

Single-line edits now re-key folds in place: a shouldChangeText
override records the edit (range + UTF-16 delta) and a pure rekey
function shifts surviving folds, kills folds whose marker line was
edited (un-hiding just that scope), and re-hides a line edited inside
a hidden scope — no parents rescan, no storage swap. Structural
edits, multi-line pastes, and wholesale loads keep the full pass; a
font probe at each survivor's scope head falls back to it whenever
hidden styling was wiped (the fence-flip restyle self-heals this way).

Chrome renders as one tiny cached layer per list parent (same glyph
rasters at ~15×18pt, geometry-flipped into the existing document-space
overlay) instead of the document-sized bitmap; an edit at/after every
parent line skips the rebuild outright, so writing at the document end
does zero geometry queries. Full-buffer scans per keystroke drop from
2–3 to one.

Finish-audit hardening: the single-line gate checks Character.isNewline
(a literal newline compare passes CRLF — one grapheme equal to neither
scalar), and apply() clears the recorded edit so structural indent/
outdent always takes the full pass (a childless unterminated block's
shift-tab is a single-line replacement that would otherwise keep a
dead fold's scope hidden — apparent line loss).

Closes #142
2026-11-03 10:40:14 +01:00

104 lines
8.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# #142 — paragraph-scoped fold re-key + per-glyph chrome layers
> **Date:** 2026-11-03
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/142
## Goal
With a fold open, every keystroke re-attributed and re-rasterized the whole
document (audit F1/F2 High): a full-buffer `ProseList.parents` scan, a
full-document `NSMutableAttributedString` rebuild through
`setAttributedString` (invalidating TextKit layout for the entire document,
per keystroke — O(n²) typing on folded documents), plus a chrome overlay
rastering an NSImage the size of the FULL document (~35M pixels on a
700×50,000pt doc) with 2–3 further full-buffer scans.
## What Was Done
- **F1 cheap re-key path** (`ProseListTextView.swift`): a `shouldChangeText`
override records the last accepted single-line edit (old-coords range +
UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes it through
`rekey` — a pure, `nonisolated static` function returning `RekeyOutcome`
(survivors shifted by delta, dead folds with translated scopes for
un-hiding, a re-hide range, a caret-park target). No parents rescan, no
storage swap. `Fold` gained the hidden `scope` (shift-maintained).
- **Guards around the cheap path**: a font probe at each survivor's scope
head falls back to the full pass when hidden styling is gone (the
fence-flip's wholesale restyle self-heals this way, pinned);
`apply()` nulls `pendingPlainEdit` — structural edits always take the full
pass (finish-audit: a childless unterminated block's ⇧⇥ is a single-line
replacement that would otherwise keep a dead fold's scope hidden);
the single-line gate is `\.isNewline`, never a literal `"\n"`/`"\r"`
compare (`"\r\n"` is ONE grapheme equal to neither — finish-audit,
converged ponytail+general finding, pinned).
- **F2 chrome rework**: chevrons/⋯N render as one tiny CALayer per visible
parent (contents = small flipped-NSImage raster, cached by glyph string in
`chromeGlyphImages`; overlay layer `isGeometryFlipped` so sublayer frames
speak lineRect's top-left y). Deleted the bitmap era:
`renderChromeImage`, `proseParentCount`, `drawListChrome`. An edit at/after
every parent line skips the rebuild outright (`parentsUnmoved`) — typing
at document end does zero `lineRect` queries. Scans per keystroke: 2–3 → 1
(the rebuild's own, same cost class as the staying `fenceDelimCount`).
- **Tests** (`MuseionTests/ProseRekeyTests.swift`, own file): view-level
pipeline pins (re-key in place, marker-line death + scope restore,
multi-line/CRLF/newline-deletion routing, wholesale-restyle self-heal,
structural outdent, scope-interior re-hide + park) and pure-math pins
(shift above/below, death + translated diedScope, boundary insertions,
scope-interior deletion). Existing `ProseFoldRenderingTests` Fold pins
widened with `scope`.
- **DOX**: `Museion/AGENTS.md` (#142 fold-maintenance + chrome bullets) and
`MuseionTests/AGENTS.md` (ProseRekeyTests entry).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Delta-shift re-key instead of rescanning parents per keystroke | A single-line edit can only shift offsets below it, kill a fold via its marker line, or touch one hidden scope — all O(1)-per-fold math. Full pass stays for multi-line/structural edits, wholesale loads, toggleFold. |
| Fold death on ANY marker-line-content edit (incl. insertion at the caret-park position) | Full-pass parity: the stored `lineText` no longer matches after such an edit, so the full re-key would kill it anyway — and it keeps `lineText` fresh on survivors by construction. |
| Font probe as the cheap path's safety net | Any wholesale restyle (fence-flip branch replaces the whole storage AFTER the edit was recorded) wipes hidden styling; probing one attribute per survivor is O(folds) and self-heals into the full pass without API coupling to the coordinator. |
| Per-glyph CALayers, not a viewport-sized bitmap | The overlay rides the scroll view (scroll fires no refresh — a viewport bitmap would need scroll tracking; culled layers would never regain chevrons). Same rendering calls as the bitmap era at ~15×18pt per glyph; CoreAnimation culls offscreen layers. |
| Glyph-raster cache keyed by glyph string | Only ▸/▾ plus one per distinct ⋯N exist — a 50k-parent document shares a handful of images instead of re-rasterizing per glyph per keystroke (finish-audit security finding). |
| `parentsUnmoved` rebuild skip | Chevron positions only move when lines shift; an edit at/after every parent line provably moves none. Kills the per-keystroke lineRect cost for the common write-at-end case. |
| Same-file `extension ProseListTextView` blocks (repo posture) | PostStore/MentorPaneView precedent; class body shrank 318→275 lines; a new file buys nothing at 2 extension consumers. |
| `performOutdent` widened internal | The apply()-fix pin must drive the real structural seam; repo has a "widened internal for tests" convention. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| CRLF edits rode the cheap path | `"\r\n"` is ONE Swift `Character` equal to neither `"\n"` nor `"\r"`; a literal line-break compare passes it (two reviewers converged, both probe-verified) | `\.isNewline` keypath (stdlib; repo precedent MicropubMedia.swift:147); pinned by seeding a CRLF buffer and deleting the parent-line terminator |
| Structural ⇧⇥ made a line vanish | A childless UNTERMINATED block's outdent is a single-line replacement → cheap path → dead fold's scope stays hidden (security reviewer verified by executing the math) | `pendingPlainEdit = nil` in `apply()`; pinned via `performOutdent` |
| First rehide/park pin passed vacuously under its flip | The test edited the scope's FIRST hidden line — the scope-head probe's full-pass fallback re-hid it, so the pin guarded the wrong seam | Moved the edit to the SECOND hidden line (probe can't see it); re-flipped, pin failed, restored |
| `let replacement` shorthand didn't compile | The parameter is `replacementString`; bare `let replacement` binds a same-named optional that doesn't exist | `let replacement = replacementString` |
| Static funcs unreachable unqualified from instance methods | Swift resolves instance-context unqualified calls to instance members | `Self.isSingleLine(...)` |
| swiftlint vs swiftformat brace war | swiftformat puts the brace on its own line after wrapped condition lists; swiftlint's `opening_brace` flags it (one such warning pre-exists at HEAD) | Restructured to avoid wrapping (nested ifs, hoisted `parentsUnmoved` helper) |
| Multi-line `for … where …` failed to compile ("Expected '{'") | Wrapped where-clause + brace-on-next-line form rejected | Guard-inside-loop |
| 2 full-suite failures on first run (UI smoke + EditorSession debounce) | Load flakes under concurrent build/analyze (learning #30 class) — both green in isolation; a third (`SessionLifecycleTests`) flaked in the finish-audit run, also green in isolation | No code change; definitive idle-machine runs: 567/567, then 569/570+verified flake |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProseListTextView.swift` | Cheap re-key path + guards, per-glyph chrome layers with raster cache + skip, deletions of the bitmap machinery, extensions split |
| `MuseionTests/ProseRekeyTests.swift` | New: pipeline + pure-math suites (9 + 6 tests), scenario header |
| `MuseionTests/ProseListTests.swift` | Fold pins widened with `scope`; suites split out |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | #142 DOX |
| `AGENTS.md` | GitNexus index-stats line (analyze churn) |
## Open Items & Next Steps
- [ ] **Dogfood**: chevron alignment under `isGeometryFlipped` is the one
headless-unverifiable fact — if chevrons land mirrored vertically,
flip that boolean in `rebuildChromeLayers`.
- [ ] Deferred (finish-audit, ceiling comments in code): viewport culling
of chrome layers + scroll-triggered refresh (needs it to avoid
stranding culled parents); phantom off-screen chevron rects
(pre-existing `lineRect` class, same blocker).
- [ ] F4 (per-keystroke O(document) fence scans) remains — separate audit
finding, out of #142 scope.
---
*Log written by write-log skill*