Something went wrong. Try again.
A local-first note taking app
Something went wrong. Try again.
8.0 kB · 228 lines
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229/** * Shared helpers for the split live-preview decoration extensions. * * Each per-node file exports a *pure builder* over `EditorState` (so it can be * unit-tested headlessly, with no DOM / EditorView) plus an `Extension` built * with `decorationExtension`, which wraps the builder in a `ViewPlugin` and, * when the builder returns an `atomic` set, registers those ranges via * `EditorView.atomicRanges` so cursor/click motion skips zero-geometry hidden * markers. * * NOTE (Fallback A / tables): when the GFM table grid lands, every builder * that emits a `Decoration.mark`/`Decoration.replace` must first skip nodes * inside a `TableCell` (an `isInsideTableCell` guard) so it doesn't split the * one-cell-equals-one-flex-item wrapper. Tables are out of scope here, so no * guard is wired yet — see the reams reference `markdown-context.ts`. * * MODE CONTRACT (edit vs view): a builder MUST make its reveal-on-cursor * decision *only* through the helpers below (`isCursorNearSameLine`, * `isCursorInRange`, `isCursorOnBlockLine`, `cursorLineNumber`) — never by * reading `state.selection` directly. In `view` mode these helpers report that * the cursor is nowhere, so every element hides its syntax and stays rendered * with no per-builder branch. Follow the contract and a new element works in * both modes for free (see `mode.ts`). */import { type EditorState, RangeSetBuilder, type Extension,} from '@codemirror/state';import { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate,} from '@codemirror/view';import { syntaxTree } from '@codemirror/language';
import { editorModeFacet } from './mode';
/** * How far past a span's boundaries the cursor still reveals its markers. * * 0 means markers are shown only while the cursor is *within* the span * (boundaries inclusive), and hide as soon as it moves one character past the * closing marker. A wider window would keep e.g. `*abc*` markers visible for N * more characters after the closing `*` is typed, which reads as the markers * "sticking" after the text is already formatted. */export const PROXIMITY_CHARS = 0;
export interface Range { from: number; to: number;}
export interface DecoRange { from: number; to: number; deco: Decoration;}
export interface BuildResult { /** Everything the plugin paints. */ decorations: DecorationSet; /** Subset registered with `EditorView.atomicRanges` (hidden markers). */ atomic?: DecorationSet;}
export type DecoBuilder = ( state: EditorState, ranges?: readonly Range[],) => BuildResult;
/** * Line number (1-based) the primary cursor sits on. In `view` mode returns -1, * which never equals a real 1-based line number, so callers comparing * `line.number !== cursorLine` always treat the cursor as absent. */export function cursorLineNumber(state: EditorState): number { if (state.facet(editorModeFacet) === 'view') return -1; return state.doc.lineAt(state.selection.main.head).number;}
/** The whole document as a single range — the headless/test default. */export function fullRanges(state: EditorState): Range[] { return [{ from: 0, to: state.doc.length }];}
/** * The view's visible ranges, or the full document when empty * (headless render / tests, where `visibleRanges` is `[]`). */export function iterRanges(view: EditorView): readonly Range[] { return view.visibleRanges.length > 0 ? view.visibleRanges : fullRanges(view.state);}
/** * True iff the cursor is on the SAME LINE as the span [from, to] AND within * `slack` chars of its boundaries (slack defaults to 0 → boundaries inclusive, * so the cursor must be within/touching the span). Same-line gating stops * proximity-reveal from leaking onto neighbouring lines. Correct for * bold/italic/strike/links, which cannot cross newlines per the * @lezer/markdown grammar. Inline code is the exception (it may span newlines) * — use `isCursorInRange` there. */export function isCursorNearSameLine( state: EditorState, from: number, to: number, slack: number = PROXIMITY_CHARS,): boolean { if (state.facet(editorModeFacet) === 'view') return false; const cursor = state.selection.main.head; if (cursor < from - slack || cursor > to + slack) return false; return state.doc.lineAt(cursor).number === state.doc.lineAt(from).number;}
/** Pure distance check (no same-line gate) — for spans that may cross lines. */export function isCursorInRange( state: EditorState, from: number, to: number, slack = 0,): boolean { if (state.facet(editorModeFacet) === 'view') return false; const cursor = state.selection.main.head; return cursor >= from - slack && cursor <= to + slack;}
/** True if the cursor's line falls anywhere within [blockFrom, blockTo]. */export function isCursorOnBlockLine( state: EditorState, blockFrom: number, blockTo: number,): boolean { if (state.facet(editorModeFacet) === 'view') return false; const cursorLine = state.doc.lineAt(state.selection.main.head).number; const startLine = state.doc.lineAt(blockFrom).number; const endLine = state.doc.lineAt(Math.min(blockTo, state.doc.length)).number; return cursorLine >= startLine && cursorLine <= endLine;}
/** * Sort a decoration list (`from` asc, then `to` asc — puts zero-length line * decorations before marks at the same offset) and pour it into a * `RangeSetBuilder`, whose `add` requires monotonic input. */export function finishDecos(decos: DecoRange[]): DecorationSet { decos.sort((a, b) => a.from - b.from || a.to - b.to); const builder = new RangeSetBuilder<Decoration>(); for (const d of decos) builder.add(d.from, d.to, d.deco); return builder.finish();}
/** * Accumulator that dedupes decorations by `from:to:class` (overlapping visible * ranges can enter the same node twice) and tracks the atomic subset. */export class DecoCollector { private readonly seen = new Set<string>(); readonly all: DecoRange[] = []; readonly atomic: DecoRange[] = [];
push(from: number, to: number, deco: Decoration, isAtomic = false): void { // `Decoration.spec` is typed `any` upstream, so direct access is fine. const cls: string = deco.spec?.class ?? ''; const key = `${from}:${to}:${cls}`; if (this.seen.has(key)) return; this.seen.add(key); this.all.push({ from, to, deco }); if (isAtomic) this.atomic.push({ from, to, deco }); }
result(): BuildResult { return { decorations: finishDecos(this.all), atomic: finishDecos(this.atomic), }; }}
/** Rebuild triggers: doc/selection/viewport changes plus incremental parses. */export function shouldRebuild(update: ViewUpdate): boolean { return ( update.docChanged || update.selectionSet || update.viewportChanged || // A mode toggle is a compartment reconfigure that sets none of the flags // above, so compare the facet explicitly to re-run the builders. update.startState.facet(editorModeFacet) !== update.state.facet(editorModeFacet) || syntaxTree(update.startState) !== syntaxTree(update.state) );}
/** * Wrap a pure builder in a ViewPlugin + optional atomicRanges provider. */export function decorationExtension(build: DecoBuilder): Extension { const plugin = ViewPlugin.fromClass( class { decorations: DecorationSet; atomic: DecorationSet; constructor(view: EditorView) { const r = build(view.state, iterRanges(view)); this.decorations = r.decorations; this.atomic = r.atomic ?? Decoration.none; } update(update: ViewUpdate) { if (!shouldRebuild(update)) return; const r = build(update.view.state, iterRanges(update.view)); this.decorations = r.decorations; this.atomic = r.atomic ?? Decoration.none; } }, { decorations: (v) => v.decorations }, );
return [ plugin, EditorView.atomicRanges.of( (view) => view.plugin(plugin)?.atomic ?? Decoration.none, ), ];}