diff --git a/CLAUDE.md b/CLAUDE.md
index 4a3ceda..4d86339 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -96,23 +96,24 @@ CI derives the npm dist-tag from the version string alone: a prerelease (hyphen)
### Viewer & scroll
-| Term | Definition |
-| ------------------- | ------------------------------------------------------------------------------------------------------ |
-| Viewer | The scrollable content area (``) |
-| Viewport | The currently visible region of the Viewer (`box.viewport.{y,height}`) |
-| Geometry | `BoxGeometry` — the narrow structural port over the scrollbox that all pure scroll math reads |
-| Overlay | The sticky region painted over the top of the Viewport (Trail row + Ancestor rows) |
-| Fold | Line `topOffset + PIN_TOP_OFFSET` below the viewport top that decides which heading is current |
-| Fold offset | Rows the Overlay occludes for a given heading; `Fold.offsetFor` / `aboveOffsetFor` |
-| Pin | A scroll that parks a heading at the Fold (`scrollChildToTop`, `pinHeadingPostLayout`) |
-| Pending target | Queued scroll (heading / top / match) retried each post-layout frame until reached; `pendingReducer` |
-| Swap reposition | A Pending target flagged `isSwap`; resolving it fires `onRepositioned`, which drops the Cover |
-| Cover | Opaque box masking the Viewer while a Doc swap repositions, so the reader never sees the top-then-jump |
-| Progressive mount | Mounting top-level nodes in chunks (`CHUNK_SIZE`) after a viewport-sized first paint |
-| Scrollbox tail | Empty `` after content so the last heading can scroll to the Fold |
-| Tail reserve | Fold offset withheld from the tail so the last heading pins correctly |
-| Real content height | `scrollHeight` minus the tail — the height used for scrollability and thumb-size math |
-| Scroll marks | Search matches resolved to document-space `y` and painted onto scrollbar track rows (`TrackCell`) |
+| Term | Definition |
+| ------------------- | ------------------------------------------------------------------------------------------------------- |
+| Viewer | The scrollable content area (``) |
+| Viewport | The currently visible region of the Viewer (`box.viewport.{y,height}`) |
+| Breakout width | Columns a rendered diagram may span: `contentWidth` with the TOC shown, the whole column with it hidden |
+| Geometry | `BoxGeometry` — the narrow structural port over the scrollbox that all pure scroll math reads |
+| Overlay | The sticky region painted over the top of the Viewport (Trail row + Ancestor rows) |
+| Fold | Line `topOffset + PIN_TOP_OFFSET` below the viewport top that decides which heading is current |
+| Fold offset | Rows the Overlay occludes for a given heading; `Fold.offsetFor` / `aboveOffsetFor` |
+| Pin | A scroll that parks a heading at the Fold (`scrollChildToTop`, `pinHeadingPostLayout`) |
+| Pending target | Queued scroll (heading / top / match) retried each post-layout frame until reached; `pendingReducer` |
+| Swap reposition | A Pending target flagged `isSwap`; resolving it fires `onRepositioned`, which drops the Cover |
+| Cover | Opaque box masking the Viewer while a Doc swap repositions, so the reader never sees the top-then-jump |
+| Progressive mount | Mounting top-level nodes in chunks (`CHUNK_SIZE`) after a viewport-sized first paint |
+| Scrollbox tail | Empty `` after content so the last heading can scroll to the Fold |
+| Tail reserve | Fold offset withheld from the tail so the last heading pins correctly |
+| Real content height | `scrollHeight` minus the tail — the height used for scrollability and thumb-size math |
+| Scroll marks | Search matches resolved to document-space `y` and painted onto scrollbar track rows (`TrackCell`) |
### Headings & overlay
diff --git a/bench/scroll.tsx b/bench/scroll.tsx
index 36b927d..79c3c43 100644
--- a/bench/scroll.tsx
+++ b/bench/scroll.tsx
@@ -162,7 +162,7 @@ for (const file of files) {
}
const renderables = countTree(setup.renderer.root)
- const matches = findMatches(nodes, 'e').length
+ const matches = findMatches({ nodes: nodes, pattern: 'e', breakoutWidth: 80 }).length
if (asJson) {
console.log(
JSON.stringify({
diff --git a/bench/stages.ts b/bench/stages.ts
index fec0794..d3a18b2 100644
--- a/bench/stages.ts
+++ b/bench/stages.ts
@@ -38,5 +38,5 @@ time('buildTreeFromTokens', () => buildTreeFromTokens(tokens))
time('buildTree (lex+tree)', () => buildTree(body))
time('buildDocument (all)', () => buildDocument(md, file))
const { nodes } = buildDocument(md, file)
-time("findMatches 'e'", () => findMatches(nodes, 'e'))
-time("findMatches 'zzqx'", () => findMatches(nodes, 'zzqx'))
+time("findMatches 'e'", () => findMatches({ nodes: nodes, pattern: 'e', breakoutWidth: 80 }))
+time("findMatches 'zzqx'", () => findMatches({ nodes: nodes, pattern: 'zzqx', breakoutWidth: 80 }))
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e661a02..6f8204e 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -75,7 +75,8 @@ Heading nodes carry an `id` (slug). The renderer for `Heading` emits a `
← absolute overlay; top/left 0; zIndex 10
- ← scrollbox, contentWidth + overhead
+ ← scrollbox, breakoutWidth + overhead
{hasToc && }
{isResizing && } ← drag shield
@@ -115,6 +116,7 @@ Both are measured against **the content below the sticky overlay**, not the raw
- `search: SearchState | null` — `{ pattern, matches, index, dir }`.
- `viewerRef: RefObject` — imperative scroll API.
- `contentWidth: number` — Viewer's inner content width after subtracting TOC, scrollbar, and padding; capped to `CONTENT_MAX_WIDTH` (100).
+- `breakoutWidth: number` — columns a rendered diagram may span: `contentWidth` while the TOC is shown, the whole Viewer column otherwise. Diagram fitting (`codeText` in `src/app/lib/diagram-fit.ts`), the search Projection, and the seam's reflow key all read it.
`ScrollboxHandle` is the only place mutation crosses the React boundary. See [Imperative scroll](#imperative-scroll).
@@ -149,7 +151,7 @@ Pure key mapping, an effectful command layer, and a pure dispatcher between them
The viewer is a `` wrapping `` plus a trailing `` so the _last_ heading can still scroll to the top of the viewport (`tailSpace = max(0, termHeight - 1 - tailReserve)`, where `tailReserve` is the last heading's overlay height).
-On mount it calls `createScrollboxHandle` (`src/app/lib/scrollbox-handle.ts`) with the raw `ScrollBoxRenderable` ref plus a `live` bag of getters (`tail`, `projections`, `isFullyMounted`, `contentWidth`, `mountedCount`, `docKey`); the seam owns the geometry port, the pending protocol and the scrollbar patches, and hands back `{ handle, onFrame, requestNotify, dispose }`. The main handle methods:
+On mount it calls `createScrollboxHandle` (`src/app/lib/scrollbox-handle.ts`) with the raw `ScrollBoxRenderable` ref plus a `live` bag of getters (`tail`, `projections`, `isFullyMounted`, `contentWidth`, `breakoutWidth`, `mountedCount`, `docKey`); the seam owns the geometry port, the pending protocol and the scrollbar patches, and hands back `{ handle, onFrame, requestNotify, dispose }`. The main handle methods:
| Method | Implementation |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -201,11 +203,11 @@ The scrollbox is wrapped in a `position=relative` box; `ScrollIndicators` render
Block boxes carry a stable id via `blockId(path)` (`src/app/lib/scroll-marks.ts`), keyed by the block's index path through the AST — the same convention headings already use via their slug `id`. `Match.blockElementId` (stamped during search) joins a match back to its block box, so `getScrollMarks` can resolve the block through the `BoxGeometry` port — `findChildren` / `collectTextBearersFor`, both one `collectById` walk over the renderable tree — and then locate the exact visual line within it via `plainText`/`lineInfo` (falling back to the block's own `y` if no text-bearing descendant is found).
-`computeTrackCells` (pure, in `scroll-marks.ts`) maps each resolved mark's document-space `y` onto a track row proportionally (`round(y / scrollHeight * viewportHeight)`), independent of scroll position. It maps over the **full `scrollHeight`** (tail included) — the exact scale OpenTUI positions the thumb with (`thumbTop = scrollPosition / scrollHeight * trackHeight`), so a mark for a match lands inside the thumb once you navigate to it; `realContentHeight` (scrollHeight minus tail) is used only to suppress the overlay when the whole document already fits the viewport. Marks resolve on **reflow**, not on every scroll tick: `createMarkCache` (`src/app/lib/mark-cache.ts`) re-resolves when the seam's reflow key (`docKey:contentWidth:mountedCount`) changes — latched in `onFrame` so it always describes the laid-out state rather than the pending render — or when the search mints a new `matches` array, which the cache detects by identity. A key change also fires a notify, so `ScrollIndicators` re-reads on a resize or TOC toggle without waiting for a scroll. It reads the current layout off `viewerRef`, on a `setTimeout(…, 0)` after mount/search changes and on every scroll notification. When several marks land on the same row, the highest-priority kind wins (`activeMatch > match`), painted with `theme.scrollMarkActive` / `scrollMarkMatch`. With no active search or on a non-scrollable document (`contentHeight <= trackHeight`), `computeTrackCells` returns no cells and the overlay renders nothing.
+`computeTrackCells` (pure, in `scroll-marks.ts`) maps each resolved mark's document-space `y` onto a track row proportionally (`round(y / scrollHeight * viewportHeight)`), independent of scroll position. It maps over the **full `scrollHeight`** (tail included) — the exact scale OpenTUI positions the thumb with (`thumbTop = scrollPosition / scrollHeight * trackHeight`), so a mark for a match lands inside the thumb once you navigate to it; `realContentHeight` (scrollHeight minus tail) is used only to suppress the overlay when the whole document already fits the viewport. Marks resolve on **reflow**, not on every scroll tick: `createMarkCache` (`src/app/lib/mark-cache.ts`) re-resolves when the seam's reflow key (`docKey:contentWidth:breakoutWidth:mountedCount`) changes — latched in `onFrame` so it always describes the laid-out state rather than the pending render — or when the search mints a new `matches` array, which the cache detects by identity. A key change also fires a notify, so `ScrollIndicators` re-reads on a resize or TOC toggle without waiting for a scroll. It reads the current layout off `viewerRef`, on a `setTimeout(…, 0)` after mount/search changes and on every scroll notification. When several marks land on the same row, the highest-priority kind wins (`activeMatch > match`), painted with `theme.scrollMarkActive` / `scrollMarkMatch`. With no active search or on a non-scrollable document (`contentHeight <= trackHeight`), `computeTrackCells` returns no cells and the overlay renders nothing.
## 8. Sticky overlay (`src/app/components/StickyHeader.tsx`)
-An **absolute overlay** over the top of the viewer (VS Code "sticky scroll" model), not a chrome row. The box is `position=absolute` at `top/left 0` of the viewer's `position=relative` row container, sized to `contentWidth`, `zIndex 10`, on `theme.stickyBg`. Being out of Yoga's flow, it never changes the viewer's height — the rows paint _over_ the top content lines rather than pushing content down, so the overlay can grow from zero without the content region reflowing.
+An **absolute overlay** over the top of the viewer (VS Code "sticky scroll" model), not a chrome row. The box is `position=absolute` at `top/left 0` of the viewer's `position=relative` row container, sized to `breakoutWidth + 1` (reaching the scrollbar), `zIndex 10`, on `theme.stickyBg`. Being out of Yoga's flow, it never changes the viewer's height — the rows paint _over_ the top content lines rather than pushing content down, so the overlay can grow from zero without the content region reflowing.
Content is `ancestorRows({ chain, visibleHeadingIds, hasH1, fileLabel })` (in `overlay-rows.ts`), where `chain = ancestorChain(toc, currentHeadingId)` is the root→current lineage:
diff --git a/src/app/App.tsx b/src/app/App.tsx
index 923dbde..421cccd 100644
--- a/src/app/App.tsx
+++ b/src/app/App.tsx
@@ -165,6 +165,9 @@ export function App({
(isTocShown ? termWidth - tocWidth : termWidth) - VIEWER_OVERHEAD,
)
const contentWidth = Math.min(effectiveContentMax, viewerColumnWidth)
+ // With no sidebar on the right, diagrams may break out past the reading cap into
+ // the free columns; prose stays at `contentWidth`.
+ const breakoutWidth = isTocShown ? contentWidth : viewerColumnWidth
// Stable across nav; rebuilt only when the doc (toc/fileLabel) changes.
const fold = useMemo(() => createFold({ toc, fileLabel }), [toc, fileLabel])
@@ -292,6 +295,7 @@ export function App({
doc: { nodes, toc, headingIds, fileLabel },
fold,
viewportHeight: renderer.height,
+ breakoutWidth,
stateRef,
actions,
historyDepth: nav.historyDepth,
@@ -315,6 +319,7 @@ export function App({
// resize; depend on the value so `scrollPage`/`scrollHalf` rebuild with the
// new page size instead of the pre-resize one.
renderer.height,
+ breakoutWidth,
nav.historyDepth,
nav.follow,
nav.back,
@@ -331,6 +336,11 @@ export function App({
commands.syncFromScroll()
}, [commands])
+ // A width change can re-fit a diagram, which moves the match offsets inside it.
+ useEffect(() => {
+ commands.refreshSearch()
+ }, [breakoutWidth])
+
const headingState = useMemo(
() => ({
currentHeadingId: view.currentHeadingId,
@@ -349,6 +359,7 @@ export function App({
tocCursorId: view.tocCursorId,
search: view.search,
contentWidth,
+ breakoutWidth,
contentMaxWidth: effectiveContentMax,
dir: nav.doc.dir,
historyDepth: nav.historyDepth,
@@ -364,6 +375,7 @@ export function App({
view.search,
view.helpVisible,
contentWidth,
+ breakoutWidth,
effectiveContentMax,
nav.doc.dir,
nav.historyDepth,
@@ -457,7 +469,7 @@ export function App({
position="absolute"
top={0}
left={0}
- width={contentWidth + VIEWER_OVERHEAD}
+ width={breakoutWidth + VIEWER_OVERHEAD}
height="100%"
backgroundColor={theme.background}
zIndex={20}
diff --git a/src/app/RenderView.tsx b/src/app/RenderView.tsx
index 17bbe74..6cef874 100644
--- a/src/app/RenderView.tsx
+++ b/src/app/RenderView.tsx
@@ -39,6 +39,7 @@ export function RenderView({
tocCursorId: null,
search: null,
contentWidth: Math.min(contentMaxWidth, width),
+ breakoutWidth: Math.min(contentMaxWidth, width),
contentMaxWidth,
dir: undefined,
historyDepth: 0,
diff --git a/src/app/components/DiagramFit.test.tsx b/src/app/components/DiagramFit.test.tsx
new file mode 100644
index 0000000..91ecd4e
--- /dev/null
+++ b/src/app/components/DiagramFit.test.tsx
@@ -0,0 +1,93 @@
+import { expect, test } from 'bun:test'
+import { createTestRenderer } from '@opentui/core/testing'
+import { createRoot } from '@opentui/react'
+import { App } from '../App'
+import { buildTreeFromTokens, lexMarkdown } from '../lib/ast'
+import { renderDiagramBlocks } from '../lib/preprocess'
+
+const mermaid = (chain: string) =>
+ ['# Diagram', '', '```mermaid', 'graph LR', ` ${chain}`, '```'].join('\n')
+
+// 180 cols at default spacing, 136 at the tightest.
+const HUGE_CHAIN = mermaid(
+ 'A[Keyboard event] --> B[mapKey pure] --> C[Action value] --> D[dispatch pure] --> E[Commands effectful] --> F[ViewActions write] --> G[React rerender] --> H[Terminal frame]',
+)
+
+// At 160 cols the content column sits at the 100-col reading cap, leaving 96
+// for a diagram between its margins.
+async function renderFrame(
+ md: string,
+ { width = 160, hideToc = false }: { width?: number; hideToc?: boolean } = {},
+): Promise {
+ const { nodes, toc, headingIds } = buildTreeFromTokens(renderDiagramBlocks(lexMarkdown(md)))
+ const { renderer, mockInput, flush, renderOnce, captureCharFrame } = await createTestRenderer({
+ width,
+ height: 20,
+ })
+ const settle = async () => {
+ await flush({ maxPasses: 20 })
+ await new Promise(r => setTimeout(r, 30))
+ await renderOnce()
+ }
+ createRoot(renderer).render(
+ ,
+ )
+ await settle()
+ // The very first key is consumed by the terminal capability handshake.
+ await mockInput.typeText('x')
+ await settle()
+ if (hideToc) {
+ await mockInput.typeText('t')
+ await settle()
+ }
+ return captureCharFrame()
+}
+
+test('a diagram wider than the content column re-renders to fit it', async () => {
+ // 114 cols at default spacing.
+ const frame = await renderFrame(
+ mermaid(
+ 'A[Start here] --> B[Parse markdown] --> C[Build tree] --> D[Render React] --> E[Paint frame] --> F[Done all]',
+ ),
+ )
+ // Tight spacing drops the padding inside boxes; the last box closes only when whole.
+ expect(frame).toContain('Done all│')
+})
+
+test('a diagram exactly as wide as the column shows whole at default spacing', async () => {
+ // 96 cols at default spacing.
+ const frame = await renderFrame(
+ mermaid(
+ 'A[Open file] --> B[Lex tokens] --> C[Render diagrams] --> D[Build tree] --> E[Mount viewer]',
+ ),
+ )
+ expect(frame).toContain('│ Mount viewer │')
+})
+
+test('with the TOC shown, a diagram stops at the reading cap', async () => {
+ const frame = await renderFrame(HUGE_CHAIN, { width: 200 })
+ expect(frame).not.toContain('Terminal frame')
+})
+
+test('with the TOC hidden, a diagram breaks out past the reading cap', async () => {
+ const frame = await renderFrame(HUGE_CHAIN, { width: 200, hideToc: true })
+ expect(frame).toContain('│ Terminal frame │')
+})
+
+test('with the TOC hidden, prose keeps the reading width', async () => {
+ const prose = `# Diagram\n\n${'word '.repeat(60)}`
+ const shown = await renderFrame(prose, { width: 200 })
+ const hidden = await renderFrame(prose, { width: 200, hideToc: true })
+ const longestProse = (frame: string) =>
+ Math.max(...frame.split('\n').map(l => l.match(/^.*word/)?.[0].length ?? 0))
+ // Hiding the TOC hands prose the sidebar's columns, not the whole terminal.
+ expect(longestProse(hidden)).toBeGreaterThan(longestProse(shown))
+ expect(longestProse(hidden)).toBeLessThan(150)
+})
diff --git a/src/app/components/ProgressiveMount.test.tsx b/src/app/components/ProgressiveMount.test.tsx
index 6a4eddf..8127569 100644
--- a/src/app/components/ProgressiveMount.test.tsx
+++ b/src/app/components/ProgressiveMount.test.tsx
@@ -113,7 +113,13 @@ const mountViewerOnly = async (md: string, onScroll?: () => void) => {
const setup = await createTestRenderer({ width: 80, height: 20 })
const viewerRef: { current: ScrollboxHandle | null } = { current: null }
const commands = { followLink: () => {} } as unknown as Commands
- const state = { viewerRef, contentWidth: 78, search: null, commands } as AppState
+ const state = {
+ viewerRef,
+ contentWidth: 78,
+ breakoutWidth: 78,
+ search: null,
+ commands,
+ } as AppState
const settle = async () => {
await setup.flush({ maxPasses: 20 })
await new Promise(r => setTimeout(r, 30))
@@ -160,7 +166,7 @@ test('jumpToMatch to an unmounted block completes once its chunk mounts', async
const { nodes, setup, settle, viewerRef } = await mountViewerOnly(bigFixture(), () => {
scrolls++
})
- const matches = findMatches(nodes, 'THE-FINAL-LINE')
+ const matches = findMatches({ nodes: nodes, pattern: 'THE-FINAL-LINE', breakoutWidth: 80 })
const match = matches[0]
if (!match) throw new Error('fixture must contain the search target')
// The match's block is still behind the spacer — jumpToMatch must record it.
@@ -234,7 +240,13 @@ test('swapping to a longer doc re-expands the initial mounted prefix', async ()
const setup = await createTestRenderer({ width: 80, height: 20 })
const viewerRef: { current: ScrollboxHandle | null } = { current: null }
const commands = { followLink: () => {} } as unknown as Commands
- const state = { viewerRef, contentWidth: 78, search: null, commands } as AppState
+ const state = {
+ viewerRef,
+ contentWidth: 78,
+ breakoutWidth: 78,
+ search: null,
+ commands,
+ } as AppState
const controller: { current: ((nodes: Node[]) => void) | null } = { current: null }
createRoot(setup.renderer).render(
diff --git a/src/app/components/ProjectionConsistency.test.tsx b/src/app/components/ProjectionConsistency.test.tsx
index 7f5ce39..6e4fc30 100644
--- a/src/app/components/ProjectionConsistency.test.tsx
+++ b/src/app/components/ProjectionConsistency.test.tsx
@@ -6,8 +6,10 @@ import { createRoot } from '@opentui/react'
import { App } from '../App'
import { collectTextBearers } from '../lib/renderable-tree'
import { isRuleBearer } from '../lib/viewport-geometry'
-import { buildTree } from '../lib/ast'
+import { buildTreeFromTokens, lexMarkdown } from '../lib/ast'
+import { renderDiagramBlocks } from '../lib/preprocess'
import { alignOffset, projectDocument, runElementCount } from '../lib/visible-text'
+import { VIEWER_OVERHEAD } from '../styles/layout'
// Kitchen-sink doc: every projected block kind, with a table wide enough to
// wrap at the narrow renderer width. Locks projection ⇄ rendered text: if a
@@ -67,6 +69,12 @@ const FIXTURE = [
'
',
'',
'
',
+ '',
+ // Wider than the column at default spacing, so it renders a tighter layout.
+ '```mermaid',
+ 'graph LR',
+ ' A[zebra one] --> B[zebra two] --> C[zebra three] --> D[zebra four]',
+ '```',
].join('\n')
const findScrollbox = (node: Renderable): ScrollBoxRenderable | null => {
@@ -81,7 +89,7 @@ const findScrollbox = (node: Renderable): ScrollBoxRenderable | null => {
const normalize = (s: string) => s.replace(/\s+/g, ' ').trim()
test('every projected run aligns into its block’s rendered text', async () => {
- const { nodes, toc, headingIds } = buildTree(FIXTURE)
+ const { nodes, toc, headingIds } = buildTreeFromTokens(renderDiagramBlocks(lexMarkdown(FIXTURE)))
const { renderer, flush, renderOnce } = await createTestRenderer({ width: 60, height: 80 })
const settle = async () => {
await flush({ maxPasses: 20 })
@@ -104,7 +112,9 @@ test('every projected run aligns into its block’s rendered text', async () =>
const box = findScrollbox(renderer.root)
if (!box) throw new Error('scrollbox not found')
- const projections = projectDocument(nodes)
+ // The Viewer column is the breakout width plus its scrollbar overhead.
+ const breakoutWidth = box.width - VIEWER_OVERHEAD
+ const projections = projectDocument(nodes, breakoutWidth)
expect(projections.length).toBeGreaterThan(15)
for (const p of projections) {
const blockBox = box.content.findDescendantById(p.blockElementId)
diff --git a/src/app/components/SearchBar.tsx b/src/app/components/SearchBar.tsx
index 0d62b41..a399981 100644
--- a/src/app/components/SearchBar.tsx
+++ b/src/app/components/SearchBar.tsx
@@ -10,7 +10,7 @@ import type { TocEntry } from '../lib/ast'
const BAR_WIDTH = 28
export function SearchBar({ toc, fileLabel }: { toc: TocEntry[]; fileLabel?: string }) {
- const { search, focus, contentWidth, commands } = useAppState()
+ const { search, focus, breakoutWidth, commands } = useAppState()
const { currentHeadingId, visibleHeadingIds } = useHeadingState()
const onInput = (pattern: string) => commands.applySearchPattern({ pattern, commit: false })
@@ -43,10 +43,10 @@ export function SearchBar({ toc, fileLabel }: { toc: TocEntry[]; fileLabel?: str
// Muted counter reads fine on the dark surfaces; on the red miss bar it
// would be illegible, so fall back to the regular bar fg there.
const counterFg = isMiss ? theme.searchBarFg : theme.foregroundMuted
- // Right-align the bar with the overlay's right edge (contentWidth + 1),
+ // Right-align the bar with the overlay's right edge (breakoutWidth + 1),
// leaving the scrollbar column uncovered.
- const barWidth = Math.min(BAR_WIDTH, contentWidth + 1)
- const barLeft = Math.max(0, contentWidth + 1 - barWidth)
+ const barWidth = Math.min(BAR_WIDTH, breakoutWidth + 1)
+ const barLeft = Math.max(0, breakoutWidth + 1 - barWidth)
// Counter right-aligned inside the bar; hidden when the pattern would run
// under it (paddingX + label + pattern + cursor cell + one gap cell).
const counterLeft = barWidth - 1 - counter.length
diff --git a/src/app/components/StickyHeader.ancestor.test.tsx b/src/app/components/StickyHeader.ancestor.test.tsx
index 7dfeed7..cde486e 100644
--- a/src/app/components/StickyHeader.ancestor.test.tsx
+++ b/src/app/components/StickyHeader.ancestor.test.tsx
@@ -21,6 +21,7 @@ function makeStub(overrides: Partial = {}): Stub {
search: null,
visibleHeadingIds: new Set(),
contentWidth: 80,
+ breakoutWidth: 80,
dir: undefined,
commands: createNoopCommands(),
historyDepth: 0,
diff --git a/src/app/components/StickyHeader.back.test.tsx b/src/app/components/StickyHeader.back.test.tsx
index f99afdc..40ebbe1 100644
--- a/src/app/components/StickyHeader.back.test.tsx
+++ b/src/app/components/StickyHeader.back.test.tsx
@@ -20,6 +20,7 @@ function makeStub(overrides: Partial = {}): Stub {
search: null,
visibleHeadingIds: new Set(),
contentWidth: 80,
+ breakoutWidth: 80,
dir: undefined,
// Real Commands surface with an assertable goToDocument for the trail click tests.
commands: { ...createNoopCommands(), goToDocument: mock() },
diff --git a/src/app/components/StickyHeader.tsx b/src/app/components/StickyHeader.tsx
index 15784fa..63cf77f 100644
--- a/src/app/components/StickyHeader.tsx
+++ b/src/app/components/StickyHeader.tsx
@@ -16,7 +16,7 @@ export function StickyHeader({
fileLabel?: string
onAncestorClick: (id: string) => void
}) {
- const { contentWidth, historyDepth, trailLabels, commands } = useAppState()
+ const { contentWidth, breakoutWidth, historyDepth, trailLabels, commands } = useAppState()
const { currentHeadingId, visibleHeadingIds } = useHeadingState()
const hasH1 = documentHasH1(toc)
@@ -48,8 +48,8 @@ export function StickyHeader({
top={0}
left={0}
// Span the viewer's paddingRight gutter too so the background reaches the
- // scrollbar (Viewer width is contentWidth + scrollbar(1) + paddingRight(1)).
- width={contentWidth + 1}
+ // scrollbar (Viewer width is breakoutWidth + scrollbar(1) + paddingRight(1)).
+ width={breakoutWidth + 1}
flexDirection="column"
backgroundColor={theme.stickyBg}
paddingX={2}
diff --git a/src/app/components/Viewer.tsx b/src/app/components/Viewer.tsx
index 9d09c24..ba2567f 100644
--- a/src/app/components/Viewer.tsx
+++ b/src/app/components/Viewer.tsx
@@ -42,7 +42,7 @@ export function Viewer({
*/
docKey: string
}) {
- const { viewerRef, contentWidth, contentMaxWidth } = useAppState()
+ const { viewerRef, contentWidth, breakoutWidth } = useAppState()
const renderer = useRenderer()
const { height } = useTerminalDimensions()
const localRef = useRef(null)
@@ -56,10 +56,13 @@ export function Viewer({
const onScrollRef = useLatest(onScroll)
const onRepositionedRef = useLatest(onRepositioned)
const contentWidthRef = useLatest(contentWidth)
+ const breakoutWidthRef = useLatest(breakoutWidth)
const docKeyRef = useLatest(docKey)
// Ref'd so the once-mounted seam effect always reads the current map.
- const projectionsRef = useLatest(useMemo(() => projectionMap(nodes), [nodes]))
+ const projectionsRef = useLatest(
+ useMemo(() => projectionMap(nodes, breakoutWidth), [nodes, breakoutWidth]),
+ )
const { mountedNodes, estimatedRemaining, fullyMounted } = useProgressiveMount({
nodes,
@@ -79,6 +82,7 @@ export function Viewer({
projections: () => projectionsRef.current,
isFullyMounted: () => fullyMountedRef.current,
contentWidth: () => contentWidthRef.current,
+ breakoutWidth: () => breakoutWidthRef.current,
mountedCount: () => mountedCountRef.current,
docKey: () => docKeyRef.current,
},
@@ -107,7 +111,7 @@ export function Viewer({
}, [fullyMounted])
return (
-
+
-
+ {/* Prose holds the reading width; diagrams overflow this box into the breakout
+ columns (see `CodeBlock`). */}
+
{!fullyMounted && }
diff --git a/src/app/components/blocks/CodeBlock.tsx b/src/app/components/blocks/CodeBlock.tsx
index 73d0094..3091a45 100644
--- a/src/app/components/blocks/CodeBlock.tsx
+++ b/src/app/components/blocks/CodeBlock.tsx
@@ -5,6 +5,7 @@ import { theme } from '../../styles/theme'
import { syntaxStyle } from '../../styles/syntax-style'
import { useAppState } from '../../state'
import { MERMAID_ASCII_LANG } from '../../lib/preprocess'
+import { codeText, DIAGRAM_MARGIN_X, textWidth } from '../../lib/diagram-fit'
import type { Node } from '../../lib/ast'
import type { AppState } from '../../state'
@@ -13,17 +14,20 @@ const PADDING_X = 2
const MARGIN_X = 2
export function CodeBlock({ node, id }: { node: Extract; id: string }) {
- const { contentWidth, search } = useAppState()
+ const { contentWidth, breakoutWidth, search } = useAppState()
// Rendered mermaid ASCII already carries its own frame; render it bare.
// Unrendered mermaid source keeps lang 'mermaid' and falls through as a
- // normal framed code block below.
+ // normal framed code block below. `minWidth` lets a diagram wider than the
+ // reading column overflow it into the breakout columns; a `wrapMode="none"`
+ // text clips at its box edge otherwise.
if (node.lang === MERMAID_ASCII_LANG) {
+ const ascii = codeText({ node, breakoutWidth })
return (
-
+
-
-
+
+
diff --git a/src/app/lib/applyScrollIntent.test.ts b/src/app/lib/applyScrollIntent.test.ts
index f3353f7..fb9d43e 100644
--- a/src/app/lib/applyScrollIntent.test.ts
+++ b/src/app/lib/applyScrollIntent.test.ts
@@ -24,6 +24,7 @@ function makeCommands(): Commands {
toggleHelp: mock(),
startSearch: mock(),
applySearchPattern: mock(),
+ refreshSearch: mock(),
stepMatch: mock(),
clearSearch: mock(),
followLink: mock(),
diff --git a/src/app/lib/ast.ts b/src/app/lib/ast.ts
index 987dfd8..e64f977 100644
--- a/src/app/lib/ast.ts
+++ b/src/app/lib/ast.ts
@@ -2,6 +2,7 @@ import { marked } from 'marked'
import type { Tokens } from 'marked'
import { detectLang } from './detect-lang'
import { htmlContainsBlockMarkdown, htmlToMarkdown, stripHtml } from './html'
+import type { DiagramCode } from './preprocess'
marked.use({
extensions: [
@@ -44,6 +45,8 @@ export type Node =
value: string
/** Guessed by `detectLang` when the fence has no info string; drives highlighting only, never the title. */
inferredLang?: string
+ /** Mermaid source of a rendered diagram; `codeText` re-renders it tighter when `value` overflows. */
+ diagramSource?: string
}
| { kind: 'list'; ordered: boolean; start?: number; items: ListItem[] }
| { kind: 'blockquote'; children: Node[] }
@@ -267,13 +270,14 @@ function blockToNode(t: Tokens.Generic, ctx: ParseContext): Node | null {
return { kind: 'paragraph', inline: (p.tokens ?? []).flatMap(inlineToNode) }
}
case 'code': {
- const c = t as Tokens.Code
+ const c = t as DiagramCode
const lang = c.lang || undefined
return {
kind: 'code',
lang,
value: c.text,
inferredLang: lang ? undefined : detectLang(c.text),
+ diagramSource: c.diagramSource,
}
}
case 'list': {
diff --git a/src/app/lib/commands.test.ts b/src/app/lib/commands.test.ts
index 4d7a5a0..b1a743c 100644
--- a/src/app/lib/commands.test.ts
+++ b/src/app/lib/commands.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, test, mock } from 'bun:test'
import { createCommands, createNoopCommands } from './commands'
import { createFold } from './fold'
+import { buildTreeFromTokens, lexMarkdown } from './ast'
+import { codeText } from './diagram-fit'
+import { renderDiagramBlocks } from './preprocess'
import type { CommandDeps } from './commands'
import type { ViewActions, ViewState } from './view-state'
import type { ScrollboxHandle } from '../state'
@@ -112,6 +115,7 @@ function makeDeps(
doc,
fold: createFold({ toc: doc.toc, fileLabel: doc.fileLabel }),
viewportHeight: 24,
+ breakoutWidth: 80,
stateRef: { current: viewState },
actions,
historyDepth: 0,
@@ -363,6 +367,50 @@ describe('createCommands.applySearchPattern', () => {
})
})
+describe('createCommands.refreshSearch', () => {
+ const diagramNodes = buildTreeFromTokens(
+ renderDiagramBlocks(
+ lexMarkdown(
+ '```mermaid\ngraph LR\n A[Start here] --> B[Parse markdown] --> C[Done all]\n```',
+ ),
+ ),
+ ).nodes
+
+ test('re-finds matches at the current content width, keeping the index', () => {
+ const breakoutWidth = 30
+ const { deps, actions } = makeDeps({
+ doc: { nodes: diagramNodes },
+ state: { search: { pattern: 'done', matches: [m()], index: 0, committed: true } },
+ })
+ createCommands({ ...deps, breakoutWidth }).refreshSearch()
+
+ const [code] = diagramNodes
+ if (code?.kind !== 'code') throw new Error('fixture must parse to a code node')
+ const start = codeText({ node: code, breakoutWidth }).toLowerCase().indexOf('done')
+ expect(start).not.toBe(code.value.toLowerCase().indexOf('done'))
+ expect(actions.search).toHaveBeenCalledWith(
+ expect.objectContaining({ index: 0, matches: [expect.objectContaining({ start })] }),
+ )
+ })
+
+ test('clamps the index when fewer matches remain', () => {
+ const { deps, actions } = makeDeps({
+ doc: { nodes: diagramNodes },
+ state: { search: { pattern: 'done', matches: [m(), m()], index: 1, committed: true } },
+ })
+ createCommands(deps).refreshSearch()
+ expect(actions.search).toHaveBeenCalledWith(expect.objectContaining({ index: 0 }))
+ })
+
+ test('no-op without a search pattern', () => {
+ const { deps, actions } = makeDeps({
+ state: { search: { pattern: '', matches: [], index: -1, committed: false } },
+ })
+ createCommands(deps).refreshSearch()
+ expect(actions.search).not.toHaveBeenCalled()
+ })
+})
+
const siblingToc: TocEntry[] = [
{
id: 'h1',
diff --git a/src/app/lib/commands.ts b/src/app/lib/commands.ts
index b38d621..a83923c 100644
--- a/src/app/lib/commands.ts
+++ b/src/app/lib/commands.ts
@@ -12,6 +12,8 @@ export type CommandDeps = {
doc: { nodes: Node[]; toc: TocEntry[]; headingIds: string[]; fileLabel?: string }
fold: Fold
viewportHeight: number
+ /** Columns a diagram may span; search projects diagrams at it. */
+ breakoutWidth: number
stateRef: RefObject
actions: ViewActions
historyDepth: number
@@ -39,6 +41,8 @@ export type Commands = {
toggleHelp(): void
startSearch(): void
applySearchPattern(p: { pattern: string; commit: boolean }): void
+ /** Re-run the current search against the current content width; keeps the match index. */
+ refreshSearch(): void
stepMatch(dir: 1 | -1): void
clearSearch(): void
followLink(href: string): void
@@ -60,6 +64,7 @@ export function createCommands(deps: CommandDeps): Commands {
doc,
fold,
viewportHeight,
+ breakoutWidth,
stateRef,
actions,
historyDepth,
@@ -205,11 +210,17 @@ export function createCommands(deps: CommandDeps): Commands {
applySearchPattern: ({ pattern, commit }) => {
const s = stateRef.current.search
if (!s) return
- const matches = findMatches(doc.nodes, pattern)
+ const matches = findMatches({ nodes: doc.nodes, pattern, breakoutWidth })
const index = matches.length ? (viewerRef.current?.seedMatchIndex({ matches }) ?? 0) : -1
actions.search({ ...s, pattern, matches, index, committed: commit })
if (commit) actions.focus('viewer')
},
+ refreshSearch: () => {
+ const s = stateRef.current.search
+ if (!s?.pattern) return
+ const matches = findMatches({ nodes: doc.nodes, pattern: s.pattern, breakoutWidth })
+ actions.search({ ...s, matches, index: Math.min(s.index, matches.length - 1) })
+ },
stepMatch: dir => {
const s = stateRef.current.search
if (!s || s.matches.length === 0) return
@@ -290,6 +301,7 @@ export function createNoopCommands(): Commands {
toggleHelp: noop,
startSearch: noop,
applySearchPattern: noop,
+ refreshSearch: noop,
stepMatch: noop,
clearSearch: noop,
followLink: noop,
diff --git a/src/app/lib/diagram-fit.test.ts b/src/app/lib/diagram-fit.test.ts
new file mode 100644
index 0000000..d2a2b27
--- /dev/null
+++ b/src/app/lib/diagram-fit.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, test } from 'bun:test'
+import { buildTreeFromTokens, lexMarkdown } from './ast'
+import { DIAGRAM_MARGIN_X, codeText } from './diagram-fit'
+import { renderDiagramBlocks } from './preprocess'
+import type { Node } from './ast'
+
+type CodeNode = Extract
+
+// Six-node LR chain: 114 cols at default spacing, 82 at the tightest.
+const WIDE_LR = [
+ '```mermaid',
+ 'graph LR',
+ ' A[Start here] --> B[Parse markdown] --> C[Build tree] --> D[Render React] --> E[Paint frame] --> F[Done all]',
+ '```',
+].join('\n')
+
+const codeNode = (md: string): CodeNode => {
+ const { nodes } = buildTreeFromTokens(renderDiagramBlocks(lexMarkdown(md)))
+ const first = nodes[0]
+ if (first?.kind !== 'code') throw new Error(`no code node parsed from: ${md}`)
+ return first
+}
+
+const widthOf = (text: string) => Math.max(...text.split('\n').map(l => l.length))
+const columnFor = (width: number) => width + 2 * DIAGRAM_MARGIN_X
+
+describe('codeText', () => {
+ test('plain code returns its value at any width', () => {
+ const node = codeNode('```ts\nconst a = 1\n```')
+ expect(codeText({ node, breakoutWidth: 5 })).toBe(node.value)
+ })
+
+ test('a diagram that fits keeps its default render', () => {
+ const node = codeNode(WIDE_LR)
+ expect(widthOf(node.value)).toBe(114)
+ expect(codeText({ node, breakoutWidth: columnFor(114) })).toBe(node.value)
+ })
+
+ test('an overflowing diagram re-renders tighter to fit the column', () => {
+ const node = codeNode(WIDE_LR)
+ const text = codeText({ node, breakoutWidth: columnFor(100) })
+ expect(widthOf(text)).toBeLessThanOrEqual(100)
+ expect(text).toContain('Done all')
+ })
+
+ test('when nothing fits, the tightest render wins', () => {
+ const node = codeNode(WIDE_LR)
+ expect(widthOf(codeText({ node, breakoutWidth: columnFor(40) }))).toBe(82)
+ })
+
+ test('DOT diagrams fit the same way', () => {
+ const node = codeNode('```dot\ndigraph { a -> b -> c -> d -> e -> f -> g -> h -> i -> j }\n```')
+ const natural = widthOf(node.value)
+ const text = codeText({ node, breakoutWidth: columnFor(natural - 1) })
+ expect(widthOf(text)).toBeLessThan(natural)
+ })
+})
diff --git a/src/app/lib/diagram-fit.ts b/src/app/lib/diagram-fit.ts
new file mode 100644
index 0000000..0f480f3
--- /dev/null
+++ b/src/app/lib/diagram-fit.ts
@@ -0,0 +1,57 @@
+import { renderAscii } from './preprocess'
+import type { Node } from './ast'
+import type { DiagramSpacing } from './preprocess'
+
+type CodeNode = Extract
+
+/** Columns left bare on each side of a rendered diagram. */
+export const DIAGRAM_MARGIN_X = 2
+
+/**
+ * Tighter spacings, loosest first: the gap between nodes shrinks before the
+ * blank rows inside boxes go. Only flowchart and state layouts respond; other
+ * diagram kinds render the same at every step.
+ */
+const COMPACT_STEPS: DiagramSpacing[] = [
+ { paddingX: 3, boxBorderPadding: 1 },
+ { paddingX: 2, boxBorderPadding: 1 },
+ { paddingX: 2, boxBorderPadding: 0 },
+ { paddingX: 1, boxBorderPadding: 0 },
+]
+
+/**
+ * The text a code block prints when diagrams may span `breakoutWidth`. A diagram
+ * wider than that re-renders at the loosest spacing that fits; when none fits,
+ * the tightest render wins so the least is clipped. `CodeBlock`, the search
+ * Projection, and row estimates all read through here so they agree.
+ */
+export function codeText({
+ node,
+ breakoutWidth,
+}: {
+ node: CodeNode
+ breakoutWidth: number
+}): string {
+ const available = breakoutWidth - 2 * DIAGRAM_MARGIN_X
+ if (node.diagramSource === undefined || textWidth(node.value) <= available) return node.value
+ const renders = compactRenders(node, node.diagramSource)
+ return renders.find(r => textWidth(r) <= available) ?? renders.at(-1) ?? node.value
+}
+
+/** Widest line, in columns. */
+export function textWidth(text: string): number {
+ return text.split('\n').reduce((max, l) => Math.max(max, l.length), 0)
+}
+
+// Keyed on the node so renders live and die with their Document.
+const compactCache = new WeakMap()
+
+function compactRenders(node: CodeNode, source: string): string[] {
+ const cached = compactCache.get(node)
+ if (cached) return cached
+ const renders = COMPACT_STEPS.map(spacing => renderAscii(source, spacing)).filter(
+ (r): r is string => r !== undefined,
+ )
+ compactCache.set(node, renders)
+ return renders
+}
diff --git a/src/app/lib/dispatch.test.ts b/src/app/lib/dispatch.test.ts
index 0211e7a..e42cb2f 100644
--- a/src/app/lib/dispatch.test.ts
+++ b/src/app/lib/dispatch.test.ts
@@ -22,6 +22,7 @@ function makeCommands(): Commands {
toggleHelp: mock(),
startSearch: mock(),
applySearchPattern: mock(),
+ refreshSearch: mock(),
stepMatch: mock(),
clearSearch: mock(),
followLink: mock(),
diff --git a/src/app/lib/match-nav.test.ts b/src/app/lib/match-nav.test.ts
index ca5c2b9..7e90b91 100644
--- a/src/app/lib/match-nav.test.ts
+++ b/src/app/lib/match-nav.test.ts
@@ -13,7 +13,7 @@ describe('nearestPrecedingHeadingId', () => {
test('returns id of heading just before match', () => {
const md = '# A\n\nfoo target\n\n# B\n\nbar'
const { nodes } = buildTree(md)
- const [m] = findMatches(nodes, 'target')
+ const [m] = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
if (!m) throw new Error('expected a match')
expect(nearestPrecedingHeadingId(nodes, m)).toBe('a')
})
@@ -21,7 +21,7 @@ describe('nearestPrecedingHeadingId', () => {
test('returns null when no heading precedes the match', () => {
const md = 'target text\n\n# H'
const { nodes } = buildTree(md)
- const [m] = findMatches(nodes, 'target')
+ const [m] = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
if (!m) throw new Error('expected a match')
expect(nearestPrecedingHeadingId(nodes, m)).toBe(null)
})
@@ -74,7 +74,7 @@ describe('matchScrollTarget', () => {
test('offset reserves the overlay height so the match lands below the overlay', () => {
const md = '# A\n\n## B\n\nfoo target\n\n# C'
const { nodes, toc } = buildTree(md)
- const [m] = findMatches(nodes, 'target')
+ const [m] = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
if (!m) throw new Error('expected a match')
// Match sits under `## B`; after the jump both `# A` and the offscreen
// `## B` render as ancestor rows — two overlay rows the scroll must clear.
@@ -87,7 +87,7 @@ describe('matchScrollTarget', () => {
test('returns null when no heading precedes the match', () => {
const md = 'target text\n\n# H'
const { nodes, toc } = buildTree(md)
- const [m] = findMatches(nodes, 'target')
+ const [m] = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
if (!m) throw new Error('expected a match')
expect(matchScrollTarget({ nodes, match: m, fold: createFold({ toc }) })).toBe(null)
})
diff --git a/src/app/lib/preprocess.ts b/src/app/lib/preprocess.ts
index e5d25e2..069cbde 100644
--- a/src/app/lib/preprocess.ts
+++ b/src/app/lib/preprocess.ts
@@ -9,10 +9,16 @@ import { dotToMermaid } from './dot-to-mermaid'
*/
export const MERMAID_ASCII_LANG = 'mermaidascii'
+/** A code token after diagram rendering; `diagramSource` is the mermaid it was rendered from. */
+export type DiagramCode = Tokens.Code & { diagramSource?: string }
+
+/** Spacing knobs of the ASCII renderer (cells between nodes, blank rows inside boxes). */
+export type DiagramSpacing = { paddingX: number; boxBorderPadding: number }
+
/**
* Rewrites mermaid / DOT fences into rendered ASCII in place and returns the
- * same token list. Only `lang` and `text` change; `raw` keeps the source
- * fence so line-number passes over the same tokens still match the file.
+ * same token list. Only `lang`, `text`, and `diagramSource` change; `raw` keeps
+ * the source fence so line-number passes over the same tokens still match the file.
* Working on tokens rather than the markdown text means fences nested in
* lists, blockquotes, or a wider code fence are handled by the lexer's own
* nesting rules instead of a regex.
@@ -20,7 +26,7 @@ export const MERMAID_ASCII_LANG = 'mermaidascii'
export function renderDiagramBlocks(tokens: Tokens.Generic[]): Tokens.Generic[] {
for (const t of tokens) {
if (t.type === 'code') {
- renderDiagramCode(t as Tokens.Code)
+ renderDiagramCode(t as DiagramCode)
} else if (t.type === 'blockquote') {
renderDiagramBlocks(((t as Tokens.Blockquote).tokens ?? []) as Tokens.Generic[])
} else if (t.type === 'list') {
@@ -32,36 +38,41 @@ export function renderDiagramBlocks(tokens: Tokens.Generic[]): Tokens.Generic[]
return tokens
}
-function renderDiagramCode(code: Tokens.Code): void {
- const lang = fenceLang(code)
- let ascii: string | undefined
- if (lang === 'mermaid') {
- ascii = renderAscii(code.text)
- } else if (lang === 'dot' || lang === 'graphviz') {
- // DOT reaches the ASCII renderer by translation; untranslatable DOT stays a code block.
- try {
- ascii = renderAscii(dotToMermaid(code.text))
- } catch {
- ascii = undefined
- }
+/** Renders mermaid to ASCII with trailing spaces trimmed; undefined when the renderer rejects it. */
+export function renderAscii(diagram: string, spacing?: DiagramSpacing): string | undefined {
+ try {
+ return renderMermaidAscii(diagram.trim(), spacing)
+ .split('\n')
+ .map(l => l.trimEnd())
+ .join('\n')
+ } catch {
+ return undefined
}
+}
+
+function renderDiagramCode(code: DiagramCode): void {
+ const source = mermaidSource(code)
+ if (source === undefined) return
+ const ascii = renderAscii(source)
if (ascii === undefined) return
code.lang = MERMAID_ASCII_LANG
code.text = ascii
+ code.diagramSource = source
}
-/** First word of the info string, so `mermaid title=x` still counts as mermaid. */
-function fenceLang(code: Tokens.Code): string {
- return (code.lang ?? '').trim().split(/\s+/)[0] ?? ''
-}
-
-function renderAscii(diagram: string): string | undefined {
+function mermaidSource(code: Tokens.Code): string | undefined {
+ const lang = fenceLang(code)
+ if (lang === 'mermaid') return code.text
+ if (lang !== 'dot' && lang !== 'graphviz') return undefined
+ // DOT reaches the ASCII renderer by translation; untranslatable DOT stays a code block.
try {
- return renderMermaidAscii(diagram.trim())
- .split('\n')
- .map(l => l.trimEnd())
- .join('\n')
+ return dotToMermaid(code.text)
} catch {
return undefined
}
}
+
+/** First word of the info string, so `mermaid title=x` still counts as mermaid. */
+function fenceLang(code: Tokens.Code): string {
+ return (code.lang ?? '').trim().split(/\s+/)[0] ?? ''
+}
diff --git a/src/app/lib/progressive.test.ts b/src/app/lib/progressive.test.ts
index 31ba2ac..cdb9b7a 100644
--- a/src/app/lib/progressive.test.ts
+++ b/src/app/lib/progressive.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test'
-import { buildTree } from './ast'
+import { buildTree, buildTreeFromTokens, lexMarkdown } from './ast'
import { renderAnsi } from './renderAnsi'
import {
estimateNodeRows,
@@ -8,7 +8,7 @@ import {
initialMountCount,
sliceCountForRows,
} from './progressive'
-import { MERMAID_ASCII_LANG } from './preprocess'
+import { MERMAID_ASCII_LANG, renderDiagramBlocks } from './preprocess'
import type { Node } from './ast'
const WIDTH = 80
@@ -46,6 +46,15 @@ describe('estimateNodeRows', () => {
expect(estimateNodeRows(n, WIDTH)).toBe(3)
})
+ test('an overflowing diagram counts the lines of its fitted render', () => {
+ const md = '```mermaid\ngraph LR\n A[Start here] --> B[Parse markdown] --> C[Done all]\n```'
+ const n = buildTreeFromTokens(renderDiagramBlocks(lexMarkdown(md))).nodes[0]
+ if (n?.kind !== 'code') throw new Error('fixture must parse to a code node')
+ expect(estimateNodeRows(n, 1000)).toBe(5)
+ // Tight spacing drops the blank rows inside each box.
+ expect(estimateNodeRows(n, 30)).toBe(3)
+ })
+
test('unrendered mermaid source is line count + 4 (framed fallback)', () => {
const n: Node = { kind: 'code', lang: 'mermaid', value: 'a\nb\nc' }
expect(estimateNodeRows(n, WIDTH)).toBe(7)
diff --git a/src/app/lib/progressive.ts b/src/app/lib/progressive.ts
index fcd7b1b..4d3ee9c 100644
--- a/src/app/lib/progressive.ts
+++ b/src/app/lib/progressive.ts
@@ -4,6 +4,7 @@
// `--render` cap.
import { inlineVisibleWidth } from './inline-width'
import { MERMAID_ASCII_LANG } from './preprocess'
+import { codeText } from './diagram-fit'
import type { ListItem, Node } from './ast'
/** Nodes appended per growth tick after first paint. */
@@ -70,7 +71,9 @@ export function estimateNodeRows(node: Node, contentWidth: number): number {
case 'paragraph':
return Math.max(1, Math.ceil(inlineVisibleWidth(node.inline) / Math.max(1, contentWidth)))
case 'code': {
- const lines = node.value.split('\n').length
+ // A diagram fitted to the content width is never taller than one fitted to the
+ // (wider or equal) breakout width, so this stays low-biased.
+ const lines = codeText({ node, breakoutWidth: contentWidth }).split('\n').length
// Rendered mermaid ASCII renders bare (no frame); others (incl. unrendered
// mermaid source) add border (2) + paddingY (2).
return node.lang === MERMAID_ASCII_LANG ? lines : lines + 4
diff --git a/src/app/lib/scrollbox-handle.test.ts b/src/app/lib/scrollbox-handle.test.ts
index 29a7f18..3950cff 100644
--- a/src/app/lib/scrollbox-handle.test.ts
+++ b/src/app/lib/scrollbox-handle.test.ts
@@ -100,6 +100,7 @@ function makeDeps(
projections: () => new Map(),
isFullyMounted: () => false,
contentWidth: () => 80,
+ breakoutWidth: () => 80,
mountedCount: () => 1,
docKey: () => 'doc.md',
...over.live,
diff --git a/src/app/lib/scrollbox-handle.ts b/src/app/lib/scrollbox-handle.ts
index 8b47c9e..cde9455 100644
--- a/src/app/lib/scrollbox-handle.ts
+++ b/src/app/lib/scrollbox-handle.ts
@@ -40,6 +40,8 @@ export type ScrollboxHandleDeps = {
projections(): Map
isFullyMounted(): boolean
contentWidth(): number
+ /** Diagrams re-fit to this, so a change moves layout like a `contentWidth` rewrap. */
+ breakoutWidth(): number
/** Top-level nodes mounted so far; grows once per progressive-mount chunk. */
mountedCount(): number
docKey(): string
@@ -68,10 +70,11 @@ export function createScrollboxHandle(deps: ScrollboxHandleDeps): ScrollboxSeam
const geom = createBoxGeometry(box)
const scrollListeners = new Set<() => void>()
// Marks are document-space, so only a rewrap or newly mounted content can move
- // one: width rewraps, each mounted chunk grows the content, and navigating swaps
+ // one: width rewraps or re-fits, each mounted chunk grows the content, and navigating swaps
// the document. A reload keeps the same key and is caught instead by the cache's
// `matches` identity check, since its doc reset clears the search.
- const renderKey = (): string => `${live.docKey()}:${live.contentWidth()}:${live.mountedCount()}`
+ const renderKey = (): string =>
+ `${live.docKey()}:${live.contentWidth()}:${live.breakoutWidth()}:${live.mountedCount()}`
// Latched in `onFrame`, not read live: these update a render before the matching
// renderables have geometry, so a read-time key would cache marks resolved against
// the previous layout and then never invalidate them.
diff --git a/src/app/lib/search.test.ts b/src/app/lib/search.test.ts
index e5f56ee..ed78acc 100644
--- a/src/app/lib/search.test.ts
+++ b/src/app/lib/search.test.ts
@@ -3,17 +3,18 @@ import { buildTree } from './ast'
import { blockId } from './scroll-marks'
import { findMatches } from './search'
-const count = (md: string, q: string) => findMatches(buildTree(md).nodes, q).length
+const count = (md: string, q: string) =>
+ findMatches({ nodes: buildTree(md).nodes, pattern: q, breakoutWidth: 80 }).length
describe('findMatches', () => {
test('empty pattern returns empty', () => {
const { nodes } = buildTree('hello world')
- expect(findMatches(nodes, '')).toEqual([])
+ expect(findMatches({ nodes: nodes, pattern: '', breakoutWidth: 80 })).toEqual([])
})
test('finds case-insensitive match in paragraph', () => {
const { nodes } = buildTree('Hello World')
- const m = findMatches(nodes, 'hello')
+ const m = findMatches({ nodes: nodes, pattern: 'hello', breakoutWidth: 80 })
expect(m.length).toBe(1)
expect(m[0]?.start).toBe(0)
expect(m[0]?.length).toBe(5)
@@ -21,23 +22,23 @@ describe('findMatches', () => {
test('finds multiple matches', () => {
const { nodes } = buildTree('foo bar foo')
- const m = findMatches(nodes, 'foo')
+ const m = findMatches({ nodes: nodes, pattern: 'foo', breakoutWidth: 80 })
expect(m.length).toBe(2)
})
test('searches inside strong', () => {
const { nodes } = buildTree('**bold target** trailing')
- expect(findMatches(nodes, 'target').length).toBe(1)
+ expect(findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 }).length).toBe(1)
})
test('searches code blocks', () => {
const { nodes } = buildTree('```\nfoo target\n```')
- expect(findMatches(nodes, 'target').length).toBe(1)
+ expect(findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 }).length).toBe(1)
})
test('searches inside blockquote and extends path', () => {
const { nodes } = buildTree('> target text')
- const m = findMatches(nodes, 'target')
+ const m = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
expect(m.length).toBe(1)
// Path should include both blockquote index and child paragraph index.
expect(m[0]?.blockPath.length).toBeGreaterThan(1)
@@ -45,25 +46,29 @@ describe('findMatches', () => {
test('searches inside list items', () => {
const { nodes } = buildTree('- alpha\n- target item\n- gamma')
- const m = findMatches(nodes, 'target')
+ const m = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
expect(m.length).toBe(1)
})
test('matches alt text on image blocks', () => {
const { nodes } = buildTree('')
- expect(findMatches(nodes, 'cat').length).toBeGreaterThan(0)
+ expect(findMatches({ nodes: nodes, pattern: 'cat', breakoutWidth: 80 }).length).toBeGreaterThan(
+ 0,
+ )
})
test('matches alt text on inline images inside paragraphs', () => {
const { nodes } = buildTree('See  in action')
- expect(findMatches(nodes, 'the cat').length).toBeGreaterThan(0)
+ expect(
+ findMatches({ nodes: nodes, pattern: 'the cat', breakoutWidth: 80 }).length,
+ ).toBeGreaterThan(0)
})
test('searches inside table header and body with run keys', () => {
const md = '| H1 | H2 |\n|---|---|\n| body target | x |'
const { nodes } = buildTree(md)
- const headerMatch = findMatches(nodes, 'H1')
- const bodyMatch = findMatches(nodes, 'target')
+ const headerMatch = findMatches({ nodes: nodes, pattern: 'H1', breakoutWidth: 80 })
+ const bodyMatch = findMatches({ nodes: nodes, pattern: 'target', breakoutWidth: 80 })
expect(headerMatch.length).toBe(1)
expect(headerMatch[0]?.runKey).toBe('h0') // first header cell
expect(bodyMatch.length).toBe(1)
@@ -72,7 +77,7 @@ describe('findMatches', () => {
test('stamps blockElementId: heading slug for headings, blockId otherwise', () => {
const { nodes } = buildTree('# Alpha bravo\n\nalpha bravo\n')
- const matches = findMatches(nodes, 'bravo')
+ const matches = findMatches({ nodes: nodes, pattern: 'bravo', breakoutWidth: 80 })
const heading = nodes[0]
expect(heading?.kind).toBe('heading')
expect(matches[0]?.blockElementId).toBe(heading?.kind === 'heading' ? heading.id : '')
@@ -121,7 +126,11 @@ describe('visible-text matching', () => {
})
test('match carries run coordinates', () => {
- const [m] = findMatches(buildTree('1. first item').nodes, '1. first')
+ const [m] = findMatches({
+ nodes: buildTree('1. first item').nodes,
+ pattern: '1. first',
+ breakoutWidth: 80,
+ })
expect(m).toMatchObject({ runKey: 'main', start: 0, length: 8 })
expect(m?.blockElementId).toBe('itm-0-0')
})
diff --git a/src/app/lib/search.ts b/src/app/lib/search.ts
index 2e3c117..0b52dc3 100644
--- a/src/app/lib/search.ts
+++ b/src/app/lib/search.ts
@@ -18,11 +18,20 @@ export type Match = {
length: number
}
-export function findMatches(nodes: Node[], pattern: string): Match[] {
+/** `breakoutWidth` must be the Viewer's: diagram text, and so match offsets, depends on it. */
+export function findMatches({
+ nodes,
+ pattern,
+ breakoutWidth,
+}: {
+ nodes: Node[]
+ pattern: string
+ breakoutWidth: number
+}): Match[] {
if (!pattern) return []
const re = new RegExp(escapeRegex(pattern), 'gi')
const out: Match[] = []
- for (const proj of projectionMap(nodes).values()) {
+ for (const proj of projectionMap(nodes, breakoutWidth).values()) {
for (const run of proj.runs) {
const text = runText(run)
re.lastIndex = 0
diff --git a/src/app/lib/visible-text.test.ts b/src/app/lib/visible-text.test.ts
index 1d81227..d562909 100644
--- a/src/app/lib/visible-text.test.ts
+++ b/src/app/lib/visible-text.test.ts
@@ -10,7 +10,7 @@ import {
} from './visible-text'
function projectMd(md: string) {
- return projectDocument(buildTree(md).nodes)
+ return projectDocument(buildTree(md).nodes, 80)
}
function texts(md: string): string[] {
return projectMd(md).flatMap(p => p.runs.map(runText))
@@ -103,7 +103,7 @@ describe('projectDocument', () => {
const list = nodes[0]
expect(list?.kind).toBe('list')
if (list?.kind !== 'list') return
- const projs = projectDocument(nodes)
+ const projs = projectDocument(nodes, 80)
list.items.forEach((item, i) => {
const run = projs[i]?.runs[0]
expect(run && runText(run)).toBe(
diff --git a/src/app/lib/visible-text.ts b/src/app/lib/visible-text.ts
index 8ce4f6a..e970955 100644
--- a/src/app/lib/visible-text.ts
+++ b/src/app/lib/visible-text.ts
@@ -2,6 +2,7 @@ import type { InlineNode, ListItem, Node } from './ast'
import type { HtmlSegment } from './html'
import { parseHtmlSegments } from './html'
import { blockId } from './scroll-marks'
+import { codeText } from './diagram-fit'
/**
* Projection of the document into the exact text the renderer prints.
@@ -20,21 +21,21 @@ export type Run = { key: string; segments: Segment[] }
export type BlockProjection = { blockElementId: string; blockPath: number[]; runs: Run[] }
-export function projectDocument(nodes: Node[]): BlockProjection[] {
+/** `breakoutWidth` picks which render of each diagram is projected (see `codeText`). */
+export function projectDocument(nodes: Node[], breakoutWidth: number): BlockProjection[] {
const out: BlockProjection[] = []
- walkBlocks(nodes, [], out)
+ walkBlocks(nodes, [], out, breakoutWidth)
return out
}
-/** Per-document projection lookup, cached on the nodes array identity. */
-const mapCache = new WeakMap>()
-export function projectionMap(nodes: Node[]): Map {
- let m = mapCache.get(nodes)
- if (!m) {
- m = new Map(projectDocument(nodes).map(p => [p.blockElementId, p]))
- mapCache.set(nodes, m)
- }
- return m
+/** Per-document projection lookup, cached on the nodes array identity for the latest width. */
+const mapCache = new WeakMap }>()
+export function projectionMap(nodes: Node[], breakoutWidth: number): Map {
+ const cached = mapCache.get(nodes)
+ if (cached && cached.breakoutWidth === breakoutWidth) return cached.map
+ const map = new Map(projectDocument(nodes, breakoutWidth).map(p => [p.blockElementId, p]))
+ mapCache.set(nodes, { breakoutWidth, map })
+ return map
}
export function runText(run: Run): string {
@@ -144,14 +145,19 @@ function seg(text: string, element: number, searchable = true): Segment {
return { text, element, searchable }
}
-function walkBlocks(nodes: Node[], path: number[], out: BlockProjection[]): void {
+function walkBlocks(
+ nodes: Node[],
+ path: number[],
+ out: BlockProjection[],
+ breakoutWidth: number,
+): void {
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i]
- if (n) walkChild(n, [...path, i], out)
+ if (n) walkChild(n, [...path, i], out, breakoutWidth)
}
}
-function walkChild(n: Node, p: number[], out: BlockProjection[]): void {
+function walkChild(n: Node, p: number[], out: BlockProjection[], breakoutWidth: number): void {
switch (n.kind) {
case 'heading': {
const segs = [seg(headingPrefixText(n.level), 0), ...inlineSegments(n.text, 0)]
@@ -170,14 +176,14 @@ function walkChild(n: Node, p: number[], out: BlockProjection[]): void {
out.push({
blockElementId: blockId(p),
blockPath: p,
- runs: [{ key: 'main', segments: [seg(n.value, 0)] }],
+ runs: [{ key: 'main', segments: [seg(codeText({ node: n, breakoutWidth }), 0)] }],
})
break
case 'list':
- projectListItems(n.ordered, n.start, n.items, p, out)
+ projectListItems(n.ordered, n.start, n.items, p, out, breakoutWidth)
break
case 'blockquote':
- walkBlocks(n.children, p, out)
+ walkBlocks(n.children, p, out, breakoutWidth)
break
case 'table': {
const runs: Run[] = [
@@ -211,7 +217,7 @@ function walkChild(n: Node, p: number[], out: BlockProjection[]): void {
{ key: 'summary', segments: [seg('▾ ', 0, false), ...inlineSegments(n.summary, 0)] },
],
})
- walkBlocks(n.children, p, out)
+ walkBlocks(n.children, p, out, breakoutWidth)
break
}
}
@@ -222,6 +228,7 @@ function projectListItems(
items: ListItem[],
listPath: number[],
out: BlockProjection[],
+ breakoutWidth: number,
): void {
for (let j = 0; j < items.length; j++) {
const item = items[j]
@@ -240,7 +247,7 @@ function projectListItems(
const restBase = isFirstParagraph ? 1 : 0
for (let k = 0; k < restNodes.length; k++) {
const child = restNodes[k]
- if (child) walkChild(child, [...itemPath, restBase + k], out)
+ if (child) walkChild(child, [...itemPath, restBase + k], out, breakoutWidth)
}
}
}
diff --git a/src/app/state.ts b/src/app/state.ts
index fd2f2e7..b28e88e 100644
--- a/src/app/state.ts
+++ b/src/app/state.ts
@@ -117,6 +117,12 @@ export type AppState = {
/** Width (in cols) of the Viewer's content area, after TOC, scrollbar and padding. Capped to CONTENT_MAX_WIDTH. */
contentWidth: number
+ /**
+ * Columns a rendered diagram may span. Equals `contentWidth` while the TOC is
+ * shown; with no sidebar it is the whole Viewer column, past the reading cap.
+ */
+ breakoutWidth: number
+
/** Directory of the active document; base dir for resolving relative links. Undefined for stdin. */
dir?: string
/** Number of entries on the back stack (drives the back affordance). */
diff --git a/test/mermaid-width.md b/test/mermaid-width.md
new file mode 100644
index 0000000..8094796
--- /dev/null
+++ b/test/mermaid-width.md
@@ -0,0 +1,153 @@
+# Mermaid Width Fitting
+
+Manual check for diagram width fitting. A rendered diagram wider than its
+column re-renders with tighter spacing (smaller gaps between nodes, then no
+blank rows inside boxes) until it fits. If no spacing fits, the tightest
+render shows and the right side clips.
+
+Widths below are in columns; a diagram needs its width + 4 for the side
+margins. With the TOC shown, diagrams stop at the content cap (default 100).
+With the TOC hidden (`t`), prose grows only by the sidebar width, but diagrams
+break out across the whole terminal, and the scrollbar moves to its right edge.
+
+| Diagram | Default | Tightest | Expected at the 100 cap |
+| -------------- | ------- | -------- | ----------------------------- |
+| Small chain | 37 | 23 | default spacing |
+| Medium chain | 96 | 70 | default spacing (exact fit) |
+| Wide chain | 114 | 82 | compact, whole |
+| Branching flow | 120 | 88 | compact, whole |
+| DOT chain | 126 | 88 | compact, whole |
+| Huge chain | 180 | 136 | tightest, right side clipped |
+| Sequence | 97 | 97 | no compaction, clips 1 column |
+| State machine | 27 | 27 | default spacing |
+
+Things to check:
+
+1. At a wide terminal with the TOC shown, every row in the table above
+ matches its "Expected" column.
+2. Narrow the terminal (or drag the TOC seam left): diagrams step down to
+ tighter spacing one by one, and the Medium chain starts to compact.
+3. Hide the TOC with `t` at a terminal of 186+ columns: every diagram,
+ including the Huge chain, shows whole at default spacing, while prose still
+ wraps near column 100 plus the sidebar width.
+4. Scroll a diagram up under the sticky header: no part of it shows to the
+ right of the header.
+5. Search `/zebra` and press Enter: the match highlights inside the Wide
+ chain, and the search bar sits at the right edge. Resize or toggle the TOC;
+ the highlight stays on the label.
+6. Diagrams nested in a list and a blockquote fit the same way.
+
+## Small chain
+
+```mermaid
+graph LR
+ A[Read] --> B[Parse] --> C[Render]
+```
+
+## Medium chain
+
+```mermaid
+graph LR
+ A[Open file] --> B[Lex tokens] --> C[Render diagrams] --> D[Build tree] --> E[Mount viewer]
+```
+
+## Wide chain
+
+The `zebra` label is the search target.
+
+```mermaid
+graph LR
+ A[Start here] --> B[Parse markdown] --> C[Build tree] --> D[Render zebra] --> E[Paint frame] --> F[Done all]
+```
+
+## Branching flow
+
+```mermaid
+flowchart LR
+ In[Markdown input] --> Lex[Lexer]
+ Lex --> Pre[Diagram pass]
+ Lex --> Lines[Heading lines]
+ Pre --> Tree[AST builder]
+ Tree --> Toc[TOC tree]
+ Tree --> Nodes[Block nodes]
+ Nodes --> Viewer[Scrollable viewer]
+ Toc --> Sidebar[Sidebar panel]
+```
+
+## DOT chain
+
+```dot
+digraph G {
+ rankdir=LR;
+ parse -> lex -> render_diagrams -> build_tree -> mount_viewer -> paint_frame -> wait_for_key;
+}
+```
+
+## Huge chain
+
+Too wide for any spacing at the default cap: with the TOC shown, the tightest
+render shows and the right side clips. Hide the TOC on a wide terminal to see
+it whole.
+
+```mermaid
+graph LR
+ A[Keyboard event] --> B[mapKey pure] --> C[Action value] --> D[dispatch pure] --> E[Commands effectful] --> F[ViewActions write] --> G[React rerender] --> H[Terminal frame]
+```
+
+## Sequence
+
+The ASCII renderer has no spacing knobs for sequence, class, or ER diagrams,
+so these keep their width at every step.
+
+```mermaid
+sequenceDiagram
+ participant User
+ participant Keyboard
+ participant Dispatcher
+ participant Commands
+ participant ScrollboxHandle
+ participant Renderer
+ User->>Keyboard: press j
+ Keyboard->>Dispatcher: mapKey result
+ Dispatcher->>Commands: scrollBy one
+ Commands->>ScrollboxHandle: scrollBy
+ ScrollboxHandle->>Renderer: request frame
+```
+
+## State machine
+
+A top-down layout: narrow already, so it never compacts.
+
+```mermaid
+stateDiagram-v2
+ [*] --> Idle
+ Idle --> Searching: slash key
+ Searching --> Committed: enter key
+ Committed --> Stepping: n or N
+ Stepping --> Committed
+ Committed --> Idle: escape key
+ Searching --> Idle: escape key
+```
+
+## Nested
+
+- A list item holding the Wide chain:
+
+ ```mermaid
+ graph LR
+ A[Start here] --> B[Parse markdown] --> C[Build tree] --> D[Render React] --> E[Paint frame] --> F[Done all]
+ ```
+
+> A blockquote holding the Branching flow:
+>
+> ```mermaid
+> flowchart LR
+> In[Markdown input] --> Lex[Lexer]
+> Lex --> Pre[Diagram pass]
+> Lex --> Lines[Heading lines]
+> Pre --> Tree[AST builder]
+> Tree --> Toc[TOC tree]
+> Tree --> Nodes[Block nodes]
+> Nodes --> Viewer[Scrollable viewer]
+> Toc --> Sidebar[Sidebar panel]
+> ```