@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,13 +1,13 @@
1
1
  import { languageIdForPath } from "./lines.js";
2
- import { createDocumentTextSnapshot, createPieceTableSnapshot } from "@singapore-editor/core/document";
3
- import { createEmptySyntaxResult, createSyntaxLanguageConfiguration, createSyntaxSnapshotTag, toEditorTokenStore } from "@singapore-editor/core/syntax";
2
+ import { createEditorDocumentAnalysis } from "@singapore-editor/core/editor";
3
+ import { createEmptySyntaxResult, createSnippetDocument, createSyntaxLanguageConfiguration, createSyntaxSnapshotTag, toEditorTokenStore } from "@singapore-editor/core/syntax";
4
4
  import { EditorSecondaryViewScheduler } from "@singapore-editor/core/secondary-views";
5
- //#region src/diffSyntax.ts
5
+ // src/diffSyntax.ts
6
6
  var nextSyntaxControllerId = 0;
7
7
  /**
8
8
  * One source side's parsed token stream and the session that recolours it on a theme change.
9
- * Exactly one holder owns it at a time — a host's store, or the controller that adopted it — and
10
- * that holder disposes it.
9
+ * Its creator owns it and disposes it. A shared owner lends separate DiffSyntaxSourceReader
10
+ * interests, whose disposal releases only that interest.
11
11
  */
