@singapore-editor/diff 0.2.0 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"editorDiffPlugin.js","names":[],"sources":["../src/editorDiffPlugin.ts"],"sourcesContent":["import { registerDiffColors } from './theme'\nimport type {\n EditorContributionChange,\n EditorDecorationContribution,\n EditorDecorationContributionContext,\n EditorDisposable,\n EditorGutterRowContext,\n EditorInjectedTextRow,\n EditorPlugin,\n EditorPluginContext,\n EditorSnippetTokenSource,\n EditorViewContribution,\n EditorViewContributionContext,\n EditorViewContributionUpdateKind,\n EditorViewSnapshot,\n} from '@singapore-editor/core/extensions'\nimport { EDITOR_SNIPPET_TOKENS_FEATURE } from '@singapore-editor/core/extensions'\nimport type { EditorToken } from '@singapore-editor/core/syntax'\nimport { createDiffGutterContribution } from './diffGutter'\nimport { diffInlineHighlightRanges, diffRowDecorations } from './diffRows'\nimport {\n DiffSyntaxController,\n type PreparedDiffSyntaxInput,\n type PreparedDiffSyntaxSource,\n} from './diffSyntax'\nimport {\n diffGutterDigits,\n type DiffGutterDigits,\n type DiffGutterLayout,\n type DiffGutterSide,\n} from './gutters'\nimport { createLiveDiffProjection, type LiveDiffProjection } from './liveProjection'\nimport { createTextDiff } from './model'\nimport { createSplitProjection, createStackedProjection } from './projection'\nimport { createDiffRegionStore, type DiffRegionStore } from './regions'\nimport type { DiffFile, DiffRenderRow, DiffSyntaxBackend, DiffTextFile } from './types'\n\nexport type DiffPluginMode = 'document' | 'overlay'\n\nexport type DiffPluginOptions = {\n /**\n * §C1. `document` is the parity path; `overlay` is explicitly non-parity — see §C2.\n *\n * Required, with no default. The factory this replaced took no arguments and was always overlay,\n * so the natural migration — rename the call, keep the empty argument list — would otherwise\n * produce a plugin that mounts, registers everything, renders nothing and reports no error,\n * because `setBaseFile` and `setEnabled` both early-return outside overlay mode.\n */\n readonly mode: DiffPluginMode\n readonly side?: DiffGutterSide\n /**\n * Expansion state, shared when a host drives two sides of one diff. Omit it and the plugin keeps\n * a private store; pass one store to both split plugins and a toggle on either side moves both.\n * See regions.ts — this is what holds §C7 together.\n */\n readonly regions?: DiffRegionStore\n readonly syntaxBackend?: DiffSyntaxBackend\n readonly syntaxHighlight?: boolean\n}\n\nexport type DiffPlugin = EditorPlugin & {\n /**\n * `document` mode: the file to project. The host owns the editor's text — §C3. `prepared`\n * streams from `prepareDiffSyntax` for this file paint with the first rows, and a preparation\n * still running is awaited in place of a second parse; the plugin owns them.\n */\n setFile(file: DiffFile | null, prepared?: PreparedDiffSyntaxInput): void\n /** The current file's parsed streams, handed to the caller; empty while a parse is running. */\n releasePreparedSyntax(): readonly PreparedDiffSyntaxSource[]\n getRows(): readonly DiffRenderRow[]\n /** Both sides in row order. Cached until the file or expansion state changes. */\n getStackedRows(): readonly DiffRenderRow[]\n /**\n * Projected syntax tokens for the current rows. The host passes them with the rows' text,\n * `setText(text, { tokens })`, or an expansion toggle repaints uncoloured (§C10).\n */\n isSyntaxReady(): boolean\n getTokens(): readonly EditorToken[]\n onDidChangeRows(listener: () => void): EditorDisposable\n onDidChangeTokens(listener: () => void): EditorDisposable\n /** §C5. Hosts must not mirror this. */\n getExpandedRegions(): ReadonlySet<string>\n toggleRegion(key: string): void\n\n /** `overlay` mode: the buffer the live editor text is diffed against. */\n setBaseFile(file: DiffTextFile | null): void\n setEnabled(enabled: boolean): void\n}\n\n/** The diff row under a pointer: which pane, that pane's rows, and the index into them. */\nexport type DiffRowHit = {\n readonly side: DiffGutterSide\n readonly rowIndex: number\n readonly rows: readonly DiffRenderRow[]\n}\n\n// How a pointer event finds the plugin that owns the pane under it, so a host never reads row\n// attributes or pane classes to work out where a press landed.\nconst viewsByScrollElement = new WeakMap<Element, DiffViewContribution>()\n\n/** `null` outside a `document`-mode diff pane, or over something that is not a diff row. */\nexport function diffRowAtEvent(event: MouseEvent): DiffRowHit | null {\n const target = event.target\n if (!(target instanceof Element)) return null\n\n const scrollElement = target.closest('[data-editor-diff-side]')\n if (!scrollElement) return null\n\n return viewsByScrollElement.get(scrollElement)?.rowHitAt(event) ?? null\n}\n\nconst EMPTY_PROJECTION: LiveDiffProjection = {\n injectedRows: [],\n rowDecorations: new Map(),\n rows: [],\n rowsByBufferRow: new Map(),\n}\nconst ROW_DECORATION_SOURCE = 'editor.diff'\nconst INLINE_HIGHLIGHT_STYLE = { backgroundColor: 'rgba(255, 255, 255, 0.18)' } as const\n\nlet nextDiffPluginId = 0\n\n/**\n * The one diff plugin (§C1), carrying two internal row-delivery modes.\n *\n * `document` — the editor holds a synthetic buffer of the projected rows and the plugin publishes\n * them for the host to push in. Everything works because the rows are real document lines.\n *\n * `overlay` — the editor holds the host's live, editable buffer and deletions arrive as injected\n * rows. Non-parity by construction; see §C2 and test/overlayModeLimits.test.ts before reaching for\n * it.\n */\nexport function createDiffPlugin(options: DiffPluginOptions): DiffPlugin {\n registerDiffColors()\n const runtime = new DiffPluginRuntime(options)\n\n return {\n name: `editor-diff-${options.mode}`,\n activate(context) {\n return runtime.activate(context)\n },\n setFile: (file, prepared) => runtime.setFile(file, prepared),\n releasePreparedSyntax: () => runtime.releasePreparedSyntax(),\n getRows: () => runtime.getRows(),\n getStackedRows: () => runtime.getStackedRows(),\n getTokens: () => runtime.getTokens(),\n isSyntaxReady: () => runtime.isSyntaxReady(),\n onDidChangeRows: (listener) => runtime.onDidChangeRows(listener),\n onDidChangeTokens: (listener) => runtime.onDidChangeTokens(listener),\n getExpandedRegions: () => runtime.getExpandedRegions(),\n toggleRegion: (key) => runtime.toggleRegion(key),\n setBaseFile: (file) => runtime.setBaseFile(file),\n setEnabled: (enabled) => runtime.setEnabled(enabled),\n }\n}\n\nclass DiffPluginRuntime {\n private readonly id = nextDiffPluginId++\n private readonly mode: DiffPluginMode\n private readonly side: DiffGutterSide\n private syntax: DiffSyntaxController\n private readonly rowListeners = new Set<() => void>()\n private readonly tokenListeners = new Set<() => void>()\n\n private readonly regions: DiffRegionStore\n private file: DiffFile | null = null\n private rows: readonly DiffRenderRow[] = []\n private stackedRows: readonly DiffRenderRow[] | null = null\n private digits: DiffGutterDigits = { old: 0, new: 0 }\n private hunkRows = false\n private expandableRows = false\n\n private baseFile: DiffTextFile | null = null\n private enabled: boolean\n private liveProjection: LiveDiffProjection = EMPTY_PROJECTION\n\n private decoration: DiffDecorationContribution | null = null\n private view: DiffViewContribution | null = null\n private injectedRowsListener: (() => void) | null = null\n private lastGutterLayout: DiffGutterLayout | null = null\n private readonly regionSubscription: EditorDisposable\n\n constructor(private readonly options: DiffPluginOptions) {\n this.mode = options.mode\n this.side = options.side ?? 'stacked'\n this.regions = options.regions ?? createDiffRegionStore()\n // A shared store means the sibling side's toggle lands here too.\n //\n // Held for the plugin's whole life, and never released. Every narrower lifetime is wrong:\n //\n // - torn down with the ACTIVATION, next to the syntax controller, which is the obvious place:\n // the first deactivation is then terminal. The plugin is re-activated against a fresh editor,\n // renders correctly, and is silently deaf to every expansion toggle after that. React\n // StrictMode makes mount -> unmount -> mount the normal development path, so a host that gets\n // this wrong sees gutter clicks do nothing at all.\n // - created only on activation: a plugin driven headlessly as a projection source, with no\n // editor behind it, never sees its own `toggleRegion`.\n // - released from `EditorPlugin.dispose`: that fires when an editor tears down, and a React\n // host reuses the same plugin instance across the next editor — so this is the first case\n // again with an extra step.\n //\n // Nothing leaks by holding it. The listener lives in the store, the store is the host's, and a\n // host drops both together; a plugin the host builds and never mounts — StrictMode\n // double-invokes the `useMemo` that builds one — is collected with it.\n this.regionSubscription = this.regions.onDidChange(() => this.handleRegionsChanged())\n // Overlay mode is switched on by the host once it has a base file; document mode is live from\n // the moment it has one.\n this.enabled = this.mode === 'document'\n this.syntax = this.createSyntaxController()\n }\n\n activate(context: EditorPluginContext): EditorDisposable[] {\n // A controller disposed by a previous deactivation is dead for good — its scheduler is\n // terminal, so `schedule()` returns an inactive handle forever and the diff would render\n // permanently uncoloured after a remove-then-re-add. The core supports that cycle\n // (`Editor.setPlugins`), so the controller's lifetime is the activation's, not the plugin's.\n //\n // Only a *replacement* controller needs the file pushed into it. Doing it unconditionally\n // re-parses a file the surviving controller is already holding — and when the host sets the\n // file before constructing the editor, which is the natural order, that means cancelling an\n // in-flight parse to start an identical one. Under shiki that is two worker owners for one\n // file.\n if (this.syntax.isDisposed()) {\n this.syntax = this.createSyntaxController()\n if (this.file) this.syntax.setFile(this.file, this.rows)\n }\n\n const disposables: EditorDisposable[] = [\n context.registerGutterContribution(\n createDiffGutterContribution({\n side: this.side,\n tint: this.mode === 'document' ? 'row' : 'cell',\n getDigits: () => this.gutterDigits(),\n resolveRow: (row) => this.resolveGutterRow(row),\n isEnabled: () => this.enabled,\n onLayout: (layout) => this.publishGutterLayout(layout),\n }),\n ),\n context.registerDecorationContribution({\n createContribution: (featureContext) => this.createDecorationContribution(featureContext),\n }),\n context.registerViewContribution({\n createContribution: (viewContext) => this.createViewContribution(viewContext),\n }),\n { dispose: () => this.syntax.dispose() },\n ]\n\n if (this.mode === 'overlay') {\n disposables.push(\n context.registerInjectedTextRowProvider({\n getInjectedTextRows: () => this.injectedRows(),\n onDidChangeInjectedTextRows: (listener) => this.setInjectedRowsListener(listener),\n }),\n )\n }\n\n return disposables\n }\n\n // ---------------------------------------------------------------- document mode (§C3, §C5)\n\n setFile(file: DiffFile | null, prepared: PreparedDiffSyntaxInput = []): void {\n if (this.mode !== 'document') {\n void Promise.resolve(prepared).then(\n (sources) => {\n for (const source of sources) source.dispose()\n },\n () => undefined,\n )\n return\n }\n\n this.file = file\n // The store decides whether this counts as the same diff, and drops expansion if not. Both\n // sides of a split share it, so both are told once.\n this.regions.setFile(file)\n this.rebuildRows()\n this.syntax.setFile(file, this.rows, prepared)\n this.notifyRows()\n }\n\n releasePreparedSyntax(): readonly PreparedDiffSyntaxSource[] {\n return this.syntax.release()\n }\n\n getRows(): readonly DiffRenderRow[] {\n if (this.mode === 'overlay') return this.liveProjection.rows\n return this.rows\n }\n\n getStackedRows(): readonly DiffRenderRow[] {\n if (this.mode === 'overlay') return this.liveProjection.rows\n if (this.side === 'stacked') return this.rows\n this.stackedRows ??= projectRows(this.file, 'stacked', this.regions.getExpandedRegions())\n return this.stackedRows\n }\n\n isSyntaxReady(): boolean {\n return this.syntax.isReady()\n }\n\n getTokens(): readonly EditorToken[] {\n return this.syntax.getTokens()\n }\n\n getExpandedRegions(): ReadonlySet<string> {\n return this.regions.getExpandedRegions()\n }\n\n toggleRegion(key: string): void {\n if (this.mode !== 'document') return\n if (!this.file) return\n\n // The store fans the change back to every plugin reading it, this one included, so the rebuild\n // happens in `handleRegionsChanged` rather than here.\n this.regions.toggleRegion(key)\n }\n\n private handleRegionsChanged(): void {\n if (this.mode !== 'document') return\n if (!this.file) return\n\n this.rebuildRows()\n // Same file, different rows: the parsed token streams still apply, so this re-projects\n // synchronously and `getTokens()` is correct before the host's `setText` returns (§C10).\n this.syntax.setRows(this.rows)\n this.notifyRows()\n }\n\n onDidChangeRows(listener: () => void): EditorDisposable {\n this.rowListeners.add(listener)\n return { dispose: () => this.rowListeners.delete(listener) }\n }\n\n onDidChangeTokens(listener: () => void): EditorDisposable {\n this.tokenListeners.add(listener)\n return { dispose: () => this.tokenListeners.delete(listener) }\n }\n\n private rebuildRows(): void {\n this.stackedRows = null\n this.rows = projectRows(this.file, this.side, this.regions.getExpandedRegions())\n // Both derived once here rather than per gutter-width recompute and per mousemove.\n this.digits = diffGutterDigits(this.rows)\n this.hunkRows = this.rows.some((row) => row.type === 'hunk')\n this.expandableRows = this.rows.some((row) => row.type === 'hunk' && row.expandable === true)\n }\n\n private notifyRows(): void {\n for (const listener of this.rowListeners) listener()\n this.decoration?.refresh()\n this.view?.refreshRows()\n }\n\n private notifyTokens(): void {\n for (const listener of this.tokenListeners) listener()\n }\n\n // ---------------------------------------------------------------- overlay mode\n\n setBaseFile(file: DiffTextFile | null): void {\n if (this.mode !== 'overlay') return\n\n this.baseFile = file\n this.decoration?.refresh()\n }\n\n setEnabled(enabled: boolean): void {\n if (this.mode !== 'overlay') return\n\n this.enabled = enabled\n this.decoration?.refresh()\n }\n\n private injectedRows(): readonly EditorInjectedTextRow[] {\n if (!this.enabled) return []\n return this.liveProjection.injectedRows\n }\n\n private setInjectedRowsListener(listener: () => void): EditorDisposable {\n this.injectedRowsListener = listener\n return {\n dispose: () => {\n if (this.injectedRowsListener === listener) this.injectedRowsListener = null\n },\n }\n }\n\n private gutterDigits(): DiffGutterDigits {\n if (this.mode === 'overlay') return diffGutterDigits(this.liveProjection.rows)\n return this.digits\n }\n\n /**\n * Which diff row a rendered gutter row is showing. The two modes cannot share an answer.\n *\n * `document` — §C4 holds, so the projection index is the buffer row and a positional lookup is\n * correct.\n *\n * `overlay` — the projection array interleaves injected deletion rows, so position and buffer\n * row diverge from the first deletion onwards; the mapping the projection publishes for exactly\n * this purpose is `rowsByBufferRow`, keyed `newLineNumber - 1`. An injected row is not in that\n * map at all and carries its own row as metadata instead.\n */\n private resolveGutterRow(row: EditorGutterRowContext): DiffRenderRow | null {\n if (this.mode === 'overlay') {\n if (row.source === 'injected') return injectedDiffRow(row)\n if (row.source !== 'document') return null\n return this.liveProjection.rowsByBufferRow.get(row.bufferRow) ?? null\n }\n\n if (row.source !== 'document') return null\n return this.rows[row.bufferRow] ?? null\n }\n\n // ---------------------------------------------------------------- contributions\n\n private createDecorationContribution(\n context: EditorDecorationContributionContext,\n ): EditorDecorationContribution {\n const contribution = new DiffDecorationContribution(context, {\n mode: this.mode,\n getRows: () => this.rows,\n buildLiveProjection: () => this.buildLiveProjection(context),\n setLiveProjection: (projection) => {\n this.liveProjection = projection\n },\n notifyInjectedRowsChanged: () => this.injectedRowsListener?.(),\n })\n this.decoration = contribution\n contribution.refresh()\n return {\n handleEditorChange: (change) => contribution.handleEditorChange(change),\n dispose: () => {\n if (this.decoration === contribution) this.decoration = null\n contribution.dispose()\n },\n }\n }\n\n private buildLiveProjection(context: EditorDecorationContributionContext): LiveDiffProjection {\n if (!this.enabled) return EMPTY_PROJECTION\n if (!this.baseFile) return EMPTY_PROJECTION\n if (!context.hasDocument()) return EMPTY_PROJECTION\n\n const file = createTextDiff({\n oldFile: this.baseFile,\n newFile: {\n path: this.baseFile.path,\n text: liveDiffDocumentText(context),\n languageId: this.baseFile.languageId,\n },\n })\n return createLiveDiffProjection(file)\n }\n\n private createViewContribution(\n context: EditorViewContributionContext,\n ): EditorViewContribution | null {\n const contribution = new DiffViewContribution(context, {\n highlightName: `editor-diff-${this.id}-${this.side}-inline`,\n mode: this.mode,\n side: this.side,\n getRows: () => this.getRows(),\n hasHunkRows: () => this.hunkRows,\n hasExpandableRows: () => this.expandableRows,\n toggleRegion: (key) => this.toggleRegion(key),\n detach: (disposed) => {\n lentSyntax?.dispose()\n if (this.view === disposed) this.view = null\n },\n })\n const lentSyntax = context\n .getFeature(EDITOR_SNIPPET_TOKENS_FEATURE)\n ?.addSource(snippetTokenSource(this.options.syntaxBackend))\n this.view = contribution\n if (this.lastGutterLayout) contribution.applyGutterLayout(this.lastGutterLayout)\n return contribution\n }\n\n private publishGutterLayout(layout: DiffGutterLayout): void {\n // Retained, never consumed. `width()` can run before a view contribution exists, and a\n // contribution can be torn down and rebuilt later on a fresh scroll element carrying none of\n // these custom properties. The gutter memoizes on the layout, so it will not republish an\n // unchanged one — leaving a replacement contribution with no other way to learn the geometry,\n // and `.editor-diff-gutter` falling back to `1fr 1fr 12px`, which is the drift the whole\n // custom-property dance exists to avoid.\n this.lastGutterLayout = layout\n this.view?.applyGutterLayout(layout)\n }\n\n private createSyntaxController(): DiffSyntaxController {\n return new DiffSyntaxController({\n side: this.side,\n backend: this.options.syntaxBackend,\n enabled: this.options.syntaxHighlight !== false,\n onDidChangeTokens: () => this.notifyTokens(),\n })\n }\n}\n\n// A live diff compares whole documents, and the diff library takes strings: an explicit extraction.\nfunction liveDiffDocumentText(context: EditorDecorationContributionContext): string {\n return context.materializeFullText()\n}\n\nfunction projectRows(\n file: DiffFile | null,\n side: DiffGutterSide,\n expandedRegions: ReadonlySet<string>,\n): readonly DiffRenderRow[] {\n if (!file) return []\n if (side === 'stacked') return createStackedProjection(file, { expandedRegions }).rows\n\n const projection = createSplitProjection(file, { expandedRegions })\n return side === 'old' ? projection.leftRows : projection.rightRows\n}\n\ntype DiffDecorationOptions = {\n readonly mode: DiffPluginMode\n readonly getRows: () => readonly DiffRenderRow[]\n readonly buildLiveProjection: () => LiveDiffProjection\n readonly setLiveProjection: (projection: LiveDiffProjection) => void\n readonly notifyInjectedRowsChanged: () => void\n}\n\nclass DiffDecorationContribution {\n private lastTextSnapshot: unknown = undefined\n\n constructor(\n private readonly context: EditorDecorationContributionContext,\n private readonly options: DiffDecorationOptions,\n ) {}\n\n /**\n * The editor's notification, which is not the same thing as \"the text changed\".\n *\n * Rebuilding an overlay projection materializes the whole document and runs `structuredPatch`\n * over it, synchronously. `handleEditorChange` also fires for selection-only changes —\n * `EditorContributionChange.kind` is one of edit/selection/undo/redo/none — and a caret move cannot\n * alter the diff, so paying for one is pure waste on the typing path. Text-snapshot identity is\n * the second guard, for the notification paths that carry no change object at all.\n *\n * Plugin-state changes (`setBaseFile`, `setEnabled`) call `refresh()` directly and are never\n * skipped: the text is the same but the diff it produces is not.\n */\n handleEditorChange(change: EditorContributionChange | null): void {\n if (this.options.mode === 'overlay') {\n if (change?.kind === 'selection') return\n\n const snapshot = this.context.getTextSnapshot()\n if (snapshot !== null && snapshot === this.lastTextSnapshot) return\n }\n\n this.refresh()\n }\n\n refresh(): void {\n this.lastTextSnapshot = this.context.getTextSnapshot()\n if (this.options.mode === 'document') {\n this.context.setRowDecorations(\n ROW_DECORATION_SOURCE,\n diffRowDecorations(this.options.getRows()),\n )\n return\n }\n\n this.applyLiveProjection(this.options.buildLiveProjection())\n }\n\n dispose(): void {\n if (this.options.mode === 'overlay') this.applyLiveProjection(EMPTY_PROJECTION)\n this.context.clearRowDecorations(ROW_DECORATION_SOURCE)\n }\n\n /**\n * These three steps are ordered, and the order is load-bearing.\n *\n * Announcing the injected-row change first would rebuild the row set before the cells are\n * repainted, and a row that the rebuild unmounts keeps whatever its cell last rendered — a\n * disabled live diff would leave a stale `4+` behind on a detached cell. Repainting first, while\n * that row is still mounted, is what clears it.\n *\n * The stored projection has to be current before the repaint, because the gutter reads its rows\n * from it.\n */\n private applyLiveProjection(projection: LiveDiffProjection): void {\n this.options.setLiveProjection(projection)\n this.context.setRowDecorations(ROW_DECORATION_SOURCE, projection.rowDecorations)\n this.options.notifyInjectedRowsChanged()\n }\n}\n\ntype DiffViewOptions = {\n readonly highlightName: string\n readonly mode: DiffPluginMode\n readonly side: DiffGutterSide\n readonly getRows: () => readonly DiffRenderRow[]\n readonly hasHunkRows: () => boolean\n readonly hasExpandableRows: () => boolean\n readonly toggleRegion: (key: string) => void\n readonly detach: (contribution: DiffViewContribution) => void\n}\n\n/** Pointer handling and inline word-diff highlights. */\nclass DiffViewContribution implements EditorViewContribution {\n readonly snapshotKey = 'diff-inline-v1'\n private readonly pressParticipant: EditorDisposable\n private readonly separatorRows: EditorDisposable\n private snapshot: EditorViewSnapshot | null = null\n private lastHighlightRows: readonly DiffRenderRow[] | null = null\n private lastHighlightTextVersion = -1\n\n constructor(\n private readonly context: EditorViewContributionContext,\n private readonly options: DiffViewOptions,\n ) {\n this.context.scrollElement.dataset.editorDiffSide = options.side\n viewsByScrollElement.set(this.context.scrollElement, this)\n this.pressParticipant = this.context.registerPressParticipant(this.claimSeparatorPress)\n this.separatorRows = this.context.registerNonCaretRows(this.isSeparatorRow)\n this.context.scrollElement.addEventListener('click', this.handleClick)\n this.context.scrollElement.addEventListener('mousemove', this.handleMouseMove)\n this.context.scrollElement.addEventListener('mouseleave', this.handleMouseLeave)\n }\n\n /**\n * The snapshot is kept for every update kind — the pointer hit-test reads it — but the two\n * derived jobs below are not per-frame work.\n *\n * `update` is called for `'viewport'` too, which `Editor.handleViewportChange` fires on every\n * scroll frame, and the highlights can only change when the rows or the text do.\n */\n update(snapshot: EditorViewSnapshot, kind: EditorViewContributionUpdateKind): void {\n this.snapshot = snapshot\n if (this.options.mode !== 'document') return\n if (kind === 'viewport' || kind === 'selection') return\n\n this.applyInlineHighlights()\n }\n\n captureVisiblePaint(snapshot: EditorViewSnapshot) {\n const viewport = this.context.scrollElement.getBoundingClientRect()\n const rows = this.options.getRows()\n const ranges = snapshot.visibleRows.flatMap((visible) => {\n const row = rows[visible.bufferRow]\n if (!row) return []\n const start = snapshot.lineStartsView.at(visible.bufferRow) ?? visible.startOffset\n return diffInlineHighlightRanges([row]).map((range) => ({\n start: range.start + start,\n end: range.end + start,\n }))\n })\n const rectangles = []\n for (const range of ranges) {\n const rect = this.context.getRangeClientRect(range.start, range.end)\n if (!rect || rect.width <= 0 || rect.height <= 0) continue\n rectangles.push({\n left: rect.left - viewport.left + snapshot.viewport.scrollLeft,\n top: rect.top - viewport.top + snapshot.viewport.scrollTop,\n width: rect.width,\n height: rect.height,\n backgroundColor: INLINE_HIGHLIGHT_STYLE.backgroundColor,\n })\n }\n return { id: `diff-inline-${this.options.side}`, status: 'ready' as const, rectangles }\n }\n\n refreshRows(): void {\n this.lastHighlightRows = null\n this.applyInlineHighlights()\n }\n\n applyGutterLayout(layout: DiffGutterLayout): void {\n // §3.3 trap 1: the canvas derived lane geometry arithmetically, so a DOM gutter has to hand CSS\n // the same numbers rather than approximate them with `1fr 1fr 12px`.\n const style = this.context.scrollElement.style\n const columns = layout.lanes.map((lane) => `${lane.width}px`).join(' ')\n style.setProperty('--editor-diff-gutter-columns', columns)\n style.setProperty('--editor-diff-gutter-total-width', `${layout.width}px`)\n }\n\n dispose(): void {\n this.pressParticipant.dispose()\n this.separatorRows.dispose()\n this.context.scrollElement.removeEventListener('click', this.handleClick)\n this.context.scrollElement.removeEventListener('mousemove', this.handleMouseMove)\n this.context.scrollElement.removeEventListener('mouseleave', this.handleMouseLeave)\n this.context.scrollElement.style.cursor = ''\n // A replacement view on the same element may already have registered itself.\n if (viewsByScrollElement.get(this.context.scrollElement) === this) {\n viewsByScrollElement.delete(this.context.scrollElement)\n }\n this.context.clearRangeHighlight(this.options.highlightName)\n // Or the runtime keeps writing highlights and gutter geometry through a torn-down context,\n // and holds its scroll element alive for the plugin's lifetime.\n this.options.detach(this)\n }\n\n // A highlight failure must not dispose the contribution and disable gutter expansion.\n private applyInlineHighlights(): void {\n const rows = this.options.getRows()\n const textVersion = this.snapshot?.textVersion ?? -1\n // Rows alone cannot key this: the view clamps ranges to the text it holds when they are set,\n // and the host pushes the new text only after the rows notification that first lands here.\n if (rows === this.lastHighlightRows && textVersion === this.lastHighlightTextVersion) return\n\n this.lastHighlightRows = rows\n this.lastHighlightTextVersion = textVersion\n try {\n this.context.setRangeHighlight(\n this.options.highlightName,\n diffInlineHighlightRanges(rows),\n INLINE_HIGHLIGHT_STYLE,\n )\n } catch (error) {\n this.context.log({\n action: 'editor.diff.inline_highlight_failed',\n level: 'warn',\n error: { message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n\n /**\n * Keeps the caret off a separator row, expandable or not.\n *\n * A separator is chrome, not content — but its label is real buffer text, because the host's\n * document is `joinRenderLines(rows)` and there is nowhere else for the label to live. So the\n * editor will happily rest a caret in the middle of `Show 12 unmodified lines`, and a collapsed\n * caret copies its own line: Cmd+C would put that sentence on the clipboard. The mousedown is\n * refused here, and arrow keys step over the row (`isSeparatorRow`). A drag that *crosses* a separator still\n * covers it, and always will while the label occupies offsets — giving these rows an offset\n * space of their own is the parallel coordinate system §C2 rules out.\n *\n * Every click count, not just the first: a second press would select a word of the label, a\n * third its line and a fourth the whole document.\n */\n private readonly claimSeparatorPress = (event: MouseEvent): boolean =>\n event.button === 0 && this.hunkRowAt(event) !== null\n\n /** The keyboard half of the same rule: arrow keys step over a separator. */\n private readonly isSeparatorRow = (bufferRow: number): boolean => {\n if (this.options.mode !== 'document' || !this.options.hasHunkRows()) return false\n return this.options.getRows()[bufferRow]?.type === 'hunk'\n }\n\n private readonly handleClick = (event: MouseEvent): void => {\n if (event.button !== 0) return\n\n const row = this.expandableRowAt(event)\n if (!row?.expandKey) return\n\n event.preventDefault()\n this.options.toggleRegion(row.expandKey)\n }\n\n private readonly handleMouseMove = (event: MouseEvent): void => {\n const cursor = this.expandableRowAt(event) ? 'pointer' : ''\n if (this.context.scrollElement.style.cursor === cursor) return\n\n this.context.scrollElement.style.cursor = cursor\n }\n\n private readonly handleMouseLeave = (): void => {\n if (!this.context.scrollElement.style.cursor) return\n\n this.context.scrollElement.style.cursor = ''\n }\n\n private expandableRowAt(event: MouseEvent): DiffRenderRow | null {\n // Avoid a point query on every mousemove when no separator can expand.\n if (!this.options.hasExpandableRows()) return null\n\n const row = this.hunkRowAt(event)\n return row?.expandable ? row : null\n }\n\n /**\n * The separator under the pointer, whether or not it can be expanded. A partial diff — a plain\n * patch with no file text behind it — has separators that say how much was skipped and cannot\n * open them, and those are still not somewhere a caret belongs.\n */\n private hunkRowAt(event: MouseEvent): DiffRenderRow | null {\n if (!this.options.hasHunkRows()) return null\n\n const hit = this.rowHitAt(event)\n const row = hit?.rows[hit.rowIndex]\n return row?.type === 'hunk' ? row : null\n }\n\n /** Only `document` mode has an answer: there a buffer row is an index into `getRows()`. */\n rowHitAt(event: MouseEvent): DiffRowHit | null {\n if (this.options.mode !== 'document') return null\n\n const hit = this.context.rowAtPoint(event.clientX, event.clientY)\n if (hit?.source !== 'document') return null\n const rowIndex = hit.bufferRow\n\n const rows = this.options.getRows()\n return rows[rowIndex] ? { side: this.options.side, rowIndex, rows } : null\n }\n}\n\nfunction injectedDiffRow(row: EditorGutterRowContext): DiffRenderRow | null {\n const metadata = row.metadata\n if (!metadata || typeof metadata !== 'object') return null\n return 'type' in metadata && 'text' in metadata ? (metadata as DiffRenderRow) : null\n}\n\nfunction snippetTokenSource(backend: DiffSyntaxBackend | undefined): EditorSnippetTokenSource {\n if (backend?.kind === 'highlighter') return { highlighter: backend.provider }\n return { syntax: backend?.provider }\n}\n"],"mappings":";;;;;;;;;;;AAkGA,IAAM,uCAAuB,IAAI,QAAuC;;AAGxE,SAAgB,eAAe,OAAsC;CAC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AAc,MAAM,QAAQ;EAE9C,KAAK,QAAQ,cAAc,MAAM,SAAS;CAC5C;CAEA,gBAAwB,OAAyC;EAE/D,IAAI,CAAC,KAAK,QAAQ,kBAAkB,GAAG,OAAO;EAE9C,MAAM,MAAM,KAAK,UAAU,KAAK;EAChC,OAAO,KAAK,aAAa,MAAM;CACjC;;;;;;CAOA,UAAkB,OAAyC;EACzD,IAAI,CAAC,KAAK,QAAQ,YAAY,GAAG,OAAO;EAExC,MAAM,MAAM,KAAK,SAAS,KAAK;EAC/B,MAAM,MAAM,KAAK,KAAK,IAAI;EAC1B,OAAO,KAAK,SAAS,SAAS,MAAM;CACtC;;CAGA,SAAS,OAAsC;EAC7C,IAAI,KAAK,QAAQ,SAAS,YAAY,OAAO;EAE7C,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,SAAS,MAAM,OAAO;EAChE,IAAI,KAAK,WAAW,YAAY,OAAO;EACvC,MAAM,WAAW,IAAI;EAErB,MAAM,OAAO,KAAK,QAAQ,QAAQ;EAClC,OAAO,KAAK,YAAY;GAAE,MAAM,KAAK,QAAQ;GAAM;GAAU;EAAK,IAAI;CACxE;AACF;AAEA,SAAS,gBAAgB,KAAmD;CAC1E,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,YAAY,OAAO,aAAa,UAAU,OAAO;CACtD,OAAO,UAAU,YAAY,UAAU,WAAY,WAA6B;AAClF;AAEA,SAAS,mBAAmB,SAAkE;CAC5F,IAAI,SAAS,SAAS,eAAe,OAAO,EAAE,aAAa,QAAQ,SAAS;CAC5E,OAAO,EAAE,QAAQ,SAAS,SAAS;AACrC"}
1
+ {"version":3,"file":"editorDiffPlugin.js","names":[],"sources":["../src/editorDiffPlugin.ts"],"sourcesContent":["import './style.css'\nimport { registerDiffColors } from './theme'\nimport type {\n EditorContributionChange,\n EditorDecorationContribution,\n EditorDecorationContributionContext,\n EditorDisposable,\n EditorGutterRowContext,\n EditorInjectedTextRow,\n EditorPlugin,\n EditorPluginContext,\n EditorSnippetTokenSource,\n EditorViewContribution,\n EditorViewContributionContext,\n EditorViewContributionUpdateKind,\n EditorViewSnapshot,\n} from '@singapore-editor/core/extensions'\nimport { EDITOR_SNIPPET_TOKENS_FEATURE } from '@singapore-editor/core/extensions'\nimport type { EditorToken } from '@singapore-editor/core/syntax'\nimport { createDiffGutterContribution } from './diffGutter'\nimport { diffInlineHighlightRanges, diffRowDecorations } from './diffRows'\nimport { DiffSyntaxController, type PreparedDiffSyntaxInput } from './diffSyntax'\nimport {\n diffGutterDigits,\n type DiffGutterDigits,\n type DiffGutterLayout,\n type DiffGutterSide,\n} from './gutters'\nimport { createLiveDiffProjection, type LiveDiffProjection } from './liveProjection'\nimport { createTextDiff } from './model'\nimport { createSplitProjection, createStackedProjection } from './projection'\nimport { createDiffRegionStore, type DiffRegionStore } from './regions'\nimport type { DiffFile, DiffRenderRow, DiffSyntaxBackend, DiffTextFile } from './types'\n\nexport type DiffPluginMode = 'document' | 'overlay'\n\nexport type DiffPluginOptions = {\n /**\n * §C1. `document` is the parity path; `overlay` is explicitly non-parity — see §C2.\n *\n * Required, with no default. The factory this replaced took no arguments and was always overlay,\n * so the natural migration — rename the call, keep the empty argument list — would otherwise\n * produce a plugin that mounts, registers everything, renders nothing and reports no error,\n * because `setBaseFile` and `setEnabled` both early-return outside overlay mode.\n */\n readonly mode: DiffPluginMode\n readonly side?: DiffGutterSide\n /**\n * Expansion state, shared when a host drives two sides of one diff. Omit it and the plugin keeps\n * a private store; pass one store to both split plugins and a toggle on either side moves both.\n * See regions.ts — this is what holds §C7 together.\n */\n readonly regions?: DiffRegionStore\n readonly syntaxBackend?: DiffSyntaxBackend\n readonly syntaxHighlight?: boolean\n}\n\nexport type DiffPlugin = EditorPlugin & {\n /**\n * `document` mode: the file to project. The host owns the editor's text — §C3. `prepared`\n * streams from `prepareDiffSyntax` for this file paint with the first rows, and a preparation\n * still running is awaited in place of a second parse. The plugin disposes each reader interest.\n */\n setFile(file: DiffFile | null, prepared?: PreparedDiffSyntaxInput): void\n /** Releases syntax interests while retaining this pane's rows and shared expansion. */\n releaseSyntax(): void\n getRows(): readonly DiffRenderRow[]\n /** Both sides in row order. Cached until the file or expansion state changes. */\n getStackedRows(): readonly DiffRenderRow[]\n /**\n * Projected syntax tokens for the current rows. The host passes them with the rows' text,\n * `setText(text, { tokens })`, or an expansion toggle repaints uncoloured (§C10).\n */\n isSyntaxReady(): boolean\n getTokens(): readonly EditorToken[]\n onDidChangeRows(listener: () => void): EditorDisposable\n onDidChangeTokens(listener: () => void): EditorDisposable\n /** §C5. Hosts must not mirror this. */\n getExpandedRegions(): ReadonlySet<string>\n toggleRegion(key: string): void\n\n /** `overlay` mode: the buffer the live editor text is diffed against. */\n setBaseFile(file: DiffTextFile | null): void\n setEnabled(enabled: boolean): void\n}\n\n/** The diff row under a pointer: which pane, that pane's rows, and the index into them. */\nexport type DiffRowHit = {\n readonly side: DiffGutterSide\n readonly rowIndex: number\n readonly rows: readonly DiffRenderRow[]\n}\n\n// How a pointer event finds the plugin that owns the pane under it, so a host never reads row\n// attributes or pane classes to work out where a press landed.\nconst viewsByScrollElement = new WeakMap<Element, DiffViewContribution>()\n\n/** `null` outside a `document`-mode diff pane, or over something that is not a diff row. */\nexport function diffRowAtEvent(event: MouseEvent): DiffRowHit | null {\n const target = event.target\n if (!(target instanceof Element)) return null\n\n const scrollElement = target.closest('[data-editor-diff-side]')\n if (!scrollElement) return null\n\n return viewsByScrollElement.get(scrollElement)?.rowHitAt(event) ?? null\n}\n\nconst EMPTY_PROJECTION: LiveDiffProjection = {\n injectedRows: [],\n rowDecorations: new Map(),\n rows: [],\n rowsByBufferRow: new Map(),\n}\nconst ROW_DECORATION_SOURCE = 'editor.diff'\nconst INLINE_HIGHLIGHT_STYLE = { backgroundColor: 'rgba(255, 255, 255, 0.18)' } as const\n\nlet nextDiffPluginId = 0\n\n/**\n * The one diff plugin (§C1), carrying two internal row-delivery modes.\n *\n * `document` — the editor holds a synthetic buffer of the projected rows and the plugin publishes\n * them for the host to push in. Everything works because the rows are real document lines.\n *\n * `overlay` — the editor holds the host's live, editable buffer and deletions arrive as injected\n * rows. Non-parity by construction; see §C2 and test/overlayModeLimits.test.ts before reaching for\n * it.\n */\nexport function createDiffPlugin(options: DiffPluginOptions): DiffPlugin {\n registerDiffColors()\n const runtime = new DiffPluginRuntime(options)\n\n return {\n name: `editor-diff-${options.mode}`,\n activate(context) {\n return runtime.activate(context)\n },\n setFile: (file, prepared) => runtime.setFile(file, prepared),\n releaseSyntax: () => runtime.releaseSyntax(),\n getRows: () => runtime.getRows(),\n getStackedRows: () => runtime.getStackedRows(),\n getTokens: () => runtime.getTokens(),\n isSyntaxReady: () => runtime.isSyntaxReady(),\n onDidChangeRows: (listener) => runtime.onDidChangeRows(listener),\n onDidChangeTokens: (listener) => runtime.onDidChangeTokens(listener),\n getExpandedRegions: () => runtime.getExpandedRegions(),\n toggleRegion: (key) => runtime.toggleRegion(key),\n setBaseFile: (file) => runtime.setBaseFile(file),\n setEnabled: (enabled) => runtime.setEnabled(enabled),\n }\n}\n\nclass DiffPluginRuntime {\n private readonly id = nextDiffPluginId++\n private readonly mode: DiffPluginMode\n private readonly side: DiffGutterSide\n private syntax: DiffSyntaxController\n private readonly rowListeners = new Set<() => void>()\n private readonly tokenListeners = new Set<() => void>()\n\n private readonly regions: DiffRegionStore\n private file: DiffFile | null = null\n private rows: readonly DiffRenderRow[] = []\n private stackedRows: readonly DiffRenderRow[] | null = null\n private digits: DiffGutterDigits = { old: 0, new: 0 }\n private hunkRows = false\n private expandableRows = false\n\n private baseFile: DiffTextFile | null = null\n private enabled: boolean\n private liveProjection: LiveDiffProjection = EMPTY_PROJECTION\n\n private decoration: DiffDecorationContribution | null = null\n private view: DiffViewContribution | null = null\n private injectedRowsListener: (() => void) | null = null\n private lastGutterLayout: DiffGutterLayout | null = null\n private readonly regionSubscription: EditorDisposable\n\n constructor(private readonly options: DiffPluginOptions) {\n this.mode = options.mode\n this.side = options.side ?? 'stacked'\n this.regions = options.regions ?? createDiffRegionStore()\n // A shared store means the sibling side's toggle lands here too.\n //\n // Held for the plugin's whole life, and never released. Every narrower lifetime is wrong:\n //\n // - torn down with the ACTIVATION, next to the syntax controller, which is the obvious place:\n // the first deactivation is then terminal. The plugin is re-activated against a fresh editor,\n // renders correctly, and is silently deaf to every expansion toggle after that. React\n // StrictMode makes mount -> unmount -> mount the normal development path, so a host that gets\n // this wrong sees gutter clicks do nothing at all.\n // - created only on activation: a plugin driven headlessly as a projection source, with no\n // editor behind it, never sees its own `toggleRegion`.\n // - released from `EditorPlugin.dispose`: that fires when an editor tears down, and a React\n // host reuses the same plugin instance across the next editor — so this is the first case\n // again with an extra step.\n //\n // Nothing leaks by holding it. The listener lives in the store, the store is the host's, and a\n // host drops both together; a plugin the host builds and never mounts — StrictMode\n // double-invokes the `useMemo` that builds one — is collected with it.\n this.regionSubscription = this.regions.onDidChange(() => this.handleRegionsChanged())\n // Overlay mode is switched on by the host once it has a base file; document mode is live from\n // the moment it has one.\n this.enabled = this.mode === 'document'\n this.syntax = this.createSyntaxController()\n }\n\n activate(context: EditorPluginContext): EditorDisposable[] {\n // A controller disposed by a previous deactivation is dead for good — its scheduler is\n // terminal, so `schedule()` returns an inactive handle forever and the diff would render\n // permanently uncoloured after a remove-then-re-add. The core supports that cycle\n // (`Editor.setPlugins`), so the controller's lifetime is the activation's, not the plugin's.\n //\n // Only a *replacement* controller needs the file pushed into it. Doing it unconditionally\n // re-parses a file the surviving controller is already holding — and when the host sets the\n // file before constructing the editor, which is the natural order, that means cancelling an\n // in-flight parse to start an identical one. Under shiki that is two worker owners for one\n // file.\n if (this.syntax.isDisposed()) {\n this.syntax = this.createSyntaxController()\n if (this.file) this.syntax.setFile(this.file, this.rows)\n }\n\n const disposables: EditorDisposable[] = [\n context.registerGutterContribution(\n createDiffGutterContribution({\n side: this.side,\n tint: this.mode === 'document' ? 'row' : 'cell',\n getDigits: () => this.gutterDigits(),\n resolveRow: (row) => this.resolveGutterRow(row),\n isEnabled: () => this.enabled,\n onLayout: (layout) => this.publishGutterLayout(layout),\n }),\n ),\n context.registerDecorationContribution({\n createContribution: (featureContext) => this.createDecorationContribution(featureContext),\n }),\n context.registerViewContribution({\n createContribution: (viewContext) => this.createViewContribution(viewContext),\n }),\n { dispose: () => this.syntax.dispose() },\n ]\n\n if (this.mode === 'overlay') {\n disposables.push(\n context.registerInjectedTextRowProvider({\n getInjectedTextRows: () => this.injectedRows(),\n onDidChangeInjectedTextRows: (listener) => this.setInjectedRowsListener(listener),\n }),\n )\n }\n\n return disposables\n }\n\n // ---------------------------------------------------------------- document mode (§C3, §C5)\n\n setFile(file: DiffFile | null, prepared: PreparedDiffSyntaxInput = []): void {\n if (this.mode !== 'document') {\n void Promise.resolve(prepared).then(\n (sources) => {\n for (const source of sources) source.dispose()\n },\n () => undefined,\n )\n return\n }\n\n this.file = file\n // The store decides whether this counts as the same diff, and drops expansion if not. Both\n // sides of a split share it, so both are told once.\n this.regions.setFile(file)\n this.rebuildRows()\n this.syntax.setFile(file, this.rows, prepared)\n this.notifyRows()\n }\n\n releaseSyntax(): void {\n this.syntax.release()\n }\n\n getRows(): readonly DiffRenderRow[] {\n if (this.mode === 'overlay') return this.liveProjection.rows\n return this.rows\n }\n\n getStackedRows(): readonly DiffRenderRow[] {\n if (this.mode === 'overlay') return this.liveProjection.rows\n if (this.side === 'stacked') return this.rows\n this.stackedRows ??= projectRows(this.file, 'stacked', this.regions.getExpandedRegions())\n return this.stackedRows\n }\n\n isSyntaxReady(): boolean {\n return this.syntax.isReady()\n }\n\n getTokens(): readonly EditorToken[] {\n return this.syntax.getTokens()\n }\n\n getExpandedRegions(): ReadonlySet<string> {\n return this.regions.getExpandedRegions()\n }\n\n toggleRegion(key: string): void {\n if (this.mode !== 'document') return\n if (!this.file) return\n\n // The store fans the change back to every plugin reading it, this one included, so the rebuild\n // happens in `handleRegionsChanged` rather than here.\n this.regions.toggleRegion(key)\n }\n\n private handleRegionsChanged(): void {\n if (this.mode !== 'document') return\n if (!this.file) return\n\n this.rebuildRows()\n // Same file, different rows: the parsed token streams still apply, so this re-projects\n // synchronously and `getTokens()` is correct before the host's `setText` returns (§C10).\n this.syntax.setRows(this.rows)\n this.notifyRows()\n }\n\n onDidChangeRows(listener: () => void): EditorDisposable {\n this.rowListeners.add(listener)\n return { dispose: () => this.rowListeners.delete(listener) }\n }\n\n onDidChangeTokens(listener: () => void): EditorDisposable {\n this.tokenListeners.add(listener)\n return { dispose: () => this.tokenListeners.delete(listener) }\n }\n\n private rebuildRows(): void {\n this.stackedRows = null\n this.rows = projectRows(this.file, this.side, this.regions.getExpandedRegions())\n // Both derived once here rather than per gutter-width recompute and per mousemove.\n this.digits = diffGutterDigits(this.rows)\n this.hunkRows = this.rows.some((row) => row.type === 'hunk')\n this.expandableRows = this.rows.some((row) => row.type === 'hunk' && row.expandable === true)\n }\n\n private notifyRows(): void {\n for (const listener of this.rowListeners) listener()\n this.decoration?.refresh()\n this.view?.refreshRows()\n }\n\n private notifyTokens(): void {\n for (const listener of this.tokenListeners) listener()\n }\n\n // ---------------------------------------------------------------- overlay mode\n\n setBaseFile(file: DiffTextFile | null): void {\n if (this.mode !== 'overlay') return\n\n this.baseFile = file\n this.decoration?.refresh()\n }\n\n setEnabled(enabled: boolean): void {\n if (this.mode !== 'overlay') return\n\n this.enabled = enabled\n this.decoration?.refresh()\n }\n\n private injectedRows(): readonly EditorInjectedTextRow[] {\n if (!this.enabled) return []\n return this.liveProjection.injectedRows\n }\n\n private setInjectedRowsListener(listener: () => void): EditorDisposable {\n this.injectedRowsListener = listener\n return {\n dispose: () => {\n if (this.injectedRowsListener === listener) this.injectedRowsListener = null\n },\n }\n }\n\n private gutterDigits(): DiffGutterDigits {\n if (this.mode === 'overlay') return diffGutterDigits(this.liveProjection.rows)\n return this.digits\n }\n\n /**\n * Which diff row a rendered gutter row is showing. The two modes cannot share an answer.\n *\n * `document` — §C4 holds, so the projection index is the buffer row and a positional lookup is\n * correct.\n *\n * `overlay` — the projection array interleaves injected deletion rows, so position and buffer\n * row diverge from the first deletion onwards; the mapping the projection publishes for exactly\n * this purpose is `rowsByBufferRow`, keyed `newLineNumber - 1`. An injected row is not in that\n * map at all and carries its own row as metadata instead.\n */\n private resolveGutterRow(row: EditorGutterRowContext): DiffRenderRow | null {\n if (this.mode === 'overlay') {\n if (row.source === 'injected') return injectedDiffRow(row)\n if (row.source !== 'document') return null\n return this.liveProjection.rowsByBufferRow.get(row.bufferRow) ?? null\n }\n\n if (row.source !== 'document') return null\n return this.rows[row.bufferRow] ?? null\n }\n\n // ---------------------------------------------------------------- contributions\n\n private createDecorationContribution(\n context: EditorDecorationContributionContext,\n ): EditorDecorationContribution {\n const contribution = new DiffDecorationContribution(context, {\n mode: this.mode,\n getRows: () => this.rows,\n buildLiveProjection: () => this.buildLiveProjection(context),\n setLiveProjection: (projection) => {\n this.liveProjection = projection\n },\n notifyInjectedRowsChanged: () => this.injectedRowsListener?.(),\n })\n this.decoration = contribution\n contribution.refresh()\n return {\n handleEditorChange: (change) => contribution.handleEditorChange(change),\n dispose: () => {\n if (this.decoration === contribution) this.decoration = null\n contribution.dispose()\n },\n }\n }\n\n private buildLiveProjection(context: EditorDecorationContributionContext): LiveDiffProjection {\n if (!this.enabled) return EMPTY_PROJECTION\n if (!this.baseFile) return EMPTY_PROJECTION\n if (!context.hasDocument()) return EMPTY_PROJECTION\n\n const file = createTextDiff({\n oldFile: this.baseFile,\n newFile: {\n path: this.baseFile.path,\n text: liveDiffDocumentText(context),\n languageId: this.baseFile.languageId,\n },\n })\n return createLiveDiffProjection(file)\n }\n\n private createViewContribution(\n context: EditorViewContributionContext,\n ): EditorViewContribution | null {\n const contribution = new DiffViewContribution(context, {\n highlightName: `editor-diff-${this.id}-${this.side}-inline`,\n mode: this.mode,\n side: this.side,\n getRows: () => this.getRows(),\n hasHunkRows: () => this.hunkRows,\n hasExpandableRows: () => this.expandableRows,\n toggleRegion: (key) => this.toggleRegion(key),\n detach: (disposed) => {\n lentSyntax?.dispose()\n if (this.view === disposed) this.view = null\n },\n })\n const lentSyntax = context\n .getFeature(EDITOR_SNIPPET_TOKENS_FEATURE)\n ?.addSource(snippetTokenSource(this.options.syntaxBackend))\n this.view = contribution\n if (this.lastGutterLayout) contribution.applyGutterLayout(this.lastGutterLayout)\n return contribution\n }\n\n private publishGutterLayout(layout: DiffGutterLayout): void {\n // Retained, never consumed. `width()` can run before a view contribution exists, and a\n // contribution can be torn down and rebuilt later on a fresh scroll element carrying none of\n // these custom properties. The gutter memoizes on the layout, so it will not republish an\n // unchanged one — leaving a replacement contribution with no other way to learn the geometry,\n // and `.editor-diff-gutter` falling back to `1fr 1fr 12px`, which is the drift the whole\n // custom-property dance exists to avoid.\n this.lastGutterLayout = layout\n this.view?.applyGutterLayout(layout)\n }\n\n private createSyntaxController(): DiffSyntaxController {\n return new DiffSyntaxController({\n side: this.side,\n backend: this.options.syntaxBackend,\n enabled: this.options.syntaxHighlight !== false,\n onDidChangeTokens: () => this.notifyTokens(),\n })\n }\n}\n\n// A live diff compares whole documents, and the diff library takes strings: an explicit extraction.\nfunction liveDiffDocumentText(context: EditorDecorationContributionContext): string {\n return context.materializeFullText()\n}\n\nfunction projectRows(\n file: DiffFile | null,\n side: DiffGutterSide,\n expandedRegions: ReadonlySet<string>,\n): readonly DiffRenderRow[] {\n if (!file) return []\n if (side === 'stacked') return createStackedProjection(file, { expandedRegions }).rows\n\n const projection = createSplitProjection(file, { expandedRegions })\n return side === 'old' ? projection.leftRows : projection.rightRows\n}\n\ntype DiffDecorationOptions = {\n readonly mode: DiffPluginMode\n readonly getRows: () => readonly DiffRenderRow[]\n readonly buildLiveProjection: () => LiveDiffProjection\n readonly setLiveProjection: (projection: LiveDiffProjection) => void\n readonly notifyInjectedRowsChanged: () => void\n}\n\nclass DiffDecorationContribution {\n private lastTextSnapshot: unknown = undefined\n\n constructor(\n private readonly context: EditorDecorationContributionContext,\n private readonly options: DiffDecorationOptions,\n ) {}\n\n /**\n * The editor's notification, which is not the same thing as \"the text changed\".\n *\n * Rebuilding an overlay projection materializes the whole document and runs `structuredPatch`\n * over it, synchronously. `handleEditorChange` also fires for selection-only changes —\n * `EditorContributionChange.kind` is one of edit/selection/undo/redo/none — and a caret move cannot\n * alter the diff, so paying for one is pure waste on the typing path. Text-snapshot identity is\n * the second guard, for the notification paths that carry no change object at all.\n *\n * Plugin-state changes (`setBaseFile`, `setEnabled`) call `refresh()` directly and are never\n * skipped: the text is the same but the diff it produces is not.\n */\n handleEditorChange(change: EditorContributionChange | null): void {\n if (this.options.mode === 'overlay') {\n if (change?.kind === 'selection') return\n\n const snapshot = this.context.getTextSnapshot()\n if (snapshot !== null && snapshot === this.lastTextSnapshot) return\n }\n\n this.refresh()\n }\n\n refresh(): void {\n this.lastTextSnapshot = this.context.getTextSnapshot()\n if (this.options.mode === 'document') {\n this.context.setRowDecorations(\n ROW_DECORATION_SOURCE,\n diffRowDecorations(this.options.getRows()),\n )\n return\n }\n\n this.applyLiveProjection(this.options.buildLiveProjection())\n }\n\n dispose(): void {\n if (this.options.mode === 'overlay') this.applyLiveProjection(EMPTY_PROJECTION)\n this.context.clearRowDecorations(ROW_DECORATION_SOURCE)\n }\n\n /**\n * These three steps are ordered, and the order is load-bearing.\n *\n * Announcing the injected-row change first would rebuild the row set before the cells are\n * repainted, and a row that the rebuild unmounts keeps whatever its cell last rendered — a\n * disabled live diff would leave a stale `4+` behind on a detached cell. Repainting first, while\n * that row is still mounted, is what clears it.\n *\n * The stored projection has to be current before the repaint, because the gutter reads its rows\n * from it.\n */\n private applyLiveProjection(projection: LiveDiffProjection): void {\n this.options.setLiveProjection(projection)\n this.context.setRowDecorations(ROW_DECORATION_SOURCE, projection.rowDecorations)\n this.options.notifyInjectedRowsChanged()\n }\n}\n\ntype DiffViewOptions = {\n readonly highlightName: string\n readonly mode: DiffPluginMode\n readonly side: DiffGutterSide\n readonly getRows: () => readonly DiffRenderRow[]\n readonly hasHunkRows: () => boolean\n readonly hasExpandableRows: () => boolean\n readonly toggleRegion: (key: string) => void\n readonly detach: (contribution: DiffViewContribution) => void\n}\n\n/** Pointer handling and inline word-diff highlights. */\nclass DiffViewContribution implements EditorViewContribution {\n readonly snapshotKey = 'diff-inline-v1'\n private readonly pressParticipant: EditorDisposable\n private readonly separatorRows: EditorDisposable\n private snapshot: EditorViewSnapshot | null = null\n private lastHighlightRows: readonly DiffRenderRow[] | null = null\n private lastHighlightTextVersion = -1\n\n constructor(\n private readonly context: EditorViewContributionContext,\n private readonly options: DiffViewOptions,\n ) {\n this.context.scrollElement.dataset.editorDiffSide = options.side\n viewsByScrollElement.set(this.context.scrollElement, this)\n this.pressParticipant = this.context.registerPressParticipant(this.claimSeparatorPress)\n this.separatorRows = this.context.registerNonCaretRows(this.isSeparatorRow)\n this.context.scrollElement.addEventListener('click', this.handleClick)\n this.context.scrollElement.addEventListener('mousemove', this.handleMouseMove)\n this.context.scrollElement.addEventListener('mouseleave', this.handleMouseLeave)\n }\n\n /**\n * The snapshot is kept for every update kind — the pointer hit-test reads it — but the two\n * derived jobs below are not per-frame work.\n *\n * `update` is called for `'viewport'` too, which `Editor.handleViewportChange` fires on every\n * scroll frame, and the highlights can only change when the rows or the text do.\n */\n update(snapshot: EditorViewSnapshot, kind: EditorViewContributionUpdateKind): void {\n this.snapshot = snapshot\n if (this.options.mode !== 'document') return\n if (kind === 'viewport' || kind === 'selection') return\n\n this.applyInlineHighlights()\n }\n\n captureVisiblePaint(snapshot: EditorViewSnapshot) {\n const viewport = this.context.scrollElement.getBoundingClientRect()\n const rows = this.options.getRows()\n const ranges = snapshot.visibleRows.flatMap((visible) => {\n const row = rows[visible.bufferRow]\n if (!row) return []\n const start = snapshot.lineStartsView.at(visible.bufferRow) ?? visible.startOffset\n return diffInlineHighlightRanges([row]).map((range) => ({\n start: range.start + start,\n end: range.end + start,\n }))\n })\n const rectangles = []\n for (const range of ranges) {\n const rect = this.context.getRangeClientRect(range.start, range.end)\n if (!rect || rect.width <= 0 || rect.height <= 0) continue\n rectangles.push({\n left: rect.left - viewport.left + snapshot.viewport.scrollLeft,\n top: rect.top - viewport.top + snapshot.viewport.scrollTop,\n width: rect.width,\n height: rect.height,\n backgroundColor: INLINE_HIGHLIGHT_STYLE.backgroundColor,\n })\n }\n return { id: `diff-inline-${this.options.side}`, status: 'ready' as const, rectangles }\n }\n\n refreshRows(): void {\n this.lastHighlightRows = null\n this.applyInlineHighlights()\n }\n\n applyGutterLayout(layout: DiffGutterLayout): void {\n // §3.3 trap 1: the canvas derived lane geometry arithmetically, so a DOM gutter has to hand CSS\n // the same numbers rather than approximate them with `1fr 1fr 12px`.\n const style = this.context.scrollElement.style\n const columns = layout.lanes.map((lane) => `${lane.width}px`).join(' ')\n style.setProperty('--editor-diff-gutter-columns', columns)\n style.setProperty('--editor-diff-gutter-total-width', `${layout.width}px`)\n }\n\n dispose(): void {\n this.pressParticipant.dispose()\n this.separatorRows.dispose()\n this.context.scrollElement.removeEventListener('click', this.handleClick)\n this.context.scrollElement.removeEventListener('mousemove', this.handleMouseMove)\n this.context.scrollElement.removeEventListener('mouseleave', this.handleMouseLeave)\n this.context.scrollElement.style.cursor = ''\n // A replacement view on the same element may already have registered itself.\n if (viewsByScrollElement.get(this.context.scrollElement) === this) {\n viewsByScrollElement.delete(this.context.scrollElement)\n }\n this.context.clearRangeHighlight(this.options.highlightName)\n // Or the runtime keeps writing highlights and gutter geometry through a torn-down context,\n // and holds its scroll element alive for the plugin's lifetime.\n this.options.detach(this)\n }\n\n // A highlight failure must not dispose the contribution and disable gutter expansion.\n private applyInlineHighlights(): void {\n const rows = this.options.getRows()\n const textVersion = this.snapshot?.textVersion ?? -1\n // Rows alone cannot key this: the view clamps ranges to the text it holds when they are set,\n // and the host pushes the new text only after the rows notification that first lands here.\n if (rows === this.lastHighlightRows && textVersion === this.lastHighlightTextVersion) return\n\n this.lastHighlightRows = rows\n this.lastHighlightTextVersion = textVersion\n try {\n this.context.setRangeHighlight(\n this.options.highlightName,\n diffInlineHighlightRanges(rows),\n INLINE_HIGHLIGHT_STYLE,\n )\n } catch (error) {\n this.context.log({\n action: 'editor.diff.inline_highlight_failed',\n level: 'warn',\n error: { message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n\n /**\n * Keeps the caret off a separator row, expandable or not.\n *\n * A separator is chrome, not content — but its label is real buffer text, because the host's\n * document is `joinRenderLines(rows)` and there is nowhere else for the label to live. So the\n * editor will happily rest a caret in the middle of `Show 12 unmodified lines`, and a collapsed\n * caret copies its own line: Cmd+C would put that sentence on the clipboard. The mousedown is\n * refused here, and arrow keys step over the row (`isSeparatorRow`). A drag that *crosses* a separator still\n * covers it, and always will while the label occupies offsets — giving these rows an offset\n * space of their own is the parallel coordinate system §C2 rules out.\n *\n * Every click count, not just the first: a second press would select a word of the label, a\n * third its line and a fourth the whole document.\n */\n private readonly claimSeparatorPress = (event: MouseEvent | TouchEvent): boolean =>\n (!('button' in event) || event.button === 0) && this.hunkRowAt(event) !== null\n\n /** The keyboard half of the same rule: arrow keys step over a separator. */\n private readonly isSeparatorRow = (bufferRow: number): boolean => {\n if (this.options.mode !== 'document' || !this.options.hasHunkRows()) return false\n return this.options.getRows()[bufferRow]?.type === 'hunk'\n }\n\n private readonly handleClick = (event: MouseEvent): void => {\n if (event.button !== 0) return\n\n const row = this.expandableRowAt(event)\n if (!row?.expandKey) return\n\n event.preventDefault()\n this.options.toggleRegion(row.expandKey)\n }\n\n private readonly handleMouseMove = (event: MouseEvent): void => {\n const cursor = this.expandableRowAt(event) ? 'pointer' : ''\n if (this.context.scrollElement.style.cursor === cursor) return\n\n this.context.scrollElement.style.cursor = cursor\n }\n\n private readonly handleMouseLeave = (): void => {\n if (!this.context.scrollElement.style.cursor) return\n\n this.context.scrollElement.style.cursor = ''\n }\n\n private expandableRowAt(event: MouseEvent): DiffRenderRow | null {\n // Avoid a point query on every mousemove when no separator can expand.\n if (!this.options.hasExpandableRows()) return null\n\n const row = this.hunkRowAt(event)\n return row?.expandable ? row : null\n }\n\n /**\n * The separator under the pointer, whether or not it can be expanded. A partial diff — a plain\n * patch with no file text behind it — has separators that say how much was skipped and cannot\n * open them, and those are still not somewhere a caret belongs.\n */\n private hunkRowAt(event: MouseEvent | TouchEvent): DiffRenderRow | null {\n if (!this.options.hasHunkRows()) return null\n\n const hit = this.rowHitAt(event)\n const row = hit?.rows[hit.rowIndex]\n return row?.type === 'hunk' ? row : null\n }\n\n /** Only `document` mode has an answer: there a buffer row is an index into `getRows()`. */\n rowHitAt(event: MouseEvent | TouchEvent): DiffRowHit | null {\n if (this.options.mode !== 'document') return null\n\n const point = 'touches' in event ? event.touches[0] : event\n if (!point) return null\n const hit = this.context.rowAtPoint(point.clientX, point.clientY)\n if (hit?.source !== 'document') return null\n const rowIndex = hit.bufferRow\n\n const rows = this.options.getRows()\n return rows[rowIndex] ? { side: this.options.side, rowIndex, rows } : null\n }\n}\n\nfunction injectedDiffRow(row: EditorGutterRowContext): DiffRenderRow | null {\n const metadata = row.metadata\n if (!metadata || typeof metadata !== 'object') return null\n return 'type' in metadata && 'text' in metadata ? (metadata as DiffRenderRow) : null\n}\n\nfunction snippetTokenSource(backend: DiffSyntaxBackend | undefined): EditorSnippetTokenSource {\n if (backend?.kind === 'highlighter') return { highlighter: backend.provider }\n return { syntax: backend?.provider }\n}\n"],"mappings":";;;;;;;;;;;;AA+FA,IAAM,uCAAuB,IAAI,QAAuC;;AAGxE,SAAgB,eAAe,OAAsC;CACnE,MAAM,SAAS,MAAM;CACrB,IAAI,EAAE,kBAAkB,UAAU,OAAO;CAEzC,MAAM,gBAAgB,OAAO,QAAQ,yBAAyB;CAC9D,IAAI,CAAC,eAAe,OAAO;CAE3B,OAAO,qBAAqB,IAAI,aAAa,CAAC,EAAE,SAAS,KAAK,KAAK;AACrE;AAEA,IAAM,mBAAuC;CAC3C,cAAc,CAAC;CACf,gCAAgB,IAAI,IAAI;CACxB,MAAM,CAAC;CACP,iCAAiB,IAAI,IAAI;AAC3B;AACA,IAAM,wBAAwB;AAC9B,IAAM,y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K,KAAK,IAAI;EAC1B,OAAO,KAAK,SAAS,SAAS,MAAM;CACtC;;CAGA,SAAS,OAAmD;EAC1D,IAAI,KAAK,QAAQ,SAAS,YAAY,OAAO;EAE7C,MAAM,QAAQ,aAAa,QAAQ,MAAM,QAAQ,KAAK;EACtD,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,SAAS,MAAM,OAAO;EAChE,IAAI,KAAK,WAAW,YAAY,OAAO;EACvC,MAAM,WAAW,IAAI;EAErB,MAAM,OAAO,KAAK,QAAQ,QAAQ;EAClC,OAAO,KAAK,YAAY;GAAE,MAAM,KAAK,QAAQ;GAAM;GAAU;EAAK,IAAI;CACxE;AACF;AAEA,SAAS,gBAAgB,KAAmD;CAC1E,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,YAAY,OAAO,aAAa,UAAU,OAAO;CACtD,OAAO,UAAU,YAAY,UAAU,WAAY,WAA6B;AAClF;AAEA,SAAS,mBAAmB,SAAkE;CAC5F,IAAI,SAAS,SAAS,eAAe,OAAO,EAAE,aAAa,QAAQ,SAAS;CAC5E,OAAO,EAAE,QAAQ,SAAS,SAAS;AACrC"}
@@ -1,11 +1,11 @@
1
1
  import type { EditorOptions } from '@singapore-editor/core/editor';
2
2
  import { type EditorKeymapOptions } from '@singapore-editor/core/keymap';
3
3
  import type { EditorCursorLineHighlightOptions } from '@singapore-editor/core/rendering';
4
- export type DiffEditorOptions = Required<Pick<EditorOptions, 'detectIndentation' | 'documentMode' | 'editability' | 'folding'>> & {
4
+ export type DiffEditorOptions = Required<Pick<EditorOptions, 'detectIndentation' | 'documentMode' | 'editability' | 'folding' | 'keymapContext'>> & {
5
5
  readonly cursorLineHighlight: Required<EditorCursorLineHighlightOptions>;
6
6
  readonly keymap: DiffKeymap;
7
7
  };
8
- type DiffKeymap = Readonly<Required<Pick<EditorKeymapOptions, 'defaultBindings' | 'layers'>>>;
8
+ type DiffKeymap = Readonly<Required<Pick<EditorKeymapOptions, 'packs' | 'bindings'>>>;
9
9
  /**
10
10
  * The options an editor holding a `mode: 'document'` diff needs; an overlay diff keeps its host's
11
11
  * editable options. Spread them and add the host's own, such as plugins, typography and theme.
@@ -1 +1 @@
1
- {"version":3,"file":"editorOptions.d.ts","sourceRoot":"","sources":["../src/editorOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAClE,OAAO,EAGL,KAAK,mBAAmB,EACzB,MAAM,+BAA+B,CAAA;AACtC,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAA;AAGxF,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CACtC,IAAI,CAAC,aAAa,EAAE,mBAAmB,GAAG,cAAc,GAAG,aAAa,GAAG,SAAS,CAAC,CACtF,GAAG;IACF,QAAQ,CAAC,mBAAmB,EAAE,QAAQ,CAAC,gCAAgC,CAAC,CAAA;IACxE,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;CAC5B,CAAA;AAED,KAAK,UAAU,GAAG,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,mBAAmB,EAAE,iBAAiB,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;AAY7F;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,iBAAiB,CAc3D"}
1
+ {"version":3,"file":"editorOptions.d.ts","sourceRoot":"","sources":["../src/editorOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAClE,OAAO,EAAoB,KAAK,mBAAmB,EAAE,MAAM,+BAA+B,CAAA;AAC1F,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAA;AAGxF,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CACtC,IAAI,CACF,aAAa,EACb,mBAAmB,GAAG,cAAc,GAAG,aAAa,GAAG,SAAS,GAAG,eAAe,CACnF,CACF,GAAG;IACF,QAAQ,CAAC,mBAAmB,EAAE,QAAQ,CAAC,gCAAgC,CAAC,CAAA;IACxE,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;CAC5B,CAAA;AAED,KAAK,UAAU,GAAG,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,mBAAmB,EAAE,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,CAAA;AAKrF;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,iBAAiB,CAe3D"}
@@ -1,10 +1,5 @@
1
- import { editorKeymapLayersForCommandPacks } from "@singapore-editor/core/keymap";
2
- //#region src/editorOptions.ts
3
- var DIFF_COMMAND_PACKS = [
4
- "navigation",
5
- "selection",
6
- "find"
7
- ];
1
+ import { readonlyDiffPack } from "@singapore-editor/core/keymap";
2
+ // src/editorOptions.ts
8
3
  var diffKeymap;
9
4
  /**
10
5
  * The options an editor holding a `mode: 'document'` diff needs; an overlay diff keeps its host's
@@ -21,13 +16,13 @@ function createDiffEditorOptions() {
21
16
  documentMode: "static",
22
17
  editability: "readonly",
23
18
  folding: false,
19
+ keymapContext: { mode: "diff" },
24
20
  keymap: diffKeymap ??= Object.freeze({
25
- defaultBindings: false,
26
- layers: editorKeymapLayersForCommandPacks(DIFF_COMMAND_PACKS)
21
+ packs: [readonlyDiffPack],
22
+ bindings: []
27
23
  })
28
24
  };
29
25
  }
30
- //#endregion
31
26
  export { createDiffEditorOptions };
32
27
 
33
28
  //# sourceMappingURL=editorOptions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"editorOptions.js","names":[],"sources":["../src/editorOptions.ts"],"sourcesContent":["import type { EditorOptions } from '@singapore-editor/core/editor'\nimport {\n editorKeymapLayersForCommandPacks,\n type EditorCommandPack,\n type EditorKeymapOptions,\n} from '@singapore-editor/core/keymap'\nimport type { EditorCursorLineHighlightOptions } from '@singapore-editor/core/rendering'\n\n// Every nested field is present, so a host extends `keymap.layers` or one highlight part in place.\nexport type DiffEditorOptions = Required<\n Pick<EditorOptions, 'detectIndentation' | 'documentMode' | 'editability' | 'folding'>\n> & {\n readonly cursorLineHighlight: Required<EditorCursorLineHighlightOptions>\n readonly keymap: DiffKeymap\n}\n\ntype DiffKeymap = Readonly<Required<Pick<EditorKeymapOptions, 'defaultBindings' | 'layers'>>>\n\n// Read-only already refuses every editing key, and `folding: false` leaves fold keys nothing to do.\nconst DIFF_COMMAND_PACKS = [\n 'navigation',\n 'selection',\n 'find',\n] as const satisfies readonly EditorCommandPack[]\n\n// One object for every call: a React host compares `keymap` by identity and re-applies a new one.\nlet diffKeymap: DiffKeymap | undefined\n\n/**\n * The options an editor holding a `mode: 'document'` diff needs; an overlay diff keeps its host's\n * editable options. Spread them and add the host's own, such as plugins, typography and theme.\n */\nexport function createDiffEditorOptions(): DiffEditorOptions {\n return {\n cursorLineHighlight: { gutterBackground: false, gutterNumber: false, rowBackground: false },\n // The buffer interleaves both sides, so a guess would change the width per file and per toggle.\n detectIndentation: false,\n documentMode: 'static',\n editability: 'readonly',\n // A fold would hide a deletion and its addition, and misalign a split.\n folding: false,\n keymap: (diffKeymap ??= Object.freeze({\n defaultBindings: false,\n layers: editorKeymapLayersForCommandPacks(DIFF_COMMAND_PACKS),\n })),\n }\n}\n"],"mappings":";;AAmBA,IAAM,qBAAqB;CACzB;CACA;CACA;AACF;AAGA,IAAI;;;;;AAMJ,SAAgB,0BAA6C;CAC3D,OAAO;EACL,qBAAqB;GAAE,kBAAkB;GAAO,cAAc;GAAO,eAAe;EAAM;EAE1F,mBAAmB;EACnB,cAAc;EACd,aAAa;EAEb,SAAS;EACT,QAAS,eAAe,OAAO,OAAO;GACpC,iBAAiB;GACjB,QAAQ,kCAAkC,kBAAkB;EAC9D,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"editorOptions.js","names":[],"sources":["../src/editorOptions.ts"],"sourcesContent":["import type { EditorOptions } from '@singapore-editor/core/editor'\nimport { readonlyDiffPack, type EditorKeymapOptions } from '@singapore-editor/core/keymap'\nimport type { EditorCursorLineHighlightOptions } from '@singapore-editor/core/rendering'\n\n// Every nested field is present, so a host extends `keymap.packs` or one highlight part in place.\nexport type DiffEditorOptions = Required<\n Pick<\n EditorOptions,\n 'detectIndentation' | 'documentMode' | 'editability' | 'folding' | 'keymapContext'\n >\n> & {\n readonly cursorLineHighlight: Required<EditorCursorLineHighlightOptions>\n readonly keymap: DiffKeymap\n}\n\ntype DiffKeymap = Readonly<Required<Pick<EditorKeymapOptions, 'packs' | 'bindings'>>>\n\n// One object for every call: a React host compares `keymap` by identity and re-applies a new one.\nlet diffKeymap: DiffKeymap | undefined\n\n/**\n * The options an editor holding a `mode: 'document'` diff needs; an overlay diff keeps its host's\n * editable options. Spread them and add the host's own, such as plugins, typography and theme.\n */\nexport function createDiffEditorOptions(): DiffEditorOptions {\n return {\n cursorLineHighlight: { gutterBackground: false, gutterNumber: false, rowBackground: false },\n // The buffer interleaves both sides, so a guess would change the width per file and per toggle.\n detectIndentation: false,\n documentMode: 'static',\n editability: 'readonly',\n // A fold would hide a deletion and its addition, and misalign a split.\n folding: false,\n keymapContext: { mode: 'diff' },\n keymap: (diffKeymap ??= Object.freeze({\n packs: [readonlyDiffPack],\n bindings: [],\n })),\n }\n}\n"],"mappings":";;AAkBA,IAAI;;;;;AAMJ,SAAgB,0BAA6C;CAC3D,OAAO;EACL,qBAAqB;GAAE,kBAAkB;GAAO,cAAc;GAAO,eAAe;EAAM;EAE1F,mBAAmB;EACnB,cAAc;EACd,aAAa;EAEb,SAAS;EACT,eAAe,EAAE,MAAM,OAAO;EAC9B,QAAS,eAAe,OAAO,OAAO;GACpC,OAAO,CAAC,gBAAgB;GACxB,UAAU,CAAC;EACb,CAAC;CACH;AACF"}
package/dist/gutters.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/gutters.ts
1
+ // src/gutters.ts
2
2
  var MIN_LINE_NUMBER_DIGITS = 3;
3
3
  var GUTTER_NUMBER_RESERVED_WIDTH = 8;
4
4
  var GUTTER_INDICATOR_WIDTH = 12;
@@ -116,7 +116,6 @@ function formatLineNumber(value) {
116
116
  if (value === void 0) return "";
117
117
  return String(value);
118
118
  }
119
- //#endregion
120
119
  export { diffGutterDigits, diffGutterIndicatorText, diffGutterLaneTone, diffGutterLayout, diffGutterNumberText, diffGutterRowTone };
121
120
 
122
121
  //# sourceMappingURL=gutters.js.map
package/dist/index.d.ts CHANGED
@@ -1,14 +1,13 @@
1
- import './style.css';
2
1
  export { createDiffPlugin, diffRowAtEvent } from './editorDiffPlugin';
3
2
  export { createDiffEditorOptions } from './editorOptions';
4
3
  export { createDiffRegionStore } from './regions';
5
4
  export { annotateInlineChanges } from './inline';
6
- export { joinRenderLines } from './lines';
5
+ export { joinRenderLines, splitTextLines } from './lines';
7
6
  export { createLiveDiffProjection } from './liveProjection';
8
7
  export { createTextDiff, parseGitPatch } from './model';
9
8
  export { createSplitProjection, createStackedProjection } from './projection';
10
9
  export { diffSyntaxBackend, prepareDiffSyntax, PreparedDiffSyntaxSource, projectDiffSyntaxTokens, } from './diffSyntax';
11
- export type { PrepareDiffSyntaxOptions, PreparedDiffSyntaxInput } from './diffSyntax';
10
+ export type { DiffSyntaxSourceReader, PrepareDiffSyntaxOptions, PreparedDiffSyntaxInput, } from './diffSyntax';
12
11
  export type { DiffPlugin, DiffPluginMode, DiffPluginOptions, DiffRowHit } from './editorDiffPlugin';
13
12
  export type { DiffEditorOptions } from './editorOptions';
14
13
  export type { DiffGutterSide } from './gutters';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,CAAA;AAEpB,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAA;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAA;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAA;AAChD,OAAO,EAAE,eAAe,EA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kB,CAAA;AAC3D,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACvD,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAC7E,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,cAAc,CAAA;AACrB,YAAY,EACV,sBAAsB,EACtB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,cAAc,CAAA;AACrB,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AACnG,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AACxD,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAC/C,YAAY,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAChD,YAAY,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAC1D,YAAY,EACV,qBAAqB,EACrB,QAAQ,EACR,kBAAkB,EAClB,QAAQ,EACR,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,GACrB,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { joinRenderLines } from "./lines.js";
1
+ import { joinRenderLines, splitTextLines } from "./lines.js";
2
2
  import { PreparedDiffSyntaxSource, diffSyntaxBackend, prepareDiffSyntax, projectDiffSyntaxTokens } from "./diffSyntax.js";
3
3
  import { createLiveDiffProjection } from "./liveProjection.js";
4
4
  import { annotateInlineChanges } from "./inline.js";
@@ -7,5 +7,4 @@ import { createSplitProjection, createStackedProjection } from "./projection.js"
7
7
  import { createDiffRegionStore } from "./regions.js";
8
8
  import { createDiffPlugin, diffRowAtEvent } from "./editorDiffPlugin.js";
9
9
  import { createDiffEditorOptions } from "./editorOptions.js";
10
- import "./style.css";
11
- export { PreparedDiffSyntaxSource, annotateInlineChanges, createDiffEditorOptions, createDiffPlugin, createDiffRegionStore, createLiveDiffProjection, createSplitProjection, createStackedProjection, createTextDiff, diffRowAtEvent, diffSyntaxBackend, joinRenderLines, parseGitPatch, prepareDiffSyntax, projectDiffSyntaxTokens };
10
+ export { PreparedDiffSyntaxSource, annotateInlineChanges, createDiffEditorOptions, createDiffPlugin, createDiffRegionStore, createLiveDiffProjection, createSplitProjection, createStackedProjection, createTextDiff, diffRowAtEvent, diffSyntaxBackend, joinRenderLines, parseGitPatch, prepareDiffSyntax, projectDiffSyntaxTokens, splitTextLines };
package/dist/inline.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { diffWordsWithSpace } from "diff";
2
- //#region src/inline.ts
2
+ // src/inline.ts
3
3
  function annotateInlineChanges(lines) {
4
4
  const result = lines.map((line) => ({ ...line }));
5
5
  let index = 0;
@@ -66,7 +66,6 @@ function appendPartRanges(part, oldRanges, newRanges, oldOffset, newOffset) {
66
66
  end: newOffset + part.value.length
67
67
  });
68
68
  }
69
- //#endregion
70
69
  export { annotateInlineChanges };
71
70
 
72
71
  //# sourceMappingURL=inline.js.map
package/dist/lines.d.ts CHANGED
@@ -1,4 +1,20 @@
1
+ /**
2
+ * A side's lines as git splits them, each held the way the editor ingests that file: its byte order
3
+ * mark goes, and a line keeps its other terminators as the LF the editor reads them as.
4
+ */
1
5
  export declare function splitTextLines(text: string): readonly string[];
6
+ /**
7
+ * One git line as an opened document holds it. With `terminated`, an LF followed it, and ingestion
8
+ * folds a CR just before that LF into it as a CRLF; any other CR, U+2028 or U+2029 is a break.
9
+ */
10
+ export declare function editorLineText(line: string, terminated: boolean): string;
11
+ /** A side's first line: the editor drops one byte order mark from the start of a file. */
12
+ export declare function firstLineText(line: string): string;
13
+ /**
14
+ * The text a host pushes into a diff editor so that it holds exactly the rows joined by LF. The
15
+ * editor drops one leading byte order mark as it ingests, so a first row starting with one gets
16
+ * another in front to spend.
17
+ */
2
18
  export declare function joinRenderLines(rows: readonly {
3
19
  readonly text: string;
4
20
  }[]): string;
@@ -1 +1 @@
1
- {"version":3,"file":"lines.d.ts","sourceRoot":"","sources":["../src/lines.ts"],"names":[],"mappings":"AAAA,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAG9D;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,MAAM,CAElF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAIvE;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAKpE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7D"}
1
+ {"version":3,"file":"lines.d.ts","sourceRoot":"","sources":["../src/lines.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAM9D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,CAGxE;AAED,0FAA0F;AAC1F,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,MAAM,CAGlF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAIvE;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAKpE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7D"}
package/dist/lines.js CHANGED
@@ -1,10 +1,37 @@
1
- //#region src/lines.ts
1
+ import { hasByteOrderMark, normalizeLineEndings } from "@singapore-editor/core/document";
2
+ // src/lines.ts
3
+ var CARRIAGE_RETURN = 13;
4
+ /**
5
+ * A side's lines as git splits them, each held the way the editor ingests that file: its byte order
6
+ * mark goes, and a line keeps its other terminators as the LF the editor reads them as.
7
+ */
2
8
  function splitTextLines(text) {
3
9
  if (text.length === 0) return [];
4
- return text.split("\n");
10
+ const body = hasByteOrderMark(text) ? text.slice(1) : text;
11
+ const lines = body.split("\n");
12
+ if (normalizeLineEndings(body) === body) return lines;
13
+ return lines.map((line, index) => editorLineText(line, index < lines.length - 1));
5
14
  }
15
+ /**
16
+ * One git line as an opened document holds it. With `terminated`, an LF followed it, and ingestion
17
+ * folds a CR just before that LF into it as a CRLF; any other CR, U+2028 or U+2029 is a break.
18
+ */
19
+ function editorLineText(line, terminated) {
20
+ const crlf = terminated && line.charCodeAt(line.length - 1) === CARRIAGE_RETURN;
21
+ return normalizeLineEndings(crlf ? line.slice(0, -1) : line);
22
+ }
23
+ /** A side's first line: the editor drops one byte order mark from the start of a file. */
24
+ function firstLineText(line) {
25
+ return hasByteOrderMark(line) ? line.slice(1) : line;
26
+ }
27
+ /**
28
+ * The text a host pushes into a diff editor so that it holds exactly the rows joined by LF. The
29
+ * editor drops one leading byte order mark as it ingests, so a first row starting with one gets
30
+ * another in front to spend.
31
+ */
6
32
  function joinRenderLines(rows) {
7
- return rows.map((row) => row.text).join("\n");
33
+ const text = rows.map((row) => row.text).join("\n");
34
+ return hasByteOrderMark(text) ? `\uFEFF${text}` : text;
8
35
  }
9
36
  function normalizeContextLines(value) {
10
37
  if (value === void 0) return 3;
@@ -43,7 +70,6 @@ var LANGUAGE_BY_EXTENSION = {
43
70
  ".ts": "typescript",
44
71
  ".tsx": "typescript"
45
72
  };
46
- //#endregion
47
- export { joinRenderLines, languageIdForPath, normalizeContextLines, splitTextLines, stripDiffPathPrefix };
73
+ export { editorLineText, firstLineText, joinRenderLines, languageIdForPath, normalizeContextLines, splitTextLines, stripDiffPathPrefix };
48
74
 
49
75
  //# sourceMappingURL=lines.js.map
package/dist/lines.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lines.js","names":[],"sources":["../src/lines.ts"],"sourcesContent":["export function splitTextLines(text: string): readonly string[] {\n if (text.length === 0) return []\n return text.split('\\n')\n}\n\nexport function joinRenderLines(rows: readonly { readonly text: string }[]): string {\n return rows.map((row) => row.text).join('\\n')\n}\n\nexport function normalizeContextLines(value: number | undefined): number {\n if (value === undefined) return 3\n if (!Number.isFinite(value)) return 3\n return Math.max(0, Math.floor(value))\n}\n\nexport function stripDiffPathPrefix(path: string | undefined): string {\n if (!path) return ''\n if (path === '/dev/null') return path\n if (path.startsWith('a/') || path.startsWith('b/')) return path.slice(2)\n return path\n}\n\nexport function languageIdForPath(path: string): string | null {\n const extension = pathExtension(path)\n if (!extension) return null\n\n return LANGUAGE_BY_EXTENSION[extension] ?? null\n}\n\nfunction pathExtension(path: string): string {\n const fileName = path.slice(path.lastIndexOf('/') + 1)\n const dotIndex = fileName.lastIndexOf('.')\n if (dotIndex === -1) return ''\n return fileName.slice(dotIndex).toLowerCase()\n}\n\nconst LANGUAGE_BY_EXTENSION: Record<string, string> = {\n '.cjs': 'javascript',\n '.css': 'css',\n '.cts': 'typescript',\n '.htm': 'html',\n '.html': 'html',\n '.js': 'javascript',\n '.json': 'json',\n '.jsx': 'javascript',\n '.md': 'markdown',\n '.mjs': 'javascript',\n '.mts': 'typescript',\n '.ts': 'typescript',\n '.tsx': 'typescript',\n}\n"],"mappings":";AAAA,SAAgB,eAAe,MAAiC;CAC9D,IAAI,KAAK,WAAW,GAAG,OAAO,CAAC;CAC/B,OAAO,KAAK,MAAM,IAAI;AACxB;AAEA,SAAgB,gBAAgB,MAAoD;CAClF,OAAO,KAAK,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,KAAK,IAAI;AAC9C;AAEA,SAAgB,sBAAsB,OAAmC;CACvE,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CACpC,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AACtC;AAEA,SAAgB,oBAAoB,MAAkC;CACpE,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,GAAG,OAAO,KAAK,MAAM,CAAC;CACvE,OAAO;AACT;AAEA,SAAgB,kBAAkB,MAA6B;CAC7D,MAAM,YAAY,cAAc,IAAI;CACpC,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,sBAAsB,cAAc;AAC7C;AAEA,SAAS,cAAc,MAAsB;CAC3C,MAAM,WAAW,KAAK,MAAM,KAAK,YAAY,GAAG,IAAI,CAAC;CACrD,MAAM,WAAW,SAAS,YAAY,GAAG;CACzC,IAAI,aAAa,IAAI,OAAO;CAC5B,OAAO,SAAS,MAAM,QAAQ,CAAC,CAAC,YAAY;AAC9C;AAEA,IAAM,wBAAgD;CACpD,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,OAAO;CACP,SAAS;CACT,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,QAAQ;AACV"}
1
+ {"version":3,"file":"lines.js","names":[],"sources":["../src/lines.ts"],"sourcesContent":["import { hasByteOrderMark, normalizeLineEndings } from '@singapore-editor/core/document'\n\nconst CARRIAGE_RETURN = 0x0d\n\n/**\n * A side's lines as git splits them, each held the way the editor ingests that file: its byte order\n * mark goes, and a line keeps its other terminators as the LF the editor reads them as.\n */\nexport function splitTextLines(text: string): readonly string[] {\n if (text.length === 0) return []\n const body = hasByteOrderMark(text) ? text.slice(1) : text\n const lines = body.split('\\n')\n if (normalizeLineEndings(body) === body) return lines\n return lines.map((line, index) => editorLineText(line, index < lines.length - 1))\n}\n\n/**\n * One git line as an opened document holds it. With `terminated`, an LF followed it, and ingestion\n * folds a CR just before that LF into it as a CRLF; any other CR, U+2028 or U+2029 is a break.\n */\nexport function editorLineText(line: string, terminated: boolean): string {\n const crlf = terminated && line.charCodeAt(line.length - 1) === CARRIAGE_RETURN\n return normalizeLineEndings(crlf ? line.slice(0, -1) : line)\n}\n\n/** A side's first line: the editor drops one byte order mark from the start of a file. */\nexport function firstLineText(line: string): string {\n return hasByteOrderMark(line) ? line.slice(1) : line\n}\n\n/**\n * The text a host pushes into a diff editor so that it holds exactly the rows joined by LF. The\n * editor drops one leading byte order mark as it ingests, so a first row starting with one gets\n * another in front to spend.\n */\nexport function joinRenderLines(rows: readonly { readonly text: string }[]): string {\n const text = rows.map((row) => row.text).join('\\n')\n return hasByteOrderMark(text) ? `\\uFEFF${text}` : text\n}\n\nexport function normalizeContextLines(value: number | undefined): number {\n if (value === undefined) return 3\n if (!Number.isFinite(value)) return 3\n return Math.max(0, Math.floor(value))\n}\n\nexport function stripDiffPathPrefix(path: string | undefined): string {\n if (!path) return ''\n if (path === '/dev/null') return path\n if (path.startsWith('a/') || path.startsWith('b/')) return path.slice(2)\n return path\n}\n\nexport function languageIdForPath(path: string): string | null {\n const extension = pathExtension(path)\n if (!extension) return null\n\n return LANGUAGE_BY_EXTENSION[extension] ?? null\n}\n\nfunction pathExtension(path: string): string {\n const fileName = path.slice(path.lastIndexOf('/') + 1)\n const dotIndex = fileName.lastIndexOf('.')\n if (dotIndex === -1) return ''\n return fileName.slice(dotIndex).toLowerCase()\n}\n\nconst LANGUAGE_BY_EXTENSION: Record<string, string> = {\n '.cjs': 'javascript',\n '.css': 'css',\n '.cts': 'typescript',\n '.htm': 'html',\n '.html': 'html',\n '.js': 'javascript',\n '.json': 'json',\n '.jsx': 'javascript',\n '.md': 'markdown',\n '.mjs': 'javascript',\n '.mts': 'typescript',\n '.ts': 'typescript',\n '.tsx': 'typescript',\n}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,cAAc;AAC7C;AAEA,SAAS,cAAc,MAAsB;CAC3C,MAAM,WAAW,KAAK,MAAM,KAAK,YAAY,GAAG,IAAI,CAAC;CACrD,MAAM,WAAW,SAAS,YAAY,GAAG;CACzC,IAAI,aAAa,IAAI,OAAO;CAC5B,OAAO,SAAS,MAAM,QAAQ,CAAC,CAAC,YAAY;AAC9C;AAEA,IAAM,wBAAgD;CACpD,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,OAAO;CACP,SAAS;CACT,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,QAAQ;AACV"}
@@ -1,4 +1,4 @@
1
- //#region src/liveProjection.ts
1
+ // src/liveProjection.ts
2
2
  var DIFF_ROW_CLASS = "editor-diff-row";
3
3
  var DIFF_GUTTER_ROW_CLASS = "editor-diff-gutter-row";
4
4
  function createLiveDiffProjection(file) {
@@ -146,7 +146,6 @@ function deletionRowId(row, hunkIndex, lineIndex) {
146
146
  if (row.oldLineNumber !== void 0) return `diff-delete-old-${row.oldLineNumber}`;
147
147
  return `diff-delete-${hunkIndex}-${lineIndex}`;
148
148
  }
149
- //#endregion
150
149
  export { createLiveDiffProjection };
151
150
 
152
151
  //# sourceMappingURL=liveProjection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EACrB,QAAQ,EAKR,oBAAoB,EACrB,MAAM,SAAS,CAAA;AAgChB,wBAAgB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,QAAQ,CA2BvE;AAED,wBAAgB,aAAa,CAC3B,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,oBAAyB,GACjC,SAAS,QAAQ,EAAE,CASrB"}
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,qBAAqB,EACrB,QAAQ,EAKR,oBAAoB,EACrB,MAAM,SAAS,CAAA;AAgChB,wBAAgB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,QAAQ,CA2BvE;AAED,wBAAgB,aAAa,CAC3B,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,oBAAyB,GACjC,SAAS,QAAQ,EAAE,CASrB"}
package/dist/model.js CHANGED
@@ -1,7 +1,7 @@
1
- import { languageIdForPath, normalizeContextLines, splitTextLines, stripDiffPathPrefix } from "./lines.js";
1
+ import { editorLineText, firstLineText, languageIdForPath, normalizeContextLines, splitTextLines, stripDiffPathPrefix } from "./lines.js";
2
2
  import { annotateInlineChanges } from "./inline.js";
3
3
  import { parsePatch, structuredPatch } from "diff";
4
- //#region src/model.ts
4
+ // src/model.ts
5
5
  function createTextDiff(options) {
6
6
  const oldFile = options.oldFile ?? null;
7
7
  const newFile = options.newFile ?? null;
@@ -94,8 +94,8 @@ function convertPatchLines(hunk) {
94
94
  const lines = [];
95
95
  let oldLineNumber = hunk.oldStart;
96
96
  let newLineNumber = hunk.newStart;
97
- for (const rawLine of hunk.lines) {
98
- const result = convertPatchLine(rawLine, oldLineNumber, newLineNumber);
97
+ for (const [index, rawLine] of hunk.lines.entries()) {
98
+ const result = convertPatchLine(rawLine, hunk.lines[index + 1]?.startsWith("\\") !== true, oldLineNumber, newLineNumber);
99
99
  if (!result) continue;
100
100
  lines.push(result.line);
101
101
  oldLineNumber += result.oldDelta;
@@ -103,16 +103,18 @@ function convertPatchLines(hunk) {
103
103
  }
104
104
  return lines;
105
105
  }
106
- function convertPatchLine(rawLine, oldLineNumber, newLineNumber) {
106
+ function convertPatchLine(rawLine, terminated, oldLineNumber, newLineNumber) {
107
107
  if (rawLine.startsWith("\\")) return null;
108
108
  if (isRawHunkHeader(rawLine)) return null;
109
109
  const marker = rawLine[0] ?? " ";
110
- const text = rawLine.slice(1);
111
- if (isRawHunkHeader(text)) return null;
110
+ const content = editorLineText(rawLine.slice(1), terminated);
111
+ const oldText = oldLineNumber === 1 ? firstLineText(content) : content;
112
+ const newText = newLineNumber === 1 ? firstLineText(content) : content;
113
+ if (isRawHunkHeader(content)) return null;
112
114
  if (marker === "-") return {
113
115
  line: {
114
116
  type: "deletion",
115
- text,
117
+ text: oldText,
116
118
  oldLineNumber
117
119
  },
118
120
  oldDelta: 1,
@@ -121,7 +123,7 @@ function convertPatchLine(rawLine, oldLineNumber, newLineNumber) {
121
123
  if (marker === "+") return {
122
124
  line: {
123
125
  type: "addition",
124
- text,
126
+ text: newText,
125
127
  newLineNumber
126
128
  },
127
129
  oldDelta: 0,
@@ -130,7 +132,8 @@ function convertPatchLine(rawLine, oldLineNumber, newLineNumber) {
130
132
  return {
131
133
  line: {
132
134
  type: "context",
133
- text,
135
+ text: newText,
136
+ ...oldText === newText ? {} : { oldText },
134
137
  oldLineNumber,
135
138
  newLineNumber
136
139
  },
@@ -153,7 +156,7 @@ function appendPatchLines(lines, hunk, side) {
153
156
  for (const line of hunk.lines) {
154
157
  if (side === "old" && line.type === "addition") continue;
155
158
  if (side === "new" && line.type === "deletion") continue;
156
- lines.push(line.text);
159
+ lines.push(side === "old" ? line.oldText ?? line.text : line.text);
157
160
  }
158
161
  }
159
162
  function changeTypeForTextFiles(oldFile, newFile, oldPath, newPath) {
@@ -241,7 +244,6 @@ function gitChangeType(partial, section) {
241
244
  if (partial.oldPath && partial.newPath && partial.oldPath !== partial.newPath) return section.includes("\n@@ ") ? "rename-change" : "rename";
242
245
  return "change";
243
246
  }
244
- //#endregion
245
247
  export { createTextDiff, parseGitPatch };
246
248
 
247
249
  //# sourceMappingURL=model.js.map