12
12
  var PreparedDiffSyntaxSource = class {
13
13
  side;
@@ -58,7 +58,10 @@ var PreparedDiffSyntaxSource = class {
58
58
  * empty.
59
59
  */
60
60
  async function prepareDiffSyntax(file, options = {}) {
61
+ if (file.isPartial || options.signal?.aborted) return [];
61
62
  const created = [];
63
+ const cancel = () => disposeMutableSessions(created);
64
+ options.signal?.addEventListener("abort", cancel, { once: true });
62
65
  const isCurrent = () => options.signal?.aborted !== true;
63
66
  try {
64
67
  const sources = await loadSyntaxSources(file, options.side ?? "stacked", options.backend, isCurrent, created);
@@ -66,6 +69,8 @@ async function prepareDiffSyntax(file, options = {}) {
66
69
  } catch (error) {
67
70
  disposeMutableSessions(created);
68
71
  throw error;
72
+ } finally {
73
+ options.signal?.removeEventListener("abort", cancel);
69
74
  }
70
75
  disposeMutableSessions(created);
71
76
  return [];
@@ -93,6 +98,7 @@ var DiffSyntaxController = class {
93
98
  tokens = [];
94
99
  disposed = false;
95
100
  ready = true;
101
+ generation = 0;
96
102
  constructor(options) {
97
103
  this.options = options;
98
104
  }
@@ -108,32 +114,33 @@ var DiffSyntaxController = class {
108
114
  }
109
115
  /**
110
116
  * New file: drop the cached streams, then adopt `prepared` when it covers this side, or reparse.
111
- * A preparation still running is awaited instead of parsing the same file twice. Takes ownership
112
- * of `prepared` either way.
117
+ * A preparation still running is awaited instead of parsing the same file twice. Detachment
118
+ * disposes each reader, releasing borrowed interests or owned sessions.
113
119
  */
114
120
  setFile(file, rows, prepared = []) {
121
+ const generation = ++this.generation;
115
122
  this.file = file;
116
- this.ready = !file || this.options.enabled === false;
123
+ this.ready = !file || file.isPartial || this.options.enabled === false;
117
124
  this.rows = rows;
118
125
  this.tokens = [];
119
126
  this.disposeSources();
120
127
  this.scheduler.cancel(this.key);
121
- if (!file || this.ready) {
128
+ if (this.disposed || !file || this.ready) {
122
129
  Promise.resolve(prepared).then(disposePrepared, () => void 0);
123
130
  return;
124
131
  }
125
132
  if (isPromiseLike(prepared)) {
126
133
  const settle = (sources) => {
127
- if (this.settlePrepared(file, sources)) this.options.onDidChangeTokens();
134
+ if (this.settlePrepared(file, generation, sources)) this.options.onDidChangeTokens();
128
135
  };
129
136
  prepared.then(settle, () => settle([]));
130
137
  return;
131
138
  }
132
- this.settlePrepared(file, prepared);
139
+ this.settlePrepared(file, generation, prepared);
133
140
  }
134
141
  /** Whether `prepared` was adopted; otherwise it is disposed, and a current file reparses. */
135
- settlePrepared(file, prepared) {
136
- if (this.disposed || this.file !== file || this.ready) {
142
+ settlePrepared(file, generation, prepared) {
143
+ if (this.disposed || this.generation !== generation || this.file !== file || this.ready) {
137
144
  disposePrepared(prepared);
138
145
  return false;
139
146
  }
@@ -150,17 +157,12 @@ var DiffSyntaxController = class {
150
157
  this.rows = rows;
151
158
  this.reproject();
152
159
  }
153
- /**
154
- * Hands the parsed streams of the current file to the caller, which then owns them; empty while
155
- * a parse is still running. The controller keeps projecting their current tokens, and stops
156
- * following their recolouring.
157
- */
158
160
  release() {
159
- if (!this.ready || this.sourcesFile !== this.file) return [];
160
- const sources = this.sources;
161
- this.unsubscribeSources();
162
- this.sources = [];
163
- return sources;
161
+ this.generation += 1;
162
+ this.scheduler.cancel(this.key);
163
+ this.disposeSources();
164
+ this.tokens = [];
165
+ this.ready = true;
164
166
  }
165
167
  dispose() {
166
168
  this.disposed = true;
@@ -228,7 +230,7 @@ var DiffSyntaxController = class {
228
230
  }
229
231
  disposeSources() {
230
232
  this.unsubscribeSources();
231
- disposeMutableSessions([...this.sources]);
233
+ disposePrepared(this.sources);
232
234
  this.sources = [];
233
235
  this.indexed = [];
234
236
  this.sourcesFile = null;
@@ -242,7 +244,7 @@ async function loadSyntaxSources(file, side, backend, isCurrent, created) {
242
244
  return null;
243
245
  };
244
246
  const sources = [];
245
- for (const document of syntaxDocumentsForFile(file, side)) {
247
+ for (const document of syntaxDocumentsForFile(file, side, service.lines)) {
246
248
  if (!isCurrent()) return stale();
247
249
  const session = await service.createSession(document);
248
250
  if (!session) continue;
@@ -305,23 +307,68 @@ function diffSyntaxService(backend) {
305
307
  }
306
308
  function highlighterDiffSyntaxService(provider) {
307
309
  if (!provider) return null;
308
- return { createSession: async (document) => highlighterDiffSyntaxSession(provider, document) };
310
+ return {
311
+ lines: "as-submitted",
312
+ createSession: async (document) => highlighterDiffSyntaxSession(provider, document)
313
+ };
309
314
  }
310
315
  function highlighterDiffSyntaxSession(provider, document) {
311
- const session = provider.createSession(highlighterSessionOptions(document));
312
- if (!session) return null;
313
- return tokenHighlighterDiffSyntaxSession(document, session);
316
+ const analysis = createEditorDocumentAnalysis({
317
+ buffer: document.snippet.buffer,
318
+ documentId: document.documentId
319
+ });
320
+ const session = analysis.borrowHighlighter({
321
+ provider,
322
+ languageId: document.languageId
323
+ });
324
+ if (!session) {
325
+ analysis.dispose();
326
+ return null;
327
+ }
328
+ const retained = tokenHighlighterDiffSyntaxSession(document, session);
329
+ return {
330
+ ...retained,
331
+ dispose() {
332
+ retained.dispose();
333
+ analysis.dispose();
334
+ }
335
+ };
314
336
  }
315
337
  function treeSitterDiffSyntaxService(provider) {
316
338
  if (!provider) return null;
317
- return { createSession: async (document) => treeSitterDiffSyntaxSession(provider, document) };
339
+ return {
340
+ lines: "as-document",
341
+ createSession: async (document) => treeSitterDiffSyntaxSession(provider, document)
342
+ };
318
343
  }
319
344
  function treeSitterDiffSyntaxSession(provider, document) {
320
- const session = provider.createSession(syntaxSessionOptions(document));
321
- if (!session) return null;
345
+ const analysis = createEditorDocumentAnalysis({
346
+ buffer: document.snippet.buffer,
347
+ documentId: document.documentId
348
+ });
349
+ const session = analysis.borrowStructural({
350
+ provider,
351
+ includeCaptures: document.request.language.includeCaptures,
352
+ includeHighlights: document.request.language.includeHighlights,
353
+ languageId: document.languageId,
354
+ syntaxMode: document.request.language.mode === "range" ? "range" : "full"
355
+ });
356
+ if (!session) {
357
+ analysis.dispose();
358
+ return null;
359
+ }
322
360
  return {
323
- dispose: () => session.dispose(),
324
- refresh: () => session.refresh(document.textSnapshot)
361
+ dispose: () => {
362
+ session.dispose();
363
+ analysis.dispose();
364
+ },
365
+ refresh: async () => {
366
+ const result = await session.refresh(document.textSnapshot);
367
+ return {
368
+ ...result,
369
+ tokens: document.snippet.submittedTokens(result.tokens)
370
+ };
371
+ }
325
372
  };
326
373
  }
327
374
  function tokenHighlighterDiffSyntaxSession(document, session) {
@@ -334,25 +381,6 @@ function tokenHighlighterDiffSyntaxSession(document, session) {
334
381
  }
335
382
  };
336
383
  }
337
- function syntaxSessionOptions(document) {
338
- return {
339
- documentId: document.documentId,
340
- includeCaptures: document.request.language.includeCaptures,
341
- includeHighlights: document.request.language.includeHighlights,
342
- languageId: document.languageId,
343
- snapshot: document.request.snapshot,
344
- syntaxMode: document.request.language.mode === "range" ? "range" : "full",
345
- textSnapshot: document.textSnapshot
346
- };
347
- }
348
- function highlighterSessionOptions(document) {
349
- return {
350
- documentId: document.documentId,
351
- languageId: document.languageId,
352
- snapshot: document.request.snapshot,
353
- textSnapshot: document.textSnapshot
354
- };
355
- }
356
384
  function syntaxResultFromTokens(request, tokens) {
357
385
  return {
358
386
  ...createEmptySyntaxResult({
@@ -370,8 +398,9 @@ function syntaxResultFromTokens(request, tokens) {
370
398
  * on the editor: the editor's own document is the *interleaved* buffer, and giving that a language
371
399
  * feeds a garbage parse into folds, brackets and injections.
372
400
  */
373
- function syntaxDocumentsForFile(file, side) {
374
- return syntaxSourcesForSide(file, side).map((source) => syntaxDocument(file, source));
401
+ function syntaxDocumentsForFile(file, side, lines) {
402
+ if (file.isPartial) return [];
403
+ return syntaxSourcesForSide(file, side).map((source) => syntaxDocument(file, source, lines));
375
404
  }
376
405
  function syntaxSourcesForSide(file, side) {
377
406
  if (side === "stacked") return [syntaxSource(file.oldLines, "old"), syntaxSource(file.newLines, "new")];
@@ -385,9 +414,9 @@ function syntaxSource(lines, side) {
385
414
  text
386
415
  };
387
416
  }
388
- function syntaxDocument(file, source) {
389
- const snapshot = createPieceTableSnapshot(source.text);
390
- const textSnapshot = createDocumentTextSnapshot(snapshot, source.text);
417
+ function syntaxDocument(file, source, lines) {
418
+ const snippet = createSnippetDocument(source.text, lines);
419
+ const { snapshot, textSnapshot } = snippet;
391
420
  const documentId = `${file.path}#diff-${source.side}`;
392
421
  const languageId = diffSyntaxLanguageId(file);
393
422
  const request = {
@@ -415,6 +444,7 @@ function syntaxDocument(file, source) {
415
444
  documentId,
416
445
  languageId,
417
446
  request,
447
+ snippet,
418
448
  textSnapshot
419
449
  };
420
450
  }
@@ -485,7 +515,6 @@ function lineStartsForLines(lines) {
485
515
  function disposeMutableSessions(sessions) {
486
516
  while (sessions.length > 0) sessions.pop()?.dispose();
487
517
  }
488
- //#endregion
489
518
  export { DiffSyntaxController, PreparedDiffSyntaxSource, diffSyntaxBackend, prepareDiffSyntax, projectDiffSyntaxTokens };
490
519
 
491
520
  //# sourceMappingURL=diffSyntax.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diffSyntax.js","names":[],"sources":["../src/diffSyntax.ts"],"sourcesContent":["import {\n createDocumentTextSnapshot,\n type DocumentTextSnapshot,\n createPieceTableSnapshot,\n} from '@singapore-editor/core/document'\nimport type {\n EditorHighlighterProvider,\n EditorHighlighterSession,\n} from '@singapore-editor/core/extensions'\nimport {\n createEmptySyntaxResult,\n createSyntaxLanguageConfiguration,\n createSyntaxSnapshotTag,\n type EditorSyntaxProvider,\n type EditorSyntaxResult,\n type EditorSyntaxServiceRequest,\n type EditorSyntaxSessionOptions,\n type EditorToken,\n type EditorTokenInput,\n type EditorTokenStore,\n toEditorTokenStore,\n} from '@singapore-editor/core/syntax'\nimport { EditorSecondaryViewScheduler } from '@singapore-editor/core/secondary-views'\nimport { languageIdForPath } from './lines'\nimport type { DiffFile, DiffRenderRow, DiffSyntaxBackend } from './types'\n\ntype DiffSyntaxSide = 'old' | 'new' | 'stacked'\ntype DiffSyntaxSourceSide = 'old' | 'new'\n\nlet nextSyntaxControllerId = 0\n\nexport type DiffSyntaxTokenSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenInput\n}\n\nexport type ProjectDiffSyntaxTokensOptions = {\n readonly rows: readonly DiffRenderRow[]\n readonly side: DiffSyntaxSide\n readonly sources: readonly DiffSyntaxTokenSource[]\n}\n\nexport type DiffSyntaxControllerOptions = {\n readonly side: DiffSyntaxSide\n readonly backend?: DiffSyntaxBackend\n readonly enabled?: boolean\n /** Fires when a *newly parsed* token stream lands; row-driven re-projection is synchronous. */\n readonly onDidChangeTokens: () => void\n}\n\n/** Streams from `prepareDiffSyntax`, or a preparation of them still running. */\nexport type PreparedDiffSyntaxInput =\n | readonly PreparedDiffSyntaxSource[]\n | Promise<readonly PreparedDiffSyntaxSource[]>\n\nexport type PrepareDiffSyntaxOptions = {\n readonly backend?: DiffSyntaxBackend\n /** Which pane the sources are for. `stacked` prepares both source sides. */\n readonly side?: DiffSyntaxSide\n readonly signal?: AbortSignal\n}\n\n/**\n * One source side's parsed token stream and the session that recolours it on a theme change.\n * Exactly one holder owns it at a time — a host's store, or the controller that adopted it — and\n * that holder disposes it.\n */\nexport class PreparedDiffSyntaxSource {\n private readonly listeners = new Set<() => void>()\n private readonly disposables: { dispose(): void }[] = []\n private current: EditorTokenStore = toEditorTokenStore([])\n private disposed = false\n\n constructor(\n readonly side: DiffSyntaxSourceSide,\n readonly lineStarts: readonly number[],\n ) {}\n\n get tokens(): EditorTokenStore {\n return this.current\n }\n\n /** Fires when a theme change recolours the stream. */\n onDidChangeTokens(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.listeners.clear()\n disposeMutableSessions(this.disposables)\n }\n\n /** @internal */\n own(disposable: { dispose(): void }): void {\n this.disposables.push(disposable)\n }\n\n /** @internal */\n setTokens(tokens: EditorTokenInput): void {\n this.current = toEditorTokenStore(tokens)\n }\n\n /** @internal */\n async recolor(session: DiffSyntaxServiceSession): Promise<void> {\n try {\n const result = await session.refresh()\n if (this.disposed) return\n\n this.setTokens(result.tokens)\n for (const listener of this.listeners) listener()\n } catch {\n // Keep the last colors if the worker fails; a subsequent change can retry.\n }\n }\n}\n\n/**\n * Parses a diff's sources ahead of the view that will show them, so `setFile(file, rows, prepared)`\n * paints coloured on its first frame. The caller owns the result; an aborted preparation resolves\n * empty.\n */\nexport async function prepareDiffSyntax(\n file: DiffFile,\n options: PrepareDiffSyntaxOptions = {},\n): Promise<readonly PreparedDiffSyntaxSource[]> {\n const created: PreparedDiffSyntaxSource[] = []\n const isCurrent = () => options.signal?.aborted !== true\n try {\n const sources = await loadSyntaxSources(\n file,\n options.side ?? 'stacked',\n options.backend,\n isCurrent,\n created,\n )\n if (sources) return sources\n } catch (error) {\n disposeMutableSessions(created)\n throw error\n }\n\n disposeMutableSessions(created)\n return []\n}\n\n/**\n * The syntax half of the old `DiffView`, with one behavioural change.\n *\n * `DiffView` re-ran the whole pipeline — new sessions, new parse — on every row change, including\n * every expansion toggle (`updatePaneRows` → `refreshSyntaxHighlighting`, DiffView.ts:564). The\n * parse result does not depend on which regions are expanded: the sources are the two *full files*,\n * and expansion only changes which of their lines the projection shows. So the per-side token\n * streams are cached against the file and re-projected synchronously when rows change, which is\n * what lets a toggle repaint without an uncoloured frame (§C10).\n */\nexport class DiffSyntaxController {\n private readonly scheduler = new EditorSecondaryViewScheduler()\n private readonly key = `diff.syntax.${nextSyntaxControllerId++}`\n private sources: readonly PreparedDiffSyntaxSource[] = []\n private sourceSubscriptions: (() => void)[] = []\n private indexed: readonly IndexedTokenSource[] = []\n private sourcesFile: DiffFile | null = null\n private file: DiffFile | null = null\n private rows: readonly DiffRenderRow[] = []\n private tokens: readonly EditorToken[] = []\n private disposed = false\n private ready = true\n\n constructor(private readonly options: DiffSyntaxControllerOptions) {}\n\n /** A disposed controller is terminal — its scheduler never runs another task. */\n isDisposed(): boolean {\n return this.disposed\n }\n\n isReady(): boolean {\n return this.ready\n }\n\n getTokens(): readonly EditorToken[] {\n return this.tokens\n }\n\n /**\n * New file: drop the cached streams, then adopt `prepared` when it covers this side, or reparse.\n * A preparation still running is awaited instead of parsing the same file twice. Takes ownership\n * of `prepared` either way.\n */\n setFile(\n file: DiffFile | null,\n rows: readonly DiffRenderRow[],\n prepared: PreparedDiffSyntaxInput = [],\n ): void {\n this.file = file\n this.ready = !file || this.options.enabled === false\n this.rows = rows\n this.tokens = []\n this.disposeSources()\n this.scheduler.cancel(this.key)\n if (!file || this.ready) {\n void Promise.resolve(prepared).then(disposePrepared, () => undefined)\n return\n }\n if (isPromiseLike(prepared)) {\n const settle = (sources: readonly PreparedDiffSyntaxSource[]) => {\n if (this.settlePrepared(file, sources)) this.options.onDidChangeTokens()\n }\n void prepared.then(settle, () => settle([]))\n return\n }\n this.settlePrepared(file, prepared)\n }\n\n /** Whether `prepared` was adopted; otherwise it is disposed, and a current file reparses. */\n private settlePrepared(file: DiffFile, prepared: readonly PreparedDiffSyntaxSource[]): boolean {\n if (this.disposed || this.file !== file || this.ready) {\n disposePrepared(prepared)\n return false\n }\n if (!coversSide(prepared, this.options.side)) {\n disposePrepared(prepared)\n this.load(file)\n return false\n }\n\n this.adoptSources(file, prepared)\n return true\n }\n\n /** Same file, different rows — an expansion toggle. Re-project what is already parsed. */\n setRows(rows: readonly DiffRenderRow[]): void {\n this.rows = rows\n this.reproject()\n }\n\n /**\n * Hands the parsed streams of the current file to the caller, which then owns them; empty while\n * a parse is still running. The controller keeps projecting their current tokens, and stops\n * following their recolouring.\n */\n release(): readonly PreparedDiffSyntaxSource[] {\n if (!this.ready || this.sourcesFile !== this.file) return []\n\n const sources = this.sources\n this.unsubscribeSources()\n this.sources = []\n return sources\n }\n\n dispose(): void {\n this.disposed = true\n this.scheduler.cancel(this.key)\n this.scheduler.dispose()\n this.disposeSources()\n this.tokens = []\n }\n\n private reproject(): void {\n if (this.indexed.length === 0 || this.sourcesFile !== this.file) {\n this.tokens = []\n return\n }\n\n this.tokens = projectIndexedTokens(this.rows, this.options.side, this.indexed)\n }\n\n private load(file: DiffFile): void {\n if (this.options.enabled === false) return\n\n const created: PreparedDiffSyntaxSource[] = []\n this.scheduler.schedule({\n key: this.key,\n taskClass: 'background-derived',\n priority: 'low',\n tags: { configuration: 'syntax', viewport: this.options.side },\n run: (context) =>\n loadSyntaxSources(\n file,\n this.options.side,\n this.options.backend,\n () => context.isCurrent(),\n created,\n ),\n apply: (sources) => this.applySources(file, sources, created),\n fail: () => {\n disposeMutableSessions(created)\n if (this.file !== file) return\n this.ready = true\n this.options.onDidChangeTokens()\n },\n cancel: () => disposeMutableSessions(created),\n })\n }\n\n private applySources(\n file: DiffFile,\n sources: readonly PreparedDiffSyntaxSource[] | null,\n created: PreparedDiffSyntaxSource[],\n ): void {\n if (this.file !== file) {\n disposeMutableSessions(created)\n return\n }\n\n // Adopted: the task's cancel path must no longer reach them.\n created.length = 0\n this.adoptSources(file, sources ?? [])\n this.options.onDidChangeTokens()\n }\n\n private adoptSources(file: DiffFile, sources: readonly PreparedDiffSyntaxSource[]): void {\n this.disposeSources()\n this.sources = sources\n this.sourceSubscriptions = sources.map((source) =>\n source.onDidChangeTokens(() => this.recolor(file)),\n )\n // Indexed here, once per parse. The index depends only on the token streams, and expansion\n // does not change those — so rebuilding it inside every re-projection would be repeated work\n // plus a fresh Map and N arrays of garbage on each toggle.\n this.indexed = indexPreparedSources(sources)\n this.ready = true\n this.sourcesFile = file\n this.reproject()\n }\n\n private recolor(file: DiffFile): void {\n if (this.disposed || this.file !== file) return\n\n this.indexed = indexPreparedSources(this.sources)\n this.reproject()\n this.options.onDidChangeTokens()\n }\n\n private unsubscribeSources(): void {\n for (const unsubscribe of this.sourceSubscriptions) unsubscribe()\n this.sourceSubscriptions = []\n }\n\n private disposeSources(): void {\n this.unsubscribeSources()\n disposeMutableSessions([...this.sources])\n this.sources = []\n this.indexed = []\n this.sourcesFile = null\n }\n}\n\nasync function loadSyntaxSources(\n file: DiffFile,\n side: DiffSyntaxSide,\n backend: DiffSyntaxBackend | undefined,\n isCurrent: () => boolean,\n created: PreparedDiffSyntaxSource[],\n): Promise<readonly PreparedDiffSyntaxSource[] | null> {\n const service = diffSyntaxService(diffSyntaxBackend(backend))\n if (!service) return null\n\n // A task cancelled mid-load has already run its cancel callback, so a stale load disposes\n // whatever it created itself: nothing else will.\n const stale = () => {\n disposeMutableSessions(created)\n return null\n }\n const sources: PreparedDiffSyntaxSource[] = []\n for (const document of syntaxDocumentsForFile(file, side)) {\n if (!isCurrent()) return stale()\n\n const session = await service.createSession(document)\n if (!session) continue\n\n const source = new PreparedDiffSyntaxSource(document.side, document.lineStarts)\n created.push(source)\n source.own(session)\n if (!isCurrent()) return stale()\n const unsubscribe = session.onDidChangeTheme?.(() => void source.recolor(session))\n if (unsubscribe) source.own({ dispose: unsubscribe })\n const result = await session.refresh()\n if (!isCurrent()) return stale()\n\n source.setTokens(result.tokens)\n sources.push(source)\n }\n\n return sources\n}\n\nfunction disposePrepared(sources: readonly PreparedDiffSyntaxSource[]): void {\n for (const source of sources) source.dispose()\n}\n\nfunction isPromiseLike(\n value: PreparedDiffSyntaxInput,\n): value is Promise<readonly PreparedDiffSyntaxSource[]> {\n return 'then' in value\n}\n\nfunction coversSide(sources: readonly PreparedDiffSyntaxSource[], side: DiffSyntaxSide): boolean {\n const sides = new Set(sources.map((source) => source.side))\n if (side === 'stacked') return sides.size === 2 && sources.length === 2\n return sides.has(side) && sources.length === 1\n}\n\nfunction indexPreparedSources(\n sources: readonly PreparedDiffSyntaxSource[],\n): readonly IndexedTokenSource[] {\n return sources.map((source) => ({\n lineStarts: source.lineStarts,\n side: source.side,\n tokens: source.tokens,\n }))\n}\n\nexport function diffSyntaxBackend(backend: DiffSyntaxBackend | undefined): DiffSyntaxBackend {\n return backend ?? { kind: 'tree-sitter' }\n}\n\nexport function projectDiffSyntaxTokens({\n rows,\n side,\n sources,\n}: ProjectDiffSyntaxTokensOptions): readonly EditorToken[] {\n return projectIndexedTokens(rows, side, indexTokenSources(sources))\n}\n\nfunction projectIndexedTokens(\n rows: readonly DiffRenderRow[],\n side: DiffSyntaxSide,\n sources: readonly IndexedTokenSource[],\n): readonly EditorToken[] {\n const projectedTokens: EditorToken[] = []\n let rowOffset = 0\n\n for (const row of rows) {\n const source = tokenSourceForRow(sources, row, side)\n if (source) {\n appendRowSyntaxTokens(projectedTokens, {\n lineStarts: source.lineStarts,\n row,\n rowOffset,\n side: source.side,\n tokens: source.tokens,\n })\n }\n rowOffset += row.text.length + 1\n }\n\n return projectedTokens\n}\n\ntype DiffSyntaxSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly text: string\n}\n\ntype DiffSyntaxDocument = DiffSyntaxSource & {\n readonly documentId: string\n readonly languageId: string | null\n readonly request: EditorSyntaxServiceRequest\n readonly textSnapshot: DocumentTextSnapshot\n}\n\ntype DiffSyntaxService = {\n createSession(document: DiffSyntaxDocument): Promise<DiffSyntaxServiceSession | null>\n}\n\ntype DiffSyntaxServiceSession = {\n onDidChangeTheme?: EditorHighlighterSession['onDidChangeTheme']\n refresh(): Promise<EditorSyntaxResult>\n dispose(): void\n}\n\nfunction diffSyntaxService(backend: DiffSyntaxBackend): DiffSyntaxService | null {\n if (backend.kind === 'tree-sitter') return treeSitterDiffSyntaxService(backend.provider ?? null)\n return highlighterDiffSyntaxService(backend.provider ?? null)\n}\n\nfunction highlighterDiffSyntaxService(\n provider: EditorHighlighterProvider | null,\n): DiffSyntaxService | null {\n if (!provider) return null\n\n return {\n createSession: async (document) => highlighterDiffSyntaxSession(provider, document),\n }\n}\n\nfunction highlighterDiffSyntaxSession(\n provider: EditorHighlighterProvider,\n document: DiffSyntaxDocument,\n): DiffSyntaxServiceSession | null {\n const session = provider.createSession(highlighterSessionOptions(document))\n if (!session) return null\n\n return tokenHighlighterDiffSyntaxSession(document, session)\n}\n\nfunction treeSitterDiffSyntaxService(\n provider: EditorSyntaxProvider | null,\n): DiffSyntaxService | null {\n if (!provider) return null\n\n return {\n createSession: async (document) => treeSitterDiffSyntaxSession(provider, document),\n }\n}\n\nfunction treeSitterDiffSyntaxSession(\n provider: EditorSyntaxProvider,\n document: DiffSyntaxDocument,\n): DiffSyntaxServiceSession | null {\n const session = provider.createSession(syntaxSessionOptions(document))\n if (!session) return null\n\n return {\n dispose: () => session.dispose(),\n refresh: () => session.refresh(document.textSnapshot),\n }\n}\n\nfunction tokenHighlighterDiffSyntaxSession(\n document: DiffSyntaxDocument,\n session: EditorHighlighterSession,\n): DiffSyntaxServiceSession {\n return {\n onDidChangeTheme: session.onDidChangeTheme,\n dispose: () => session.dispose(),\n refresh: async () => {\n const result = await session.refresh(document.textSnapshot)\n return syntaxResultFromTokens(document.request, result.tokens)\n },\n }\n}\n\nfunction syntaxSessionOptions(document: DiffSyntaxDocument): EditorSyntaxSessionOptions {\n return {\n documentId: document.documentId,\n includeCaptures: document.request.language.includeCaptures,\n includeHighlights: document.request.language.includeHighlights,\n languageId: document.languageId,\n snapshot: document.request.snapshot,\n syntaxMode: document.request.language.mode === 'range' ? 'range' : 'full',\n textSnapshot: document.textSnapshot,\n }\n}\n\nfunction highlighterSessionOptions(\n document: DiffSyntaxDocument,\n): Omit<EditorSyntaxSessionOptions, 'includeCaptures' | 'includeHighlights' | 'syntaxMode'> {\n return {\n documentId: document.documentId,\n languageId: document.languageId,\n snapshot: document.request.snapshot,\n textSnapshot: document.textSnapshot,\n }\n}\n\nfunction syntaxResultFromTokens(\n request: EditorSyntaxServiceRequest,\n tokens: EditorTokenInput,\n): EditorSyntaxResult {\n return {\n ...createEmptySyntaxResult({\n language: request.language,\n requestedRanges: request.requestedRanges,\n snapshot: request.snapshotTag,\n }),\n tokens,\n }\n}\n\n/**\n * The two full files, parsed whole.\n *\n * This is the language the diff is highlighted in, and §C11 is the reason it lives here rather than\n * on the editor: the editor's own document is the *interleaved* buffer, and giving that a language\n * feeds a garbage parse into folds, brackets and injections.\n */\nfunction syntaxDocumentsForFile(\n file: DiffFile,\n side: DiffSyntaxSide,\n): readonly DiffSyntaxDocument[] {\n return syntaxSourcesForSide(file, side).map((source) => syntaxDocument(file, source))\n}\n\nfunction syntaxSourcesForSide(file: DiffFile, side: DiffSyntaxSide): readonly DiffSyntaxSource[] {\n if (side === 'stacked') {\n return [syntaxSource(file.oldLines, 'old'), syntaxSource(file.newLines, 'new')]\n }\n\n return [syntaxSource(side === 'old' ? file.oldLines : file.newLines, side)]\n}\n\nfunction syntaxSource(lines: readonly string[], side: DiffSyntaxSourceSide): DiffSyntaxSource {\n const text = lines.join('\\n')\n return {\n lineStarts: lineStartsForLines(lines),\n side,\n text,\n }\n}\n\nfunction syntaxDocument(file: DiffFile, source: DiffSyntaxSource): DiffSyntaxDocument {\n const snapshot = createPieceTableSnapshot(source.text)\n const textSnapshot = createDocumentTextSnapshot(snapshot, source.text)\n const documentId = `${file.path}#diff-${source.side}`\n const languageId = diffSyntaxLanguageId(file)\n const request: EditorSyntaxServiceRequest = {\n editSummary: null,\n language: createSyntaxLanguageConfiguration({\n includeCaptures: true,\n includeHighlights: true,\n languageId,\n mode: 'full',\n }),\n requestedRanges: [{ startIndex: 0, endIndex: snapshot.length }],\n snapshot,\n snapshotTag: createSyntaxSnapshotTag({\n documentId,\n length: snapshot.length,\n version: 0,\n }),\n textSnapshot,\n }\n return { ...source, documentId, languageId, request, textSnapshot }\n}\n\nfunction diffSyntaxLanguageId(file: DiffFile): string | null {\n return file.languageId ?? languageIdForPath(file.path)\n}\n\ntype IndexedTokenSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenStore\n}\n\n/**\n * A row reads its line's tokens by bisection, and rows do not visit source lines in order once\n * expanded regions interleave. The store is sorted whichever producer made the tokens.\n */\nfunction indexTokenSources(\n sources: readonly DiffSyntaxTokenSource[],\n): readonly IndexedTokenSource[] {\n return sources.map((source) => ({\n lineStarts: source.lineStarts,\n side: source.side,\n tokens: toEditorTokenStore(source.tokens),\n }))\n}\n\nfunction tokenSourceForRow(\n sources: readonly IndexedTokenSource[],\n row: DiffRenderRow,\n side: DiffSyntaxSide,\n): IndexedTokenSource | null {\n const sourceSide = sourceSideForRow(row, side)\n return sources.find((source) => source.side === sourceSide) ?? null\n}\n\nfunction appendRowSyntaxTokens(\n projectedTokens: EditorToken[],\n {\n lineStarts,\n row,\n rowOffset,\n side,\n tokens,\n }: {\n readonly lineStarts: readonly number[]\n readonly row: DiffRenderRow\n readonly rowOffset: number\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenStore\n },\n): void {\n const lineNumber = sourceLineNumberForRow(row, side)\n if (lineNumber === undefined) return\n\n const lineStart = lineStarts[lineNumber - 1]\n const nextLineStart = lineStarts[lineNumber]\n if (lineStart === undefined) return\n\n const lineEnd = Math.min(\n nextLineStart === undefined ? Number.POSITIVE_INFINITY : nextLineStart - 1,\n lineStart + row.text.length,\n )\n\n const last = tokens.firstStartingAtOrAfter(lineEnd)\n tokens.forEachInRange(tokens.firstEndingAfter(lineStart, last), last, (start, end, styleId) => {\n const token = { start, end, style: tokens.styles[styleId]! }\n appendProjectedToken(projectedTokens, token, lineStart, lineEnd, rowOffset)\n })\n}\n\nfunction appendProjectedToken(\n projectedTokens: EditorToken[],\n token: EditorToken,\n lineStart: number,\n lineEnd: number,\n rowOffset: number,\n): void {\n if (token.end <= lineStart) return\n if (token.start >= lineEnd) return\n\n const start = Math.max(token.start, lineStart)\n const end = Math.min(token.end, lineEnd)\n if (end <= start) return\n\n projectedTokens.push({\n end: rowOffset + end - lineStart,\n start: rowOffset + start - lineStart,\n style: token.style,\n })\n}\n\nfunction sourceLineNumberForRow(\n row: DiffRenderRow,\n side: DiffSyntaxSourceSide,\n): number | undefined {\n if (side === 'old') return row.oldLineNumber\n return row.newLineNumber\n}\n\nfunction sourceSideForRow(row: DiffRenderRow, side: DiffSyntaxSide): DiffSyntaxSourceSide {\n if (side === 'old' || side === 'new') return side\n if (row.type === 'deletion') return 'old'\n\n return 'new'\n}\n\nfunction lineStartsForLines(lines: readonly string[]): readonly number[] {\n const starts: number[] = []\n let offset = 0\n for (const line of lines) {\n starts.push(offset)\n offset += line.length + 1\n }\n return starts\n}\n\nfunction disposeMutableSessions(sessions: { dispose(): void }[]): void {\n while (sessions.length > 0) sessions.pop()?.dispose()\n}\n"],"mappings":";;;;;AA6BA,IAAI,yBAAyB;;;;;;AAuC7B,IAAa,2BAAb,MAAsC;CAOzB;CACA;CAPX,4BAA6B,IAAI,IAAgB;CACjD,cAAsD,CAAC;CACvD,UAAoC,mBAAmB,CAAC,CAAC;CACzD,WAAmB;CAEnB,YACE,MACA,YACA;EAFS,KAAA,OAAA;EACA,KAAA,aAAA;CACR;CAEH,IAAI,SAA2B;EAC7B,OAAO,KAAK;CACd;;CAGA,kBAAkB,UAAkC;EAClD,KAAK,UAAU,IA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C;CACrE,OAAO,SAAS,SAAS,GAAG,SAAS,IAAI,CAAC,EAAE,QAAQ;AACtD"}
1
+ {"version":3,"file":"diffSyntax.js","names":[],"sources":["../src/diffSyntax.ts"],"sourcesContent":["import type { DocumentTextSnapshot } from '@singapore-editor/core/document'\nimport { createEditorDocumentAnalysis } from '@singapore-editor/core/editor'\nimport type {\n EditorHighlighterProvider,\n EditorHighlighterSession,\n} from '@singapore-editor/core/extensions'\nimport {\n createEmptySyntaxResult,\n createSnippetDocument,\n createSyntaxLanguageConfiguration,\n createSyntaxSnapshotTag,\n type EditorSyntaxProvider,\n type EditorSyntaxResult,\n type EditorSyntaxServiceRequest,\n type EditorToken,\n type EditorTokenInput,\n type EditorTokenStore,\n toEditorTokenStore,\n} from '@singapore-editor/core/syntax'\nimport { EditorSecondaryViewScheduler } from '@singapore-editor/core/secondary-views'\nimport { languageIdForPath } from './lines'\nimport type { DiffFile, DiffRenderRow, DiffSyntaxBackend } from './types'\n\ntype DiffSyntaxSide = 'old' | 'new' | 'stacked'\ntype DiffSyntaxSourceSide = 'old' | 'new'\ntype DiffSnippetLines = Parameters<typeof createSnippetDocument>[1]\n\nlet nextSyntaxControllerId = 0\n\ntype DiffSyntaxTokenSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenInput\n}\n\nexport type ProjectDiffSyntaxTokensOptions = {\n readonly rows: readonly DiffRenderRow[]\n readonly side: DiffSyntaxSide\n readonly sources: readonly DiffSyntaxTokenSource[]\n}\n\nexport type DiffSyntaxControllerOptions = {\n readonly side: DiffSyntaxSide\n readonly backend?: DiffSyntaxBackend\n readonly enabled?: boolean\n /** Fires when a *newly parsed* token stream lands; row-driven re-projection is synchronous. */\n readonly onDidChangeTokens: () => void\n}\n\n/** A disposable interest in one owned or borrowed immutable source stream. */\nexport type DiffSyntaxSourceReader = {\n readonly side: DiffSyntaxSourceSide\n readonly lineStarts: readonly number[]\n readonly tokens: EditorTokenStore\n onDidChangeTokens(listener: () => void): () => void\n dispose(): void\n}\n\n/** Owned streams or borrowed readers, including a preparation still running. */\nexport type PreparedDiffSyntaxInput =\n | readonly DiffSyntaxSourceReader[]\n | Promise<readonly DiffSyntaxSourceReader[]>\n\nexport type PrepareDiffSyntaxOptions = {\n readonly backend?: DiffSyntaxBackend\n /** Which pane the sources are for. `stacked` prepares both source sides. */\n readonly side?: DiffSyntaxSide\n readonly signal?: AbortSignal\n}\n\n/**\n * One source side's parsed token stream and the session that recolours it on a theme change.\n * Its creator owns it and disposes it. A shared owner lends separate DiffSyntaxSourceReader\n * interests, whose disposal releases only that interest.\n */\nexport class PreparedDiffSyntaxSource {\n private readonly listeners = new Set<() => void>()\n private readonly disposables: { dispose(): void }[] = []\n private current: EditorTokenStore = toEditorTokenStore([])\n private disposed = false\n\n constructor(\n readonly side: DiffSyntaxSourceSide,\n readonly lineStarts: readonly number[],\n ) {}\n\n get tokens(): EditorTokenStore {\n return this.current\n }\n\n /** Fires when a theme change recolours the stream. */\n onDidChangeTokens(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.listeners.clear()\n disposeMutableSessions(this.disposables)\n }\n\n /** @internal */\n own(disposable: { dispose(): void }): void {\n this.disposables.push(disposable)\n }\n\n /** @internal */\n setTokens(tokens: EditorTokenInput): void {\n this.current = toEditorTokenStore(tokens)\n }\n\n /** @internal */\n async recolor(session: DiffSyntaxServiceSession): Promise<void> {\n try {\n const result = await session.refresh()\n if (this.disposed) return\n\n this.setTokens(result.tokens)\n for (const listener of this.listeners) listener()\n } catch {\n // Keep the last colors if the worker fails; a subsequent change can retry.\n }\n }\n}\n\n/**\n * Parses a diff's sources ahead of the view that will show them, so `setFile(file, rows, prepared)`\n * paints coloured on its first frame. The caller owns the result; an aborted preparation resolves\n * empty.\n */\nexport async function prepareDiffSyntax(\n file: DiffFile,\n options: PrepareDiffSyntaxOptions = {},\n): Promise<readonly PreparedDiffSyntaxSource[]> {\n if (file.isPartial || options.signal?.aborted) return []\n const created: PreparedDiffSyntaxSource[] = []\n const cancel = () => disposeMutableSessions(created)\n options.signal?.addEventListener('abort', cancel, { once: true })\n const isCurrent = () => options.signal?.aborted !== true\n try {\n const sources = await loadSyntaxSources(\n file,\n options.side ?? 'stacked',\n options.backend,\n isCurrent,\n created,\n )\n if (sources) return sources\n } catch (error) {\n disposeMutableSessions(created)\n throw error\n } finally {\n options.signal?.removeEventListener('abort', cancel)\n }\n\n disposeMutableSessions(created)\n return []\n}\n\n/**\n * The syntax half of the old `DiffView`, with one behavioural change.\n *\n * `DiffView` re-ran the whole pipeline — new sessions, new parse — on every row change, including\n * every expansion toggle (`updatePaneRows` → `refreshSyntaxHighlighting`, DiffView.ts:564). The\n * parse result does not depend on which regions are expanded: the sources are the two *full files*,\n * and expansion only changes which of their lines the projection shows. So the per-side token\n * streams are cached against the file and re-projected synchronously when rows change, which is\n * what lets a toggle repaint without an uncoloured frame (§C10).\n */\nexport class DiffSyntaxController {\n private readonly scheduler = new EditorSecondaryViewScheduler()\n private readonly key = `diff.syntax.${nextSyntaxControllerId++}`\n private sources: readonly DiffSyntaxSourceReader[] = []\n private sourceSubscriptions: (() => void)[] = []\n private indexed: readonly IndexedTokenSource[] = []\n private sourcesFile: DiffFile | null = null\n private file: DiffFile | null = null\n private rows: readonly DiffRenderRow[] = []\n private tokens: readonly EditorToken[] = []\n private disposed = false\n private ready = true\n private generation = 0\n\n constructor(private readonly options: DiffSyntaxControllerOptions) {}\n\n /** A disposed controller is terminal — its scheduler never runs another task. */\n isDisposed(): boolean {\n return this.disposed\n }\n\n isReady(): boolean {\n return this.ready\n }\n\n getTokens(): readonly EditorToken[] {\n return this.tokens\n }\n\n /**\n * New file: drop the cached streams, then adopt `prepared` when it covers this side, or reparse.\n * A preparation still running is awaited instead of parsing the same file twice. Detachment\n * disposes each reader, releasing borrowed interests or owned sessions.\n */\n setFile(\n file: DiffFile | null,\n rows: readonly DiffRenderRow[],\n prepared: PreparedDiffSyntaxInput = [],\n ): void {\n const generation = ++this.generation\n this.file = file\n this.ready = !file || file.isPartial || this.options.enabled === false\n this.rows = rows\n this.tokens = []\n this.disposeSources()\n this.scheduler.cancel(this.key)\n if (this.disposed || !file || this.ready) {\n void Promise.resolve(prepared).then(disposePrepared, () => undefined)\n return\n }\n if (isPromiseLike(prepared)) {\n const settle = (sources: readonly DiffSyntaxSourceReader[]) => {\n if (this.settlePrepared(file, generation, sources)) this.options.onDidChangeTokens()\n }\n void prepared.then(settle, () => settle([]))\n return\n }\n this.settlePrepared(file, generation, prepared)\n }\n\n /** Whether `prepared` was adopted; otherwise it is disposed, and a current file reparses. */\n private settlePrepared(\n file: DiffFile,\n generation: number,\n prepared: readonly DiffSyntaxSourceReader[],\n ): boolean {\n if (this.disposed || this.generation !== generation || this.file !== file || this.ready) {\n disposePrepared(prepared)\n return false\n }\n if (!coversSide(prepared, this.options.side)) {\n disposePrepared(prepared)\n this.load(file)\n return false\n }\n\n this.adoptSources(file, prepared)\n return true\n }\n\n /** Same file, different rows — an expansion toggle. Re-project what is already parsed. */\n setRows(rows: readonly DiffRenderRow[]): void {\n this.rows = rows\n this.reproject()\n }\n\n release(): void {\n this.generation += 1\n this.scheduler.cancel(this.key)\n this.disposeSources()\n this.tokens = []\n this.ready = true\n }\n\n dispose(): void {\n this.disposed = true\n this.scheduler.cancel(this.key)\n this.scheduler.dispose()\n this.disposeSources()\n this.tokens = []\n }\n\n private reproject(): void {\n if (this.indexed.length === 0 || this.sourcesFile !== this.file) {\n this.tokens = []\n return\n }\n\n this.tokens = projectIndexedTokens(this.rows, this.options.side, this.indexed)\n }\n\n private load(file: DiffFile): void {\n if (this.options.enabled === false) return\n\n const created: PreparedDiffSyntaxSource[] = []\n this.scheduler.schedule({\n key: this.key,\n taskClass: 'background-derived',\n priority: 'low',\n tags: { configuration: 'syntax', viewport: this.options.side },\n run: (context) =>\n loadSyntaxSources(\n file,\n this.options.side,\n this.options.backend,\n () => context.isCurrent(),\n created,\n ),\n apply: (sources) => this.applySources(file, sources, created),\n fail: () => {\n disposeMutableSessions(created)\n if (this.file !== file) return\n this.ready = true\n this.options.onDidChangeTokens()\n },\n cancel: () => disposeMutableSessions(created),\n })\n }\n\n private applySources(\n file: DiffFile,\n sources: readonly PreparedDiffSyntaxSource[] | null,\n created: PreparedDiffSyntaxSource[],\n ): void {\n if (this.file !== file) {\n disposeMutableSessions(created)\n return\n }\n\n // Adopted: the task's cancel path must no longer reach them.\n created.length = 0\n this.adoptSources(file, sources ?? [])\n this.options.onDidChangeTokens()\n }\n\n private adoptSources(file: DiffFile, sources: readonly DiffSyntaxSourceReader[]): void {\n this.disposeSources()\n this.sources = sources\n this.sourceSubscriptions = sources.map((source) =>\n source.onDidChangeTokens(() => this.recolor(file)),\n )\n // Indexed here, once per parse. The index depends only on the token streams, and expansion\n // does not change those — so rebuilding it inside every re-projection would be repeated work\n // plus a fresh Map and N arrays of garbage on each toggle.\n this.indexed = indexPreparedSources(sources)\n this.ready = true\n this.sourcesFile = file\n this.reproject()\n }\n\n private recolor(file: DiffFile): void {\n if (this.disposed || this.file !== file) return\n\n this.indexed = indexPreparedSources(this.sources)\n this.reproject()\n this.options.onDidChangeTokens()\n }\n\n private unsubscribeSources(): void {\n for (const unsubscribe of this.sourceSubscriptions) unsubscribe()\n this.sourceSubscriptions = []\n }\n\n private disposeSources(): void {\n this.unsubscribeSources()\n disposePrepared(this.sources)\n this.sources = []\n this.indexed = []\n this.sourcesFile = null\n }\n}\n\nasync function loadSyntaxSources(\n file: DiffFile,\n side: DiffSyntaxSide,\n backend: DiffSyntaxBackend | undefined,\n isCurrent: () => boolean,\n created: PreparedDiffSyntaxSource[],\n): Promise<readonly PreparedDiffSyntaxSource[] | null> {\n const service = diffSyntaxService(diffSyntaxBackend(backend))\n if (!service) return null\n\n // A task cancelled mid-load has already run its cancel callback, so a stale load disposes\n // whatever it created itself: nothing else will.\n const stale = () => {\n disposeMutableSessions(created)\n return null\n }\n const sources: PreparedDiffSyntaxSource[] = []\n for (const document of syntaxDocumentsForFile(file, side, service.lines)) {\n if (!isCurrent()) return stale()\n\n const session = await service.createSession(document)\n if (!session) continue\n\n const source = new PreparedDiffSyntaxSource(document.side, document.lineStarts)\n created.push(source)\n source.own(session)\n if (!isCurrent()) return stale()\n const unsubscribe = session.onDidChangeTheme?.(() => void source.recolor(session))\n if (unsubscribe) source.own({ dispose: unsubscribe })\n const result = await session.refresh()\n if (!isCurrent()) return stale()\n\n source.setTokens(result.tokens)\n sources.push(source)\n }\n\n return sources\n}\n\nfunction disposePrepared(sources: readonly DiffSyntaxSourceReader[]): void {\n for (const source of sources) source.dispose()\n}\n\nfunction isPromiseLike(\n value: PreparedDiffSyntaxInput,\n): value is Promise<readonly DiffSyntaxSourceReader[]> {\n return 'then' in value\n}\n\nfunction coversSide(sources: readonly DiffSyntaxSourceReader[], side: DiffSyntaxSide): boolean {\n const sides = new Set(sources.map((source) => source.side))\n if (side === 'stacked') return sides.size === 2 && sources.length === 2\n return sides.has(side) && sources.length === 1\n}\n\nfunction indexPreparedSources(\n sources: readonly DiffSyntaxSourceReader[],\n): readonly IndexedTokenSource[] {\n return sources.map((source) => ({\n lineStarts: source.lineStarts,\n side: source.side,\n tokens: source.tokens,\n }))\n}\n\nexport function diffSyntaxBackend(backend: DiffSyntaxBackend | undefined): DiffSyntaxBackend {\n return backend ?? { kind: 'tree-sitter' }\n}\n\nexport function projectDiffSyntaxTokens({\n rows,\n side,\n sources,\n}: ProjectDiffSyntaxTokensOptions): readonly EditorToken[] {\n return projectIndexedTokens(rows, side, indexTokenSources(sources))\n}\n\nfunction projectIndexedTokens(\n rows: readonly DiffRenderRow[],\n side: DiffSyntaxSide,\n sources: readonly IndexedTokenSource[],\n): readonly EditorToken[] {\n const projectedTokens: EditorToken[] = []\n let rowOffset = 0\n\n for (const row of rows) {\n const source = tokenSourceForRow(sources, row, side)\n if (source) {\n appendRowSyntaxTokens(projectedTokens, {\n lineStarts: source.lineStarts,\n row,\n rowOffset,\n side: source.side,\n tokens: source.tokens,\n })\n }\n rowOffset += row.text.length + 1\n }\n\n return projectedTokens\n}\n\ntype DiffSyntaxSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly text: string\n}\n\ntype DiffSyntaxDocument = DiffSyntaxSource & {\n readonly documentId: string\n readonly languageId: string | null\n readonly request: EditorSyntaxServiceRequest\n readonly snippet: ReturnType<typeof createSnippetDocument>\n readonly textSnapshot: DocumentTextSnapshot\n}\n\ntype DiffSyntaxService = {\n /** The line model its engine parses with; tokens come back as offsets into the source text. */\n readonly lines: DiffSnippetLines\n createSession(document: DiffSyntaxDocument): Promise<DiffSyntaxServiceSession | null>\n}\n\ntype DiffSyntaxServiceSession = {\n onDidChangeTheme?: EditorHighlighterSession['onDidChangeTheme']\n refresh(): Promise<EditorSyntaxResult>\n dispose(): void\n}\n\nfunction diffSyntaxService(backend: DiffSyntaxBackend): DiffSyntaxService | null {\n if (backend.kind === 'tree-sitter') return treeSitterDiffSyntaxService(backend.provider ?? null)\n return highlighterDiffSyntaxService(backend.provider ?? null)\n}\n\nfunction highlighterDiffSyntaxService(\n provider: EditorHighlighterProvider | null,\n): DiffSyntaxService | null {\n if (!provider) return null\n\n return {\n lines: 'as-submitted',\n createSession: async (document) => highlighterDiffSyntaxSession(provider, document),\n }\n}\n\nfunction highlighterDiffSyntaxSession(\n provider: EditorHighlighterProvider,\n document: DiffSyntaxDocument,\n): DiffSyntaxServiceSession | null {\n const analysis = createEditorDocumentAnalysis({\n buffer: document.snippet.buffer,\n documentId: document.documentId,\n })\n const session = analysis.borrowHighlighter({ provider, languageId: document.languageId })\n if (!session) {\n analysis.dispose()\n return null\n }\n const retained = tokenHighlighterDiffSyntaxSession(document, session)\n return {\n ...retained,\n dispose() {\n retained.dispose()\n analysis.dispose()\n },\n }\n}\n\nfunction treeSitterDiffSyntaxService(\n provider: EditorSyntaxProvider | null,\n): DiffSyntaxService | null {\n if (!provider) return null\n\n return {\n lines: 'as-document',\n createSession: async (document) => treeSitterDiffSyntaxSession(provider, document),\n }\n}\n\nfunction treeSitterDiffSyntaxSession(\n provider: EditorSyntaxProvider,\n document: DiffSyntaxDocument,\n): DiffSyntaxServiceSession | null {\n const analysis = createEditorDocumentAnalysis({\n buffer: document.snippet.buffer,\n documentId: document.documentId,\n })\n const session = analysis.borrowStructural({\n provider,\n includeCaptures: document.request.language.includeCaptures,\n includeHighlights: document.request.language.includeHighlights,\n languageId: document.languageId,\n syntaxMode: document.request.language.mode === 'range' ? 'range' : 'full',\n })\n if (!session) {\n analysis.dispose()\n return null\n }\n\n return {\n dispose: () => {\n session.dispose()\n analysis.dispose()\n },\n refresh: async () => {\n const result = await session.refresh(document.textSnapshot)\n return { ...result, tokens: document.snippet.submittedTokens(result.tokens) }\n },\n }\n}\n\nfunction tokenHighlighterDiffSyntaxSession(\n document: DiffSyntaxDocument,\n session: EditorHighlighterSession,\n): DiffSyntaxServiceSession {\n return {\n onDidChangeTheme: session.onDidChangeTheme,\n dispose: () => session.dispose(),\n refresh: async () => {\n const result = await session.refresh(document.textSnapshot)\n return syntaxResultFromTokens(document.request, result.tokens)\n },\n }\n}\n\nfunction syntaxResultFromTokens(\n request: EditorSyntaxServiceRequest,\n tokens: EditorTokenInput,\n): EditorSyntaxResult {\n return {\n ...createEmptySyntaxResult({\n language: request.language,\n requestedRanges: request.requestedRanges,\n snapshot: request.snapshotTag,\n }),\n tokens,\n }\n}\n\n/**\n * The two full files, parsed whole.\n *\n * This is the language the diff is highlighted in, and §C11 is the reason it lives here rather than\n * on the editor: the editor's own document is the *interleaved* buffer, and giving that a language\n * feeds a garbage parse into folds, brackets and injections.\n */\nfunction syntaxDocumentsForFile(\n file: DiffFile,\n side: DiffSyntaxSide,\n lines: DiffSnippetLines,\n): readonly DiffSyntaxDocument[] {\n if (file.isPartial) return []\n return syntaxSourcesForSide(file, side).map((source) => syntaxDocument(file, source, lines))\n}\n\nfunction syntaxSourcesForSide(file: DiffFile, side: DiffSyntaxSide): readonly DiffSyntaxSource[] {\n if (side === 'stacked') {\n return [syntaxSource(file.oldLines, 'old'), syntaxSource(file.newLines, 'new')]\n }\n\n return [syntaxSource(side === 'old' ? file.oldLines : file.newLines, side)]\n}\n\nfunction syntaxSource(lines: readonly string[], side: DiffSyntaxSourceSide): DiffSyntaxSource {\n const text = lines.join('\\n')\n return {\n lineStarts: lineStartsForLines(lines),\n side,\n text,\n }\n}\n\nfunction syntaxDocument(\n file: DiffFile,\n source: DiffSyntaxSource,\n lines: DiffSnippetLines,\n): DiffSyntaxDocument {\n const snippet = createSnippetDocument(source.text, lines)\n const { snapshot, textSnapshot } = snippet\n const documentId = `${file.path}#diff-${source.side}`\n const languageId = diffSyntaxLanguageId(file)\n const request: EditorSyntaxServiceRequest = {\n editSummary: null,\n language: createSyntaxLanguageConfiguration({\n includeCaptures: true,\n includeHighlights: true,\n languageId,\n mode: 'full',\n }),\n requestedRanges: [{ startIndex: 0, endIndex: snapshot.length }],\n snapshot,\n snapshotTag: createSyntaxSnapshotTag({\n documentId,\n length: snapshot.length,\n version: 0,\n }),\n textSnapshot,\n }\n return { ...source, documentId, languageId, request, snippet, textSnapshot }\n}\n\nfunction diffSyntaxLanguageId(file: DiffFile): string | null {\n return file.languageId ?? languageIdForPath(file.path)\n}\n\ntype IndexedTokenSource = {\n readonly lineStarts: readonly number[]\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenStore\n}\n\n/**\n * A row reads its line's tokens by bisection, and rows do not visit source lines in order once\n * expanded regions interleave. The store is sorted whichever producer made the tokens.\n */\nfunction indexTokenSources(\n sources: readonly DiffSyntaxTokenSource[],\n): readonly IndexedTokenSource[] {\n return sources.map((source) => ({\n lineStarts: source.lineStarts,\n side: source.side,\n tokens: toEditorTokenStore(source.tokens),\n }))\n}\n\nfunction tokenSourceForRow(\n sources: readonly IndexedTokenSource[],\n row: DiffRenderRow,\n side: DiffSyntaxSide,\n): IndexedTokenSource | null {\n const sourceSide = sourceSideForRow(row, side)\n return sources.find((source) => source.side === sourceSide) ?? null\n}\n\nfunction appendRowSyntaxTokens(\n projectedTokens: EditorToken[],\n {\n lineStarts,\n row,\n rowOffset,\n side,\n tokens,\n }: {\n readonly lineStarts: readonly number[]\n readonly row: DiffRenderRow\n readonly rowOffset: number\n readonly side: DiffSyntaxSourceSide\n readonly tokens: EditorTokenStore\n },\n): void {\n const lineNumber = sourceLineNumberForRow(row, side)\n if (lineNumber === undefined) return\n\n const lineStart = lineStarts[lineNumber - 1]\n const nextLineStart = lineStarts[lineNumber]\n if (lineStart === undefined) return\n\n const lineEnd = Math.min(\n nextLineStart === undefined ? Number.POSITIVE_INFINITY : nextLineStart - 1,\n lineStart + row.text.length,\n )\n\n const last = tokens.firstStartingAtOrAfter(lineEnd)\n tokens.forEachInRange(tokens.firstEndingAfter(lineStart, last), last, (start, end, styleId) => {\n const token = { start, end, style: tokens.styles[styleId]! }\n appendProjectedToken(projectedTokens, token, lineStart, lineEnd, rowOffset)\n })\n}\n\nfunction appendProjectedToken(\n projectedTokens: EditorToken[],\n token: EditorToken,\n lineStart: number,\n lineEnd: number,\n rowOffset: number,\n): void {\n if (token.end <= lineStart) return\n if (token.start >= lineEnd) return\n\n const start = Math.max(token.start, lineStart)\n const end = Math.min(token.end, lineEnd)\n if (end <= start) return\n\n projectedTokens.push({\n end: rowOffset + end - lineStart,\n start: rowOffset + start - lineStart,\n style: token.style,\n })\n}\n\nfunction sourceLineNumberForRow(\n row: DiffRenderRow,\n side: DiffSyntaxSourceSide,\n): number | undefined {\n if (side === 'old') return row.oldLineNumber\n return row.newLineNumber\n}\n\nfunction sourceSideForRow(row: DiffRenderRow, side: DiffSyntaxSide): DiffSyntaxSourceSide {\n if (side === 'old' || side === 'new') return side\n if (row.type === 'deletion') return 'old'\n\n return 'new'\n}\n\nfunction lineStartsForLines(lines: readonly string[]): readonly number[] {\n const starts: number[] = []\n let offset = 0\n for (const line of lines) {\n starts.push(offset)\n offset += line.length + 1\n }\n return starts\n}\n\nfunction disposeMutableSessions(sessions: { dispose(): void }[]): void {\n while (sessions.length > 0) sessions.pop()?.dispose()\n}\n"],"mappings":";;;;;AA2BA,IAAI,yBAAyB;;;;;;AAgD7B,IAAa,2BAAb,MAAsC;CAOzB;CACA;CAPX,4BAA6B,IAAI,IAAgB;CACjD,cAAsD,CAAC;CACvD,UAAoC,mBAAmB,CAAC,CAAC;CACzD,WAAmB;CAEnB,YACE,MACA,YACA;EAFS,KAAA,OAAA;EACA,KAAA,aAAA;CACR;CAEH,IAAI,SAA2B;EAC7B,OAAO,KAAK;CACd;;CAGA,kBAAkB,UAAkC;EAClD,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,IAAI,KAAK,UAAU;EAEnB,KAAK,WAAW;EAChB,KAAK,UAAU,MAAM;EACrB,uBAAuB,KAAK,WAAW;CACzC;;CAGA,IAAI,YAAuC;EACzC,KAAK,YAAY,KAAK,UAAU;CAClC;;CAGA,UAAU,QAAgC;EACxC,KAAK,UAAU,mBAAmB,MAAM;CAC1C;;CAGA,MAAM,QAAQ,SAAkD;EAC9D,IAAI;GACF,MAAM,SAAS,MAAM,QAAQ,QAAQ;GACrC,IAAI,KAAK,UAAU;GAEnB,KAAK,UAAU,OAAO,MAAM;GAC5B,KAAK,MAAM,YAAY,KAAK,WAAW,SAAS;EAClD,QAAQ,CAER;CACF;AACF;;;;;;AAOA,eAAsB,kBACpB,MACA,UAAoC,CAAC,GACS;CAC9C,IAAI,KAAK,aAAa,QAAQ,QAAQ,SAAS,OAAO,CAAC;CACvD,MAAM,UAAsC,CAAC;CAC7C,MAAM,eAAe,uBAAuB,OAAO;CACnD,QAAQ,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;CAChE,MAAM,kBAAkB,QAAQ,QAAQ,YAAY;CACpD,IAAI;EACF,MAAM,UAAU,MAAM,kBACpB,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B;CAEA,MAAM,OAAO,OAAO,uBAAuB,OAAO;CAClD,OAAO,eAAe,OAAO,iBAAiB,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK,YAAY;EAE7F,qBAAqB,iBAAiB;GADtB;GAAO;GAAK,OAAO,OAAO,OAAO;EACX,GAAO,WAAW,SAAS,SAAS;CAC5E,CAAC;AACH;AAEA,SAAS,qBACP,iBACA,OACA,WACA,SACA,WACM;CACN,IAAI,MAAM,OAAO,WAAW;CAC5B,IAAI,MAAM,SAAS,SAAS;CAE5B,MAAM,QAAQ,KAAK,IAAI,MAAM,OAAO,SAAS;CAC7C,MAAM,MAAM,KAAK,IAAI,MAAM,KAAK,OAAO;CACvC,IAAI,OAAO,OAAO;CAElB,gBAAgB,KAAK;EACnB,KAAK,YAAY,MAAM;EACvB,OAAO,YAAY,QAAQ;EAC3B,OAAO,MAAM;CACf,CAAC;AACH;AAEA,SAAS,uBACP,KACA,MACoB;CACpB,IAAI,SAAS,OAAO,OAAO,IAAI;CAC/B,OAAO,IAAI;AACb;AAEA,SAAS,iBAAiB,KAAoB,MAA4C;CACxF,IAAI,SAAS,SAAS,SAAS,OAAO,OAAO;CAC7C,IAAI,IAAI,SAAS,YAAY,OAAO;CAEpC,OAAO;AACT;AAEA,SAAS,mBAAmB,OAA6C;CACvE,MAAM,SAAmB,CAAC;CAC1B,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO;EACxB,OAAO,KAAK,MAAM;EAClB,UAAU,KAAK,SAAS;CAC1B;CACA,OAAO;AACT;AAEA,SAAS,uBAAuB,UAAuC;CACrE,OAAO,SAAS,SAAS,GAAG,SAAS,IAAI,CAAC,EAAE,QAAQ;AACtD"}
@@ -1,6 +1,7 @@
1
+ import './style.css';
1
2
  import type { EditorDisposable, EditorPlugin } from '@singapore-editor/core/extensions';
2
3
  import type { EditorToken } from '@singapore-editor/core/syntax';
3
- import { type PreparedDiffSyntaxInput, type PreparedDiffSyntaxSource } from './diffSyntax';
4
+ import { type PreparedDiffSyntaxInput } from './diffSyntax';
4
5
  import { type DiffGutterSide } from './gutters';
5
6
  import { type DiffRegionStore } from './regions';
6
7
  import type { DiffFile, DiffRenderRow, DiffSyntaxBackend, DiffTextFile } from './types';
@@ -29,11 +30,11 @@ export type DiffPlugin = EditorPlugin & {
29
30
  /**
30
31
  * `document` mode: the file to project. The host owns the editor's text — §C3. `prepared`
31
32
  * streams from `prepareDiffSyntax` for this file paint with the first rows, and a preparation
32
- * still running is awaited in place of a second parse; the plugin owns them.
33
+ * still running is awaited in place of a second parse. The plugin disposes each reader interest.
33
34
  */
34
35
  setFile(file: DiffFile | null, prepared?: PreparedDiffSyntaxInput): void;
35
- /** The current file's parsed streams, handed to the caller; empty while a parse is running. */
36
- releasePreparedSyntax(): readonly PreparedDiffSyntaxSource[];
36
+ /** Releases syntax interests while retaining this pane's rows and shared expansion. */
37
+ releaseSyntax(): void;
37
38
  getRows(): readonly DiffRenderRow[];
38
39
  /** Both sides in row order. Cached until the file or expansion state changes. */
39
40
  getStackedRows(): readonly DiffRenderRow[];
@@ -1 +1 @@
1
- {"version":3,"file":"editorDiffPlugin.d.ts","sourceRoot":"","sources":["../src/editorDiffPlugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAIV,gBAAgB,EAGhB,YAAY,EAOb,MAAM,mCAAmC,CAAA;AAE1C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAGhE,OAAO,EAEL,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAA;AACrB,OAAO,EAIL,KAAK,cAAc,EACpB,MAAM,WAAW,CAAA;AAIlB,OAAO,EAAyB,KAAK,eAAe,EAAE,MAAM,WAAW,CAAA;AACvE,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAEvF,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG,SAAS,CAAA;AAEnD,M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AAI,EAAE,QAAQ,GAAG,IAAI,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAA;IACxE,uFAAuF;IACvF,aAAa,IAAI,IAAI,CAAA;IACrB,OAAO,IAAI,SAAS,aAAa,EAAE,CAAA;IACnC,iFAAiF;IACjF,cAAc,IAAI,SAAS,aAAa,EAAE,CAAA;IAC1C;;;OAGG;IACH,aAAa,IAAI,OAAO,CAAA;IACxB,SAAS,IAAI,SAAS,WAAW,EAAE,CAAA;IACnC,eAAe,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,gBAAgB,CAAA;IACvD,iBAAiB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,gBAAgB,CAAA;IACzD,uCAAuC;IACvC,kBAAkB,IAAI,WAAW,CAAC,MAAM,CAAC,CAAA;IACzC,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAE/B,yEAAyE;IACzE,WAAW,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,GAAG,IAAI,CAAA;IAC5C,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;CACnC,CAAA;AAED,2FAA2F;AAC3F,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,IAAI,EAAE,SAAS,aAAa,EAAE,CAAA;CACxC,CAAA;AAMD,4FAA4F;AAC5F,wBAAgB,cAAc,CAAC,KAAK,EAAE,UAAU,GAAG,UAAU,GAAG,IAAI,CAQnE;AAaD;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAsBvE"}
@@ -7,8 +7,9 @@ import { createLiveDiffProjection } from "./liveProjection.js";
7
7
  import { createTextDiff } from "./model.js";
8
8
  import { createSplitProjection, createStackedProjection } from "./projection.js";
9
9
  import { createDiffRegionStore } from "./regions.js";
10
+ import "./style.css";
10
11
  import { EDITOR_SNIPPET_TOKENS_FEATURE } from "@singapore-editor/core/extensions";
11
- //#region src/editorDiffPlugin.ts
12
+ // src/editorDiffPlugin.ts
12
13
  var viewsByScrollElement = /* @__PURE__ */ new WeakMap();
13
14
  /** `null` outside a `document`-mode diff pane, or over something that is not a diff row. */
14
15
  function diffRowAtEvent(event) {
@@ -46,7 +47,7 @@ function createDiffPlugin(options) {
46
47
  return runtime.activate(context);
47
48
  },
48
49
  setFile: (file, prepared) => runtime.setFile(file, prepared),
49
- releasePreparedSyntax: () => runtime.releasePreparedSyntax(),
50
+ releaseSyntax: () => runtime.releaseSyntax(),
50
51
  getRows: () => runtime.getRows(),
51
52
  getStackedRows: () => runtime.getStackedRows(),
52
53
  getTokens: () => runtime.getTokens(),
@@ -131,8 +132,8 @@ var DiffPluginRuntime = class {
131
132
  this.syntax.setFile(file, this.rows, prepared);
132
133
  this.notifyRows();
133
134
  }
134
- releasePreparedSyntax() {
135
- return this.syntax.release();
135
+ releaseSyntax() {
136
+ this.syntax.release();
136
137
  }
137
138
  getRows() {
138
139
  if (this.mode === "overlay") return this.liveProjection.rows;
@@ -479,7 +480,7 @@ var DiffViewContribution = class {
479
480
  * Every click count, not just the first: a second press would select a word of the label, a
480
481
  * third its line and a fourth the whole document.
481
482
  */
482
- claimSeparatorPress = (event) => event.button === 0 && this.hunkRowAt(event) !== null;
483
+ claimSeparatorPress = (event) => (!("button" in event) || event.button === 0) && this.hunkRowAt(event) !== null;
483
484
  /** The keyboard half of the same rule: arrow keys step over a separator. */
484
485
  isSeparatorRow = (bufferRow) => {
485
486
  if (this.options.mode !== "document" || !this.options.hasHunkRows()) return false;
@@ -520,7 +521,9 @@ var DiffViewContribution = class {
520
521
  /** Only `document` mode has an answer: there a buffer row is an index into `getRows()`. */
521
522
  rowHitAt(event) {
522
523
  if (this.options.mode !== "document") return null;
523
- const hit = this.context.rowAtPoint(event.clientX, event.clientY);
524
+ const point = "touches" in event ? event.touches[0] : event;
525
+ if (!point) return null;
526
+ const hit = this.context.rowAtPoint(point.clientX, point.clientY);
524
527
  if (hit?.source !== "document") return null;
525
528
  const rowIndex = hit.bufferRow;
526
529
  const rows = this.options.getRows();
@@ -540,7 +543,6 @@ function snippetTokenSource(backend) {
540
543
  if (backend?.kind === "highlighter") return { highlighter: backend.provider };
541
544
  return { syntax: backend?.provider };
542
545
  }
543
- //#endregion
544
546
  export { createDiffPlugin, diffRowAtEvent };
545
547
 
546
548
  //# sourceMappingURL=editorDiffPlugin.js.map