@ovvi/git 1.10.18 → 1.10.19

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,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../node_modules/@pierre/diffs/src/utils/getThemes.ts", "../node_modules/@pierre/diffs/src/highlighter/themes/areThemesAttached.ts", "../node_modules/@pierre/diffs/src/highlighter/shared_highlighter.ts", "../node_modules/@pierre/diffs/src/managers/UniversalRenderingManager.ts", "../node_modules/@pierre/diffs/src/utils/areObjectsEqual.ts", "../node_modules/@pierre/diffs/src/utils/areThemesEqual.ts", "../node_modules/@pierre/diffs/src/utils/areOptionsEqual.ts", "../node_modules/@pierre/diffs/src/utils/areSelectionsEqual.ts", "../node_modules/@pierre/diffs/src/utils/createWindowFromScrollPosition.ts", "../node_modules/@pierre/diffs/src/utils/createGutterUtilityElement.ts", "../node_modules/@pierre/diffs/src/utils/areSelectionPointsEqual.ts", "../node_modules/@pierre/diffs/src/utils/isGutterUtilityPath.ts", "../node_modules/@pierre/diffs/src/managers/InteractionManager.ts", "../node_modules/@pierre/diffs/src/managers/ResizeManager.ts", "../node_modules/@pierre/diffs/src/highlighter/languages/areLanguagesAttached.ts", "../node_modules/@pierre/diffs/src/utils/areRenderRangesEqual.ts", "../node_modules/@pierre/diffs/src/utils/createAnnotationElement.ts", "../node_modules/@pierre/diffs/src/utils/getIconForType.ts", "../node_modules/@pierre/diffs/src/utils/createFileHeaderElement.ts", "../node_modules/@pierre/diffs/src/utils/createPreElement.ts", "../node_modules/@pierre/diffs/src/utils/getFiletypeFromFileName.ts", "../node_modules/@pierre/diffs/src/utils/getHighlighterOptions.ts", "../node_modules/@pierre/diffs/src/utils/getLineAnnotationName.ts", "../node_modules/@pierre/diffs/src/utils/isDefaultRenderRange.ts", "../node_modules/@pierre/theming/src/modules/color.ts", "../node_modules/@pierre/theming/src/modules/normalizeThemeColors.ts", "../node_modules/@pierre/diffs/src/utils/getHighlighterThemeStyles.ts", "../node_modules/@pierre/diffs/src/utils/getTokenOptions.ts", "../node_modules/@pierre/diffs/src/utils/resolvePreferredHighlighter.ts", "../node_modules/@pierre/diffs/src/utils/includesFileAnnotations.ts", "../node_modules/@pierre/diffs/src/utils/applyLineTextWithNewline.ts", "../node_modules/@pierre/diffs/src/utils/createContentColumn.ts", "../node_modules/@pierre/diffs/src/sprite.ts", "../node_modules/@pierre/diffs/src/utils/arePrePropertiesEqual.ts", "../node_modules/@pierre/diffs/src/utils/createAnnotationWrapperNode.ts", "../node_modules/@pierre/diffs/src/utils/createGutterUtilityContentNode.ts", "../node_modules/@pierre/diffs/src/utils/createUnsafeCSSStyleNode.ts", "../node_modules/@pierre/diffs/src/style.css", "../node_modules/@pierre/diffs/src/utils/scrollbarGutter.ts", "../node_modules/@pierre/diffs/src/utils/cssWrappers.ts", "../node_modules/@pierre/diffs/src/utils/lineAnnotationIdentity.ts", "../node_modules/@pierre/diffs/src/utils/getOrCreateCodeNode.ts", "../node_modules/@pierre/diffs/src/utils/prerenderHTMLIfNecessary.ts", "../node_modules/@pierre/diffs/src/utils/setWrapperNodeProps.ts", "../node_modules/@pierre/diffs/src/utils/isStyleNode.ts", "../node_modules/@pierre/diffs/src/utils/platform.ts", "../node_modules/@pierre/diffs/src/utils/editSessionAnnotations.ts", "../node_modules/@pierre/diffs/src/utils/shouldUseTokenTransformer.ts", "../node_modules/@pierre/diffs/src/utils/guardWebKitScrollDuringRebuild.ts", "../node_modules/@pierre/diffs/src/utils/hostTheme.ts", "../node_modules/@pierre/diffs/src/worker/errors.ts", "../node_modules/@pierre/diffs/src/components/web-components.ts", "../node_modules/@pierre/diffs/src/utils/computeVirtualFileMetrics.ts", "../node_modules/@pierre/diffs/src/utils/areDiffTargetsEqual.ts", "../node_modules/@pierre/diffs/src/utils/areFilesEqual.ts", "../node_modules/@pierre/diffs/src/utils/cloneFileDiffMetadata.ts", "../node_modules/@pierre/diffs/src/utils/getHunkSideBoundaries.ts", "../node_modules/@pierre/diffs/src/utils/composeCacheKey.ts", "../node_modules/@pierre/diffs/src/utils/splitFileContents.ts", "../node_modules/@pierre/diffs/src/utils/hydratePartialDiff.ts", "../node_modules/@pierre/diffs/src/utils/cleanLastNewline.ts", "../node_modules/@pierre/diffs/src/utils/detachString.ts", "../node_modules/@pierre/diffs/src/utils/parseQuotedDiffFileName.ts", "../node_modules/@pierre/diffs/src/utils/realignChangeContent.ts", "../node_modules/@pierre/diffs/src/utils/parsePatchFiles.ts", "../node_modules/diff/libesm/diff/base.js", "../node_modules/diff/libesm/diff/character.js", "../node_modules/diff/libesm/util/string.js", "../node_modules/diff/libesm/diff/word.js", "../node_modules/diff/libesm/diff/line.js", "../node_modules/diff/libesm/patch/create.js", "../node_modules/@pierre/diffs/src/utils/parseDiffFromFile.ts", "../node_modules/@pierre/diffs/src/managers/ScrollSyncManager.ts", "../node_modules/@pierre/diffs/src/utils/areDiffRenderOptionsEqual.ts", "../node_modules/@pierre/diffs/src/utils/createEmptyRowBuffer.ts", "../node_modules/@pierre/diffs/src/utils/createNoNewlineElement.ts", "../node_modules/@pierre/diffs/src/utils/createSeparator.ts", "../node_modules/@pierre/diffs/src/utils/getHunkSeparatorSlotName.ts", "../node_modules/@pierre/diffs/src/utils/getTotalLineCountFromHunks.ts", "../node_modules/@pierre/diffs/src/utils/parseDiffDecorations.ts", "../node_modules/@pierre/diffs/src/utils/virtualDiffLayout.ts", "../node_modules/@pierre/diffs/src/utils/iterateOverDiff.ts", "../node_modules/@pierre/diffs/src/utils/renderDiffWithHighlighter.ts", "../node_modules/@pierre/diffs/src/utils/updateDiffHunks.ts", "../node_modules/@pierre/diffs/src/utils/editSessionHunks.ts", "../node_modules/@pierre/diffs/src/utils/isDiffPlainText.ts", "../node_modules/@pierre/diffs/src/renderers/DiffHunksRenderer.ts", "../node_modules/@pierre/diffs/src/utils/areDiffLineAnnotationsEqual.ts", "../node_modules/@pierre/diffs/src/utils/areHunkDataEqual.ts", "../node_modules/@pierre/diffs/src/utils/awaitWithTimeout.ts", "../node_modules/@pierre/diffs/src/utils/getDiffFileInput.ts", "../node_modules/@pierre/diffs/src/utils/getDiffHunksRendererOptions.ts", "../node_modules/@pierre/diffs/src/components/FileDiff.ts", "../node_modules/@pierre/diffs/src/utils/computeEstimatedDiffHeights.ts", "../node_modules/@pierre/diffs/src/components/VirtualizedFileDiff.ts", "../node_modules/@pierre/diffs/src/utils/areVirtualWindowSpecsEqual.ts", "../node_modules/@pierre/diffs/src/components/Virtualizer.ts", "../src/diff.ts"],
4
- "sourcesContent": ["import { DEFAULT_THEMES } from '../constants';\nimport type { DiffsThemeNames, ThemesType } from '../types';\n\nexport function getThemes(\n theme: DiffsThemeNames | ThemesType = DEFAULT_THEMES\n): DiffsThemeNames[] {\n const themesArr: DiffsThemeNames[] = [];\n if (typeof theme === 'string') {\n themesArr.push(theme);\n } else {\n themesArr.push(theme.dark);\n themesArr.push(theme.light);\n }\n return themesArr;\n}\n", "import type {\n DiffsHighlighter,\n DiffsThemeNames,\n HighlighterTypes,\n ThemesType,\n} from '../../types';\nimport { getThemes } from '../../utils/getThemes';\nimport { resolveHighlighterType } from '../highlighterType';\nimport { createDiffsThemeResolver } from './themeResolver';\n\nexport function areThemesAttached(\n themes: DiffsThemeNames | ThemesType,\n highlighter: DiffsHighlighter | HighlighterTypes = resolveHighlighterType()\n): boolean {\n // Shared resolvers can retain themes after an instance is disposed.\n if (typeof highlighter !== 'string' && highlighter.isDisposed) {\n return false;\n }\n const resolver =\n typeof highlighter === 'string'\n ? createDiffsThemeResolver(highlighter)\n : highlighter.themeResolver;\n return resolver.hasResolvedThemes(getThemes(themes));\n}\n", "import type {\n DiffsHighlighter,\n DiffsThemeNames,\n HighlighterTypes,\n SupportedLanguages,\n ThemesType,\n} from '../types';\nimport {\n acquireHighlighterType,\n getHighlighterType,\n HighlighterDisposedError,\n releaseHighlighterType,\n resolveHighlighterType,\n} from './highlighterType';\nimport { cleanUpResolvedLanguages } from './languages/cleanUpResolvedLanguages';\nimport { areThemesAttached } from './themes/areThemesAttached';\nimport { cleanUpResolvedThemes } from './themes/cleanUpResolvedThemes';\n\nexport {\n getHighlighterType,\n HighlighterDisposedError,\n} from './highlighterType';\n\nlet highlighter: DiffsHighlighter | Promise<DiffsHighlighter> | undefined;\n\nexport interface HighlighterOptions {\n themes: DiffsThemeNames[];\n langs: SupportedLanguages[];\n preferredHighlighter?: HighlighterTypes;\n}\n\n/**\n * Creates an instance the caller must dispose. Defaults to the active type\n * or DEFAULT_HIGHLIGHTER; rejects if a different type is already active.\n */\nexport async function createHighlighter(\n type?: HighlighterTypes\n): Promise<DiffsHighlighter> {\n const resolvedType = resolveHighlighterType(type);\n // Reserve the type before importing to prevent concurrent backend loads.\n acquireHighlighterType(resolvedType);\n try {\n if (resolvedType === 'highlights') {\n const { HighlightsHighlighter } = await import('./backends/highlights');\n return new HighlightsHighlighter();\n }\n const { ShikiHighlighter } = await import('./backends/shiki');\n return await ShikiHighlighter.create(resolvedType);\n } finally {\n releaseHighlighterType();\n }\n}\n\nexport async function getSharedHighlighter({\n themes,\n langs,\n preferredHighlighter,\n}: HighlighterOptions): Promise<DiffsHighlighter> {\n dropDisposedHighlighter();\n const cached = (highlighter ??= createHighlighter(\n getHighlighterType() ?? preferredHighlighter\n ));\n let instance: DiffsHighlighter;\n try {\n instance = await cached;\n } catch (error) {\n // Allow retries without clearing a newer request.\n if (highlighter === cached) {\n highlighter = undefined;\n }\n throw error;\n }\n if (highlighter === cached) {\n highlighter = instance;\n }\n await Promise.all([\n instance.themeResolver.resolveThemes(themes),\n instance.loadLanguages(langs),\n ]);\n // disposeHighlighter() may run while themes and languages load.\n if (instance.isDisposed) {\n throw new HighlighterDisposedError();\n }\n return instance;\n}\n\n// Direct dispose() calls leave the shared reference pointing to a dead instance.\nfunction dropDisposedHighlighter(): void {\n if (\n highlighter != null &&\n !('then' in highlighter) &&\n highlighter.isDisposed\n ) {\n highlighter = undefined;\n }\n}\n\nexport function isHighlighterLoaded(): boolean {\n dropDisposedHighlighter();\n return highlighter != null && !('then' in highlighter);\n}\n\ninterface GetHighlighterIfLoadedProps {\n theme?: DiffsThemeNames | ThemesType;\n lang?: SupportedLanguages;\n langs?: SupportedLanguages[];\n}\n\n/**\n * Returns undefined if the theme or language is not loaded.\n */\nexport function getHighlighterIfLoaded({\n theme,\n lang,\n langs,\n}: GetHighlighterIfLoadedProps = {}): DiffsHighlighter | undefined {\n dropDisposedHighlighter();\n const instance = highlighter;\n if (\n instance == null ||\n 'then' in instance ||\n (theme != null && !areThemesAttached(theme, instance)) ||\n ((lang != null || langs != null) &&\n !instance.hasLoadedLanguages([\n ...(lang != null ? [lang] : []),\n ...(langs ?? []),\n ]))\n ) {\n return undefined;\n }\n return instance;\n}\n\nexport function isHighlighterLoading(): boolean {\n return highlighter != null && 'then' in highlighter;\n}\n\nexport function isHighlighterNull(): boolean {\n dropDisposedHighlighter();\n return highlighter == null;\n}\n\nexport async function preloadHighlighter(\n options: HighlighterOptions\n): Promise<void> {\n await getSharedHighlighter(options);\n}\n\n/**\n * Disposes an already loaded shared instance synchronously and clears caches.\n * Instances from createHighlighter() must be disposed separately before\n * switching types.\n */\nexport async function disposeHighlighter(): Promise<void> {\n const cached = highlighter;\n highlighter = undefined;\n cleanUpResolvedLanguages();\n cleanUpResolvedThemes();\n if (cached != null && 'then' in cached) {\n // A failed initialization has nothing to dispose.\n (await cached.catch(() => undefined))?.dispose();\n } else {\n cached?.dispose();\n }\n}\n", "type Callback = (time: number) => unknown;\n\nconst callbacks = new Set<Callback>();\nlet frameId: null | number = null;\n\n// TODO(amadeus): Figure out a proper name for this module...\nexport function queueRender(callback: Callback): void {\n callbacks.add(callback);\n frameId ??= requestAnimationFrame(render);\n}\n\nexport function dequeueRender(callback: Callback): void {\n if (callbacks.delete(callback) && callbacks.size === 0 && frameId != null) {\n cancelAnimationFrame(frameId);\n frameId = null;\n }\n}\n\n// Drops every queued callback and cancels the pending frame. The guard\n// matters in test teardown, where the harness may have already removed the\n// requestAnimationFrame globals.\nexport function clearRenderQueue(): void {\n callbacks.clear();\n if (frameId != null && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(frameId);\n }\n frameId = null;\n}\n\nfunction render(time: number): void {\n const toIterate = new Set(callbacks);\n callbacks.clear();\n for (const callback of toIterate) {\n try {\n callback(time);\n } catch (error) {\n console.error(error);\n }\n }\n // If render picked up any new callbacks, lets trigger a new\n // requestAnimationFrame\n if (callbacks.size > 0) {\n frameId = requestAnimationFrame(render);\n } else {\n frameId = null;\n }\n}\n", "export function areObjectsEqual<T extends object>(\n objA: T | undefined,\n objB: T | undefined,\n omitKeys?: (keyof T)[]\n): boolean {\n // Lets get out of here early if they are the same or either is undefined\n if (objA === objB || objA == null || objB == null) {\n return objA === objB;\n }\n\n // Convert array to Set for O(1) lookup\n const omitSet = new Set(omitKeys);\n const keysA = Object.keys(objA) as (keyof T)[];\n const keysBSet = new Set(Object.keys(objB) as (keyof T)[]);\n\n // Compare keys from objA\n for (const key of keysA) {\n keysBSet.delete(key);\n if (omitSet.has(key)) {\n continue;\n }\n\n if (!(key in objB) || objA[key] !== objB[key]) {\n return false;\n }\n }\n\n // If we got any remaining keys that aren't omitted in objB,\n // then we gotta return false\n for (const key of Array.from(keysBSet)) {\n if (!omitSet.has(key)) {\n return false;\n }\n }\n\n return true;\n}\n", "import type { DiffsThemeNames, ThemesType } from '../types';\n\nexport function areThemesEqual(\n themeA: DiffsThemeNames | ThemesType | undefined,\n themeB: DiffsThemeNames | ThemesType | undefined\n): boolean {\n if (\n themeA == null ||\n themeB == null ||\n typeof themeA === 'string' ||\n typeof themeB === 'string'\n ) {\n return themeA === themeB;\n }\n return themeA.dark === themeB.dark && themeA.light === themeB.light;\n}\n", "import type { CreatePatchOptionsNonabortable } from 'diff';\n\nimport type { CodeViewOptions } from '../components/CodeView';\nimport type { FileDiffOptions } from '../components/FileDiff';\nimport { DEFAULT_THEMES } from '../constants';\nimport type { FileOptions } from '../react';\nimport { areObjectsEqual } from './areObjectsEqual';\nimport { areThemesEqual } from './areThemesEqual';\n\ntype AnyOptions<L, C> =\n | CodeViewOptions<L, C>\n | FileOptions<L, C>\n | FileDiffOptions<L, C>\n | undefined;\n\nexport function areOptionsEqual<LAnnotation, Caret>(\n optionsA: AnyOptions<LAnnotation, Caret>,\n optionsB: AnyOptions<LAnnotation, Caret>\n): boolean {\n const themeA = optionsA?.theme ?? DEFAULT_THEMES;\n const themeB = optionsB?.theme ?? DEFAULT_THEMES;\n const diffOptsA = getParseDiffOptions(optionsA);\n const diffOptsB = getParseDiffOptions(optionsB);\n return (\n areThemesEqual(themeA, themeB) &&\n areObjectsEqual(optionsA, optionsB, [\n 'theme',\n 'parseDiffOptions' as keyof typeof optionsA,\n ]) &&\n areObjectsEqual(diffOptsA, diffOptsB)\n );\n}\n\nfunction getParseDiffOptions<L, C>(\n options: AnyOptions<L, C>\n): CreatePatchOptionsNonabortable | undefined {\n if (options != null && 'parseDiffOptions' in options) {\n return options.parseDiffOptions;\n }\n return undefined;\n}\n", "import type { SelectedLineRange } from '../types';\n\nexport function areSelectionsEqual(\n selectionA: SelectedLineRange | undefined,\n selectionB: SelectedLineRange | undefined\n): boolean {\n return (\n selectionA?.start === selectionB?.start &&\n selectionA?.end === selectionB?.end &&\n selectionA?.side === selectionB?.side &&\n selectionA?.endSide === selectionB?.endSide\n );\n}\n", "import type { VirtualWindowSpecs } from '../types';\n\ninterface WindowFromScrollPositionProps {\n scrollTop: number;\n height: number;\n scrollHeight: number;\n fitPerfectly?: boolean;\n fitPerfectlyOverscroll?: number;\n overscrollSize: number;\n}\n\nexport function createWindowFromScrollPosition({\n scrollTop,\n scrollHeight,\n height,\n fitPerfectly = false,\n fitPerfectlyOverscroll = 0,\n overscrollSize,\n}: WindowFromScrollPositionProps): VirtualWindowSpecs {\n const windowHeight = height + overscrollSize * 2;\n const effectiveHeight = fitPerfectly\n ? height + fitPerfectlyOverscroll * 2\n : windowHeight;\n scrollHeight = Math.max(scrollHeight, effectiveHeight);\n\n if (windowHeight >= scrollHeight || fitPerfectly) {\n const top = Math.max(scrollTop - fitPerfectlyOverscroll, 0);\n const bottom = Math.min(scrollTop + effectiveHeight, scrollHeight);\n return {\n top,\n bottom: Math.max(bottom, top),\n };\n }\n\n const scrollCenter = scrollTop + height / 2;\n let top = scrollCenter - windowHeight / 2;\n let bottom = top + windowHeight;\n if (top < 0) {\n top = 0;\n }\n if (bottom > scrollHeight) {\n bottom = scrollHeight;\n }\n top = Math.floor(Math.max(top, 0));\n return {\n top,\n bottom: Math.ceil(Math.max(Math.min(bottom, scrollHeight), top)),\n };\n}\n", "import type { Element as HASTElement } from 'hast';\n\nimport { createHastElement, createIconElement } from './hast_utils';\n\nexport function createGutterUtilityElement(): HASTElement {\n return createHastElement({\n tagName: 'button',\n properties: { 'data-utility-button': '', type: 'button' },\n children: [\n createIconElement({\n name: 'diffs-icon-plus',\n properties: { 'data-icon': '' },\n }),\n ],\n });\n}\n", "import type { SelectionPoint } from '../types';\n\nexport function areSelectionPointsEqual(\n a: SelectionPoint,\n b: SelectionPoint\n): boolean {\n return a.lineNumber === b.lineNumber && a.side === b.side;\n}\n", "// Recognize both the built-in utility button and custom content assigned to the\n// gutter utility slot so other pointer handlers leave the gesture untouched.\nexport function isGutterUtilityPath(\n path: readonly (EventTarget | undefined)[]\n): boolean {\n for (const element of path) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n if (\n element.hasAttribute('data-utility-button') ||\n element.hasAttribute('data-gutter-utility-slot') ||\n element.getAttribute('slot') === 'gutter-utility-slot' ||\n element.getAttribute('name') === 'gutter-utility-slot'\n ) {\n return true;\n }\n }\n return false;\n}\n", "import type {\n AnnotationSide,\n DiffLineEventBaseProps,\n DiffTokenEventBaseProps,\n ExpansionDirections,\n LineEventBaseProps,\n LineTypes,\n MergeConflictResolution,\n SelectedLineRange,\n SelectionPoint,\n SelectionSide,\n TokenEventBase,\n} from '../types';\nimport { areSelectionPointsEqual } from '../utils/areSelectionPointsEqual';\nimport { areSelectionsEqual } from '../utils/areSelectionsEqual';\nimport { createGutterUtilityElement } from '../utils/createGutterUtilityElement';\nimport { hastToHtml } from '../utils/hastToHtml';\nimport { isGutterUtilityPath } from '../utils/isGutterUtilityPath';\nimport { dequeueRender, queueRender } from './UniversalRenderingManager';\n\ninterface TokenCache {\n tokenElement: HTMLElement;\n lineCharStart: number;\n lineCharEnd: number;\n tokenText: string;\n}\n\ninterface ExpandCache {\n hunkIndex: number | undefined;\n direction: ExpansionDirections;\n all: boolean;\n}\n\nexport type LogTypes = 'click' | 'move' | 'both' | 'none';\n\nexport type InteractionManagerMode = 'file' | 'diff';\n\nexport interface OnLineClickProps extends LineEventBaseProps {\n event: PointerEvent;\n}\n\nexport interface OnLineEnterLeaveProps extends LineEventBaseProps {\n event: PointerEvent;\n}\n\nexport interface OnDiffLineClickProps extends DiffLineEventBaseProps {\n event: PointerEvent;\n}\n\nexport interface OnDiffLineEnterLeaveProps extends DiffLineEventBaseProps {\n event: PointerEvent;\n}\n\nexport interface SelectionWriteOptions {\n notify?: boolean;\n // Limit the selected-line highlight to one side's column of a split diff.\n // It has no effect on unified or single-file views, whose one code column\n // carries no side attribute.\n activeLineSide?: SelectionSide;\n // Highlight only the gutter line number, not the line background.\n lineNumberOnly?: boolean;\n}\n\ninterface EditorActiveLineWriteOptions {\n lineNumberOnly?: boolean;\n side?: SelectionSide;\n}\n\nexport type GetLineIndexUtility = (\n lineNumber: number,\n side?: SelectionSide\n) => [number, number] | undefined;\n\ntype EventClickProps<TMode extends InteractionManagerMode> =\n TMode extends 'file' ? OnLineClickProps : OnDiffLineClickProps;\n\ntype PointerEventEnterLeaveProps<TMode extends InteractionManagerMode> =\n TMode extends 'file' ? OnLineEnterLeaveProps : OnDiffLineEnterLeaveProps;\n\ntype EventBaseProps<TMode extends InteractionManagerMode> = TMode extends 'file'\n ? LineEventBaseProps\n : DiffLineEventBaseProps;\n\nexport type OnTokenEventProps<TMode extends InteractionManagerMode> =\n TMode extends 'file' ? TokenEventBase : DiffTokenEventBaseProps;\n\ninterface ExpandoEventProps {\n type: 'line-info';\n hunkIndex: number;\n direction: ExpansionDirections;\n all: boolean;\n}\n\nexport type GetHoveredLineResult<TMode extends InteractionManagerMode> =\n TMode extends 'file'\n ? { lineNumber: number }\n : { lineNumber: number; side: AnnotationSide };\n\ninterface SelectionInfo {\n lineNumber: number;\n eventSide: SelectionSide | undefined;\n lineIndex: number;\n}\n\ntype SelectionHitSource = 'event-path' | 'coordinates-first';\n\ninterface SelectionHitOptions {\n source: SelectionHitSource;\n excludeUtility?: boolean;\n}\n\ninterface SelectionInfoOptions extends SelectionHitOptions {\n requireNumberColumn: boolean;\n}\n\ninterface SelectionEnds {\n top: SelectionPoint;\n bottom: SelectionPoint;\n}\n\ninterface LineRenderState {\n range: SelectedLineRange | null;\n highlightSide: SelectionSide | undefined;\n lineNumberOnly: boolean;\n}\n\ninterface SelectionRenderState {\n selectedLines: LineRenderState;\n editorActiveLine: LineRenderState;\n}\n\ninterface LineRenderColumn {\n content: HTMLElement;\n gutter: HTMLElement;\n renderEditorActiveLine: boolean;\n renderSelectedLines: boolean;\n}\n\ninterface ResolvedLineTarget<TMode extends InteractionManagerMode> {\n kind: 'line';\n lineType: LineTypes;\n lineElement: HTMLElement;\n lineNumber: number;\n numberColumn: boolean;\n numberElement: HTMLElement;\n side: TMode extends 'diff' ? AnnotationSide : undefined;\n splitLineIndex: number | undefined;\n}\n\ninterface ResolvedTokenTarget<TMode extends InteractionManagerMode> {\n kind: 'token';\n lineType: LineTypes;\n lineElement: HTMLElement;\n lineNumber: number;\n numberColumn: boolean;\n numberElement: HTMLElement;\n side: TMode extends 'diff' ? AnnotationSide : undefined;\n splitLineIndex: number | undefined;\n tokenElement: HTMLElement;\n tokenText: string;\n lineCharStart: number;\n lineCharEnd: number;\n}\n\nexport interface MergeConflictActionTarget {\n kind: 'merge-conflict-action';\n resolution: MergeConflictResolution;\n conflictIndex: number;\n}\n\ntype ResolvedPointerTarget<TMode extends InteractionManagerMode> =\n | ResolvedLineTarget<TMode>\n | ResolvedTokenTarget<TMode>\n | ExpandoEventProps\n | MergeConflictActionTarget;\n\ntype LinePointerTarget<TMode extends InteractionManagerMode> =\n ResolvedLineTarget<TMode>;\n\ntype TokenPointerTarget<TMode extends InteractionManagerMode> =\n ResolvedTokenTarget<TMode>;\n\ntype HoverableLinePointerTarget<TMode extends InteractionManagerMode> =\n | LinePointerTarget<TMode>\n | TokenPointerTarget<TMode>;\n\ninterface SessionIdle {\n mode: 'idle';\n}\n\ninterface SessionSelecting {\n mode: 'selecting';\n pointerId: number;\n}\n\ninterface SessionPendingSingleLineUnselect {\n mode: 'pendingSingleLineUnselect';\n pointerId: number;\n anchor: SelectionPoint;\n pending: SelectionPoint;\n}\n\ninterface SessionGutterSelecting {\n mode: 'gutterSelecting';\n pointerId: number;\n anchor: SelectionPoint;\n current: SelectionPoint;\n}\n\ntype PointerSession =\n | SessionIdle\n | SessionSelecting\n | SessionPendingSingleLineUnselect\n | SessionGutterSelecting;\n\nexport interface InteractionManagerBaseOptions<\n TMode extends InteractionManagerMode,\n> {\n lineHoverHighlight?: 'disabled' | 'both' | 'number' | 'line';\n enableTokenInteractionsOnWhitespace?: boolean;\n enableGutterUtility?: boolean;\n onGutterUtilityClick?(range: SelectedLineRange): unknown;\n onLineClick?(props: EventClickProps<TMode>): unknown;\n onLineNumberClick?(props: EventClickProps<TMode>): unknown;\n onLineEnter?(props: PointerEventEnterLeaveProps<TMode>): unknown;\n onLineLeave?(props: PointerEventEnterLeaveProps<TMode>): unknown;\n onTokenClick?(props: OnTokenEventProps<TMode>, event: MouseEvent): unknown;\n onTokenEnter?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;\n onTokenLeave?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;\n __debugPointerEvents?: LogTypes;\n enableLineSelection?: boolean;\n controlledSelection?: boolean;\n onLineSelected?: (range: SelectedLineRange | null) => void;\n onLineSelectionStart?: (range: SelectedLineRange | null) => void;\n onLineSelectionChange?: (range: SelectedLineRange | null) => void;\n onLineSelectionEnd?: (range: SelectedLineRange | null) => void;\n getLineIndex?: GetLineIndexUtility;\n}\n\nexport interface InteractionManagerOptions<\n TMode extends InteractionManagerMode,\n> extends InteractionManagerBaseOptions<TMode> {\n usesCustomGutterUtility?: boolean;\n onHunkExpand?(\n hunkIndex: number,\n direction: ExpansionDirections,\n expansionLineCountOverride?: number\n ): unknown;\n onMergeConflictActionClick?(target: MergeConflictActionTarget): void;\n}\n\ninterface HandlePointerEventProps {\n eventType: 'click' | 'move';\n event: PointerEvent | MouseEvent;\n}\n\nexport class InteractionManager<TMode extends InteractionManagerMode> {\n private hoveredLine: EventBaseProps<TMode> | undefined;\n private hoveredToken: OnTokenEventProps<TMode> | undefined;\n private pre: HTMLPreElement | undefined;\n\n private gutterUtilityLine: EventBaseProps<TMode> | undefined;\n private gutterUtilityContainer: HTMLDivElement | undefined;\n private gutterUtilityButton: HTMLButtonElement | undefined;\n private gutterUtilitySlot: HTMLSlotElement | undefined;\n\n private interactiveLinesAttr = false;\n private interactiveLineNumbersAttr = false;\n\n private hasPointerListeners = false;\n private hasDocumentPointerListeners = false;\n\n private selectedRange: SelectedLineRange | null = null;\n private selectedRangeHighlightSide: SelectionSide | undefined;\n private selectedRangeLineNumberOnly = false;\n // Editor caret highlights are retained separately so selected lines and the\n // cursor line can render without overwriting each other.\n private editorActiveLine: number | null = null;\n private editorActiveLineSide: SelectionSide | undefined;\n private editorLineNumberOnly = false;\n private proposedSelectedRange: SelectedLineRange | null | undefined;\n private renderedSelectedLinesState: LineRenderState | undefined;\n private renderedEditorActiveLineState: LineRenderState | undefined;\n private selectionAnchor: SelectionPoint | undefined;\n private pointerSession: PointerSession = { mode: 'idle' };\n\n constructor(\n private mode: TMode,\n private options: InteractionManagerOptions<TMode>\n ) {}\n\n setOptions(options: InteractionManagerOptions<TMode>): void {\n this.options = options;\n }\n\n cleanUp(): void {\n this.pre?.removeEventListener('click', this.handlePointerClick);\n this.pre?.removeEventListener('pointerdown', this.handlePointerDown);\n this.pre?.removeEventListener('pointermove', this.handlePointerMove);\n this.pre?.removeEventListener('pointerleave', this.handlePointerLeave);\n this.pre?.removeAttribute('data-interactive-lines');\n this.pre?.removeAttribute('data-interactive-line-numbers');\n this.pre = undefined;\n this.gutterUtilityContainer?.remove();\n this.gutterUtilityLine = undefined;\n this.gutterUtilityContainer = undefined;\n this.gutterUtilityButton = undefined;\n this.gutterUtilitySlot = undefined;\n this.clearHoveredLine();\n this.clearHoveredToken();\n this.detachDocumentPointerListeners();\n this.clearPointerSession();\n dequeueRender(this.renderSelection);\n this.interactiveLinesAttr = false;\n this.interactiveLineNumbersAttr = false;\n this.hasPointerListeners = false;\n this.setSelectionDirty();\n }\n\n setup(pre: HTMLPreElement): void {\n this.setSelectionDirty();\n const { usesCustomGutterUtility = false, enableGutterUtility = false } =\n this.options;\n\n const newContainer = this.pre !== pre;\n if (newContainer) {\n this.cleanUp();\n this.pre = pre;\n }\n\n if (enableGutterUtility) {\n this.ensureGutterUtilityNode(usesCustomGutterUtility);\n } else if (this.gutterUtilityContainer != null) {\n this.gutterUtilityContainer.remove();\n this.gutterUtilityLine = undefined;\n this.gutterUtilityContainer = undefined;\n this.gutterUtilityButton = undefined;\n this.gutterUtilitySlot = undefined;\n if (this.pointerSession.mode === 'gutterSelecting') {\n this.clearPointerSession();\n this.detachDocumentPointerListeners();\n }\n }\n\n this.syncPointerListeners(pre);\n this.updateInteractiveLineAttributes();\n this.renderSelection();\n this.placeUtility();\n }\n\n setSelectionDirty(): void {\n this.renderedSelectedLinesState = undefined;\n this.renderedEditorActiveLineState = undefined;\n }\n\n isSelectionDirty(): boolean {\n return (\n this.renderedSelectedLinesState === undefined ||\n this.renderedEditorActiveLineState === undefined\n );\n }\n\n setSelection(\n range: SelectedLineRange | null,\n options?: SelectionWriteOptions\n ): void {\n const isRangeChange = !(\n range === this.selectedRange ||\n areSelectionsEqual(range ?? undefined, this.selectedRange ?? undefined)\n );\n const lineNumberOnly = options?.lineNumberOnly ?? false;\n const isStyleChange =\n options?.activeLineSide !== this.selectedRangeHighlightSide ||\n lineNumberOnly !== this.selectedRangeLineNumberOnly;\n if (!this.isSelectionDirty() && !isRangeChange && !isStyleChange) {\n return;\n }\n this.proposedSelectedRange = undefined;\n this.selectedRange = range;\n this.selectedRangeHighlightSide = options?.activeLineSide;\n this.selectedRangeLineNumberOnly = lineNumberOnly;\n this.renderSelection();\n this.placeUtility();\n if (isRangeChange && options?.notify !== false) {\n this.notifySelectionCommitted(range);\n }\n }\n\n // Update the editor caret decoration without changing selected lines,\n // callbacks, or gutter utility placement.\n setEditorActiveLine(\n lineNumber: number | null,\n { lineNumberOnly = false, side }: EditorActiveLineWriteOptions = {}\n ): void {\n const isLineChange = lineNumber !== this.editorActiveLine;\n const isStyleChange =\n side !== this.editorActiveLineSide ||\n lineNumberOnly !== this.editorLineNumberOnly;\n if (!this.isSelectionDirty() && !isLineChange && !isStyleChange) {\n return;\n }\n this.editorActiveLine = lineNumber;\n this.editorActiveLineSide = side;\n this.editorLineNumberOnly = lineNumberOnly;\n this.renderSelection();\n }\n\n getSelection(): SelectedLineRange | null {\n return this.selectedRange;\n }\n\n getHoveredLine = (): GetHoveredLineResult<TMode> | undefined => {\n const gutterUtilityLine = this.gutterUtilityLine ?? this.hoveredLine;\n if (gutterUtilityLine != null) {\n if (this.mode === 'diff' && gutterUtilityLine.type === 'diff-line') {\n return {\n lineNumber: gutterUtilityLine.lineNumber,\n side: gutterUtilityLine.annotationSide,\n } as GetHoveredLineResult<TMode>;\n }\n if (this.mode === 'file' && gutterUtilityLine.type === 'line') {\n return {\n lineNumber: gutterUtilityLine.lineNumber,\n } as GetHoveredLineResult<TMode>;\n }\n }\n return undefined;\n };\n\n handlePointerClick = (event: MouseEvent): void => {\n const {\n onHunkExpand,\n onLineClick,\n onLineNumberClick,\n onTokenClick,\n onMergeConflictActionClick,\n } = this.options;\n if (\n onHunkExpand == null &&\n onLineClick == null &&\n onLineNumberClick == null &&\n onMergeConflictActionClick == null &&\n onTokenClick == null\n ) {\n return;\n }\n if (\n this.options.onGutterUtilityClick != null &&\n isGutterUtilityPath(event.composedPath())\n ) {\n return;\n }\n debugLogIfEnabled(\n this.options.__debugPointerEvents,\n 'click',\n 'FileDiff.DEBUG.handlePointerClick:',\n event\n );\n this.handlePointerEvent({ eventType: 'click', event });\n };\n\n handlePointerMove = (event: PointerEvent): void => {\n // Touch and pen moves are active drag/scroll gestures, not hover. Keeping\n // hover mouse-only prevents content scrolls from leaving stale utilities.\n if (event.pointerType !== 'mouse') {\n return;\n }\n\n const {\n lineHoverHighlight = 'disabled',\n onLineEnter,\n onLineLeave,\n onTokenEnter,\n onTokenLeave,\n enableGutterUtility = false,\n } = this.options;\n if (\n lineHoverHighlight === 'disabled' &&\n !enableGutterUtility &&\n onLineEnter == null &&\n onLineLeave == null &&\n onTokenEnter == null &&\n onTokenLeave == null\n ) {\n return;\n }\n debugLogIfEnabled(\n this.options.__debugPointerEvents,\n 'move',\n 'FileDiff.DEBUG.handlePointerMove:',\n event\n );\n // should we perhaps throttle this a bit because move can be fast as fuk\n // boiiii\n this.handlePointerEvent({ eventType: 'move', event });\n };\n\n handlePointerLeave = (event: PointerEvent): void => {\n const { __debugPointerEvents } = this.options;\n debugLogIfEnabled(\n __debugPointerEvents,\n 'move',\n 'FileDiff.DEBUG.handlePointerLeave: no event'\n );\n if (this.hoveredLine == null && this.hoveredToken == null) {\n debugLogIfEnabled(\n __debugPointerEvents,\n 'move',\n 'FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token'\n );\n return;\n }\n if (this.hoveredToken != null) {\n this.options.onTokenLeave?.(this.hoveredToken, event);\n this.clearHoveredToken();\n }\n\n if (this.hoveredLine != null) {\n this.options.onLineLeave?.({\n ...this.hoveredLine,\n event,\n } as PointerEventEnterLeaveProps<TMode>);\n this.clearHoveredLine();\n }\n this.placeUtility();\n };\n\n private handlePointerEvent({ eventType, event }: HandlePointerEventProps) {\n const { __debugPointerEvents } = this.options;\n const composedPath = event.composedPath();\n debugLogIfEnabled(\n __debugPointerEvents,\n eventType,\n 'FileDiff.DEBUG.handlePointerEvent:',\n { eventType, composedPath }\n );\n const target = this.resolvePointerTarget(composedPath);\n debugLogIfEnabled(\n __debugPointerEvents,\n eventType,\n 'FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:',\n target\n );\n\n const {\n onLineClick,\n onLineNumberClick,\n onLineEnter,\n onLineLeave,\n onTokenClick,\n onTokenEnter,\n onTokenLeave,\n onHunkExpand,\n onMergeConflictActionClick,\n } = this.options;\n\n switch (eventType) {\n case 'move': {\n const sameLine =\n isHoverableLinePointerTarget(target) &&\n this.hoveredLine?.lineElement === target.lineElement;\n const sameToken =\n isTokenPointerTarget(target) &&\n this.hoveredToken?.tokenElement === target.tokenElement;\n\n // Handle token transitions\n if (!sameToken) {\n if (this.hoveredToken != null) {\n onTokenLeave?.(this.hoveredToken, event as PointerEvent);\n this.clearHoveredToken();\n }\n if (isTokenPointerTarget(target)) {\n this.setHoveredToken(this.toTokenEventBaseProps(target));\n onTokenEnter?.(\n this.hoveredToken as OnTokenEventProps<TMode>,\n event as PointerEvent\n );\n }\n }\n\n // Handle line transitions\n if (!sameLine) {\n if (this.hoveredLine != null) {\n onLineLeave?.({\n ...this.hoveredLine,\n event: event as PointerEvent,\n } as PointerEventEnterLeaveProps<TMode>);\n this.clearHoveredLine();\n }\n if (isHoverableLinePointerTarget(target)) {\n this.setHoveredLine(this.toEventBaseProps(target));\n this.placeUtility();\n onLineEnter?.({\n ...this.hoveredLine,\n event: event as PointerEvent,\n } as PointerEventEnterLeaveProps<TMode>);\n } else {\n this.placeUtility();\n }\n }\n break;\n }\n case 'click': {\n if (target == null) {\n break;\n }\n if (\n isMergeConflictActionPointerTarget(target) &&\n onMergeConflictActionClick != null\n ) {\n onMergeConflictActionClick(target);\n break;\n }\n if (isExpandoPointerTarget(target) && onHunkExpand != null) {\n onHunkExpand(\n target.hunkIndex,\n target.all || event.shiftKey ? 'both' : target.direction,\n target.all || event.shiftKey ? Number.POSITIVE_INFINITY : undefined\n );\n break;\n }\n\n if (!isHoverableLinePointerTarget(target)) {\n break;\n }\n\n if (isTokenPointerTarget(target) && onTokenClick != null) {\n onTokenClick(this.toTokenEventBaseProps(target), event);\n }\n\n const eventBase = this.toEventBaseProps(target);\n if (onLineNumberClick != null && target.numberColumn) {\n onLineNumberClick({\n ...eventBase,\n event: event as PointerEvent,\n } as EventClickProps<TMode>);\n } else if (onLineClick != null) {\n onLineClick({\n ...eventBase,\n event: event as PointerEvent,\n } as EventClickProps<TMode>);\n }\n break;\n }\n }\n }\n\n private syncPointerListeners(pre: HTMLPreElement): void {\n const {\n __debugPointerEvents,\n lineHoverHighlight = 'disabled',\n onLineClick,\n onLineNumberClick,\n onLineEnter,\n onLineLeave,\n onTokenClick,\n onTokenEnter,\n onTokenLeave,\n onHunkExpand,\n onMergeConflictActionClick,\n enableGutterUtility = false,\n enableLineSelection = false,\n onGutterUtilityClick,\n } = this.options;\n const enableGutterSelection = onGutterUtilityClick != null;\n const shouldAttachPointerListeners =\n lineHoverHighlight !== 'disabled' ||\n onLineClick != null ||\n onLineNumberClick != null ||\n onLineEnter != null ||\n onLineLeave != null ||\n onTokenClick != null ||\n onTokenEnter != null ||\n onTokenLeave != null ||\n onHunkExpand != null ||\n onMergeConflictActionClick != null ||\n enableGutterUtility ||\n enableLineSelection ||\n enableGutterSelection;\n\n if (shouldAttachPointerListeners && !this.hasPointerListeners) {\n pre.addEventListener('click', this.handlePointerClick);\n pre.addEventListener('pointerdown', this.handlePointerDown);\n pre.addEventListener('pointermove', this.handlePointerMove);\n pre.addEventListener('pointerleave', this.handlePointerLeave);\n this.hasPointerListeners = true;\n\n debugLogIfEnabled(\n __debugPointerEvents,\n 'click',\n 'FileDiff.DEBUG.attachEventListeners: Attaching click events for:',\n (() => {\n const reasons: string[] = [];\n if (\n __debugPointerEvents === 'both' ||\n __debugPointerEvents === 'click'\n ) {\n if (onLineClick != null) {\n reasons.push('onLineClick');\n }\n if (onLineNumberClick != null) {\n reasons.push('onLineNumberClick');\n }\n if (onHunkExpand != null) {\n reasons.push('expandable hunk separators');\n }\n if (onMergeConflictActionClick != null) {\n reasons.push('merge conflict actions');\n }\n }\n return reasons;\n })()\n );\n debugLogIfEnabled(\n __debugPointerEvents,\n 'move',\n 'FileDiff.DEBUG.attachEventListeners: Attaching pointer move event'\n );\n debugLogIfEnabled(\n __debugPointerEvents,\n 'move',\n 'FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event'\n );\n } else if (!shouldAttachPointerListeners && this.hasPointerListeners) {\n pre.removeEventListener('click', this.handlePointerClick);\n pre.removeEventListener('pointerdown', this.handlePointerDown);\n pre.removeEventListener('pointermove', this.handlePointerMove);\n pre.removeEventListener('pointerleave', this.handlePointerLeave);\n this.hasPointerListeners = false;\n }\n\n const hasActiveLineSelectionSession =\n this.pointerSession.mode === 'selecting' ||\n this.pointerSession.mode === 'pendingSingleLineUnselect';\n const hasActiveGutterSelectionSession =\n this.pointerSession.mode === 'gutterSelecting';\n if (\n (!enableLineSelection && hasActiveLineSelectionSession) ||\n (!enableGutterSelection && hasActiveGutterSelectionSession)\n ) {\n this.clearPointerSession();\n this.detachDocumentPointerListeners();\n this.selectionAnchor = undefined;\n this.clearPendingSingleLineState();\n }\n }\n\n private updateInteractiveLineAttributes(): void {\n if (this.pre == null) {\n return;\n }\n\n const {\n onLineClick,\n onLineNumberClick,\n enableLineSelection = false,\n } = this.options;\n\n const shouldHaveInteractiveLines = onLineClick != null;\n const shouldHaveInteractiveLineNumbers =\n onLineNumberClick != null || enableLineSelection;\n\n if (shouldHaveInteractiveLines && !this.interactiveLinesAttr) {\n this.pre.setAttribute('data-interactive-lines', '');\n this.interactiveLinesAttr = true;\n } else if (!shouldHaveInteractiveLines && this.interactiveLinesAttr) {\n this.pre.removeAttribute('data-interactive-lines');\n this.interactiveLinesAttr = false;\n }\n\n if (shouldHaveInteractiveLineNumbers && !this.interactiveLineNumbersAttr) {\n this.pre.setAttribute('data-interactive-line-numbers', '');\n this.interactiveLineNumbersAttr = true;\n } else if (\n !shouldHaveInteractiveLineNumbers &&\n this.interactiveLineNumbersAttr\n ) {\n this.pre.removeAttribute('data-interactive-line-numbers');\n this.interactiveLineNumbersAttr = false;\n }\n }\n\n private handlePointerDown = (event: PointerEvent): void => {\n if (\n (event.pointerType === 'mouse' && event.button !== 0) ||\n this.pre == null ||\n this.pointerSession.mode !== 'idle'\n ) {\n return;\n }\n\n const path = event.composedPath();\n if (\n isGutterUtilityPath(path) &&\n this.options.onGutterUtilityClick != null\n ) {\n this.startGutterSelectionFromPointerDown(event);\n } else {\n if (event.pointerType !== 'mouse') {\n this.revealUtilityFromGutterPath(path);\n }\n this.startLineSelectionFromPointerDown(event);\n }\n };\n\n private startLineSelectionFromPointerDown(event: PointerEvent): void {\n const { enableLineSelection = false } = this.options;\n if (!enableLineSelection) {\n return;\n }\n\n const pointerInfo = this.resolveSelectionInfo(event, {\n source: 'event-path',\n requireNumberColumn: true,\n });\n if (pointerInfo == null) {\n return;\n }\n\n const { pre } = this;\n if (pre == null) {\n return;\n }\n\n // Intentionally no preventDefault here. The line-number gutter uses\n // `user-select: none`, so a drag that starts on it never begins a native\n // text selection. Calling preventDefault would also cancel the browser's\n // native focus change, which stops a focusable host wrapper from receiving\n // focus (and the keyboard events it needs) when a line number is clicked.\n const { lineNumber, eventSide, lineIndex } = pointerInfo;\n\n if (event.shiftKey && this.selectedRange != null) {\n const rowRange = this.getIndexesFromSelection(\n this.selectedRange,\n pre.getAttribute('data-diff-type') === 'split'\n );\n if (rowRange == null) {\n return;\n }\n const useStart =\n rowRange.start <= rowRange.end\n ? lineIndex >= rowRange.start\n : lineIndex <= rowRange.end;\n this.selectionAnchor = {\n lineNumber: useStart\n ? this.selectedRange.start\n : this.selectedRange.end,\n side: useStart\n ? this.selectedRange.side\n : (this.selectedRange.endSide ?? this.selectedRange.side),\n };\n this.updateSelection(lineNumber, eventSide, false);\n this.notifySelectionStart(this.getCurrentSelectionRange());\n this.pointerSession = { mode: 'selecting', pointerId: event.pointerId };\n this.attachDocumentPointerListeners();\n return;\n }\n\n if (\n this.selectedRange?.start === lineNumber &&\n this.selectedRange?.end === lineNumber\n ) {\n const point = { lineNumber, side: eventSide };\n this.selectionAnchor = point;\n this.pointerSession = {\n mode: 'pendingSingleLineUnselect',\n pointerId: event.pointerId,\n anchor: point,\n pending: point,\n };\n this.attachDocumentPointerListeners();\n return;\n }\n\n if (this.options.controlledSelection === true) {\n this.proposedSelectedRange = null;\n } else {\n this.selectedRange = null;\n }\n this.placeUtility();\n this.selectionAnchor = { lineNumber, side: eventSide };\n this.updateSelection(lineNumber, eventSide, false);\n this.notifySelectionStart(this.getCurrentSelectionRange());\n this.pointerSession = { mode: 'selecting', pointerId: event.pointerId };\n this.attachDocumentPointerListeners();\n }\n\n private startGutterSelectionFromPointerDown(event: PointerEvent): void {\n const { onGutterUtilityClick } = this.options;\n if (onGutterUtilityClick == null) {\n return;\n }\n // If a selection already exists, the utility represents that whole range.\n // Dragging should start from the visual top and extend from the visual\n // bottom, regardless of the direction the range was originally created.\n const selectedEndpoints = this.currentSelectionEnds();\n const point =\n selectedEndpoints?.bottom ??\n this.resolveSelectionPoint(event, {\n source: 'event-path',\n excludeUtility: false,\n });\n const anchor = selectedEndpoints?.top ?? point;\n if (point == null || anchor == null) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n this.pointerSession = {\n mode: 'gutterSelecting',\n pointerId: event.pointerId,\n anchor,\n current: point,\n };\n this.selectionAnchor = {\n lineNumber: anchor.lineNumber,\n side: anchor.side,\n };\n this.updateSelection(point.lineNumber, point.side, false);\n this.notifySelectionStart(this.getCurrentSelectionRange());\n this.attachDocumentPointerListeners();\n }\n\n private handleDocumentPointerMove = (event: PointerEvent): void => {\n switch (this.pointerSession.mode) {\n case 'idle':\n return;\n case 'gutterSelecting': {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n event.preventDefault();\n const point = this.resolveSelectionPoint(event, {\n source: 'coordinates-first',\n });\n if (point == null) {\n return;\n }\n this.pointerSession.current = point;\n this.updateSelection(point.lineNumber, point.side);\n return;\n }\n case 'selecting': {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n event.preventDefault();\n const pointerInfo = this.resolveSelectionInfo(event, {\n source: 'coordinates-first',\n requireNumberColumn: false,\n });\n if (pointerInfo == null || this.selectionAnchor == null) {\n return;\n }\n this.updateSelection(pointerInfo.lineNumber, pointerInfo.eventSide);\n return;\n }\n case 'pendingSingleLineUnselect': {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n event.preventDefault();\n const pointerInfo = this.resolveSelectionInfo(event, {\n source: 'coordinates-first',\n requireNumberColumn: false,\n });\n if (pointerInfo == null || this.selectionAnchor == null) {\n return;\n }\n const point = {\n lineNumber: pointerInfo.lineNumber,\n side: pointerInfo.eventSide,\n };\n if (areSelectionPointsEqual(this.pointerSession.pending, point)) {\n return;\n }\n this.updateSelection(\n pointerInfo.lineNumber,\n pointerInfo.eventSide,\n false\n );\n this.notifySelectionStart(this.getCurrentSelectionRange());\n this.notifySelectionChangeDelta();\n this.pointerSession = {\n mode: 'selecting',\n pointerId: event.pointerId,\n };\n return;\n }\n }\n };\n\n private handleDocumentPointerUp = (event: PointerEvent): void => {\n const { onGutterUtilityClick } = this.options;\n switch (this.pointerSession.mode) {\n case 'idle':\n return;\n case 'gutterSelecting': {\n const { pointerSession: session } = this;\n if (event.pointerId !== session.pointerId) {\n return;\n }\n event.preventDefault();\n const point = this.resolveSelectionPoint(event, {\n source: 'coordinates-first',\n });\n if (point != null) {\n session.current = point;\n this.updateSelection(point.lineNumber, point.side);\n }\n // Keep the completed gesture stable when callbacks synchronously\n // replace the manager's controlled or uncontrolled selection.\n const completedRange = this.buildSelectedLineRange(\n session.anchor,\n session.current\n );\n onGutterUtilityClick?.({ ...completedRange });\n this.selectionAnchor = undefined;\n this.notifySelectionEnd(completedRange);\n this.notifySelectionCommitted(completedRange);\n this.clearProposedSelection();\n this.clearPointerSession();\n this.detachDocumentPointerListeners();\n return;\n }\n case 'pendingSingleLineUnselect': {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n event.preventDefault();\n this.updateSelection(null, undefined, false);\n this.selectionAnchor = undefined;\n this.clearPendingSingleLineState();\n this.detachDocumentPointerListeners();\n this.notifySelectionEnd(this.getCurrentSelectionRange());\n this.notifySelectionCommitted(this.getCurrentSelectionRange());\n this.clearProposedSelection();\n return;\n }\n case 'selecting': {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n event.preventDefault();\n this.selectionAnchor = undefined;\n this.detachDocumentPointerListeners();\n this.clearPointerSession();\n this.notifySelectionEnd(this.getCurrentSelectionRange());\n this.notifySelectionCommitted(this.getCurrentSelectionRange());\n this.clearProposedSelection();\n }\n }\n };\n\n private handleDocumentPointerCancel = (event: PointerEvent): void => {\n switch (this.pointerSession.mode) {\n case 'idle':\n return;\n case 'gutterSelecting':\n case 'selecting':\n case 'pendingSingleLineUnselect': {\n if ('pointerId' in this.pointerSession) {\n if (event.pointerId !== this.pointerSession.pointerId) {\n return;\n }\n }\n this.selectionAnchor = undefined;\n this.clearProposedSelection();\n this.clearPendingSingleLineState();\n this.clearPointerSession();\n this.detachDocumentPointerListeners();\n }\n }\n };\n\n private clearHoveredLine() {\n if (this.hoveredLine == null) {\n return;\n }\n this.hoveredLine.lineElement.removeAttribute('data-hovered');\n this.hoveredLine.numberElement.removeAttribute('data-hovered');\n this.hoveredLine = undefined;\n }\n\n private setHoveredLine(hoveredLine: EventBaseProps<TMode>) {\n const { lineHoverHighlight = 'disabled' } = this.options;\n if (this.hoveredLine != null) {\n this.clearHoveredLine();\n }\n this.hoveredLine = hoveredLine;\n if (lineHoverHighlight !== 'disabled') {\n if (lineHoverHighlight === 'both' || lineHoverHighlight === 'line') {\n this.hoveredLine.lineElement.setAttribute('data-hovered', '');\n }\n if (lineHoverHighlight === 'both' || lineHoverHighlight === 'number') {\n this.hoveredLine.numberElement.setAttribute('data-hovered', '');\n }\n }\n }\n\n private clearHoveredToken() {\n if (this.hoveredToken == null) {\n return;\n }\n this.hoveredToken = undefined;\n }\n\n private setHoveredToken(hoveredToken: OnTokenEventProps<TMode>) {\n if (this.hoveredToken != null) {\n this.clearHoveredToken();\n }\n this.hoveredToken = hoveredToken;\n }\n\n private ensureGutterUtilityNode(useCustomGutterUtility: boolean): void {\n if (this.gutterUtilityContainer == null) {\n this.gutterUtilityContainer = document.createElement('div');\n this.gutterUtilityContainer.setAttribute('data-gutter-utility-slot', '');\n }\n if (useCustomGutterUtility) {\n if (this.gutterUtilityButton != null) {\n this.gutterUtilityButton.remove();\n this.gutterUtilityButton = undefined;\n }\n if (this.gutterUtilitySlot == null) {\n this.gutterUtilitySlot = document.createElement('slot');\n this.gutterUtilitySlot.name = 'gutter-utility-slot';\n }\n if (this.gutterUtilitySlot.parentNode !== this.gutterUtilityContainer) {\n this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);\n }\n } else {\n this.gutterUtilitySlot?.remove();\n this.gutterUtilitySlot = undefined;\n if (this.gutterUtilityButton == null) {\n const tempDiv = document.createElement('div');\n tempDiv.innerHTML = hastToHtml(createGutterUtilityElement());\n const utilityButton = tempDiv.firstElementChild;\n if (!(utilityButton instanceof HTMLButtonElement)) {\n throw new Error(\n 'InteractionManager.ensureGutterUtilityNode: Node element should be a button'\n );\n }\n utilityButton.remove();\n this.gutterUtilityButton = utilityButton;\n }\n if (this.gutterUtilityButton.parentNode !== this.gutterUtilityContainer) {\n this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton);\n }\n }\n }\n\n private revealUtilityFromGutterPath(path: (EventTarget | undefined)[]): void {\n if (this.placeUtilityFromSelection()) {\n return;\n }\n const target = this.resolvePointerTarget(path);\n if (isLinePointerTarget(target) && target.numberColumn) {\n this.showUtilityOnLine(this.toEventBaseProps(target));\n }\n }\n\n // The gutter utility follows the active selection first because a selected\n // range is more stable than transient hover/touch state. Without a\n // selection, desktop hover and mobile tap reveal can still place it on a\n // single row.\n private placeUtility(): void {\n if (this.placeUtilityFromSelection()) {\n return;\n }\n if (this.hoveredLine != null) {\n this.showUtilityOnLine(this.hoveredLine);\n return;\n }\n this.hideUtility();\n }\n\n private placeUtilityFromSelection(): boolean {\n const endpoints = this.currentSelectionEnds();\n if (endpoints == null) {\n return false;\n }\n const target = this.targetForSelectionPoint(endpoints.bottom);\n if (target == null) {\n this.hideUtility();\n } else {\n this.showUtilityOnLine(this.toEventBaseProps(target));\n }\n return true;\n }\n\n private showUtilityOnLine(line: EventBaseProps<TMode>): void {\n if (this.gutterUtilityContainer == null) {\n return;\n }\n this.gutterUtilityLine = line;\n line.numberElement.appendChild(this.gutterUtilityContainer);\n }\n\n private hideUtility(): void {\n this.gutterUtilityContainer?.remove();\n this.gutterUtilityLine = undefined;\n }\n\n // Selection ranges preserve drag direction, so compare rendered row indexes to\n // find the visually top-most and bottom-most endpoints.\n private currentSelectionEnds(): SelectionEnds | undefined {\n const range = this.getCurrentSelectionRange();\n return range == null ? undefined : this.selectionEnds(range);\n }\n\n private selectionEnds(range: SelectedLineRange): SelectionEnds | undefined {\n const start: SelectionPoint = {\n lineNumber: range.start,\n side: range.side,\n };\n const end: SelectionPoint = {\n lineNumber: range.end,\n side: range.endSide ?? range.side,\n };\n const startIndex = this.selectionPointRowIndex(start);\n const endIndex = this.selectionPointRowIndex(end);\n if (startIndex == null || endIndex == null) {\n return undefined;\n }\n return startIndex > endIndex\n ? { top: end, bottom: start }\n : { top: start, bottom: end };\n }\n\n private selectionPointRowIndex(point: SelectionPoint): number | undefined {\n const indexes = this.getLineIndex(point.lineNumber, point.side);\n if (indexes == null) {\n return undefined;\n }\n return this.isSplitDiff() ? indexes[1] : indexes[0];\n }\n\n private targetForSelectionPoint(\n point: SelectionPoint\n ): LinePointerTarget<TMode> | undefined {\n if (this.pre == null) {\n return undefined;\n }\n const indexes = this.getLineIndex(point.lineNumber, point.side);\n if (indexes == null) {\n return undefined;\n }\n const lineIndex =\n this.mode === 'diff' ? `${indexes[0]},${indexes[1]}` : `${indexes[0]}`;\n // Rebuild the real gutter-row target from the selection point so the\n // utility can anchor to the visible row even when the point came from\n // controlled state rather than a pointer event.\n const candidates = this.pre.querySelectorAll(\n `[data-column-number=\"${point.lineNumber}\"][data-line-index=\"${lineIndex}\"]`\n );\n for (const element of candidates) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n const target = this.resolvePointerTarget(getElementPath(element));\n if (!isLinePointerTarget(target)) {\n continue;\n }\n if (\n this.mode === 'diff' &&\n point.side != null &&\n target.side !== point.side\n ) {\n continue;\n }\n return target;\n }\n return undefined;\n }\n\n private attachDocumentPointerListeners(): void {\n if (this.hasDocumentPointerListeners) {\n return;\n }\n document.addEventListener('pointermove', this.handleDocumentPointerMove);\n document.addEventListener('pointerup', this.handleDocumentPointerUp);\n document.addEventListener(\n 'pointercancel',\n this.handleDocumentPointerCancel\n );\n this.hasDocumentPointerListeners = true;\n }\n\n private detachDocumentPointerListeners(): void {\n if (!this.hasDocumentPointerListeners) {\n return;\n }\n document.removeEventListener('pointermove', this.handleDocumentPointerMove);\n document.removeEventListener('pointerup', this.handleDocumentPointerUp);\n document.removeEventListener(\n 'pointercancel',\n this.handleDocumentPointerCancel\n );\n this.hasDocumentPointerListeners = false;\n }\n\n private clearPointerSession(): void {\n this.pointerSession = { mode: 'idle' };\n }\n\n private clearPendingSingleLineState(): void {\n if (this.pointerSession.mode === 'pendingSingleLineUnselect') {\n this.pointerSession = { mode: 'idle' };\n }\n }\n\n private selectionInfoFromPath(\n path: (EventTarget | undefined)[],\n requireNumberColumn: boolean\n ): SelectionInfo | undefined {\n const target = this.resolvePointerTarget(path);\n if (!isLinePointerTarget(target)) {\n return undefined;\n }\n if (requireNumberColumn && !target.numberColumn) {\n return undefined;\n }\n if (target.splitLineIndex == null) {\n return undefined;\n }\n\n return {\n lineIndex: target.splitLineIndex,\n lineNumber: target.lineNumber,\n eventSide: this.mode === 'diff' ? target.side : undefined,\n };\n }\n\n private resolveSelectionInfo(\n event: PointerEvent,\n options: SelectionInfoOptions\n ): SelectionInfo | undefined {\n const path = this.resolveSelectionPath(event, options);\n return path != null\n ? this.selectionInfoFromPath(path, options.requireNumberColumn)\n : undefined;\n }\n\n private selectionPointFromPath(\n path: (EventTarget | undefined)[]\n ): SelectionPoint | undefined {\n const target = this.resolvePointerTarget(path);\n if (!isLinePointerTarget(target)) {\n return undefined;\n }\n return {\n lineNumber: target.lineNumber,\n side: this.mode === 'diff' ? target.side : undefined,\n };\n }\n\n private resolveSelectionPoint(\n event: PointerEvent,\n options: SelectionHitOptions\n ): SelectionPoint | undefined {\n const path = this.resolveSelectionPath(event, options);\n return path != null ? this.selectionPointFromPath(path) : undefined;\n }\n\n private resolveSelectionPath(\n event: PointerEvent,\n options: SelectionHitOptions\n ): (EventTarget | undefined)[] | undefined {\n const excludeUtility = options.excludeUtility !== false;\n switch (options.source) {\n case 'event-path':\n return this.pathFromEventPath(event.composedPath(), excludeUtility);\n case 'coordinates-first': {\n // Touch pointers can keep dispatching move/up events to the element\n // where the drag began. Prefer the row currently under the finger,\n // then fall back only when coordinate hit-testing is unavailable.\n const coordinatePath = this.pathFromCoordinates(event, excludeUtility);\n if (coordinatePath !== undefined) {\n return coordinatePath ?? undefined;\n }\n return this.pathFromEventPath(event.composedPath(), excludeUtility);\n }\n }\n }\n\n private pathFromCoordinates(\n event: PointerEvent,\n excludeUtility: boolean\n ): (EventTarget | undefined)[] | null | undefined {\n const coordinateTarget = this.hitTest(event);\n if (coordinateTarget === undefined) {\n return undefined;\n }\n if (coordinateTarget === null) {\n return null;\n }\n // A coordinate hit can be a token span, line-number span, utility overlay,\n // or separator. Normalize valid descendants back to their row; invalid\n // hits intentionally return null so the last selected row stays sticky.\n return this.pathFromElement(coordinateTarget, excludeUtility) ?? null;\n }\n\n private pathFromEventPath(\n path: (EventTarget | undefined)[],\n excludeUtility: boolean\n ): (EventTarget | undefined)[] | undefined {\n if (excludeUtility && isGutterUtilityPath(path)) {\n return undefined;\n }\n for (const element of path) {\n if (element instanceof Element) {\n return this.pathFromElement(element, excludeUtility);\n }\n }\n return undefined;\n }\n\n private pathFromElement(\n element: Element,\n excludeUtility: boolean\n ): (EventTarget | undefined)[] | undefined {\n const path = getElementPath(element);\n if (excludeUtility && isGutterUtilityPath(path)) {\n return undefined;\n }\n // Selection is row-based, not child-element-based. Lateral movement over\n // tokens, annotations, or line-number text should still update to the\n // nearest content or gutter row; anything else is ignored by returning\n // undefined.\n const row = closestSelectableRow(element);\n if (row != null) {\n return getElementPath(row);\n }\n return this.pathFromAnnotationSlot(element);\n }\n\n private pathFromAnnotationSlot(\n element: Element\n ): (EventTarget | undefined)[] | undefined {\n // Don't trust the slot name for the line number: during an edit session\n // an annotation keeps its original name while edits move it to other\n // lines, so a name like \"annotation-20\" can point at a line the\n // annotation left long ago. The code row directly above the annotation\n // row always reflects where it sits now, so read the line from there and\n // parse the name only as a fallback.\n const annotationRow = annotationRowFromSlot(element);\n const annotatedLine = annotationRow?.previousElementSibling;\n if (\n annotatedLine instanceof HTMLElement &&\n (annotatedLine.hasAttribute('data-line') ||\n annotatedLine.hasAttribute('data-column-number'))\n ) {\n return getElementPath(annotatedLine);\n }\n const point = selectionPointFromAnnotationSlotName(\n getAnnotationSlotName(element)\n );\n if (point == null) {\n return undefined;\n }\n const target = this.targetForSelectionPoint(point);\n return target != null ? getElementPath(target.lineElement) : undefined;\n }\n\n private hitTest(event: PointerEvent): Element | null | undefined {\n // Return undefined when coordinate hit-testing cannot run at all, which\n // allows callers to fall back to the event path for tests and older DOMs.\n // Return null when hit-testing ran but found no element, so active drags\n // keep their previous endpoint instead of using a stale captured target.\n if (!Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) {\n return undefined;\n }\n const root = this.pre?.getRootNode();\n const elementFromPointRoot = hasElementFromPoint(root)\n ? root\n : hasElementFromPoint(document)\n ? document\n : undefined;\n if (elementFromPointRoot == null) {\n return undefined;\n }\n const element = elementFromPointRoot.elementFromPoint(\n event.clientX,\n event.clientY\n );\n return element;\n }\n\n private getLineIndex(\n lineNumber: number,\n side?: SelectionSide\n ): [number, number] | undefined {\n const { getLineIndex } = this.options;\n return getLineIndex != null\n ? getLineIndex(lineNumber, side)\n : [lineNumber - 1, lineNumber - 1];\n }\n\n private getCurrentSelectionRange(): SelectedLineRange | null {\n return this.proposedSelectedRange !== undefined\n ? this.proposedSelectedRange\n : this.selectedRange;\n }\n\n private clearProposedSelection(): void {\n this.proposedSelectedRange = undefined;\n }\n\n private updateSelection(\n currentLine: number | null,\n side?: SelectionSide,\n emitChange = true\n ): void {\n const previousRange = this.getCurrentSelectionRange();\n let nextRange: SelectedLineRange | null;\n if (currentLine == null) {\n nextRange = null;\n } else {\n const anchorSide = this.selectionAnchor?.side ?? side;\n const anchorLine = this.selectionAnchor?.lineNumber ?? currentLine;\n nextRange = this.buildSelectionRange(\n anchorLine,\n currentLine,\n anchorSide,\n side\n );\n }\n if (\n areSelectionsEqual(previousRange ?? undefined, nextRange ?? undefined)\n ) {\n return;\n }\n this.selectedRangeHighlightSide = undefined;\n this.selectedRangeLineNumberOnly = false;\n if (this.options.controlledSelection === true) {\n this.proposedSelectedRange = nextRange;\n } else {\n this.selectedRange = nextRange;\n queueRender(this.renderSelection);\n }\n this.placeUtility();\n if (emitChange) {\n this.notifySelectionChangeDelta();\n }\n }\n\n private getIndexesFromSelection(\n selectedRange: SelectedLineRange,\n split: boolean\n ): { start: number; end: number } | undefined {\n if (this.pre == null) {\n return undefined;\n }\n const startIndexes = this.getLineIndex(\n selectedRange.start,\n selectedRange.side\n );\n const finalIndexes = this.getLineIndex(\n selectedRange.end,\n selectedRange.endSide ?? selectedRange.side\n );\n\n return startIndexes != null && finalIndexes != null\n ? {\n start: split ? startIndexes[1] : startIndexes[0],\n end: split ? finalIndexes[1] : finalIndexes[0],\n }\n : undefined;\n }\n\n // Resolve selected lines and the editor active line together while their DOM\n // attributes retain independent rendered snapshots.\n private getSelectionRenderState(): SelectionRenderState {\n return {\n selectedLines: {\n range: this.selectedRange,\n highlightSide: this.selectedRangeHighlightSide,\n lineNumberOnly: this.selectedRangeLineNumberOnly,\n },\n editorActiveLine: {\n range:\n this.editorActiveLine == null\n ? null\n : {\n start: this.editorActiveLine,\n end: this.editorActiveLine,\n side: this.editorActiveLineSide,\n },\n highlightSide: this.editorActiveLineSide,\n lineNumberOnly: this.editorLineNumberOnly,\n },\n };\n }\n\n // Resolve a desired line range before touching the last successful DOM\n // state, so a transient line-index mismatch leaves that rendering intact and\n // dirty.\n private resolveLineRenderRange(\n state: LineRenderState,\n split: boolean,\n source: 'selected-lines' | 'editor-active-line'\n ): { start: number; end: number } | undefined {\n if (state.range == null) {\n return undefined;\n }\n const rowRange = this.getIndexesFromSelection(state.range, split);\n if (rowRange == null) {\n console.error({ rowRange, range: state.range });\n throw new Error(\n `InteractionManager.renderSelection: No valid ${source} rowRange`\n );\n }\n return rowRange;\n }\n\n // Validate every code column that will receive changed attributes before\n // clearing either channel's previous rendering.\n private getLineRenderColumns(\n selectedLines: LineRenderState | undefined,\n selectedRowRange: { start: number; end: number } | undefined,\n editorActiveLine: LineRenderState | undefined,\n editorRowRange: { start: number; end: number } | undefined\n ): LineRenderColumn[] {\n if (\n this.pre == null ||\n (selectedRowRange == null && editorRowRange == null)\n ) {\n return [];\n }\n\n const { children: codeElements } = this.pre;\n if (codeElements.length > 2) {\n console.error(codeElements);\n throw new Error(\n 'InteractionManager.renderSelection: Somehow there are more than 2 code elements...'\n );\n }\n\n const columns: LineRenderColumn[] = [];\n for (const code of codeElements) {\n const side: SelectionSide | undefined = code.hasAttribute(\n 'data-deletions'\n )\n ? 'deletions'\n : code.hasAttribute('data-additions')\n ? 'additions'\n : undefined;\n const renderSelectedLines =\n selectedLines != null &&\n selectedRowRange != null &&\n (selectedLines.highlightSide == null ||\n side == null ||\n selectedLines.highlightSide === side);\n const renderEditorActiveLine =\n editorActiveLine != null &&\n editorRowRange != null &&\n (editorActiveLine.highlightSide == null ||\n side == null ||\n editorActiveLine.highlightSide === side);\n if (!renderSelectedLines && !renderEditorActiveLine) {\n continue;\n }\n\n const [gutter, content] = code.children;\n if (\n !(gutter instanceof HTMLElement) ||\n !(content instanceof HTMLElement)\n ) {\n throw new Error(\n 'InteractionManager.renderSelection: missing gutter or content element'\n );\n }\n if (content.children.length !== gutter.children.length) {\n throw new Error(\n 'InteractionManager.renderSelection: gutter and content children dont match, something is wrong'\n );\n }\n columns.push({\n content,\n gutter,\n renderEditorActiveLine,\n renderSelectedLines,\n });\n }\n return columns;\n }\n\n private renderSelection = (): void => {\n dequeueRender(this.renderSelection);\n const renderState = this.getSelectionRenderState();\n if (this.pre == null) {\n return;\n }\n const { editorActiveLine, selectedLines } = renderState;\n const selectedLinesChanged = !areLineRenderStatesEqual(\n this.renderedSelectedLinesState,\n selectedLines\n );\n const editorActiveLineChanged = !areLineRenderStatesEqual(\n this.renderedEditorActiveLineState,\n editorActiveLine\n );\n if (!selectedLinesChanged && !editorActiveLineChanged) {\n return;\n }\n\n // A changed channel remains explicitly dirty until its DOM update finishes,\n // which lets an identical write retry after a transient render failure.\n if (selectedLinesChanged) {\n this.renderedSelectedLinesState = undefined;\n }\n if (editorActiveLineChanged) {\n this.renderedEditorActiveLineState = undefined;\n }\n\n const split = this.pre.getAttribute('data-diff-type') === 'split';\n const selectedRowRange = !selectedLinesChanged\n ? undefined\n : this.resolveLineRenderRange(selectedLines, split, 'selected-lines');\n const editorRowRange = !editorActiveLineChanged\n ? undefined\n : this.resolveLineRenderRange(\n editorActiveLine,\n split,\n 'editor-active-line'\n );\n const columns = this.getLineRenderColumns(\n selectedLinesChanged ? selectedLines : undefined,\n selectedRowRange,\n editorActiveLineChanged ? editorActiveLine : undefined,\n editorRowRange\n );\n const selectedLinesComplete =\n selectedLines.range == null ||\n columns.some((column) => column.renderSelectedLines);\n const editorActiveLineComplete =\n editorActiveLine.range == null ||\n columns.some((column) => column.renderEditorActiveLine);\n\n if (selectedLinesChanged) {\n for (const element of this.pre.querySelectorAll('[data-selected-line]')) {\n element.removeAttribute('data-selected-line');\n }\n }\n if (editorActiveLineChanged) {\n for (const element of this.pre.querySelectorAll(\n '[data-editor-active-line]'\n )) {\n element.removeAttribute('data-editor-active-line');\n }\n }\n\n const selectedFirst =\n selectedRowRange == null\n ? undefined\n : Math.min(selectedRowRange.start, selectedRowRange.end);\n const selectedLast =\n selectedRowRange == null\n ? undefined\n : Math.max(selectedRowRange.start, selectedRowRange.end);\n const selectedIsSingle = selectedFirst === selectedLast;\n const editorLineIndex = editorRowRange?.start;\n for (const column of columns) {\n const { content, gutter, renderEditorActiveLine, renderSelectedLines } =\n column;\n const finalLineIndex = Math.max(\n renderSelectedLines ? (selectedLast ?? -Infinity) : -Infinity,\n renderEditorActiveLine ? (editorLineIndex ?? -Infinity) : -Infinity\n );\n const len = content.children.length;\n for (let i = 0; i < len; i++) {\n const contentElement = content.children[i];\n const gutterElement = gutter.children[i];\n if (\n !(contentElement instanceof HTMLElement) ||\n !(gutterElement instanceof HTMLElement)\n ) {\n continue;\n }\n\n const lineIndex = this.parseLineIndex(contentElement, split);\n if ((lineIndex ?? 0) > finalLineIndex) {\n break;\n }\n if (lineIndex == null) {\n continue;\n }\n if (\n renderSelectedLines &&\n selectedFirst != null &&\n selectedLast != null &&\n lineIndex >= selectedFirst &&\n lineIndex <= selectedLast\n ) {\n let attributeValue = selectedIsSingle\n ? 'single'\n : lineIndex === selectedFirst\n ? 'first'\n : lineIndex === selectedLast\n ? 'last'\n : '';\n gutterElement.setAttribute('data-selected-line', attributeValue);\n // A number-only highlight marks just the gutter number, leaving the\n // line background and any annotation rows untouched.\n if (!selectedLines.lineNumberOnly) {\n contentElement.setAttribute('data-selected-line', attributeValue);\n if (\n gutterElement.nextSibling instanceof HTMLElement &&\n contentElement.nextSibling instanceof HTMLElement &&\n (contentElement.nextSibling.hasAttribute(\n 'data-line-annotation'\n ) ||\n contentElement.nextSibling.hasAttribute(\n 'data-merge-conflict-actions'\n ))\n ) {\n if (selectedIsSingle) {\n attributeValue = 'last';\n contentElement.setAttribute('data-selected-line', 'first');\n } else if (lineIndex === selectedFirst) {\n attributeValue = '';\n } else if (lineIndex === selectedLast) {\n contentElement.setAttribute('data-selected-line', '');\n }\n contentElement.nextSibling.setAttribute(\n 'data-selected-line',\n attributeValue\n );\n gutterElement.nextSibling.setAttribute(\n 'data-selected-line',\n attributeValue\n );\n }\n }\n }\n if (renderEditorActiveLine && lineIndex === editorLineIndex) {\n gutterElement.setAttribute('data-editor-active-line', '');\n if (!editorActiveLine.lineNumberOnly) {\n contentElement.setAttribute('data-editor-active-line', '');\n }\n }\n }\n }\n\n if (selectedLinesChanged && selectedLinesComplete) {\n this.renderedSelectedLinesState = selectedLines;\n }\n if (editorActiveLineChanged && editorActiveLineComplete) {\n this.renderedEditorActiveLineState = editorActiveLine;\n }\n };\n\n private notifySelectionCommitted(range: SelectedLineRange | null): void {\n this.options.onLineSelected?.(range);\n }\n\n private notifySelectionChangeDelta(): void {\n this.options.onLineSelectionChange?.(\n this.getCurrentSelectionRange() ?? null\n );\n }\n\n private notifySelectionStart(range: SelectedLineRange | null): void {\n this.options.onLineSelectionStart?.(range);\n }\n\n private notifySelectionEnd(range: SelectedLineRange | null): void {\n this.options.onLineSelectionEnd?.(range);\n }\n\n private toEventBaseProps(\n target: HoverableLinePointerTarget<TMode>\n ): EventBaseProps<TMode> {\n if (this.mode === 'file') {\n return {\n type: 'line',\n lineElement: target.lineElement,\n lineNumber: target.lineNumber,\n numberColumn: target.numberColumn,\n numberElement: target.numberElement,\n } as EventBaseProps<TMode>;\n }\n\n return {\n type: 'diff-line',\n annotationSide: target.side as AnnotationSide,\n lineType: target.lineType,\n lineElement: target.lineElement,\n numberElement: target.numberElement,\n lineNumber: target.lineNumber,\n numberColumn: target.numberColumn,\n } as EventBaseProps<TMode>;\n }\n\n private toTokenEventBaseProps({\n lineCharEnd,\n lineCharStart,\n lineNumber,\n side,\n tokenElement,\n tokenText,\n }: TokenPointerTarget<TMode>): OnTokenEventProps<TMode> {\n if (this.mode === 'file') {\n return {\n type: 'token',\n lineCharEnd,\n lineCharStart,\n lineNumber,\n tokenElement,\n tokenText,\n } as OnTokenEventProps<TMode>;\n }\n\n return {\n type: 'token',\n lineCharEnd,\n lineCharStart,\n lineNumber,\n side,\n tokenElement,\n tokenText,\n } as OnTokenEventProps<TMode>;\n }\n\n private buildSelectedLineRange(\n anchor: SelectionPoint,\n current: SelectionPoint\n ): SelectedLineRange {\n return this.buildSelectionRange(\n anchor.lineNumber,\n current.lineNumber,\n anchor.side,\n current.side\n );\n }\n\n private buildSelectionRange(\n start: number,\n end: number,\n side?: SelectionSide,\n endSide?: SelectionSide\n ): SelectedLineRange {\n return {\n start,\n end,\n ...(side != null ? { side } : {}),\n ...(side !== endSide && endSide != null ? { endSide } : {}),\n };\n }\n\n private resolvePointerTarget(\n path: (EventTarget | undefined)[]\n ): ResolvedPointerTarget<TMode> | undefined {\n let numberColumn = false;\n let lineType: LineTypes | undefined;\n let codeElement: HTMLElement | undefined;\n let lineElement: HTMLElement | undefined;\n let lineIndexValue: string | undefined;\n let numberElement: HTMLElement | undefined;\n let tokenElement: HTMLElement | undefined;\n let tokenInfo: TokenCache | undefined;\n let expandInfo: ExpandCache | undefined;\n let lineNumber: number | undefined;\n let mergeConflictActionTarget: MergeConflictActionTarget | undefined;\n\n for (const element of path) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n\n if (\n mergeConflictActionTarget == null &&\n element.hasAttribute('data-merge-conflict-action')\n ) {\n const resolutionValue =\n element.getAttribute('data-merge-conflict-action') ?? undefined;\n const conflictIndexValue =\n element.getAttribute('data-merge-conflict-conflict-index') ??\n undefined;\n const conflictIndex =\n conflictIndexValue != null\n ? Number.parseInt(conflictIndexValue, 10)\n : Number.NaN;\n if (\n isMergeConflictResolution(resolutionValue) &&\n Number.isFinite(conflictIndex)\n ) {\n mergeConflictActionTarget = {\n kind: 'merge-conflict-action',\n resolution: resolutionValue,\n conflictIndex,\n };\n }\n }\n\n if (tokenElement == null && element.hasAttribute('data-char')) {\n tokenElement = element;\n const startAttr = element.getAttribute('data-char');\n\n if (startAttr != null) {\n const lineCharStart = Number.parseInt(startAttr, 10);\n if (!Number.isNaN(lineCharStart)) {\n const tokenText = element.textContent ?? '';\n const lineCharEnd = lineCharStart + tokenText.length;\n if (\n tokenText.trim() !== '' ||\n this.options.enableTokenInteractionsOnWhitespace === true\n ) {\n tokenInfo = {\n tokenElement,\n lineCharStart,\n lineCharEnd,\n tokenText,\n };\n }\n continue;\n }\n }\n }\n\n const columnNumber =\n numberElement == null\n ? (element.getAttribute('data-column-number') ?? undefined)\n : undefined;\n if (columnNumber != null) {\n numberElement = element;\n lineNumber = Number.parseInt(columnNumber, 10);\n numberColumn = true;\n lineType = getLineTypeFromElement(element);\n lineIndexValue = element.getAttribute('data-line-index') ?? undefined;\n continue;\n }\n\n const lineAttr =\n lineElement == null\n ? (element.getAttribute('data-line') ?? undefined)\n : undefined;\n if (lineAttr != null) {\n lineElement = element;\n lineNumber = Number.parseInt(lineAttr, 10);\n lineType = getLineTypeFromElement(element);\n lineIndexValue = element.getAttribute('data-line-index') ?? undefined;\n continue;\n }\n\n if (\n expandInfo == null &&\n (element.hasAttribute('data-expand-button') ||\n element.hasAttribute('data-unmodified-lines'))\n ) {\n expandInfo = {\n hunkIndex: undefined,\n direction: (() => {\n if (element.hasAttribute('data-expand-up')) {\n return 'up';\n }\n if (element.hasAttribute('data-expand-down')) {\n return 'down';\n }\n return 'both';\n })(),\n all: element.hasAttribute('data-expand-all-button'),\n };\n continue;\n }\n\n const expandIndexValue =\n expandInfo != null\n ? (element.getAttribute('data-expand-index') ?? undefined)\n : undefined;\n if (expandInfo != null && expandIndexValue != null) {\n const expandIndex = Number.parseInt(expandIndexValue, 10);\n if (!Number.isNaN(expandIndex)) {\n expandInfo.hunkIndex = expandIndex;\n }\n continue;\n }\n\n if (codeElement == null && element.hasAttribute('data-code')) {\n codeElement = element;\n break;\n }\n }\n\n if (mergeConflictActionTarget != null) {\n return mergeConflictActionTarget;\n }\n\n if (expandInfo?.hunkIndex != null) {\n return {\n type: 'line-info',\n hunkIndex: expandInfo.hunkIndex,\n direction: expandInfo.direction,\n all: expandInfo.all,\n };\n }\n\n lineElement ??=\n lineIndexValue != null\n ? queryHTMLElement(\n codeElement,\n `[data-line][data-line-index=\"${lineIndexValue}\"]`\n )\n : undefined;\n numberElement ??=\n lineIndexValue != null\n ? queryHTMLElement(\n codeElement,\n `[data-column-number][data-line-index=\"${lineIndexValue}\"]`\n )\n : undefined;\n\n if (\n codeElement == null ||\n lineElement == null ||\n numberElement == null ||\n lineType == null ||\n lineNumber == null ||\n Number.isNaN(lineNumber)\n ) {\n return undefined;\n }\n\n const splitLineIndex = this.parseLineIndex(lineElement, this.isSplitDiff());\n\n if (tokenInfo != null) {\n if (this.mode === 'file') {\n return {\n kind: 'token',\n lineType,\n lineElement,\n lineNumber,\n numberColumn,\n numberElement,\n side: undefined,\n splitLineIndex,\n ...tokenInfo,\n } as ResolvedPointerTarget<TMode>;\n }\n\n return {\n kind: 'token',\n lineType,\n lineElement,\n lineNumber,\n numberColumn,\n numberElement,\n side: getAnnotationSide(lineType, codeElement),\n splitLineIndex,\n ...tokenInfo,\n } as ResolvedPointerTarget<TMode>;\n }\n\n // Otherwise return line target\n if (this.mode === 'file') {\n return {\n kind: 'line',\n lineType,\n lineElement,\n lineNumber,\n numberColumn,\n numberElement,\n side: undefined,\n splitLineIndex,\n } as ResolvedPointerTarget<TMode>;\n }\n\n return {\n kind: 'line',\n lineType,\n lineElement,\n lineNumber,\n numberColumn,\n numberElement,\n side: getAnnotationSide(lineType, codeElement),\n splitLineIndex,\n } as ResolvedPointerTarget<TMode>;\n }\n\n private isSplitDiff(): boolean {\n return this.pre?.getAttribute('data-diff-type') === 'split';\n }\n\n private parseLineIndex(\n element: HTMLElement,\n split: boolean\n ): number | undefined {\n const lineIndexes = (element.getAttribute('data-line-index') ?? '')\n .split(',')\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => !Number.isNaN(value));\n\n if (split && lineIndexes.length === 2) {\n return lineIndexes[1];\n }\n if (!split) {\n return lineIndexes[0];\n }\n return undefined;\n }\n}\n\ntype InteractionPluckOptions<TMode extends InteractionManagerMode> =\n InteractionManagerBaseOptions<TMode> & {\n renderGutterUtility?(\n getHoveredRow: () => GetHoveredLineResult<TMode> | undefined\n ): HTMLElement | null | undefined;\n };\n\nexport function pluckInteractionOptions<TMode extends InteractionManagerMode>(\n {\n enableTokenInteractionsOnWhitespace,\n enableGutterUtility,\n lineHoverHighlight,\n onGutterUtilityClick,\n onLineClick,\n onLineEnter,\n onLineLeave,\n onLineNumberClick,\n onTokenClick,\n onTokenEnter,\n onTokenLeave,\n renderGutterUtility,\n __debugPointerEvents,\n enableLineSelection,\n controlledSelection,\n onLineSelected,\n onLineSelectionStart,\n onLineSelectionChange,\n onLineSelectionEnd,\n }: InteractionPluckOptions<TMode>,\n onHunkExpand?: (\n hunkIndex: number,\n direction: ExpansionDirections,\n expansionLineCountOverride?: number\n ) => unknown,\n getLineIndex?: GetLineIndexUtility,\n onMergeConflictActionClick?: (target: MergeConflictActionTarget) => void\n): InteractionManagerOptions<TMode> {\n return {\n enableTokenInteractionsOnWhitespace,\n enableGutterUtility: resolveEnableGutterUtilityOption({\n enableGutterUtility,\n renderGutterUtility,\n onGutterUtilityClick,\n }),\n usesCustomGutterUtility: renderGutterUtility != null,\n lineHoverHighlight,\n\n onGutterUtilityClick,\n onHunkExpand,\n onMergeConflictActionClick,\n onLineClick,\n onLineEnter,\n onLineLeave,\n onLineNumberClick,\n onTokenClick,\n onTokenEnter,\n onTokenLeave,\n __debugPointerEvents,\n\n enableLineSelection,\n controlledSelection,\n onLineSelected,\n onLineSelectionStart,\n onLineSelectionChange,\n onLineSelectionEnd,\n\n getLineIndex,\n };\n}\n\nfunction resolveEnableGutterUtilityOption<\n TMode extends InteractionManagerMode,\n>({\n enableGutterUtility,\n renderGutterUtility,\n onGutterUtilityClick,\n}: Pick<\n InteractionPluckOptions<TMode>,\n 'enableGutterUtility' | 'renderGutterUtility' | 'onGutterUtilityClick'\n>): boolean {\n if (onGutterUtilityClick != null && renderGutterUtility != null) {\n throw new Error(\n \"Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.\"\n );\n }\n return enableGutterUtility ?? false;\n}\n\nfunction isLinePointerTarget<TMode extends InteractionManagerMode>(\n target: ResolvedPointerTarget<TMode> | undefined\n): target is LinePointerTarget<TMode> {\n return target != null && 'kind' in target && target.kind === 'line';\n}\n\nfunction isTokenPointerTarget<TMode extends InteractionManagerMode>(\n target: ResolvedPointerTarget<TMode> | undefined\n): target is TokenPointerTarget<TMode> {\n return target != null && 'kind' in target && target.kind === 'token';\n}\n\nfunction isHoverableLinePointerTarget<TMode extends InteractionManagerMode>(\n target: ResolvedPointerTarget<TMode> | undefined\n): target is HoverableLinePointerTarget<TMode> {\n return isLinePointerTarget(target) || isTokenPointerTarget(target);\n}\n\nfunction isExpandoPointerTarget<TMode extends InteractionManagerMode>(\n target: ResolvedPointerTarget<TMode>\n): target is ExpandoEventProps {\n return 'type' in target && target.type === 'line-info';\n}\n\nfunction isMergeConflictActionPointerTarget<\n TMode extends InteractionManagerMode,\n>(target: ResolvedPointerTarget<TMode>): target is MergeConflictActionTarget {\n return 'kind' in target && target.kind === 'merge-conflict-action';\n}\n\nfunction isMergeConflictResolution(\n value: string | undefined\n): value is MergeConflictResolution {\n return value === 'current' || value === 'incoming' || value === 'both';\n}\n\nfunction queryHTMLElement(\n parent: HTMLElement | undefined,\n query: string\n): HTMLElement | undefined {\n const element = parent?.querySelector(query);\n return element instanceof HTMLElement ? element : undefined;\n}\n\nfunction getElementPath(element: Node): EventTarget[] {\n const path: EventTarget[] = [];\n let current: Node | null = element;\n while (current != null) {\n path.push(current);\n current = current.parentNode;\n }\n return path;\n}\n\n// Pointer hits often land on text/token descendants. This normalizes those\n// hits back to the row elements InteractionManager knows how to resolve.\nfunction closestSelectableRow(element: Element): HTMLElement | undefined {\n const row = element.closest('[data-line], [data-column-number]');\n if (row instanceof HTMLElement) {\n return row;\n }\n\n const annotationRow = element.closest(\n '[data-line-annotation], [data-gutter-buffer=\"annotation\"]'\n );\n if (!(annotationRow instanceof HTMLElement)) {\n return undefined;\n }\n\n const previousRow = annotationRow.previousElementSibling;\n return previousRow instanceof HTMLElement &&\n (previousRow.hasAttribute('data-line') ||\n previousRow.hasAttribute('data-column-number'))\n ? previousRow\n : undefined;\n}\n\n// Resolve the shadow annotation row an event target projects into, from\n// either slotted light-DOM content or the slot element itself.\nfunction annotationRowFromSlot(element: Element): HTMLElement | undefined {\n const slotted = element.closest('[slot^=\"annotation-\"]');\n const slot =\n slotted instanceof HTMLElement && slotted.assignedSlot != null\n ? slotted.assignedSlot\n : element.tagName === 'SLOT'\n ? element\n : undefined;\n const row = slot?.closest('[data-line-annotation]');\n return row instanceof HTMLElement ? row : undefined;\n}\n\nfunction getAnnotationSlotName(element: Element): string | undefined {\n const slottedElement = element.closest('[slot^=\"annotation-\"]');\n if (slottedElement instanceof HTMLElement) {\n return slottedElement.getAttribute('slot') ?? undefined;\n }\n\n if (element instanceof HTMLElement) {\n const slotName = element.getAttribute('name') ?? undefined;\n return slotName != null && slotName.startsWith('annotation-')\n ? slotName\n : undefined;\n }\n\n return undefined;\n}\n\nfunction selectionPointFromAnnotationSlotName(\n slotName: string | undefined\n): SelectionPoint | undefined {\n if (slotName == null) {\n return undefined;\n }\n\n const match = /^annotation-(?:(additions|deletions)-)?(\\d+)$/.exec(slotName);\n if (match == null) {\n return undefined;\n }\n\n const lineNumber = Number.parseInt(match[2], 10);\n if (!Number.isFinite(lineNumber) || lineNumber <= 0) {\n return undefined;\n }\n\n const side = match[1] as SelectionSide | undefined;\n return { lineNumber, side };\n}\n\ninterface ElementFromPointRoot {\n elementFromPoint(x: number, y: number): Element | null;\n}\n\nfunction hasElementFromPoint(\n value: Node | undefined\n): value is Node & ElementFromPointRoot {\n return (\n value != null &&\n typeof (value as Partial<ElementFromPointRoot>).elementFromPoint ===\n 'function'\n );\n}\n\nfunction areSelectionRangesEqual(\n first: SelectedLineRange | null,\n second: SelectedLineRange | null\n): boolean {\n return (\n first === second ||\n areSelectionsEqual(first ?? undefined, second ?? undefined)\n );\n}\n\nfunction areLineRenderStatesEqual(\n first: LineRenderState | undefined,\n second: LineRenderState\n): boolean {\n return (\n first?.highlightSide === second.highlightSide &&\n first?.lineNumberOnly === second.lineNumberOnly &&\n areSelectionRangesEqual(first?.range ?? null, second.range)\n );\n}\n\nfunction getAnnotationSide(\n lineType: LineTypes,\n codeElement: HTMLElement\n): AnnotationSide {\n switch (lineType) {\n case 'change-deletion':\n return 'deletions';\n case 'change-addition':\n return 'additions';\n default:\n return codeElement.hasAttribute('data-deletions')\n ? 'deletions'\n : 'additions';\n }\n}\n\nfunction getLineTypeFromElement(element: HTMLElement): LineTypes | undefined {\n const lineType = element.getAttribute('data-line-type');\n if (lineType == null) {\n return undefined;\n }\n switch (lineType) {\n case 'change-deletion':\n case 'change-addition':\n case 'context':\n case 'context-expanded':\n return lineType;\n default:\n return undefined;\n }\n}\n\nfunction debugLogIfEnabled(\n debugLogType: LogTypes | undefined = 'none',\n logIfType: 'move' | 'click',\n ...args: unknown[]\n) {\n switch (debugLogType) {\n case 'none':\n return;\n case 'both':\n break;\n case 'click':\n if (logIfType !== 'click') {\n return;\n }\n break;\n case 'move':\n if (logIfType !== 'move') {\n return;\n }\n break;\n }\n console.log(...args);\n}\n", "import type { ObservedAnnotationNodes, ObservedGridNodes } from '../types';\n\ninterface CodeColumnUpdate {\n codeInlineSize?: number;\n numberInlineSize?: number;\n measuredNumberInlineSize?: number;\n}\n\ninterface CodeColumnVariableChanges {\n codeWidthChanged: boolean;\n numberWidthChanged: boolean;\n}\n\ntype CodeUpdateMap = Map<ObservedGridNodes, CodeColumnUpdate>;\n\nexport type ResizeManagerColumnVariableMode = 'apply' | 'measure';\n\nexport interface ResizeManagerSetupOptions {\n disableAnnotations: boolean;\n columnVariables?: ResizeManagerColumnVariableMode;\n}\n\ninterface AnnotationSetup {\n child1: HTMLElement;\n child2: HTMLElement;\n item: ObservedAnnotationNodes;\n newHeight: number;\n}\n\nexport class ResizeManager {\n // Shared static resizeObserver that all ResizeManagers use\n private static resizeObserver: ResizeObserver | undefined;\n private static managersByElement = new Map<Element, ResizeManager>();\n\n private static getResizeObserver(): ResizeObserver {\n const resizeObserver =\n ResizeManager.resizeObserver ??\n new ResizeObserver(ResizeManager.handleSharedResizeEntries);\n ResizeManager.resizeObserver = resizeObserver;\n return resizeObserver;\n }\n\n private static handleSharedResizeEntries(entries: ResizeObserverEntry[]) {\n // First we need to batch all elements by manager, so callbacks are\n // properly aligned with a per-instance ResizeManager\n const entriesByManager = new Map<ResizeManager, ResizeObserverEntry[]>();\n for (const entry of entries) {\n const manager = ResizeManager.managersByElement.get(entry.target);\n if (manager == null) {\n continue;\n }\n const managerEntries = entriesByManager.get(manager);\n if (managerEntries == null) {\n entriesByManager.set(manager, [entry]);\n } else {\n managerEntries.push(entry);\n }\n }\n\n for (const [manager, managerEntries] of entriesByManager) {\n manager.handleResizeEntries(managerEntries);\n }\n }\n\n private observedNodes = new Map<\n HTMLElement,\n ObservedAnnotationNodes | ObservedGridNodes\n >();\n\n setup(\n pre: HTMLPreElement,\n { disableAnnotations, columnVariables = 'apply' }: ResizeManagerSetupOptions\n ): void {\n const annotationUpdates = new Set<AnnotationSetup>();\n const applyColumnVariables = columnVariables === 'apply';\n let columnCount = 0;\n const observedNodes = new Map(this.observedNodes);\n this.observedNodes.clear();\n\n for (const element of pre.children) {\n if (columnCount === 2) {\n break;\n }\n const codeElement: HTMLElement | undefined = (() => {\n if (element instanceof HTMLElement && element.tagName === 'CODE') {\n return element;\n }\n return undefined;\n })();\n if (codeElement == null) {\n continue;\n }\n columnCount++;\n let item: ObservedGridNodes | ObservedAnnotationNodes | undefined =\n observedNodes.get(codeElement);\n if (item != null && item.type !== 'code') {\n throw new Error(\n 'ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible'\n );\n }\n\n let numberElement = codeElement.firstElementChild;\n if (!(numberElement instanceof HTMLElement)) {\n numberElement = null;\n }\n if (item != null) {\n this.observedNodes.set(codeElement, item);\n observedNodes.delete(codeElement);\n if (item.numberElement !== numberElement) {\n if (item.numberElement != null) {\n this.unobserve(item.numberElement);\n observedNodes.delete(item.numberElement);\n }\n if (numberElement != null) {\n this.observe(numberElement);\n observedNodes.delete(numberElement);\n this.observedNodes.set(numberElement, item);\n }\n item.numberElement = numberElement;\n item.numberWidth = 0;\n } else if (item.numberElement != null) {\n observedNodes.delete(item.numberElement);\n this.observedNodes.set(item.numberElement, item);\n // If there is a resize, let the resize handler handle it...\n } else {\n item.numberWidth = 0;\n }\n syncColumnVariableMode(item, applyColumnVariables);\n } else {\n item = {\n type: 'code',\n codeElement,\n numberElement,\n codeWidth: 'auto',\n numberWidth: 0,\n applyColumnVariables,\n };\n this.observedNodes.set(codeElement, item);\n this.observe(codeElement);\n if (numberElement != null) {\n this.observedNodes.set(numberElement, item);\n this.observe(numberElement);\n }\n }\n }\n\n if (columnCount > 1 && !disableAnnotations) {\n const annotationElements = pre.querySelectorAll(\n '[data-line-annotation*=\",\"]'\n );\n\n const elementMap = new Map<string, HTMLElement[]>();\n // Iterate through all the matched elements and organize them into pairs\n // based on the data-line-annotation attribute\n for (const element of annotationElements) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n const lineAnnotation =\n element.getAttribute('data-line-annotation') ?? '';\n if (!/^-?\\d+,-?\\d+$/.test(lineAnnotation)) {\n console.error(\n 'DiffFileRenderer.setupResizeObserver: Invalid element or annotation',\n { lineAnnotation, element }\n );\n continue;\n }\n let pairs = elementMap.get(lineAnnotation);\n if (pairs == null) {\n pairs = [];\n elementMap.set(lineAnnotation, pairs);\n }\n pairs.push(element);\n }\n\n for (const [key, pair] of elementMap) {\n if (pair.length !== 2) {\n console.error(\n 'DiffFileRenderer.setupResizeObserver: Bad Pair',\n key,\n pair\n );\n continue;\n }\n const [container1, container2] = pair;\n const child1 = container1.firstElementChild;\n const child2 = container2.firstElementChild;\n if (\n !(container1 instanceof HTMLElement) ||\n !(container2 instanceof HTMLElement) ||\n !(child1 instanceof HTMLElement) ||\n !(child2 instanceof HTMLElement)\n ) {\n continue;\n }\n\n let item = observedNodes.get(child1);\n\n if (item != null) {\n this.observedNodes.set(child1, item);\n this.observedNodes.set(child2, item);\n observedNodes.delete(child1);\n observedNodes.delete(child2);\n continue;\n }\n\n const child1Height = child1.getBoundingClientRect().height;\n const child2Height = child2.getBoundingClientRect().height;\n item = {\n type: 'annotations',\n column1: {\n container: container1,\n child: child1,\n childHeight: child1Height,\n },\n column2: {\n container: container2,\n child: child2,\n childHeight: child2Height,\n },\n currentHeight: 'auto',\n };\n annotationUpdates.add({\n child1,\n child2,\n item,\n newHeight: Math.max(child1Height, child2Height),\n });\n }\n\n // Measure all annotation heights first, then apply the paired min-height\n // styles after the read phase so setup does not bounce between layout\n // reads and writes for every annotation pair.\n for (const pendingUpdate of annotationUpdates) {\n this.applyNewHeight(pendingUpdate.item, pendingUpdate.newHeight);\n this.observedNodes.set(pendingUpdate.child1, pendingUpdate.item);\n this.observedNodes.set(pendingUpdate.child2, pendingUpdate.item);\n this.observe(pendingUpdate.child1);\n this.observe(pendingUpdate.child2);\n }\n annotationUpdates.clear();\n }\n\n // Cleanup any old nodes that might still be observed\n for (const [element, item] of observedNodes) {\n this.unobserve(element);\n if (item.type === 'code') {\n cleanupStaleCodeItem(item);\n } else {\n cleanupStaleAnnotationItem(item);\n }\n }\n observedNodes.clear();\n }\n\n cleanUp(): void {\n for (const element of this.observedNodes.keys()) {\n this.unobserve(element);\n }\n this.observedNodes.clear();\n }\n\n private observe(element: HTMLElement): void {\n const { managersByElement } = ResizeManager;\n const owner = managersByElement.get(element);\n // Already registered\n if (owner === this) {\n return;\n }\n // If we've already somehow registered with another manager, we in for a\n // world of pain, so complain loudly\n else if (owner != null && owner !== this) {\n throw new Error(\n 'ResizeManager.observe: element is already owned by another ResizeManager'\n );\n }\n managersByElement.set(element, this);\n ResizeManager.getResizeObserver().observe(element);\n }\n\n private unobserve(element: HTMLElement): void {\n const { managersByElement, resizeObserver } = ResizeManager;\n const owner = managersByElement.get(element);\n if (owner == null) {\n return;\n } else if (owner !== this) {\n throw new Error(\n 'ResizeManager.unobserve: element is owned by another ResizeManager'\n );\n }\n\n managersByElement.delete(element);\n resizeObserver?.unobserve(element);\n if (resizeObserver != null && managersByElement.size === 0) {\n resizeObserver.disconnect();\n ResizeManager.resizeObserver = undefined;\n }\n }\n\n private handleResizeEntries(entries: ResizeObserverEntry[]) {\n const codeUpdates: CodeUpdateMap = new Map();\n const annotationUpdates: Set<ObservedAnnotationNodes> = new Set();\n for (const entry of entries) {\n const { target, borderBoxSize, contentBoxSize } = entry;\n if (!(target instanceof HTMLElement)) {\n console.error(\n 'ResizeManager.handleResizeEntries: Invalid element for ResizeObserver',\n entry\n );\n continue;\n }\n const item = this.observedNodes.get(target);\n if (item == null) {\n console.error(\n 'ResizeManager.handleResizeEntries: Not a valid observed node',\n entry\n );\n continue;\n }\n if (item.type === 'annotations') {\n const column = (() => {\n if (target === item.column1.child) {\n return item.column1;\n }\n if (target === item.column2.child) {\n return item.column2;\n }\n return undefined;\n })();\n\n if (column == null) {\n console.error(\n `ResizeManager.handleResizeEntries: Couldn't find a column for`,\n { item, target }\n );\n continue;\n }\n\n column.childHeight = borderBoxSize[0].blockSize;\n annotationUpdates.add(item);\n } else if (item.type === 'code') {\n const update = codeUpdates.get(item) ?? {};\n const inlineSize = contentBoxSize[0].inlineSize;\n if (target === item.codeElement) {\n update.codeInlineSize = inlineSize;\n } else if (target === item.numberElement) {\n update.numberInlineSize = inlineSize;\n }\n codeUpdates.set(item, update);\n }\n }\n this.applyAnnotationUpdates(annotationUpdates);\n annotationUpdates.clear();\n this.applyColumnUpdates(codeUpdates);\n codeUpdates.clear();\n }\n\n private applyAnnotationUpdates(\n annotationUpdates: Set<ObservedAnnotationNodes>\n ) {\n for (const item of annotationUpdates) {\n this.applyNewHeight(\n item,\n Math.max(item.column1.childHeight, item.column2.childHeight)\n );\n }\n }\n\n private applyColumnUpdates = (queuedUpdates: CodeUpdateMap) => {\n for (const [item, update] of queuedUpdates) {\n const nextCodeWidth =\n update.codeInlineSize != null\n ? resolveCodeWidth(update.codeInlineSize)\n : item.codeWidth;\n const nextNumberWidth =\n update.numberInlineSize != null\n ? resolveNumberWidth(update.numberInlineSize)\n : item.numberWidth;\n const codeWidthChanged = nextCodeWidth !== item.codeWidth;\n const numberWidthChanged = nextNumberWidth !== item.numberWidth;\n\n if (!codeWidthChanged && !numberWidthChanged) {\n continue;\n }\n\n item.codeWidth = nextCodeWidth;\n item.numberWidth = nextNumberWidth;\n\n if (item.applyColumnVariables) {\n applyCodeColumnVariables(item, {\n codeWidthChanged,\n numberWidthChanged,\n });\n }\n }\n };\n\n private applyNewHeight(item: ObservedAnnotationNodes, newHeight: number) {\n if (newHeight !== item.currentHeight) {\n item.currentHeight = Math.max(newHeight, 0);\n item.column1.container.style.setProperty(\n '--diffs-annotation-min-height',\n `${item.currentHeight}px`\n );\n item.column2.container.style.setProperty(\n '--diffs-annotation-min-height',\n `${item.currentHeight}px`\n );\n }\n }\n}\n\nfunction resolveCodeWidth(inlineSize: number): number | 'auto' {\n const width = Math.max(Math.floor(inlineSize), 0);\n return width === 0 ? 'auto' : width;\n}\n\nfunction resolveNumberWidth(inlineSize: number): number {\n return Math.max(Math.ceil(inlineSize), 0);\n}\n\nfunction syncColumnVariableMode(\n item: ObservedGridNodes,\n applyColumnVariables: boolean\n): void {\n if (item.applyColumnVariables === applyColumnVariables) {\n return;\n }\n\n item.applyColumnVariables = applyColumnVariables;\n if (applyColumnVariables) {\n applyCodeColumnVariables(item, {\n codeWidthChanged: true,\n numberWidthChanged: true,\n });\n } else {\n removeCodeColumnVariables(item);\n }\n}\n\nfunction applyCodeColumnVariables(\n item: ObservedGridNodes,\n { codeWidthChanged, numberWidthChanged }: CodeColumnVariableChanges\n): void {\n const { codeElement, codeWidth, numberWidth } = item;\n if (codeWidthChanged) {\n codeElement.style.setProperty(\n '--diffs-column-width',\n `${typeof codeWidth === 'number' ? `${codeWidth}px` : 'auto'}`\n );\n }\n\n if (numberWidthChanged) {\n codeElement.style.setProperty(\n '--diffs-column-number-width',\n `${numberWidth === 0 ? 'auto' : `${numberWidth}px`}`\n );\n }\n\n if (codeWidthChanged || (numberWidthChanged && codeWidth !== 'auto')) {\n const targetWidth =\n typeof codeWidth === 'number' ? Math.max(codeWidth - numberWidth, 0) : 0;\n codeElement.style.setProperty(\n '--diffs-column-content-width',\n `${targetWidth > 0 ? `${targetWidth}px` : 'auto'}`\n );\n }\n}\n\nfunction removeCodeColumnVariables(item: ObservedGridNodes): void {\n item.codeElement.style.removeProperty('--diffs-column-content-width');\n item.codeElement.style.removeProperty('--diffs-column-number-width');\n item.codeElement.style.removeProperty('--diffs-column-width');\n}\n\nfunction cleanupStaleCodeItem(item: ObservedGridNodes): void {\n if (item.codeElement.isConnected) {\n removeCodeColumnVariables(item);\n }\n}\n\nfunction cleanupStaleAnnotationItem(item: ObservedAnnotationNodes): void {\n if (item.column1.container.isConnected) {\n item.column1.container.style.removeProperty(\n '--diffs-annotation-min-height'\n );\n }\n if (item.column2.container.isConnected) {\n item.column2.container.style.removeProperty(\n '--diffs-annotation-min-height'\n );\n }\n}\n", "import type { DiffsHighlighter, SupportedLanguages } from '../../types';\nimport { AttachedLanguages } from './constants';\n\nexport function areLanguagesAttached(\n languages: SupportedLanguages | SupportedLanguages[],\n highlighter?: DiffsHighlighter\n): boolean {\n const names = Array.isArray(languages) ? languages : [languages];\n if (highlighter != null) {\n return highlighter.hasLoadedLanguages(names);\n }\n return names.every(\n (name) => name === 'text' || name === 'ansi' || AttachedLanguages.has(name)\n );\n}\n", "import type { RenderRange } from '../types';\n\nexport function areRenderRangesEqual(\n renderRangeA: RenderRange | undefined,\n renderRangeB: RenderRange | undefined\n): boolean {\n if (renderRangeA == null || renderRangeB == null) {\n return renderRangeA === renderRangeB;\n }\n return (\n renderRangeA.startingLine === renderRangeB.startingLine &&\n renderRangeA.totalLines === renderRangeB.totalLines &&\n renderRangeA.bufferBefore === renderRangeB.bufferBefore &&\n renderRangeA.bufferAfter === renderRangeB.bufferAfter\n );\n}\n", "import type { Element as HASTElement } from 'hast';\n\nimport type { AnnotationSpan } from '../types';\nimport { createHastElement } from './hast_utils';\n\nexport function createAnnotationElement(span: AnnotationSpan): HASTElement {\n return createHastElement({\n tagName: 'div',\n children: [\n createHastElement({\n tagName: 'div',\n children: span.annotations?.map((slotId) =>\n createHastElement({ tagName: 'slot', properties: { name: slotId } })\n ),\n properties: { 'data-annotation-content': '' },\n }),\n ],\n properties: {\n 'data-line-annotation': `${span.hunkIndex},${span.lineIndex}`,\n },\n });\n}\n", "import type { SVGSpriteNames } from '../sprite';\nimport type { ChangeTypes } from '../types';\n\nexport function getIconForType(\n type: ChangeTypes | 'file'\n): Extract<\n SVGSpriteNames,\n | 'diffs-icon-file-code'\n | 'diffs-icon-symbol-modified'\n | 'diffs-icon-symbol-deleted'\n | 'diffs-icon-symbol-added'\n | 'diffs-icon-symbol-moved'\n> {\n switch (type) {\n case 'file':\n return 'diffs-icon-file-code';\n case 'change':\n return 'diffs-icon-symbol-modified';\n case 'new':\n return 'diffs-icon-symbol-added';\n case 'deleted':\n return 'diffs-icon-symbol-deleted';\n case 'rename-pure':\n case 'rename-changed':\n return 'diffs-icon-symbol-moved';\n }\n}\n", "import type { ElementContent, Element as HASTElement, Properties } from 'hast';\n\nimport {\n CUSTOM_HEADER_SLOT_ID,\n HEADER_FILENAME_SUFFIX_SLOT_ID,\n HEADER_METADATA_SLOT_ID,\n HEADER_PREFIX_SLOT_ID,\n} from '../constants';\nimport type {\n ChangeTypes,\n FileContents,\n FileDiffMetadata,\n FileHeaderRenderMode,\n} from '../types';\nimport { getIconForType } from './getIconForType';\nimport {\n createHastElement,\n createIconElement,\n createTextNodeElement,\n} from './hast_utils';\n\nexport interface CreateFileHeaderElementProps {\n fileOrDiff: FileDiffMetadata | FileContents;\n mode: FileHeaderRenderMode;\n stickyHeader: boolean;\n}\n\nexport function createFileHeaderElement({\n fileOrDiff,\n mode,\n stickyHeader,\n}: CreateFileHeaderElementProps): HASTElement {\n const fileDiff = 'type' in fileOrDiff ? fileOrDiff : undefined;\n const properties: Properties = {\n 'data-diffs-header': mode,\n 'data-change-type': fileDiff?.type,\n 'data-sticky': stickyHeader ? '' : undefined,\n };\n\n return createHastElement({\n tagName: 'div',\n children: [\n mode === 'custom'\n ? createHastElement({\n tagName: 'slot',\n properties: { name: CUSTOM_HEADER_SLOT_ID },\n })\n : createHeaderElement({\n name: fileOrDiff.name,\n prevName:\n 'prevName' in fileOrDiff ? fileOrDiff.prevName : undefined,\n iconType: fileDiff?.type ?? 'file',\n }),\n ...(mode === 'custom' ? [] : [createMetadataElement(fileDiff)]),\n ],\n properties,\n });\n}\n\ninterface CreateHeaderElementOptions {\n name: string;\n prevName?: string;\n iconType: ChangeTypes | 'file';\n}\n\nfunction createHeaderElement({\n name,\n prevName,\n iconType,\n}: CreateHeaderElementOptions): HASTElement {\n const children: ElementContent[] = [\n createHastElement({\n tagName: 'slot',\n properties: { name: HEADER_PREFIX_SLOT_ID },\n }),\n createIconElement({\n name: getIconForType(iconType),\n properties: { 'data-change-icon': iconType },\n }),\n ];\n if (prevName != null) {\n children.push(\n createHastElement({\n tagName: 'div',\n children: [\n createHastElement({\n tagName: 'bdi',\n children: [createTextNodeElement(prevName)],\n }),\n ],\n properties: {\n 'data-prev-name': '',\n },\n })\n );\n children.push(\n createIconElement({\n name: 'diffs-icon-arrow-right-short',\n properties: {\n 'data-rename-icon': '',\n },\n })\n );\n }\n children.push(\n createHastElement({\n tagName: 'div',\n children: [\n createHastElement({\n tagName: 'bdi',\n children: [createTextNodeElement(name)],\n }),\n ],\n properties: { 'data-title': '' },\n })\n );\n children.push(\n createHastElement({\n tagName: 'slot',\n properties: { name: HEADER_FILENAME_SUFFIX_SLOT_ID },\n })\n );\n return createHastElement({\n tagName: 'div',\n children,\n properties: { 'data-header-content': '' },\n });\n}\n\nfunction createMetadataElement(\n fileDiff: FileDiffMetadata | undefined\n): HASTElement {\n const children: ElementContent[] = [];\n if (fileDiff != null) {\n let additions = 0;\n let deletions = 0;\n for (const hunk of fileDiff.hunks) {\n additions += hunk.additionLines;\n deletions += hunk.deletionLines;\n }\n if (deletions > 0 || additions === 0) {\n children.push(\n createHastElement({\n tagName: 'span',\n children: [createTextNodeElement(`-${deletions}`)],\n properties: { 'data-deletions-count': '' },\n })\n );\n }\n if (additions > 0 || deletions === 0) {\n children.push(\n createHastElement({\n tagName: 'span',\n children: [createTextNodeElement(`+${additions}`)],\n properties: { 'data-additions-count': '' },\n })\n );\n }\n }\n children.push(\n createHastElement({\n tagName: 'slot',\n properties: { name: HEADER_METADATA_SLOT_ID },\n })\n );\n return createHastElement({\n tagName: 'div',\n children,\n properties: { 'data-metadata': '' },\n });\n}\n", "import type { Element as HASTElement, Properties } from 'hast';\n\nimport type { PrePropertiesConfig } from '../types';\nimport { createHastElement } from './hast_utils';\n\nexport function createPreElement(options: PrePropertiesConfig): HASTElement {\n return createHastElement({\n tagName: 'pre',\n properties: createPreWrapperProperties(options),\n });\n}\n\nexport function createPreWrapperProperties({\n diffIndicators,\n disableBackground,\n disableLineNumbers,\n overflow,\n split,\n totalLines,\n type,\n customProperties,\n}: PrePropertiesConfig): Properties {\n const properties: Properties = {\n // NOTE: We always apply custom properties first so the important\n // properties cannot be overridden\n ...customProperties,\n 'data-diff': type === 'diff' ? '' : undefined,\n 'data-file': type === 'file' ? '' : undefined,\n 'data-diff-type':\n type === 'diff' ? (split ? 'split' : 'single') : undefined,\n 'data-overflow': overflow,\n 'data-disable-line-numbers': disableLineNumbers ? '' : undefined,\n 'data-background': !disableBackground ? '' : undefined,\n 'data-indicators':\n diffIndicators === 'bars' || diffIndicators === 'classic'\n ? diffIndicators\n : undefined,\n // The pre is intentionally not focusable. It is not the scroll container\n // (`[data-code]` inside it is) and has no keyboard behavior of its own, so\n // a tabindex would only add a tab stop per diff and steal focus from a host\n // wrapper that wants to own keyboard navigation of the selection.\n style: `--diffs-min-number-column-width-default:${`${totalLines}`.length}ch;`,\n };\n\n return properties;\n}\n", "import type { ExtensionFormatMap, SupportedLanguages } from '../types';\n\nconst CUSTOM_EXTENSION_TO_FILE_FORMAT: Map<string, SupportedLanguages> =\n new Map();\n\nlet customExtensionsVersion = 0;\n\nexport const EXTENSION_TO_FILE_FORMAT: ExtensionFormatMap = {\n '1c': '1c',\n abap: 'abap',\n as: 'actionscript-3',\n ada: 'ada',\n adb: 'ada',\n ads: 'ada',\n adoc: 'asciidoc',\n asciidoc: 'asciidoc',\n 'component.html': 'angular-html',\n 'component.ts': 'angular-ts',\n conf: 'nginx',\n htaccess: 'apache',\n cls: 'tex',\n trigger: 'apex',\n apl: 'apl',\n applescript: 'applescript',\n scpt: 'applescript',\n ara: 'ara',\n asm: 'asm',\n s: 'riscv',\n astro: 'astro',\n awk: 'awk',\n bal: 'ballerina',\n sh: 'zsh',\n bash: 'zsh',\n bat: 'cmd',\n cmd: 'cmd',\n be: 'berry',\n beancount: 'beancount',\n bib: 'bibtex',\n bicep: 'bicep',\n 'blade.php': 'blade',\n bsl: 'bsl',\n c: 'c',\n h: 'objective-cpp',\n cs: 'csharp',\n cpp: 'cpp',\n hpp: 'cpp',\n cc: 'cpp',\n cxx: 'cpp',\n hh: 'cpp',\n cdc: 'cdc',\n cairo: 'cairo',\n clar: 'clarity',\n clj: 'clojure',\n cljs: 'clojure',\n cljc: 'clojure',\n soy: 'soy',\n cmake: 'cmake',\n 'CMakeLists.txt': 'cmake',\n cob: 'cobol',\n cbl: 'cobol',\n cobol: 'cobol',\n CODEOWNERS: 'codeowners',\n ql: 'ql',\n coffee: 'coffeescript',\n lisp: 'lisp',\n cl: 'lisp',\n lsp: 'lisp',\n log: 'log',\n v: 'verilog',\n cql: 'cql',\n cr: 'crystal',\n css: 'css',\n csv: 'csv',\n cue: 'cue',\n cypher: 'cypher',\n cyp: 'cypher',\n d: 'd',\n dart: 'dart',\n dax: 'dax',\n desktop: 'desktop',\n diff: 'diff',\n patch: 'diff',\n Dockerfile: 'dockerfile',\n dockerfile: 'dockerfile',\n env: 'dotenv',\n dm: 'dream-maker',\n edge: 'edge',\n el: 'emacs-lisp',\n ex: 'elixir',\n exs: 'elixir',\n elm: 'elm',\n erb: 'erb',\n erl: 'erlang',\n hrl: 'erlang',\n f: 'fortran-fixed-form',\n for: 'fortran-fixed-form',\n fs: 'fsharp',\n fsi: 'fsharp',\n fsx: 'fsharp',\n f03: 'f03',\n f08: 'f08',\n f18: 'f18',\n f77: 'f77',\n f90: 'fortran-free-form',\n f95: 'fortran-free-form',\n fnl: 'fennel',\n fish: 'fish',\n ftl: 'ftl',\n tres: 'gdresource',\n res: 'gdresource',\n gd: 'gdscript',\n gdshader: 'gdshader',\n gs: 'genie',\n feature: 'gherkin',\n COMMIT_EDITMSG: 'git-commit',\n 'git-rebase-todo': 'git-rebase',\n gjs: 'glimmer-js',\n gleam: 'gleam',\n gts: 'glimmer-ts',\n glsl: 'glsl',\n vert: 'glsl',\n frag: 'glsl',\n shader: 'shaderlab',\n gp: 'gnuplot',\n plt: 'gnuplot',\n gnuplot: 'gnuplot',\n go: 'go',\n graphql: 'graphql',\n gql: 'graphql',\n groovy: 'groovy',\n gvy: 'groovy',\n hack: 'hack',\n haml: 'haml',\n hbs: 'handlebars',\n handlebars: 'handlebars',\n hs: 'haskell',\n lhs: 'haskell',\n hx: 'haxe',\n hcl: 'hcl',\n hjson: 'hjson',\n hlsl: 'hlsl',\n fx: 'hlsl',\n html: 'html',\n htm: 'html',\n http: 'http',\n rest: 'http',\n hxml: 'hxml',\n hy: 'hy',\n imba: 'imba',\n ini: 'ini',\n cfg: 'ini',\n jade: 'pug',\n pug: 'pug',\n java: 'java',\n js: 'javascript',\n mjs: 'javascript',\n cjs: 'javascript',\n jinja: 'jinja',\n jinja2: 'jinja',\n j2: 'jinja',\n jison: 'jison',\n jl: 'julia',\n json: 'json',\n json5: 'json5',\n jsonc: 'jsonc',\n jsonl: 'jsonl',\n jsonnet: 'jsonnet',\n libsonnet: 'jsonnet',\n jssm: 'jssm',\n jsx: 'jsx',\n kt: 'kotlin',\n kts: 'kts',\n kql: 'kusto',\n tex: 'tex',\n ltx: 'tex',\n lean: 'lean4',\n less: 'less',\n liquid: 'liquid',\n lit: 'lit',\n ll: 'llvm',\n logo: 'logo',\n lua: 'lua',\n luau: 'luau',\n Makefile: 'makefile',\n mk: 'makefile',\n makefile: 'makefile',\n md: 'markdown',\n markdown: 'markdown',\n marko: 'marko',\n m: 'wolfram',\n mat: 'matlab',\n mdc: 'mdc',\n mdx: 'mdx',\n wiki: 'wikitext',\n mediawiki: 'wikitext',\n mmd: 'mermaid',\n mermaid: 'mermaid',\n mips: 'mipsasm',\n mojo: 'mojo',\n '🔥': 'mojo',\n move: 'move',\n nar: 'narrat',\n nf: 'nextflow',\n nim: 'nim',\n nims: 'nim',\n nimble: 'nim',\n nix: 'nix',\n nu: 'nushell',\n mm: 'objective-cpp',\n ml: 'ocaml',\n mli: 'ocaml',\n mll: 'ocaml',\n mly: 'ocaml',\n odin: 'odin',\n pas: 'pascal',\n p: 'pascal',\n pl: 'prolog',\n pm: 'perl',\n t: 'perl',\n raku: 'raku',\n p6: 'raku',\n pl6: 'raku',\n php: 'php',\n phtml: 'php',\n pls: 'plsql',\n sql: 'sql',\n po: 'po',\n polar: 'polar',\n pcss: 'postcss',\n pot: 'pot',\n potx: 'potx',\n pq: 'powerquery',\n pqm: 'powerquery',\n ps1: 'powershell',\n psm1: 'powershell',\n psd1: 'powershell',\n prisma: 'prisma',\n pro: 'prolog',\n P: 'prolog',\n properties: 'properties',\n proto: 'protobuf',\n pp: 'puppet',\n purs: 'purescript',\n py: 'python',\n pyw: 'python',\n pyi: 'python',\n // FIXME: these should be changed to a Starlark file type if/when one\n // appears in shiki. For now, Starlark is highlighted like the Python subset\n // it is.\n BUCK: 'python',\n BUILD: 'python',\n PACKAGE: 'python',\n WORKSPACE: 'python',\n Tiltfile: 'python',\n bazel: 'python',\n bxl: 'python',\n bzl: 'python',\n bzlmod: 'python',\n star: 'python',\n sky: 'python',\n qml: 'qml',\n qmldir: 'qmldir',\n qss: 'qss',\n r: 'r',\n R: 'r',\n rkt: 'racket',\n rktl: 'racket',\n razor: 'razor',\n cshtml: 'razor',\n rb: 'ruby',\n rbw: 'ruby',\n reg: 'reg',\n regex: 'regexp',\n rel: 'rel',\n rs: 'rust',\n rst: 'rst',\n rake: 'ruby',\n gemspec: 'ruby',\n jbuilder: 'ruby',\n builder: 'ruby',\n rabl: 'ruby',\n arb: 'ruby',\n ru: 'ruby',\n podspec: 'ruby',\n Gemfile: 'ruby',\n Rakefile: 'ruby',\n Guardfile: 'ruby',\n Capfile: 'ruby',\n Berksfile: 'ruby',\n Brewfile: 'ruby',\n Vagrantfile: 'ruby',\n Thorfile: 'ruby',\n Appraisals: 'ruby',\n Dangerfile: 'ruby',\n sas: 'sas',\n sass: 'sass',\n scala: 'scala',\n sc: 'scala',\n scm: 'scheme',\n ss: 'scheme',\n sld: 'scheme',\n scss: 'scss',\n sdbl: 'sdbl',\n shadergraph: 'shader',\n st: 'smalltalk',\n sol: 'solidity',\n sparql: 'sparql',\n rq: 'sparql',\n spl: 'splunk',\n config: 'ssh-config',\n do: 'stata',\n ado: 'stata',\n dta: 'stata',\n styl: 'stylus',\n stylus: 'stylus',\n svelte: 'svelte',\n swift: 'swift',\n sv: 'system-verilog',\n svh: 'system-verilog',\n service: 'systemd',\n socket: 'systemd',\n device: 'systemd',\n timer: 'systemd',\n talon: 'talonscript',\n tasl: 'tasl',\n tcl: 'tcl',\n templ: 'templ',\n tf: 'tf',\n tfvars: 'tfvars',\n toml: 'toml',\n ts: 'typescript',\n mts: 'typescript',\n cts: 'typescript',\n tsp: 'typespec',\n tsv: 'tsv',\n tsx: 'tsx',\n ttl: 'turtle',\n twig: 'twig',\n typ: 'typst',\n vv: 'v',\n vala: 'vala',\n vapi: 'vala',\n vb: 'vb',\n vbs: 'vb',\n bas: 'vb',\n vh: 'verilog',\n vhd: 'vhdl',\n vhdl: 'vhdl',\n vim: 'vimscript',\n vue: 'vue',\n 'vine.ts': 'vue-vine',\n vy: 'vyper',\n wasm: 'wasm',\n wat: 'wasm',\n wy: '文言',\n wgsl: 'wgsl',\n wit: 'wit',\n wl: 'wolfram',\n nb: 'wolfram',\n xml: 'xml',\n xsl: 'xsl',\n xslt: 'xsl',\n yaml: 'yaml',\n yml: 'yml',\n zs: 'zenscript',\n zig: 'zig',\n zsh: 'zsh',\n sty: 'tex',\n};\n\nexport function getFiletypeFromFileName(fileName: string): SupportedLanguages {\n const format = matchFiletypeFromName(fileName);\n if (format != null) {\n return format;\n }\n\n // Special files are keyed by their exact name (Dockerfile, CMakeLists.txt), but callers\n // routinely pass a repository-relative path. Retry on the basename so `docker/Dockerfile`\n // resolves the same way a top-level `Dockerfile` does. The retry only runs once the full\n // path has matched nothing, so real extensions still win (e.g. `docker/Dockerfile.ts`).\n const baseName = fileName.split(/[/\\\\]/).pop() ?? fileName;\n return baseName === fileName\n ? 'text'\n : (matchFiletypeFromName(baseName) ?? 'text');\n}\n\nfunction matchFiletypeFromName(fileName: string): SupportedLanguages | null {\n if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(fileName)) {\n return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(fileName) ?? 'text';\n }\n // Handle special files without extensions first\n if (Object.hasOwn(EXTENSION_TO_FILE_FORMAT, fileName)) {\n return EXTENSION_TO_FILE_FORMAT[fileName] ?? null;\n }\n\n // Try compound extensions first (e.g., .blade.php, .component.ts)\n const compoundMatch = fileName.match(/\\.([^/\\\\]+\\.[^/\\\\]+)$/);\n if (compoundMatch != null) {\n if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(compoundMatch[1])) {\n return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(compoundMatch[1]) ?? 'text';\n }\n if (Object.hasOwn(EXTENSION_TO_FILE_FORMAT, compoundMatch[1])) {\n return EXTENSION_TO_FILE_FORMAT[compoundMatch[1]] ?? 'text';\n }\n }\n\n // Fall back to simple extension\n const simpleMatch = fileName.match(/\\.([^.]+)$/)?.[1] ?? '';\n if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(simpleMatch)) {\n return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(simpleMatch) ?? 'text';\n }\n return Object.hasOwn(EXTENSION_TO_FILE_FORMAT, simpleMatch)\n ? (EXTENSION_TO_FILE_FORMAT[simpleMatch] ?? 'text')\n : null;\n}\n\nexport function replaceCustomExtensions(\n version: number,\n map: ExtensionFormatMap\n): boolean {\n if (version <= customExtensionsVersion) {\n return false;\n }\n CUSTOM_EXTENSION_TO_FILE_FORMAT.clear();\n for (const key in map) {\n const lang = map[key];\n if (lang != null) {\n CUSTOM_EXTENSION_TO_FILE_FORMAT.set(key, lang);\n }\n }\n customExtensionsVersion = version;\n return true;\n}\n\nexport function getCustomExtensionsVersion(): number {\n return customExtensionsVersion;\n}\n\nexport function setCustomExtension(\n key: string,\n lang: SupportedLanguages\n): boolean {\n const existing = CUSTOM_EXTENSION_TO_FILE_FORMAT.get(key);\n if (existing === lang) {\n return false;\n }\n if (existing != null) {\n console.warn(\n `setCustomExtension: overriding custom mapping for \"${key}\" from \"${existing}\" to \"${lang}\"`\n );\n }\n CUSTOM_EXTENSION_TO_FILE_FORMAT.set(key, lang);\n customExtensionsVersion++;\n return true;\n}\n\nexport function getCustomExtensionsMap(): ExtensionFormatMap {\n return Object.fromEntries(CUSTOM_EXTENSION_TO_FILE_FORMAT);\n}\n", "import { resolveHighlighterType } from '../highlighter/highlighterType';\nimport type {\n DiffsThemeNames,\n HighlighterTypes,\n SupportedLanguages,\n ThemesType,\n} from '../types';\nimport { getThemes } from './getThemes';\n\ninterface HighlighterOptionsShape {\n theme?: DiffsThemeNames | ThemesType;\n preferredHighlighter?: HighlighterTypes;\n}\n\ninterface GetHighlighterOptionsReturn {\n langs: SupportedLanguages[];\n themes: DiffsThemeNames[];\n preferredHighlighter: HighlighterTypes;\n}\n\nexport function getHighlighterOptions(\n lang: SupportedLanguages | SupportedLanguages[] | undefined,\n { theme, preferredHighlighter }: HighlighterOptionsShape\n): GetHighlighterOptionsReturn {\n return {\n langs: Array.isArray(lang) ? lang : [lang ?? 'text'],\n themes: getThemes(theme),\n preferredHighlighter: resolveHighlighterType(preferredHighlighter),\n };\n}\n", "import type { DiffLineAnnotation, LineAnnotation } from '../types';\n\nexport function getLineAnnotationName<T = undefined>(\n annotation: LineAnnotation<T> | DiffLineAnnotation<T>\n): string {\n return `annotation-${'side' in annotation ? `${annotation.side}-` : ''}${annotation.lineNumber}`;\n}\n", "import type { RenderRange } from '../types';\n\nexport function isDefaultRenderRange(renderRange: RenderRange): boolean {\n return (\n renderRange.startingLine === 0 &&\n renderRange.totalLines === Infinity &&\n renderRange.bufferBefore === 0 &&\n renderRange.bufferAfter === 0\n );\n}\n", "/**\n * Canonical color/contrast primitives\n */\n\n// MIN_READABLE_RATIO is the primary-foreground floor (WCAG AA large text); used\n// when picking the most legible foreground token for a surface.\nexport const MIN_READABLE_RATIO = 3;\n// MIN_MUTED_RATIO is the muted-text floor (WCAG AA normal text); used when\n// deciding whether a description/muted token is readable on a surface.\nexport const MIN_MUTED_RATIO = 4.5;\n\n// Matches a fully-transparent hex color: a 4-digit form whose alpha nibble is\n// 0 (`#rgb0`) or an 8-digit form whose alpha byte is 00 (`#rrggbb00`).\nconst HEX_TRANSPARENT_RE = /^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i;\n// Matches an alpha component that is effectively zero: `0`, `0.0`, `0%`, etc.\nconst ALPHA_ZERO_RE = /^0(?:\\.0+)?%?$/;\n\n// Extracts the alpha component from a functional color notation\n// (rgb/rgba/hsl/hsla/hwb/lab/lch/oklab/oklch/color). Supports both the modern\n// slash syntax (`rgb(0 0 0 / 0)`) and the legacy comma syntax\n// (`rgba(0, 0, 0, 0)`). Returns undefined when the input isn't a recognized\n// functional notation or has no alpha component. Used by isFullyTransparent to\n// detect zero-alpha colors without a full CSS color parser.\nfunction getFunctionalAlpha(color: string): string | undefined {\n const openParen = color.indexOf('(');\n if (openParen <= 0 || !color.endsWith(')')) {\n return undefined;\n }\n\n const fn = color.slice(0, openParen).trim();\n if (!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(fn)) {\n return undefined;\n }\n\n const inner = color.slice(openParen + 1, -1).trim();\n if (inner.length === 0) {\n return undefined;\n }\n\n // Modern functional syntax: rgb(0 0 0 / 0), color(... / 0%), etc.\n const slashIndex = inner.lastIndexOf('/');\n if (slashIndex !== -1) {\n return inner.slice(slashIndex + 1).trim();\n }\n\n // Legacy syntax: rgba(0, 0, 0, 0), hsla(210, 40%, 50%, 0.0)\n if (/^(?:rgba|hsla)$/i.test(fn)) {\n const parts = inner.split(',');\n if (parts.length === 4) {\n return parts[3]?.trim();\n }\n }\n\n return undefined;\n}\n\n// Parses `#rgb`, `#rrggbb`, or `#rrggbbaa` into [r, g, b, a] with channels in\n// [0, 255] and alpha in [0, 1]. Returns null for any other format. Stay in\n// 0..255 (not normalized) and alpha is decoded from the 8-digit form.\nexport function parseHexRgba(\n color: string\n): readonly [number, number, number, number] | null {\n // The \\b anchor is inherited from the diffshub source to preserve parity.\n // Callers pass trimmed bare hex strings, so \\b matches the end of the whole color.\n const match = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\\b/i.exec(color.trim());\n if (match == null) return null;\n const hex = match[1];\n let expanded: string;\n let alpha = 1;\n if (hex.length === 3) {\n expanded = hex\n .split('')\n .map((c) => c + c)\n .join('');\n } else if (hex.length === 6) {\n expanded = hex;\n } else {\n expanded = hex.slice(0, 6);\n alpha = parseInt(hex.slice(6, 8), 16) / 255;\n }\n return [\n parseInt(expanded.slice(0, 2), 16),\n parseInt(expanded.slice(2, 4), 16),\n parseInt(expanded.slice(4, 6), 16),\n alpha,\n ];\n}\n\n// WCAG relative luminance of a hex color in [0, 1], or null for non-hex inputs\n// (var(...), color-mix(...), named colors) and undefined.\n//\n// Accepts 3-, 6-, AND 8-digit hex. The alpha byte of an 8-digit color is\n// IGNORED for the luminance computation\nexport function relativeLuminance(color?: string): number | null {\n if (color == null) return null;\n const rgba = parseHexRgba(color);\n if (rgba == null) return null;\n // parseHexRgba returns channels in 0..255; normalize to 0..1, dropping alpha.\n const r = rgba[0] / 255;\n const g = rgba[1] / 255;\n const b = rgba[2] / 255;\n // sRGB channel → linear → weighted sum (WCAG formula).\n const channel = (v: number): number =>\n v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);\n}\n\n// WCAG contrast ratio between two luminances: (lighter + 0.05) / (darker + 0.05).\n// Symmetric in its arguments.\nexport function contrastRatio(a: number, b: number): number {\n const [hi, lo] = a > b ? [a, b] : [b, a];\n return (hi + 0.05) / (lo + 0.05);\n}\n\n// Composites a hex (`#rrggbb` or `#rrggbbaa`) foreground over a hex background\n// and returns the resulting opaque `#rrggbb`. Used to measure the actual\n// contrast of semi-transparent tokens (e.g. `#576daf79`) against the surface\n// they'll render on, rather than the alpha-stripped base color. Returns\n// undefined when no background is given or either color is unparseable.\nexport function compositeOverBg(\n fgColor: string,\n bgColor?: string\n): string | undefined {\n if (bgColor == null) return undefined;\n const fgParts = parseHexRgba(fgColor);\n const bgParts = parseHexRgba(bgColor);\n if (fgParts == null || bgParts == null) return undefined;\n const [fr, fg, fb, fa] = fgParts;\n const [br, bg, bb] = bgParts;\n const r = Math.round(fr * fa + br * (1 - fa));\n const g = Math.round(fg * fa + bg * (1 - fa));\n const b = Math.round(fb * fa + bb * (1 - fa));\n return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');\n}\n\n// True when a color is fully transparent: the `transparent` keyword, a\n// zero-alpha hex (`#rgb0` / `#rrggbb00`), or a functional color whose alpha\n// component is effectively zero (`rgba(0,0,0,0)`, `hsla(0,0%,0%,0)`,\n// `rgb(0 0 0 / 0%)`). Returns false for undefined and for any opaque color.\nexport function isFullyTransparent(color?: string): boolean {\n if (color == null) return false;\n const normalized = color.trim().toLowerCase();\n if (normalized === 'transparent') return true;\n if (HEX_TRANSPARENT_RE.test(normalized)) return true;\n\n const alpha = getFunctionalAlpha(normalized);\n return alpha != null && ALPHA_ZERO_RE.test(alpha);\n}\n\n// True when a chrome surface is perceptually dark. Prefers the surface's own\n// luminance (dark when < 0.4); when the bg hex isn't parseable, falls back to a\n// foreground hint (light fg, luminance > 0.6 → dark surface, the conventional\n// pairing). An undefined or unparseable fgHint behaves like a miss → false.\nexport function isDarkSurface(bg?: string, fgHint?: string): boolean {\n const fromBg = relativeLuminance(bg);\n if (fromBg != null) return fromBg < 0.4;\n const fromFg = relativeLuminance(fgHint);\n return fromFg != null ? fromFg > 0.6 : false;\n}\n\n// True when two colors read as the \"same surface\": identical hex (case- and\n// whitespace-insensitive) or close enough in luminance (Δ < 0.06) that a border\n// tuned for one looks right on the other. Non-hex inputs we can't measure, and\n// undefined inputs, are treated as non-matching.\nexport function surfacesMatch(a?: string, b?: string): boolean {\n if (a == null || b == null) return false;\n if (a.trim().toLowerCase() === b.trim().toLowerCase()) return true;\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n if (la == null || lb == null) return false;\n return Math.abs(la - lb) < 0.06;\n}\n\n// True when `hover` is closer in luminance to `fg` than to `bg` — i.e. the\n// hover surface would land on top of the row text rather than next to it,\n// erasing legibility. Returns false when bg or fg is missing, or when any color\n// can't be parsed (unknown format → trust the theme designer's intent).\nexport function hoverWouldEraseText(\n hover: string,\n bg: string | undefined,\n fg: string | undefined\n): boolean {\n if (bg == null || fg == null) return false;\n const hoverL = relativeLuminance(hover);\n const bgL = relativeLuminance(bg);\n const fgL = relativeLuminance(fg);\n if (hoverL == null || bgL == null || fgL == null) return false;\n return Math.abs(hoverL - fgL) < Math.abs(hoverL - bgL);\n}\n\n// Walks `candidates` in priority order. Returns the first color whose contrast\n// against `bg` clears MIN_READABLE_RATIO. If nothing reaches that bar, returns\n// the candidate with the highest contrast — that keeps weakly-typed themes\n// (where everything is dim) on the brightest available token rather than\n// silently picking the first dim one. Non-hex candidates (var(...),\n// color-mix(...), named colors) can't be measured here without rendering;\n// they're treated as opaque misses and only returned via the `firstDefined`\n// fallback when nothing parses.\nexport function pickReadableForeground(\n bg: string | undefined,\n candidates: ReadonlyArray<string | undefined>\n): string | undefined {\n const bgL = relativeLuminance(bg);\n const firstDefined = candidates.find(\n (candidate) => candidate != null && candidate !== ''\n );\n if (bgL == null) return firstDefined;\n let best: string | undefined;\n let bestRatio = -1;\n for (const candidate of candidates) {\n if (candidate == null || candidate === '') continue;\n const candidateL = relativeLuminance(candidate);\n if (candidateL == null) continue;\n const ratio = contrastRatio(bgL, candidateL);\n if (ratio >= MIN_READABLE_RATIO) return candidate;\n if (ratio > bestRatio) {\n best = candidate;\n bestRatio = ratio;\n }\n }\n return best ?? firstDefined;\n}\n\n// Mixes primaryFg toward bg until the result clears MIN_MUTED_RATIO, stepping\n// from a strong-hierarchy 60% blend up to 90%. Returning primaryFg as a final\n// fallback flattens the muted/primary hierarchy on extreme palettes, which is\n// the correct tradeoff: dim but legible chrome beats stylish but unreadable\n// chrome. Falls back to a CSS `color-mix` expression when either input isn't a\n// parseable hex — the browser can still composite, we just can't verify the\n// contrast.\nexport function deriveMutedFg(\n primaryFg: string,\n bg: string | undefined\n): string {\n if (bg == null) return primaryFg;\n const fgParts = parseHexRgba(primaryFg);\n const bgParts = parseHexRgba(bg);\n const bgL = relativeLuminance(bg);\n if (fgParts == null || bgParts == null || bgL == null) {\n return `color-mix(in srgb, ${primaryFg} 70%, ${bg})`;\n }\n const [fr, fg2, fb] = fgParts;\n const [br, bg3, bb] = bgParts;\n for (const weight of [0.6, 0.7, 0.8, 0.9]) {\n const r = Math.round(fr * weight + br * (1 - weight));\n const g = Math.round(fg2 * weight + bg3 * (1 - weight));\n const b = Math.round(fb * weight + bb * (1 - weight));\n const hex =\n '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');\n const L = relativeLuminance(hex);\n if (L != null && contrastRatio(bgL, L) >= MIN_MUTED_RATIO) {\n return hex;\n }\n }\n return primaryFg;\n}\n", "/**\n * normalizeThemeColors is the public front door for reading the colors a\n * Shiki/VS Code theme defines. It returns a SAME-SHAPE theme (same top-level\n * fields, same `colors` key vocabulary) whose `colors` map has the standard\n * fallback chains applied and a few universal repairs done, so every consumer\n * reads one resolved set of workbench keys instead of re-deriving the chains.\n *\n * It does NOT touch syntax/editor token colors or the base fg/bg/type — those\n * are owned by Shiki's normalizeTheme upstream, and this function assumes a\n * theme that has already passed through it. Do not confuse the two:\n * `normalizeTheme` (Shiki) normalizes the whole theme; `normalizeThemeColors`\n * (here) only resolves the workbench `colors` map.\n *\n * What it fills (mechanical fallback, no opinion):\n * - surfaces: editor/sideBar background+foreground, input.background,\n * sideBarSectionHeader.foreground, list.activeSelectionForeground — via the\n * editor→base and sideBar→editor→base precedence.\n * - git status: gitDecoration.{added,modified,deleted}ResourceForeground via\n * the gitDecoration → terminal.ansi* → editorGutter.* chain.\n * - focus ring: list.focusOutline set to the first NON-transparent of\n * [list.focusOutline, focusBorder].\n *\n * What it repairs (universal correctness, the ceiling of what it adds):\n * - drops list.hoverBackground when it exactly equals the sidebar surface or\n * would land on top of the row text (hoverWouldEraseText) — a hover that\n * erases legibility is broken for any consumer.\n *\n * What it deliberately leaves alone (consumer presentation opinion):\n * - the selection lookup (list.activeSelectionBackground vs the same-surface\n * swap to list.focusBackground) stays a consumer recipe; the raw keys pass\n * through untouched so a consumer can apply its own choice.\n *\n * The result is pure, frozen, and WeakMap-memoized per input theme, and the\n * function is idempotent: normalizeThemeColors(normalizeThemeColors(t)) yields\n * an equal result. That idempotency is what lets it run lazily at read time\n * (the default) OR be pre-applied at load time and seeded — without a consumer\n * ever getting a different answer.\n *\n * The fallback chains are small and used only here, so they are inlined rather\n * than split into a separate resolver module.\n */\nimport { hoverWouldEraseText, isFullyTransparent } from './color';\nimport type { ThemeLike } from './types';\n\nconst cache = new WeakMap<ThemeLike, ThemeLike>();\n\nexport function normalizeThemeColors(theme: ThemeLike): ThemeLike {\n const cached = cache.get(theme);\n if (cached != null) return cached;\n\n const originalColors = theme.colors ?? {};\n const colors: Record<string, string> = { ...originalColors };\n\n // Surface precedence: the editor falls back to the base theme bg/fg, and the\n // sidebar falls back to the editor. Plain `??` so an explicit value is honored\n // and the chain never invents a color.\n const editorBackground = originalColors['editor.background'] ?? theme.bg;\n const editorForeground = originalColors['editor.foreground'] ?? theme.fg;\n const sidebarBackground =\n originalColors['sideBar.background'] ?? editorBackground;\n const sidebarForeground =\n originalColors['sideBar.foreground'] ?? editorForeground;\n\n // Write each resolved surface back onto its canonical key so consumers read a\n // single key instead of re-walking the chain.\n fill(colors, 'editor.background', editorBackground);\n fill(colors, 'editor.foreground', editorForeground);\n fill(colors, 'sideBar.background', sidebarBackground);\n fill(colors, 'sideBar.foreground', sidebarForeground);\n fill(\n colors,\n 'input.background',\n originalColors['input.background'] ?? sidebarBackground\n );\n fill(\n colors,\n 'sideBarSectionHeader.foreground',\n originalColors['sideBarSectionHeader.foreground'] ?? sidebarForeground\n );\n fill(\n colors,\n 'list.activeSelectionForeground',\n originalColors['list.activeSelectionForeground'] ?? sidebarForeground\n );\n\n // Git status foreground chains: the dedicated gitDecoration key, then the\n // terminal ANSI color, then the editor gutter background (which catches\n // gutter-only themes like vesper). firstColor skips empty strings so a blank\n // key falls through to the next tier.\n fill(\n colors,\n 'gitDecoration.addedResourceForeground',\n firstColor(\n originalColors['gitDecoration.addedResourceForeground'],\n originalColors['terminal.ansiGreen'],\n originalColors['editorGutter.addedBackground']\n )\n );\n fill(\n colors,\n 'gitDecoration.modifiedResourceForeground',\n firstColor(\n originalColors['gitDecoration.modifiedResourceForeground'],\n originalColors['terminal.ansiBlue'],\n originalColors['editorGutter.modifiedBackground']\n )\n );\n fill(\n colors,\n 'gitDecoration.deletedResourceForeground',\n firstColor(\n originalColors['gitDecoration.deletedResourceForeground'],\n originalColors['terminal.ansiRed'],\n originalColors['editorGutter.deletedBackground']\n )\n );\n\n // Focus ring: first non-transparent of [list.focusOutline, focusBorder]. A\n // transparent outline is rejected so the resolved key is always a visible\n // color; if neither candidate is visible the key is left absent.\n const focusRing =\n (isFullyTransparent(originalColors['list.focusOutline'])\n ? undefined\n : originalColors['list.focusOutline']) ??\n (isFullyTransparent(originalColors['focusBorder'])\n ? undefined\n : originalColors['focusBorder']);\n if (focusRing != null) {\n colors['list.focusOutline'] = focusRing;\n } else {\n delete colors['list.focusOutline'];\n }\n\n // Hover repair: a hover background that exactly matches the surface, or that\n // sits closer to the text color than the surface (so it would erase the row\n // text), is unusable for any consumer — drop it and let the consumer apply its\n // own hover default.\n const hover = originalColors['list.hoverBackground'];\n if (\n hover != null &&\n (matchesSurface(hover, sidebarBackground) ||\n hoverWouldEraseText(hover, sidebarBackground, sidebarForeground))\n ) {\n delete colors['list.hoverBackground'];\n }\n\n const result = Object.freeze({ ...theme, colors: Object.freeze(colors) });\n cache.set(theme, result);\n return result;\n}\n\n// Writes `value` to `key` only when it is a real color, so an absent source key\n// stays absent rather than being coerced to undefined/''.\nfunction fill(\n colors: Record<string, string>,\n key: string,\n value: string | undefined\n): void {\n if (value != null && value !== '') colors[key] = value;\n}\n\n// Returns the first non-empty color among the candidates, in priority order.\n// Skipping '' lets a blank workbench key fall through to the next tier.\nfunction firstColor(...candidates: (string | undefined)[]): string | undefined {\n for (const candidate of candidates) {\n if (candidate != null && candidate !== '') return candidate;\n }\n return undefined;\n}\n\n// Case-insensitive exact-string surface match (NOT a luminance-based compare).\n// Matches the equality the hover repair has always used.\nfunction matchesSurface(color: string, surface: string | undefined): boolean {\n return surface != null && color.toLowerCase() === surface.toLowerCase();\n}\n", "import { normalizeThemeColors } from '@pierre/theming/color';\n\nimport { DEFAULT_THEMES } from '../constants';\nimport type {\n DiffsHighlighter,\n DiffsTheme,\n DiffsThemeNames,\n ThemesType,\n} from '../types';\nimport { formatCSSVariablePrefix } from './formatCSSVariablePrefix';\n\ninterface GetHighlighterThemeStylesProps {\n theme?: DiffsThemeNames | ThemesType;\n highlighter: DiffsHighlighter;\n prefix?: string;\n}\n\nexport function getHighlighterThemeStyles({\n theme = DEFAULT_THEMES,\n highlighter,\n prefix,\n}: GetHighlighterThemeStylesProps): string {\n let styles = '';\n if (typeof theme === 'string') {\n const themeData = highlighter.getTheme(theme);\n const normalized = getThemeColors(themeData, highlighter);\n styles += `color:${normalized.fg};`;\n styles += `background-color:${normalized.bg};`;\n styles += `${formatCSSVariablePrefix('global')}fg:${normalized.fg};`;\n styles += `${formatCSSVariablePrefix('global')}bg:${normalized.bg};`;\n styles += getGitVariables(themeData, prefix);\n } else {\n let themeData = highlighter.getTheme(theme.dark);\n let normalized = getThemeColors(themeData, highlighter);\n styles += `${formatCSSVariablePrefix('global')}dark:${normalized.fg};`;\n styles += `${formatCSSVariablePrefix('global')}dark-bg:${normalized.bg};`;\n styles += getGitVariables(themeData, 'dark');\n\n themeData = highlighter.getTheme(theme.light);\n normalized = getThemeColors(themeData, highlighter);\n styles += `${formatCSSVariablePrefix('global')}light:${normalized.fg};`;\n styles += `${formatCSSVariablePrefix('global')}light-bg:${normalized.bg};`;\n styles += getGitVariables(themeData, 'light');\n }\n return styles;\n}\n\n// cssVariables: true must use the same prefix for backgrounds and tokens.\n// Object palettes already include their configured prefix and defaults.\nfunction getThemeColors(theme: DiffsTheme, highlighter: DiffsHighlighter) {\n if (highlighter.name === 'highlights' && theme.zed?.cssVariables === true) {\n const prefix = formatCSSVariablePrefix('token');\n return { fg: `var(${prefix}foreground)`, bg: `var(${prefix}background)` };\n }\n return normalizeThemeColors(theme);\n}\n\n// Keep the gitDecoration → terminal.ansi fallback; adding editorGutter colors\n// here would change diff backgrounds for existing themes.\nfunction getGitVariables(themeData: DiffsTheme, modePrefix?: string) {\n modePrefix = modePrefix != null ? `${modePrefix}-` : '';\n let styles = '';\n const additionGreen =\n themeData.colors?.['gitDecoration.addedResourceForeground'] ??\n themeData.colors?.['terminal.ansiGreen'];\n if (additionGreen != null) {\n styles += `${formatCSSVariablePrefix('global')}${modePrefix}addition-color:${additionGreen};`;\n }\n const deletionRed =\n themeData.colors?.['gitDecoration.deletedResourceForeground'] ??\n themeData.colors?.['terminal.ansiRed'];\n if (deletionRed != null) {\n styles += `${formatCSSVariablePrefix('global')}${modePrefix}deletion-color:${deletionRed};`;\n }\n const modifiedBlue =\n themeData.colors?.['gitDecoration.modifiedResourceForeground'] ??\n themeData.colors?.['terminal.ansiBlue'];\n if (modifiedBlue != null) {\n styles += `${formatCSSVariablePrefix('global')}${modePrefix}modified-color:${modifiedBlue};`;\n }\n return styles;\n}\n", "import type {\n CodeToTokensOptions,\n DiffsThemeNames,\n SupportedLanguages,\n ThemesType,\n} from '../types';\nimport { formatCSSVariablePrefix } from './formatCSSVariablePrefix';\n\nexport function getTokenOptions(\n lang: SupportedLanguages,\n theme: DiffsThemeNames | ThemesType,\n tokenizeMaxLineLength: number | undefined\n): CodeToTokensOptions {\n return {\n lang,\n ...(typeof theme === 'string' ? { theme } : { themes: theme }),\n defaultColor: false,\n cssVariablePrefix: formatCSSVariablePrefix('token'),\n tokenizeMaxLineLength,\n // Timed aborts can leave incomplete tokens; limit line length instead.\n tokenizeTimeLimit: 0,\n };\n}\n", "import type { HighlighterTypes } from '../types';\n\n/**\n * Undefined lets the caller use the active type or the default.\n */\nexport function resolvePreferredHighlighter(\n workerManager: { getPreferredHighlighter(): HighlighterTypes } | undefined,\n options: { preferredHighlighter?: HighlighterTypes | undefined }\n): HighlighterTypes | undefined {\n return (\n workerManager?.getPreferredHighlighter() ?? options.preferredHighlighter\n );\n}\n", "import type { RenderRange } from '../types';\n\nexport const FILE_ANNOTATION_LINE_NUMBER = 0;\nexport const FILE_ANNOTATION_HUNK_INDEX = -1;\nexport const FILE_ANNOTATION_LINE_INDEX = -1;\nexport const FILE_ANNOTATION_DOM_KEY: string = `${FILE_ANNOTATION_HUNK_INDEX},${FILE_ANNOTATION_LINE_INDEX}`;\n\ntype AnnotationLineMap<TAnnotation> = Record<number, TAnnotation[] | undefined>;\ntype FileLevelAnnotationLike = { lineNumber: number };\n\nexport function includesFileAnnotations(\n annotations: readonly FileLevelAnnotationLike[] | undefined\n): boolean {\n return (\n annotations?.some(\n (annotation) => annotation.lineNumber === FILE_ANNOTATION_LINE_NUMBER\n ) ?? false\n );\n}\n\nexport function getFileAnnotations<TAnnotation>(\n annotations: AnnotationLineMap<TAnnotation>\n): TAnnotation[] | undefined {\n const fileAnnotations = annotations[FILE_ANNOTATION_LINE_NUMBER];\n return fileAnnotations != null && fileAnnotations.length > 0\n ? fileAnnotations\n : undefined;\n}\n\nexport function shouldRenderFileAnnotations(renderRange: RenderRange): boolean {\n return (\n renderRange.startingLine === FILE_ANNOTATION_LINE_NUMBER &&\n renderRange.totalLines > 0\n );\n}\n", "// Editor token text omits line endings; renderer line caches (diff\n// `additionLines`, FileRenderer's split-line cache) keep the suffix from\n// parsing. Re-apply the previous line's ending so edited text can be written\n// back into those caches without corrupting reconstructed file contents.\nexport function applyLineTextWithNewline(\n line: string,\n lineText: string\n): string {\n if (line.endsWith('\\r\\n')) {\n return lineText + '\\r\\n';\n }\n if (line.endsWith('\\r')) {\n return lineText + '\\r';\n }\n if (line.endsWith('\\n')) {\n return lineText + '\\n';\n }\n return lineText;\n}\n", "import type { ElementContent, Element as HASTElement } from 'hast';\n\nimport { createHastElement } from './hast_utils';\n\nexport function createContentColumn(\n children: ElementContent[],\n rowCount: number\n): HASTElement {\n return createHastElement({\n tagName: 'div',\n children,\n properties: {\n 'data-content': '',\n style: `grid-row: span ${rowCount}`,\n },\n });\n}\n", "export type SVGSpriteNames =\n | 'diffs-icon-arrow-right-short'\n | 'diffs-icon-brand-github'\n | 'diffs-icon-chevron'\n | 'diffs-icon-chevrons-narrow'\n | 'diffs-icon-diff-split'\n | 'diffs-icon-diff-unified'\n | 'diffs-icon-expand'\n | 'diffs-icon-expand-all'\n | 'diffs-icon-eye-slash'\n | 'diffs-icon-file-code'\n | 'diffs-icon-plus'\n | 'diffs-icon-symbol-added'\n | 'diffs-icon-symbol-added-duo'\n | 'diffs-icon-symbol-added-fill'\n | 'diffs-icon-symbol-deleted'\n | 'diffs-icon-symbol-deleted-duo'\n | 'diffs-icon-symbol-deleted-fill'\n | 'diffs-icon-symbol-diffstat'\n | 'diffs-icon-symbol-diffstat-duo'\n | 'diffs-icon-symbol-diffstat-fill'\n | 'diffs-icon-symbol-extracted'\n | 'diffs-icon-symbol-extracted-duo'\n | 'diffs-icon-symbol-extracted-fill'\n | 'diffs-icon-symbol-ignored'\n | 'diffs-icon-symbol-ignored-duo'\n | 'diffs-icon-symbol-ignored-fill'\n | 'diffs-icon-symbol-inlined'\n | 'diffs-icon-symbol-inlined-duo'\n | 'diffs-icon-symbol-inlined-fill'\n | 'diffs-icon-symbol-modified'\n | 'diffs-icon-symbol-modified-duo'\n | 'diffs-icon-symbol-modified-fill'\n | 'diffs-icon-symbol-moved'\n | 'diffs-icon-symbol-moved-duo'\n | 'diffs-icon-symbol-moved-fill'\n | 'diffs-icon-symbol-ref';\n\nexport const SVGSpriteSheet = `<svg data-icon-sprite aria-hidden=\"true\" width=\"0\" height=\"0\">\n <symbol id=\"diffs-icon-arrow-right-short\" viewBox=\"0 0 16 16\">\n <path d=\"M8.47 4.22a.75.75 0 0 0 0 1.06l1.97 1.97H3.75a.75.75 0 0 0 0 1.5h6.69l-1.97 1.97a.75.75 0 1 0 1.06 1.06l3.25-3.25a.75.75 0 0 0 0-1.06L9.53 4.22a.75.75 0 0 0-1.06 0\"/>\n </symbol>\n <symbol id=\"diffs-icon-brand-github\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0c4.42 0 8 3.58 8 8a8.01 8.01 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27s-1.36.09-2 .27c-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8\"/>\n </symbol>\n <symbol id=\"diffs-icon-chevron\" viewBox=\"0 0 16 16\">\n <path d=\"M1.47 4.47a.75.75 0 0 1 1.06 0L8 9.94l5.47-5.47a.75.75 0 1 1 1.06 1.06l-6 6a.75.75 0 0 1-1.06 0l-6-6a.75.75 0 0 1 0-1.06\"/>\n </symbol>\n <symbol id=\"diffs-icon-chevrons-narrow\" viewBox=\"0 0 10 16\">\n <path d=\"M4.47 2.22a.75.75 0 0 1 1.06 0l3.25 3.25a.75.75 0 0 1-1.06 1.06L5 3.81 2.28 6.53a.75.75 0 0 1-1.06-1.06zM1.22 9.47a.75.75 0 0 1 1.06 0L5 12.19l2.72-2.72a.75.75 0 0 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0l-3.25-3.25a.75.75 0 0 1 0-1.06\"/>\n </symbol>\n <symbol id=\"diffs-icon-diff-split\" viewBox=\"0 0 16 16\">\n <path d=\"M14 0H8.5v16H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2m-1.5 6.5v1h1a.5.5 0 0 1 0 1h-1v1a.5.5 0 0 1-1 0v-1h-1a.5.5 0 0 1 0-1h1v-1a.5.5 0 0 1 1 0\"/><path d=\"M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h5.5V0zm.5 7.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1 0-1\" opacity=\".3\"/>\n </symbol>\n <symbol id=\"diffs-icon-diff-unified\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M16 14a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8.5h16zm-8-4a.5.5 0 0 0-.5.5v1h-1a.5.5 0 0 0 0 1h1v1a.5.5 0 0 0 1 0v-1h1a.5.5 0 0 0 0-1h-1v-1A.5.5 0 0 0 8 10\" clip-rule=\"evenodd\"/><path fill-rule=\"evenodd\" d=\"M14 0a2 2 0 0 1 2 2v5.5H0V2a2 2 0 0 1 2-2zM6.5 3.5a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1z\" clip-rule=\"evenodd\" opacity=\".4\"/>\n </symbol>\n <symbol id=\"diffs-icon-expand\" viewBox=\"0 0 16 16\">\n <path d=\"M3.47 5.47a.75.75 0 0 1 1.06 0L8 8.94l3.47-3.47a.75.75 0 1 1 1.06 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 0 1 0-1.06\"/>\n </symbol>\n <symbol id=\"diffs-icon-expand-all\" viewBox=\"0 0 16 16\">\n <path d=\"M11.47 9.47a.75.75 0 1 1 1.06 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 1 1 1.06-1.06L8 12.94zM7.526 1.418a.75.75 0 0 1 1.004.052l4 4a.75.75 0 1 1-1.06 1.06L8 3.06 4.53 6.53a.75.75 0 1 1-1.06-1.06l4-4z\"/>\n </symbol>\n <symbol id=\"diffs-icon-eye-slash\" viewBox=\"0 0 16 16\">\n <path d=\"m13.47 1.47-12 12 1.06 1.06 12-12zM8 14c-.92 0-1.802-.208-2.624-.547l1.173-1.174c.476.142.963.221 1.451.221 1.66 0 3.307-.949 4.626-2.196a10.4 10.4 0 0 0 1.494-1.751A5 5 0 0 0 14.443 8a5 5 0 0 0-.323-.553 10 10 0 0 0-1.238-1.5l1.061-1.062C15.222 6.173 16 7.511 16 8c0 1.05-3.582 6-8 6\"/><path d=\"M8 11q-.084 0-.167-.005l3.162-3.162q.006.083.005.167a3 3 0 0 1-3 3M5.005 8.167l3.162-3.162a3 3 0 0 0-3.162 3.162\"/><path d=\"M8 3.5c.485 0 .97.081 1.445.227l1.168-1.169C9.794 2.212 8.915 2 8 2 3.582 2 0 6.8 0 8c0 .555.766 1.88 2.027 3.144l1.06-1.06a9.5 9.5 0 0 1-1.203-1.461 4.3 4.3 0 0 1-.345-.617L1.536 8l.003-.006c.064-.149.176-.359.345-.617a9.8 9.8 0 0 1 1.482-1.73C4.675 4.427 6.326 3.5 8 3.5\"/>\n </symbol>\n <symbol id=\"diffs-icon-file-code\" viewBox=\"0 0 16 16\">\n <path d=\"M10.75 0c.199 0 .39.08.53.22l3.5 3.5c.14.14.22.331.22.53v9A2.75 2.75 0 0 1 12.25 16h-8.5A2.75 2.75 0 0 1 1 13.25V2.75A2.75 2.75 0 0 1 3.75 0zm-7 1.5c-.69 0-1.25.56-1.25 1.25v10.5c0 .69.56 1.25 1.25 1.25h8.5c.69 0 1.25-.56 1.25-1.25V5h-1.25A2.25 2.25 0 0 1 10 2.75V1.5z\"/><path d=\"M7.248 6.19a.75.75 0 0 1 .063 1.058L5.753 9l1.558 1.752a.75.75 0 0 1-1.122.996l-2-2.25a.75.75 0 0 1 0-.996l2-2.25a.75.75 0 0 1 1.06-.063M8.69 7.248a.75.75 0 1 1 1.12-.996l2 2.25a.75.75 0 0 1 0 .996l-2 2.25a.75.75 0 1 1-1.12-.996L10.245 9z\"/>\n </symbol>\n <symbol id=\"diffs-icon-plus\" viewBox=\"0 0 16 16\">\n <path d=\"M8 3a.75.75 0 0 1 .75.75v3.5h3.5a.75.75 0 0 1 0 1.5h-3.5v3.5a.75.75 0 0 1-1.5 0v-3.5h-3.5a.75.75 0 0 1 0-1.5h3.5v-3.5A.75.75 0 0 1 8 3\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-added\" viewBox=\"0 0 16 16\">\n <path d=\"M8 4a.75.75 0 0 1 .75.75v2.5h2.5a.75.75 0 0 1 0 1.5h-2.5v2.5a.75.75 0 0 1-1.5 0v-2.5h-2.5a.75.75 0 0 1 0-1.5h2.5v-2.5A.75.75 0 0 1 8 4\"/><path d=\"M1.788 4.296c.196-.88.478-1.381.802-1.706s.826-.606 1.706-.802C5.194 1.588 6.387 1.5 8 1.5s2.806.088 3.704.288c.88.196 1.381.478 1.706.802s.607.826.802 1.706c.2.898.288 2.091.288 3.704s-.088 2.806-.288 3.704c-.195.88-.478 1.381-.802 1.706s-.826.607-1.706.802c-.898.2-2.091.288-3.704.288s-2.806-.088-3.704-.288c-.88-.195-1.381-.478-1.706-.802s-.606-.826-.802-1.706C1.588 10.806 1.5 9.613 1.5 8s.088-2.806.288-3.704M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-added-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M8 4a.75.75 0 0 1 .75.75v2.5h2.5a.75.75 0 0 1 0 1.5h-2.5v2.5a.75.75 0 0 1-1.5 0v-2.5h-2.5a.75.75 0 0 1 0-1.5h2.5v-2.5A.75.75 0 0 1 8 4\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-added-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8m0 4a.75.75 0 0 0-.75.75v2.5h-2.5a.75.75 0 0 0 0 1.5h2.5v2.5a.75.75 0 0 0 1.5 0v-2.5h2.5a.75.75 0 0 0 0-1.5h-2.5v-2.5A.75.75 0 0 0 8 4\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-deleted\" viewBox=\"0 0 16 16\">\n <path d=\"M4 8a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5A.75.75 0 0 1 4 8\"/><path d=\"M1.788 4.296c.196-.88.478-1.381.802-1.706s.826-.606 1.706-.802C5.194 1.588 6.387 1.5 8 1.5s2.806.088 3.704.288c.88.196 1.381.478 1.706.802s.607.826.802 1.706c.2.898.288 2.091.288 3.704s-.088 2.806-.288 3.704c-.195.88-.478 1.381-.802 1.706s-.826.607-1.706.802c-.898.2-2.091.288-3.704.288s-2.806-.088-3.704-.288c-.88-.195-1.381-.478-1.706-.802s-.606-.826-.802-1.706C1.588 10.806 1.5 9.613 1.5 8s.088-2.806.288-3.704M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-deleted-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M4 8a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5A.75.75 0 0 1 4 8\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-deleted-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8M4.75 7.25a.75.75 0 0 0 0 1.5h6.5a.75.75 0 0 0 0-1.5z\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-diffstat\" viewBox=\"0 0 16 16\">\n <path d=\"M1.788 4.296c.196-.88.478-1.381.802-1.706s.826-.606 1.706-.802C5.194 1.588 6.387 1.5 8 1.5s2.806.088 3.704.288c.88.196 1.381.478 1.706.802s.607.826.802 1.706c.2.898.288 2.091.288 3.704s-.088 2.806-.288 3.704c-.195.88-.478 1.381-.802 1.706s-.826.607-1.706.802c-.898.2-2.091.288-3.704.288s-2.806-.088-3.704-.288c-.88-.195-1.381-.478-1.706-.802s-.606-.826-.802-1.706C1.588 10.806 1.5 9.613 1.5 8s.088-2.806.288-3.704M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\"/><path d=\"M8.75 4.296a.75.75 0 0 0-1.5 0V6.25h-2a.75.75 0 0 0 0 1.5h2v1.5h1.5v-1.5h2a.75.75 0 0 0 0-1.5h-2zM5.25 10a.75.75 0 0 0 0 1.5h5.5a.75.75 0 0 0 0-1.5z\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-diffstat-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M8.75 4.296a.75.75 0 0 0-1.5 0V6.25h-2a.75.75 0 0 0 0 1.5h2v1.5h1.5v-1.5h2a.75.75 0 0 0 0-1.5h-2zM5.25 10a.75.75 0 0 0 0 1.5h5.5a.75.75 0 0 0 0-1.5z\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-diffstat-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8M5.25 10a.75.75 0 0 0 0 1.5h5.5a.75.75 0 0 0 0-1.5zM8 3.546a.75.75 0 0 0-.75.75V6.25h-2a.75.75 0 0 0 0 1.5h2v1.5h1.5v-1.5h2a.75.75 0 0 0 0-1.5h-2V4.296a.75.75 0 0 0-.75-.75\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-extracted\" viewBox=\"0 0 16 16\">\n <path d=\"M8.25 4.25a.75.75 0 0 1 0 1.5H6.81l3.302 3.302a1.5 1.5 0 1 1-1.06 1.06L5.75 6.811V8.25a.75.75 0 0 1-1.5 0V5A.75.75 0 0 1 5 4.25z\"/><path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8m0 1.5c-1.613 0-2.807.089-3.704.288-.88.196-1.382.477-1.706.802-.325.324-.606.826-.802 1.706C1.588 5.193 1.5 6.387 1.5 8s.089 2.807.288 3.704c.196.88.477 1.382.802 1.706.324.325.826.606 1.706.802.897.2 2.091.288 3.704.288s2.807-.089 3.704-.288c.88-.196 1.382-.477 1.706-.802.325-.324.606-.826.802-1.706.2-.897.288-2.091.288-3.704s-.089-2.807-.288-3.704c-.196-.88-.477-1.382-.802-1.706-.324-.325-.826-.606-1.706-.802C10.807 1.588 9.613 1.5 8 1.5\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-extracted-duo\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8\" clip-rule=\"evenodd\" opacity=\".2\"/><path d=\"M8.25 4.25a.75.75 0 0 1 0 1.5H6.81l3.302 3.302a1.5 1.5 0 1 1-1.06 1.06L5.75 6.811V8.25a.75.75 0 0 1-1.5 0V5A.75.75 0 0 1 5 4.25z\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-extracted-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8M5 4.25a.75.75 0 0 0-.75.75v3.25a.75.75 0 0 0 1.5 0V6.81l3.302 3.302a1.5 1.5 0 1 0 1.06-1.06L6.811 5.75H8.25a.75.75 0 0 0 0-1.5z\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-ignored\" viewBox=\"0 0 16 16\">\n <path d=\"M1.5 8c0 1.613.088 2.806.288 3.704.196.88.478 1.381.802 1.706s.826.607 1.706.802c.898.2 2.091.288 3.704.288s2.806-.088 3.704-.288c.88-.195 1.381-.478 1.706-.802s.607-.826.802-1.706c.2-.898.288-2.091.288-3.704s-.088-2.806-.288-3.704c-.195-.88-.478-1.381-.802-1.706s-.826-.606-1.706-.802C10.806 1.588 9.613 1.5 8 1.5s-2.806.088-3.704.288c-.88.196-1.381.478-1.706.802s-.606.826-.802 1.706C1.588 5.194 1.5 6.387 1.5 8M0 8c0-6.588 1.412-8 8-8s8 1.412 8 8-1.412 8-8 8-8-1.412-8-8m11.53-2.47a.75.75 0 0 0-1.06-1.06l-6 6a.75.75 0 1 0 1.06 1.06z\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-ignored-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M11.53 4.47a.75.75 0 0 1 0 1.06l-6 6a.75.75 0 0 1-1.06-1.06l6-6a.75.75 0 0 1 1.06 0\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-ignored-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8m3.53 4.47a.75.75 0 0 0-1.06 0l-6 6a.75.75 0 1 0 1.06 1.06l6-6a.75.75 0 0 0 0-1.06\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-inlined\" viewBox=\"0 0 16 16\">\n <path d=\"M7.75 11.75a.75.75 0 0 1 0-1.5h1.44L5.887 6.948a1.5 1.5 0 1 1 1.06-1.06l3.302 3.301V7.75a.75.75 0 0 1 1.5 0V11a.75.75 0 0 1-.75.75z\"/><path fill-rule=\"evenodd\" d=\"M8 16c-6.588 0-8-1.412-8-8s1.412-8 8-8 8 1.412 8 8-1.412 8-8 8m0-1.5c1.613 0 2.807-.089 3.704-.288.88-.196 1.382-.477 1.706-.802.325-.324.606-.826.802-1.706.2-.897.288-2.091.288-3.704s-.089-2.807-.288-3.704c-.196-.88-.477-1.382-.802-1.706-.324-.325-.826-.606-1.706-.802C10.807 1.588 9.613 1.5 8 1.5s-2.807.089-3.704.288c-.88.196-1.382.477-1.706.802-.325.324-.606.826-.802 1.706C1.588 5.193 1.5 6.387 1.5 8s.089 2.807.288 3.704c.196.88.477 1.382.802 1.706.324.325.826.606 1.706.802.897.2 2.091.288 3.704.288\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-inlined-duo\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 16c-6.588 0-8-1.412-8-8s1.412-8 8-8 8 1.412 8 8-1.412 8-8 8\" clip-rule=\"evenodd\" opacity=\".2\"/><path d=\"M7.75 11.75a.75.75 0 0 1 0-1.5h1.44L5.887 6.948a1.5 1.5 0 1 1 1.06-1.06l3.302 3.301V7.75a.75.75 0 0 1 1.5 0V11a.75.75 0 0 1-.75.75z\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-inlined-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8M5.5 4a1.5 1.5 0 1 0 .388 2.948l3.301 3.302H7.75a.75.75 0 0 0 0 1.5H11a.75.75 0 0 0 .75-.75V7.75a.75.75 0 0 0-1.5 0v1.44L6.948 5.887A1.5 1.5 0 0 0 5.5 4\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-modified\" viewBox=\"0 0 16 16\">\n <path d=\"M1.5 8c0 1.613.088 2.806.288 3.704.196.88.478 1.381.802 1.706s.826.607 1.706.802c.898.2 2.091.288 3.704.288s2.806-.088 3.704-.288c.88-.195 1.381-.478 1.706-.802s.607-.826.802-1.706c.2-.898.288-2.091.288-3.704s-.088-2.806-.288-3.704c-.195-.88-.478-1.381-.802-1.706s-.826-.606-1.706-.802C10.806 1.588 9.613 1.5 8 1.5s-2.806.088-3.704.288c-.88.196-1.381.478-1.706.802s-.606.826-.802 1.706C1.588 5.194 1.5 6.387 1.5 8M0 8c0-6.588 1.412-8 8-8s8 1.412 8 8-1.412 8-8 8-8-1.412-8-8m8 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-modified-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-modified-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8m0 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-moved\" viewBox=\"0 0 16 16\">\n <path d=\"M1.788 4.296c.196-.88.478-1.381.802-1.706s.826-.606 1.706-.802C5.194 1.588 6.387 1.5 8 1.5s2.806.088 3.704.288c.88.196 1.381.478 1.706.802s.607.826.802 1.706c.2.898.288 2.091.288 3.704s-.088 2.806-.288 3.704c-.195.88-.478 1.381-.802 1.706s-.826.607-1.706.802c-.898.2-2.091.288-3.704.288s-2.806-.088-3.704-.288c-.88-.195-1.381-.478-1.706-.802s-.606-.826-.802-1.706C1.588 10.806 1.5 9.613 1.5 8s.088-2.806.288-3.704M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\"/><path d=\"M8.495 4.695a.75.75 0 0 0-.05 1.06L10.486 8l-2.041 2.246a.75.75 0 0 0 1.11 1.008l2.5-2.75a.75.75 0 0 0 0-1.008l-2.5-2.75a.75.75 0 0 0-1.06-.051m-4 0a.75.75 0 0 0-.05 1.06l2.044 2.248-1.796 1.995a.75.75 0 0 0 1.114 1.004l2.25-2.5a.75.75 0 0 0-.002-1.007l-2.5-2.75a.75.75 0 0 0-1.06-.05\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-moved-duo\" viewBox=\"0 0 16 16\">\n <path d=\"M8 0C1.412 0 0 1.412 0 8s1.412 8 8 8 8-1.412 8-8-1.412-8-8-8\" opacity=\".2\"/><path d=\"M8.496 4.695a.75.75 0 0 0-.051 1.06L10.486 8l-2.041 2.246a.75.75 0 0 0 1.11 1.008l2.5-2.75a.75.75 0 0 0 0-1.008l-2.5-2.75a.75.75 0 0 0-1.06-.051m-4 0a.75.75 0 0 0-.051 1.06L6.49 8.003 4.693 9.998a.75.75 0 0 0 1.114 1.004l2.25-2.5a.75.75 0 0 0-.002-1.007l-2.5-2.75a.75.75 0 0 0-1.06-.05\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-moved-fill\" viewBox=\"0 0 16 16\">\n <path fill-rule=\"evenodd\" d=\"M8 0c6.588 0 8 1.412 8 8s-1.412 8-8 8-8-1.412-8-8 1.412-8 8-8m1.555 4.745a.75.75 0 0 0-1.11 1.01L10.486 8l-2.04 2.245a.75.75 0 0 0 1.109 1.01l2.5-2.75a.75.75 0 0 0 0-1.01zm-4 0a.75.75 0 0 0-1.11 1.01l2.043 2.248-1.796 1.995a.75.75 0 0 0 1.116 1.004l2.25-2.5a.75.75 0 0 0-.003-1.007z\" clip-rule=\"evenodd\"/>\n </symbol>\n <symbol id=\"diffs-icon-symbol-ref\" viewBox=\"0 0 16 16\">\n <path d=\"M1.5 8c0 1.613.088 2.806.288 3.704.196.88.478 1.381.802 1.706.286.286.71.54 1.41.73V1.86c-.7.19-1.124.444-1.41.73-.324.325-.606.826-.802 1.706C1.588 5.194 1.5 6.387 1.5 8m4 6.397c.697.07 1.522.103 2.5.103 1.613 0 2.806-.088 3.704-.288.88-.195 1.381-.478 1.706-.802s.607-.826.802-1.706c.2-.898.288-2.091.288-3.704s-.088-2.806-.288-3.704c-.195-.88-.478-1.381-.802-1.706s-.826-.606-1.706-.802C10.806 1.588 9.613 1.5 8 1.5c-.978 0-1.803.033-2.5.103zM0 8c0-6.588 1.412-8 8-8s8 1.412 8 8-1.412 8-8 8-8-1.412-8-8m7-2a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z\"/>\n </symbol>\n</svg>`;\n", "import type { CustomPreProperties, PrePropertiesConfig } from '../types';\n\nexport function arePrePropertiesEqual(\n propsA: PrePropertiesConfig | undefined,\n propsB: PrePropertiesConfig | undefined\n): boolean {\n if (propsA == null || propsB == null) {\n return propsA === propsB;\n }\n return (\n areCustomPropertiesEqual(\n propsA.customProperties,\n propsB.customProperties\n ) &&\n propsA.type === propsB.type &&\n propsA.diffIndicators === propsB.diffIndicators &&\n propsA.disableBackground === propsB.disableBackground &&\n propsA.disableLineNumbers === propsB.disableLineNumbers &&\n propsA.overflow === propsB.overflow &&\n propsA.split === propsB.split &&\n propsA.totalLines === propsB.totalLines\n );\n}\n\nconst EMPTY_CUSTOM_PROPERTIES: CustomPreProperties = {};\n\nfunction areCustomPropertiesEqual(\n customPropertiesA: CustomPreProperties = EMPTY_CUSTOM_PROPERTIES,\n customPropertiesB: CustomPreProperties = EMPTY_CUSTOM_PROPERTIES\n): boolean {\n if (customPropertiesA === customPropertiesB) {\n return true;\n }\n const keysA = Object.keys(customPropertiesA);\n const keysB = Object.keys(customPropertiesB);\n if (keysA.length !== keysB.length) {\n return false;\n }\n for (const key of keysA) {\n if (customPropertiesA[key] !== customPropertiesB[key]) {\n return false;\n }\n }\n return true;\n}\n", "export function createAnnotationWrapperNode(slot: string): HTMLElement {\n const wrapper = document.createElement('div');\n wrapper.dataset.annotationSlot = '';\n wrapper.slot = slot;\n wrapper.style.whiteSpace = 'normal';\n return wrapper;\n}\n", "export function createGutterUtilityContentNode(): HTMLElement {\n const gutterUtilityContent = document.createElement('div');\n gutterUtilityContent.slot = 'gutter-utility-slot';\n gutterUtilityContent.style.position = 'absolute';\n gutterUtilityContent.style.top = '0';\n gutterUtilityContent.style.bottom = '0';\n gutterUtilityContent.style.textAlign = 'center';\n gutterUtilityContent.style.whiteSpace = 'normal';\n gutterUtilityContent.style.touchAction = 'none';\n return gutterUtilityContent;\n}\n", "import { UNSAFE_CSS_ATTRIBUTE } from '../constants';\n\nexport function createUnsafeCSSStyleNode(): HTMLStyleElement {\n const node = document.createElement('style');\n node.setAttribute(UNSAFE_CSS_ATTRIBUTE, '');\n return node;\n}\n", "@layer base, theme, rendered, unsafe;\n\n@layer base {\n :host {\n --diffs-font-fallback:\n 'SF Mono', Monaco, Consolas, 'Ubuntu Mono', 'Liberation Mono',\n 'Courier New', monospace;\n --diffs-header-font-fallback:\n system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue',\n 'Noto Sans', 'Liberation Sans', Arial, sans-serif;\n\n --diffs-mixer: light-dark(black, white);\n --diffs-gap-fallback: 8px;\n --diffs-scrollbar-gutter-fallback: 6px;\n --diffs-scrollbar-gutter: var(\n --diffs-scrollbar-gutter-override,\n var(\n --diffs-scrollbar-gutter-measured,\n var(--diffs-scrollbar-gutter-fallback)\n )\n );\n\n --diffs-added-light: #0dbe4e;\n --diffs-added-dark: #5ecc71;\n --diffs-modified-light: #009fff;\n --diffs-modified-dark: #69b1ff;\n --diffs-deleted-light: #ff2e3f;\n --diffs-deleted-dark: #ff6762;\n --diffs-warning-light: #d5a910;\n --diffs-warning-dark: #ffd452;\n\n /*\n // Available CSS Color Overrides\n --diffs-bg-buffer-override\n --diffs-bg-hover-override\n --diffs-bg-context-override\n --diffs-bg-context-gutter-override\n --diffs-bg-separator-override\n --diffs-bg-caret-override\n\n --diffs-fg-number-override\n --diffs-fg-number-addition-override\n --diffs-fg-number-deletion-override\n --diffs-fg-conflict-marker-override\n\n --diffs-deletion-color-override\n --diffs-addition-color-override\n --diffs-modified-color-override\n\n --diffs-bg-deletion-override\n --diffs-bg-deletion-number-override\n --diffs-bg-deletion-emphasis-override\n\n --diffs-bg-addition-override\n --diffs-bg-addition-number-override\n --diffs-bg-addition-emphasis-override\n\n --conflict-bg-current-override\n --conflict-bg-current-number-override\n --conflict-bg-current-header-override\n --conflict-bg-incoming-override\n --conflict-bg-incoming-number-override\n --conflict-bg-incoming-header-override\n\n // Line Selection Color Overrides (for enableLineSelection)\n --diffs-selection-color-override\n --diffs-bg-selection-override\n --diffs-bg-selection-number-override\n\n // Available CSS Layout Overrides\n --diffs-gap-inline\n --diffs-gap-block\n --diffs-gap-style\n --diffs-scrollbar-gutter-override\n --diffs-tab-size\n --diffs-popover-gap (edit mode: inset for edge-clamped popovers)\n */\n\n color-scheme: light dark;\n display: block;\n font-family: var(\n --diffs-header-font-family,\n var(--diffs-header-font-fallback)\n );\n font-size: var(--diffs-font-size, 13px);\n line-height: var(--diffs-line-height, 20px);\n font-feature-settings: var(--diffs-font-features);\n\n /* NOTE(amadeus): we cannot use 'in oklch' because current versions of cursor\n * and vscode use an older build of chrome that appears to have a bug with\n * color-mix and 'in oklch', so use 'in lab' instead */\n --diffs-bg: light-dark(\n var(--diffs-light-bg, #fff),\n var(--diffs-dark-bg, #000)\n );\n --diffs-bg-buffer: var(\n --diffs-bg-buffer-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg) 92%, var(--diffs-mixer)),\n color-mix(in lab, var(--diffs-bg) 92%, var(--diffs-mixer))\n )\n );\n --diffs-bg-context: var(\n --diffs-bg-context-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg) 98.5%, var(--diffs-mixer)),\n color-mix(in lab, var(--diffs-bg) 92.5%, var(--diffs-mixer))\n )\n );\n --diffs-bg-context-gutter: var(\n --diffs-bg-context-gutter-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg-context) 90%, var(--diffs-bg)),\n color-mix(in lab, var(--diffs-bg-context) 45%, var(--diffs-bg))\n )\n );\n --diffs-bg-separator: var(\n --diffs-bg-separator-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg) 96%, var(--diffs-mixer)),\n color-mix(in lab, var(--diffs-bg) 85%, var(--diffs-mixer))\n )\n );\n\n --diffs-fg: light-dark(var(--diffs-light, #000), var(--diffs-dark, #fff));\n --diffs-fg-number: var(\n --diffs-fg-number-override,\n light-dark(\n color-mix(in lab, var(--diffs-fg) 65%, var(--diffs-bg)),\n color-mix(in lab, var(--diffs-fg) 65%, var(--diffs-bg))\n )\n );\n --diffs-fg-conflict-marker: var(\n --diffs-fg-conflict-marker-override,\n var(--diffs-fg-number)\n );\n\n --diffs-deletion-base: var(\n --diffs-deletion-color-override,\n light-dark(\n var(\n --diffs-light-deletion-color,\n var(--diffs-deletion-color, var(--diffs-deleted-light))\n ),\n var(\n --diffs-dark-deletion-color,\n var(--diffs-deletion-color, var(--diffs-deleted-dark))\n )\n )\n );\n --diffs-addition-base: var(\n --diffs-addition-color-override,\n light-dark(\n var(\n --diffs-light-addition-color,\n var(--diffs-addition-color, var(--diffs-added-light))\n ),\n var(\n --diffs-dark-addition-color,\n var(--diffs-addition-color, var(--diffs-added-dark))\n )\n )\n );\n --diffs-modified-base: var(\n --diffs-modified-color-override,\n light-dark(\n var(\n --diffs-light-modified-color,\n var(--diffs-modified-color, var(--diffs-modified-light))\n ),\n var(\n --diffs-dark-modified-color,\n var(--diffs-modified-color, var(--diffs-modified-dark))\n )\n )\n );\n\n /* NOTE(amadeus): we cannot use 'in oklch' because current versions of cursor\n * and vscode use an older build of chrome that appears to have a bug with\n * color-mix and 'in oklch', so use 'in lab' instead */\n --diffs-bg-deletion: var(\n --diffs-bg-deletion-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg) 88%, var(--diffs-deletion-base)),\n color-mix(in lab, var(--diffs-bg) 80%, var(--diffs-deletion-base))\n )\n );\n --diffs-bg-deletion-emphasis: var(\n --diffs-bg-deletion-emphasis-override,\n light-dark(\n rgb(from var(--diffs-deletion-base) r g b / 0.15),\n rgb(from var(--diffs-deletion-base) r g b / 0.2)\n )\n );\n\n --diffs-bg-addition: var(\n --diffs-bg-addition-override,\n light-dark(\n color-mix(in lab, var(--diffs-bg) 88%, var(--diffs-addition-base)),\n color-mix(in lab, var(--diffs-bg) 80%, var(--diffs-addition-base))\n )\n );\n --diffs-bg-addition-emphasis: var(\n --diffs-bg-addition-emphasis-override,\n light-dark(\n rgb(from var(--diffs-addition-base) r g b / 0.15),\n rgb(from var(--diffs-addition-base) r g b / 0.2)\n )\n );\n\n --diffs-selection-base: var(--diffs-modified-base);\n --diffs-selection-number-fg: light-dark(\n color-mix(in lab, var(--diffs-selection-base) 65%, var(--diffs-mixer)),\n color-mix(in lab, var(--diffs-selection-base) 75%, var(--diffs-mixer))\n );\n background-color: var(--diffs-bg);\n color: var(--diffs-fg);\n }\n\n /* NOTE(mdo): Some semantic HTML elements (e.g. `pre`, `code`) have default\n * user-agent styles. These must be overridden to use our custom styles. */\n pre,\n code,\n [data-error-wrapper] {\n isolation: isolate;\n margin: 0;\n padding: 0;\n display: block;\n outline: none;\n font-family: var(--diffs-font-family, var(--diffs-font-fallback));\n }\n\n pre,\n code {\n background-color: var(--diffs-bg);\n }\n\n code {\n contain: content;\n }\n\n input,\n button {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n }\n\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n }\n\n [data-icon-sprite] {\n display: none;\n }\n\n /* NOTE(mdo): Headers and separators are within pre/code, so we need to reset\n * their font-family explicitly. */\n [data-diffs-header],\n [data-separator] {\n font-family: var(\n --diffs-header-font-family,\n var(--diffs-header-font-fallback)\n );\n }\n\n [data-diffs-header][data-sticky] {\n position: sticky;\n top: 0;\n z-index: 1;\n background-color: var(--diffs-bg);\n }\n\n [data-file-info] {\n padding: 10px;\n font-weight: 700;\n color: var(--fg);\n /* NOTE(amadeus): we cannot use 'in oklch' because current versions of cursor\n * and vscode use an older build of chrome that appears to have a bug with\n * color-mix and 'in oklch', so use 'in lab' instead */\n background-color: color-mix(in lab, var(--bg) 98%, var(--fg));\n border-block: 1px solid color-mix(in lab, var(--bg) 95%, var(--fg));\n }\n\n [data-diff],\n [data-file] {\n /* This feels a bit crazy to me... so I need to think about it a bit more... */\n --diffs-grid-number-column-width: minmax(min-content, max-content);\n --diffs-code-grid: var(--diffs-grid-number-column-width) 1fr;\n\n &[data-dehydrated] {\n --diffs-code-grid: var(--diffs-grid-number-column-width) minmax(0, 1fr);\n }\n\n &:hover [data-code]::-webkit-scrollbar-thumb {\n background-color: var(--diffs-bg-context);\n }\n }\n\n /* iOS WebKit uses overlay scrollbars, so unmeasured layout compensation\n * should start at zero rather than the desktop custom-scrollbar fallback. */\n @supports (-webkit-touch-callout: none) {\n :host {\n --diffs-scrollbar-gutter-fallback: 0px;\n }\n }\n\n [data-line] span,\n [data-edit-prediction-suffix] span {\n color: light-dark(\n var(--diffs-token-light, var(--diffs-light)),\n var(--diffs-token-dark, var(--diffs-dark))\n );\n background-color: light-dark(\n var(--diffs-token-light-bg, inherit),\n var(--diffs-token-dark-bg, inherit)\n );\n }\n\n /* Line Color and BG Calculations */\n [data-line],\n [data-gutter-buffer],\n [data-column-number],\n [data-line-annotation],\n [data-no-newline],\n [data-merge-conflict],\n [data-merge-conflict-actions],\n [data-editor-overlay] {\n /* Pre-fill css variables for appropriate up-mixing */\n --diffs-computed-decoration-bg: var(--diffs-bg);\n --diffs-computed-diff-line-bg: var(--diffs-computed-decoration-bg);\n --diffs-computed-selected-line-bg: var(--diffs-computed-diff-line-bg);\n --diffs-computed-editor-active-line-bg: var(\n --diffs-computed-selected-line-bg\n );\n --diffs-computed-hovered-line-bg: var(\n --diffs-computed-editor-active-line-bg\n );\n\n --diffs-hover-mix-target: var(\n --diffs-bg-hover-override,\n var(--diffs-mixer)\n );\n --diffs-line-bg: var(--diffs-computed-hovered-line-bg);\n\n color: var(--diffs-fg);\n background-color: var(--diffs-line-bg, var(--diffs-bg));\n }\n\n [data-line],\n [data-no-newline] {\n &[data-decoration-bg] {\n --mix-deco-light: 92%;\n --mix-deco-dark: 85%;\n\n &[data-decoration-bg-depth='2'] {\n --mix-deco-light: 88%;\n --mix-deco-dark: 80%;\n }\n\n &[data-decoration-bg-depth='3'] {\n --mix-deco-light: 85%;\n --mix-deco-dark: 78%;\n }\n\n --diffs-hover-mix-target: var(--diffs-decoration-bg);\n\n --diffs-computed-decoration-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-bg) var(--mix-deco-light),\n var(--diffs-decoration-bg)\n ),\n color-mix(\n in lab,\n var(--diffs-bg) var(--mix-deco-dark),\n var(--diffs-decoration-bg)\n )\n );\n }\n }\n\n [data-line-annotation],\n [data-gutter-buffer='annotation'] {\n --diffs-annotation-bg: var(--diffs-bg-context);\n --diffs-computed-decoration-bg: var(--diffs-annotation-bg);\n --diffs-hover-mix-target: var(--diffs-computed-editor-active-line-bg);\n }\n\n [data-merge-conflict-actions],\n [data-gutter-buffer='merge-conflict-action'],\n [data-gutter-buffer='merge-conflict-marker-base'],\n [data-gutter-buffer='merge-conflict-marker-separator'],\n [data-merge-conflict='marker-base'],\n [data-merge-conflict='marker-separator'] {\n --diffs-computed-decoration-bg: var(--diffs-bg-context);\n --diffs-hover-mix-target: var(--diffs-computed-editor-active-line-bg);\n }\n\n [data-gutter-buffer='merge-conflict-marker-start'],\n [data-merge-conflict='marker-start'] {\n --diffs-computed-decoration-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-bg) 78%,\n var(--conflict-bg-current-header-override, var(--diffs-addition-base))\n ),\n color-mix(\n in lab,\n var(--diffs-bg) 68%,\n var(--conflict-bg-current-header-override, var(--diffs-addition-base))\n )\n );\n --diffs-hover-mix-target: var(--diffs-computed-editor-active-line-bg);\n }\n\n [data-gutter-buffer='merge-conflict-marker-end'],\n [data-merge-conflict='marker-end'] {\n --diffs-computed-decoration-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-bg) 78%,\n var(--conflict-bg-incoming-header-override, var(--diffs-modified-base))\n ),\n color-mix(\n in lab,\n var(--diffs-bg) 68%,\n var(--conflict-bg-incoming-header-override, var(--diffs-modified-base))\n )\n );\n --diffs-hover-mix-target: var(--diffs-computed-editor-active-line-bg);\n }\n\n [data-has-merge-conflict] [data-line-annotation],\n [data-has-merge-conflict] [data-gutter-buffer='annotation'] {\n --diffs-computed-decoration-bg: var(--diffs-bg);\n --diffs-hover-mix-target: var(--diffs-computed-editor-active-line-bg);\n }\n\n /* We are using where here to not affect the nesting impacts later on for\n * hover and selection */\n :where([data-background]) {\n [data-gutter-buffer],\n [data-column-number] {\n --mix-light: 91%;\n --mix-dark: 85%;\n }\n\n [data-line],\n [data-no-newline] {\n --mix-light: 88%;\n --mix-dark: 80%;\n }\n\n [data-gutter-buffer],\n [data-column-number],\n [data-line],\n [data-no-newline] {\n --diffs-diff-line-mix-target: var(--diffs-bg);\n\n &[data-line-type='change-deletion'] {\n --diffs-diff-line-mix-target: var(\n --diffs-bg-deletion-override,\n var(--diffs-deletion-base)\n );\n --diffs-hover-mix-target: var(--diffs-diff-line-mix-target);\n\n &:where([data-gutter-buffer], [data-column-number]) {\n color: var(\n --diffs-fg-number-deletion-override,\n var(--diffs-deletion-base)\n );\n\n --diffs-diff-line-mix-target: var(\n --diffs-bg-deletion-number-override,\n var(--diffs-deletion-base)\n );\n }\n\n --diffs-computed-diff-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-light),\n var(--diffs-diff-line-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-dark),\n var(--diffs-diff-line-mix-target)\n )\n );\n }\n\n &[data-line-type='change-addition'] {\n --diffs-diff-line-mix-target: var(\n --diffs-bg-addition-override,\n var(--diffs-addition-base)\n );\n --diffs-hover-mix-target: var(--diffs-diff-line-mix-target);\n\n &:where([data-gutter-buffer], [data-column-number]) {\n color: var(\n --diffs-fg-number-addition-override,\n var(--diffs-addition-base)\n );\n\n --diffs-diff-line-mix-target: var(\n --diffs-bg-addition-number-override,\n var(--diffs-addition-base)\n );\n }\n\n --diffs-computed-diff-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-light),\n var(--diffs-diff-line-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-dark),\n var(--diffs-diff-line-mix-target)\n )\n );\n }\n\n &[data-merge-conflict='current'] {\n --diffs-diff-line-mix-target: var(\n --conflict-bg-current-override,\n var(--diffs-addition-base)\n );\n --diffs-hover-mix-target: var(--diffs-diff-line-mix-target);\n\n &:where([data-gutter-buffer], [data-column-number]) {\n color: var(\n --diffs-fg-number-addition-override,\n var(--diffs-addition-base)\n );\n\n --diffs-diff-line-mix-target: var(\n --conflict-bg-current-number-override,\n var(--diffs-addition-base)\n );\n }\n\n --diffs-computed-diff-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-light),\n var(--diffs-diff-line-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-dark),\n var(--diffs-diff-line-mix-target)\n )\n );\n }\n\n &[data-merge-conflict='incoming'] {\n --diffs-diff-line-mix-target: var(\n --conflict-bg-incoming-override,\n var(--diffs-modified-base)\n );\n --diffs-hover-mix-target: var(--diffs-diff-line-mix-target);\n\n &:where([data-gutter-buffer], [data-column-number]) {\n color: var(--diffs-modified-base);\n\n --diffs-diff-line-mix-target: var(\n --conflict-bg-incoming-number-override,\n var(--diffs-modified-base)\n );\n }\n\n --diffs-computed-diff-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-light),\n var(--diffs-diff-line-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-decoration-bg) var(--mix-dark),\n var(--diffs-diff-line-mix-target)\n )\n );\n }\n }\n }\n\n /* Order is important for rationalizing these selectors and for order of\n * application, therefore we need to disable this style-lint rule */\n /* stylelint-disable-next-line no-duplicate-selectors */\n [data-gutter-buffer],\n [data-column-number],\n [data-line],\n [data-line-annotation],\n [data-merge-conflict],\n [data-merge-conflict-actions],\n [data-no-newline],\n [data-editor-overlay] {\n --diffs-selection-mix-target: var(\n --diffs-bg-selection-override,\n var(--diffs-selection-base)\n );\n --diffs-selection-emphasis-mix-target: var(--diffs-selection-mix-target);\n\n &:where([data-editor-overlay]),\n &:where(\n [data-line],\n [data-line-annotation],\n [data-merge-conflict],\n [data-merge-conflict-actions],\n [data-no-newline]\n )[data-selected-line] {\n --mix-selection-light: 82%;\n --mix-selection-dark: 75%;\n --diffs-hover-mix-target: var(--diffs-selection-mix-target);\n }\n\n &:where(\n [data-gutter-buffer][data-selected-line],\n [data-column-number]:is([data-selected-line], [data-editor-active-line])\n ) {\n --mix-selection-light: 75%;\n --mix-selection-dark: 60%;\n --diffs-selection-mix-target: var(\n --diffs-bg-selection-number-override,\n var(--diffs-selection-base)\n );\n --diffs-hover-mix-target: var(--diffs-selection-mix-target);\n }\n\n /* Keep the light-theme emphasis on a selected changed line tied to its\n * resolved diff and selection colors. */\n &:where([data-line][data-selected-line]):is(\n [data-line-type='change-addition'],\n [data-line-type='change-deletion']\n ) {\n --diffs-selection-emphasis-mix-target: light-dark(\n color-mix(\n in lab,\n var(--diffs-diff-line-mix-target, var(--diffs-selection-mix-target))\n var(--mix-selection-light),\n var(--diffs-selection-mix-target)\n ),\n var(--diffs-selection-mix-target)\n );\n }\n\n &:where([data-editor-overlay]),\n &[data-selected-line] {\n --diffs-computed-selected-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-diff-line-bg) var(--mix-selection-light),\n var(--diffs-selection-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-diff-line-bg) var(--mix-selection-dark),\n var(--diffs-selection-mix-target)\n )\n );\n }\n }\n\n /* The editor's active line sits above selection, but hover remains the final\n * line-background treatment. */\n [data-line][data-editor-active-line],\n [data-column-number][data-editor-active-line] {\n --diffs-computed-editor-active-line-bg: color-mix(\n in lab,\n var(--diffs-computed-selected-line-bg)\n var(--diffs-editor-active-line-source-mix, 100%),\n var(--diffs-selection-emphasis-mix-target)\n );\n }\n\n @media (pointer: fine) {\n [data-line][data-hovered],\n [data-gutter-buffer][data-hovered],\n [data-column-number][data-hovered],\n [data-line-annotation][data-hovered],\n [data-no-newline][data-hovered],\n [data-merge-conflict][data-hovered],\n [data-merge-conflict-actions][data-hovered],\n [data-editor-overlay][data-hovered] {\n --diffs-computed-hovered-line-bg: light-dark(\n color-mix(\n in lab,\n var(--diffs-computed-editor-active-line-bg) 97%,\n var(--diffs-hover-mix-target)\n ),\n color-mix(\n in lab,\n var(--diffs-computed-editor-active-line-bg) 91%,\n var(--diffs-hover-mix-target)\n )\n );\n }\n }\n\n [data-gutter-buffer][data-selected-line],\n [data-column-number]:is([data-selected-line], [data-editor-active-line]) {\n color: var(--diffs-selection-number-fg);\n }\n\n [data-no-newline] {\n user-select: none;\n\n span {\n opacity: 0.6;\n }\n }\n\n [data-diff-type='split'][data-overflow='scroll'] {\n display: grid;\n grid-template-columns: 1fr 1fr;\n\n [data-additions] {\n border-left: 1px solid var(--diffs-bg);\n }\n\n [data-deletions] {\n border-right: 1px solid var(--diffs-bg);\n }\n }\n\n [data-code] {\n display: grid;\n grid-auto-flow: dense;\n grid-template-columns: var(--diffs-code-grid);\n overflow: var(--diffs-overflow-override, scroll) clip;\n overscroll-behavior-x: none;\n tab-size: var(--diffs-tab-size, 2);\n align-self: flex-start;\n padding-top: var(--diffs-gap-block, var(--diffs-gap-fallback));\n padding-bottom: max(\n 0px,\n calc(\n var(--diffs-gap-block, var(--diffs-gap-fallback)) -\n var(--diffs-scrollbar-gutter)\n )\n );\n scrollbar-gutter: stable;\n }\n\n [data-diffs-scrollbar-measure] {\n position: absolute;\n top: -200px;\n left: -200px;\n opacity: 0;\n pointer-events: none;\n width: 100px;\n height: 100px;\n padding: 0;\n grid-template-columns: none;\n scrollbar-gutter: auto;\n }\n\n [data-container-size] {\n container-type: inline-size;\n }\n\n [data-code]::-webkit-scrollbar {\n width: 0;\n height: var(--diffs-scrollbar-gutter);\n }\n\n [data-code]::-webkit-scrollbar-track {\n background: transparent;\n }\n\n [data-code]::-webkit-scrollbar-thumb {\n background-color: transparent;\n border: 1px solid transparent;\n background-clip: content-box;\n border-radius: 3px;\n }\n\n [data-code]::-webkit-scrollbar-corner {\n background-color: transparent;\n }\n\n /*\n * If we apply these rules globally it will mean that webkit will opt into the\n * standards compliant version of custom css scrollbars, which we do not want\n * because the custom stuff will look better\n */\n @supports (-moz-appearance: none) {\n [data-code] {\n scrollbar-width: thin;\n scrollbar-color: var(--diffs-bg-context) transparent;\n padding-bottom: var(--diffs-gap-block, var(--diffs-gap-fallback));\n }\n }\n\n [data-diffs-header] ~ [data-diff],\n [data-diffs-header] ~ [data-file] {\n [data-code],\n &[data-overflow='wrap'],\n &[data-dehydrated][data-diff-type='split'][data-overflow='scroll'] {\n padding-top: 0;\n }\n }\n\n [data-gutter] {\n display: grid;\n grid-template-rows: subgrid;\n grid-template-columns: subgrid;\n grid-column: 1;\n z-index: 3;\n position: relative;\n background-color: var(--diffs-bg);\n\n [data-gutter-buffer],\n [data-column-number] {\n border-right: var(--diffs-gap-style, 2px solid var(--diffs-bg));\n }\n }\n\n [data-content] {\n display: grid;\n grid-template-rows: subgrid;\n grid-template-columns: subgrid;\n grid-column: 2;\n min-width: 0;\n background-color: var(--diffs-bg);\n }\n\n /* Keep per-row selectors outside this guard: :has would rescan the columns\n * for every row. */\n [data-overflow='scroll']:not(\n [data-dehydrated],\n [data-custom-styles],\n :has(\n > [data-code] > [contenteditable],\n > [data-code]\n > *\n > :is(\n [data-line-annotation],\n [data-separator],\n [data-merge-conflict],\n [data-merge-conflict-actions]\n )\n )\n )\n > [data-code] {\n display: flex;\n\n > [data-gutter] {\n display: block;\n flex-shrink: 0;\n }\n\n > [data-content] {\n display: block;\n flex: 1 0 max-content;\n }\n }\n\n /* Both split layouts that share one grid across the two columns: wrap\n * always, and scroll while dehydrated. Scroll mode normally renders each\n * column as its own scroll container, where paired annotation rows only get\n * equal heights once the resize manager measures them — before hydration\n * that measurement hasn't run, so the side hosting the annotation content\n * would be taller and the rows below it would shift on hydration. The\n * shared grid gives paired rows equal heights in pure CSS; the dehydrated\n * scroll variant keeps nowrap text and clips horizontal overflow until\n * hydration swaps in the real scroll containers. */\n [data-diff-type='split'][data-overflow='wrap'],\n [data-dehydrated][data-diff-type='split'][data-overflow='scroll'] {\n display: grid;\n grid-auto-flow: dense;\n grid-template-columns: repeat(2, var(--diffs-code-grid));\n padding-block: var(--diffs-gap-block, var(--diffs-gap-fallback));\n\n [data-code] {\n display: contents;\n }\n\n [data-deletions] {\n [data-gutter] {\n grid-column: 1;\n }\n\n [data-content] {\n grid-column: 2;\n border-right: 1px solid var(--diffs-bg);\n }\n }\n\n [data-additions] {\n [data-gutter] {\n grid-column: 3;\n border-left: 1px solid var(--diffs-bg);\n }\n\n [data-content] {\n grid-column: 4;\n }\n }\n }\n\n [data-dehydrated][data-diff-type='split'][data-overflow='scroll']\n [data-content] {\n overflow: clip;\n }\n\n [data-overflow='scroll'] [data-gutter] {\n position: sticky;\n left: 0;\n }\n\n [data-interactive-lines] [data-line] {\n cursor: pointer;\n }\n\n [data-interactive-line-numbers] [data-column-number] {\n cursor: pointer;\n touch-action: none;\n }\n\n [data-content-buffer],\n [data-gutter-buffer] {\n position: relative;\n user-select: none;\n min-height: 1lh;\n }\n\n [data-gutter-buffer] {\n padding-left: 2ch;\n padding-right: 1ch;\n\n &::before {\n content: '';\n display: block;\n min-width: var(\n --diffs-min-number-column-width,\n var(--diffs-min-number-column-width-default, 3ch)\n );\n }\n }\n\n [data-gutter-buffer='annotation'] {\n --diffs-annotation-bg: var(--diffs-bg-context-gutter);\n min-height: 0;\n }\n\n [data-gutter-buffer='buffer'] {\n --diffs-line-bg: var(--diffs-bg-context-gutter);\n }\n\n [data-content-buffer] {\n grid-column: 1;\n /* We multiply by 1.414 (√2) to better approximate the diagonal repeat distance */\n background-size: 8px 8px;\n background-position: 5px 0;\n background-origin: border-box;\n /* This is incredibley expensive... */\n background-image: repeating-linear-gradient(\n -45deg,\n transparent,\n transparent calc(3px * 1.414),\n var(--diffs-bg-buffer) calc(3px * 1.414),\n var(--diffs-bg-buffer) calc(4px * 1.414)\n );\n }\n\n /* Hunk Separators */\n /* --------------- */\n [data-separator] {\n box-sizing: content-box;\n background-color: var(--diffs-bg);\n }\n\n [data-separator='simple'] {\n min-height: 4px;\n }\n\n [data-separator='line-info'],\n [data-separator='line-info-basic'],\n [data-separator='metadata'],\n [data-separator='simple'] {\n background-color: var(--diffs-bg-separator);\n }\n\n [data-separator='line-info'],\n [data-separator='line-info-basic'],\n [data-separator='metadata'] {\n height: 32px;\n position: relative;\n }\n\n [data-separator-wrapper] {\n user-select: none;\n fill: currentColor;\n position: absolute;\n inset-inline: 0;\n display: flex;\n align-items: center;\n background-color: var(--diffs-bg);\n height: 100%;\n }\n\n [data-content] [data-separator-wrapper] {\n display: none;\n }\n\n [data-separator='metadata'] [data-separator-wrapper] {\n inset-inline: 100% auto;\n padding-inline: 1ch;\n height: 100%;\n background-color: var(--diffs-bg-separator);\n color: var(--diffs-fg-number);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: min-content;\n }\n\n [data-separator='line-info'] {\n margin-block: var(--diffs-gap-block, var(--diffs-gap-fallback));\n\n [data-separator-wrapper] {\n min-width: 16px;\n }\n }\n\n [data-separator='line-info-basic'],\n [data-separator='metadata'] {\n margin-block: 0;\n }\n\n [data-separator='line-info'][data-separator-first] {\n margin-top: 0;\n }\n\n [data-separator='line-info'][data-separator-last] {\n margin-bottom: 0;\n }\n\n [data-expand-index] [data-separator-wrapper] {\n display: grid;\n grid-template-columns: 32px auto;\n }\n\n [data-expand-index] [data-separator-wrapper][data-separator-multi-button] {\n grid-template-columns: 32px 32px auto;\n }\n\n [data-expand-button],\n [data-separator-content] {\n display: flex;\n flex: 0 0 auto;\n align-items: center;\n background-color: var(--diffs-bg-separator);\n }\n\n [data-expand-index] [data-separator-content]:hover {\n text-decoration: underline;\n cursor: pointer;\n }\n\n [data-expand-button] {\n justify-content: center;\n flex-shrink: 0;\n cursor: pointer;\n min-width: 32px;\n align-self: stretch;\n color: var(--diffs-fg-number);\n border-right: 2px solid var(--diffs-bg);\n\n &:hover {\n color: var(--diffs-fg);\n }\n\n &[data-expand-all-button] {\n display: none;\n }\n }\n\n [data-expand-down] [data-icon] {\n transform: scaleY(-1);\n }\n\n [data-separator-content] {\n flex: 1 1 auto;\n padding: 0 1ch;\n height: 100%;\n color: var(--diffs-fg-number);\n\n overflow: hidden;\n justify-content: flex-start;\n }\n\n [data-separator='line-info'],\n [data-separator='line-info-basic'] {\n [data-separator-content] {\n height: 100%;\n user-select: none;\n overflow: clip;\n }\n }\n\n [data-unmodified-lines] {\n display: block;\n overflow: hidden;\n min-width: 0;\n text-overflow: ellipsis;\n white-space: nowrap;\n flex: 0 1 auto;\n }\n\n @supports (width: 1cqi) {\n [data-unified] {\n [data-separator='line-info'] [data-separator-wrapper] {\n padding-inline: var(--diffs-gap-inline, var(--diffs-gap-fallback));\n width: 100cqi;\n\n [data-separator-content] {\n border-radius: 6px;\n }\n }\n\n [data-separator='line-info'][data-expand-index]\n [data-separator-wrapper]\n [data-separator-content] {\n border-top-left-radius: unset;\n border-bottom-left-radius: unset;\n }\n }\n\n [data-gutter] {\n [data-separator='line-info'] [data-separator-wrapper] {\n padding-left: var(--diffs-gap-inline, var(--diffs-gap-fallback));\n }\n\n [data-separator='line-info'] [data-separator-content] {\n border-top-left-radius: 6px;\n border-bottom-left-radius: 6px;\n }\n\n [data-separator='line-info'][data-expand-index] [data-separator-content] {\n border-top-left-radius: unset;\n border-bottom-left-radius: unset;\n }\n }\n\n [data-additions] {\n [data-content] [data-separator='line-info'] {\n background-color: var(--diffs-bg);\n\n [data-separator-wrapper] {\n display: none;\n }\n }\n\n [data-gutter] [data-separator='line-info'] [data-separator-wrapper] {\n display: block;\n height: 100%;\n background-color: var(--diffs-bg-separator);\n border-top-right-radius: 6px;\n border-bottom-right-radius: 6px;\n\n [data-separator-content],\n [data-expand-button] {\n display: none;\n }\n }\n }\n\n [data-overflow='scroll']\n [data-additions]\n [data-gutter]\n [data-separator='line-info']\n [data-separator-wrapper] {\n width: calc(100cqi - var(--diffs-gap-inline, var(--diffs-gap-fallback)));\n }\n\n [data-overflow='wrap']\n [data-additions]\n [data-content]\n [data-separator='line-info']\n [data-separator-wrapper] {\n background-color: var(--diffs-bg-separator);\n display: block;\n height: 100%;\n margin-right: var(--diffs-gap-inline, var(--diffs-gap-fallback));\n border-top-right-radius: 6px;\n border-bottom-right-radius: 6px;\n\n [data-separator-content],\n [data-expand-button] {\n display: none;\n }\n }\n\n [data-separator='line-info'] [data-separator-wrapper] {\n [data-expand-both],\n [data-expand-down],\n [data-expand-up] {\n border-top-left-radius: 6px;\n border-bottom-left-radius: 6px;\n }\n }\n\n @media (pointer: fine) {\n [data-separator='line-info'] [data-separator-wrapper] {\n &[data-separator-multi-button] {\n [data-expand-up] {\n border-top-left-radius: 6px;\n border-bottom-left-radius: unset;\n }\n\n [data-expand-down] {\n border-bottom-left-radius: 6px;\n border-top-left-radius: unset;\n }\n }\n }\n }\n }\n\n @media (pointer: coarse) {\n [data-separator='line-info-basic']\n [data-separator-wrapper][data-separator-multi-button] {\n grid-template-columns: 34px 34px auto;\n\n [data-separator-content] {\n grid-column: unset;\n grid-row: unset;\n }\n }\n\n @supports (width: 1cqi) {\n [data-separator='line-info'] [data-separator-wrapper] {\n [data-expand-both],\n [data-expand-down],\n [data-expand-up] {\n border-top-left-radius: 6px;\n border-bottom-left-radius: 6px;\n }\n\n &[data-separator-multi-button] {\n [data-expand-up] {\n border-top-left-radius: 6px;\n border-bottom-left-radius: 6px;\n }\n\n [data-expand-down] {\n border-bottom-left-radius: unset;\n border-top-left-radius: unset;\n }\n }\n }\n }\n }\n\n @media (pointer: fine) {\n [data-separator-wrapper][data-separator-multi-button] {\n display: grid;\n grid-template-rows: 50% 50%;\n\n [data-separator-content] {\n grid-column: 2;\n grid-row: 1 / -1;\n min-width: min-content;\n }\n\n [data-expand-button] {\n grid-column: 1;\n }\n }\n\n [data-separator='line-info'] [data-separator-wrapper],\n [data-separator='line-info']\n [data-separator-wrapper][data-separator-multi-button] {\n grid-template-columns: 34px auto;\n }\n\n [data-separator='line-info-basic'][data-expand-index]\n [data-separator-wrapper] {\n grid-template-columns: 100% auto;\n }\n\n [data-separator='line-info'],\n [data-separator='line-info-basic'] {\n [data-separator-multi-button] {\n [data-expand-up] {\n border-bottom: 1px solid var(--diffs-bg);\n border-right: 2px solid var(--diffs-bg);\n }\n [data-expand-down] {\n border-top: 1px solid var(--diffs-bg);\n border-right: 2px solid var(--diffs-bg);\n }\n }\n }\n }\n\n /* Hunk separator content is duplicated across gutters and content columns,\n * so custom CSS can do some stuff. Lets hide things for defaults */\n [data-additions] [data-gutter] [data-separator-wrapper],\n [data-additions] [data-separator='line-info-basic'] [data-separator-wrapper],\n [data-content] [data-separator-wrapper] {\n display: none;\n }\n\n [data-line-annotation] {\n min-height: var(--diffs-annotation-min-height, 0);\n z-index: 2;\n }\n\n [data-merge-conflict-actions] {\n z-index: 2;\n }\n\n [data-separator='custom'] {\n display: grid;\n grid-template-columns: subgrid;\n }\n\n [data-line],\n [data-column-number],\n [data-no-newline] {\n position: relative;\n padding-inline: 1ch;\n }\n\n [data-indicators='classic'] [data-line] {\n padding-inline-start: 2ch;\n }\n\n [data-indicators='classic'] {\n [data-line-type='change-addition'],\n [data-line-type='change-deletion'] {\n &[data-no-newline],\n &[data-line] {\n &::before {\n display: inline-block;\n width: 1ch;\n height: 1lh;\n position: absolute;\n top: 0;\n left: 0;\n user-select: none;\n }\n }\n }\n\n [data-line-type='change-addition'] {\n &[data-line],\n &[data-no-newline] {\n &::before {\n content: '+';\n color: var(--diffs-addition-base);\n }\n }\n }\n\n [data-line-type='change-deletion'] {\n &[data-line],\n &[data-no-newline] {\n &::before {\n content: '-';\n color: var(--diffs-deletion-base);\n }\n }\n }\n }\n\n [data-indicators='bars'] {\n [data-line-type='change-deletion'],\n [data-line-type='change-addition'] {\n &[data-column-number] {\n &::before {\n content: '';\n display: block;\n width: 4px;\n height: 100%;\n position: absolute;\n top: 0;\n left: 0;\n user-select: none;\n contain: strict;\n }\n }\n }\n\n [data-line-type='change-deletion'] {\n &[data-column-number] {\n &::before {\n background-image: linear-gradient(\n 0deg,\n var(--diffs-bg-deletion) 50%,\n var(--diffs-deletion-base) 50%\n );\n background-repeat: repeat;\n background-size: 2px 2px;\n background-size: calc(1lh / round(1lh / 2px))\n calc(1lh / round(1lh / 2px));\n }\n }\n }\n\n [data-line-type='change-addition'] {\n &[data-column-number] {\n &::before {\n background-color: var(--diffs-addition-base);\n }\n }\n }\n }\n\n [data-overflow='wrap'] {\n [data-line] {\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n /* Annotations wrap in every overflow mode (see the base\n * [data-annotation-content] rule). In wrap mode, also break long words so\n * they do not overflow the wrapped column. */\n [data-annotation-content] {\n word-break: break-word;\n }\n }\n\n [data-overflow='scroll'] [data-line] {\n white-space: pre;\n min-height: 1lh;\n }\n\n [data-overflow='scroll'] [data-column-number] {\n min-height: 1lh;\n }\n\n [data-column-number] {\n box-sizing: content-box;\n text-align: right;\n user-select: none;\n color: var(--diffs-fg-number);\n padding-left: 2ch;\n }\n\n [data-line-number-content] {\n display: inline-block;\n min-width: var(\n --diffs-min-number-column-width,\n var(--diffs-min-number-column-width-default, 3ch)\n );\n position: relative;\n z-index: 1;\n }\n\n [data-disable-line-numbers] {\n [data-gutter-buffer],\n [data-column-number] {\n min-width: 4px;\n padding: 0;\n\n &::before {\n min-width: 0;\n }\n }\n\n [data-line-number-content] {\n display: none;\n }\n\n [data-gutter-utility-slot] {\n right: unset;\n left: 0;\n justify-content: flex-start;\n }\n\n &[data-indicators='bars'] [data-gutter-utility-slot] {\n /* Using 5px here because theres a 2px separator after the bar */\n left: 6px;\n }\n }\n\n [data-file][data-disable-line-numbers] {\n [data-gutter-buffer],\n [data-column-number] {\n min-width: 0;\n border-right: 0;\n }\n }\n\n [data-diff-span] {\n border-radius: 3px;\n box-decoration-break: clone;\n }\n\n [data-line-type='change-addition'] [data-diff-span] {\n background-color: var(--diffs-bg-addition-emphasis);\n }\n\n [data-line-type='change-deletion'] [data-diff-span] {\n background-color: var(--diffs-bg-deletion-emphasis);\n }\n\n [data-merge-conflict='marker-start'],\n [data-merge-conflict='marker-base'],\n [data-merge-conflict='marker-separator'],\n [data-merge-conflict='marker-end'] {\n padding-left: 1ch;\n color: var(--diffs-fg);\n }\n\n [data-merge-conflict='marker-start'],\n [data-merge-conflict='marker-end'] {\n display: flex;\n align-items: center;\n\n &::after {\n color: var(--diffs-fg-conflict-marker);\n font-style: normal;\n font-size: 0.75rem;\n line-height: 1.25rem;\n padding-left: 1ch;\n font-family: var(\n --diffs-header-font-family,\n var(--diffs-header-font-fallback)\n );\n }\n }\n\n [data-merge-conflict='marker-start']::after {\n content: '(Current Change)';\n }\n\n [data-merge-conflict='marker-end']::after {\n content: '(Incoming Change)';\n }\n\n [data-merge-conflict-actions-content] {\n display: flex;\n align-items: center;\n gap: 0.25rem;\n padding-inline: 0.5rem;\n min-height: 1.75rem;\n font-family: var(\n --diffs-header-font-family,\n var(--diffs-header-font-fallback)\n );\n font-size: 0.75rem;\n line-height: 1.2;\n color: var(--diffs-fg);\n }\n\n [data-merge-conflict-action] {\n appearance: none;\n border: 0;\n background: transparent;\n color: var(--diffs-fg-number);\n font: inherit;\n font-style: normal;\n cursor: pointer;\n padding: 0;\n }\n\n [data-merge-conflict-action]:hover {\n color: var(--diffs-fg);\n }\n\n [data-merge-conflict-action='current']:hover {\n color: var(--diffs-addition-base);\n }\n\n [data-merge-conflict-action='incoming']:hover {\n color: var(--diffs-modified-base);\n }\n\n [data-merge-conflict-action-separator] {\n color: var(--diffs-fg-number);\n opacity: 0.6;\n user-select: none;\n }\n\n /* Default Header Styles */\n /* --------------------- */\n [data-diffs-header='default'] {\n position: relative;\n background-color: var(--diffs-bg);\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n gap: var(--diffs-gap-inline, var(--diffs-gap-fallback));\n min-height: calc(\n 1lh + (var(--diffs-gap-block, var(--diffs-gap-fallback)) * 3)\n );\n padding-inline: 16px;\n top: 0;\n z-index: 2;\n }\n\n [data-header-content] {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: var(--diffs-gap-inline, var(--diffs-gap-fallback));\n min-width: 0;\n white-space: nowrap;\n }\n\n [data-header-content] [data-prev-name],\n [data-header-content] [data-title] {\n direction: rtl;\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: 0;\n white-space: nowrap;\n }\n\n [data-prev-name] {\n opacity: 0.7;\n }\n\n [data-rename-icon] {\n fill: currentColor;\n flex-shrink: 0;\n flex-grow: 0;\n }\n\n [data-diffs-header='default'] [data-metadata] {\n display: flex;\n align-items: center;\n gap: 1ch;\n white-space: nowrap;\n }\n\n [data-diffs-header='default'] [data-additions-count] {\n font-family: var(--diffs-font-family, var(--diffs-font-fallback));\n color: var(--diffs-addition-base);\n }\n\n [data-diffs-header='default'] [data-deletions-count] {\n font-family: var(--diffs-font-family, var(--diffs-font-fallback));\n color: var(--diffs-deletion-base);\n }\n\n [data-change-icon] {\n fill: currentColor;\n flex-shrink: 0;\n }\n\n [data-change-icon='change'],\n [data-change-icon='rename-pure'],\n [data-change-icon='rename-changed'] {\n color: var(--diffs-modified-base);\n }\n\n [data-change-icon='new'] {\n color: var(--diffs-addition-base);\n }\n\n [data-change-icon='deleted'] {\n color: var(--diffs-deletion-base);\n }\n\n [data-change-icon='file'] {\n opacity: 0.6;\n }\n\n [data-annotation-content] {\n position: relative;\n display: flow-root;\n align-self: flex-start;\n z-index: 2;\n min-width: 0;\n isolation: isolate;\n /* Annotations contain prose, not code. The text must wrap in every\n * overflow mode. Slotted annotation content inherits this white-space\n * value. In scroll mode without this rule, the text inherits\n * `white-space: pre` from the `pre` element. Then long text does not\n * wrap. */\n white-space: normal;\n }\n\n /* Sticky positioning has a composite costs, so we should _only_ pay it if we\n * need to */\n [data-overflow='scroll'] [data-annotation-content] {\n position: sticky;\n width: var(--diffs-column-content-width, auto);\n left: var(--diffs-column-number-width, 0);\n }\n\n [data-overflow='scroll'] [data-merge-conflict-actions-content] {\n position: sticky;\n width: var(--diffs-column-content-width, auto);\n left: var(--diffs-column-number-width, 0);\n }\n\n /* Undo some of the stuff that the 'pre' tag does */\n [data-annotation-slot] {\n text-wrap-mode: wrap;\n word-break: normal;\n white-space-collapse: collapse;\n }\n\n [data-gutter-utility-slot] {\n position: absolute;\n top: 0;\n bottom: 0;\n right: 0;\n display: flex;\n justify-content: flex-end;\n touch-action: none;\n }\n\n [data-utility-button] {\n display: flex;\n align-items: center;\n justify-content: center;\n border: none;\n appearance: none;\n width: 1lh;\n height: 1lh;\n margin-right: calc((1lh - 1ch) * -1);\n padding: 0;\n cursor: pointer;\n font-size: var(--diffs-font-size, 13px);\n line-height: var(--diffs-line-height, 20px);\n border-radius: 4px;\n background-color: var(--diffs-modified-base);\n color: var(--diffs-bg);\n fill: currentColor;\n position: relative;\n z-index: 4;\n touch-action: none;\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n inset: 0 0 0 -4px;\n }\n }\n\n /* Decoration Bars */\n /* --------------- */\n [data-decoration-bar-stack] {\n position: absolute;\n top: 0;\n bottom: 0;\n right: -2px;\n width: 6px;\n pointer-events: none;\n isolation: isolate;\n z-index: 1;\n background-color: var(--diffs-decoration-bar-color, transparent);\n /* overflow: clip visible; */\n box-sizing: content-box;\n border-left: 2px solid var(--diffs-bg);\n border-right: 2px solid var(--diffs-bg);\n\n [data-decoration-bar-depth='1'] & {\n background-color: color-mix(\n in lab,\n var(--diffs-bg) 20%,\n var(--diffs-decoration-bar-color, transparent)\n );\n }\n\n [data-decoration-bar-depth='2'] & {\n background-color: color-mix(\n in lab,\n var(--diffs-bg) 45%,\n var(--diffs-decoration-bar-color, transparent)\n );\n }\n\n [data-decoration-bar-depth='3'] & {\n background-color: color-mix(\n in lab,\n var(--diffs-bg) 65%,\n var(--diffs-decoration-bar-color, transparent)\n );\n }\n\n [data-decoration-bar-start] & {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n\n /* &::before { */\n /* content: ''; */\n /* position: absolute; */\n /* box-sizing: content-box; */\n /* display: block; */\n /* width: 6px; */\n /* height: 6px; */\n /* z-index: 1; */\n /* border-top-left-radius: 3px; */\n /* border-top-right-radius: 3px; */\n /* border-top: 2px solid var(--diffs-bg); */\n /* border-left: 2px solid var(--diffs-bg); */\n /* border-right: 2px solid var(--diffs-bg); */\n /* left: -2px; */\n /* top: -2px; */\n /* } */\n }\n\n [data-decoration-bar-end] & {\n z-index: 3;\n border-bottom-left-radius: 5px;\n border-bottom-right-radius: 5px;\n\n /* &::after { */\n /* content: ''; */\n /* position: absolute; */\n /* box-sizing: content-box; */\n /* display: block; */\n /* width: 6px; */\n /* height: 6px; */\n /* border-bottom-left-radius: 3px; */\n /* border-bottom-right-radius: 3px; */\n /* border-bottom: 2px solid var(--diffs-bg); */\n /* border-left: 2px solid var(--diffs-bg); */\n /* border-right: 2px solid var(--diffs-bg); */\n /* left: -2px; */\n /* bottom: -2px; */\n /* } */\n }\n\n /* [data-decoration-bar-end] & { */\n /* border-bottom-left-radius: 5px; */\n /* border-bottom-right-radius: 5px; */\n /* border-bottom: 2px solid var(--diffs-bg); */\n /* border-left: 2px solid var(--diffs-bg); */\n /* border-right: 2px solid var(--diffs-bg); */\n /* right: -2px; */\n /* bottom: -2px; */\n /* z-index: 3; */\n /* } */\n }\n\n [data-placeholder] {\n contain: strict;\n }\n\n [data-error-wrapper] {\n overflow: auto;\n padding: var(--diffs-gap-block, var(--diffs-gap-fallback))\n var(--diffs-gap-inline, var(--diffs-gap-fallback));\n max-height: 400px;\n scrollbar-width: none;\n\n [data-error-message] {\n font-weight: bold;\n font-size: 18px;\n color: var(--diffs-deletion-base);\n }\n\n [data-error-stack] {\n color: var(--diffs-fg-number);\n }\n }\n}\n", "import {\n DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY,\n DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE,\n} from '../constants';\n\nlet measuredScrollbarGutter: number | undefined;\n\n// Measures the horizontal scrollbar used by `[data-code]` once per page. The\n// hidden probe opts into the same selector as real code panes so custom\n// scrollbar CSS is reflected in the measured value.\nexport function getMeasuredScrollbarGutter(\n shadowRoot: ShadowRoot\n): number | undefined {\n if (measuredScrollbarGutter != null) {\n return measuredScrollbarGutter;\n }\n\n const host = shadowRoot.host;\n if (\n typeof HTMLElement !== 'undefined' &&\n host instanceof HTMLElement &&\n !host.isConnected\n ) {\n return undefined;\n }\n\n const wrapper = document.createElement('div');\n wrapper.setAttribute('data-code', '');\n wrapper.setAttribute(DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, 'true');\n\n const child = document.createElement('div');\n child.style.position = 'relative';\n child.style.width = '200%';\n child.style.height = '200%';\n wrapper.appendChild(child);\n\n shadowRoot.appendChild(wrapper);\n measuredScrollbarGutter = Math.max(\n wrapper.offsetHeight - wrapper.clientHeight,\n 0\n );\n wrapper.remove();\n return measuredScrollbarGutter;\n}\n\nexport function createMeasuredScrollbarGutterDeclaration(\n scrollbarGutter: number | undefined\n): string {\n const value =\n scrollbarGutter == null\n ? 'var(--diffs-scrollbar-gutter-fallback)'\n : `${scrollbarGutter}px`;\n return `${DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY}: ${value};`;\n}\n", "import { DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY } from '../constants';\nimport rawStyles from '../style.css?inline';\nimport type { ThemeTypes } from '../types';\nimport { createMeasuredScrollbarGutterDeclaration } from './scrollbarGutter';\n\nconst LAYER_ORDER = `@layer base, theme, rendered, unsafe;`;\nconst SCROLLBAR_GUTTER_DECLARATION_PATTERN = new RegExp(\n `${escapeRegExp(DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY)}\\\\s*:\\\\s*[^;]+;`\n);\n\nexport function wrapCoreCSS(mainCSS: string) {\n return `${LAYER_ORDER}\n${rawStyles}\n@layer theme {\n ${mainCSS}\n}`;\n}\n\nexport function wrapUnsafeCSS(unsafeCSS: string) {\n return `${LAYER_ORDER}\n@layer unsafe {\n ${unsafeCSS}\n}`;\n}\n\nexport function wrapThemeCSS(\n themeCSS: string,\n themeType: ThemeTypes = 'system',\n scrollbarGutter?: number\n) {\n const colorSchemeRule =\n themeType === 'system'\n ? ''\n : `\n color-scheme: ${themeType};`;\n const scrollbarGutterVar =\n createMeasuredScrollbarGutterDeclaration(scrollbarGutter);\n const tokenFontStyles = (\n themeType === 'system' ? ['light', 'dark'] : [themeType]\n )\n .map((type) => {\n const styles = `\n [data-line] span, [data-edit-prediction-suffix] span {\n font-weight: var(--diffs-token-${type}-font-weight, inherit);\n font-style: var(--diffs-token-${type}-font-style, inherit);\n text-decoration: var(--diffs-token-${type}-text-decoration, inherit);\n }`;\n return themeType === 'system' && type === 'dark'\n ? `@media (prefers-color-scheme: dark) {${styles}\\n}`\n : styles;\n })\n .join('\\n');\n\n return `${LAYER_ORDER}\n@layer base {\n ${tokenFontStyles}\n}\n@layer rendered {\n :host {${colorSchemeRule}\n ${scrollbarGutterVar}\n ${themeCSS}\n }\n}`;\n}\n\nexport function patchScrollbarGutterSize(\n themeCSS: string,\n scrollbarGutter: number | undefined\n): string {\n const scrollbarGutterRule =\n createMeasuredScrollbarGutterDeclaration(scrollbarGutter);\n return themeCSS.replace(\n SCROLLBAR_GUTTER_DECLARATION_PATTERN,\n scrollbarGutterRule\n );\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n", "import type { AnnotationSide } from '../types';\n\nexport interface LineAnnotationPosition {\n lineNumber: number;\n side?: AnnotationSide;\n}\n\n// When an edit moves an annotation to another line, the remap replaces it\n// with a shallow clone holding the new line number, and later edits clone\n// those clones again. This map links every clone back to the original\n// annotation the caller passed in, so session state keyed by that original —\n// most importantly recorded slot names — keeps working no matter how many\n// times an annotation has been cloned, or which clone generation an undo\n// brings back.\nconst lineAnnotationSources = new WeakMap<\n LineAnnotationPosition,\n LineAnnotationPosition\n>();\n\n/**\n * Resolve a possibly-remapped annotation back to the original object it\n * descends from. Annotations that were never cloned resolve to themselves.\n */\nexport function getLineAnnotationSource<T extends LineAnnotationPosition>(\n annotation: T\n): T {\n const source = lineAnnotationSources.get(annotation);\n return source == null ? annotation : (source as T);\n}\n\nexport function recordLineAnnotationSource(\n moved: LineAnnotationPosition,\n annotation: LineAnnotationPosition\n): void {\n lineAnnotationSources.set(moved, annotation);\n}\n", "interface CreateCodeNodeProps {\n pre?: HTMLPreElement;\n code?: HTMLElement;\n columnType?: 'additions' | 'deletions' | 'unified';\n rowSpan?: number;\n containerSize?: boolean;\n}\n\nexport function getOrCreateCodeNode({\n code,\n pre,\n columnType,\n rowSpan,\n containerSize = false,\n}: CreateCodeNodeProps = {}): HTMLElement {\n if (code == null) {\n code = document.createElement('code');\n code.setAttribute('data-code', '');\n if (columnType != null) {\n code.setAttribute(`data-${columnType}`, '');\n }\n pre?.appendChild(code);\n }\n if (rowSpan != null) {\n code.style.setProperty('grid-row', `span ${rowSpan}`);\n } else {\n code.style.removeProperty('grid-row');\n }\n if (containerSize) {\n code.setAttribute('data-container-size', '');\n } else {\n code.removeAttribute('data-container-size');\n }\n return code;\n}\n", "export function prerenderHTMLIfNecessary(\n element: HTMLElement,\n html: string | undefined\n): void {\n if (html == null) return;\n const shadowRoot =\n element.shadowRoot ?? element.attachShadow({ mode: 'open' });\n if (shadowRoot.innerHTML === '') {\n shadowRoot.innerHTML = html;\n }\n}\n", "import type { PrePropertiesConfig } from '../types';\n\nexport function setPreNodeProperties(\n pre: HTMLPreElement,\n {\n type,\n diffIndicators,\n disableBackground,\n disableLineNumbers,\n overflow,\n split,\n totalLines,\n customProperties,\n }: PrePropertiesConfig\n): HTMLPreElement {\n // NOTE: We always apply custom properties first so the important properties\n // cannot be overridden.\n if (customProperties != null) {\n for (const key in customProperties) {\n const value = customProperties[key];\n if (value != null) {\n pre.setAttribute(key, `${value}`);\n }\n }\n }\n if (type === 'diff') {\n pre.setAttribute('data-diff', '');\n pre.removeAttribute('data-file');\n } else {\n pre.setAttribute('data-file', '');\n pre.removeAttribute('data-diff');\n }\n switch (diffIndicators) {\n case 'bars':\n case 'classic':\n pre.setAttribute('data-indicators', diffIndicators);\n break;\n case 'none':\n pre.removeAttribute('data-indicators');\n break;\n }\n if (disableLineNumbers) {\n pre.setAttribute('data-disable-line-numbers', '');\n } else {\n pre.removeAttribute('data-disable-line-numbers');\n }\n if (disableBackground) {\n pre.removeAttribute('data-background');\n } else {\n pre.setAttribute('data-background', '');\n }\n if (type === 'diff') {\n pre.setAttribute('data-diff-type', split ? 'split' : 'single');\n } else {\n pre.removeAttribute('data-diff-type');\n }\n pre.setAttribute('data-overflow', overflow);\n // Set CSS custom property for line number column width\n pre.style.setProperty(\n '--diffs-min-number-column-width-default',\n `${`${totalLines}`.length}ch`\n );\n return pre;\n}\n", "export function isStyleNode(element: Element): element is HTMLStyleElement {\n if (\n typeof HTMLStyleElement !== 'undefined' &&\n element instanceof HTMLStyleElement\n ) {\n return true;\n }\n\n const tagName = element.tagName ?? element.nodeName;\n return typeof tagName === 'string' && tagName.toLowerCase() === 'style';\n}\n", "let _isMacLike: boolean | undefined = undefined;\nlet _isLinux: boolean | undefined = undefined;\nlet _isSafari: boolean | undefined = undefined;\nlet _isFirefox: boolean | undefined = undefined;\n\n/**\n * Clears the cached platform/browser detection. Detection is memoized on first\n * call, so a test process that swaps `navigator` (e.g. to exercise Linux or\n * Safari behavior) must reset it; otherwise the value cached by an earlier test\n * leaks across tests and no longer matches the active navigator.\n */\nexport function resetPlatformDetection(): void {\n _isMacLike = undefined;\n _isLinux = undefined;\n _isSafari = undefined;\n _isFirefox = undefined;\n}\n\nexport function isMacLike(): boolean {\n return (_isMacLike ??= /macOS|MacIntel|iPhone|iPad|iPod/i.test(\n getPlatform()\n ));\n}\n\nexport function isLinux(): boolean {\n return (_isLinux ??= /Linux/i.test(getPlatform()));\n}\n\nexport function isSafari(): boolean {\n return (_isSafari ??=\n // oxlint-disable-next-line typescript/no-explicit-any\n ('safari' in window && 'pushNotification' in (window as any).safari) ||\n /^((?!chrome|android).)*safari/i.test(navigator.userAgent));\n}\n\n// Gecko-based Firefox builds (desktop and Android). Firefox on iOS (FxiOS)\n// renders with WebKit and is intentionally excluded.\nexport function isFirefox(): boolean {\n return (_isFirefox ??= /\\bFirefox\\//.test(navigator.userAgent));\n}\n\nfunction getPlatform(): string {\n const navigator = globalThis.navigator as Navigator & {\n userAgentData?: { platform?: string };\n };\n return navigator?.platform ?? navigator?.userAgentData?.platform ?? 'unknown';\n}\n", "import {\n getLineAnnotationSource,\n type LineAnnotationPosition,\n} from './lineAnnotationIdentity';\n\n/**\n * Annotation state for an active edit session. Like the private\n * `editSessionFile`/`editSessionDiff` render models, we avoid mutating the\n * original annotations and instead create a duplicate set that we mutate as\n * needed while the user is editing the file or diff. When editing is\n * finished, we can either revert back to the old state, or inherit the new\n * mutated annotations.\n *\n * `current` holds the annotations actually rendered; the editor replaces\n * them as edits move annotations between lines. `provided` is the last\n * annotations array the component rendered with. When a render is called with\n * annotations, we check whether it's a new array or the existing annotations\n * we've previously rendered. If new, we fully replace whatever the edit\n * session derived since there's no way to really reasonably rectify existing\n * state. If it's the same as `provided` or `current`, we continue assuming\n * `current` is the latest source of truth.\n *\n * `slotNames` map is a hack to keep annotation content attached while lines\n * move around. Normally slotNames are derived from the target line number (and\n * possibly side of the diff). Doing this while editing would force every\n * annotation that gets moved to remount which is not ideal. So by keeping a\n * reference map of annotation to slot name, we can keep invalid slot names\n * until editing is completed, and then either revert back to our original\n * annotations or update them with their new slot names (which will currently\n * trigger a remount). In a future update we'll add a better ID system for\n * annotations so we don't need to depend on this flawed keying architecture.\n */\n\nexport interface EditSessionAnnotations<TAnnotation> {\n provided: TAnnotation[];\n current: TAnnotation[];\n slotNames: Map<object, string>;\n}\n\n/**\n * Creates session state when an editor attaches. The array is kept as-is for\n * both `provided` and `current`, and we record each annotation's slot name\n * before any edits can move it.\n *\n * `previousSession` covers a whole new file or diff arriving mid-edit. The\n * annotations that come with it describe the new document, so we rebuild the\n * session around them — but any annotation the outgoing session already\n * named keeps that name, since the caller's content is already rendered into\n * a slot with it. Names for annotations that didn't survive the swap are\n * simply dropped.\n */\nexport function adoptEditSessionAnnotations<\n TAnnotation extends LineAnnotationPosition,\n>(\n annotations: TAnnotation[],\n getName: (annotation: TAnnotation) => string,\n previousSession?: EditSessionAnnotations<TAnnotation>\n): EditSessionAnnotations<TAnnotation> {\n const slotNames = new Map<object, string>();\n for (const annotation of annotations) {\n const source = getLineAnnotationSource(annotation);\n slotNames.set(\n source,\n previousSession?.slotNames.get(source) ?? getName(annotation)\n );\n }\n return { provided: annotations, current: annotations, slotNames };\n}\n\n/**\n * Handles the caller passing a brand new annotations array while editing is\n * active. We take it exactly as given — line numbers are read against the\n * document as currently edited, and there's no merging with what the session\n * had — so it replaces both `provided` and `current`. Annotations we've seen\n * before keep their recorded slot names; new ones record a name for wherever\n * they landed.\n */\nexport function writeEditSessionAnnotations<\n TAnnotation extends LineAnnotationPosition,\n>(\n session: EditSessionAnnotations<TAnnotation>,\n annotations: TAnnotation[],\n getName: (annotation: TAnnotation) => string\n): void {\n for (const annotation of annotations) {\n const source = getLineAnnotationSource(annotation);\n if (!session.slotNames.has(source)) {\n session.slotNames.set(source, getName(annotation));\n }\n }\n session.provided = annotations;\n session.current = annotations;\n}\n\n/**\n * Every slot name an editable component renders resolves through here. With\n * no active session this is just the normal position-derived name. During a\n * session we return the recorded name instead, and an annotation we've never\n * seen records its name the first time anyone asks. That way everything that\n * writes slot names — the renderers, the editor, the light-DOM wrappers —\n * lands on the same name for the same annotation.\n */\nexport function resolveEditSessionSlotName<\n TAnnotation extends LineAnnotationPosition,\n>(\n session: EditSessionAnnotations<TAnnotation> | undefined,\n annotation: TAnnotation,\n getName: (annotation: TAnnotation) => string\n): string {\n if (session == null) {\n return getName(annotation);\n }\n const source = getLineAnnotationSource(annotation);\n let name = session.slotNames.get(source);\n if (name == null) {\n name = getName(annotation);\n session.slotNames.set(source, name);\n }\n return name;\n}\n", "import type {\n InteractionManagerMode,\n OnTokenEventProps,\n} from '../managers/InteractionManager';\n\ninterface ShouldUseTokenTransformerProps<TMode extends InteractionManagerMode> {\n onTokenClick?(props: OnTokenEventProps<TMode>, event: MouseEvent): unknown;\n onTokenEnter?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;\n onTokenLeave?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;\n useTokenTransformer?: boolean;\n}\n\n// Token interaction callbacks require token metadata in the markup to fire at\n// all, so attaching any token callback enables the transformer;\nexport function shouldUseTokenTransformer<\n TMode extends 'file' | 'diff' = 'file',\n>(options: ShouldUseTokenTransformerProps<TMode> | undefined): boolean {\n return (\n options?.useTokenTransformer === true ||\n options?.onTokenClick != null ||\n options?.onTokenEnter != null ||\n options?.onTokenLeave != null\n );\n}\n", "/**\n * Runs a wholesale code-column rebuild with the pre element's height pinned,\n * working around a WebKit bug (https://bugs.webkit.org/show_bug.cgi?id=308027):\n * when the subtree of a `container-type: inline-size` element is rewritten in\n * bulk (column innerHTML swaps, grid-row span rewrites), WebKit resolves the\n * ancestor scroller's offset against a transiently collapsed interim layout\n * and clamps scrollTop to 0 — the scroller visibly jumps to the top on every\n * edit. Pinning `min-height` keeps that interim layout at full height so the\n * scroll offset survives; the layout read before unpinning is required, since\n * it materializes the interim layout while the pin is active.\n *\n * Both the pin height read and the pinned-layout read force a synchronous\n * layout, so callers own the gating via shouldGuardRebuildScroll: Safari-only,\n * edit-mode-only, and never inside CodeView's batched read/write render pass.\n */\nexport function guardWebKitScrollDuringRebuild(\n pre: HTMLElement | undefined,\n rebuild: () => void\n): void {\n const height = pre?.offsetHeight ?? 0;\n if (pre == null || height === 0) {\n rebuild();\n return;\n }\n pre.style.minHeight = `${height}px`;\n try {\n rebuild();\n void pre.offsetHeight;\n } finally {\n pre.style.minHeight = '';\n }\n}\n", "import { THEME_CSS_ATTRIBUTE } from '../constants';\n\ninterface UpsertHostThemeStyleProps {\n shadowRoot: ShadowRoot;\n currentNode: HTMLStyleElement | undefined;\n themeCSS: string;\n}\n\n// Keep the host theme style stable so renderers can update the host-scoped theme\n// CSS without rebuilding the rest of the shadow DOM.\nexport function upsertHostThemeStyle({\n shadowRoot,\n currentNode,\n themeCSS,\n}: UpsertHostThemeStyleProps): HTMLStyleElement | undefined {\n if (themeCSS.trim() === '') {\n currentNode?.remove();\n return undefined;\n }\n\n currentNode ??= createHostThemeStyleNode();\n currentNode.textContent = themeCSS;\n if (currentNode.parentNode !== shadowRoot) {\n shadowRoot.appendChild(currentNode);\n }\n return currentNode;\n}\n\nexport function createHostThemeStyleNode(): HTMLStyleElement {\n const node = document.createElement('style');\n node.setAttribute(THEME_CSS_ATTRIBUTE, '');\n return node;\n}\n", "// Error types shared by the worker pool and its consumers. Keep this module\n// free of imports so components can handle pool errors without loading the\n// pool implementation and its dependencies.\n\n/** The pool was terminated while the operation was pending. */\nexport class WorkerPoolTerminatedError extends Error {\n constructor() {\n super('WorkerPoolManager: operation canceled because the pool terminated');\n this.name = 'WorkerPoolTerminatedError';\n }\n}\n\n/** The task was replaced or removed before it completed. */\nexport class WorkerPoolTaskCanceledError extends Error {\n constructor() {\n super('WorkerPoolManager: operation canceled before the task completed');\n this.name = 'WorkerPoolTaskCanceledError';\n }\n}\n\n/**\n * A worker failed during initialization. The pool rejects initialization and\n * pending highlight requests with this error. Components then highlight on\n * the main thread.\n */\nexport class WorkerPoolWorkerError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WorkerPoolWorkerError';\n }\n}\n\n// Track errors passed to onWorkerError without adding fields to the errors.\nconst reportedWorkerErrors = new WeakSet<WorkerPoolWorkerError>();\n\n/**\n * Mark a worker error as reported so the pool and its consumers do not log it\n * again. Used internally by the pool; not exported from the package entry.\n */\nexport function markWorkerErrorReported(error: WorkerPoolWorkerError): void {\n reportedWorkerErrors.add(error);\n}\n\n/**\n * Returns true when an operation was canceled because the pool was terminated\n * or the task was replaced or removed before completion.\n */\nexport function isWorkerPoolCancellation(\n error: unknown\n): error is WorkerPoolTerminatedError | WorkerPoolTaskCanceledError {\n return (\n error instanceof WorkerPoolTerminatedError ||\n error instanceof WorkerPoolTaskCanceledError\n );\n}\n\n/**\n * Returns true for cancellations and worker errors passed to onWorkerError.\n * Callers use this to skip cancellation logs and duplicate error reports.\n */\nexport function isHandledWorkerPoolError(error: unknown): boolean {\n return (\n isWorkerPoolCancellation(error) ||\n (error instanceof WorkerPoolWorkerError && reportedWorkerErrors.has(error))\n );\n}\n", "import { DIFFS_TAG_NAME } from '../constants';\nimport styles from '../style.css?inline';\nimport { getMeasuredScrollbarGutter } from '../utils/scrollbarGutter';\n\n// If HTMLElement is undefined it usually means we are in a server environment\n// so best to just not do anything\nif (\n typeof HTMLElement !== 'undefined' &&\n customElements.get(DIFFS_TAG_NAME) == null\n) {\n let sheet: CSSStyleSheet | undefined;\n\n class FileDiffContainer extends HTMLElement {\n constructor() {\n super();\n // If shadow root is already open, we can sorta assume the\n // CSS is already in place\n if (this.shadowRoot != null) {\n return;\n }\n const shadowRoot = this.attachShadow({ mode: 'open' });\n if (sheet == null) {\n sheet = new CSSStyleSheet();\n sheet.replaceSync(styles);\n }\n shadowRoot.adoptedStyleSheets = [sheet];\n }\n\n connectedCallback() {\n const shadowRoot = this.shadowRoot ?? this.attachShadow({ mode: 'open' });\n getMeasuredScrollbarGutter(shadowRoot);\n }\n }\n\n customElements.define(DIFFS_TAG_NAME, FileDiffContainer);\n}\n\nexport const DiffsContainerLoaded = true;\n", "import { DEFAULT_VIRTUAL_FILE_METRICS } from '../constants';\nimport type { HunkSeparators, VirtualFileMetrics } from '../types';\n\nexport function computeVirtualFileMetrics(\n metrics?: Partial<VirtualFileMetrics>\n): VirtualFileMetrics {\n return {\n ...DEFAULT_VIRTUAL_FILE_METRICS,\n ...metrics,\n };\n}\n\nexport function getVirtualFileHeaderRegion(\n metrics: VirtualFileMetrics,\n disableFileHeader: boolean\n): number {\n return (\n getVirtualFileHeaderHeight(metrics, disableFileHeader) +\n getVirtualFilePaddingTop(metrics, disableFileHeader)\n );\n}\n\n// Collapsed items render only the header. The top padding belongs to the\n// code content, which is removed on collapse.\nexport function getVirtualFileHeaderHeight(\n metrics: VirtualFileMetrics,\n disableFileHeader: boolean\n): number {\n return disableFileHeader ? 0 : metrics.diffHeaderHeight;\n}\n\nexport function getVirtualFilePaddingTop(\n metrics: VirtualFileMetrics,\n disableFileHeader: boolean\n): number {\n return metrics.paddingTop ?? (disableFileHeader ? metrics.spacing : 0);\n}\n\nexport function getVirtualFilePaddingBottom(\n metrics: VirtualFileMetrics\n): number {\n return metrics.paddingBottom ?? metrics.spacing;\n}\n\nexport function getDefaultHunkSeparatorHeight(type: HunkSeparators): number {\n switch (type) {\n case 'simple':\n return 4;\n case 'metadata':\n case 'line-info':\n case 'line-info-basic':\n case 'custom':\n return 32;\n }\n}\n", "import type { FileDiffMetadata } from '../types';\n\n// Because FileDiffMetadata is a potentially unbounded and structurally deep\n// object, we only check for top level equality or a cache key, otherwise we\n// just assume it's different every time\nexport function areDiffTargetsEqual(\n diffA: FileDiffMetadata | undefined,\n diffB: FileDiffMetadata | undefined\n): boolean {\n return diffA?.cacheKey != null || diffB?.cacheKey != null\n ? diffA?.cacheKey === diffB?.cacheKey\n : diffA === diffB;\n}\n", "import type { FileContents } from '../types';\n\nexport function areFilesEqual(\n fileA: FileContents | undefined,\n fileB: FileContents | undefined\n): boolean {\n return (\n fileA?.cacheKey === fileB?.cacheKey &&\n fileA?.contents === fileB?.contents &&\n fileA?.name === fileB?.name &&\n fileA?.lang === fileB?.lang\n );\n}\n", "import type { FileDiffMetadata, Hunk } from '../types';\n\nexport function cloneHunks(hunks: Hunk[]): Hunk[] {\n return hunks.map((hunk) => ({\n ...hunk,\n hunkContent: hunk.hunkContent.map((content) => ({ ...content })),\n }));\n}\n\nexport function cloneFileDiffMetadata(\n fileDiff: FileDiffMetadata\n): FileDiffMetadata {\n return {\n ...fileDiff,\n hunks: cloneHunks(fileDiff.hunks),\n deletionLines: [...fileDiff.deletionLines],\n additionLines: [...fileDiff.additionLines],\n };\n}\n", "/** Converts a unified hunk side's start/count into its consumed-file range. */\nexport function getHunkSideStartBoundary(start: number, count: number): number {\n return start - (count === 0 ? 0 : 1);\n}\n\nexport function getHunkSideEndBoundary(start: number, count: number): number {\n return getHunkSideStartBoundary(start, count) + count;\n}\n", "const CACHE_KEY_VERSION = 1;\n\n/** Encodes caller-controlled segments without delimiter ambiguity. */\nexport function composeCacheKey(\n scope: string,\n ...segments: readonly string[]\n): string {\n return `ck${CACHE_KEY_VERSION}:${JSON.stringify([scope, ...segments])}`;\n}\n", "import { SPLIT_WITH_NEWLINES } from '../constants';\n\n/**\n * Splits file contents into lines using the same logic as diff parsing.\n * - Preserves trailing newlines on each line\n *\n * @param contents - The raw file contents string\n * @returns Array of lines with newlines preserved\n */\nexport function splitFileContents(contents: string): string[] {\n return contents !== '' ? contents.split(SPLIT_WITH_NEWLINES) : [];\n}\n", "import type {\n FileContents,\n FileDiffLoadedFiles,\n FileDiffMetadata,\n Hunk,\n} from '../types';\nimport { cloneFileDiffMetadata } from './cloneFileDiffMetadata';\nimport { composeCacheKey } from './composeCacheKey';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\nimport { splitFileContents } from './splitFileContents';\n\ninterface HydratedHunksResult {\n hunks: Hunk[];\n splitLineCount: number;\n unifiedLineCount: number;\n}\n\n/**\n * Hydrates a partial diff in place with full file line arrays.\n */\nexport function hydratePartialDiff(\n type: 'clone' | 'merge',\n fileDiff: FileDiffMetadata,\n files: FileDiffLoadedFiles\n): FileDiffMetadata {\n const targetFileDiff =\n type === 'clone' ? cloneFileDiffMetadata(fileDiff) : fileDiff;\n\n if (!targetFileDiff.isPartial) {\n throw new Error('hydratePartialDiff: fileDiff must be partial');\n }\n\n switch (targetFileDiff.type) {\n case 'change':\n case 'rename-changed': {\n const oldFile = requireOldFile(targetFileDiff, files);\n const newFile = requireNewFile(targetFileDiff, files);\n return hydrateTwoSidedFileDiff(targetFileDiff, oldFile, newFile);\n }\n case 'rename-pure': {\n const newFile = requireNewFile(targetFileDiff, files);\n requireMissingOldFile(targetFileDiff, files);\n const lines = splitFileContents(newFile.contents);\n targetFileDiff.isPartial = false;\n targetFileDiff.deletionLines = lines;\n targetFileDiff.additionLines = lines;\n targetFileDiff.deletionCharacterCount = newFile.contents.length;\n targetFileDiff.additionCharacterCount = newFile.contents.length;\n setHydratedCacheKey(targetFileDiff, null, newFile);\n return targetFileDiff;\n }\n }\n throw new Error(\n `hydratePartialDiff: ${targetFileDiff.type} diffs cannot be hydrated from loaded files`\n );\n}\n\nfunction hydrateTwoSidedFileDiff(\n fileDiff: FileDiffMetadata,\n oldFile: FileContents,\n newFile: FileContents\n): FileDiffMetadata {\n const deletionLines = splitFileContents(oldFile.contents);\n const additionLines = splitFileContents(newFile.contents);\n const { hunks, splitLineCount, unifiedLineCount } = hydrateHunks(\n fileDiff.hunks,\n additionLines.length\n );\n\n fileDiff.hunks = hunks;\n fileDiff.splitLineCount = splitLineCount;\n fileDiff.unifiedLineCount = unifiedLineCount;\n fileDiff.isPartial = false;\n fileDiff.deletionLines = deletionLines;\n fileDiff.additionLines = additionLines;\n fileDiff.deletionCharacterCount = oldFile.contents.length;\n fileDiff.additionCharacterCount = newFile.contents.length;\n setHydratedCacheKey(fileDiff, oldFile, newFile);\n return fileDiff;\n}\n\nfunction hydrateHunks(\n hunks: Hunk[],\n totalAdditionLines: number\n): HydratedHunksResult {\n let splitLineCount = 0;\n let unifiedLineCount = 0;\n let lastHunkAdditionEnd = 0;\n\n const hydratedHunks: Hunk[] = [];\n\n for (const hunk of hunks) {\n const additionLineIndex = Math.max(hunk.additionStart - 1, 0);\n const deletionLineIndex = Math.max(hunk.deletionStart - 1, 0);\n let contentAdditionLineIndex = additionLineIndex;\n let contentDeletionLineIndex = deletionLineIndex;\n let hunkAdditionLines = 0;\n let hunkDeletionLines = 0;\n let hunkSplitLineCount = 0;\n let hunkUnifiedLineCount = 0;\n const hunkContent: Hunk['hunkContent'] = [];\n\n for (const content of hunk.hunkContent) {\n if (content.type === 'context') {\n hunkContent.push({\n ...content,\n additionLineIndex: contentAdditionLineIndex,\n deletionLineIndex: contentDeletionLineIndex,\n });\n contentAdditionLineIndex += content.lines;\n contentDeletionLineIndex += content.lines;\n hunkSplitLineCount += content.lines;\n hunkUnifiedLineCount += content.lines;\n continue;\n }\n\n hunkContent.push({\n ...content,\n additionLineIndex: contentAdditionLineIndex,\n deletionLineIndex: contentDeletionLineIndex,\n });\n contentAdditionLineIndex += content.additions;\n contentDeletionLineIndex += content.deletions;\n hunkAdditionLines += content.additions;\n hunkDeletionLines += content.deletions;\n hunkSplitLineCount += Math.max(content.additions, content.deletions);\n hunkUnifiedLineCount += content.additions + content.deletions;\n }\n\n const collapsedBefore = Math.max(\n getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) -\n lastHunkAdditionEnd,\n 0\n );\n hydratedHunks.push({\n ...hunk,\n collapsedBefore,\n additionLineIndex,\n deletionLineIndex,\n additionLines: hunkAdditionLines,\n deletionLines: hunkDeletionLines,\n hunkContent,\n splitLineStart: splitLineCount + collapsedBefore,\n unifiedLineStart: unifiedLineCount + collapsedBefore,\n splitLineCount: hunkSplitLineCount,\n unifiedLineCount: hunkUnifiedLineCount,\n });\n\n splitLineCount += collapsedBefore + hunkSplitLineCount;\n unifiedLineCount += collapsedBefore + hunkUnifiedLineCount;\n lastHunkAdditionEnd = getHunkSideEndBoundary(\n hunk.additionStart,\n hunk.additionCount\n );\n }\n\n if (hydratedHunks.length > 0) {\n const lastHunk = hydratedHunks[hydratedHunks.length - 1];\n const lastHunkEnd = getHunkSideEndBoundary(\n lastHunk.additionStart,\n lastHunk.additionCount\n );\n const collapsedAfter = Math.max(totalAdditionLines - lastHunkEnd, 0);\n splitLineCount += collapsedAfter;\n unifiedLineCount += collapsedAfter;\n }\n\n return { hunks: hydratedHunks, splitLineCount, unifiedLineCount };\n}\n\nfunction requireOldFile(\n fileDiff: FileDiffMetadata,\n files: FileDiffLoadedFiles\n): FileContents {\n if (files.oldFile == null) {\n throw new Error(\n `hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile`\n );\n }\n return files.oldFile;\n}\n\nfunction requireNewFile(\n fileDiff: FileDiffMetadata,\n files: FileDiffLoadedFiles\n): FileContents {\n if (files.newFile == null) {\n throw new Error(\n `hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires newFile`\n );\n }\n return files.newFile;\n}\n\nfunction requireMissingOldFile(\n fileDiff: FileDiffMetadata,\n files: FileDiffLoadedFiles\n): void {\n if (files.oldFile !== null) {\n throw new Error(\n `hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile to be null`\n );\n }\n}\n\nfunction getHydratedCacheKey(\n fileDiff: FileDiffMetadata,\n oldFile: FileContents | null,\n newFile: FileContents | null\n): string | undefined {\n if (fileDiff.cacheKey != null) {\n return `${fileDiff.cacheKey}:hydrated`;\n }\n return getLoadedFileCacheKey(oldFile, newFile);\n}\n\nfunction setHydratedCacheKey(\n fileDiff: FileDiffMetadata,\n oldFile: FileContents | null,\n newFile: FileContents | null\n): void {\n const cacheKey = getHydratedCacheKey(fileDiff, oldFile, newFile);\n if (cacheKey == null) {\n delete fileDiff.cacheKey;\n return;\n }\n fileDiff.cacheKey = cacheKey;\n}\n\nfunction getLoadedFileCacheKey(\n oldFile: FileContents | null,\n newFile: FileContents | null\n): string | undefined {\n if (oldFile != null && newFile != null) {\n return oldFile.cacheKey != null && newFile.cacheKey != null\n ? composeCacheKey('hydrated-files', oldFile.cacheKey, newFile.cacheKey)\n : undefined;\n }\n return oldFile?.cacheKey ?? newFile?.cacheKey;\n}\n", "export function cleanLastNewline(contents: string): string {\n let end = contents.length;\n if (contents.charCodeAt(end - 1) === /* \\n */ 10) {\n end--;\n if (contents.charCodeAt(end - 1) === /* \\r */ 13) {\n end--;\n }\n }\n return contents.slice(0, end);\n}\n", "const stringDetachEncoder = new TextEncoder();\nconst stringDetachDecoder = new TextDecoder('utf-8', { ignoreBOM: true });\nconst SURROGATE_CODE_UNIT_PATTERN = /[\\uD800-\\uDFFF]/;\nconst STRING_DETACH_INITIAL_BUFFER_SIZE = 1024;\nlet stringDetachBuffer = new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);\n\n// Drops the reusable scratch buffer after a parsing run so one unusually long\n// line does not pin that peak allocation for the lifetime of the process.\nexport function releaseStringDetachBuffer(): void {\n if (stringDetachBuffer.length !== STRING_DETACH_INITIAL_BUFFER_SIZE) {\n stringDetachBuffer = new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);\n }\n}\n\n// Forces a fresh backing string so a retained substring does not keep the\n// original raw patch/file text alive.\nexport function detachString(value: string): string {\n if (value.length === 0) {\n return value;\n }\n\n // TextEncoder replaces lone surrogate code units with U+FFFD, but diff input\n // can contain arbitrary text. JSON round-tripping preserves those code units\n // while still forcing V8 to allocate a fresh backing string.\n if (SURROGATE_CODE_UNIT_PATTERN.test(value)) {\n return JSON.parse(JSON.stringify(value)) as string;\n }\n\n // Without surrogates, each UTF-16 code unit encodes to at most 3 UTF-8 bytes.\n // Reusing this scratch buffer avoids allocating a new Uint8Array for every\n // parsed line while keeping retained line strings detached from the raw patch.\n const requiredByteLength = value.length * 3;\n if (stringDetachBuffer.length < requiredByteLength) {\n stringDetachBuffer = new Uint8Array(requiredByteLength);\n }\n\n const { written } = stringDetachEncoder.encodeInto(value, stringDetachBuffer);\n // Decoding only the written bytes materializes a compact string, preserving\n // the low post-GC memory profile that the old TextEncoder/TextDecoder path had.\n return stringDetachDecoder.decode(stringDetachBuffer.subarray(0, written));\n}\n", "const filenameDecoder = new TextDecoder('utf-8', { ignoreBOM: true });\nconst NAMED_ESCAPES: Record<string, string | undefined> = {\n '\"': '\"',\n '\\\\': '\\\\',\n a: '\\x07',\n b: '\\b',\n t: '\\t',\n n: '\\n',\n v: '\\v',\n f: '\\f',\n r: '\\r',\n};\n\n// Reads one quoted Git/jsdiff filename and reports where the token ends.\n// Adjacent octal escapes encode UTF-8 bytes, so they must be decoded together.\nexport function parseQuotedDiffFileName(\n input: string\n): { fileName: string; rawLength: number } | undefined {\n if (input[0] !== '\"') {\n return undefined;\n }\n\n let fileName = '';\n let index = 1;\n while (index < input.length) {\n const char = input[index];\n if (char === '\"') {\n return { fileName, rawLength: index + 1 };\n }\n if (char !== '\\\\') {\n fileName += char;\n index++;\n continue;\n }\n\n const escaped = NAMED_ESCAPES[input[index + 1]];\n if (escaped != null) {\n fileName += escaped;\n index += 2;\n continue;\n }\n\n const bytes: number[] = [];\n do {\n const byte = readOctalByte(input, index + 1);\n if (byte == null) {\n return undefined;\n }\n bytes.push(byte);\n index += 4;\n } while (\n input[index] === '\\\\' &&\n input[index + 1] >= '0' &&\n input[index + 1] <= '7'\n );\n fileName += filenameDecoder.decode(new Uint8Array(bytes));\n }\n return undefined;\n}\n\n// Requires three octal digits in the byte range so malformed escapes cannot\n// be truncated or wrapped when copied into a Uint8Array.\nfunction readOctalByte(input: string, index: number): number | undefined {\n const first = input.charCodeAt(index) - 48;\n const second = input.charCodeAt(index + 1) - 48;\n const third = input.charCodeAt(index + 2) - 48;\n if (\n first >= 0 &&\n first <= 3 &&\n second >= 0 &&\n second <= 7 &&\n third >= 0 &&\n third <= 7\n ) {\n return first * 64 + second * 8 + third;\n }\n return undefined;\n}\n", "import type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n} from '../types';\n\n// The diff library emits one change block per replaced run, ordering every\n// deleted line before every added line. Renderers pair a block's lines\n// positionally (deletion[i] across from addition[i] in split view), so a\n// block like { deletions: 1, additions: 2 } pairs the deleted line with\n// whichever addition happens to come first — even when a later addition is\n// the edited version of it (e.g. pressing Enter above a changed line pushes\n// a blank line in front of it). These helpers re-split such blocks so the\n// most similar lines pair up and the surplus renders as pure insert/delete\n// rows at the block's edges.\n\n// Skip realignment when a block would need more than this many line\n// comparisons; pathological blocks keep the library's positional pairing.\nconst MAX_ALIGNMENT_COMPARISONS = 4096;\n\n// A shifted pairing must beat the positional one by this much per paired\n// line before the block is re-split. Near-ties (e.g. lines that merely share\n// an import-statement shape) keep the library's canonical order; the\n// realignment is meant for decisive wins like a blank or unrelated inserted\n// line displacing an edited one, where the gap approaches 1.\nconst MIN_IMPROVEMENT_PER_PAIR = 0.5;\n\n/**\n * Re-split count-mismatched change blocks in every hunk so paired lines are\n * chosen by content similarity instead of position. Mutates `hunks` in place\n * without moving changes across context lines; rendered row counts are\n * unchanged (a split block covers the same split/unified rows as the original).\n */\nexport function realignChangeContentBySimilarity(\n diff: Pick<FileDiffMetadata, 'hunks' | 'additionLines' | 'deletionLines'>\n): void {\n for (const hunk of diff.hunks) {\n for (let index = 0; index < hunk.hunkContent.length; index++) {\n const content = hunk.hunkContent[index];\n if (content.type !== 'change') {\n continue;\n }\n const replacement = realignChangeBlock(diff, content);\n if (replacement != null) {\n hunk.hunkContent.splice(index, 1, ...replacement);\n index += replacement.length - 1;\n }\n }\n }\n}\n\n/**\n * During editing, slide pure insert/delete blocks made entirely of blank lines\n * to the top of the blank run they sit in. Adding or removing a blank line next to\n * existing blanks is ambiguous, and the diff library reports the change at\n * the run's bottom — so pressing Enter at the end of a line marks a blank\n * *below* the caret as inserted while the caret's own new line renders as\n * context. Sliding up anchors the change to the content above it (the caret\n * line after an Enter) instead.\n *\n * `resolveSlide` receives each block that qualifies along with the full\n * distance to the run's top and returns how far to actually move it; 0 keeps\n * the parsed position. Without it, every qualifying block slides to the top.\n *\n * The slide only applies when the block comes to rest directly beneath\n * remaining in-hunk content. A slide that would consume the\n * hunk's entire leading context was stopped by the hunk's edge — a context\n * window cut, not the top of the blank run — and that landing spot is\n * arbitrary, so the block keeps the library's bottom-of-run anchor (which\n * sits against the content below the run). Non-blank blocks never slide, so\n * code that merely ends like its neighbor (an added function before an\n * identical `}`) keeps the library's canonical position.\n */\nexport function slideBlankBoundaryBlocksUp(\n hunk: Hunk,\n diff: Pick<FileDiffMetadata, 'additionLines' | 'deletionLines'>,\n resolveSlide?: (block: ChangeContent, maxSlide: number) => number\n): void {\n const { hunkContent } = hunk;\n for (let index = 1; index < hunkContent.length; index++) {\n const block = hunkContent[index];\n const previous = hunkContent[index - 1];\n if (\n block.type !== 'change' ||\n (block.additions > 0 && block.deletions > 0) ||\n previous.type !== 'context'\n ) {\n continue;\n }\n const isInsert = block.additions > 0;\n const lines = isInsert ? diff.additionLines : diff.deletionLines;\n const blockStart = isInsert\n ? block.additionLineIndex\n : block.deletionLineIndex;\n const blockLength = isInsert ? block.additions : block.deletions;\n\n // Sliding through identical lines is only well-defined when the block is\n // a uniform run; require every block line to equal the first one, and\n // that line to be blank.\n const unit = lines[blockStart] ?? '';\n if (unit.trim() !== '') {\n continue;\n }\n let uniform = true;\n for (let offset = 1; offset < blockLength; offset++) {\n if (lines[blockStart + offset] !== unit) {\n uniform = false;\n break;\n }\n }\n if (!uniform) {\n continue;\n }\n\n // Slide distance: how many trailing context lines match the block's line\n // exactly (context lines are identical on both sides by definition).\n let slide = 0;\n while (\n slide < previous.lines &&\n diff.additionLines[\n previous.additionLineIndex + previous.lines - 1 - slide\n ] === unit\n ) {\n slide++;\n }\n if (slide === 0) {\n continue;\n }\n // Stopped by the hunk's leading edge rather than by content: the blank\n // run extends to (and possibly beyond) the hunk's top, so there is no\n // in-hunk line to anchor beneath. Keep the bottom-of-run position.\n if (index === 1 && slide === previous.lines) {\n continue;\n }\n if (resolveSlide != null) {\n slide = resolveSlide(block, slide);\n if (slide === 0) {\n continue;\n }\n }\n\n block.additionLineIndex -= slide;\n block.deletionLineIndex -= slide;\n const blockAdditionEnd = block.additionLineIndex + block.additions;\n const blockDeletionEnd = block.deletionLineIndex + block.deletions;\n const next = hunkContent[index + 1];\n if (next?.type === 'context') {\n next.lines += slide;\n next.additionLineIndex = blockAdditionEnd;\n next.deletionLineIndex = blockDeletionEnd;\n } else {\n hunkContent.splice(index + 1, 0, {\n type: 'context',\n lines: slide,\n additionLineIndex: blockAdditionEnd,\n deletionLineIndex: blockDeletionEnd,\n });\n }\n previous.lines -= slide;\n if (previous.lines === 0) {\n hunkContent.splice(index - 1, 1);\n index--;\n }\n }\n}\n\n// Returns the split blocks for one change block, or null when the block is\n// balanced, too large to scan, or already best paired positionally.\nfunction realignChangeBlock(\n diff: Pick<FileDiffMetadata, 'additionLines' | 'deletionLines'>,\n content: ChangeContent\n): (ContextContent | ChangeContent)[] | null {\n const { deletions, additions, deletionLineIndex, additionLineIndex } =\n content;\n const pairCount = Math.min(deletions, additions);\n const surplus = Math.abs(additions - deletions);\n if (\n pairCount === 0 ||\n surplus === 0 ||\n pairCount * (surplus + 1) > MAX_ALIGNMENT_COMPARISONS\n ) {\n return null;\n }\n\n // Whitespace (indentation, formatter churn, trailing spaces, the line\n // break itself) is noise for deciding which lines pair — the rendered diff\n // still shows every whitespace change on the paired row. Strip it once per\n // line here rather than per comparison.\n const strippedDeletions: string[] = [];\n for (let line = 0; line < deletions; line++) {\n strippedDeletions.push(\n stripWhitespace(diff.deletionLines[deletionLineIndex + line] ?? '')\n );\n }\n const strippedAdditions: string[] = [];\n for (let line = 0; line < additions; line++) {\n strippedAdditions.push(\n stripWhitespace(diff.additionLines[additionLineIndex + line] ?? '')\n );\n }\n\n // Score every offset of the shorter side along the longer side and keep\n // the best one only when it decisively beats the positional pairing.\n const additionsAreLonger = additions > deletions;\n let bestOffset = 0;\n let bestScore = -1;\n for (let offset = 0; offset <= surplus; offset++) {\n let score = 0;\n for (let pair = 0; pair < pairCount; pair++) {\n score += lineSimilarity(\n strippedDeletions[pair + (additionsAreLonger ? 0 : offset)],\n strippedAdditions[pair + (additionsAreLonger ? offset : 0)]\n );\n }\n if (offset === 0) {\n bestScore = score + pairCount * MIN_IMPROVEMENT_PER_PAIR;\n } else if (score > bestScore) {\n bestScore = score;\n bestOffset = offset;\n }\n }\n if (bestOffset === 0) {\n return null;\n }\n\n const blocks: ChangeContent[] = [];\n const pushBlock = (\n blockDeletions: number,\n blockAdditions: number,\n blockDeletionIndex: number,\n blockAdditionIndex: number\n ) => {\n if (blockDeletions > 0 || blockAdditions > 0) {\n blocks.push({\n type: 'change',\n deletions: blockDeletions,\n additions: blockAdditions,\n deletionLineIndex: blockDeletionIndex,\n additionLineIndex: blockAdditionIndex,\n });\n }\n };\n if (additionsAreLonger) {\n pushBlock(0, bestOffset, deletionLineIndex, additionLineIndex);\n pushBlock(\n pairCount,\n pairCount,\n deletionLineIndex,\n additionLineIndex + bestOffset\n );\n pushBlock(\n 0,\n additions - pairCount - bestOffset,\n deletionLineIndex + pairCount,\n additionLineIndex + bestOffset + pairCount\n );\n } else {\n pushBlock(bestOffset, 0, deletionLineIndex, additionLineIndex);\n pushBlock(\n pairCount,\n pairCount,\n deletionLineIndex + bestOffset,\n additionLineIndex\n );\n pushBlock(\n deletions - pairCount - bestOffset,\n 0,\n deletionLineIndex + bestOffset + pairCount,\n additionLineIndex + pairCount\n );\n }\n return blocks;\n}\n\nconst WHITESPACE = /\\s+/g;\n\nfunction stripWhitespace(line: string): string {\n return line.replace(WHITESPACE, '');\n}\n\n// Cheap 0..1 similarity over whitespace-stripped lines: shared prefix plus\n// shared suffix over the longer length. Exact for lines that differ only in\n// whitespace, 0 for a blank against content — enough to steer pairing\n// without a real edit-distance pass.\nfunction lineSimilarity(a: string, b: string): number {\n if (a === b) {\n return 1;\n }\n const maxLength = Math.max(a.length, b.length);\n const minLength = Math.min(a.length, b.length);\n if (minLength === 0) {\n return 0;\n }\n let prefix = 0;\n while (prefix < minLength && a[prefix] === b[prefix]) {\n prefix++;\n }\n let suffix = 0;\n while (\n suffix < minLength - prefix &&\n a[a.length - 1 - suffix] === b[b.length - 1 - suffix]\n ) {\n suffix++;\n }\n return (prefix + suffix) / maxLength;\n}\n", "import {\n COMMIT_METADATA_SPLIT,\n FILENAME_HEADER_REGEX,\n GIT_DIFF_FILE_BREAK_REGEX,\n INDEX_LINE_METADATA,\n} from '../constants';\nimport type {\n ChangeContent,\n ContextContent,\n FileContents,\n FileDiffMetadata,\n Hunk,\n HunkLineType,\n ParsedPatch,\n} from '../types';\nimport { cleanLastNewline } from './cleanLastNewline';\nimport { composeCacheKey } from './composeCacheKey';\nimport { detachString, releaseStringDetachBuffer } from './detachString';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\nimport { parseQuotedDiffFileName } from './parseQuotedDiffFileName';\nimport { realignChangeContentBySimilarity } from './realignChangeContent';\n\n// Keep quotes and transport prefixes until decoding, while allowing spaces in\n// unquoted paths and escaped quotes inside quoted paths.\nconst GIT_DIFF_HEADER_FILENAMES =\n /^diff --git (\"a\\/(?:[^\"\\\\]|\\\\.)*\"|a\\/.+?) (\"b\\/(?:[^\"\\\\]|\\\\.)*\"|b\\/.+?)$/;\n\ninterface ParsedHunkHeader {\n additionCount: number;\n additionStart: number;\n deletionCount: number;\n deletionStart: number;\n hunkContext?: string;\n}\n\nexport function processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError?: boolean\n): ParsedPatch {\n try {\n return _processPatch(data, cacheKeyPrefix, throwOnError);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false,\n patchIndex?: number\n): ParsedPatch {\n const isGitDiff = isGitDiffPatch(data);\n const rawFiles = isGitDiff\n ? splitGitDiffFiles(data)\n : splitUnifiedDiffFiles(data);\n let patchMetadata: string | undefined;\n const files: FileDiffMetadata[] = [];\n for (const fileOrPatchMetadata of rawFiles) {\n if (isGitDiff && !GIT_DIFF_FILE_BREAK_REGEX.test(fileOrPatchMetadata)) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n // If we get in here, it's most likely the introductory metadata from the\n // patch, or something is fucked with the diff format\n continue;\n } else if (\n !isGitDiff &&\n !startsWithUnifiedDiffFileHeader(fileOrPatchMetadata)\n ) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n continue;\n }\n const currentFile = _processFile(fileOrPatchMetadata, {\n cacheKey:\n cacheKeyPrefix != null\n ? patchIndex == null\n ? composeCacheKey(\n 'patch-file',\n cacheKeyPrefix,\n String(files.length)\n )\n : composeCacheKey(\n 'patch-file',\n cacheKeyPrefix,\n String(patchIndex),\n String(files.length)\n )\n : undefined,\n isGitDiff,\n throwOnError,\n });\n if (currentFile != null) {\n files.push(currentFile);\n }\n }\n return { patchMetadata, files };\n}\n\ninterface ProcessFileOptions {\n cacheKey?: string;\n isGitDiff?: boolean;\n oldFile?: FileContents;\n newFile?: FileContents;\n throwOnError?: boolean;\n}\n\nexport function processFile(\n fileDiffString: string,\n options?: ProcessFileOptions\n): FileDiffMetadata | undefined {\n try {\n return _processFile(fileDiffString, options);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processFile(\n fileDiffString: string,\n {\n cacheKey,\n isGitDiff = GIT_DIFF_FILE_BREAK_REGEX.test(fileDiffString),\n oldFile,\n newFile,\n throwOnError = false,\n }: ProcessFileOptions = {}\n): FileDiffMetadata | undefined {\n let lastHunkEnd = 0;\n const hunks = splitAtLinePrefix(fileDiffString, '@@ ');\n let currentFile: FileDiffMetadata | undefined;\n const isPartial = oldFile == null || newFile == null;\n let deletionLineIndex = 0;\n let additionLineIndex = 0;\n for (const hunk of hunks) {\n const lines = splitWithNewlines(hunk);\n const firstLine = lines[0];\n if (firstLine == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk');\n } else {\n console.error('parsePatchContent: invalid hunk', hunk);\n }\n continue;\n }\n const fileHeader = parseHunkHeader(firstLine);\n let additionLines = 0;\n let deletionLines = 0;\n // Setup currentFile, this should be the first iteration of our hunks, and\n // technically not a hunk\n if (fileHeader == null || currentFile == null) {\n if (currentFile != null) {\n if (throwOnError) {\n throw Error('parsePatchContent: Invalid hunk');\n } else {\n console.error('parsePatchContent: Invalid hunk', hunk);\n }\n continue;\n }\n currentFile = {\n name: '',\n type: 'change',\n hunks: [],\n splitLineCount: 0,\n unifiedLineCount: 0,\n isPartial,\n additionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(newFile.contents)\n : [],\n deletionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(oldFile.contents)\n : [],\n additionCharacterCount:\n !isPartial && oldFile != null && newFile != null\n ? newFile.contents.length\n : 0,\n deletionCharacterCount:\n !isPartial && oldFile != null && newFile != null\n ? oldFile.contents.length\n : 0,\n cacheKey: maybeDetachOptionalString(cacheKey),\n };\n // If either file is technically empty, then we should empty the\n // arrays respectively\n if (currentFile.additionLines.length === 1 && newFile?.contents === '') {\n currentFile.additionLines.length = 0;\n }\n if (currentFile.deletionLines.length === 1 && oldFile?.contents === '') {\n currentFile.deletionLines.length = 0;\n }\n\n for (const line of lines) {\n if (line.startsWith('diff --git')) {\n const filenameMatch = line.trim().match(GIT_DIFF_HEADER_FILENAMES);\n if (filenameMatch == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid git diff header');\n } else {\n console.error('parsePatchContent: invalid git diff header', line);\n }\n continue;\n }\n const prevName = decodeDiffFileName(filenameMatch[1], true);\n const name = decodeDiffFileName(filenameMatch[2], true);\n currentFile.name = detachString(name);\n if (prevName !== name) {\n currentFile.prevName = detachString(prevName);\n }\n continue;\n }\n\n const filenameMatch =\n line.startsWith('---') || line.startsWith('+++')\n ? line.match(FILENAME_HEADER_REGEX)\n : null;\n if (filenameMatch != null) {\n const [, type, rawFileName] = filenameMatch;\n const fileName = decodeDiffFileName(rawFileName, isGitDiff);\n if (type === '---' && fileName !== '/dev/null') {\n const detachedFileName = detachString(fileName);\n currentFile.prevName = detachedFileName;\n currentFile.name = detachedFileName;\n } else if (type === '+++' && fileName !== '/dev/null') {\n currentFile.name = detachString(fileName);\n }\n }\n // Git diffs have a bunch of additional metadata we can pull from\n else if (isGitDiff) {\n if (line.startsWith('new mode ')) {\n currentFile.mode = detachString(\n line.slice('new mode'.length).trim()\n );\n }\n if (line.startsWith('old mode ')) {\n currentFile.prevMode = detachString(\n line.slice('old mode'.length).trim()\n );\n }\n if (line.startsWith('new file mode')) {\n currentFile.type = 'new';\n currentFile.mode = detachString(\n line.slice('new file mode'.length).trim()\n );\n }\n if (line.startsWith('deleted file mode')) {\n currentFile.type = 'deleted';\n currentFile.mode = detachString(\n line.slice('deleted file mode'.length).trim()\n );\n }\n if (line.startsWith('similarity index')) {\n if (line.startsWith('similarity index 100%')) {\n currentFile.type = 'rename-pure';\n } else {\n currentFile.type = 'rename-changed';\n }\n }\n if (line.startsWith('index ')) {\n const [, prevObjectId, newObjectId, mode] =\n line.trim().match(INDEX_LINE_METADATA) ?? [];\n if (prevObjectId != null) {\n currentFile.prevObjectId = detachString(prevObjectId);\n }\n if (newObjectId != null) {\n currentFile.newObjectId = detachString(newObjectId);\n }\n if (mode != null) {\n currentFile.mode = detachString(mode);\n }\n }\n // Pure renames and copies have no --- / +++ headers. These paths\n // are already relative to the repository, without transport prefixes.\n if (\n line.startsWith('rename from ') ||\n line.startsWith('copy from ')\n ) {\n currentFile.prevName = detachString(\n decodeDiffFileName(\n line.slice(\n line.startsWith('rename')\n ? 'rename from '.length\n : 'copy from '.length\n )\n )\n );\n }\n if (line.startsWith('rename to ') || line.startsWith('copy to ')) {\n currentFile.name = detachString(\n decodeDiffFileName(\n line.slice(\n line.startsWith('rename')\n ? 'rename to '.length\n : 'copy to '.length\n )\n )\n );\n }\n }\n }\n continue;\n }\n\n // Otherwise, time to start parsing out the hunk\n let currentContent: ContextContent | ChangeContent | undefined;\n let lastLineType: 'context' | 'addition' | 'deletion' | undefined;\n\n // Strip trailing bare newlines (format-patch separators between commits)\n // if needed\n while (\n lines.length > 0 &&\n (lines[lines.length - 1] === '\\n' ||\n lines[lines.length - 1] === '\\r' ||\n lines[lines.length - 1] === '\\r\\n' ||\n lines[lines.length - 1] === '')\n ) {\n lines.pop();\n }\n\n const { additionStart, deletionStart } = fileHeader;\n deletionLineIndex = isPartial ? deletionLineIndex : deletionStart - 1;\n additionLineIndex = isPartial ? additionLineIndex : additionStart - 1;\n\n const hunkData: Hunk = {\n collapsedBefore: 0,\n\n splitLineCount: 0,\n splitLineStart: 0,\n\n unifiedLineCount: 0,\n unifiedLineStart: 0,\n\n additionCount: fileHeader.additionCount,\n additionStart,\n additionLines,\n\n deletionCount: fileHeader.deletionCount,\n deletionStart,\n deletionLines,\n\n deletionLineIndex,\n additionLineIndex,\n\n hunkContent: [],\n hunkContext: maybeDetachOptionalString(fileHeader.hunkContext),\n hunkSpecs: detachString(firstLine),\n\n noEOFCRAdditions: false,\n noEOFCRDeletions: false,\n };\n\n // Now we process each line of the hunk\n let parsedAdditionLines = 0;\n let parsedDeletionLines = 0;\n for (let lineIndex = 1; lineIndex < lines.length; lineIndex++) {\n const rawLine = lines[lineIndex];\n if (\n parsedAdditionLines >= hunkData.additionCount &&\n parsedDeletionLines >= hunkData.deletionCount &&\n !rawLine.startsWith('\\\\')\n ) {\n const isUnexpectedBodyLine =\n isHunkBodyLine(rawLine) && !isFormatPatchVersionSeparator(rawLine);\n if (!isUnexpectedBodyLine) {\n break;\n }\n if (throwOnError) {\n throw Error('parsePatchContent: hunk has more lines than expected');\n }\n }\n\n const firstChar = rawLine[0];\n // If we can't properly process the line, well, lets just try to salvage\n // things and continue... It's possible an AI generated diff might have\n // some stray blank lines or something in there\n if (\n firstChar !== '+' &&\n firstChar !== '-' &&\n firstChar !== ' ' &&\n firstChar !== '\\\\'\n ) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk line');\n }\n console.error(\n `parseLineType: Invalid firstChar: \"${firstChar}\", full line: \"${rawLine}\"`\n );\n console.error('processFile: invalid rawLine:', rawLine);\n continue;\n }\n\n const type = parseRawLineType(firstChar);\n if (type === 'addition') {\n if (throwOnError && parsedAdditionLines >= hunkData.additionCount) {\n throw Error('parsePatchContent: hunk has too many addition lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n parsedAdditionLines++;\n if (isPartial) {\n currentFile.additionLines.push(line);\n currentFile.additionCharacterCount += line.length;\n }\n currentContent.additions++;\n additionLines++;\n lastLineType = 'addition';\n } else if (type === 'deletion') {\n if (throwOnError && parsedDeletionLines >= hunkData.deletionCount) {\n throw Error('parsePatchContent: hunk has too many deletion lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n deletionLineIndex++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n currentFile.deletionCharacterCount += line.length;\n }\n currentContent.deletions++;\n deletionLines++;\n lastLineType = 'deletion';\n } else if (type === 'context') {\n if (\n throwOnError &&\n (parsedDeletionLines >= hunkData.deletionCount ||\n parsedAdditionLines >= hunkData.additionCount)\n ) {\n throw Error('parsePatchContent: hunk has too many context lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'context') {\n currentContent = createContentGroup(\n 'context',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n deletionLineIndex++;\n parsedAdditionLines++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n currentFile.additionLines.push(line);\n currentFile.deletionCharacterCount += line.length;\n currentFile.additionCharacterCount += line.length;\n }\n currentContent.lines++;\n lastLineType = 'context';\n } else if (type === 'metadata' && currentContent != null) {\n if (currentContent.type === 'context') {\n hunkData.noEOFCRAdditions = true;\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'deletion') {\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'addition') {\n hunkData.noEOFCRAdditions = true;\n }\n // If we're dealing with partial content from a diff, we need to strip\n // newlines manually from the content\n if (\n isPartial &&\n (lastLineType === 'addition' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.additionLines.length - 1;\n if (lastIndex >= 0) {\n const line = currentFile.additionLines[lastIndex];\n const cleanedLine = cleanLastNewline(line);\n currentFile.additionLines[lastIndex] = cleanedLine;\n currentFile.additionCharacterCount +=\n cleanedLine.length - line.length;\n }\n }\n if (\n isPartial &&\n (lastLineType === 'deletion' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.deletionLines.length - 1;\n if (lastIndex >= 0) {\n const line = currentFile.deletionLines[lastIndex];\n const cleanedLine = cleanLastNewline(line);\n currentFile.deletionLines[lastIndex] = cleanedLine;\n currentFile.deletionCharacterCount +=\n cleanedLine.length - line.length;\n }\n }\n }\n }\n\n if (\n parsedAdditionLines !== hunkData.additionCount ||\n parsedDeletionLines !== hunkData.deletionCount\n ) {\n if (throwOnError) {\n throw Error('parsePatchContent: hunk line count mismatch');\n }\n console.error(\n `parsePatchContent: hunk line count mismatch: \"${firstLine.trimEnd()}\", declared old/new ${hunkData.deletionCount}/${hunkData.additionCount}, parsed old/new ${parsedDeletionLines}/${parsedAdditionLines}`\n );\n // Re-encode each original boundary using the repaired count. Zero-count\n // ranges use the boundary itself as their start; positive ranges use +1.\n const repairedAdditionStart =\n getHunkSideStartBoundary(\n hunkData.additionStart,\n hunkData.additionCount\n ) + (parsedAdditionLines === 0 ? 0 : 1);\n const repairedDeletionStart =\n getHunkSideStartBoundary(\n hunkData.deletionStart,\n hunkData.deletionCount\n ) + (parsedDeletionLines === 0 ? 0 : 1);\n\n // Hydrated hunks index into full-file line arrays, so their indexes must\n // move with repaired starts. Partial hunks index patch-built arrays.\n if (!isPartial) {\n const additionStartDelta =\n repairedAdditionStart - hunkData.additionStart;\n const deletionStartDelta =\n repairedDeletionStart - hunkData.deletionStart;\n hunkData.additionLineIndex += additionStartDelta;\n hunkData.deletionLineIndex += deletionStartDelta;\n for (const content of hunkData.hunkContent) {\n content.additionLineIndex += additionStartDelta;\n content.deletionLineIndex += deletionStartDelta;\n }\n }\n\n hunkData.additionStart = repairedAdditionStart;\n hunkData.deletionStart = repairedDeletionStart;\n hunkData.additionCount = parsedAdditionLines;\n hunkData.deletionCount = parsedDeletionLines;\n }\n\n hunkData.additionLines = additionLines;\n hunkData.deletionLines = deletionLines;\n\n hunkData.collapsedBefore = Math.max(\n getHunkSideStartBoundary(hunkData.additionStart, hunkData.additionCount) -\n lastHunkEnd,\n 0\n );\n currentFile.hunks.push(hunkData);\n lastHunkEnd = getHunkSideEndBoundary(\n hunkData.additionStart,\n hunkData.additionCount\n );\n for (const content of hunkData.hunkContent) {\n if (content.type === 'context') {\n hunkData.splitLineCount += content.lines;\n hunkData.unifiedLineCount += content.lines;\n } else {\n hunkData.splitLineCount += Math.max(\n content.additions,\n content.deletions\n );\n hunkData.unifiedLineCount += content.deletions + content.additions;\n }\n }\n hunkData.splitLineStart =\n currentFile.splitLineCount + hunkData.collapsedBefore;\n hunkData.unifiedLineStart =\n currentFile.unifiedLineCount + hunkData.collapsedBefore;\n\n currentFile.splitLineCount +=\n hunkData.collapsedBefore + hunkData.splitLineCount;\n currentFile.unifiedLineCount +=\n hunkData.collapsedBefore + hunkData.unifiedLineCount;\n }\n if (currentFile == null) {\n return undefined;\n }\n if (\n throwOnError &&\n isPartial &&\n !isGitDiff &&\n currentFile.hunks.length === 0\n ) {\n throw Error('parsePatchContent: unified file has no hunks');\n }\n\n // Account for collapsed lines after the final hunk and increment the\n // split/unified counts properly\n if (\n currentFile.hunks.length > 0 &&\n !isPartial &&\n currentFile.additionLines.length > 0 &&\n currentFile.deletionLines.length > 0\n ) {\n const lastHunk = currentFile.hunks[currentFile.hunks.length - 1];\n const lastHunkEnd = getHunkSideEndBoundary(\n lastHunk.additionStart,\n lastHunk.additionCount\n );\n const totalFileLines = currentFile.additionLines.length;\n const collapsedAfter = Math.max(totalFileLines - lastHunkEnd, 0);\n currentFile.splitLineCount += collapsedAfter;\n currentFile.unifiedLineCount += collapsedAfter;\n }\n\n // If this isn't a git diff style patch, then we'll need to sus out some\n // additional metadata manually\n if (!isGitDiff) {\n if (\n currentFile.prevName != null &&\n currentFile.name !== currentFile.prevName\n ) {\n if (currentFile.hunks.length > 0) {\n currentFile.type = 'rename-changed';\n } else {\n currentFile.type = 'rename-pure';\n }\n }\n // Sort of a hack for detecting deleted/added files...\n else if (\n (oldFile == null || oldFile.contents === '') &&\n newFile != null &&\n newFile.contents !== ''\n ) {\n currentFile.type = 'new';\n } else if (\n oldFile != null &&\n oldFile.contents !== '' &&\n (newFile == null || newFile.contents === '')\n ) {\n currentFile.type = 'deleted';\n }\n }\n if (\n currentFile.type !== 'rename-pure' &&\n currentFile.type !== 'rename-changed'\n ) {\n currentFile.prevName = undefined;\n }\n // Pair change-block lines by similarity instead of the patch's positional\n // ordering. Partial diffs work too: their hunk line indexes point into the\n // patch-built line arrays, which hold every line a block references.\n realignChangeContentBySimilarity(currentFile);\n return currentFile;\n}\n\n/**\n * Parses a patch file string into an array of parsed patches.\n *\n * @param data - The raw patch file content (supports multi-commit patches)\n * @param cacheKeyPrefix - Optional prefix for collision-safe cache keys derived\n * from the prefix, patch index, and file index. This enables caching of\n * rendered diff results in the worker pool.\n * @param throwOnError - When true, invalid data throws. When false, invalid data\n * is reported with `console.error` and the parser attempts to recover when\n * possible. Recovery is best-effort and does not guarantee valid output.\n */\nexport function parsePatchFiles(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false\n): ParsedPatch[] {\n // NOTE(amadeus): This function is pretty forgiving in that it can accept a\n // patch file that includes commit metdata, multiple commits, or not\n const patches: ParsedPatch[] = [];\n const rawPatches = hasCommitMetadataBoundary(data)\n ? data.split(COMMIT_METADATA_SPLIT)\n : [data];\n for (const patch of rawPatches) {\n try {\n patches.push(\n _processPatch(\n patch,\n cacheKeyPrefix,\n throwOnError,\n cacheKeyPrefix != null ? patches.length : undefined\n )\n );\n } catch (error) {\n if (throwOnError) {\n throw error;\n } else {\n console.error(error);\n }\n } finally {\n releaseStringDetachBuffer();\n }\n }\n return patches;\n}\n\n// Decode only quoted tokens, preserving whitespace inside them. Git's a/ and\n// b/ prefixes are part of the quoted token and must be removed after decoding.\nfunction decodeDiffFileName(value: string, stripGitPrefix = false): string {\n const rawName = value.trim();\n const name = rawName.startsWith('\"')\n ? (parseQuotedDiffFileName(rawName)?.fileName ?? rawName)\n : rawName;\n return stripGitPrefix && (name.startsWith('a/') || name.startsWith('b/'))\n ? name.slice(2)\n : name;\n}\n\nfunction hasCommitMetadataBoundary(data: string): boolean {\n return data.startsWith('From ') || data.includes('\\nFrom ');\n}\n\nfunction splitFileContents(contents: string): string[] {\n const lines = splitWithNewlines(contents);\n for (let index = 0; index < lines.length; index++) {\n lines[index] = detachString(lines[index]);\n }\n return lines;\n}\n\nfunction splitWithNewlines(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const lines: string[] = [];\n let startIndex = 0;\n for (;;) {\n const newlineIndex = contents.indexOf('\\n', startIndex);\n if (newlineIndex === -1) {\n break;\n }\n\n lines.push(contents.slice(startIndex, newlineIndex + 1));\n startIndex = newlineIndex + 1;\n }\n\n if (startIndex < contents.length) {\n lines.push(contents.slice(startIndex));\n }\n return lines;\n}\n\nfunction splitGitDiffFiles(contents: string): string[] {\n return splitAtLinePrefix(contents, 'diff --git');\n}\n\nfunction splitUnifiedDiffFiles(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const parts: string[] = [];\n let partStartIndex = 0;\n let lineStartIndex = 0;\n let remainingDeletionLines = 0;\n let remainingAdditionLines = 0;\n let hasOpenedUnifiedFile = false;\n\n while (lineStartIndex < contents.length) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n if (remainingDeletionLines <= 0 && remainingAdditionLines <= 0) {\n if (isUnifiedDiffFileHeaderAt(contents, lineStartIndex)) {\n if (lineStartIndex > partStartIndex) {\n parts.push(contents.slice(partStartIndex, lineStartIndex));\n }\n partStartIndex = lineStartIndex;\n hasOpenedUnifiedFile = true;\n lineStartIndex = getNextLineStartIndex(contents, nextLineStartIndex);\n continue;\n }\n\n if (hasOpenedUnifiedFile && contents.startsWith('@@ -', lineStartIndex)) {\n const fileHeader = parseHunkHeader(\n contents.slice(lineStartIndex, nextLineStartIndex)\n );\n if (fileHeader != null) {\n remainingDeletionLines = fileHeader.deletionCount;\n remainingAdditionLines = fileHeader.additionCount;\n }\n }\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n const firstChar = contents[lineStartIndex];\n if (firstChar === '\\\\') {\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n if (firstChar === ' ') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n } else if (firstChar === '-') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n } else if (firstChar === '+') {\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n }\n lineStartIndex = nextLineStartIndex;\n }\n\n parts.push(contents.slice(partStartIndex));\n return parts;\n}\n\nfunction startsWithUnifiedDiffFileHeader(contents: string): boolean {\n return isUnifiedDiffFileHeaderAt(contents, 0);\n}\n\nfunction isUnifiedDiffFileHeaderAt(contents: string, lineStartIndex: number) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n return (\n isUnifiedDiffHeaderLineAt(contents, lineStartIndex, '---') &&\n isUnifiedDiffHeaderLineAt(contents, nextLineStartIndex, '+++')\n );\n}\n\nfunction isUnifiedDiffHeaderLineAt(\n contents: string,\n lineStartIndex: number,\n prefix: '---' | '+++'\n): boolean {\n if (!contents.startsWith(prefix, lineStartIndex)) {\n return false;\n }\n\n const separator = contents[lineStartIndex + prefix.length];\n if (separator !== ' ' && separator !== '\\t') {\n return false;\n }\n\n for (\n let index = lineStartIndex + prefix.length + 1;\n index < contents.length;\n index++\n ) {\n const char = contents[index];\n if (char === '\\n' || char === '\\r') {\n break;\n }\n if (char !== ' ' && char !== '\\t') {\n return true;\n }\n }\n return false;\n}\n\nfunction getNextLineStartIndex(\n contents: string,\n lineStartIndex: number\n): number {\n const newlineIndex = contents.indexOf('\\n', lineStartIndex);\n return newlineIndex === -1 ? contents.length : newlineIndex + 1;\n}\n\nfunction isHunkBodyLine(line: string): boolean {\n const firstChar = line[0];\n return firstChar === '+' || firstChar === '-' || firstChar === ' ';\n}\n\nfunction isFormatPatchVersionSeparator(line: string): boolean {\n if (!line.startsWith('--')) {\n return false;\n }\n\n for (let index = 2; index < line.length; index++) {\n const char = line[index];\n if (char !== ' ' && char !== '\\t' && char !== '\\n' && char !== '\\r') {\n return false;\n }\n }\n return true;\n}\n\nfunction parseHunkHeader(line: string): ParsedHunkHeader | undefined {\n if (!line.startsWith('@@ -')) {\n return undefined;\n }\n\n let index = 4;\n const deletionStartResult = readPositiveInteger(line, index);\n if (deletionStartResult == null) {\n return undefined;\n }\n const deletionStart = deletionStartResult.value;\n index = deletionStartResult.endIndex;\n\n let deletionCount = 1;\n if (line[index] === ',') {\n const deletionCountResult = readPositiveInteger(line, index + 1);\n if (deletionCountResult == null) {\n return undefined;\n }\n deletionCount = deletionCountResult.value;\n index = deletionCountResult.endIndex;\n }\n\n if (line[index] !== ' ' || line[index + 1] !== '+') {\n return undefined;\n }\n index += 2;\n\n const additionStartResult = readPositiveInteger(line, index);\n if (additionStartResult == null) {\n return undefined;\n }\n const additionStart = additionStartResult.value;\n index = additionStartResult.endIndex;\n\n let additionCount = 1;\n if (line[index] === ',') {\n const additionCountResult = readPositiveInteger(line, index + 1);\n if (additionCountResult == null) {\n return undefined;\n }\n additionCount = additionCountResult.value;\n index = additionCountResult.endIndex;\n }\n\n if (\n line[index] !== ' ' ||\n line[index + 1] !== '@' ||\n line[index + 2] !== '@'\n ) {\n return undefined;\n }\n\n let hunkContext: string | undefined;\n const contextStartIndex = index + 3;\n if (line[contextStartIndex] === ' ') {\n hunkContext = trimLineEnd(line.slice(contextStartIndex + 1));\n }\n\n return {\n additionCount,\n additionStart,\n deletionCount,\n deletionStart,\n hunkContext,\n };\n}\n\nfunction readPositiveInteger(\n value: string,\n startIndex: number\n): { value: number; endIndex: number } | undefined {\n let index = startIndex;\n let parsedValue = 0;\n for (; index < value.length; index++) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) {\n break;\n }\n parsedValue = parsedValue * 10 + digit;\n }\n\n if (index === startIndex) {\n return undefined;\n }\n return { value: parsedValue, endIndex: index };\n}\n\nfunction trimLineEnd(value: string): string {\n if (value.endsWith('\\r\\n')) {\n return value.slice(0, -2);\n }\n if (value.endsWith('\\n')) {\n return value.slice(0, -1);\n }\n return value;\n}\n\nfunction isGitDiffPatch(data: string): boolean {\n return data.startsWith('diff --git') || data.includes('\\ndiff --git');\n}\n\nfunction splitAtLinePrefix(contents: string, prefix: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const newlinePrefix = `\\n${prefix}`;\n const firstBoundaryIndex = contents.startsWith(prefix)\n ? 0\n : findLinePrefixIndex(contents, newlinePrefix, 0);\n if (firstBoundaryIndex === -1) {\n return [contents];\n }\n\n const parts: string[] = [];\n if (firstBoundaryIndex > 0) {\n parts.push(contents.slice(0, firstBoundaryIndex));\n }\n\n let startIndex = firstBoundaryIndex;\n for (;;) {\n const nextBoundaryIndex = findLinePrefixIndex(\n contents,\n newlinePrefix,\n startIndex + 1\n );\n if (nextBoundaryIndex === -1) {\n break;\n }\n\n parts.push(contents.slice(startIndex, nextBoundaryIndex));\n startIndex = nextBoundaryIndex;\n }\n parts.push(contents.slice(startIndex));\n return parts;\n}\n\nfunction findLinePrefixIndex(\n contents: string,\n newlinePrefix: string,\n fromIndex: number\n): number {\n const index = contents.indexOf(newlinePrefix, fromIndex);\n return index === -1 ? -1 : index + 1;\n}\n\nfunction maybeDetachOptionalString<T extends string | undefined>(value: T): T {\n return (value == null ? value : detachString(value)) as T;\n}\n\nfunction parseRawLineType(\n firstChar: string | undefined\n): Exclude<HunkLineType, 'expanded'> {\n return firstChar === ' '\n ? 'context'\n : firstChar === '\\\\'\n ? 'metadata'\n : firstChar === '+'\n ? 'addition'\n : 'deletion';\n}\n\nfunction getParsedLineContent(rawLine: string): string {\n const processedLine = rawLine.slice(1);\n return detachString(processedLine === '' ? '\\n' : processedLine);\n}\n\nfunction createContentGroup(\n type: 'change',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent;\nfunction createContentGroup(\n type: 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ContextContent;\nfunction createContentGroup(\n type: 'change' | 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent | ContextContent {\n if (type === 'change') {\n return {\n type: 'change',\n additions: 0,\n deletions: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n }\n return {\n type: 'context',\n lines: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n}\n", "export default class Diff {\n diff(oldStr, newStr, \n // Type below is not accurate/complete - see above for full possibilities - but it compiles\n options = {}) {\n let callback;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n else if ('callback' in options) {\n callback = options.callback;\n }\n // Allow subclasses to massage the input prior to running\n const oldString = this.castInput(oldStr, options);\n const newString = this.castInput(newStr, options);\n const oldTokens = this.removeEmpty(this.tokenize(oldString, options));\n const newTokens = this.removeEmpty(this.tokenize(newString, options));\n return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);\n }\n diffWithOptionsObj(oldTokens, newTokens, options, callback) {\n var _a;\n const done = (value) => {\n value = this.postProcess(value, options);\n if (callback) {\n setTimeout(function () { callback(value); }, 0);\n return undefined;\n }\n else {\n return value;\n }\n };\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let editLength = 1;\n let maxEditLength = newLen + oldLen;\n if (options.maxEditLength != null) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;\n const abortAfterTimestamp = Date.now() + maxExecutionTime;\n const bestPath = [{ oldPos: -1, lastComponent: undefined }];\n // Seed editLength = 0, i.e. the content starts with the same values\n let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // Identity per the equality and tokenizer\n return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));\n }\n // Once we hit the right edge of the edit graph on some diagonal k, we can\n // definitely reach the end of the edit graph in no more than k edits, so\n // there's no point in considering any moves to diagonal k+1 any more (from\n // which we're guaranteed to need at least k+1 more edits).\n // Similarly, once we've reached the bottom of the edit graph, there's no\n // point considering moves to lower diagonals.\n // We record this fact by setting minDiagonalToConsider and\n // maxDiagonalToConsider to some finite value once we've hit the edge of\n // the edit graph.\n // This optimization is not faithful to the original algorithm presented in\n // Myers's paper, which instead pointlessly extends D-paths off the end of\n // the edit graph - see page 7 of Myers's paper which notes this point\n // explicitly and illustrates it with a diagram. This has major performance\n // implications for some common scenarios. For instance, to compute a diff\n // where the new text simply appends d characters on the end of the\n // original text of length n, the true Myers algorithm will take O(n+d^2)\n // time while this optimization needs only O(n+d) time.\n let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;\n // Main worker method. checks all permutations of a given edit length for acceptance.\n const execEditLength = () => {\n for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n let basePath;\n const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n // No one else is going to attempt to use this value, clear it\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath - 1] = undefined;\n }\n let canAdd = false;\n if (addPath) {\n // what newPos will be after we do an insertion:\n const addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n const canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath] = undefined;\n continue;\n }\n // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the old string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {\n basePath = this.addToPath(addPath, true, false, 0, options);\n }\n else {\n basePath = this.addToPath(removePath, false, true, 1, options);\n }\n newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // If we have hit the end of both strings, then we are done\n return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;\n }\n else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n };\n // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced, or until the edit length exceeds options.maxEditLength (if given),\n // in which case it will return undefined.\n if (callback) {\n (function exec() {\n setTimeout(function () {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback(undefined);\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n }());\n }\n else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n const ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n }\n addToPath(path, added, removed, oldPosInc, options) {\n const last = path.lastComponent;\n if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }\n };\n }\n else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: 1, added: added, removed: removed, previousComponent: last }\n };\n }\n }\n extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {\n newPos++;\n oldPos++;\n commonCount++;\n if (options.oneChangePerToken) {\n basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n }\n if (commonCount && !options.oneChangePerToken) {\n basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n basePath.oldPos = oldPos;\n return newPos;\n }\n equals(left, right, options) {\n if (options.comparator) {\n return options.comparator(left, right);\n }\n else {\n return left === right\n || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase());\n }\n }\n removeEmpty(array) {\n const ret = [];\n for (let i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n castInput(value, options) {\n return value;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n tokenize(value, options) {\n return Array.from(value);\n }\n join(chars) {\n // Assumes ValueT is string, which is the case for most subclasses.\n // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)\n // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF\n // assume tokens and values are strings, but not completely - is weird and janky.\n return chars.join('');\n }\n postProcess(changeObjects, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n options) {\n return changeObjects;\n }\n get useLongestToken() {\n return false;\n }\n buildValues(lastComponent, newTokens, oldTokens) {\n // First we convert our linked list of components in reverse order to an\n // array in the right order:\n const components = [];\n let nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n const componentLen = components.length;\n let componentPos = 0, newPos = 0, oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n const component = components[componentPos];\n if (!component.removed) {\n if (!component.added && this.useLongestToken) {\n let value = newTokens.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n const oldValue = oldTokens[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = this.join(value);\n }\n else {\n component.value = this.join(newTokens.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n // Common case\n if (!component.added) {\n oldPos += component.count;\n }\n }\n else {\n component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n }\n }\n return components;\n }\n}\n", "import Diff from './base.js';\nclass CharacterDiff extends Diff {\n}\nexport const characterDiff = new CharacterDiff();\nexport function diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n", "export function longestCommonPrefix(str1, str2) {\n let i;\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[i] != str2[i]) {\n return str1.slice(0, i);\n }\n }\n return str1.slice(0, i);\n}\nexport function longestCommonSuffix(str1, str2) {\n let i;\n // Unlike longestCommonPrefix, we need a special case to handle all scenarios\n // where we return the empty string since str1.slice(-0) will return the\n // entire string.\n if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {\n return '';\n }\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {\n return str1.slice(-i);\n }\n }\n return str1.slice(-i);\n}\nexport function replacePrefix(string, oldPrefix, newPrefix) {\n if (string.slice(0, oldPrefix.length) != oldPrefix) {\n throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);\n }\n return newPrefix + string.slice(oldPrefix.length);\n}\nexport function replaceSuffix(string, oldSuffix, newSuffix) {\n if (!oldSuffix) {\n return string + newSuffix;\n }\n if (string.slice(-oldSuffix.length) != oldSuffix) {\n throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);\n }\n return string.slice(0, -oldSuffix.length) + newSuffix;\n}\nexport function removePrefix(string, oldPrefix) {\n return replacePrefix(string, oldPrefix, '');\n}\nexport function removeSuffix(string, oldSuffix) {\n return replaceSuffix(string, oldSuffix, '');\n}\nexport function maximumOverlap(string1, string2) {\n return string2.slice(0, overlapCount(string1, string2));\n}\n// Nicked from https://stackoverflow.com/a/60422853/1709587\nfunction overlapCount(a, b) {\n // Deal with cases where the strings differ in length\n let startA = 0;\n if (a.length > b.length) {\n startA = a.length - b.length;\n }\n let endB = b.length;\n if (a.length < b.length) {\n endB = a.length;\n }\n // Create a back-reference for each index\n // that should be followed in case of a mismatch.\n // We only need B to make these references:\n const map = Array(endB);\n let k = 0; // Index that lags behind j\n map[0] = 0;\n for (let j = 1; j < endB; j++) {\n if (b[j] == b[k]) {\n map[j] = map[k]; // skip over the same character (optional optimisation)\n }\n else {\n map[j] = k;\n }\n while (k > 0 && b[j] != b[k]) {\n k = map[k];\n }\n if (b[j] == b[k]) {\n k++;\n }\n }\n // Phase 2: use these references while iterating over A\n k = 0;\n for (let i = startA; i < a.length; i++) {\n while (k > 0 && a[i] != b[k]) {\n k = map[k];\n }\n if (a[i] == b[k]) {\n k++;\n }\n }\n return k;\n}\n/**\n * Returns true if the string consistently uses Windows line endings.\n */\nexport function hasOnlyWinLineEndings(string) {\n return string.includes('\\r\\n') && !string.startsWith('\\n') && !string.match(/[^\\r]\\n/);\n}\n/**\n * Returns true if the string consistently uses Unix line endings.\n */\nexport function hasOnlyUnixLineEndings(string) {\n return !string.includes('\\r\\n') && string.includes('\\n');\n}\n/**\n * Split a string into segments using a word segmenter, merging consecutive\n * segments if they are both whitespace segments. Whitespace segments can\n * appear adjacent to one another for two reasons:\n * - newlines always get their own segment\n * - where a diacritic is attached to a whitespace character in the text, the\n * segment ends after the diacritic, so e.g. \" \\u0300 \" becomes two segments.\n * This function therefore runs the segmenter's .segment() method and then\n * merges consecutive segments of whitespace into a single part.\n */\nexport function segment(string, segmenter) {\n const parts = [];\n for (const segmentObj of Array.from(segmenter.segment(string))) {\n const segment = segmentObj.segment;\n if (parts.length && (/\\s/).test(parts[parts.length - 1]) && (/\\s/).test(segment)) {\n parts[parts.length - 1] += segment;\n }\n else {\n parts.push(segment);\n }\n }\n return parts;\n}\n// The functions below take a `segmenter` argument so that, when called from\n// diffWords when it is using a segmenter, they can use a notion of what\n// constitutes \"whitespace\" that is consistent with the segmenter.\n//\n// USUALLY this will be identical to the result of the non-segmenter-based\n// logic, but it differs in at least one case: when whitespace characters are\n// modified by diacritics. A word segmenter considers these diacritics to be\n// part of the whitespace, whereas our non-segmenter-based logic does not.\n//\n// Because the segmenter-based approach necessarily requires segmenting the\n// entire string, we offer a leadingAndTrailingWs function to allow getting the\n// whitespace prefix AND whitespace suffix with a single call to the segmenter,\n// for efficiency's sake.\nexport function trailingWs(string, segmenter) {\n if (segmenter) {\n return leadingAndTrailingWs(string, segmenter)[1];\n }\n // Yes, this looks overcomplicated and dumb - why not replace the whole function with\n // return string.match(/\\s*$/)[0]\n // you ask? Because:\n // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing\n // this would cause this function to take O(n\u00B2) time in the worst case (specifically when\n // there is a massive run of NON-TRAILING whitespace in `string`), and\n // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible\n // with old Safari versions that we'd like to not break if possible (see\n // https://github.com/kpdecker/jsdiff/pull/550)\n // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a\n // better way that doesn't result in broken behaviour.\n let i;\n for (i = string.length - 1; i >= 0; i--) {\n if (!string[i].match(/\\s/)) {\n break;\n }\n }\n return string.substring(i + 1);\n}\nexport function leadingWs(string, segmenter) {\n if (segmenter) {\n return leadingAndTrailingWs(string, segmenter)[0];\n }\n // Thankfully the annoying considerations described in trailingWs don't apply here:\n const match = string.match(/^\\s*/);\n return match ? match[0] : '';\n}\nexport function leadingAndTrailingWs(string, segmenter) {\n if (!segmenter) {\n return [leadingWs(string), trailingWs(string)];\n }\n if (segmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n const segments = segment(string, segmenter);\n const firstSeg = segments[0];\n const lastSeg = segments[segments.length - 1];\n const head = (/\\s/).test(firstSeg) ? firstSeg : '';\n const tail = (/\\s/).test(lastSeg) ? lastSeg : '';\n return [head, tail];\n}\n", "import Diff from './base.js';\nimport { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs, leadingAndTrailingWs, segment } from '../util/string.js';\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Chars/ranges counted as \"word\" characters by this regex are as follows:\n//\n// + U+00AD Soft hyphen\n// + 00C0\u201300FF (letters with diacritics from the Latin-1 Supplement), except:\n// - U+00D7 \u00D7 Multiplication sign\n// - U+00F7 \u00F7 Division sign\n// + Latin Extended-A, 0100\u2013017F\n// + Latin Extended-B, 0180\u2013024F\n// + IPA Extensions, 0250\u201302AF\n// + Spacing Modifier Letters, 02B0\u201302FF, except:\n// - U+02C7 \u02C7 &#711; Caron\n// - U+02D8 \u02D8 &#728; Breve\n// - U+02D9 \u02D9 &#729; Dot Above\n// - U+02DA \u02DA &#730; Ring Above\n// - U+02DB \u02DB &#731; Ogonek\n// - U+02DC \u02DC &#732; Small Tilde\n// - U+02DD \u02DD &#733; Double Acute Accent\n// + Latin Extended Additional, 1E00\u20131EFF\nconst extendedWordChars = 'a-zA-Z0-9_\\\\u{AD}\\\\u{C0}-\\\\u{D6}\\\\u{D8}-\\\\u{F6}\\\\u{F8}-\\\\u{2C6}\\\\u{2C8}-\\\\u{2D7}\\\\u{2DE}-\\\\u{2FF}\\\\u{1E00}-\\\\u{1EFF}';\n// Each token is one of the following:\n// - A punctuation mark plus the surrounding whitespace\n// - A word plus the surrounding whitespace\n// - Pure whitespace (but only in the special case where the entire text\n// is just whitespace)\n//\n// We have to include surrounding whitespace in the tokens because the two\n// alternative approaches produce horribly broken results:\n// * If we just discard the whitespace, we can't fully reproduce the original\n// text from the sequence of tokens and any attempt to render the diff will\n// get the whitespace wrong.\n// * If we have separate tokens for whitespace, then in a typical text every\n// second token will be a single space character. But this often results in\n// the optimal diff between two texts being a perverse one that preserves\n// the spaces between words but deletes and reinserts actual common words.\n// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640\n// for an example.\n//\n// Keeping the surrounding whitespace of course has implications for .equals\n// and .join, not just .tokenize.\n// This regex does NOT fully implement the tokenization rules described above.\n// Instead, it gives runs of whitespace their own \"token\". The tokenize method\n// then handles stitching whitespace tokens onto adjacent word or punctuation\n// tokens.\nconst tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\\\s+|[^${extendedWordChars}]`, 'ug');\nclass WordDiff extends Diff {\n equals(left, right, options) {\n if (options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left.trim() === right.trim();\n }\n tokenize(value, options = {}) {\n let parts;\n if (options.intlSegmenter) {\n const segmenter = options.intlSegmenter;\n if (segmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n // We want `parts` to be an array whose elements alternate between being\n // pure whitespace and being pure non-whitespace. This is ALMOST what the\n // segments returned by a word-based Intl.Segmenter already look like,\n // but not quite - see explanation in the docs of our custom segment()\n // function.\n parts = segment(value, segmenter);\n }\n else {\n parts = value.match(tokenizeIncludingWhitespace) || [];\n }\n const tokens = [];\n let prevPart = null;\n parts.forEach(part => {\n if ((/\\s/).test(part)) {\n if (prevPart == null) {\n tokens.push(part);\n }\n else {\n tokens.push(tokens.pop() + part);\n }\n }\n else if (prevPart != null && (/\\s/).test(prevPart)) {\n if (tokens[tokens.length - 1] == prevPart) {\n tokens.push(tokens.pop() + part);\n }\n else {\n tokens.push(prevPart + part);\n }\n }\n else {\n tokens.push(part);\n }\n prevPart = part;\n });\n return tokens;\n }\n join(tokens) {\n // Tokens being joined here will always have appeared consecutively in the\n // same text, so we can simply strip off the leading whitespace from all the\n // tokens except the first (and except any whitespace-only tokens - but such\n // a token will always be the first and only token anyway) and then join them\n // and the whitespace around words and punctuation will end up correct.\n return tokens.map((token, i) => {\n if (i == 0) {\n return token;\n }\n else {\n return token.replace((/^\\s+/), '');\n }\n }).join('');\n }\n postProcess(changes, options) {\n if (!changes || options.oneChangePerToken) {\n return changes;\n }\n let lastKeep = null;\n // Change objects representing any insertion or deletion since the last\n // \"keep\" change object. There can be at most one of each.\n let insertion = null;\n let deletion = null;\n changes.forEach(change => {\n if (change.added) {\n insertion = change;\n }\n else if (change.removed) {\n deletion = change;\n }\n else {\n if (insertion || deletion) { // May be false at start of text\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change, options.intlSegmenter);\n }\n lastKeep = change;\n insertion = null;\n deletion = null;\n }\n });\n if (insertion || deletion) {\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter);\n }\n return changes;\n }\n}\nexport const wordDiff = new WordDiff();\nexport function diffWords(oldStr, newStr, options) {\n // This option has never been documented and never will be (it's clearer to\n // just call `diffWordsWithSpace` directly if you need that behavior), but\n // has existed in jsdiff for a long time, so we retain support for it here\n // for the sake of backwards compatibility.\n if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {\n return diffWordsWithSpace(oldStr, newStr, options);\n }\n return wordDiff.diff(oldStr, newStr, options);\n}\nfunction dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter) {\n // Before returning, we tidy up the leading and trailing whitespace of the\n // change objects to eliminate cases where trailing whitespace in one object\n // is repeated as leading whitespace in the next.\n // Below are examples of the outcomes we want here to explain the code.\n // I=insert, K=keep, D=delete\n // 1. diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'\n //\n // 2. Diffing 'foo bar baz' vs 'foo qux baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'\n // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'\n //\n // 3. Diffing 'foo\\nbar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:'\\nbar ' K:' baz'\n // After cleanup, we want K'foo' D:'\\nbar' K:' baz'\n //\n // 4. Diffing 'foo baz' vs 'foo\\nbar baz'\n // Prior to cleanup, we have K:'foo\\n' I:'\\nbar ' K:' baz'\n // After cleanup, we ideally want K'foo' I:'\\nbar' K:' baz'\n // but don't actually manage this currently (the pre-cleanup change\n // objects don't contain enough information to make it possible).\n //\n // 5. Diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want K:'foo ' D:' bar ' K:'baz'\n //\n // Our handling is unavoidably imperfect in the case where there's a single\n // indel between keeps and the whitespace has changed. For instance, consider\n // diffing 'foo\\tbar\\nbaz' vs 'foo baz'. Unless we create an extra change\n // object to represent the insertion of the space character (which isn't even\n // a token), we have no way to avoid losing information about the texts'\n // original whitespace in the result we return. Still, we do our best to\n // output something that will look sensible if we e.g. print it with\n // insertions in green and deletions in red.\n // Between two \"keep\" change objects (or before the first or after the last\n // change object), we can have either:\n // * A \"delete\" followed by an \"insert\"\n // * Just an \"insert\"\n // * Just a \"delete\"\n // We handle the three cases separately.\n if (deletion && insertion) {\n const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter);\n const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter);\n if (startKeep) {\n const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);\n startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);\n deletion.value = removePrefix(deletion.value, commonWsPrefix);\n insertion.value = removePrefix(insertion.value, commonWsPrefix);\n }\n if (endKeep) {\n const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);\n endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);\n deletion.value = removeSuffix(deletion.value, commonWsSuffix);\n insertion.value = removeSuffix(insertion.value, commonWsSuffix);\n }\n }\n else if (insertion) {\n // The whitespaces all reflect what was in the new text rather than\n // the old, so we essentially have no information about whitespace\n // insertion or deletion. We just want to dedupe the whitespace.\n // We do that by having each change object keep its trailing\n // whitespace and deleting duplicate leading whitespace where\n // present.\n if (startKeep) {\n const ws = leadingWs(insertion.value, segmenter);\n insertion.value = insertion.value.substring(ws.length);\n }\n if (endKeep) {\n const ws = leadingWs(endKeep.value, segmenter);\n endKeep.value = endKeep.value.substring(ws.length);\n }\n // otherwise we've got a deletion and no insertion\n }\n else if (startKeep && endKeep) {\n const newWsFull = leadingWs(endKeep.value, segmenter), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter);\n // Any whitespace that comes straight after startKeep in both the old and\n // new texts, assign to startKeep and remove from the deletion.\n const newWsStart = longestCommonPrefix(newWsFull, delWsStart);\n deletion.value = removePrefix(deletion.value, newWsStart);\n // Any whitespace that comes straight before endKeep in both the old and\n // new texts, and hasn't already been assigned to startKeep, assign to\n // endKeep and remove from the deletion.\n const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);\n deletion.value = removeSuffix(deletion.value, newWsEnd);\n endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);\n // If there's any whitespace from the new text that HASN'T already been\n // assigned, assign it to the start:\n startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));\n }\n else if (endKeep) {\n // We are at the start of the text. Preserve all the whitespace on\n // endKeep, and just remove whitespace from the end of deletion to the\n // extent that it overlaps with the start of endKeep.\n const endKeepWsPrefix = leadingWs(endKeep.value, segmenter);\n const deletionWsSuffix = trailingWs(deletion.value, segmenter);\n const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);\n deletion.value = removeSuffix(deletion.value, overlap);\n }\n else if (startKeep) {\n // We are at the END of the text. Preserve all the whitespace on\n // startKeep, and just remove whitespace from the start of deletion to\n // the extent that it overlaps with the end of startKeep.\n const startKeepWsSuffix = trailingWs(startKeep.value, segmenter);\n const deletionWsPrefix = leadingWs(deletion.value, segmenter);\n const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);\n deletion.value = removePrefix(deletion.value, overlap);\n }\n}\nclass WordsWithSpaceDiff extends Diff {\n tokenize(value) {\n // Slightly different to the tokenizeIncludingWhitespace regex used above in\n // that this one treats each individual newline as a distinct token, rather\n // than merging them into other surrounding whitespace. This was requested\n // in https://github.com/kpdecker/jsdiff/issues/180 &\n // https://github.com/kpdecker/jsdiff/issues/211\n const regex = new RegExp(`(\\\\r?\\\\n)|[${extendedWordChars}]+|[^\\\\S\\\\n\\\\r]+|[^${extendedWordChars}]`, 'ug');\n return value.match(regex) || [];\n }\n}\nexport const wordsWithSpaceDiff = new WordsWithSpaceDiff();\nexport function diffWordsWithSpace(oldStr, newStr, options) {\n return wordsWithSpaceDiff.diff(oldStr, newStr, options);\n}\n", "import Diff from './base.js';\nimport { generateOptions } from '../util/params.js';\nclass LineDiff extends Diff {\n constructor() {\n super(...arguments);\n this.tokenize = tokenize;\n }\n equals(left, right, options) {\n // If we're ignoring whitespace, we need to normalise lines by stripping\n // whitespace before checking equality. (This has an annoying interaction\n // with newlineIsToken that requires special handling: if newlines get their\n // own token, then we DON'T want to trim the *newline* tokens down to empty\n // strings, since this would cause us to treat whitespace-only line content\n // as equal to a separator between lines, which would be weird and\n // inconsistent with the documented behavior of the options.)\n if (options.ignoreWhitespace) {\n if (!options.newlineIsToken || !left.includes('\\n')) {\n left = left.trim();\n }\n if (!options.newlineIsToken || !right.includes('\\n')) {\n right = right.trim();\n }\n }\n else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {\n if (left.endsWith('\\n')) {\n left = left.slice(0, -1);\n }\n if (right.endsWith('\\n')) {\n right = right.slice(0, -1);\n }\n }\n return super.equals(left, right, options);\n }\n}\nexport const lineDiff = new LineDiff();\nexport function diffLines(oldStr, newStr, options) {\n return lineDiff.diff(oldStr, newStr, options);\n}\nexport function diffTrimmedLines(oldStr, newStr, options) {\n options = generateOptions(options, { ignoreWhitespace: true });\n return lineDiff.diff(oldStr, newStr, options);\n}\n// Exported standalone so it can be used from jsonDiff too.\nexport function tokenize(value, options) {\n if (options.stripTrailingCr) {\n // remove one \\r before \\n to match GNU diff's --strip-trailing-cr behavior\n value = value.replace(/\\r\\n/g, '\\n');\n }\n const retLines = [], linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n // Ignore the final empty token that occurs if the string ends with a new line\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n // Merge the content and line separators into single tokens\n for (let i = 0; i < linesAndNewlines.length; i++) {\n const line = linesAndNewlines[i];\n if (i % 2 && !options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n }\n else {\n retLines.push(line);\n }\n }\n return retLines;\n}\n", "import { diffLines } from '../diff/line.js';\n/**\n * Returns true if the filename contains characters that require C-style\n * quoting (as used by Git and GNU diffutils in diff output).\n */\nfunction needsQuoting(s) {\n for (let i = 0; i < s.length; i++) {\n if (s[i] < '\\x20' || s[i] > '\\x7e' || s[i] === '\"' || s[i] === '\\\\') {\n return true;\n }\n }\n return false;\n}\n/**\n * C-style quotes a filename, encoding special characters as escape sequences\n * and non-ASCII bytes as octal escapes. This is the inverse of\n * `parseQuotedFileName` in parse.ts.\n *\n * Non-ASCII bytes are encoded as UTF-8 before being emitted as octal escapes.\n * This matches the behaviour of both Git and GNU diffutils, which always emit\n * UTF-8 octal escapes regardless of the underlying filesystem encoding (e.g.\n * Git for Windows converts from NTFS's UTF-16 to UTF-8 internally).\n *\n * If the filename doesn't need quoting, returns it as-is.\n */\nfunction quoteFileNameIfNeeded(s) {\n if (!needsQuoting(s)) {\n return s;\n }\n let result = '\"';\n const bytes = new TextEncoder().encode(s);\n let i = 0;\n while (i < bytes.length) {\n const b = bytes[i];\n // See https://en.wikipedia.org/wiki/Escape_sequences_in_C#Escape_sequences\n if (b === 0x07) {\n result += '\\\\a';\n }\n else if (b === 0x08) {\n result += '\\\\b';\n }\n else if (b === 0x09) {\n result += '\\\\t';\n }\n else if (b === 0x0a) {\n result += '\\\\n';\n }\n else if (b === 0x0b) {\n result += '\\\\v';\n }\n else if (b === 0x0c) {\n result += '\\\\f';\n }\n else if (b === 0x0d) {\n result += '\\\\r';\n }\n else if (b === 0x22) {\n result += '\\\\\"';\n }\n else if (b === 0x5c) {\n result += '\\\\\\\\';\n }\n else if (b >= 0x20 && b <= 0x7e) {\n // Just a printable ASCII character that is neither a double quote nor a\n // backslash; no need to escape it.\n result += String.fromCharCode(b);\n }\n else {\n // Either part of a non-ASCII character or a control character without a\n // special escape sequence; needs escaping as a 3-digit octal escape\n result += '\\\\' + b.toString(8).padStart(3, '0');\n }\n i++;\n }\n result += '\"';\n return result;\n}\nexport const INCLUDE_HEADERS = {\n includeIndex: true,\n includeUnderline: true,\n includeFileHeaders: true\n};\nexport const FILE_HEADERS_ONLY = {\n includeIndex: false,\n includeUnderline: false,\n includeFileHeaders: true\n};\nexport const OMIT_HEADERS = {\n includeIndex: false,\n includeUnderline: false,\n includeFileHeaders: false\n};\nexport function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n let optionsObj;\n if (!options) {\n optionsObj = {};\n }\n else if (typeof options === 'function') {\n optionsObj = { callback: options };\n }\n else {\n optionsObj = options;\n }\n if (typeof optionsObj.context === 'undefined') {\n optionsObj.context = 4;\n }\n // We copy this into its own variable to placate TypeScript, which thinks\n // optionsObj.context might be undefined in the callbacks below.\n const context = optionsObj.context;\n // @ts-expect-error (runtime check for something that is correctly a static type error)\n if (optionsObj.newlineIsToken) {\n throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');\n }\n if (!optionsObj.callback) {\n return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));\n }\n else {\n const { callback } = optionsObj;\n diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {\n const patch = diffLinesResultToPatch(diff);\n // TypeScript is unhappy without the cast because it does not understand that `patch` may\n // be undefined here only if `callback` is StructuredPatchCallbackAbortable:\n callback(patch);\n } }));\n }\n function diffLinesResultToPatch(diff) {\n // STEP 1: Build up the patch with no \"\\" lines and with the arrays\n // of lines containing trailing newline characters. We'll tidy up later...\n if (!diff) {\n return;\n }\n diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier\n function contextLines(lines) {\n return lines.map(function (entry) { return ' ' + entry; });\n }\n const hunks = [];\n let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;\n for (let i = 0; i < diff.length; i++) {\n const current = diff[i], lines = current.lines || splitLines(current.value);\n current.lines = lines;\n if (current.added || current.removed) {\n // If we have previous context, start with that\n if (!oldRangeStart) {\n const prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n if (prev) {\n curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n }\n // Output our changes\n for (const line of lines) {\n curRange.push((current.added ? '+' : '-') + line);\n }\n // Track the updated file position\n if (current.added) {\n newLine += lines.length;\n }\n else {\n oldLine += lines.length;\n }\n }\n else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= context * 2 && i < diff.length - 2) {\n // Overlapping\n for (const line of contextLines(lines)) {\n curRange.push(line);\n }\n }\n else {\n // end the range and output\n const contextSize = Math.min(lines.length, context);\n for (const line of contextLines(lines.slice(0, contextSize))) {\n curRange.push(line);\n }\n const hunk = {\n oldStart: oldRangeStart,\n oldLines: (oldLine - oldRangeStart + contextSize),\n newStart: newRangeStart,\n newLines: (newLine - newRangeStart + contextSize),\n lines: curRange\n };\n hunks.push(hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n oldLine += lines.length;\n newLine += lines.length;\n }\n }\n // Step 2: eliminate the trailing `\\n` from each line of each hunk, and, where needed, add\n // \"\\".\n for (const hunk of hunks) {\n for (let i = 0; i < hunk.lines.length; i++) {\n if (hunk.lines[i].endsWith('\\n')) {\n hunk.lines[i] = hunk.lines[i].slice(0, -1);\n }\n else {\n hunk.lines.splice(i + 1, 0, '\\\');\n i++; // Skip the line we just added, then continue iterating\n }\n }\n }\n return {\n oldFileName: oldFileName, newFileName: newFileName,\n oldHeader: oldHeader, newHeader: newHeader,\n hunks: hunks\n };\n }\n}\n/**\n * creates a unified diff patch.\n *\n * @param patch either a single structured patch object (as returned by `structuredPatch`) or an\n * array of them (as returned by `parsePatch`).\n * @param headerOptions behaves the same as the `headerOptions` option of `createTwoFilesPatch`.\n * Ignored for patches where `isGit` is `true`.\n *\n * When a patch has `isGit: true`, `formatPatch` output is changed to more closely match Git's\n * output: it emits a `diff --git` header, emits Git extended headers as appropriate based on\n * properties like `isRename`, `isCreate`, `newMode`, etc, and will omit `---`/`+++` file\n * headers for patches with no hunks (e.g. renames without content changes).\n */\nexport function formatPatch(patch, headerOptions) {\n var _a, _b, _c, _d, _e, _f;\n if (!headerOptions) {\n headerOptions = INCLUDE_HEADERS;\n }\n if (Array.isArray(patch)) {\n if (patch.length > 1 && !headerOptions.includeFileHeaders && !patch.every(p => p.isGit)) {\n throw new Error('Cannot omit file headers on a multi-file patch. '\n + '(The result would be unparseable; how would a tool trying to apply '\n + 'the patch know which changes are to which file?)');\n }\n return patch.map(p => formatPatch(p, headerOptions)).join('\\n');\n }\n const ret = [];\n // Git patches have a fixed header format (diff --git, extended headers,\n // and ---/+++ when hunks are present), so headerOptions is ignored.\n if (patch.isGit) {\n headerOptions = INCLUDE_HEADERS;\n // Emit Git-style diff --git header and extended headers.\n // Git never puts /dev/null in the \"diff --git\" line; for file\n // creations/deletions it uses the real filename on both sides.\n if (!patch.oldFileName) {\n throw new Error('oldFileName must be specified for Git patches');\n }\n if (!patch.newFileName) {\n throw new Error('newFileName must be specified for Git patches');\n }\n let gitOldName = patch.oldFileName;\n let gitNewName = patch.newFileName;\n if (patch.isCreate && gitOldName === '/dev/null') {\n gitOldName = gitNewName.replace(/^b\\//, 'a/');\n }\n else if (patch.isDelete && gitNewName === '/dev/null') {\n gitNewName = gitOldName.replace(/^a\\//, 'b/');\n }\n ret.push('diff --git ' + quoteFileNameIfNeeded(gitOldName) + ' ' + quoteFileNameIfNeeded(gitNewName));\n if (patch.isDelete) {\n ret.push('deleted file mode ' + ((_a = patch.oldMode) !== null && _a !== void 0 ? _a : '100644'));\n }\n if (patch.isCreate) {\n ret.push('new file mode ' + ((_b = patch.newMode) !== null && _b !== void 0 ? _b : '100644'));\n }\n if (patch.oldMode && patch.newMode && !patch.isDelete && !patch.isCreate) {\n ret.push('old mode ' + patch.oldMode);\n ret.push('new mode ' + patch.newMode);\n }\n if (patch.isRename) {\n ret.push('rename from ' + quoteFileNameIfNeeded(((_c = patch.oldFileName) !== null && _c !== void 0 ? _c : '').replace(/^a\\//, '')));\n ret.push('rename to ' + quoteFileNameIfNeeded(((_d = patch.newFileName) !== null && _d !== void 0 ? _d : '').replace(/^b\\//, '')));\n }\n if (patch.isCopy) {\n ret.push('copy from ' + quoteFileNameIfNeeded(((_e = patch.oldFileName) !== null && _e !== void 0 ? _e : '').replace(/^a\\//, '')));\n ret.push('copy to ' + quoteFileNameIfNeeded(((_f = patch.newFileName) !== null && _f !== void 0 ? _f : '').replace(/^b\\//, '')));\n }\n }\n else {\n if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName && patch.oldFileName !== undefined) {\n ret.push('Index: ' + patch.oldFileName);\n }\n if (headerOptions.includeUnderline) {\n ret.push('===================================================================');\n }\n }\n // Emit --- / +++ file headers. For Git patches with no hunks (e.g.\n // pure renames, mode-only changes), Git omits these, so we do too.\n const hasHunks = patch.hunks.length > 0;\n if (headerOptions.includeFileHeaders && patch.oldFileName !== undefined && patch.newFileName !== undefined\n && (!patch.isGit || hasHunks)) {\n ret.push('--- ' + quoteFileNameIfNeeded(patch.oldFileName) + (patch.oldHeader ? '\\t' + patch.oldHeader : ''));\n ret.push('+++ ' + quoteFileNameIfNeeded(patch.newFileName) + (patch.newHeader ? '\\t' + patch.newHeader : ''));\n }\n for (let i = 0; i < patch.hunks.length; i++) {\n const hunk = patch.hunks[i];\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n const oldStart = hunk.oldLines === 0 ? hunk.oldStart - 1 : hunk.oldStart;\n const newStart = hunk.newLines === 0 ? hunk.newStart - 1 : hunk.newStart;\n ret.push('@@ -' + oldStart + ',' + hunk.oldLines\n + ' +' + newStart + ',' + hunk.newLines\n + ' @@');\n for (const line of hunk.lines) {\n ret.push(line);\n }\n }\n return ret.join('\\n') + '\\n';\n}\nexport function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (typeof options === 'function') {\n options = { callback: options };\n }\n if (!(options === null || options === void 0 ? void 0 : options.callback)) {\n const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);\n if (!patchObj) {\n return;\n }\n return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions);\n }\n else {\n const { callback } = options;\n structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => {\n if (!patchObj) {\n callback(undefined);\n }\n else {\n callback(formatPatch(patchObj, options.headerOptions));\n }\n } }));\n }\n}\nexport function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n/**\n * Split `text` into an array of lines, including the trailing newline character (where present)\n */\nfunction splitLines(text) {\n const hasTrailingNl = text.endsWith('\\n');\n const result = text.split('\\n').map(line => line + '\\n');\n if (hasTrailingNl) {\n result.pop();\n }\n else {\n result.push(result.pop().slice(0, -1));\n }\n return result;\n}\n", "import { type CreatePatchOptionsNonabortable, createTwoFilesPatch } from 'diff';\n\nimport type { FileContents, FileDiffMetadata } from '../types';\nimport { composeCacheKey } from './composeCacheKey';\nimport { processFile } from './parsePatchFiles';\n\nconst MISSING_FILE_NAME = '/dev/null';\n\n/**\n * Parses a diff from two file contents objects.\n *\n * If both `oldFile` and `newFile` have a `cacheKey`, the resulting diff gets a\n * collision-safe key derived from both values.\n */\nexport function parseDiffFromFile(\n oldFile: FileContents | null,\n newFile: FileContents | null,\n options?: CreatePatchOptionsNonabortable,\n throwOnError = false\n): FileDiffMetadata {\n if (oldFile === null && newFile === null) {\n throw new Error(\n 'parseDiffFromFile: You must pass oldFile, newFile, or both'\n );\n }\n\n const resolvedOldFile = oldFile ?? createMissingFile();\n const resolvedNewFile = newFile ?? createMissingFile();\n const patch = createTwoFilesPatch(\n resolvedOldFile.name,\n resolvedNewFile.name,\n resolvedOldFile.contents,\n resolvedNewFile.contents,\n resolvedOldFile.header,\n resolvedNewFile.header,\n options\n );\n\n const fileData = processFile(patch, {\n cacheKey: (() => {\n const oldCacheKey = oldFile?.cacheKey;\n const newCacheKey = newFile?.cacheKey;\n return oldCacheKey != null && newCacheKey != null\n ? composeCacheKey('diff', oldCacheKey, newCacheKey)\n : undefined;\n })(),\n oldFile: resolvedOldFile,\n newFile: resolvedNewFile,\n throwOnError,\n });\n if (fileData == null) {\n throw new Error(\n 'parseDiffFrom: FileInvalid diff -- probably need to fix something -- if the files are the same maybe?'\n );\n }\n if (oldFile === null) {\n fileData.type = 'new';\n fileData.prevName = undefined;\n } else if (newFile === null) {\n fileData.type = 'deleted';\n fileData.prevName = undefined;\n }\n // If we've been provided an override for language in the newFile, let’s pass\n // it through to FileDiffMetadata.\n const language =\n newFile?.lang ?? (newFile === null ? oldFile?.lang : undefined);\n if (language != null) {\n fileData.lang = language;\n }\n return fileData;\n}\n\nfunction createMissingFile(): FileContents {\n return { name: MISSING_FILE_NAME, contents: '' };\n}\n", "export class ScrollSyncManager {\n isDeletionsScrolling: boolean = false;\n isAdditionsScrolling: boolean = false;\n timeoutId: NodeJS.Timeout = -1 as unknown as NodeJS.Timeout;\n codeDeletions: HTMLElement | undefined;\n codeAdditions: HTMLElement | undefined;\n private enabled = false;\n\n cleanUp(): void {\n if (!this.enabled) {\n return;\n }\n this.codeDeletions?.removeEventListener(\n 'scroll',\n this.handleDeletionsScroll\n );\n this.codeAdditions?.removeEventListener(\n 'scroll',\n this.handleAdditionsScroll\n );\n clearTimeout(this.timeoutId);\n this.codeDeletions = undefined;\n this.codeAdditions = undefined;\n this.enabled = false;\n }\n\n setup(\n pre: HTMLPreElement,\n codeDeletions?: HTMLElement,\n codeAdditions?: HTMLElement\n ): void {\n // If no code elements were provided, lets try to find them in\n // the pre element\n if (codeDeletions == null || codeAdditions == null) {\n for (const element of pre.children ?? []) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n if ('deletions' in element.dataset) {\n codeDeletions = element;\n } else if ('additions' in element.dataset) {\n codeAdditions = element;\n }\n }\n }\n if (codeAdditions == null || codeDeletions == null) {\n this.cleanUp();\n return;\n }\n\n if (this.codeDeletions !== codeDeletions) {\n this.codeDeletions?.removeEventListener(\n 'scroll',\n this.handleDeletionsScroll\n );\n this.codeDeletions = codeDeletions;\n codeDeletions.addEventListener('scroll', this.handleDeletionsScroll, {\n passive: true,\n });\n }\n if (this.codeAdditions !== codeAdditions) {\n this.codeAdditions?.removeEventListener(\n 'scroll',\n this.handleAdditionsScroll\n );\n this.codeAdditions = codeAdditions;\n codeAdditions.addEventListener('scroll', this.handleAdditionsScroll, {\n passive: true,\n });\n }\n this.enabled = true;\n }\n\n private handleDeletionsScroll = () => {\n if (this.isAdditionsScrolling) {\n return;\n }\n this.isDeletionsScrolling = true;\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => {\n this.isDeletionsScrolling = false;\n }, 300);\n this.codeAdditions?.scrollTo({\n left: this.codeDeletions?.scrollLeft,\n });\n };\n\n private handleAdditionsScroll = () => {\n if (this.isDeletionsScrolling) {\n return;\n }\n this.isAdditionsScrolling = true;\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => {\n this.isAdditionsScrolling = false;\n }, 300);\n this.codeDeletions?.scrollTo({\n left: this.codeAdditions?.scrollLeft,\n });\n };\n}\n", "import type { RenderDiffOptions } from '../types';\nimport { areThemesEqual } from './areThemesEqual';\n\nexport function areDiffRenderOptionsEqual(\n optionsA: RenderDiffOptions,\n optionsB: RenderDiffOptions\n): boolean {\n return (\n areThemesEqual(optionsA.theme, optionsB.theme) &&\n optionsA.useTokenTransformer === optionsB.useTokenTransformer &&\n optionsA.tokenizeMaxLineLength === optionsB.tokenizeMaxLineLength &&\n optionsA.lineDiffType === optionsB.lineDiffType &&\n optionsA.maxLineDiffLength === optionsB.maxLineDiffLength\n );\n}\n", "import type { Element as HASTElement } from 'hast';\n\nimport { createHastElement } from './hast_utils';\n\nexport function createEmptyRowBuffer(size: number): HASTElement {\n return createHastElement({\n tagName: 'div',\n properties: {\n 'data-content-buffer': '',\n 'data-buffer-size': size,\n style: `grid-row: span ${size};min-height:calc(${size} * 1lh)`,\n },\n });\n}\n", "import type { Element as HASTElement } from 'hast';\n\nimport type { LineTypes } from '../types';\nimport { createHastElement, createTextNodeElement } from './hast_utils';\n\nexport function createNoNewlineElement(type: LineTypes): HASTElement {\n return createHastElement({\n tagName: 'div',\n children: [\n createHastElement({\n tagName: 'span',\n children: [createTextNodeElement('No newline at end of file')],\n }),\n ],\n properties: {\n 'data-no-newline': '',\n 'data-line-type': type,\n 'data-column-content': '',\n },\n });\n}\n", "import type { ElementContent, Element as HASTElement } from 'hast';\n\nimport type { ExpansionDirections, HunkSeparators } from '../types';\nimport {\n createHastElement,\n createIconElement,\n createTextNodeElement,\n} from './hast_utils';\n\ninterface CreateSeparatorProps {\n type: HunkSeparators;\n content?: string;\n expandIndex?: number;\n chunked?: boolean;\n slotName?: string;\n isFirstHunk: boolean;\n isLastHunk: boolean;\n}\n\nfunction createExpandButton(type: ExpansionDirections) {\n return createHastElement({\n tagName: 'div',\n children: [\n createIconElement({\n name: type === 'both' ? 'diffs-icon-expand-all' : 'diffs-icon-expand',\n properties: { 'data-icon': '' },\n }),\n ],\n properties: {\n role: 'button',\n 'data-expand-button': '',\n 'data-expand-both': type === 'both' ? '' : undefined,\n 'data-expand-up': type === 'up' ? '' : undefined,\n 'data-expand-down': type === 'down' ? '' : undefined,\n },\n });\n}\n\nexport function createSeparator({\n type,\n content,\n expandIndex,\n chunked = false,\n slotName,\n isFirstHunk,\n isLastHunk,\n}: CreateSeparatorProps): HASTElement {\n let buttonCount = 0;\n const children = [];\n if (type === 'metadata' && content != null) {\n children.push(\n createHastElement({\n tagName: 'div',\n children: [createTextNodeElement(content)],\n properties: { 'data-separator-wrapper': '' },\n })\n );\n }\n if ((type === 'line-info' || type === 'line-info-basic') && content != null) {\n const contentChildren: ElementContent[] = [];\n if (expandIndex != null) {\n if (!chunked) {\n contentChildren.push(\n createExpandButton(\n !isFirstHunk && !isLastHunk ? 'both' : isFirstHunk ? 'down' : 'up'\n )\n );\n buttonCount++;\n } else {\n if (!isFirstHunk) {\n contentChildren.push(createExpandButton('up'));\n buttonCount++;\n }\n if (!isLastHunk) {\n contentChildren.push(createExpandButton('down'));\n buttonCount++;\n }\n }\n }\n contentChildren.push(\n createHastElement({\n tagName: 'div',\n children: [\n createHastElement({\n tagName: 'span',\n children: [createTextNodeElement(content)],\n properties: { 'data-unmodified-lines': '' },\n }),\n ],\n properties: { 'data-separator-content': '' },\n })\n );\n if (chunked && expandIndex != null) {\n contentChildren.push(\n createHastElement({\n tagName: 'div',\n children: [createTextNodeElement('Expand all')],\n properties: {\n role: 'button',\n 'data-expand-button': '',\n 'data-expand-all-button': '',\n },\n })\n );\n }\n children.push(\n createHastElement({\n tagName: 'div',\n children: contentChildren,\n properties: {\n 'data-separator-wrapper': '',\n 'data-separator-multi-button': buttonCount > 1 ? '' : undefined,\n },\n })\n );\n }\n if (type === 'custom' && slotName != null) {\n children.push(\n createHastElement({\n tagName: 'slot',\n properties: { name: slotName },\n })\n );\n }\n return createHastElement({\n tagName: 'div',\n children,\n properties: {\n 'data-separator': children.length === 0 ? 'simple' : type,\n 'data-expand-index': expandIndex,\n 'data-separator-first': isFirstHunk ? '' : undefined,\n 'data-separator-last': isLastHunk ? '' : undefined,\n },\n });\n}\n", "import type { CodeColumnType } from '../types';\n\nexport function getHunkSeparatorSlotName(\n type: CodeColumnType,\n hunkIndex: number\n) {\n return `hunk-separator-${type}-${hunkIndex}`;\n}\n", "import type { Hunk } from '../types';\nimport { getHunkSideEndBoundary } from './getHunkSideBoundaries';\n\nexport function getTotalLineCountFromHunks(hunks: Hunk[]): number {\n const lastHunk = hunks.at(-1);\n if (lastHunk == null) {\n return 0;\n }\n return Math.max(\n getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount),\n getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount)\n );\n}\n", "import { type ChangeObject } from 'diff';\n\nimport type { DecorationItem } from '../types';\n\ninterface CreateDiffSpanDecorationProps {\n line: number;\n spanStart: number;\n spanLength: number;\n}\n\nexport function createDiffSpanDecoration({\n line,\n spanStart,\n spanLength,\n}: CreateDiffSpanDecorationProps): DecorationItem {\n return {\n start: { line, character: spanStart },\n end: { line, character: spanStart + spanLength },\n properties: { 'data-diff-span': '' },\n alwaysWrap: true,\n };\n}\n\ninterface PushOrJoinSpanProps {\n item: ChangeObject<string>;\n arr: [0 | 1, string][];\n enableJoin: boolean;\n isNeutral?: boolean;\n isLastItem?: boolean;\n}\n\n// For diff decoration spans, we want to be sure that if there is a single\n// white-space gap between diffs that we join them together into a longer diff span.\n// Spans are basically just a tuple - 1 means the content should be\n// highlighted, 0 means it should not, we still need to the span data to figure\n// out span positions\nexport function pushOrJoinSpan({\n item,\n arr,\n enableJoin,\n isNeutral = false,\n isLastItem = false,\n}: PushOrJoinSpanProps): void {\n const lastItem = arr[arr.length - 1];\n if (lastItem == null || isLastItem || !enableJoin) {\n arr.push([isNeutral ? 0 : 1, item.value]);\n return;\n }\n const isLastItemNeutral = lastItem[0] === 0;\n if (\n isNeutral === isLastItemNeutral ||\n // If we have a single space neutral item, lets join it to a previous\n // space non-neutral item to avoid single space gaps\n (isNeutral && item.value.length === 1 && !isLastItemNeutral)\n ) {\n lastItem[1] += item.value;\n return;\n }\n arr.push([isNeutral ? 0 : 1, item.value]);\n}\n", "import type {\n FileDiffMetadata,\n Hunk,\n HunkExpansionRegion,\n HunkSeparators,\n VirtualFileMetrics,\n} from '../types';\nimport { getDefaultHunkSeparatorHeight } from './computeVirtualFileMetrics';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\n\nexport interface ExpandedRegionResult {\n fromStart: number;\n fromEnd: number;\n rangeSize: number;\n collapsedLines: number;\n renderAll: boolean;\n}\n\nexport interface GetExpandedRegionProps {\n isPartial: boolean;\n rangeSize: number;\n expandedHunks: Map<number, HunkExpansionRegion> | true | undefined;\n hunkIndex: number;\n collapsedContextThreshold: number;\n}\n\nexport interface GetTrailingContextRangeSizeProps {\n fileDiff: FileDiffMetadata;\n errorPrefix: string;\n}\n\nexport interface GetTrailingExpandedRegionProps extends GetTrailingContextRangeSizeProps {\n hunkIndex: number;\n expandedHunks: GetExpandedRegionProps['expandedHunks'];\n collapsedContextThreshold: number;\n}\n\n/** One-based new-file line range covered by a hunk, as `[start, end)`. */\nexport function getHunkAdditionLineRange(hunk: Hunk): [number, number] {\n return [\n getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) + 1,\n getHunkSideEndBoundary(hunk.additionStart, hunk.additionCount) + 1,\n ];\n}\n\nexport interface HunkSeparatorLayout {\n height: number;\n gapBefore: number;\n gapAfter: number;\n totalHeight: number;\n}\n\ninterface HunkSeparatorBaseProps {\n type: HunkSeparators;\n metrics: VirtualFileMetrics;\n}\n\ninterface LeadingHunkSeparatorLayoutProps extends HunkSeparatorBaseProps {\n hunkIndex: number;\n hunkSpecs: string | undefined;\n}\n\n// Converts a collapsed unchanged range into the slices that should render near\n// the start and end of that range for the active hunk expansion state.\nexport function getExpandedRegion({\n isPartial,\n rangeSize,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n}: GetExpandedRegionProps): ExpandedRegionResult {\n const normalizedRangeSize = Math.max(rangeSize, 0);\n if (normalizedRangeSize === 0 || isPartial) {\n return {\n fromStart: 0,\n fromEnd: 0,\n rangeSize: normalizedRangeSize,\n collapsedLines: normalizedRangeSize,\n renderAll: false,\n };\n }\n\n if (\n expandedHunks === true ||\n normalizedRangeSize <= collapsedContextThreshold\n ) {\n return {\n fromStart: normalizedRangeSize,\n fromEnd: 0,\n rangeSize: normalizedRangeSize,\n collapsedLines: 0,\n renderAll: true,\n };\n }\n\n const region = expandedHunks?.get(hunkIndex);\n const fromStart = Math.min(\n Math.max(region?.fromStart ?? 0, 0),\n normalizedRangeSize\n );\n const fromEnd = Math.min(\n Math.max(region?.fromEnd ?? 0, 0),\n normalizedRangeSize\n );\n const expandedCount = fromStart + fromEnd;\n const renderAll = expandedCount >= normalizedRangeSize;\n return {\n fromStart: renderAll ? normalizedRangeSize : fromStart,\n fromEnd: renderAll ? 0 : fromEnd,\n rangeSize: normalizedRangeSize,\n collapsedLines: Math.max(normalizedRangeSize - expandedCount, 0),\n renderAll,\n };\n}\n\nexport function hasTrailingContext(fileDiff: FileDiffMetadata): boolean {\n const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];\n if (\n lastHunk == null ||\n fileDiff.isPartial ||\n fileDiff.additionLines.length === 0 ||\n fileDiff.deletionLines.length === 0\n ) {\n return false;\n }\n\n const additionRemaining =\n fileDiff.additionLines.length -\n getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount);\n const deletionRemaining =\n fileDiff.deletionLines.length -\n getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount);\n\n return additionRemaining > 0 || deletionRemaining > 0;\n}\n\n// Returns true when trailing-context line counts disagree between sides.\nexport function hasTrailingContextMismatch(\n fileDiff: FileDiffMetadata\n): boolean {\n const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];\n if (\n lastHunk == null ||\n fileDiff.isPartial ||\n fileDiff.additionLines.length === 0 ||\n fileDiff.deletionLines.length === 0\n ) {\n return false;\n }\n\n const additionRemaining =\n fileDiff.additionLines.length -\n getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount);\n const deletionRemaining =\n fileDiff.deletionLines.length -\n getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount);\n\n if (additionRemaining <= 0 && deletionRemaining <= 0) {\n return false;\n }\n\n return additionRemaining !== deletionRemaining;\n}\n\n// Measures the unchanged tail after the final hunk. Both sides must have the\n// same remaining length because trailing context represents paired lines.\nexport function getTrailingContextRangeSize({\n fileDiff,\n errorPrefix,\n}: GetTrailingContextRangeSizeProps): number {\n const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];\n if (\n lastHunk == null ||\n fileDiff.isPartial ||\n fileDiff.additionLines.length === 0 ||\n fileDiff.deletionLines.length === 0\n ) {\n return 0;\n }\n\n const additionRemaining =\n fileDiff.additionLines.length -\n getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount);\n const deletionRemaining =\n fileDiff.deletionLines.length -\n getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount);\n\n if (additionRemaining <= 0 && deletionRemaining <= 0) {\n return 0;\n }\n\n if (additionRemaining !== deletionRemaining) {\n throw new Error(\n `${errorPrefix}: trailing context mismatch (additions=${additionRemaining}, deletions=${deletionRemaining}) for ${fileDiff.name}`\n );\n }\n return Math.min(additionRemaining, deletionRemaining);\n}\n\nexport function getTrailingExpandedRegion({\n fileDiff,\n hunkIndex,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix,\n}: GetTrailingExpandedRegionProps): ExpandedRegionResult | undefined {\n if (hunkIndex !== fileDiff.hunks.length - 1) {\n return undefined;\n }\n\n const trailingRangeSize = getTrailingContextRangeSize({\n fileDiff,\n errorPrefix,\n });\n if (trailingRangeSize <= 0) {\n return undefined;\n }\n\n if (\n expandedHunks === true ||\n trailingRangeSize <= collapsedContextThreshold\n ) {\n return {\n fromStart: trailingRangeSize,\n fromEnd: 0,\n rangeSize: trailingRangeSize,\n collapsedLines: 0,\n renderAll: true,\n };\n }\n\n // The final trailing separator only exposes upward partial expansion. Treat it\n // as a bottom-only pseudo-hunk and ignore unsupported downward expansion.\n const region = expandedHunks?.get(fileDiff.hunks.length);\n const fromStart = Math.min(\n Math.max(region?.fromStart ?? 0, 0),\n trailingRangeSize\n );\n return {\n fromStart,\n fromEnd: 0,\n rangeSize: trailingRangeSize,\n collapsedLines: trailingRangeSize - fromStart,\n renderAll: fromStart >= trailingRangeSize,\n };\n}\n\nexport interface IsAdditionLineRenderableProps {\n fileDiff: FileDiffMetadata;\n /** One-based line number in the new file. */\n lineNumber: number;\n expandedHunks: Map<number, HunkExpansionRegion> | true | undefined;\n collapsedContextThreshold: number;\n}\n\n/**\n * Whether a one-based new-file line currently has (or will have on scroll) a\n * rendered row under the given expansion state — the editor-facing\n * visibility oracle. False only for lines hidden inside a collapsed\n * unchanged region; lines outside the diff's modeled range report true so\n * callers keep their existing missing-row handling. Computed from the same\n * inputs as `iterateOverDiff` so layout math and the oracle cannot diverge.\n */\nexport function isAdditionLineRenderable({\n fileDiff,\n lineNumber,\n expandedHunks,\n collapsedContextThreshold,\n}: IsAdditionLineRenderableProps): boolean {\n if (expandedHunks === true || fileDiff.isPartial) {\n return true;\n }\n\n for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {\n const [hunkStart, hunkEnd] = getHunkAdditionLineRange(hunk);\n if (lineNumber < hunkStart) {\n // Inside the collapsed gap before this hunk: renderable only within\n // the expanded slices at the gap's edges.\n const region = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const gapStart = hunkStart - region.rangeSize;\n return (\n region.renderAll ||\n lineNumber < gapStart + region.fromStart ||\n lineNumber >= hunkStart - region.fromEnd\n );\n }\n if (lineNumber < hunkEnd) {\n return true;\n }\n }\n\n const trailingRegion = getTrailingExpandedRegion({\n fileDiff,\n hunkIndex: fileDiff.hunks.length - 1,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'isAdditionLineRenderable',\n });\n if (trailingRegion == null || trailingRegion.renderAll) {\n return true;\n }\n const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];\n const [, trailingStart] = getHunkAdditionLineRange(lastHunk);\n return (\n lineNumber < trailingStart + trailingRegion.fromStart ||\n lineNumber >= trailingStart + trailingRegion.rangeSize\n );\n}\n\nexport interface GetNearestRenderableAdditionLineProps extends IsAdditionLineRenderableProps {\n direction: 'up' | 'down';\n}\n\n/**\n * The nearest renderable new-file line at or beyond `lineNumber` in the\n * given direction (one-based), or undefined when every line that way is\n * hidden inside collapsed regions. Sequential caret motion uses this to skip\n * over collapsed regions like code folds; it walks the hunk metadata once\n * instead of probing line by line across a gap.\n */\nexport function getNearestRenderableAdditionLine({\n fileDiff,\n lineNumber,\n direction,\n expandedHunks,\n collapsedContextThreshold,\n}: GetNearestRenderableAdditionLineProps): number | undefined {\n if (expandedHunks === true || fileDiff.isPartial) {\n return lineNumber;\n }\n\n // Renderable [start, end) line ranges in ascending order, plus the\n // exclusive end of the modeled range — anything past it (the editor's\n // phantom document-end line) counts as renderable.\n const ranges: Array<[start: number, end: number]> = [];\n let modeledEnd = 1;\n for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {\n const [hunkStart, hunkEnd] = getHunkAdditionLineRange(hunk);\n const region = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const gapStart = hunkStart - region.rangeSize;\n if (region.renderAll) {\n ranges.push([gapStart, hunkStart]);\n } else {\n if (region.fromStart > 0) {\n ranges.push([gapStart, gapStart + region.fromStart]);\n }\n if (region.fromEnd > 0) {\n ranges.push([hunkStart - region.fromEnd, hunkStart]);\n }\n }\n ranges.push([hunkStart, hunkEnd]);\n modeledEnd = hunkEnd;\n }\n const trailingRegion = getTrailingExpandedRegion({\n fileDiff,\n hunkIndex: fileDiff.hunks.length - 1,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'getNearestRenderableAdditionLine',\n });\n if (trailingRegion != null) {\n const trailingStart = modeledEnd;\n modeledEnd = trailingStart + trailingRegion.rangeSize;\n if (trailingRegion.renderAll) {\n ranges.push([trailingStart, modeledEnd]);\n } else if (trailingRegion.fromStart > 0) {\n ranges.push([trailingStart, trailingStart + trailingRegion.fromStart]);\n }\n }\n\n if (lineNumber >= modeledEnd) {\n return lineNumber;\n }\n if (direction === 'down') {\n for (const [start, end] of ranges) {\n if (end > lineNumber) {\n return Math.max(start, lineNumber);\n }\n }\n return undefined;\n }\n for (let index = ranges.length - 1; index >= 0; index--) {\n const [start, end] = ranges[index];\n if (start <= lineNumber) {\n return Math.min(end - 1, lineNumber);\n }\n }\n return undefined;\n}\n\nexport function getHunkSeparatorHeight({\n type,\n metrics,\n}: HunkSeparatorBaseProps): number {\n return metrics.hunkSeparatorHeight ?? getDefaultHunkSeparatorHeight(type);\n}\n\nexport function getHunkSeparatorGap({\n type,\n metrics,\n}: HunkSeparatorBaseProps): number {\n return type === 'simple' || type === 'metadata' || type === 'line-info-basic'\n ? 0\n : metrics.spacing;\n}\n\nexport function hasLeadingHunkSeparator({\n type,\n hunkIndex,\n hunkSpecs,\n}: Omit<LeadingHunkSeparatorLayoutProps, 'metrics'>): boolean {\n switch (type) {\n case 'simple':\n return hunkIndex > 0;\n case 'metadata':\n return hunkSpecs != null;\n case 'line-info':\n case 'line-info-basic':\n case 'custom':\n return true;\n }\n}\n\nexport function hasTrailingHunkSeparator(type: HunkSeparators): boolean {\n return type !== 'simple' && type !== 'metadata';\n}\n\n// Mirrors the renderer/CSS spacing rules for the separator shown before a hunk.\nexport function getLeadingHunkSeparatorLayout({\n type,\n metrics,\n hunkIndex,\n hunkSpecs,\n}: LeadingHunkSeparatorLayoutProps): HunkSeparatorLayout | undefined {\n if (!hasLeadingHunkSeparator({ type, hunkIndex, hunkSpecs })) {\n return undefined;\n }\n\n const height = getHunkSeparatorHeight({ type, metrics });\n const gap = getHunkSeparatorGap({ type, metrics });\n const gapBefore = hunkIndex > 0 ? gap : 0;\n const gapAfter = gap;\n return {\n height,\n gapBefore,\n gapAfter,\n totalHeight: gapBefore + height + gapAfter,\n };\n}\n\n// Mirrors the renderer/CSS spacing rules for the separator shown after the last\n// hunk when trailing unchanged context is collapsed.\nexport function getTrailingHunkSeparatorLayout({\n type,\n metrics,\n}: HunkSeparatorBaseProps): HunkSeparatorLayout | undefined {\n if (!hasTrailingHunkSeparator(type)) {\n return undefined;\n }\n\n const height = getHunkSeparatorHeight({ type, metrics });\n const gapBefore = getHunkSeparatorGap({ type, metrics });\n return {\n height,\n gapBefore,\n gapAfter: 0,\n totalHeight: gapBefore + height,\n };\n}\n", "import { DEFAULT_COLLAPSED_CONTEXT_THRESHOLD } from '../constants';\nimport type {\n ChangeContent,\n FileDiffMetadata,\n Hunk,\n HunkExpansionRegion,\n} from '../types';\nimport { getHunkSideStartBoundary } from './getHunkSideBoundaries';\nimport {\n getExpandedRegion,\n getTrailingExpandedRegion,\n} from './virtualDiffLayout';\n\nexport interface DiffLineMetadata {\n unifiedLineIndex: number;\n splitLineIndex: number;\n lineIndex: number;\n lineNumber: number;\n noEOFCR: boolean;\n}\n\nexport interface DiffLineCallbackBase {\n hunkIndex: number;\n hunk: Hunk | undefined; // undefined for trailing expansion region\n collapsedBefore: number; // > 0 means separator before this line, value = hidden lines\n collapsedAfter: number; // > 0 only on final line if trailing collapsed content\n}\n\ninterface DiffLineCallbackContextChange extends DiffLineCallbackBase {\n type: 'change' | 'context' | 'context-expanded';\n deletionLine: DiffLineMetadata;\n additionLine: DiffLineMetadata;\n}\n\ninterface DiffLineCallbackChangeDeletion extends DiffLineCallbackBase {\n type: 'change';\n deletionLine: DiffLineMetadata;\n additionLine?: undefined;\n}\n\ninterface DiffLineCallbackChangeAddition extends DiffLineCallbackBase {\n type: 'change';\n deletionLine?: undefined;\n additionLine: DiffLineMetadata;\n}\n\nexport type DiffLineCallbackProps =\n | DiffLineCallbackContextChange\n | DiffLineCallbackChangeDeletion\n | DiffLineCallbackChangeAddition;\n\ntype DiffStyle = 'unified' | 'split' | 'both';\n\ntype LineIterationBounds = [startIndex: number, endIndex: number];\n\ntype ChangeContentSide = 'deletions' | 'additions';\n\ntype ContextLineCallback = (index: number) => boolean | void;\n\ninterface IterationState {\n isWindowedHighlight: boolean;\n viewportStart: number;\n viewportEnd: number;\n splitCount: number;\n unifiedCount: number;\n finalHunkIndex: number;\n shouldBreak(): boolean;\n shouldSkip(unifiedHeight: number, splitHeight: number): boolean;\n incrementCounts(unifiedValue: number, splitValue: number): void;\n isInWindow(unifiedHeight: number, splitHeight: number): boolean;\n isInUnifiedWindow(height: number): boolean;\n isInSplitWindow(height: number): boolean;\n emit(props: DiffLineCallbackProps, silent?: boolean): boolean;\n}\n\ninterface IterationStartState {\n hunkIndex: number;\n splitCount: number;\n unifiedCount: number;\n}\n\ninterface HunkPrefixCounts {\n splitCount: number;\n unifiedCount: number;\n}\n\ninterface IterationStartStateProps extends Omit<\n IterateOverDiffProps,\n 'callback' | 'totalLines'\n> {\n startingLine: number;\n collapsedContextThreshold: number;\n}\n\ninterface HunkPrefixCountsProps extends Pick<\n IterationStartStateProps,\n 'diff' | 'expandedHunks' | 'collapsedContextThreshold'\n> {}\n\nexport type DiffLineCallback = (props: DiffLineCallbackProps) => boolean | void;\n\nexport interface IterateOverDiffProps {\n diff: FileDiffMetadata;\n diffStyle: DiffStyle;\n startingLine?: number;\n totalLines?: number;\n expandedHunks?: Map<number, HunkExpansionRegion> | true;\n collapsedContextThreshold?: number;\n callback: DiffLineCallback;\n}\n\nexport function iterateOverDiff({\n diff,\n diffStyle,\n startingLine = 0,\n totalLines = Infinity,\n expandedHunks,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n callback,\n}: IterateOverDiffProps): void {\n const iterationStart = getIterationStartState({\n diff,\n diffStyle,\n startingLine,\n expandedHunks,\n collapsedContextThreshold,\n });\n const state: IterationState = {\n viewportStart: startingLine,\n viewportEnd: startingLine + totalLines,\n isWindowedHighlight: startingLine > 0 || totalLines < Infinity,\n splitCount: iterationStart.splitCount,\n unifiedCount: iterationStart.unifiedCount,\n finalHunkIndex: diff.hunks.length - 1,\n shouldBreak() {\n if (!state.isWindowedHighlight) {\n return false;\n }\n\n const breakUnified = state.unifiedCount >= startingLine + totalLines;\n const breakSplit = state.splitCount >= startingLine + totalLines;\n\n if (diffStyle === 'unified') {\n return breakUnified;\n } else if (diffStyle === 'split') {\n return breakSplit;\n } else {\n return breakUnified && breakSplit;\n }\n },\n shouldSkip(unifiedCount: number, splitCount: number) {\n if (!state.isWindowedHighlight) {\n return false;\n }\n\n const skipUnified =\n unifiedCount > 0 && state.unifiedCount + unifiedCount <= startingLine;\n const skipSplit =\n splitCount > 0 && state.splitCount + splitCount <= startingLine;\n\n if (diffStyle === 'unified') {\n return skipUnified;\n } else if (diffStyle === 'split') {\n return skipSplit;\n } else {\n return skipUnified && skipSplit;\n }\n },\n incrementCounts(unifiedValue: number, splitValue: number) {\n if (diffStyle === 'unified' || diffStyle === 'both') {\n state.unifiedCount += unifiedValue;\n }\n if (diffStyle === 'split' || diffStyle === 'both') {\n state.splitCount += splitValue;\n }\n },\n isInWindow(unifiedHeight: number, splitHeight: number) {\n if (!state.isWindowedHighlight) {\n return true;\n }\n\n const unifiedInWindow = state.isInUnifiedWindow(unifiedHeight);\n const splitInWindow = state.isInSplitWindow(splitHeight);\n\n if (diffStyle === 'unified') {\n return unifiedInWindow;\n } else if (diffStyle === 'split') {\n return splitInWindow;\n } else {\n return unifiedInWindow || splitInWindow;\n }\n },\n isInUnifiedWindow(unifiedHeight: number) {\n return (\n !state.isWindowedHighlight ||\n (state.unifiedCount >= startingLine - unifiedHeight &&\n state.unifiedCount < startingLine + totalLines)\n );\n },\n isInSplitWindow(splitHeight: number) {\n return (\n !state.isWindowedHighlight ||\n (state.splitCount >= startingLine - splitHeight &&\n state.splitCount < startingLine + totalLines)\n );\n },\n emit(props: DiffLineCallbackProps, silent = false): boolean {\n if (!silent) {\n if (diffStyle === 'unified') {\n state.incrementCounts(1, 0);\n } else if (diffStyle === 'split') {\n state.incrementCounts(0, 1);\n } else {\n state.incrementCounts(1, 1);\n }\n }\n return callback(props) ?? false;\n },\n };\n\n hunkIterator: for (\n let hunkIndex = iterationStart.hunkIndex;\n hunkIndex < diff.hunks.length;\n hunkIndex++\n ) {\n const hunk = diff.hunks[hunkIndex];\n if (hunk == null) {\n throw new Error('iterateOverDiff: invalid hunk index');\n }\n if (state.shouldBreak()) {\n break;\n }\n\n const deletionBoundary = getHunkSideStartBoundary(\n hunk.deletionStart,\n hunk.deletionCount\n );\n const additionBoundary = getHunkSideStartBoundary(\n hunk.additionStart,\n hunk.additionCount\n );\n const deletionStartIndex =\n !diff.isPartial && hunk.deletionCount === 0\n ? deletionBoundary\n : hunk.deletionLineIndex;\n const additionStartIndex =\n !diff.isPartial && hunk.additionCount === 0\n ? additionBoundary\n : hunk.additionLineIndex;\n\n const leadingRegion = getExpandedRegion({\n isPartial: diff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const trailingRegion =\n hunkIndex === state.finalHunkIndex\n ? getTrailingExpandedRegion({\n fileDiff: diff,\n hunkIndex,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'iterateOverDiff',\n })\n : undefined;\n const expandedLineCount = leadingRegion.fromStart + leadingRegion.fromEnd;\n\n function getTrailingCollapsedAfter(\n unifiedLineIndex: number,\n splitLineIndex: number\n ) {\n if (\n trailingRegion == null ||\n trailingRegion.collapsedLines <= 0 ||\n trailingRegion.fromStart + trailingRegion.fromEnd > 0\n ) {\n return 0;\n }\n if (diffStyle === 'unified') {\n return unifiedLineIndex ===\n hunk.unifiedLineStart + hunk.unifiedLineCount - 1\n ? trailingRegion.collapsedLines\n : 0;\n }\n return splitLineIndex === hunk.splitLineStart + hunk.splitLineCount - 1\n ? trailingRegion.collapsedLines\n : 0;\n }\n\n let consumedCollapsed = leadingRegion.collapsedLines === 0;\n function consumePendingCollapsed() {\n if (consumedCollapsed) {\n return 0;\n }\n consumedCollapsed = true;\n return leadingRegion.collapsedLines;\n }\n\n // Emit for expanded lines\n if (!state.shouldSkip(expandedLineCount, expandedLineCount)) {\n let unifiedLineIndex = hunk.unifiedLineStart - leadingRegion.rangeSize;\n let splitLineIndex = hunk.splitLineStart - leadingRegion.rangeSize;\n\n let deletionLineIndex = deletionStartIndex - leadingRegion.rangeSize;\n let additionLineIndex = additionStartIndex - leadingRegion.rangeSize;\n let deletionLineNumber = deletionBoundary + 1 - leadingRegion.rangeSize;\n let additionLineNumber = additionBoundary + 1 - leadingRegion.rangeSize;\n\n if (\n walkContextLines(state, leadingRegion.fromStart, diffStyle, (index) => {\n return state.emit({\n hunkIndex,\n hunk: hunk,\n collapsedBefore: 0,\n collapsedAfter: 0,\n type: 'context-expanded',\n deletionLine: {\n lineNumber: deletionLineNumber + index,\n lineIndex: deletionLineIndex + index,\n noEOFCR: false,\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n },\n additionLine: {\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n lineIndex: additionLineIndex + index,\n lineNumber: additionLineNumber + index,\n noEOFCR: false,\n },\n });\n })\n ) {\n break hunkIterator;\n }\n\n unifiedLineIndex = hunk.unifiedLineStart - leadingRegion.fromEnd;\n splitLineIndex = hunk.splitLineStart - leadingRegion.fromEnd;\n\n deletionLineIndex = deletionStartIndex - leadingRegion.fromEnd;\n additionLineIndex = additionStartIndex - leadingRegion.fromEnd;\n deletionLineNumber = deletionBoundary + 1 - leadingRegion.fromEnd;\n additionLineNumber = additionBoundary + 1 - leadingRegion.fromEnd;\n if (\n walkContextLines(\n state,\n leadingRegion.fromEnd,\n diffStyle,\n (index) => {\n return state.emit({\n hunkIndex,\n hunk,\n collapsedBefore: consumePendingCollapsed(),\n collapsedAfter: 0,\n type: 'context-expanded',\n deletionLine: {\n lineNumber: deletionLineNumber + index,\n lineIndex: deletionLineIndex + index,\n noEOFCR: false,\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n },\n additionLine: {\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n lineIndex: additionLineIndex + index,\n lineNumber: additionLineNumber + index,\n noEOFCR: false,\n },\n });\n },\n () => {\n // The collapsed separator belongs before this fromEnd slice. If the\n // render window starts inside the slice, consume it with the skipped\n // rows so it is not attached to the first emitted row.\n consumePendingCollapsed();\n }\n )\n ) {\n break hunkIterator;\n }\n } else {\n state.incrementCounts(expandedLineCount, expandedLineCount);\n consumePendingCollapsed();\n }\n\n let unifiedLineIndex = hunk.unifiedLineStart;\n let splitLineIndex = hunk.splitLineStart;\n\n let deletionLineIndex = deletionStartIndex;\n let additionLineIndex = additionStartIndex;\n let deletionLineNumber = deletionBoundary + 1;\n let additionLineNumber = additionBoundary + 1;\n const lastContent = hunk.hunkContent.at(-1);\n\n for (const content of hunk.hunkContent) {\n if (state.shouldBreak()) {\n break hunkIterator;\n }\n\n const isLastContent = content === lastContent;\n\n // Hunk Context Content\n if (content.type === 'context') {\n if (!state.shouldSkip(content.lines, content.lines)) {\n if (\n walkContextLines(\n state,\n content.lines,\n diffStyle,\n (index) => {\n const isLastLine = isLastContent && index === content.lines - 1;\n const unifiedRowIndex = unifiedLineIndex + index;\n const splitRowIndex = splitLineIndex + index;\n return state.emit({\n hunkIndex,\n hunk,\n collapsedBefore: consumePendingCollapsed(),\n collapsedAfter: getTrailingCollapsedAfter(\n unifiedRowIndex,\n splitRowIndex\n ),\n type: 'context',\n deletionLine: {\n lineNumber: deletionLineNumber + index,\n lineIndex: deletionLineIndex + index,\n noEOFCR: isLastLine && hunk.noEOFCRDeletions,\n unifiedLineIndex: unifiedRowIndex,\n splitLineIndex: splitRowIndex,\n },\n additionLine: {\n unifiedLineIndex: unifiedRowIndex,\n splitLineIndex: splitRowIndex,\n lineIndex: additionLineIndex + index,\n lineNumber: additionLineNumber + index,\n noEOFCR: isLastLine && hunk.noEOFCRAdditions,\n },\n });\n },\n () => {\n // When windowing starts inside context content, the leading\n // separator was above the visible range and should not be\n // emitted on the first rendered context line.\n consumePendingCollapsed();\n }\n )\n ) {\n break hunkIterator;\n }\n } else {\n state.incrementCounts(content.lines, content.lines);\n consumePendingCollapsed();\n }\n unifiedLineIndex += content.lines;\n splitLineIndex += content.lines;\n\n deletionLineIndex += content.lines;\n additionLineIndex += content.lines;\n deletionLineNumber += content.lines;\n additionLineNumber += content.lines;\n }\n // Hunk Change Content\n else {\n const splitCount = Math.max(content.deletions, content.additions);\n const unifiedCount = content.deletions + content.additions;\n const shouldSkipChange = state.shouldSkip(unifiedCount, splitCount);\n if (!shouldSkipChange) {\n const iterationRanges = getChangeIterationRanges(\n state,\n content,\n diffStyle\n );\n const firstRangeStart = iterationRanges[0]?.[0] ?? 0;\n if (firstRangeStart > 0) {\n // Change rows can be windowed from the middle of the block too. In\n // that case the leading separator belongs to skipped rows, not to\n // the first visible deletion/addition row.\n consumePendingCollapsed();\n }\n // Change ranges are already clipped to the active window. Counts move\n // once for the whole change block after the selected rows emit.\n for (const [rangeStart, rangeEnd] of iterationRanges) {\n for (let index = rangeStart; index < rangeEnd; index++) {\n const unifiedRowIndex = unifiedLineIndex + index;\n const splitRowIndex =\n diffStyle === 'unified'\n ? splitLineIndex +\n (index < content.deletions\n ? index\n : index - content.deletions)\n : splitLineIndex + index;\n const collapsedAfter = getTrailingCollapsedAfter(\n unifiedRowIndex,\n splitRowIndex\n );\n if (\n state.emit(\n getChangeLineData({\n hunkIndex,\n hunk,\n collapsedBefore: consumePendingCollapsed(),\n collapsedAfter,\n diffStyle,\n index,\n unifiedLineIndex,\n splitLineIndex,\n additionLineIndex,\n deletionLineIndex,\n additionLineNumber,\n deletionLineNumber,\n content,\n isLastContent,\n unifiedCount,\n splitCount,\n }),\n true\n )\n ) {\n break hunkIterator;\n }\n }\n }\n }\n\n consumePendingCollapsed();\n state.incrementCounts(unifiedCount, splitCount);\n unifiedLineIndex += unifiedCount;\n splitLineIndex += splitCount;\n deletionLineIndex += content.deletions;\n additionLineIndex += content.additions;\n deletionLineNumber += content.deletions;\n additionLineNumber += content.additions;\n }\n }\n\n if (trailingRegion != null) {\n const { collapsedLines, fromStart, fromEnd } = trailingRegion;\n const len = fromStart + fromEnd;\n if (\n walkContextLines(\n state,\n len,\n diffStyle,\n (index) => {\n const isLastLine = index === len - 1;\n return state.emit({\n hunkIndex: diff.hunks.length,\n hunk: undefined,\n collapsedBefore: 0,\n collapsedAfter: isLastLine ? collapsedLines : 0,\n type: 'context-expanded',\n deletionLine: {\n lineNumber: deletionLineNumber + index,\n lineIndex: deletionLineIndex + index,\n noEOFCR: false,\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n },\n additionLine: {\n unifiedLineIndex: unifiedLineIndex + index,\n splitLineIndex: splitLineIndex + index,\n lineIndex: additionLineIndex + index,\n lineNumber: additionLineNumber + index,\n noEOFCR: false,\n },\n });\n },\n undefined,\n () => state.shouldBreak()\n )\n ) {\n break hunkIterator;\n }\n }\n }\n}\n\n// Seek the iterator to the hunk that contains `startingLine` without changing\n// the public meaning of `startingLine`: it is a dense rendered-row index, not\n// a raw split/unified line index. We first build prefix counts for each hunk\n// under the current expansion/collapse settings, binary-search those counts to\n// find the first hunk whose rendered rows cross `startingLine`, then seed the\n// running split/unified counters as if every prior hunk had already been\n// walked.\nfunction getIterationStartState({\n diff,\n diffStyle,\n startingLine,\n expandedHunks,\n collapsedContextThreshold,\n}: IterationStartStateProps): IterationStartState {\n if (startingLine <= 0 || diffStyle === 'both') {\n return { hunkIndex: 0, splitCount: 0, unifiedCount: 0 };\n }\n\n const prefixCounts = getHunkPrefixCounts({\n diff,\n expandedHunks,\n collapsedContextThreshold,\n });\n\n let low = 0;\n let high = diff.hunks.length - 1;\n let result = diff.hunks.length;\n\n while (low <= high) {\n const mid = (low + high) >> 1;\n const counts = prefixCounts[mid + 1];\n if (counts == null) {\n throw new Error('iterateOverDiff: invalid hunk prefix index');\n }\n const selectedCount =\n diffStyle === 'unified' ? counts.unifiedCount : counts.splitCount;\n\n if (selectedCount > startingLine) {\n result = mid;\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n\n if (result >= diff.hunks.length) {\n const counts = prefixCounts[diff.hunks.length];\n if (counts == null) {\n throw new Error('iterateOverDiff: invalid terminal hunk prefix index');\n }\n return {\n hunkIndex: diff.hunks.length,\n splitCount: counts.splitCount,\n unifiedCount: counts.unifiedCount,\n };\n }\n\n const counts = prefixCounts[result];\n if (counts == null) {\n throw new Error('iterateOverDiff: invalid selected hunk prefix index');\n }\n return {\n hunkIndex: result,\n splitCount: counts.splitCount,\n unifiedCount: counts.unifiedCount,\n };\n}\n\n// Build cumulative rendered-row counts at every hunk boundary for the current\n// expansion state. Entry 0 is always zero rows before the first hunk; entry N\n// is the split/unified row count after hunks [0, N). These counts let\n// getIterationStartState binary-search by dense rendered row without replaying\n// every prior hunk.\nfunction getHunkPrefixCounts({\n diff,\n expandedHunks,\n collapsedContextThreshold,\n}: HunkPrefixCountsProps): HunkPrefixCounts[] {\n let splitCount = 0;\n let unifiedCount = 0;\n const finalHunkIndex = diff.hunks.length - 1;\n const prefixCounts: HunkPrefixCounts[] = [\n {\n splitCount: 0,\n unifiedCount: 0,\n },\n ];\n\n for (let index = 0; index < diff.hunks.length; index++) {\n const hunk = diff.hunks[index];\n if (hunk == null) {\n throw new Error('iterateOverDiff: invalid hunk summary index');\n }\n\n const leadingRegion = getExpandedRegion({\n isPartial: diff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex: index,\n collapsedContextThreshold,\n });\n const leadingCount = leadingRegion.fromStart + leadingRegion.fromEnd;\n splitCount += leadingCount + hunk.splitLineCount;\n unifiedCount += leadingCount + hunk.unifiedLineCount;\n\n const trailingRegion =\n index === finalHunkIndex\n ? getTrailingExpandedRegion({\n fileDiff: diff,\n hunkIndex: index,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'iterateOverDiff',\n })\n : undefined;\n if (trailingRegion != null) {\n const trailingCount = trailingRegion.fromStart + trailingRegion.fromEnd;\n splitCount += trailingCount;\n unifiedCount += trailingCount;\n }\n\n prefixCounts.push({ splitCount, unifiedCount });\n }\n\n return prefixCounts;\n}\n\n// Clip a run of context rows to a single bounded hull around the active rendered\n// window. `diffStyle: both` can make split and unified rows visible in disjoint\n// ranges, so these bounds may include interior gaps that still need per-row\n// filtering before emitting.\nfunction getContextLineIterationBounds(\n state: IterationState,\n count: number,\n diffStyle: DiffStyle\n): LineIterationBounds {\n if (!state.isWindowedHighlight || count <= 0) {\n return [0, count];\n }\n\n const ranges: LineIterationBounds[] = [];\n function pushRange(currentCount: number): void {\n const start = Math.max(0, state.viewportStart - currentCount);\n const end = Math.min(count, state.viewportEnd - currentCount);\n if (end > start) {\n ranges.push([start, end]);\n }\n }\n\n if (diffStyle !== 'split') {\n pushRange(state.unifiedCount);\n }\n if (diffStyle !== 'unified') {\n pushRange(state.splitCount);\n }\n\n if (ranges.length === 0) {\n return [0, 0];\n }\n\n let start = ranges[0][0];\n let end = ranges[0][1];\n for (let index = 1; index < ranges.length; index++) {\n const range = ranges[index];\n start = Math.min(start, range[0]);\n end = Math.max(end, range[1]);\n }\n return [start, end];\n}\n\n// Walk context rows through the active window while keeping split and\n// unified counters aligned. The callback only runs after the final per-row\n// window check, which keeps `diffStyle: both` gap rows from being emitted.\nfunction walkContextLines(\n state: IterationState,\n count: number,\n diffStyle: DiffStyle,\n callback: ContextLineCallback,\n onSkippedStart?: () => void,\n shouldBreak?: () => boolean\n): boolean {\n const [startIndex, endIndex] = getContextLineIterationBounds(\n state,\n count,\n diffStyle\n );\n if (startIndex > 0) {\n state.incrementCounts(startIndex, startIndex);\n onSkippedStart?.();\n }\n\n let index = startIndex;\n while (index < count) {\n if (shouldBreak?.() === true) {\n return true;\n }\n if (index >= endIndex) {\n state.incrementCounts(count - index, count - index);\n break;\n }\n if (state.isInWindow(0, 0)) {\n if (callback(index) === true) {\n return true;\n }\n } else {\n state.incrementCounts(1, 1);\n }\n index++;\n }\n\n return false;\n}\n\n// Clip a change block to the rows that can be visible in the active coordinate\n// space. `diffStyle: both` iterates in split row space, but includes the unified\n// ranges too so either view can render the visible change rows it needs.\nfunction getChangeIterationRanges(\n state: IterationState,\n content: ChangeContent,\n diffStyle: DiffStyle\n): LineIterationBounds[] {\n // If not a window highlight, then we should just render the entire range\n if (!state.isWindowedHighlight) {\n return [\n [\n 0,\n diffStyle === 'unified'\n ? content.deletions + content.additions\n : Math.max(content.deletions, content.additions),\n ],\n ];\n }\n const useUnified = diffStyle !== 'split';\n const useSplit = diffStyle !== 'unified';\n const iterationSpace = diffStyle === 'unified' ? 'unified' : 'split';\n const iterationRanges: LineIterationBounds[] = [];\n function getVisibleRange(\n start: number,\n count: number\n ): LineIterationBounds | undefined {\n const end = start + count;\n if (end <= state.viewportStart || start >= state.viewportEnd) {\n return undefined;\n }\n const visibleStart = Math.max(0, state.viewportStart - start);\n const visibleEnd = Math.min(count, state.viewportEnd - start);\n return visibleEnd > visibleStart ? [visibleStart, visibleEnd] : undefined;\n }\n function mapRangeToIteration(\n range: LineIterationBounds,\n kind: ChangeContentSide\n ): LineIterationBounds {\n if (iterationSpace === 'split') {\n // For split iteration, additions/deletions are already in split row space.\n return range;\n }\n return kind === 'additions'\n ? [range[0] + content.deletions, range[1] + content.deletions]\n : range;\n }\n function pushRange(\n range: LineIterationBounds | undefined,\n kind: ChangeContentSide\n ) {\n if (range == null) {\n return;\n }\n const [start, end] = mapRangeToIteration(range, kind);\n if (end > start) {\n iterationRanges.push([start, end]);\n }\n }\n\n if (useUnified) {\n pushRange(\n getVisibleRange(state.unifiedCount, content.deletions),\n 'deletions'\n );\n pushRange(\n getVisibleRange(\n state.unifiedCount + content.deletions,\n content.additions\n ),\n 'additions'\n );\n }\n\n if (useSplit) {\n pushRange(\n getVisibleRange(state.splitCount, content.deletions),\n 'deletions'\n );\n pushRange(\n getVisibleRange(state.splitCount, content.additions),\n 'additions'\n );\n }\n\n if (iterationRanges.length === 0) {\n return iterationRanges;\n }\n\n iterationRanges.sort((a, b) => a[0] - b[0]);\n const merged: LineIterationBounds[] = [iterationRanges[0]];\n for (const [start, end] of iterationRanges.slice(1)) {\n const last = merged[merged.length - 1];\n if (start <= last[1]) {\n last[1] = Math.max(last[1], end);\n } else {\n merged.push([start, end]);\n }\n }\n\n return merged;\n}\n\ninterface GetChangeLineDataProps {\n hunkIndex: number;\n hunk: Hunk;\n collapsedBefore: number;\n collapsedAfter: number;\n diffStyle: DiffStyle;\n index: number;\n unifiedLineIndex: number;\n splitLineIndex: number;\n additionLineIndex: number;\n additionLineNumber: number;\n deletionLineNumber: number;\n deletionLineIndex: number;\n content: ChangeContent;\n isLastContent: boolean;\n unifiedCount: number;\n splitCount: number;\n}\n\n// Build the callback payload for one change row, mapping the selected row index\n// into split/unified coordinates and addition/deletion line metadata.\nfunction getChangeLineData({\n hunkIndex,\n hunk,\n collapsedAfter,\n collapsedBefore,\n diffStyle,\n index,\n unifiedLineIndex,\n splitLineIndex,\n additionLineIndex,\n deletionLineIndex,\n additionLineNumber,\n deletionLineNumber,\n content,\n isLastContent,\n unifiedCount,\n splitCount,\n}: GetChangeLineDataProps): DiffLineCallbackProps {\n const unifiedDeletionLineIndex =\n index < content.deletions ? unifiedLineIndex + index : undefined;\n const unifiedAdditionLineIndex =\n diffStyle === 'unified'\n ? index >= content.deletions\n ? unifiedLineIndex + index\n : undefined\n : index < content.additions\n ? unifiedLineIndex + content.deletions + index\n : undefined;\n\n const resolvedSplitLineIndex =\n diffStyle === 'unified'\n ? splitLineIndex +\n (index < content.deletions ? index : index - content.deletions)\n : splitLineIndex + index;\n\n const deletionLineIndexValue =\n index < content.deletions ? deletionLineIndex + index : undefined;\n const deletionLineNumberValue =\n index < content.deletions ? deletionLineNumber + index : undefined;\n const additionLineIndexValue =\n diffStyle === 'unified'\n ? index >= content.deletions\n ? additionLineIndex + (index - content.deletions)\n : undefined\n : index < content.additions\n ? additionLineIndex + index\n : undefined;\n const additionLineNumberValue =\n diffStyle === 'unified'\n ? index >= content.deletions\n ? additionLineNumber + (index - content.deletions)\n : undefined\n : index < content.additions\n ? additionLineNumber + index\n : undefined;\n\n const noEOFCRDeletion =\n diffStyle === 'unified'\n ? isLastContent &&\n index === content.deletions - 1 &&\n hunk.noEOFCRDeletions\n : isLastContent && index === splitCount - 1 && hunk.noEOFCRDeletions;\n const noEOFCRAddition =\n diffStyle === 'unified'\n ? isLastContent && index === unifiedCount - 1 && hunk.noEOFCRAdditions\n : isLastContent && index === splitCount - 1 && hunk.noEOFCRAdditions;\n\n const deletionLine: DiffLineMetadata | undefined =\n deletionLineIndexValue != null &&\n deletionLineNumberValue != null &&\n unifiedDeletionLineIndex != null\n ? {\n lineNumber: deletionLineNumberValue,\n lineIndex: deletionLineIndexValue,\n noEOFCR: noEOFCRDeletion,\n unifiedLineIndex: unifiedDeletionLineIndex,\n splitLineIndex: resolvedSplitLineIndex,\n }\n : undefined;\n const additionLine: DiffLineMetadata | undefined =\n additionLineIndexValue != null &&\n additionLineNumberValue != null &&\n unifiedAdditionLineIndex != null\n ? {\n unifiedLineIndex: unifiedAdditionLineIndex,\n splitLineIndex: resolvedSplitLineIndex,\n lineIndex: additionLineIndexValue,\n lineNumber: additionLineNumberValue,\n noEOFCR: noEOFCRAddition,\n }\n : undefined;\n\n if (deletionLine == null && additionLine != null) {\n return {\n type: 'change',\n hunkIndex,\n hunk,\n collapsedAfter,\n collapsedBefore,\n deletionLine: undefined,\n additionLine,\n };\n } else if (deletionLine != null && additionLine == null) {\n return {\n type: 'change',\n hunkIndex,\n hunk,\n collapsedAfter,\n collapsedBefore,\n deletionLine,\n additionLine: undefined,\n };\n }\n\n if (deletionLine == null || additionLine == null) {\n throw new Error('iterateOverDiff: missing change line data');\n }\n\n return {\n type: 'change',\n hunkIndex,\n hunk,\n collapsedAfter,\n collapsedBefore,\n deletionLine,\n additionLine,\n };\n}\n", "import { type ChangeObject, diffChars, diffWordsWithSpace } from 'diff';\n\nimport { DEFAULT_COLLAPSED_CONTEXT_THRESHOLD } from '../constants';\nimport type {\n DecorationItem,\n DiffsHighlighter,\n FileContents,\n FileDiffMetadata,\n ForceDiffPlainTextOptions,\n LineDiffTypes,\n LineInfo,\n RenderDiffFilesResult,\n RenderDiffOptions,\n SupportedLanguages,\n ThemedDiffResult,\n} from '../types';\nimport { appendItems } from './appendItems';\nimport { cleanLastNewline } from './cleanLastNewline';\nimport { getFiletypeFromFileName } from './getFiletypeFromFileName';\nimport { getHighlighterThemeStyles } from './getHighlighterThemeStyles';\nimport { getTokenOptions } from './getTokenOptions';\nimport { iterateOverDiff } from './iterateOverDiff';\nimport {\n createDiffSpanDecoration,\n pushOrJoinSpan,\n} from './parseDiffDecorations';\nimport { renderTokenLines } from './renderTokenLines';\nimport { setDeferredArrayItem } from './setDeferredArrayItem';\n\nconst DEFAULT_PLAIN_TEXT_OPTIONS: ForceDiffPlainTextOptions = {\n forcePlainText: false,\n};\n\nexport function renderDiffWithHighlighter(\n diff: FileDiffMetadata,\n highlighter: DiffsHighlighter,\n options: RenderDiffOptions,\n {\n forcePlainText,\n lazyLineAST = false,\n startingLine,\n totalLines,\n expandedHunks,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n }: ForceDiffPlainTextOptions = DEFAULT_PLAIN_TEXT_OPTIONS\n): ThemedDiffResult {\n if (forcePlainText) {\n startingLine ??= 0;\n totalLines ??= Infinity;\n } else {\n // Tokenization must include preceding lines to preserve lexical state.\n startingLine = 0;\n totalLines = Infinity;\n }\n const isWindowedHighlight = startingLine > 0 || totalLines < Infinity;\n lazyLineAST &&= !forcePlainText && !options.useTokenTransformer;\n const baseThemeType =\n typeof options.theme === 'string'\n ? highlighter.getTheme(options.theme).type\n : undefined;\n const themeStyles = getHighlighterThemeStyles({\n theme: options.theme,\n highlighter,\n });\n\n // If we have a large file and we are rendering the WHOLE plain diff ast,\n // then we should remove the lineDiffType to make sure things render quickly.\n // For highlighted ASTs or windowed highlights, we should just inherit the\n // setting\n const lineDiffType =\n forcePlainText &&\n !isWindowedHighlight &&\n (diff.unifiedLineCount > 1000 || diff.splitLineCount > 1000)\n ? 'none'\n : options.lineDiffType;\n\n const code: RenderDiffFilesResult = {\n deletionLines: [],\n additionLines: [],\n };\n\n const { maxLineDiffLength } = options;\n const shouldGroupAll = !forcePlainText && !diff.isPartial;\n const expandedHunksForIteration = forcePlainText ? expandedHunks : undefined;\n const buckets = new Map<number, RenderBucket>();\n function getBucketForHunk(hunkIndex: number) {\n const index = shouldGroupAll ? 0 : hunkIndex;\n const bucket = buckets.get(index) ?? createBucket();\n buckets.set(index, bucket);\n return bucket;\n }\n\n function appendContent(\n lineContent: string,\n lineIndex: number,\n segments: HighlightSegment[],\n contentWrapper: FakeArrayType\n ) {\n if (isWindowedHighlight) {\n let segment = segments.at(-1);\n if (\n segment == null ||\n segment.targetIndex + segment.count !== lineIndex\n ) {\n segment = {\n targetIndex: lineIndex,\n originalOffset: contentWrapper.length,\n count: 0,\n };\n segments.push(segment);\n }\n segment.count++;\n }\n contentWrapper.push(lineContent);\n }\n\n iterateOverDiff({\n diff,\n diffStyle: 'both',\n startingLine,\n totalLines,\n expandedHunks: isWindowedHighlight ? expandedHunksForIteration : true,\n collapsedContextThreshold,\n callback: ({ hunkIndex, additionLine, deletionLine, type }) => {\n const bucket = getBucketForHunk(hunkIndex);\n const splitLineIndex =\n additionLine != null\n ? additionLine.splitLineIndex\n : deletionLine.splitLineIndex;\n\n if (type === 'change' && additionLine != null && deletionLine != null) {\n computeLineDiffDecorations({\n additionLine: diff.additionLines[additionLine.lineIndex],\n deletionLine: diff.deletionLines[deletionLine.lineIndex],\n deletionLineIndex: bucket.deletionContent.length,\n additionLineIndex: bucket.additionContent.length,\n deletionDecorations: bucket.deletionDecorations,\n additionDecorations: bucket.additionDecorations,\n lineDiffType,\n maxLineDiffLength,\n });\n }\n\n if (deletionLine != null) {\n appendContent(\n diff.deletionLines[deletionLine.lineIndex],\n deletionLine.lineIndex,\n bucket.deletionSegments,\n bucket.deletionContent\n );\n bucket.deletionInfo.push({\n type: type === 'change' ? 'change-deletion' : type,\n lineNumber: deletionLine.lineNumber,\n altLineNumber:\n type === 'change'\n ? undefined\n : (additionLine.lineNumber ?? undefined),\n lineIndex: `${deletionLine.unifiedLineIndex},${splitLineIndex}`,\n });\n }\n\n if (additionLine != null) {\n appendContent(\n diff.additionLines[additionLine.lineIndex],\n additionLine.lineIndex,\n bucket.additionSegments,\n bucket.additionContent\n );\n bucket.additionInfo.push({\n type: type === 'change' ? 'change-addition' : type,\n lineNumber: additionLine.lineNumber,\n altLineNumber:\n type === 'change'\n ? undefined\n : (deletionLine.lineNumber ?? undefined),\n lineIndex: `${additionLine.unifiedLineIndex},${splitLineIndex}`,\n });\n }\n },\n });\n\n for (const bucket of buckets.values()) {\n if (\n bucket.deletionContent.length === 0 &&\n bucket.additionContent.length === 0\n ) {\n continue;\n }\n\n const deletionFile = {\n name: diff.prevName ?? diff.name,\n contents: bucket.deletionContent.value,\n };\n const additionFile = {\n name: diff.name,\n contents: bucket.additionContent.value,\n };\n const { deletionLines, additionLines } = renderTwoFiles({\n deletionFile,\n deletionInfo: bucket.deletionInfo,\n deletionDecorations: bucket.deletionDecorations,\n\n additionFile,\n additionInfo: bucket.additionInfo,\n additionDecorations: bucket.additionDecorations,\n\n highlighter,\n options,\n languageOverride: forcePlainText ? 'text' : diff.lang,\n lazyLineAST,\n });\n\n if (shouldGroupAll) {\n code.deletionLines = deletionLines;\n code.additionLines = additionLines;\n continue;\n }\n\n for (const [target, lines, segments] of [\n [code.deletionLines, deletionLines, bucket.deletionSegments],\n [code.additionLines, additionLines, bucket.additionSegments],\n ] as const) {\n if (segments.length > 0) {\n for (const segment of segments) {\n for (let index = 0; index < segment.count; index++) {\n target[segment.targetIndex + index] =\n lines[segment.originalOffset + index];\n }\n }\n } else if (lazyLineAST) {\n const offset = target.length;\n for (let index = 0; index < lines.length; index++) {\n setDeferredArrayItem(target, offset + index, () => lines[index]);\n }\n } else {\n appendItems(target, lines);\n }\n }\n }\n\n return { code, themeStyles, baseThemeType };\n}\n\n// The line indexes and decoration arrays a line diff writes its highlights to\ninterface LineDiffDecorationTargets {\n deletionLineIndex: number;\n additionLineIndex: number;\n deletionDecorations: DecorationItem[];\n additionDecorations: DecorationItem[];\n}\n\ninterface ProcessLineDiffProps extends LineDiffDecorationTargets {\n deletionLine: string | undefined;\n additionLine: string | undefined;\n lineDiffType: LineDiffTypes;\n maxLineDiffLength: number;\n}\n\n// Push one decoration per side covering the first through last changed\n// token, so each line only has one highlight. Offsets come straight from the\n// diff items, skipping the span arrays the other word modes build.\nfunction pushWordLineDecorations(\n lineDiff: ChangeObject<string>[],\n {\n deletionLineIndex,\n additionLineIndex,\n deletionDecorations,\n additionDecorations,\n }: LineDiffDecorationTargets\n): void {\n let deletionOffset = 0;\n let additionOffset = 0;\n let deletionStart = -1;\n let deletionEnd = 0;\n let additionStart = -1;\n let additionEnd = 0;\n for (const { value, added, removed } of lineDiff) {\n if (removed) {\n if (deletionStart === -1) deletionStart = deletionOffset;\n deletionOffset += value.length;\n deletionEnd = deletionOffset;\n } else if (added) {\n if (additionStart === -1) additionStart = additionOffset;\n additionOffset += value.length;\n additionEnd = additionOffset;\n } else {\n deletionOffset += value.length;\n additionOffset += value.length;\n }\n }\n if (deletionStart !== -1) {\n deletionDecorations.push(\n createDiffSpanDecoration({\n line: deletionLineIndex,\n spanStart: deletionStart,\n spanLength: deletionEnd - deletionStart,\n })\n );\n }\n if (additionStart !== -1) {\n additionDecorations.push(\n createDiffSpanDecoration({\n line: additionLineIndex,\n spanStart: additionStart,\n spanLength: additionEnd - additionStart,\n })\n );\n }\n}\n\nfunction computeLineDiffDecorations({\n deletionLine,\n additionLine,\n deletionLineIndex,\n additionLineIndex,\n deletionDecorations,\n additionDecorations,\n lineDiffType,\n maxLineDiffLength,\n}: ProcessLineDiffProps) {\n if (deletionLine == null || additionLine == null || lineDiffType === 'none') {\n return;\n }\n deletionLine = cleanLastNewline(deletionLine);\n additionLine = cleanLastNewline(additionLine);\n // If we have really long lines, we probably shouldn't compute diffs on them.\n if (\n deletionLine.length > maxLineDiffLength ||\n additionLine.length > maxLineDiffLength\n ) {\n return;\n }\n // NOTE(amadeus): Because we visually trim trailing newlines when rendering,\n // we also gotta make sure the diff parsing doesn't include the newline\n // character that could be there...\n const lineDiff =\n lineDiffType === 'char'\n ? diffChars(deletionLine, additionLine)\n : diffWordsWithSpace(deletionLine, additionLine);\n if (lineDiffType === 'word-line') {\n pushWordLineDecorations(lineDiff, {\n deletionLineIndex,\n additionLineIndex,\n deletionDecorations,\n additionDecorations,\n });\n return;\n }\n const deletionSpans: [0 | 1, string][] = [];\n const additionSpans: [0 | 1, string][] = [];\n const enableJoin = lineDiffType === 'word-alt';\n const lastItem = lineDiff.at(-1);\n for (const item of lineDiff) {\n const isLastItem = item === lastItem;\n if (!item.added && !item.removed) {\n pushOrJoinSpan({\n item,\n arr: deletionSpans,\n enableJoin,\n isNeutral: true,\n isLastItem,\n });\n pushOrJoinSpan({\n item,\n arr: additionSpans,\n enableJoin,\n isNeutral: true,\n isLastItem,\n });\n } else if (item.removed) {\n pushOrJoinSpan({ item, arr: deletionSpans, enableJoin, isLastItem });\n } else {\n pushOrJoinSpan({ item, arr: additionSpans, enableJoin, isLastItem });\n }\n }\n let spanIndex = 0;\n for (const span of deletionSpans) {\n if (span[0] === 1) {\n deletionDecorations.push(\n createDiffSpanDecoration({\n line: deletionLineIndex,\n spanStart: spanIndex,\n spanLength: span[1].length,\n })\n );\n }\n spanIndex += span[1].length;\n }\n spanIndex = 0;\n for (const span of additionSpans) {\n if (span[0] === 1) {\n additionDecorations.push(\n createDiffSpanDecoration({\n line: additionLineIndex,\n spanStart: spanIndex,\n spanLength: span[1].length,\n })\n );\n }\n spanIndex += span[1].length;\n }\n}\n\ninterface HighlightSegment {\n // The where the highlighted region starts\n originalOffset: number;\n // Where to place the highlighted line in RenderDiffFilesResult\n targetIndex: number;\n // Number of highlighted lines\n count: number;\n}\n\ninterface FakeArrayType {\n push(value: string): void;\n value: string;\n length: number;\n}\n\ninterface RenderBucket {\n deletionContent: FakeArrayType;\n additionContent: FakeArrayType;\n deletionInfo: (LineInfo | undefined)[];\n additionInfo: (LineInfo | undefined)[];\n deletionDecorations: DecorationItem[];\n additionDecorations: DecorationItem[];\n deletionSegments: HighlightSegment[];\n additionSegments: HighlightSegment[];\n}\n\nfunction createBucket(): RenderBucket {\n return {\n deletionContent: {\n push(value: string) {\n this.value += value;\n this.length++;\n },\n value: '',\n length: 0,\n },\n additionContent: {\n push(value: string) {\n this.value += value;\n this.length++;\n },\n value: '',\n length: 0,\n },\n deletionInfo: [],\n additionInfo: [],\n deletionDecorations: [],\n additionDecorations: [],\n deletionSegments: [],\n additionSegments: [],\n };\n}\n\ninterface RenderTwoFilesProps {\n lazyLineAST: boolean;\n deletionFile: FileContents;\n additionFile: FileContents;\n deletionInfo: (LineInfo | undefined)[];\n additionInfo: (LineInfo | undefined)[];\n deletionDecorations: DecorationItem[];\n additionDecorations: DecorationItem[];\n options: RenderDiffOptions;\n highlighter: DiffsHighlighter;\n languageOverride: SupportedLanguages | undefined;\n}\n\nfunction renderTwoFiles({\n lazyLineAST,\n deletionFile,\n additionFile,\n deletionInfo,\n additionInfo,\n highlighter,\n deletionDecorations,\n additionDecorations,\n languageOverride,\n options: { theme, useTokenTransformer, tokenizeMaxLineLength },\n}: RenderTwoFilesProps): RenderDiffFilesResult {\n const renderFile = (\n file: FileContents,\n lineInfo: (LineInfo | undefined)[],\n decorations: DecorationItem[]\n ): RenderDiffFilesResult['additionLines'] => {\n if (file.contents === '') return [];\n return renderTokenLines(\n highlighter.codeToTokens(\n cleanLastNewline(file.contents),\n getTokenOptions(\n languageOverride ?? getFiletypeFromFileName(file.name),\n theme,\n tokenizeMaxLineLength\n )\n ).tokens,\n {\n state: { lineInfo },\n useTokenTransformer,\n decorations,\n lazyLineAST,\n cacheHtmlStyles: highlighter.name === 'highlights',\n }\n );\n };\n\n return {\n deletionLines: renderFile(deletionFile, deletionInfo, deletionDecorations),\n additionLines: renderFile(additionFile, additionInfo, additionDecorations),\n };\n}\n", "import type { CreatePatchOptionsNonabortable } from 'diff';\n\nimport type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n} from '../types';\nimport { cleanLastNewline } from './cleanLastNewline';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\nimport { parseDiffFromFile } from './parseDiffFromFile';\nimport { hasTrailingContextMismatch } from './virtualDiffLayout';\n\ntype HunkContent = ContextContent | ChangeContent;\n\ntype HunkMetadataUpdate = Pick<\n FileDiffMetadata,\n 'hunks' | 'splitLineCount' | 'unifiedLineCount' | 'type'\n>;\n\ntype FullDiffHunkUpdate = HunkMetadataUpdate &\n Pick<\n FileDiffMetadata,\n | 'additionLines'\n | 'deletionLines'\n | 'additionCharacterCount'\n | 'deletionCharacterCount'\n >;\n\n/** Rebuilds all hunk metadata from the current deletion/addition line arrays. */\nexport function recomputeDiffHunks(\n diff: FileDiffMetadata,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): FullDiffHunkUpdate {\n const recomputed = parseDiffFromFile(\n {\n name: diff.prevName ?? diff.name,\n contents: diff.deletionLines.join(''),\n },\n {\n name: diff.name,\n contents: diff.additionLines.join(''),\n lang: diff.lang,\n },\n parseDiffOptions\n );\n return {\n hunks: recomputed.hunks,\n splitLineCount: recomputed.splitLineCount,\n unifiedLineCount: recomputed.unifiedLineCount,\n additionLines: recomputed.additionLines,\n deletionLines: recomputed.deletionLines,\n additionCharacterCount: recomputed.additionCharacterCount,\n deletionCharacterCount: recomputed.deletionCharacterCount,\n type: recomputed.type,\n };\n}\n\n// Builds placeholder addition contents that diff as one top-aligned change row per\n// line. Bare `\\\\n` sentinels align as context against the first deletion lines,\n// which pushes the real addition rows down in split view.\nfunction buildTopAlignedAdditionSentinel(\n lineCount: number,\n deletionContents: string\n): string {\n const count = Math.max(lineCount, 1);\n let sentinel = Array.from(\n { length: count },\n (_, index) => `${' '.repeat(index + 1)}\\n`\n ).join('');\n if (sentinel === deletionContents) {\n sentinel = Array.from(\n { length: count },\n (_, index) => `\\u0000${' '.repeat(index)}\\n`\n ).join('');\n }\n return sentinel;\n}\n\nfunction hasOnlyBlankAdditionContents(additionLines: string[]): boolean {\n for (const line of additionLines) {\n if (line.trim().length > 0) {\n return false;\n }\n }\n return true;\n}\n\n// After delete-all the editable side is blank and much shorter than the deletion\n// side. A normal recompute can still treat newline-only additions as context and\n// render the first editable row deep in split view instead of at the top.\nexport function shouldTopAlignAdditionRecompute(\n diff: FileDiffMetadata,\n additionLines: string[]\n): boolean {\n return (\n additionLines.length > 0 &&\n additionLines.length < diff.deletionLines.length &&\n hasOnlyBlankAdditionContents(additionLines)\n );\n}\n\n// Rebuilds hunk metadata while keeping the editable addition rows top-aligned in\n// split view. The sentinel only shapes hunks; the caller's addition lines are\n// preserved so the editor document stays the source of truth.\nexport function recomputeTopAlignedAdditionDiff(\n diff: FileDiffMetadata,\n additionLines: string[],\n additionCharacterCount: number,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): FullDiffHunkUpdate {\n const deletionContents = diff.deletionLines.join('');\n const additionSentinel = buildTopAlignedAdditionSentinel(\n additionLines.length,\n deletionContents\n );\n const recomputed = parseDiffFromFile(\n {\n name: diff.prevName ?? diff.name,\n contents: deletionContents,\n },\n {\n name: diff.name,\n contents: additionSentinel,\n lang: diff.lang,\n },\n parseDiffOptions\n );\n return {\n hunks: recomputed.hunks,\n splitLineCount: recomputed.splitLineCount,\n unifiedLineCount: recomputed.unifiedLineCount,\n additionLines,\n deletionLines: recomputed.deletionLines,\n additionCharacterCount,\n deletionCharacterCount: recomputed.deletionCharacterCount,\n type: recomputed.type,\n };\n}\n\n// Rebuilds hunk metadata when the editable side has been emptied of all text.\n//\n// The editor always keeps one (empty) line for an empty document, but an empty\n// string splits into zero addition lines, so a normal recompute produces a diff\n// with no addition rows at all. Rendering that leaves the attached editor with\n// no line element to host its caret.\nexport function recomputeEmptyDocumentDiff(\n diff: FileDiffMetadata,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): FullDiffHunkUpdate {\n return recomputeTopAlignedAdditionDiff(diff, [''], 0, parseDiffOptions);\n}\n\n/** Rebuilds diff hunks after an edit, top-aligning sparse addition sides when needed. */\nexport function recomputeDiffHunksForEdit(\n diff: FileDiffMetadata,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): FullDiffHunkUpdate {\n if (diff.additionLines.length === 0) {\n return recomputeEmptyDocumentDiff(diff, parseDiffOptions);\n }\n if (shouldTopAlignAdditionRecompute(diff, diff.additionLines)) {\n return recomputeTopAlignedAdditionDiff(\n diff,\n diff.additionLines,\n diff.additionCharacterCount,\n parseDiffOptions\n );\n }\n const additionLines = diff.additionLines;\n const recomputed = recomputeDiffHunks(diff, parseDiffOptions);\n preserveTrailingEditorBlankLine(recomputed, additionLines);\n return recomputed;\n}\n\nfunction hasTrailingEditorBlankLine(additionLines: string[]): boolean {\n return additionLines.length > 1 && additionLines.at(-1) === '';\n}\n\n// Re-adds the editor's phantom trailing empty line (a document ending in a\n// newline exposes one extra empty line) as an addition row when the last\n// hunk's final change block can absorb it, so the caret keeps a rendered row.\nexport function preserveTrailingEditorBlankLine(\n recomputed: Pick<\n FullDiffHunkUpdate,\n 'hunks' | 'additionLines' | 'splitLineCount' | 'unifiedLineCount'\n >,\n additionLines: string[]\n): void {\n if (!hasTrailingEditorBlankLine(additionLines)) {\n return;\n }\n const extraLineCount = additionLines.length - recomputed.additionLines.length;\n if (extraLineCount <= 0) {\n return;\n }\n const extraAdditionLineIndex = recomputed.additionLines.length;\n\n const lastHunk = recomputed.hunks.at(-1);\n if (lastHunk == null) {\n return;\n }\n\n const lastHunkAdditionEnd = getHunkSideEndBoundary(\n lastHunk.additionStart,\n lastHunk.additionCount\n );\n if (lastHunkAdditionEnd !== extraAdditionLineIndex) {\n return;\n }\n\n for (const content of lastHunk.hunkContent) {\n if (\n content.type === 'change' &&\n content.additions < content.deletions &&\n content.additionLineIndex + content.additions === extraAdditionLineIndex\n ) {\n recomputed.additionLines = additionLines;\n content.additions += extraLineCount;\n lastHunk.additionCount += extraLineCount;\n lastHunk.additionLines += extraLineCount;\n recomputeDiffRenderLineCounts(recomputed);\n return;\n }\n }\n}\n\n/** Updates hunk metadata after addition lines change; re-parses affected hunks only. */\nexport function updateDiffHunks(\n diff: FileDiffMetadata,\n changedAdditionLineIndexes: Iterable<number>,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): HunkMetadataUpdate {\n if (diff.isPartial) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n\n if (diff.deletionLines.length !== diff.additionLines.length) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n\n const changedLines = Array.from(changedAdditionLineIndexes);\n if (changedLines.length === 0) {\n return applyHunkUpdateResult(diff, {\n hunks: diff.hunks,\n splitLineCount: diff.splitLineCount,\n unifiedLineCount: diff.unifiedLineCount,\n type: diff.type,\n });\n }\n for (const line of changedLines) {\n const additionLine = diff.additionLines[line];\n const deletionLine = diff.deletionLines[line];\n if (additionLine == null || deletionLine == null) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n // Restoring a line to the old side can merge/split hunks across context windows.\n if (cleanLastNewline(additionLine) === cleanLastNewline(deletionLine)) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n }\n\n const affectedHunkIndexes = getAffectedHunkIndexes(diff, changedLines);\n if (affectedHunkIndexes.size === 0) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n\n for (const hunkIndex of affectedHunkIndexes) {\n const updated = reparseHunkRegion(diff, hunkIndex, parseDiffOptions);\n if (!updated) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n }\n\n recomputeDiffRenderLineCounts(diff);\n\n if (hasTrailingContextMismatch(diff)) {\n return applyHunkUpdateResult(\n diff,\n recomputeDiffHunks(diff, parseDiffOptions)\n );\n }\n\n return applyHunkUpdateResult(diff, {\n hunks: diff.hunks,\n splitLineCount: diff.splitLineCount,\n unifiedLineCount: diff.unifiedLineCount,\n type: diff.type,\n });\n}\n\nfunction applyHunkUpdateResult<T extends HunkMetadataUpdate>(\n diff: FileDiffMetadata,\n result: T\n): T {\n Object.assign(diff, result);\n return result;\n}\n\nfunction getAffectedHunkIndexes(\n diff: FileDiffMetadata,\n changedAdditionLineIndexes: Iterable<number>\n): Set<number> {\n const indexes = new Set<number>();\n for (const line of changedAdditionLineIndexes) {\n const hunkIndex = findHunkIndexForAdditionLine(diff, line);\n if (hunkIndex == null) {\n return new Set();\n }\n indexes.add(hunkIndex);\n }\n return indexes;\n}\n\nfunction findHunkIndexForAdditionLine(\n diff: FileDiffMetadata,\n line: number\n): number | undefined {\n for (const [hunkIndex, hunk] of diff.hunks.entries()) {\n const end = hunk.additionLineIndex + hunk.additionCount;\n if (line >= hunk.additionLineIndex && line < end) {\n return hunkIndex;\n }\n }\n return undefined;\n}\n\nfunction reparseHunkRegion(\n diff: FileDiffMetadata,\n hunkIndex: number,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): boolean {\n const hunk = diff.hunks[hunkIndex];\n if (hunk == null) {\n return false;\n }\n\n const deletionSlice = diff.deletionLines.slice(\n hunk.deletionLineIndex,\n hunk.deletionLineIndex + hunk.deletionCount\n );\n const additionSlice = diff.additionLines.slice(\n hunk.additionLineIndex,\n hunk.additionLineIndex + hunk.additionCount\n );\n\n const reparsed = parseDiffFromFile(\n {\n name: diff.prevName ?? diff.name,\n contents: deletionSlice.join(''),\n },\n {\n name: diff.name,\n contents: additionSlice.join(''),\n lang: diff.lang,\n },\n { ...parseDiffOptions, context: 0 }\n );\n\n const reparsedHunk = reparsed.hunks[0];\n if (reparsedHunk == null || reparsed.hunks.length !== 1) {\n return false;\n }\n\n applyReparsedHunk(hunk, reparsedHunk);\n syncHunkNoEOFCRFromFullFile(diff, hunkIndex);\n return true;\n}\n\nexport function syncHunkNoEOFCRFromFullFile(\n diff: FileDiffMetadata,\n hunkIndex: number\n): void {\n const hunk = diff.hunks[hunkIndex];\n if (hunk == null) {\n return;\n }\n\n const isLastHunk = hunkIndex === diff.hunks.length - 1;\n if (!isLastHunk) {\n hunk.noEOFCRAdditions = false;\n hunk.noEOFCRDeletions = false;\n return;\n }\n\n const lastAdditionLine = diff.additionLines.at(-1);\n const lastDeletionLine = diff.deletionLines.at(-1);\n hunk.noEOFCRAdditions =\n lastAdditionLine != null &&\n lastAdditionLine !== '' &&\n !lastAdditionLine.endsWith('\\n');\n hunk.noEOFCRDeletions =\n lastDeletionLine != null &&\n lastDeletionLine !== '' &&\n !lastDeletionLine.endsWith('\\n');\n}\n\nfunction applyReparsedHunk(target: Hunk, parsed: Hunk): void {\n const additionOffset = target.additionLineIndex;\n const deletionOffset = target.deletionLineIndex;\n\n target.hunkContent = parsed.hunkContent.map((content) =>\n offsetHunkContent(content, additionOffset, deletionOffset)\n );\n target.additionLineIndex = additionOffset + parsed.additionLineIndex;\n target.additionStart = target.additionStart + parsed.additionLineIndex;\n target.additionCount = parsed.additionCount;\n target.additionLines = parsed.additionLines;\n if (parsed.deletionLineIndex >= 0) {\n target.deletionLineIndex = deletionOffset + parsed.deletionLineIndex;\n target.deletionStart = target.deletionStart + parsed.deletionLineIndex;\n }\n target.deletionCount = parsed.deletionCount;\n target.deletionLines = parsed.deletionLines;\n target.noEOFCRAdditions = parsed.noEOFCRAdditions;\n target.noEOFCRDeletions = parsed.noEOFCRDeletions;\n\n recomputeHunkRenderLineCounts(target);\n}\n\nexport function offsetHunkContent(\n content: HunkContent,\n additionOffset: number,\n deletionOffset: number\n): HunkContent {\n return {\n ...content,\n additionLineIndex: content.additionLineIndex + additionOffset,\n deletionLineIndex: content.deletionLineIndex + deletionOffset,\n };\n}\n\nexport function recomputeHunkRenderLineCounts(hunk: Hunk): void {\n let splitLineCount = 0;\n let unifiedLineCount = 0;\n\n for (const content of hunk.hunkContent) {\n if (content.type === 'context') {\n splitLineCount += content.lines;\n unifiedLineCount += content.lines;\n } else {\n splitLineCount += Math.max(content.additions, content.deletions);\n unifiedLineCount += content.additions + content.deletions;\n }\n }\n\n hunk.splitLineCount = splitLineCount;\n hunk.unifiedLineCount = unifiedLineCount;\n}\n\nexport function recomputeDiffRenderLineCounts(\n diff: Pick<\n FileDiffMetadata,\n 'hunks' | 'splitLineCount' | 'unifiedLineCount' | 'additionLines'\n >\n): void {\n let splitTotal = 0;\n let unifiedTotal = 0;\n let lastHunkAdditionEnd = 0;\n\n for (const hunk of diff.hunks) {\n hunk.collapsedBefore = Math.max(\n getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) -\n lastHunkAdditionEnd,\n 0\n );\n hunk.splitLineStart = splitTotal + hunk.collapsedBefore;\n hunk.unifiedLineStart = unifiedTotal + hunk.collapsedBefore;\n\n recomputeHunkRenderLineCounts(hunk);\n\n splitTotal += hunk.collapsedBefore + hunk.splitLineCount;\n unifiedTotal += hunk.collapsedBefore + hunk.unifiedLineCount;\n lastHunkAdditionEnd = getHunkSideEndBoundary(\n hunk.additionStart,\n hunk.additionCount\n );\n }\n\n if (diff.hunks.length > 0) {\n const lastHunk = diff.hunks[diff.hunks.length - 1];\n const collapsedAfter = Math.max(\n diff.additionLines.length -\n getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount),\n 0\n );\n splitTotal += collapsedAfter;\n unifiedTotal += collapsedAfter;\n }\n\n diff.splitLineCount = splitTotal;\n diff.unifiedLineCount = unifiedTotal;\n}\n", "import type { CreatePatchOptionsNonabortable } from 'diff';\n\nimport type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n HunkExpansionRegion,\n} from '../types';\nimport { getHunkSideStartBoundary } from './getHunkSideBoundaries';\nimport { parseDiffFromFile } from './parseDiffFromFile';\nimport { slideBlankBoundaryBlocksUp } from './realignChangeContent';\nimport {\n offsetHunkContent,\n preserveTrailingEditorBlankLine,\n recomputeDiffHunks,\n recomputeDiffHunksForEdit,\n recomputeDiffRenderLineCounts,\n recomputeHunkRenderLineCounts,\n syncHunkNoEOFCRFromFullFile,\n} from './updateDiffHunks';\nimport {\n getExpandedRegion,\n getTrailingExpandedRegion,\n} from './virtualDiffLayout';\n\n// While an editor is attached to a FileDiff, each hunk is a persistent region\n// identified by its old-side range. Structural passes rebuild those regions\n// from one canonical old/current diff; a reverted region remains as context so\n// its rows keep rendering until the session-exit recompute.\n\nexport interface DivergenceCore {\n start: number;\n deletionEnd: number;\n additionEnd: number;\n}\n\ninterface PreviousRegionSpan {\n firstIndex: number;\n lastIndex: number;\n}\n\n/** Maps rebuilt regions back to the previous skeleton for expansion remapping. */\nexport interface SessionRegionChange {\n regions: Array<PreviousRegionSpan | undefined>;\n}\n\ninterface RegionBounds {\n additionStart: number;\n additionEnd: number;\n deletionStart: number;\n deletionEnd: number;\n}\n\ninterface RegionPlan {\n deletionStart: number;\n deletionEnd: number;\n blocks: ChangeContent[];\n previousSpan: PreviousRegionSpan | undefined;\n}\n\nconst deletionLineSetCache = new WeakMap<\n FileDiffMetadata,\n { lines: string[]; set: Set<string> }\n>();\n\n/**\n * Drops the editor document's phantom trailing empty line (a document ending\n * in a newline exposes one extra empty line the parsed diff never contains)\n * so session line arrays compare like parse-derived ones.\n */\nexport function normalizeEditorLines(lines: string[]): string[] {\n if (lines.length > 1 && lines[lines.length - 1] === '') {\n return lines.slice(0, -1);\n }\n return lines;\n}\n\n/**\n * Find the complete old/current divergence core. The old side is immutable\n * during an edit session, so this result needs no prior-pass snapshot.\n */\nexport function findDivergenceCore(\n deletionLines: string[],\n additionLines: string[]\n): DivergenceCore | undefined {\n const maxStart = Math.min(deletionLines.length, additionLines.length);\n let start = 0;\n while (start < maxStart && deletionLines[start] === additionLines[start]) {\n start++;\n }\n let deletionEnd = deletionLines.length;\n let additionEnd = additionLines.length;\n while (\n deletionEnd > start &&\n additionEnd > start &&\n deletionLines[deletionEnd - 1] === additionLines[additionEnd - 1]\n ) {\n deletionEnd--;\n additionEnd--;\n }\n if (start === deletionEnd && start === additionEnd) {\n return undefined;\n }\n return { start, deletionEnd, additionEnd };\n}\n\n/**\n * Rebuild session regions from old/current lines and the previous change blocks.\n * A full parse supplies changes, preserving existing blank positions while\n * sliding new or edited blank changes up for the live editor. Previous line text\n * distinguishes edits to an insertion from untouched blocks of the same size.\n */\nexport function rebuildSessionHunks(\n diff: FileDiffMetadata,\n parseDiffOptions?: CreatePatchOptionsNonabortable,\n getPreviousAdditionLine?: (index: number) => string | undefined\n): SessionRegionChange | undefined {\n const previousHunks = diff.hunks;\n const editorAdditionLines = diff.additionLines;\n const canonicalAdditionLines = normalizeEditorLines(editorAdditionLines);\n const canonicalDiff =\n canonicalAdditionLines === editorAdditionLines\n ? diff\n : { ...diff, additionLines: canonicalAdditionLines };\n const blocks = parseSessionChangeBlocks(\n canonicalDiff,\n parseDiffOptions,\n getPreviousAdditionLine\n );\n const plans = buildRegionPlans(\n previousHunks,\n blocks,\n diff.deletionLines.length\n );\n\n const nextHunks = buildRegionHunks(canonicalDiff, plans);\n diff.additionLines = canonicalAdditionLines;\n diff.hunks = nextHunks;\n diff.editSessionDirty = true;\n finalizeSessionHunks(diff);\n preserveTrailingEditorBlankLine(diff, editorAdditionLines);\n const layoutChanged = hasRegionOrSplitLayoutChanged(\n previousHunks,\n diff.hunks\n );\n if (!layoutChanged) {\n return undefined;\n }\n return { regions: plans.map((plan) => plan.previousSpan) };\n}\n\n/**\n * Keep a cheap content-only path when a same-line-count pass cannot alter the\n * canonical blocks. Gap, ambiguous, or multi-region edits rebuild statelessly.\n */\nexport function applySessionChangedLines(\n diff: FileDiffMetadata,\n changedAdditionLineIndexes: Iterable<number>,\n parseDiffOptions?: CreatePatchOptionsNonabortable,\n previousAdditionLines?: ReadonlyMap<number, string>\n): SessionRegionChange | undefined {\n const changedLines = new Set(changedAdditionLineIndexes);\n const lines = Array.from(changedLines)\n .filter((line) => line >= 0 && line < diff.additionLines.length)\n .sort((a, b) => a - b);\n if (lines.length === 0) {\n return undefined;\n }\n const getPreviousAdditionLine = (index: number) =>\n changedLines.has(index)\n ? previousAdditionLines?.get(index)\n : diff.additionLines[index];\n\n const { hunks } = diff;\n let regionIndex: number | undefined;\n let hunkIndex = 0;\n for (const line of lines) {\n while (hunkIndex < hunks.length) {\n const hunk = hunks[hunkIndex];\n const start = getHunkAdditionStart(hunk);\n if (line < start + hunk.additionCount) break;\n hunkIndex++;\n }\n const hunk = hunks[hunkIndex];\n const start = hunk == null ? undefined : getHunkAdditionStart(hunk);\n if (\n start == null ||\n line < start ||\n (regionIndex != null && regionIndex !== hunkIndex)\n ) {\n return rebuildSessionHunks(\n diff,\n parseDiffOptions,\n getPreviousAdditionLine\n );\n }\n regionIndex = hunkIndex;\n }\n\n if (regionIndex == null) {\n return undefined;\n }\n if (\n canRetainCanonicalBlocks(\n diff,\n lines,\n regionIndex,\n previousAdditionLines,\n parseDiffOptions\n )\n ) {\n diff.editSessionDirty = true;\n return undefined;\n }\n return rebuildSessionHunks(diff, parseDiffOptions, getPreviousAdditionLine);\n}\n\n// Existing balanced change blocks remain canonical when every edited line was\n// unmatched before and stays unmatched now: the old/new equality matrix is\n// unchanged, and similarity realignment never reorders a balanced block.\nfunction canRetainCanonicalBlocks(\n diff: FileDiffMetadata,\n changedLines: number[],\n regionIndex: number,\n previousAdditionLines: ReadonlyMap<number, string> | undefined,\n parseDiffOptions: CreatePatchOptionsNonabortable | undefined\n): boolean {\n if (\n previousAdditionLines == null ||\n parseDiffOptions?.ignoreWhitespace === true ||\n parseDiffOptions?.stripTrailingCr === true\n ) {\n return false;\n }\n const deletionLineSet = getDeletionLineSet(diff);\n const hunk = diff.hunks[regionIndex];\n if (hunk.hunkContent.some(isPureChange)) {\n return false;\n }\n for (const line of changedLines) {\n const previousLine = previousAdditionLines.get(line);\n const additionLine = diff.additionLines[line];\n if (\n previousLine == null ||\n additionLine == null ||\n deletionLineSet.has(previousLine) ||\n deletionLineSet.has(additionLine)\n ) {\n return false;\n }\n let insideBalancedChange = false;\n for (const content of hunk.hunkContent) {\n if (\n content.type === 'change' &&\n content.additions === content.deletions &&\n line >= content.additionLineIndex &&\n line < content.additionLineIndex + content.additions\n ) {\n insideBalancedChange = true;\n break;\n }\n }\n if (!insideBalancedChange) {\n return false;\n }\n }\n return true;\n}\n\nfunction getDeletionLineSet(diff: FileDiffMetadata): Set<string> {\n const cached = deletionLineSetCache.get(diff);\n if (cached?.lines === diff.deletionLines) {\n return cached.set;\n }\n const set = new Set(diff.deletionLines);\n deletionLineSetCache.set(diff, { lines: diff.deletionLines, set });\n return set;\n}\n\nfunction isPureChange(\n content: ContextContent | ChangeContent | undefined\n): boolean {\n return (\n content?.type === 'change' &&\n (content.additions === 0 || content.deletions === 0)\n );\n}\n\n/** Preserve expansion at the surviving outer edges of rebuilt old-side gaps. */\nexport function remapExpandedHunksForRegionChange(\n expandedHunks: Map<number, HunkExpansionRegion>,\n change: SessionRegionChange\n): Map<number, HunkExpansionRegion> {\n const remapped = new Map<number, HunkExpansionRegion>();\n const { regions } = change;\n for (let key = 0; key <= regions.length; key++) {\n const previous = regions[key - 1];\n const next = regions[key];\n const fromStartSource =\n key === 0\n ? expandedHunks.get(0)\n : previous == null\n ? undefined\n : expandedHunks.get(previous.lastIndex + 1);\n const fromEndSource =\n next == null ? undefined : expandedHunks.get(next.firstIndex);\n const fromStart = fromStartSource?.fromStart ?? 0;\n const fromEnd = fromEndSource?.fromEnd ?? 0;\n if (fromStart > 0 || fromEnd > 0) {\n remapped.set(key, { fromStart, fromEnd });\n }\n }\n return remapped;\n}\n\n/**\n * An expanded gap-edge slice in old-side (deletion-line) coordinates as a\n * `[start, end)` range. Old-side coordinates survive the exit recompute\n * unchanged — edits only touch the new side — so these anchor best-effort\n * expansion preservation across the recompute.\n */\nexport type ExpansionAnchorRange = [start: number, end: number];\n\n/** Snapshot the expanded gap-edge slices before the exit recompute. */\nexport function captureExpansionAnchors(\n diff: FileDiffMetadata,\n expandedHunks: Map<number, HunkExpansionRegion>,\n collapsedContextThreshold: number\n): ExpansionAnchorRange[] {\n const anchors: ExpansionAnchorRange[] = [];\n if (diff.isPartial) {\n return anchors;\n }\n for (const [hunkIndex, hunk] of diff.hunks.entries()) {\n const region = getExpandedRegion({\n isPartial: diff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n // Gaps at or below the threshold render on their own; only explicit\n // expansion state needs preserving.\n if (region.rangeSize <= collapsedContextThreshold) {\n continue;\n }\n const gapEnd = getHunkDeletionStart(hunk);\n const gapStart = gapEnd - region.rangeSize;\n if (region.fromStart > 0) {\n anchors.push([gapStart, gapStart + region.fromStart]);\n }\n if (region.fromEnd > 0) {\n anchors.push([gapEnd - region.fromEnd, gapEnd]);\n }\n }\n const trailingRegion = getTrailingExpandedRegion({\n fileDiff: diff,\n hunkIndex: diff.hunks.length - 1,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'captureExpansionAnchors',\n });\n if (\n trailingRegion != null &&\n trailingRegion.fromStart > 0 &&\n trailingRegion.rangeSize > collapsedContextThreshold\n ) {\n const lastHunk = diff.hunks[diff.hunks.length - 1];\n const gapStart = getHunkDeletionStart(lastHunk) + lastHunk.deletionCount;\n anchors.push([gapStart, gapStart + trailingRegion.fromStart]);\n }\n return anchors;\n}\n\n/**\n * Rebuild gap expansion state against the recomputed hunks: for each new\n * gap, an anchor touching the gap's start edge restores `fromStart`, one\n * touching its end edge restores `fromEnd`, and anchors for gaps that no\n * longer exist drop.\n */\nexport function rebuildExpansionFromAnchors(\n diff: FileDiffMetadata,\n anchors: ExpansionAnchorRange[]\n): Map<number, HunkExpansionRegion> {\n const rebuilt = new Map<number, HunkExpansionRegion>();\n if (anchors.length === 0) {\n return rebuilt;\n }\n const applyGap = (key: number, gapStart: number, gapEnd: number) => {\n if (gapEnd <= gapStart) {\n return;\n }\n let fromStart = 0;\n let fromEnd = 0;\n for (const [start, end] of anchors) {\n if (end <= gapStart || start >= gapEnd) {\n continue;\n }\n if (start <= gapStart) {\n fromStart = Math.max(fromStart, Math.min(end, gapEnd) - gapStart);\n }\n if (end >= gapEnd) {\n fromEnd = Math.max(fromEnd, gapEnd - Math.max(start, gapStart));\n }\n }\n if (fromStart > 0 || fromEnd > 0) {\n rebuilt.set(key, { fromStart, fromEnd });\n }\n };\n for (const [hunkIndex, hunk] of diff.hunks.entries()) {\n const gapEnd = getHunkDeletionStart(hunk);\n applyGap(hunkIndex, gapEnd - Math.max(hunk.collapsedBefore, 0), gapEnd);\n }\n const lastHunk = diff.hunks[diff.hunks.length - 1];\n if (lastHunk != null && !diff.isPartial && diff.deletionLines.length > 0) {\n applyGap(\n diff.hunks.length,\n getHunkDeletionStart(lastHunk) + lastHunk.deletionCount,\n diff.deletionLines.length\n );\n }\n return rebuilt;\n}\n\n/**\n * While editing, hunk updates keep a lightweight session-specific shape and\n * mark the diff with `editSessionDirty`. Called at session end, this\n * recomputes the hunks in full from the diff's current lines — the same\n * hunks a non-session edit would have produced — and clears the flag.\n * Returns true when a recompute ran.\n */\nexport function finishEditSessionForDiff(\n diff: FileDiffMetadata,\n parseDiffOptions?: CreatePatchOptionsNonabortable\n): boolean {\n if (diff.editSessionDirty !== true) {\n return false;\n }\n delete diff.editSessionDirty;\n // The empty editor row only hosts a caret; it is not file content after exit.\n Object.assign(\n diff,\n diff.additionLines.length <= 1 && diff.additionLines.join('') === ''\n ? recomputeDiffHunks(diff, parseDiffOptions)\n : recomputeDiffHunksForEdit(diff, parseDiffOptions)\n );\n return true;\n}\n\n// Parse the complete old/current files once with the same context policy as\n// session exit, then slide new or edited blank changes before extracting blocks.\n// Use the parsed context window so a larger persistent session region cannot\n// extend the slide. Running cursors normalize unified N,0 indexes.\nfunction parseSessionChangeBlocks(\n diff: FileDiffMetadata,\n parseDiffOptions: CreatePatchOptionsNonabortable | undefined,\n getPreviousAdditionLine: ((index: number) => string | undefined) | undefined\n): ChangeContent[] {\n if (findDivergenceCore(diff.deletionLines, diff.additionLines) == null) {\n return [];\n }\n const parsed = parseDiffFromFile(\n {\n name: diff.prevName ?? diff.name,\n contents: diff.deletionLines.join(''),\n },\n {\n name: diff.name,\n contents: diff.additionLines.join(''),\n lang: diff.lang,\n },\n parseDiffOptions\n );\n\n // Built on the first blank block that qualifies to slide, so passes without\n // one never scan the previous skeleton.\n let previousBlocks: Map<number, ChangeContent> | undefined;\n // The parsed block sits at the bottom of its blank run. A previous block of\n // the same shape anywhere between there and the run's top is the same change\n // and keeps its position: offset 0 is untouched at the parsed position, and\n // `maxSlide` is one already slid to the top. A block with no previous\n // counterpart, or an insertion whose text changed in place, is new to this\n // pass and slides to the top.\n const resolveSlide = (block: ChangeContent, maxSlide: number): number => {\n previousBlocks ??= collectPureChangeBlocks(diff.hunks);\n for (let offset = 0; offset <= maxSlide; offset++) {\n const previous = previousBlocks.get(block.deletionLineIndex - offset);\n if (\n previous == null ||\n previous.additions !== block.additions ||\n previous.deletions !== block.deletions\n ) {\n continue;\n }\n // Old-side text is immutable. For insertions, compare the previous text\n // at its previous indexes because structural edits shift the new side.\n if (block.additions > 0 && getPreviousAdditionLine != null) {\n for (let line = 0; line < block.additions; line++) {\n if (\n getPreviousAdditionLine(previous.additionLineIndex + line) !==\n parsed.additionLines[block.additionLineIndex + line]\n ) {\n return maxSlide;\n }\n }\n }\n return offset;\n }\n return maxSlide;\n };\n\n const blocks: ChangeContent[] = [];\n let coveredAdditions = 0;\n let coveredDeletions = 0;\n for (const hunk of parsed.hunks) {\n slideBlankBoundaryBlocksUp(hunk, parsed, resolveSlide);\n const contextLines =\n hunk.additionCount > 0\n ? hunk.additionLineIndex - coveredAdditions\n : hunk.deletionLineIndex - coveredDeletions;\n coveredAdditions += contextLines;\n coveredDeletions += contextLines;\n for (const content of hunk.hunkContent) {\n if (content.type === 'context') {\n coveredAdditions += content.lines;\n coveredDeletions += content.lines;\n continue;\n }\n const block = offsetHunkContent(content, 0, 0) as ChangeContent;\n if (block.additions === 0) {\n block.additionLineIndex = coveredAdditions;\n }\n if (block.deletions === 0) {\n block.deletionLineIndex = coveredDeletions;\n }\n blocks.push(block);\n coveredAdditions += block.additions;\n coveredDeletions += block.deletions;\n }\n }\n return blocks;\n}\n\n// Pure insert/delete blocks keyed by old-side index. The old side is immutable\n// during a session, so that index identifies a block across passes while\n// new-side rows shift around it. Adjacent insert and delete runs parse as one\n// mixed block, so two pure blocks never share an index.\nfunction collectPureChangeBlocks(hunks: Hunk[]): Map<number, ChangeContent> {\n const blocks = new Map<number, ChangeContent>();\n for (const hunk of hunks) {\n for (const content of hunk.hunkContent) {\n if (\n content.type === 'change' &&\n (content.additions === 0 || content.deletions === 0)\n ) {\n blocks.set(content.deletionLineIndex, content);\n }\n }\n }\n return blocks;\n}\n\n// Co-walk canonical blocks and previous old-side regions. A block touching a\n// region grows it; touching several merges them; a block wholly in a gap gets\n// its own region. Pure insertions/deletions absorb one adjacent context line\n// when available so the region stays renderable on both sides and after undo.\nfunction buildRegionPlans(\n previousHunks: Hunk[],\n blocks: ChangeContent[],\n deletionLineCount: number\n): RegionPlan[] {\n const previousPlans = previousHunks.map((hunk, index): RegionPlan => {\n const deletionStart = getHunkDeletionStart(hunk);\n return {\n deletionStart,\n deletionEnd: deletionStart + hunk.deletionCount,\n blocks: [],\n previousSpan: { firstIndex: index, lastIndex: index },\n };\n });\n const plans: RegionPlan[] = [];\n let previousIndex = 0;\n\n for (const block of blocks) {\n const blockStart = block.deletionLineIndex;\n const blockEnd = blockStart + block.deletions;\n while (\n previousIndex < previousPlans.length &&\n previousPlans[previousIndex].deletionEnd < blockStart\n ) {\n plans.push(previousPlans[previousIndex]);\n previousIndex++;\n }\n\n let plan =\n plans.length > 0 &&\n blockTouchesRegion(blockStart, blockEnd, plans[plans.length - 1])\n ? plans.pop()\n : undefined;\n while (\n previousIndex < previousPlans.length &&\n previousPlans[previousIndex].deletionStart <= blockEnd\n ) {\n plan = mergeRegionPlans(plan, previousPlans[previousIndex]);\n previousIndex++;\n }\n\n if (plan == null) {\n let deletionStart = blockStart;\n let deletionEnd = blockEnd;\n if (\n (block.deletions === 0 || block.additions === 0) &&\n deletionLineCount > block.deletions\n ) {\n const previousEnd = plans[plans.length - 1]?.deletionEnd ?? 0;\n const nextStart =\n previousPlans[previousIndex]?.deletionStart ?? deletionLineCount;\n if (blockStart > previousEnd) {\n deletionStart--;\n } else if (blockEnd < nextStart) {\n deletionEnd++;\n }\n }\n plan = {\n deletionStart,\n deletionEnd,\n blocks: [],\n previousSpan: undefined,\n };\n }\n plan.deletionStart = Math.min(plan.deletionStart, blockStart);\n plan.deletionEnd = Math.max(plan.deletionEnd, blockEnd);\n plan.blocks.push(block);\n plans.push(plan);\n }\n\n while (previousIndex < previousPlans.length) {\n plans.push(previousPlans[previousIndex]);\n previousIndex++;\n }\n return plans;\n}\n\nfunction blockTouchesRegion(\n blockStart: number,\n blockEnd: number,\n region: RegionPlan\n): boolean {\n return blockStart <= region.deletionEnd && blockEnd >= region.deletionStart;\n}\n\nfunction mergeRegionPlans(\n target: RegionPlan | undefined,\n source: RegionPlan\n): RegionPlan {\n if (target == null) {\n return source;\n }\n target.deletionStart = Math.min(target.deletionStart, source.deletionStart);\n target.deletionEnd = Math.max(target.deletionEnd, source.deletionEnd);\n target.blocks.push(...source.blocks);\n if (source.previousSpan != null) {\n target.previousSpan ??= { ...source.previousSpan };\n target.previousSpan.firstIndex = Math.min(\n target.previousSpan.firstIndex,\n source.previousSpan.firstIndex\n );\n target.previousSpan.lastIndex = Math.max(\n target.previousSpan.lastIndex,\n source.previousSpan.lastIndex\n );\n }\n return target;\n}\n\n// One paired-context walk constructs every region's new-side range. There is\n// no downstream coordinate shifting: each boundary is derived from the\n// canonical blocks that precede it.\nfunction buildRegionHunks(diff: FileDiffMetadata, plans: RegionPlan[]): Hunk[] {\n const hunks: Hunk[] = [];\n let deletionCursor = 0;\n let additionCursor = 0;\n for (const plan of plans) {\n const contextBefore = plan.deletionStart - deletionCursor;\n if (contextBefore < 0) {\n throw new Error('buildRegionHunks: overlapping old-side regions');\n }\n deletionCursor += contextBefore;\n additionCursor += contextBefore;\n const additionStart = additionCursor;\n const hunkContent: Array<ContextContent | ChangeContent> = [];\n\n for (const canonicalBlock of plan.blocks) {\n const deletionContext = canonicalBlock.deletionLineIndex - deletionCursor;\n const additionContext = canonicalBlock.additionLineIndex - additionCursor;\n if (deletionContext < 0 || deletionContext !== additionContext) {\n throw new Error('buildRegionHunks: canonical block context mismatch');\n }\n pushContext(hunkContent, deletionContext, additionCursor, deletionCursor);\n deletionCursor += deletionContext;\n additionCursor += additionContext;\n hunkContent.push({ ...canonicalBlock });\n deletionCursor += canonicalBlock.deletions;\n additionCursor += canonicalBlock.additions;\n }\n\n const trailingContext = plan.deletionEnd - deletionCursor;\n if (trailingContext < 0) {\n throw new Error('buildRegionHunks: block exceeds its old-side region');\n }\n pushContext(hunkContent, trailingContext, additionCursor, deletionCursor);\n deletionCursor += trailingContext;\n additionCursor += trailingContext;\n hunks.push(\n createRegionHunk(\n diff,\n {\n additionStart,\n additionEnd: additionCursor,\n deletionStart: plan.deletionStart,\n deletionEnd: plan.deletionEnd,\n },\n hunkContent\n )\n );\n }\n\n if (\n diff.deletionLines.length - deletionCursor !==\n diff.additionLines.length - additionCursor\n ) {\n throw new Error('buildRegionHunks: trailing context mismatch');\n }\n return hunks;\n}\n\nfunction createRegionHunk(\n diff: FileDiffMetadata,\n bounds: RegionBounds,\n hunkContent: Array<ContextContent | ChangeContent>\n): Hunk {\n const additionCount = bounds.additionEnd - bounds.additionStart;\n const deletionCount = bounds.deletionEnd - bounds.deletionStart;\n let additionLines = 0;\n let deletionLines = 0;\n for (const content of hunkContent) {\n if (content.type === 'change') {\n additionLines += content.additions;\n deletionLines += content.deletions;\n }\n }\n const hunk: Hunk = {\n collapsedBefore: 0,\n additionStart: getUnifiedStart(bounds.additionStart, additionCount),\n additionCount,\n additionLines,\n additionLineIndex: getUnifiedLineIndex(bounds.additionStart, additionCount),\n deletionStart: getUnifiedStart(bounds.deletionStart, deletionCount),\n deletionCount,\n deletionLines,\n deletionLineIndex: getUnifiedLineIndex(bounds.deletionStart, deletionCount),\n hunkContent,\n hunkSpecs: `@@ -${getUnifiedStart(bounds.deletionStart, deletionCount)},${deletionCount} +${getUnifiedStart(bounds.additionStart, additionCount)},${additionCount} @@`,\n splitLineStart: 0,\n splitLineCount: 0,\n unifiedLineStart: 0,\n unifiedLineCount: 0,\n noEOFCRAdditions: false,\n noEOFCRDeletions: false,\n };\n recomputeHunkRenderLineCounts(hunk);\n return hunk;\n}\n\nfunction pushContext(\n hunkContent: Array<ContextContent | ChangeContent>,\n lines: number,\n additionLineIndex: number,\n deletionLineIndex: number\n): void {\n if (lines > 0) {\n hunkContent.push({\n type: 'context',\n lines,\n additionLineIndex,\n deletionLineIndex,\n });\n }\n}\n\nfunction hasRegionOrSplitLayoutChanged(\n previous: Hunk[],\n next: Hunk[]\n): boolean {\n if (previous.length !== next.length) {\n return true;\n }\n for (let index = 0; index < previous.length; index++) {\n const previousHunk = previous[index];\n const nextHunk = next[index];\n if (\n getHunkDeletionStart(previousHunk) !== getHunkDeletionStart(nextHunk) ||\n previousHunk.deletionCount !== nextHunk.deletionCount ||\n getHunkAdditionStart(previousHunk) !== getHunkAdditionStart(nextHunk) ||\n previousHunk.additionCount !== nextHunk.additionCount ||\n previousHunk.splitLineCount !== nextHunk.splitLineCount ||\n !haveSameSplitRowMapping(previousHunk, nextHunk)\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction haveSameSplitRowMapping(previous: Hunk, next: Hunk): boolean {\n const previousRows = iterateSplitRowMapping(previous);\n const nextRows = iterateSplitRowMapping(next);\n while (true) {\n const previousRow = previousRows.next();\n const nextRow = nextRows.next();\n if (previousRow.done === true || nextRow.done === true) {\n return previousRow.done === nextRow.done;\n }\n if (\n previousRow.value[0] !== nextRow.value[0] ||\n previousRow.value[1] !== nextRow.value[1]\n ) {\n return false;\n }\n }\n}\n\nfunction* iterateSplitRowMapping(\n hunk: Hunk\n): Generator<\n [deletionLine: number | undefined, additionLine: number | undefined]\n> {\n for (const content of hunk.hunkContent) {\n if (content.type === 'context') {\n for (let offset = 0; offset < content.lines; offset++) {\n yield [\n content.deletionLineIndex + offset,\n content.additionLineIndex + offset,\n ];\n }\n continue;\n }\n const rowCount = Math.max(content.deletions, content.additions);\n for (let offset = 0; offset < rowCount; offset++) {\n yield [\n offset < content.deletions\n ? content.deletionLineIndex + offset\n : undefined,\n offset < content.additions\n ? content.additionLineIndex + offset\n : undefined,\n ];\n }\n }\n}\n\nfunction getHunkAdditionStart(hunk: Hunk): number {\n return getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount);\n}\n\nfunction getHunkDeletionStart(hunk: Hunk): number {\n return getHunkSideStartBoundary(hunk.deletionStart, hunk.deletionCount);\n}\n\nfunction getUnifiedStart(lineIndex: number, count: number): number {\n return count === 0 ? lineIndex : lineIndex + 1;\n}\n\nfunction getUnifiedLineIndex(lineIndex: number, count: number): number {\n return count === 0 ? lineIndex - 1 : lineIndex;\n}\n\nfunction finalizeSessionHunks(diff: FileDiffMetadata): void {\n recomputeDiffRenderLineCounts(diff);\n for (let index = 0; index < diff.hunks.length; index++) {\n syncHunkNoEOFCRFromFullFile(diff, index);\n }\n}\n", "import type { FileDiffMetadata } from '../types';\nimport { getFiletypeFromFileName } from './getFiletypeFromFileName';\n\nexport function isDiffPlainText(diff: FileDiffMetadata): boolean {\n const computedLang = diff.lang ?? getFiletypeFromFileName(diff.name);\n const computedPreviousLang =\n diff.lang ??\n (diff.prevName != null ? getFiletypeFromFileName(diff.prevName) : 'text');\n return computedLang === 'text' && computedPreviousLang === 'text';\n}\n", "import type { ElementContent, Element as HASTElement, Properties } from 'hast';\n\nimport {\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n DEFAULT_EXPANDED_REGION,\n DEFAULT_RENDER_RANGE,\n DEFAULT_THEMES,\n DEFAULT_TOKENIZE_MAX_LENGTH,\n} from '../constants';\nimport type { TextDocument } from '../editor/textDocument';\nimport { areLanguagesAttached } from '../highlighter/languages/areLanguagesAttached';\nimport {\n getHighlighterIfLoaded,\n getSharedHighlighter,\n HighlighterDisposedError,\n} from '../highlighter/shared_highlighter';\nimport { areThemesAttached } from '../highlighter/themes/areThemesAttached';\nimport type {\n AnnotationLineMap,\n AnnotationSpan,\n BaseCodeOptions,\n BaseDiffOptions,\n BaseDiffOptionsWithDefaults,\n CodeColumnType,\n CustomPreProperties,\n DiffLineAnnotation,\n DiffsHighlighter,\n ExpansionDirections,\n FileDiffMetadata,\n FileHeaderRenderMode,\n HighlightedToken,\n HunkData,\n HunkExpansionRegion,\n HunkSeparators,\n LineTypes,\n RenderDiffOptions,\n RenderDiffResult,\n RenderedDiffASTCache,\n RenderRange,\n SupportedLanguages,\n ThemedDiffResult,\n} from '../types';\nimport { applyLineTextWithNewline } from '../utils/applyLineTextWithNewline';\nimport { areDiffRenderOptionsEqual } from '../utils/areDiffRenderOptionsEqual';\nimport { areDiffTargetsEqual } from '../utils/areDiffTargetsEqual';\nimport { areRenderRangesEqual } from '../utils/areRenderRangesEqual';\nimport { cleanLastNewline } from '../utils/cleanLastNewline';\nimport { createAnnotationElement as createDefaultAnnotationElement } from '../utils/createAnnotationElement';\nimport { createContentColumn } from '../utils/createContentColumn';\nimport { createEmptyRowBuffer } from '../utils/createEmptyRowBuffer';\nimport { createFileHeaderElement } from '../utils/createFileHeaderElement';\nimport { createNoNewlineElement } from '../utils/createNoNewlineElement';\nimport { createPreElement } from '../utils/createPreElement';\nimport { createSeparator } from '../utils/createSeparator';\nimport {\n applySessionChangedLines,\n rebuildSessionHunks,\n remapExpandedHunksForRegionChange,\n type SessionRegionChange,\n} from '../utils/editSessionHunks';\nimport { getFiletypeFromFileName } from '../utils/getFiletypeFromFileName';\nimport { getHighlighterOptions } from '../utils/getHighlighterOptions';\nimport { getHunkSeparatorSlotName } from '../utils/getHunkSeparatorSlotName';\nimport { getLineAnnotationName } from '../utils/getLineAnnotationName';\nimport { getTotalLineCountFromHunks } from '../utils/getTotalLineCountFromHunks';\nimport {\n createGutterGap,\n createGutterItem,\n createGutterWrapper,\n createHastElement,\n} from '../utils/hast_utils';\nimport { hastToHtml } from '../utils/hastToHtml';\nimport {\n FILE_ANNOTATION_HUNK_INDEX,\n FILE_ANNOTATION_LINE_INDEX,\n getFileAnnotations,\n shouldRenderFileAnnotations,\n} from '../utils/includesFileAnnotations';\nimport { isDefaultRenderRange } from '../utils/isDefaultRenderRange';\nimport { isDiffPlainText } from '../utils/isDiffPlainText';\nimport type { DiffLineMetadata } from '../utils/iterateOverDiff';\nimport { iterateOverDiff } from '../utils/iterateOverDiff';\nimport { renderDiffWithHighlighter } from '../utils/renderDiffWithHighlighter';\nimport { resolvePreferredHighlighter } from '../utils/resolvePreferredHighlighter';\nimport {\n recomputeDiffHunksForEdit,\n recomputeEmptyDocumentDiff,\n recomputeTopAlignedAdditionDiff,\n shouldTopAlignAdditionRecompute,\n updateDiffHunks,\n} from '../utils/updateDiffHunks';\nimport { getTrailingContextRangeSize } from '../utils/virtualDiffLayout';\nimport type { WorkerPoolManager } from '../worker';\nimport { isHandledWorkerPoolError } from '../worker/errors';\n\ninterface PushLineWithAnnotation {\n diffStyle: 'unified' | 'split';\n type: 'context' | 'context-expanded' | 'change';\n\n deletionLine?: ElementContent;\n additionLine?: ElementContent;\n\n unifiedSpan?: AnnotationSpan;\n deletionSpan?: AnnotationSpan;\n additionSpan?: AnnotationSpan;\n\n createAnnotationElement(span: AnnotationSpan): HASTElement;\n context: ProcessContext;\n}\n\ninterface GetRenderOptionsReturn {\n options: RenderDiffOptions;\n forceHighlight: boolean;\n}\n\ninterface PendingHighlightResult extends RenderDiffResult {\n diff: FileDiffMetadata;\n highlighted: boolean;\n}\n\ninterface DiffRenderCache extends RenderedDiffASTCache {\n // hydrate() describes DOM that already exists, even when no reusable AST\n // was available for that server-rendered content.\n hydrated?: boolean;\n}\n\ninterface PushSeparatorProps {\n hunkIndex: number;\n collapsedLines: number | 'unknown';\n rangeSize: number;\n hunkSpecs: string | undefined;\n isFirstHunk: boolean;\n isLastHunk: boolean;\n isExpandable: boolean;\n}\n\ninterface ProcessContext {\n rowCount: number;\n expansionLineCount: number;\n hunkSeparators: HunkSeparators;\n unifiedContentAST: ElementContent[];\n deletionsContentAST: ElementContent[];\n additionsContentAST: ElementContent[];\n unifiedGutterAST: HASTElement;\n deletionsGutterAST: HASTElement;\n additionsGutterAST: HASTElement;\n hunkData: HunkData[];\n pushToGutter(type: CodeColumnType, element: HASTElement): void;\n incrementRowCount(count?: number): void;\n}\n\nexport interface DiffHunksRendererOptions extends BaseDiffOptions {\n headerRenderMode?: FileHeaderRenderMode;\n}\n\nexport interface DiffHunksRendererOptionsWithDefaults extends Omit<\n BaseDiffOptionsWithDefaults,\n 'themeType'\n> {\n headerRenderMode: FileHeaderRenderMode;\n}\n\nexport interface UnifiedLineDecorationProps {\n type: 'context' | 'context-expanded' | 'change';\n lineType: LineTypes;\n additionLineIndex: number | undefined;\n deletionLineIndex: number | undefined;\n}\n\nexport interface SplitLineDecorationProps {\n side: 'deletions' | 'additions';\n type: 'context' | 'context-expanded' | 'change';\n lineIndex: number | undefined;\n}\n\nexport interface LineDecoration {\n gutterLineType: LineTypes;\n gutterProperties?: Properties;\n contentProperties?: Properties;\n}\n\ninterface PendingSplitContext {\n size: number;\n side: 'additions' | 'deletions' | undefined;\n increment(): void;\n flush(): void;\n}\n\nexport interface RenderedLineContext {\n type: 'context' | 'context-expanded' | 'change';\n hunkIndex: number;\n lineIndex: number;\n unifiedLineIndex: number;\n splitLineIndex: number;\n deletionLine?: DiffLineMetadata;\n additionLine?: DiffLineMetadata;\n}\n\nexport interface InjectedRow {\n content: HASTElement;\n gutter: HASTElement;\n}\n\nexport interface SplitInjectedRow {\n deletion: InjectedRow | undefined;\n addition: InjectedRow | undefined;\n}\n\nexport interface UnifiedInjectedRowPlacement {\n before?: InjectedRow[];\n after?: InjectedRow[];\n}\n\nexport interface SplitInjectedRowPlacement {\n before?: SplitInjectedRow[];\n after?: SplitInjectedRow[];\n}\n\nexport interface HunksRenderResult {\n fileDiff: FileDiffMetadata;\n unifiedGutterAST: ElementContent[] | undefined;\n unifiedContentAST: ElementContent[] | undefined;\n deletionsGutterAST: ElementContent[] | undefined;\n deletionsContentAST: ElementContent[] | undefined;\n additionsGutterAST: ElementContent[] | undefined;\n additionsContentAST: ElementContent[] | undefined;\n hunkData: HunkData[];\n css: string;\n preNode: HASTElement;\n headerElement: HASTElement | undefined;\n totalLines: number;\n themeStyles: string;\n baseThemeType: 'light' | 'dark' | undefined;\n rowCount: number;\n bufferBefore: number;\n bufferAfter: number;\n}\n\nlet instanceId = -1;\n\nexport class DiffHunksRenderer<LAnnotation = undefined> {\n readonly __id: string = `diff-hunks-renderer:${++instanceId}`;\n\n // The latest diff requested by the component. The render cache may\n // intentionally keep displaying an older highlighted diff while this one\n // is highlighted in the background.\n private diff: FileDiffMetadata | undefined;\n\n private expandedHunks = new Map<number, HunkExpansionRegion>();\n\n private deletionAnnotations: AnnotationLineMap<LAnnotation> = {};\n private additionAnnotations: AnnotationLineMap<LAnnotation> = {};\n\n private computedLangs: SupportedLanguages[] = ['text'];\n private renderCache: DiffRenderCache | undefined;\n // Completed background work waits here until the next render can update its\n // DOM and layout together.\n private pendingHighlightResult: PendingHighlightResult | undefined;\n // Newly highlighted rows from a line-count edit wait here until the old row\n // cache has been shifted to match the document's new line indexes.\n private pendingStructuralRows: Map<number, HASTElement> | undefined;\n\n // Edit-session state: while active, hunk updates go through the frozen\n // region skeleton (editSessionHunks) instead of the full recompute, and\n // rendering stays on the main thread with editor-compatible token markup —\n // the editor's caret/selection mapping needs the token transformer, and\n // the pool's global options are not guaranteed to produce it. The pool\n // keeps serving every surface without a session.\n private editSessionActive = false;\n\n constructor(\n public options: DiffHunksRendererOptions = { theme: DEFAULT_THEMES },\n private annotationSlotName: (\n annotation: DiffLineAnnotation<LAnnotation>\n ) => string = getLineAnnotationName,\n private onRenderUpdate?: () => unknown,\n private workerManager?: WorkerPoolManager | undefined\n ) {}\n\n public cleanUp(): void {\n this.endEditSession();\n this.recycle();\n this.expandedHunks.clear();\n this.workerManager = undefined;\n this.onRenderUpdate = undefined;\n }\n\n public recycle(): void {\n this.diff = undefined;\n if (this.editSessionActive) {\n // The editor keeps its document and undo history while offscreen. Its\n // private highlight result belongs to that session and can resume too.\n if (this.renderCache != null) {\n this.renderCache.renderRange = undefined;\n }\n this.pendingHighlightResult = undefined;\n this.pendingStructuralRows = undefined;\n } else {\n this.clearRenderCache();\n }\n this.additionAnnotations = {};\n this.deletionAnnotations = {};\n this.workerManager?.cleanUpTasks(this);\n }\n\n /**\n * Enter edit-session mode: hunk updates preserve the current region\n * skeleton instead of recomputing hunks, and rendering happens locally\n * with the token transformer forced on (worker-pool requests/results are\n * suspended for this renderer). When the session was freshly cloned from\n * `externalDiff`, compatible highlighted markup is detached from its external\n * cache owner so the editor can reuse it without mutating shared data. An\n * empty additions document gets one row for the editor's caret.\n */\n public beginEditSession(\n diff: FileDiffMetadata,\n externalDiff?: FileDiffMetadata\n ): void {\n const { editSessionActive: wasAlreadyActive } = this;\n this.editSessionActive = true;\n if (!wasAlreadyActive) {\n this.pendingHighlightResult = undefined;\n }\n this.diff = diff;\n // A replacement creates a new session diff. The old session's result\n // cannot become the new one's private editor markup.\n if (\n wasAlreadyActive &&\n this.renderCache != null &&\n this.renderCache.diff !== diff\n ) {\n this.clearRenderCache();\n }\n const { renderCache } = this;\n\n if (!diff.isPartial && diff.additionLines.length === 0) {\n Object.assign(\n diff,\n recomputeEmptyDocumentDiff(diff, this.options.parseDiffOptions)\n );\n this.markEditSessionPass(diff);\n this.clearRenderCache();\n return;\n }\n\n if (renderCache == null) {\n return;\n }\n // Edit updates call this again before each write. That cache is already\n // private and must retain plain-text session results.\n if (wasAlreadyActive && renderCache.diff === diff) {\n return;\n }\n const { options } = this.getRenderOptions(diff);\n const cacheBelongsToSession = renderCache.diff === diff;\n const cacheBelongsToExternal =\n externalDiff != null &&\n areDiffTargetsEqual(renderCache.diff, externalDiff);\n const { result } = renderCache;\n if (\n !renderCache.highlighted ||\n result == null ||\n !areDiffRenderOptionsEqual(renderCache.options, options) ||\n (!cacheBelongsToSession && !cacheBelongsToExternal)\n ) {\n this.clearRenderCache();\n return;\n }\n if (cacheBelongsToSession) {\n return;\n }\n\n // Edit paths replace addition entries and their containing array,\n // but only read the existing HAST nodes and deletion entries.\n this.renderCache = {\n diff,\n options,\n highlighted: true,\n result: {\n ...result,\n code: {\n ...result.code,\n additionLines: [...result.code.additionLines],\n },\n },\n renderRange: renderCache.renderRange,\n };\n }\n\n /** Leave edit-session mode. The exit recompute is the host's concern. */\n public endEditSession(): void {\n this.editSessionActive = false;\n this.pendingHighlightResult = undefined;\n if (this.diff == null) {\n this.clearRenderCache();\n }\n }\n\n /**\n * Ensures that the DOM is compatible with editor render updates\n */\n public editorRenderReady(): boolean {\n return (\n this.renderCache?.options.useTokenTransformer === true &&\n this.renderCache.highlighted &&\n this.renderCache.result != null\n );\n }\n\n /**\n * Re-highlights the current diff in the background and stages the fresh\n * result for the next render. Needed after an edit session's exit recompute:\n * session passes plain-fill shifted lines in the cached result, and the\n * recompute mutates the keyless session diff in place, so object identity\n * alone would otherwise treat the stale highlight as current forever. The\n * current result — content-correct, mostly highlighted — keeps rendering\n * until the fresh one is promoted, so no interim paint drops highlighting.\n */\n public refreshHighlightedResult(): Promise<void> {\n const { diff, renderCache, workerManager } = this;\n if (\n diff == null ||\n renderCache == null ||\n !areDiffTargetsEqual(renderCache.diff, diff) ||\n isDiffPlainText(diff) ||\n isDiffMassive(diff, this.getTokenizeMaxLength())\n ) {\n return Promise.resolve();\n }\n // The pool's diff cache is keyed by cacheKey, so a worker refresh needs\n // one; a keyless diff uses the local highlighter fallback below instead.\n if (\n !this.editSessionActive &&\n workerManager?.isWorkingPool() === true &&\n diff.cacheKey != null\n ) {\n workerManager.evictDiffFromCache(diff.cacheKey);\n return workerManager\n .primeDiffHighlightCache(diff)\n .then(() => {\n this.applyRefreshedResult(\n diff,\n workerManager.getDiffResultCache(diff)\n );\n })\n .catch((error: unknown) => {\n // A canceled prime leaves the current result in place.\n if (!isHandledWorkerPoolError(error)) {\n this.onHighlightError(error);\n }\n });\n }\n return this.asyncHighlight(diff)\n .then((fresh) => this.applyRefreshedResult(diff, fresh))\n .catch((error: unknown) => this.onHighlightError(error));\n }\n\n // Holds a freshly highlighted result for the next render transaction, unless\n // the renderer moved on while the highlight ran (new diff, options change,\n // or a new edit session whose passes the fresh result wouldn't reflect).\n private applyRefreshedResult(\n diff: FileDiffMetadata,\n fresh: RenderDiffResult | undefined\n ): void {\n const { diff: currentDiff, renderCache } = this;\n if (\n fresh == null ||\n currentDiff == null ||\n renderCache == null ||\n !areDiffTargetsEqual(currentDiff, diff) ||\n !areDiffTargetsEqual(renderCache.diff, diff) ||\n this.editSessionActive\n ) {\n return;\n }\n const { options } = this.getRenderOptions(currentDiff);\n if (!areDiffRenderOptionsEqual(options, fresh.options)) {\n return;\n }\n this.pendingHighlightResult = {\n diff: currentDiff,\n options: fresh.options,\n highlighted: true,\n result: fresh.result,\n };\n this.onRenderUpdate?.();\n }\n\n public get diffCache(): FileDiffMetadata | undefined {\n return this.renderCache?.diff ?? this.diff;\n }\n\n public clearRenderCache(): void {\n this.renderCache = undefined;\n this.pendingHighlightResult = undefined;\n this.pendingStructuralRows = undefined;\n }\n\n public setOptions(options: DiffHunksRendererOptions): void {\n this.options = options;\n }\n\n public mergeOptions(options: Partial<DiffHunksRendererOptions>): void {\n this.options = { ...this.options, ...options };\n }\n\n public expandHunk(\n index: number,\n direction: ExpansionDirections,\n expansionLineCount: number = this.getOptionsWithDefaults()\n .expansionLineCount\n ): void {\n const region = {\n ...(this.expandedHunks.get(index) ?? {\n fromStart: 0,\n fromEnd: 0,\n }),\n };\n if (direction === 'up' || direction === 'both') {\n region.fromStart += expansionLineCount;\n }\n if (direction === 'down' || direction === 'both') {\n region.fromEnd += expansionLineCount;\n }\n // NOTE(amadeus): If our render cache is not highlighted, we need to clear\n // it, otherwise we won't have the correct AST lines. Clearing is safe\n // mid-edit-session even though the dirty cache carries live edits: both\n // session hunk-update paths keep diff.additionLines current every pass,\n // so the rebuilt AST reproduces the live document.\n if (this.renderCache?.highlighted !== true) {\n this.clearRenderCache();\n }\n this.expandedHunks.set(index, region);\n }\n\n public getExpandedHunk(hunkIndex: number): HunkExpansionRegion {\n return this.expandedHunks.get(hunkIndex) ?? DEFAULT_EXPANDED_REGION;\n }\n\n public getExpandedHunksMap(): Map<number, HunkExpansionRegion> {\n return this.expandedHunks;\n }\n\n /** Replace the whole expansion map (session-exit expansion remapping). */\n public setExpandedHunksMap(\n expandedHunks: Map<number, HunkExpansionRegion>\n ): void {\n this.expandedHunks = expandedHunks;\n }\n\n public setLineAnnotations(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): void {\n this.additionAnnotations = {};\n this.deletionAnnotations = {};\n for (const annotation of lineAnnotations) {\n const map = ((): AnnotationLineMap<LAnnotation> => {\n switch (annotation.side) {\n case 'deletions':\n return this.deletionAnnotations;\n case 'additions':\n return this.additionAnnotations;\n }\n })();\n const arr = map[annotation.lineNumber] ?? [];\n map[annotation.lineNumber] = arr;\n arr.push(annotation);\n }\n }\n\n /**\n * Returns true when a session-mode pass changed the region skeleton itself\n * (a gap edit synthesized or merged regions), which changes the rendered\n * row set without a line-count change — the host must escalate to a full\n * re-render instead of its cheap refresh path.\n */\n public updateRenderCache(\n dirtyLines: Map<number, Array<HighlightedToken>>,\n themeType: 'dark' | 'light',\n lineCountChangeInFlight = false,\n changedDocumentLines?: ReadonlyMap<number, string>,\n documentLineCount?: number\n ): boolean {\n this.pendingStructuralRows = undefined;\n const { renderCache } = this;\n if (renderCache == null) {\n return false;\n }\n const { result, diff } = renderCache;\n if (result == null) {\n return false;\n }\n if (diff.isPartial) {\n throw new Error('Could not update render cache for partial diff');\n }\n\n const hastLines = result.code.additionLines;\n const pendingStructuralRows = (this.pendingStructuralRows =\n lineCountChangeInFlight ? new Map<number, HASTElement>() : undefined);\n // Structural rows use post-edit indexes while the current diff and HAST\n // still use pre-edit indexes. Hold those rows until applyDocumentChange\n // has shifted the old data into its authoritative positions.\n const changedAdditionLines: number[] = [];\n const previousAdditionLines = new Map<number, string>();\n // Source edits must reach the session diff independently of highlighting.\n // The parsed diff omits the final empty editor row. Once that row has\n // text, include it in the file; leave it out while it is still empty.\n if (pendingStructuralRows == null && changedDocumentLines != null) {\n const additionLineCount = diff.additionLines.length;\n const canAppendFinalRow = canAppendFinalDocumentRow(\n diff.additionLines,\n documentLineCount\n );\n for (const [line, text] of changedDocumentLines) {\n if (\n line < 0 ||\n line > additionLineCount ||\n (line === additionLineCount && (text === '' || !canAppendFinalRow))\n ) {\n continue;\n }\n const previous = diff.additionLines[line] ?? '';\n if (previous !== text) {\n diff.additionLines[line] = text;\n diff.additionCharacterCount += text.length - previous.length;\n changedAdditionLines.push(line);\n previousAdditionLines.set(line, previous);\n // A newly revealed row must show current text even before the\n // tokenizer supplies its colors.\n if (!dirtyLines.has(line)) {\n hastLines[line] = createPlainAdditionLineElement(\n line,\n cleanLastNewline(text)\n );\n }\n }\n }\n }\n for (const [line, tokens] of dirtyLines) {\n const prev = hastLines[line] as HASTElement | undefined;\n const prevProps = prev?.properties ?? {};\n const lineText = tokens.map((a) => a[2]).join('');\n const canSyncDiffLine = line < diff.additionLines.length;\n const prevLine = canSyncDiffLine ? (diff.additionLines[line] ?? '') : '';\n const prevText = cleanLastNewline(prevLine);\n // The host text document can expose one extra trailing empty line when\n // the file ends with a newline. Deferred tokenization must not grow\n // additionLines from that mismatch or hunk trailing context desyncs.\n if (\n pendingStructuralRows == null &&\n canSyncDiffLine &&\n changedDocumentLines?.has(line) !== true\n ) {\n const nextLine = applyLineTextWithNewline(prevLine, lineText);\n diff.additionLines[line] = nextLine;\n diff.additionCharacterCount += nextLine.length - prevLine.length;\n if (prevText !== lineText) {\n changedAdditionLines.push(line);\n previousAdditionLines.set(line, prevLine);\n }\n }\n const row: HASTElement = {\n type: 'element',\n tagName: 'div',\n properties: {\n 'data-line': prevProps['data-line'] ?? line + 1,\n 'data-line-index': prevProps['data-line-index'] ?? line,\n 'data-line-type': prevProps['data-line-type'] ?? 'context',\n },\n children: tokens.map(([char, fg, text]) => {\n if (char === 0 && fg === '') {\n if (text === '') {\n return {\n type: 'element',\n tagName: 'br',\n properties: {},\n children: [],\n };\n }\n return { type: 'text', value: text };\n }\n return {\n type: 'element',\n tagName: 'span',\n properties: {\n 'data-char': char,\n style: `color:${fg};`,\n },\n children: [{ type: 'text', value: text }],\n };\n }),\n };\n if (pendingStructuralRows != null) {\n pendingStructuralRows.set(line, row);\n } else {\n hastLines[line] = row;\n }\n }\n\n let regionsChanged = false;\n if (changedAdditionLines.length > 0) {\n if (this.editSessionActive) {\n if (\n diff.additionLines.length <= 1 &&\n diff.additionLines.join('') === ''\n ) {\n this.applyRecomputePreservingSessionType(\n diff,\n recomputeEmptyDocumentDiff(diff, this.options.parseDiffOptions)\n );\n regionsChanged = true;\n } else if (shouldTopAlignAdditionRecompute(diff, diff.additionLines)) {\n this.applyRecomputePreservingSessionType(\n diff,\n recomputeTopAlignedAdditionDiff(\n diff,\n diff.additionLines,\n diff.additionCharacterCount,\n this.options.parseDiffOptions\n )\n );\n regionsChanged = true;\n } else {\n const change = applySessionChangedLines(\n diff,\n changedAdditionLines,\n this.options.parseDiffOptions,\n previousAdditionLines\n );\n this.applyExpansionRemap(change);\n regionsChanged = change != null;\n }\n } else {\n Object.assign(\n diff,\n updateDiffHunks(\n diff,\n changedAdditionLines,\n this.options.parseDiffOptions\n )\n );\n }\n }\n\n result.baseThemeType = themeType;\n renderCache.isDirty = true;\n return regionsChanged;\n }\n\n private applyExpansionRemap(change: SessionRegionChange | undefined): void {\n if (change != null) {\n this.expandedHunks = remapExpandedHunksForRegionChange(\n this.expandedHunks,\n change\n );\n }\n }\n\n // Rebuild the session diff from the document even without a highlighted\n // result; suspended programmatic edits still need current hunks on return.\n public applyDocumentChange(\n textDocument: TextDocument<'file-diff', LAnnotation>\n ): void {\n const { pendingStructuralRows, renderCache } = this;\n this.pendingStructuralRows = undefined;\n const diff = this.diff ?? renderCache?.diff;\n if (diff == null) {\n return;\n }\n const result = renderCache?.result;\n if (diff.isPartial) {\n throw new Error('Could not apply document change for partial diff');\n }\n\n // The structural token pass leaves the diff in its pre-edit shape so this\n // document remains the single source of truth for shifting its lines.\n // Reading line-by-line also preserves blank documents and the final\n // editable empty row after a trailing line break.\n const { additionLines: previousAdditionLines } = diff;\n const { lines, characterCount } = getEditorDocumentLines(textDocument);\n diff.additionLines = lines;\n diff.additionCharacterCount = characterCount;\n if (result != null) {\n result.code.additionLines = realignAdditionHastLines(\n previousAdditionLines,\n diff.additionLines,\n result.code.additionLines,\n textDocument\n );\n }\n // An empty document splits into zero addition lines, which would recompute\n // to a diff with no editable rows and leave the attached host with no\n // line element for its caret (the additions column vanishes in split;\n // unified shows only deletions). Keep one empty editable line instead.\n if (diff.additionLines.length <= 1 && diff.additionLines.join('') === '') {\n this.applyRecomputePreservingSessionType(\n diff,\n recomputeEmptyDocumentDiff(diff, this.options.parseDiffOptions)\n );\n if (result != null) {\n result.code.additionLines[0] = createPlainAdditionLineElement(\n 0,\n textDocument.getLineText(0)\n );\n }\n } else if (this.editSessionActive) {\n this.applySessionDocumentChange(diff, previousAdditionLines);\n } else {\n Object.assign(\n diff,\n recomputeDiffHunksForEdit(diff, this.options.parseDiffOptions)\n );\n }\n\n if (pendingStructuralRows != null && result != null) {\n for (const [line, row] of pendingStructuralRows) {\n if (line < result.code.additionLines.length) {\n result.code.additionLines[line] = row;\n }\n }\n }\n\n if (renderCache != null) {\n renderCache.isDirty = true;\n }\n }\n\n // Session-mode counterpart of the line-count recompute: derive canonical\n // old/current pairing and rebuild the old-side region skeleton from it.\n private applySessionDocumentChange(\n diff: FileDiffMetadata,\n previousAdditionLines: readonly string[]\n ): void {\n const { parseDiffOptions } = this.options;\n const rawLines = diff.additionLines;\n if (shouldTopAlignAdditionRecompute(diff, rawLines)) {\n this.applyRecomputePreservingSessionType(\n diff,\n recomputeTopAlignedAdditionDiff(\n diff,\n rawLines,\n diff.additionCharacterCount,\n parseDiffOptions\n )\n );\n return;\n }\n this.applyExpansionRemap(\n rebuildSessionHunks(\n diff,\n parseDiffOptions,\n (index) => previousAdditionLines[index]\n )\n );\n }\n\n // Empty-document and top-aligned recomputes rebuild the complete diff. While\n // editing, keep the session's original classification until finalization.\n private applyRecomputePreservingSessionType(\n diff: FileDiffMetadata,\n update: ReturnType<typeof recomputeEmptyDocumentDiff>\n ): void {\n const sessionType = this.editSessionActive ? diff.type : undefined;\n Object.assign(diff, update);\n if (sessionType != null) {\n diff.type = sessionType;\n }\n this.markEditSessionPass(diff);\n }\n\n // Records a session pass that replaced hunks wholesale.\n private markEditSessionPass(diff: FileDiffMetadata): void {\n if (!this.editSessionActive) {\n return;\n }\n diff.editSessionDirty = true;\n }\n\n protected getUnifiedLineDecoration({\n lineType,\n }: UnifiedLineDecorationProps): LineDecoration {\n return {\n gutterLineType: lineType,\n contentProperties: {\n 'data-line-type': lineType,\n },\n };\n }\n\n protected getSplitLineDecoration({\n side,\n type,\n }: SplitLineDecorationProps): LineDecoration {\n const lineType: LineTypes =\n type === 'change'\n ? side === 'deletions'\n ? 'change-deletion'\n : 'change-addition'\n : type;\n return {\n gutterLineType: lineType,\n contentProperties: {\n 'data-line-type': lineType,\n },\n };\n }\n\n private createAnnotationElement = (span: AnnotationSpan): HASTElement => {\n return createDefaultAnnotationElement(span);\n };\n\n // Unified hook returns extra rows that render before/after the current line.\n declare protected getUnifiedInjectedRowsForLine?: (\n ctx: RenderedLineContext\n ) => UnifiedInjectedRowPlacement | undefined;\n\n // Split hook returns extra rows per side before/after the current line.\n declare protected getSplitInjectedRowsForLine?: (\n ctx: RenderedLineContext\n ) => SplitInjectedRowPlacement | undefined;\n\n protected getOptionsWithDefaults(): DiffHunksRendererOptionsWithDefaults {\n const {\n diffIndicators = 'bars',\n diffStyle = 'split',\n disableBackground = false,\n disableFileHeader = false,\n disableLineNumbers = false,\n disableVirtualizationBuffers = false,\n collapsed = false,\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n expansionLineCount = 100,\n hunkSeparators = 'line-info',\n lineDiffType = 'word-alt',\n maxLineDiffLength = 1000,\n overflow = 'scroll',\n stickyHeader = false,\n theme = DEFAULT_THEMES,\n headerRenderMode = 'default',\n tokenizeMaxLineLength = 1000,\n tokenizeMaxLength = DEFAULT_TOKENIZE_MAX_LENGTH,\n useTokenTransformer = false,\n useCSSClasses = false,\n } = this.options;\n return {\n diffIndicators,\n diffStyle,\n disableBackground,\n disableFileHeader,\n disableLineNumbers,\n disableVirtualizationBuffers,\n collapsed,\n expandUnchanged,\n collapsedContextThreshold,\n expansionLineCount,\n hunkSeparators,\n lineDiffType,\n maxLineDiffLength,\n overflow,\n stickyHeader,\n theme: this.workerManager?.getDiffRenderOptions().theme ?? theme,\n headerRenderMode,\n tokenizeMaxLineLength,\n tokenizeMaxLength,\n useTokenTransformer,\n useCSSClasses,\n };\n }\n\n public initializeHighlighter(): Promise<DiffsHighlighter> {\n return getSharedHighlighter(\n getHighlighterOptions(this.computedLangs, {\n theme: this.getLocalHighlightTheme(),\n preferredHighlighter: resolvePreferredHighlighter(\n this.workerManager,\n this.options\n ),\n })\n );\n }\n\n public hydrate(diff: FileDiffMetadata | undefined): void {\n if (diff == null) {\n return;\n }\n this.diff = diff;\n const { options } = this.getRenderOptions(diff);\n const massiveDiff = isDiffMassive(diff, this.getTokenizeMaxLength());\n let cache = this.workerManager?.getDiffResultCache(diff);\n if (cache != null && !areDiffRenderOptionsEqual(options, cache.options)) {\n cache = undefined;\n }\n this.renderCache ??= {\n diff,\n hydrated: true,\n highlighted: !massiveDiff && !isDiffPlainText(diff),\n options,\n result: massiveDiff ? undefined : cache?.result,\n renderRange: undefined,\n };\n const workerManager = this.getHighlightWorkerManager(diff);\n if (workerManager != null) {\n if (this.renderCache.result == null && !massiveDiff) {\n // We should only kick off a preload of the AST if we have a WorkerPool\n workerManager.highlightDiffAST(this, this.diff);\n }\n }\n // Lets attempt to get the highlighter/languages ready immediately\n else if (\n getHighlighterIfLoaded({ theme: this.getLocalHighlightTheme() }) == null\n ) {\n this.computedLangs = getDiffLanguages(diff);\n void this.initializeHighlighter().catch((error: unknown) => {\n if (!(error instanceof HighlighterDisposedError)) {\n this.onHighlightError(error);\n }\n });\n }\n }\n\n // Returns the pool when there's a valid worker AND we should use it\n private getHighlightWorkerManager(\n diff: FileDiffMetadata\n ): WorkerPoolManager | undefined {\n const { editSessionActive, workerManager } = this;\n return !editSessionActive &&\n workerManager?.isWorkingPool() === true &&\n !workerManager.shouldHighlightOnMainThread(diff)\n ? workerManager\n : undefined;\n }\n\n private cacheHighlightResult(\n diff: FileDiffMetadata,\n renderResult: RenderDiffResult\n ): void {\n const { editSessionActive, workerManager } = this;\n if (!editSessionActive && workerManager?.isWorkingPool() === true) {\n workerManager.setDiffResultCache(diff.cacheKey, renderResult);\n }\n }\n\n private getLocalHighlightTheme(): RenderDiffOptions['theme'] {\n return (\n this.workerManager?.getDiffRenderOptions().theme ??\n this.options.theme ??\n DEFAULT_THEMES\n );\n }\n\n public getEffectiveCodeOptions(): Pick<\n BaseCodeOptions,\n 'theme' | 'tokenizeMaxLineLength'\n > {\n const poolOptions =\n this.workerManager?.isWorkingPool() === true\n ? this.workerManager.getDiffRenderOptions()\n : undefined;\n return {\n theme: this.getLocalHighlightTheme(),\n tokenizeMaxLineLength:\n poolOptions?.tokenizeMaxLineLength ??\n this.options.tokenizeMaxLineLength,\n };\n }\n\n private getRenderOptions(diff: FileDiffMetadata): GetRenderOptionsReturn {\n const options: RenderDiffOptions = (() => {\n if (this.workerManager?.isWorkingPool() === true) {\n const poolOptions = this.workerManager.getDiffRenderOptions();\n // Active edit sessions require `useTokenTransformer: true`\n if (\n this.editSessionActive &&\n poolOptions.useTokenTransformer !== true\n ) {\n return { ...poolOptions, useTokenTransformer: true };\n }\n return poolOptions;\n }\n const { theme, tokenizeMaxLineLength, lineDiffType, maxLineDiffLength } =\n this.getOptionsWithDefaults();\n return {\n theme,\n useTokenTransformer:\n this.editSessionActive || this.options.useTokenTransformer === true,\n tokenizeMaxLineLength,\n lineDiffType,\n maxLineDiffLength,\n };\n })();\n this.getOptionsWithDefaults();\n const { renderCache } = this;\n if (renderCache?.result == null) {\n return { options, forceHighlight: true };\n }\n if (\n !areDiffTargetsEqual(diff, renderCache.diff) ||\n !areDiffRenderOptionsEqual(options, renderCache.options)\n ) {\n return { options, forceHighlight: true };\n }\n return { options, forceHighlight: false };\n }\n\n /**\n * Returns the diff that the next synchronous render can commit without\n * changing the renderer's current diff or render cache. Components use this\n * to prepare state that must match the following DOM render.\n */\n public getDiffForNextRender(diff: FileDiffMetadata): FileDiffMetadata {\n const { options } = this.getRenderOptions(diff);\n if (this.getReadyRenderResult(diff, options) != null) {\n return diff;\n }\n\n if (this.renderCache == null) {\n return diff;\n }\n if (areDiffTargetsEqual(this.renderCache.diff, diff)) {\n return this.renderCache.diff;\n }\n\n const hasContent =\n diff.additionLines.length > 0 || diff.deletionLines.length > 0;\n const forcePlainText =\n !hasContent ||\n isDiffPlainText(diff) ||\n isDiffMassive(diff, this.getTokenizeMaxLength());\n return this.canRenderDiff(diff, options, forcePlainText)\n ? diff\n : this.renderCache.diff;\n }\n\n private canRenderDiff(\n diff: FileDiffMetadata,\n options: RenderDiffOptions,\n forcePlainText: boolean\n ): boolean {\n const { renderCache } = this;\n if (renderCache == null || areDiffTargetsEqual(renderCache.diff, diff)) {\n return true;\n }\n if (forcePlainText) {\n return (\n (renderCache.result == null && renderCache.hydrated !== true) ||\n (this.workerManager?.isWorkingPool() === true &&\n !this.workerManager.shouldHighlightOnMainThread(diff)) ||\n getHighlighterIfLoaded({ theme: options.theme }) != null\n );\n }\n // Hydration has highlighted DOM without a local AST. It is still active\n // rendered content and must remain visible while a non-plain replacement\n // is prepared.\n if (renderCache.result == null && renderCache.hydrated !== true) {\n return true;\n }\n\n if (this.getHighlightWorkerManager(diff) != null) {\n return !renderCache.highlighted;\n }\n\n return getHighlighterIfLoaded({ theme: options.theme }) != null;\n }\n\n public renderDiff(\n diff: FileDiffMetadata | undefined = this.diff,\n renderRange: RenderRange = DEFAULT_RENDER_RANGE\n ): HunksRenderResult | undefined {\n this.diff = diff;\n if (diff == null) {\n this.pendingHighlightResult = undefined;\n return undefined;\n }\n const { expandUnchanged, collapsedContextThreshold } =\n this.getOptionsWithDefaults();\n let { options, forceHighlight } = this.getRenderOptions(diff);\n const readyResult = this.getReadyRenderResult(diff, options);\n this.pendingHighlightResult = undefined;\n if (readyResult != null) {\n this.renderCache = {\n ...readyResult,\n diff,\n renderRange: undefined,\n };\n forceHighlight = false;\n }\n this.renderCache ??= {\n diff,\n highlighted: false,\n options,\n result: undefined,\n renderRange: undefined,\n };\n const hasContent =\n diff.additionLines.length > 0 || diff.deletionLines.length > 0;\n const forcePlainText =\n !hasContent ||\n isDiffPlainText(diff) ||\n isDiffMassive(diff, this.getTokenizeMaxLength());\n const canRenderDiff = this.canRenderDiff(diff, options, forcePlainText);\n const newContent = !areDiffTargetsEqual(diff, this.renderCache.diff);\n const newRenderRange = !areRenderRangesEqual(\n this.renderCache.renderRange,\n renderRange\n );\n const workerManager = this.getHighlightWorkerManager(diff);\n if (workerManager != null) {\n // Hydration has highlighted DOM but no local AST. Keep that DOM until\n // its corresponding worker result is ready.\n const preserveHydratedContent =\n this.renderCache.result == null &&\n this.renderCache.highlighted &&\n !forcePlainText &&\n !newContent &&\n isDefaultRenderRange(renderRange);\n if (\n canRenderDiff &&\n !preserveHydratedContent &&\n (forcePlainText ||\n this.renderCache.result == null ||\n (!this.renderCache.highlighted && (newContent || newRenderRange)))\n ) {\n this.renderCache.diff = diff;\n this.renderCache.options = options;\n this.renderCache.highlighted = false;\n if (\n this.renderCache.result == null ||\n newContent ||\n newRenderRange ||\n forceHighlight\n ) {\n this.renderCache.result = workerManager.getPlainDiffAST(\n diff,\n renderRange.startingLine,\n renderRange.totalLines,\n // If we aren't using a windowed render, then we need to render\n // everything\n isDefaultRenderRange(renderRange)\n ? true\n : expandUnchanged\n ? true\n : this.expandedHunks,\n collapsedContextThreshold\n );\n }\n this.renderCache.renderRange = renderRange;\n }\n\n // Should we kick off an async highlight process\n if (\n !forcePlainText &&\n hasContent &&\n (!this.renderCache.highlighted || forceHighlight)\n ) {\n workerManager.highlightDiffAST(this, diff);\n }\n } else {\n this.computedLangs = getDiffLanguages(diff);\n const highlighter = getHighlighterIfLoaded();\n const hasThemes =\n highlighter != null && areThemesAttached(options.theme, highlighter);\n const hasLangs =\n highlighter != null &&\n areLanguagesAttached(this.computedLangs, highlighter);\n const canHighlight = !forcePlainText && hasLangs;\n const lazyLineAST = Number.isFinite(renderRange.totalLines);\n\n if (\n canRenderDiff &&\n highlighter != null &&\n hasThemes &&\n (forceHighlight ||\n forcePlainText ||\n (!this.renderCache.highlighted && canHighlight) ||\n this.renderCache.result == null)\n ) {\n const { result, options } = this.renderDiffWithHighlighter(\n diff,\n highlighter,\n forcePlainText || !hasLangs,\n lazyLineAST\n );\n this.renderCache = {\n diff,\n options,\n highlighted: canHighlight,\n result,\n renderRange: undefined,\n };\n if (canHighlight) {\n this.cacheHighlightResult(diff, { result, options });\n }\n }\n\n if (!hasThemes || (!forcePlainText && !hasLangs)) {\n void this.asyncHighlight(diff, lazyLineAST)\n .then(({ result, options }) => {\n if (!forcePlainText) {\n this.cacheHighlightResult(diff, { result, options });\n }\n this.applyHighlightResult(diff, result, options, !forcePlainText);\n })\n .catch((error: unknown) => {\n if (!(error instanceof HighlighterDisposedError)) {\n this.onHighlightError(error);\n }\n });\n }\n }\n return this.renderCache.result != null\n ? this.processDiffResult(\n this.renderCache.diff,\n renderRange,\n this.renderCache.result\n )\n : undefined;\n }\n\n public async asyncRender(\n diff: FileDiffMetadata,\n renderRange: RenderRange = DEFAULT_RENDER_RANGE\n ): Promise<HunksRenderResult> {\n this.diff = diff;\n const { result } = await this.asyncHighlight(\n diff,\n Number.isFinite(renderRange.totalLines)\n );\n return this.processDiffResult(diff, renderRange, result);\n }\n\n protected createPreElement(\n split: boolean,\n totalLines: number,\n customProperties?: CustomPreProperties\n ): HASTElement {\n const { diffIndicators, disableBackground, disableLineNumbers, overflow } =\n this.getOptionsWithDefaults();\n return createPreElement({\n type: 'diff',\n diffIndicators,\n disableBackground,\n disableLineNumbers,\n overflow,\n split,\n totalLines,\n customProperties,\n });\n }\n\n private async asyncHighlight(\n diff: FileDiffMetadata,\n lazyLineAST = false\n ): Promise<RenderDiffResult> {\n const forcePlainText = isDiffMassive(diff, this.getTokenizeMaxLength());\n this.computedLangs = forcePlainText ? ['text'] : getDiffLanguages(diff);\n let highlighter = getHighlighterIfLoaded();\n const hasThemes =\n highlighter != null &&\n areThemesAttached(this.getLocalHighlightTheme(), highlighter);\n const hasLangs =\n forcePlainText ||\n (highlighter != null &&\n areLanguagesAttached(this.computedLangs, highlighter));\n // If we don't have the required langs or themes, then we need to\n // initialize the highlighter to load the appropriate languages and themes\n if (highlighter == null || !hasThemes || !hasLangs) {\n highlighter = await this.initializeHighlighter();\n }\n return this.renderDiffWithHighlighter(\n diff,\n highlighter,\n forcePlainText,\n lazyLineAST\n );\n }\n\n private renderDiffWithHighlighter(\n diff: FileDiffMetadata,\n highlighter: DiffsHighlighter,\n forcePlainText = false,\n lazyLineAST = false\n ): RenderDiffResult {\n const { options } = this.getRenderOptions(diff);\n const { collapsedContextThreshold } = this.getOptionsWithDefaults();\n const result = renderDiffWithHighlighter(diff, highlighter, options, {\n forcePlainText,\n lazyLineAST,\n expandedHunks: forcePlainText ? true : undefined,\n collapsedContextThreshold,\n });\n if (\n this.editSessionActive &&\n diff.additionLines.length === 1 &&\n diff.additionLines[0] === '' &&\n result.code.additionLines[0] == null\n ) {\n let fallbackLine: DiffLineMetadata | undefined;\n iterateOverDiff({\n diff,\n diffStyle: 'both',\n expandedHunks: forcePlainText ? true : undefined,\n collapsedContextThreshold,\n callback: ({ additionLine }) => {\n if (additionLine?.lineIndex !== 0) return;\n fallbackLine = additionLine;\n return true;\n },\n });\n if (fallbackLine == null) {\n throw new Error('DiffHunksRenderer: missing empty addition line');\n }\n result.code.additionLines[0] = createPlainAdditionLineElement(\n 0,\n '',\n fallbackLine.unifiedLineIndex,\n fallbackLine.splitLineIndex\n );\n }\n return { result, options };\n }\n\n public onHighlightSuccess(\n diff: FileDiffMetadata,\n result: ThemedDiffResult,\n options: RenderDiffOptions,\n highlighted = true\n ): void {\n if (this.editSessionActive) {\n return;\n }\n this.applyHighlightResult(diff, result, options, highlighted);\n }\n\n private applyHighlightResult(\n diff: FileDiffMetadata,\n result: ThemedDiffResult,\n options: RenderDiffOptions,\n highlighted = true\n ): void {\n const { diff: currentDiff, renderCache } = this;\n if (\n currentDiff == null ||\n renderCache == null ||\n !areDiffTargetsEqual(currentDiff, diff) ||\n !areDiffRenderOptionsEqual(\n options,\n this.getRenderOptions(currentDiff).options\n )\n ) {\n return;\n }\n\n const triggerRender =\n renderCache.result == null ||\n !renderCache.highlighted ||\n !areDiffRenderOptionsEqual(renderCache.options, options) ||\n !areDiffTargetsEqual(renderCache.diff, currentDiff);\n if (!triggerRender) {\n return;\n }\n\n this.pendingHighlightResult = {\n diff: currentDiff,\n options,\n highlighted,\n result,\n };\n this.onRenderUpdate?.();\n }\n\n private getMatchingWorkerResultCache(\n diff: FileDiffMetadata,\n options: RenderDiffOptions\n ): RenderDiffResult | undefined {\n if (this.editSessionActive) {\n return undefined;\n }\n const cache = this.workerManager?.getDiffResultCache(diff);\n if (cache == null || !areDiffRenderOptionsEqual(options, cache.options)) {\n return undefined;\n }\n return cache;\n }\n\n // Returns completed background work that can replace the rendered AST on\n // the next render. Reading it does not promote or discard pending work.\n private getReadyRenderResult(\n diff: FileDiffMetadata,\n options: RenderDiffOptions\n ): PendingHighlightResult | undefined {\n const { pendingHighlightResult } = this;\n if (\n pendingHighlightResult != null &&\n areDiffTargetsEqual(pendingHighlightResult.diff, diff) &&\n areDiffRenderOptionsEqual(pendingHighlightResult.options, options)\n ) {\n return pendingHighlightResult;\n }\n\n const workerCache = this.getMatchingWorkerResultCache(diff, options);\n // Return nothing when the worker has not finished, or when this diff is\n // already rendered with matching highlighted markup. In both cases the\n // current render cache should remain unchanged.\n if (workerCache == null || this.hasHighlightedRenderCache(diff, options)) {\n return undefined;\n }\n return { diff, highlighted: true, ...workerCache };\n }\n\n private hasHighlightedRenderCache(\n diff: FileDiffMetadata,\n options: RenderDiffOptions\n ): boolean {\n const { renderCache } = this;\n return (\n renderCache?.result != null &&\n renderCache.highlighted &&\n areDiffTargetsEqual(diff, renderCache.diff) &&\n areDiffRenderOptionsEqual(options, renderCache.options)\n );\n }\n\n public onHighlightError(error: unknown): void {\n console.error(error);\n }\n\n private getTokenizeMaxLength(): number {\n return this.options.tokenizeMaxLength ?? DEFAULT_TOKENIZE_MAX_LENGTH;\n }\n\n private processDiffResult(\n fileDiff: FileDiffMetadata,\n renderRange: RenderRange,\n { code, themeStyles, baseThemeType }: ThemedDiffResult\n ): HunksRenderResult {\n const {\n diffStyle,\n disableFileHeader,\n expandUnchanged,\n expansionLineCount,\n collapsedContextThreshold,\n hunkSeparators,\n } = this.getOptionsWithDefaults();\n const isRenderCacheDirty = this.renderCache?.isDirty ?? false;\n\n const unified = diffStyle === 'unified';\n const canHydrateContext = canHydrateCollapsedContext(\n fileDiff,\n this.options.loadDiffFiles != null\n );\n const isExpandableDiff = !fileDiff.isPartial || canHydrateContext;\n\n let additionsContentAST: ElementContent[] | undefined = [];\n let deletionsContentAST: ElementContent[] | undefined = [];\n let unifiedContentAST: ElementContent[] | undefined = [];\n\n const hunkData: HunkData[] = [];\n const { additionLines, deletionLines } = code;\n const context: ProcessContext = {\n rowCount: 0,\n hunkSeparators,\n additionsContentAST,\n deletionsContentAST,\n unifiedContentAST,\n unifiedGutterAST: createGutterWrapper(),\n deletionsGutterAST: createGutterWrapper(),\n additionsGutterAST: createGutterWrapper(),\n expansionLineCount,\n hunkData,\n incrementRowCount(count = 1) {\n context.rowCount += count;\n },\n pushToGutter(type: CodeColumnType, element: HASTElement) {\n switch (type) {\n case 'unified': {\n context.unifiedGutterAST.children.push(element);\n break;\n }\n case 'deletions': {\n context.deletionsGutterAST.children.push(element);\n break;\n }\n case 'additions': {\n context.additionsGutterAST.children.push(element);\n break;\n }\n }\n },\n };\n const trailingRangeSize = getTrailingContextRangeSize({\n fileDiff,\n errorPrefix: 'DiffHunksRenderer.processDiffResult',\n });\n const pendingSplitContext: PendingSplitContext = {\n size: 0,\n side: undefined,\n increment() {\n this.size += 1;\n },\n flush() {\n if (diffStyle === 'unified') {\n return;\n }\n if (this.size <= 0 || this.side == null) {\n this.side = undefined;\n this.size = 0;\n return;\n }\n if (this.side === 'additions') {\n context.pushToGutter(\n 'additions',\n createGutterGap(undefined, 'buffer', this.size)\n );\n additionsContentAST?.push(createEmptyRowBuffer(this.size));\n } else {\n context.pushToGutter(\n 'deletions',\n createGutterGap(undefined, 'buffer', this.size)\n );\n deletionsContentAST?.push(createEmptyRowBuffer(this.size));\n }\n this.size = 0;\n this.side = undefined;\n },\n };\n\n const pushGutterLineNumber = (\n type: CodeColumnType,\n lineType: LineTypes | 'buffer' | 'separator' | 'annotation',\n lineNumber: number,\n lineIndex: string,\n gutterProperties: Properties | undefined\n ) => {\n context.pushToGutter(\n type,\n createGutterItem(lineType, lineNumber, lineIndex, gutterProperties)\n );\n };\n\n function pushSeparators(props: PushSeparatorProps) {\n pendingSplitContext.flush();\n if (diffStyle === 'unified') {\n pushSeparator('unified', props, context);\n } else {\n pushSeparator('deletions', props, context);\n pushSeparator('additions', props, context);\n }\n }\n\n this.pushFileLevelAnnotations(fileDiff, diffStyle, renderRange, context);\n\n iterateOverDiff({\n diff: fileDiff,\n diffStyle,\n startingLine: renderRange.startingLine,\n totalLines: renderRange.totalLines,\n expandedHunks: expandUnchanged ? true : this.expandedHunks,\n collapsedContextThreshold,\n callback: ({\n hunkIndex,\n hunk,\n collapsedBefore,\n collapsedAfter,\n additionLine,\n deletionLine,\n type,\n }) => {\n const splitLineIndex =\n deletionLine != null\n ? deletionLine.splitLineIndex\n : additionLine.splitLineIndex;\n const unifiedLineIndex =\n additionLine != null\n ? additionLine.unifiedLineIndex\n : deletionLine.unifiedLineIndex;\n\n if (diffStyle === 'split' && type !== 'change') {\n pendingSplitContext.flush();\n }\n\n if (collapsedBefore > 0) {\n pushSeparators({\n hunkIndex,\n collapsedLines: collapsedBefore,\n rangeSize: Math.max(hunk?.collapsedBefore ?? 0, 0),\n hunkSpecs: hunk?.hunkSpecs,\n isFirstHunk: hunkIndex === 0,\n isLastHunk: false,\n isExpandable: isExpandableDiff,\n });\n }\n\n const lineIndex =\n diffStyle === 'unified' ? unifiedLineIndex : splitLineIndex;\n const renderedLineContext: RenderedLineContext = {\n type,\n hunkIndex,\n lineIndex,\n unifiedLineIndex,\n splitLineIndex,\n deletionLine,\n additionLine,\n };\n\n if (diffStyle === 'unified') {\n const injectedRows =\n this.getUnifiedInjectedRowsForLine?.(renderedLineContext);\n if (injectedRows?.before != null) {\n pushUnifiedInjectedRows(injectedRows.before, context);\n }\n let deletionLineContent =\n deletionLine != null\n ? deletionLines[deletionLine.lineIndex]\n : undefined;\n let additionLineContent =\n additionLine != null\n ? additionLines[additionLine.lineIndex]\n : undefined;\n if (deletionLineContent == null && additionLineContent == null) {\n const errorMessage =\n 'DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong';\n console.error(errorMessage, { file: fileDiff.name });\n throw new Error(errorMessage);\n }\n const lineType =\n type === 'change'\n ? additionLine != null\n ? 'change-addition'\n : 'change-deletion'\n : type;\n const lineDecoration = this.getUnifiedLineDecoration({\n // NOTE: This function gets extended so don't remove\n // these extra props\n type,\n lineType,\n additionLineIndex: additionLine?.lineIndex,\n deletionLineIndex: deletionLine?.lineIndex,\n });\n pushGutterLineNumber(\n 'unified',\n lineDecoration.gutterLineType,\n additionLine != null\n ? additionLine.lineNumber\n : deletionLine.lineNumber,\n `${unifiedLineIndex},${splitLineIndex}`,\n lineDecoration.gutterProperties\n );\n if (additionLineContent != null) {\n additionLineContent = withContentProperties(\n additionLineContent,\n lineDecoration.contentProperties,\n isRenderCacheDirty && additionLine != null\n ? {\n 'data-line': additionLine.lineNumber,\n 'data-line-index': `${unifiedLineIndex},${splitLineIndex}`,\n }\n : undefined\n );\n } else if (deletionLineContent != null) {\n deletionLineContent = withContentProperties(\n deletionLineContent,\n lineDecoration.contentProperties,\n isRenderCacheDirty && deletionLine != null\n ? {\n 'data-line': deletionLine.lineNumber,\n 'data-line-index': `${unifiedLineIndex},${splitLineIndex}`,\n }\n : undefined\n );\n }\n pushLineWithAnnotation({\n diffStyle: 'unified',\n type: type,\n deletionLine: deletionLineContent,\n additionLine: additionLineContent,\n unifiedSpan: this.getAnnotations(\n 'unified',\n deletionLine?.lineNumber,\n additionLine?.lineNumber,\n hunkIndex,\n lineIndex\n ),\n createAnnotationElement: (span) =>\n this.createAnnotationElement(span),\n context,\n });\n if (injectedRows?.after != null) {\n pushUnifiedInjectedRows(injectedRows.after, context);\n }\n } else {\n const injectedRows =\n this.getSplitInjectedRowsForLine?.(renderedLineContext);\n if (injectedRows?.before != null) {\n pushSplitInjectedRows(\n injectedRows.before,\n context,\n pendingSplitContext\n );\n }\n\n let deletionLineContent =\n deletionLine != null\n ? deletionLines[deletionLine.lineIndex]\n : undefined;\n let additionLineContent =\n additionLine != null\n ? additionLines[additionLine.lineIndex]\n : undefined;\n const deletionLineDecoration = this.getSplitLineDecoration({\n side: 'deletions',\n type,\n lineIndex: deletionLine?.lineIndex,\n });\n const additionLineDecoration = this.getSplitLineDecoration({\n side: 'additions',\n type,\n lineIndex: additionLine?.lineIndex,\n });\n\n if (deletionLineContent == null && additionLineContent == null) {\n const errorMessage =\n 'DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong';\n console.error(errorMessage, { file: fileDiff.name });\n throw new Error(errorMessage);\n }\n\n const missingSide = (() => {\n if (type === 'change') {\n if (additionLineContent == null) {\n return 'additions';\n } else if (deletionLineContent == null) {\n return 'deletions';\n }\n }\n return undefined;\n })();\n if (missingSide != null) {\n if (\n pendingSplitContext.side != null &&\n pendingSplitContext.side !== missingSide\n ) {\n pendingSplitContext.flush();\n }\n pendingSplitContext.side = missingSide;\n pendingSplitContext.increment();\n } else if (type === 'change') {\n // A change row with both sides fills the column a pending\n // one-sided buffer was holding open (an insert/delete block\n // directly followed by a paired block, from similarity\n // realignment); flush first so the buffer lands above this row.\n pendingSplitContext.flush();\n }\n\n const annotationSpans = this.getAnnotations(\n 'split',\n deletionLine?.lineNumber,\n additionLine?.lineNumber,\n hunkIndex,\n lineIndex\n );\n if (annotationSpans != null && pendingSplitContext.size > 0) {\n pendingSplitContext.flush();\n }\n\n if (deletionLine != null) {\n const deletionLineDecorated = withContentProperties(\n deletionLineContent,\n deletionLineDecoration.contentProperties,\n isRenderCacheDirty\n ? {\n 'data-line': deletionLine.lineNumber,\n 'data-line-index': `${deletionLine.unifiedLineIndex},${splitLineIndex}`,\n }\n : undefined\n );\n pushGutterLineNumber(\n 'deletions',\n deletionLineDecoration.gutterLineType,\n deletionLine.lineNumber,\n `${deletionLine.unifiedLineIndex},${splitLineIndex}`,\n deletionLineDecoration.gutterProperties\n );\n if (deletionLineDecorated != null) {\n deletionLineContent = deletionLineDecorated;\n }\n }\n if (additionLine != null) {\n const additionLineDecorated = withContentProperties(\n additionLineContent,\n additionLineDecoration.contentProperties,\n isRenderCacheDirty\n ? {\n 'data-line': additionLine.lineNumber,\n 'data-line-index': `${additionLine.unifiedLineIndex},${splitLineIndex}`,\n }\n : undefined\n );\n pushGutterLineNumber(\n 'additions',\n additionLineDecoration.gutterLineType,\n additionLine.lineNumber,\n `${additionLine.unifiedLineIndex},${splitLineIndex}`,\n additionLineDecoration.gutterProperties\n );\n if (additionLineDecorated != null) {\n additionLineContent = additionLineDecorated;\n }\n }\n pushLineWithAnnotation({\n diffStyle: 'split',\n type: type,\n additionLine: additionLineContent,\n deletionLine: deletionLineContent,\n ...annotationSpans,\n createAnnotationElement: (span) =>\n this.createAnnotationElement(span),\n context,\n });\n if (injectedRows?.after != null) {\n pushSplitInjectedRows(\n injectedRows.after,\n context,\n pendingSplitContext\n );\n }\n }\n\n const isFinalSplitHunkRow =\n diffStyle === 'split' &&\n hunk != null &&\n splitLineIndex === hunk.splitLineStart + hunk.splitLineCount - 1;\n const isFinalHunkRow =\n hunkIndex === fileDiff.hunks.length - 1 &&\n hunk != null &&\n (diffStyle === 'split'\n ? splitLineIndex === hunk.splitLineStart + hunk.splitLineCount - 1\n : unifiedLineIndex ===\n hunk.unifiedLineStart + hunk.unifiedLineCount - 1);\n const splitNoEOFCRDeletion = isFinalSplitHunkRow\n ? hunk.noEOFCRDeletions\n : false;\n const splitNoEOFCRAddition = isFinalSplitHunkRow\n ? hunk.noEOFCRAdditions\n : false;\n const noEOFCRDeletion =\n (deletionLine?.noEOFCR ?? false) || splitNoEOFCRDeletion;\n const noEOFCRAddition =\n (additionLine?.noEOFCR ?? false) || splitNoEOFCRAddition;\n if (noEOFCRAddition || noEOFCRDeletion) {\n if (diffStyle === 'split') {\n pendingSplitContext.flush();\n }\n if (noEOFCRDeletion) {\n const noEOFType =\n type === 'context' || type === 'context-expanded'\n ? type\n : 'change-deletion';\n if (diffStyle === 'unified') {\n context.unifiedContentAST.push(createNoNewlineElement(noEOFType));\n context.pushToGutter(\n 'unified',\n createGutterGap(noEOFType, 'metadata', 1)\n );\n } else {\n context.deletionsContentAST.push(\n createNoNewlineElement(noEOFType)\n );\n context.pushToGutter(\n 'deletions',\n createGutterGap(noEOFType, 'metadata', 1)\n );\n if (!noEOFCRAddition) {\n context.pushToGutter(\n 'additions',\n createGutterGap(undefined, 'buffer', 1)\n );\n context.additionsContentAST.push(createEmptyRowBuffer(1));\n }\n }\n }\n if (\n noEOFCRAddition &&\n !(unified && noEOFCRDeletion && type !== 'change')\n ) {\n const noEOFType =\n type === 'context' || type === 'context-expanded'\n ? type\n : 'change-addition';\n if (diffStyle === 'unified') {\n context.unifiedContentAST.push(createNoNewlineElement(noEOFType));\n context.pushToGutter(\n 'unified',\n createGutterGap(noEOFType, 'metadata', 1)\n );\n } else {\n context.additionsContentAST.push(\n createNoNewlineElement(noEOFType)\n );\n context.pushToGutter(\n 'additions',\n createGutterGap(noEOFType, 'metadata', 1)\n );\n if (!noEOFCRDeletion) {\n context.pushToGutter(\n 'deletions',\n createGutterGap(undefined, 'buffer', 1)\n );\n context.deletionsContentAST.push(createEmptyRowBuffer(1));\n }\n }\n }\n context.incrementRowCount(1);\n }\n\n if (\n hunkSeparators !== 'simple' &&\n hunkSeparators !== 'metadata' &&\n (collapsedAfter > 0 || (isFinalHunkRow && canHydrateContext))\n ) {\n pushSeparators({\n hunkIndex: type === 'context-expanded' ? hunkIndex : hunkIndex + 1,\n collapsedLines:\n isFinalHunkRow && canHydrateContext ? 'unknown' : collapsedAfter,\n rangeSize: trailingRangeSize,\n hunkSpecs: undefined,\n isFirstHunk: false,\n isLastHunk: true,\n isExpandable: isExpandableDiff,\n });\n }\n context.incrementRowCount(1);\n },\n });\n\n if (diffStyle === 'split') {\n pendingSplitContext.flush();\n }\n\n const totalLines = Math.max(\n getTotalLineCountFromHunks(fileDiff.hunks),\n fileDiff.additionLines.length ?? 0,\n fileDiff.deletionLines.length ?? 0\n );\n\n const hasBuffer =\n renderRange.bufferBefore > 0 || renderRange.bufferAfter > 0;\n // Determine which ASTs to include based on diff style and file type\n const shouldIncludeAdditions = !unified && fileDiff.type !== 'deleted';\n const shouldIncludeDeletions = !unified && fileDiff.type !== 'new';\n const hasContent = context.rowCount > 0 || hasBuffer;\n\n additionsContentAST =\n shouldIncludeAdditions && hasContent ? additionsContentAST : undefined;\n deletionsContentAST =\n shouldIncludeDeletions && hasContent ? deletionsContentAST : undefined;\n unifiedContentAST = unified && hasContent ? unifiedContentAST : undefined;\n\n const preNode = this.createPreElement(\n deletionsContentAST != null && additionsContentAST != null,\n totalLines\n );\n\n return {\n fileDiff,\n unifiedGutterAST:\n unified && hasContent ? context.unifiedGutterAST.children : undefined,\n unifiedContentAST,\n deletionsGutterAST:\n shouldIncludeDeletions && hasContent\n ? context.deletionsGutterAST.children\n : undefined,\n deletionsContentAST,\n additionsGutterAST:\n shouldIncludeAdditions && hasContent\n ? context.additionsGutterAST.children\n : undefined,\n additionsContentAST,\n hunkData,\n preNode,\n themeStyles,\n baseThemeType,\n headerElement: !disableFileHeader\n ? this.renderHeader(fileDiff)\n : undefined,\n totalLines,\n rowCount: context.rowCount,\n bufferBefore: renderRange.bufferBefore,\n bufferAfter: renderRange.bufferAfter,\n // FIXME\n css: '',\n };\n }\n\n public renderCodeAST(\n type: 'unified' | 'deletions' | 'additions',\n result: HunksRenderResult\n ): ElementContent[] | undefined {\n const gutterAST =\n type === 'unified'\n ? result.unifiedGutterAST\n : type === 'deletions'\n ? result.deletionsGutterAST\n : result.additionsGutterAST;\n\n const contentAST =\n type === 'unified'\n ? result.unifiedContentAST\n : type === 'deletions'\n ? result.deletionsContentAST\n : result.additionsContentAST;\n\n if (gutterAST == null || contentAST == null) {\n return undefined;\n }\n\n const gutter = createGutterWrapper(gutterAST);\n gutter.properties.style = `grid-row: span ${result.rowCount}`;\n const contentColumn = createContentColumn(contentAST, result.rowCount);\n return [gutter, contentColumn];\n }\n\n public renderFullAST(\n result: HunksRenderResult,\n children: ElementContent[] = []\n ): HASTElement {\n const containerSize =\n this.getOptionsWithDefaults().hunkSeparators === 'line-info';\n const unifiedAST = this.renderCodeAST('unified', result);\n if (unifiedAST != null) {\n children.push(\n createHastElement({\n tagName: 'code',\n children: unifiedAST,\n properties: {\n 'data-code': '',\n 'data-container-size': containerSize ? '' : undefined,\n 'data-unified': '',\n },\n })\n );\n return { ...result.preNode, children };\n }\n\n const deletionsAST = this.renderCodeAST('deletions', result);\n if (deletionsAST != null) {\n children.push(\n createHastElement({\n tagName: 'code',\n children: deletionsAST,\n properties: {\n 'data-code': '',\n 'data-container-size': containerSize ? '' : undefined,\n 'data-deletions': '',\n },\n })\n );\n }\n const additionsAST = this.renderCodeAST('additions', result);\n if (additionsAST != null) {\n children.push(\n createHastElement({\n tagName: 'code',\n children: additionsAST,\n properties: {\n 'data-code': '',\n 'data-container-size': containerSize ? '' : undefined,\n 'data-additions': '',\n },\n })\n );\n }\n return { ...result.preNode, children };\n }\n\n public renderFullHTML(\n result: HunksRenderResult,\n tempChildren: ElementContent[] = []\n ): string {\n return hastToHtml(this.renderFullAST(result, tempChildren));\n }\n\n public renderPartialHTML(\n children: ElementContent[],\n columnType?: 'unified' | 'deletions' | 'additions'\n ): string {\n if (columnType == null) {\n return hastToHtml(children);\n }\n return hastToHtml(\n createHastElement({\n tagName: 'code',\n children,\n properties: {\n 'data-code': '',\n 'data-container-size':\n this.getOptionsWithDefaults().hunkSeparators === 'line-info'\n ? ''\n : undefined,\n [`data-${columnType}`]: '',\n },\n })\n );\n }\n\n private pushFileLevelAnnotations(\n fileDiff: FileDiffMetadata,\n diffStyle: 'unified' | 'split',\n renderRange: RenderRange,\n context: ProcessContext\n ): void {\n if (!shouldRenderFileAnnotations(renderRange)) {\n return;\n }\n\n const deletionAnnotationNames =\n fileDiff.type !== 'new'\n ? this.getAnnotationNames(getFileAnnotations(this.deletionAnnotations))\n : [];\n const additionAnnotationNames =\n fileDiff.type !== 'deleted'\n ? this.getAnnotationNames(getFileAnnotations(this.additionAnnotations))\n : [];\n if (\n deletionAnnotationNames.length === 0 &&\n additionAnnotationNames.length === 0\n ) {\n return;\n }\n\n const hunkIndex = FILE_ANNOTATION_HUNK_INDEX;\n const lineIndex = FILE_ANNOTATION_LINE_INDEX;\n const { createAnnotationElement } = this;\n\n if (diffStyle === 'unified') {\n pushLineWithAnnotation({\n diffStyle,\n type: 'context',\n unifiedSpan: {\n type: 'annotation',\n hunkIndex,\n lineIndex,\n annotations: deletionAnnotationNames.concat(additionAnnotationNames),\n },\n createAnnotationElement,\n context,\n });\n return;\n }\n\n pushLineWithAnnotation({\n diffStyle,\n type: 'context',\n deletionSpan: {\n type: 'annotation',\n hunkIndex,\n lineIndex,\n annotations: deletionAnnotationNames,\n },\n additionSpan: {\n type: 'annotation',\n hunkIndex,\n lineIndex,\n annotations: additionAnnotationNames,\n },\n createAnnotationElement,\n context,\n });\n }\n\n private getAnnotations(\n type: 'unified',\n deletionLineNumber: number | undefined,\n additionLineNumber: number | undefined,\n hunkIndex: number,\n lineIndex: number\n ): AnnotationSpan | undefined;\n private getAnnotations(\n type: 'split',\n deletionLineNumber: number | undefined,\n additionLineNumber: number | undefined,\n hunkIndex: number,\n lineIndex: number\n ): { deletionSpan: AnnotationSpan; additionSpan: AnnotationSpan } | undefined;\n private getAnnotations(\n type: 'unified' | 'split',\n deletionLineNumber: number | undefined,\n additionLineNumber: number | undefined,\n hunkIndex: number,\n lineIndex: number\n ):\n | AnnotationSpan\n | { deletionSpan: AnnotationSpan; additionSpan: AnnotationSpan }\n | undefined {\n const deletionSpan: AnnotationSpan = {\n type: 'annotation',\n hunkIndex,\n lineIndex,\n annotations: [],\n };\n if (deletionLineNumber != null) {\n for (const anno of this.deletionAnnotations[deletionLineNumber] ?? []) {\n deletionSpan.annotations.push(this.annotationSlotName(anno));\n }\n }\n const additionSpan: AnnotationSpan = {\n type: 'annotation',\n hunkIndex,\n lineIndex,\n annotations: [],\n };\n if (additionLineNumber != null) {\n for (const anno of this.additionAnnotations[additionLineNumber] ?? []) {\n (type === 'unified' ? deletionSpan : additionSpan).annotations.push(\n this.annotationSlotName(anno)\n );\n }\n }\n if (type === 'unified') {\n if (deletionSpan.annotations.length > 0) {\n return deletionSpan;\n }\n return undefined;\n }\n if (\n additionSpan.annotations.length === 0 &&\n deletionSpan.annotations.length === 0\n ) {\n return undefined;\n }\n return { deletionSpan, additionSpan };\n }\n\n private getAnnotationNames(\n annotations: DiffLineAnnotation<LAnnotation>[] | undefined\n ): string[] {\n return (\n annotations?.map((annotation) => this.annotationSlotName(annotation)) ??\n []\n );\n }\n\n private renderHeader(diff: FileDiffMetadata): HASTElement {\n const { headerRenderMode, stickyHeader } = this.getOptionsWithDefaults();\n return createFileHeaderElement({\n fileOrDiff: diff,\n mode: headerRenderMode,\n stickyHeader,\n });\n }\n}\n\n// Use the platform's English plural rules to pick \"line\" vs \"lines\" so a\n// count of 0 reads as \"0 unmodified lines\". en-US returns \"one\" only for 1.\nconst EN_PLURAL_RULES = new Intl.PluralRules('en-US');\n\nfunction getModifiedLinesString(lines: number) {\n const suffix = EN_PLURAL_RULES.select(lines) === 'one' ? '' : 's';\n return `${lines} unmodified line${suffix}`;\n}\n\nfunction pushUnifiedInjectedRows(\n rows: InjectedRow[],\n context: ProcessContext\n): void {\n for (const row of rows) {\n context.unifiedContentAST.push(row.content);\n context.pushToGutter('unified', row.gutter);\n context.incrementRowCount(1);\n }\n}\n\nfunction pushSplitInjectedRows(\n rows: SplitInjectedRow[],\n context: ProcessContext,\n pendingSplitContext: PendingSplitContext\n): void {\n for (const { deletion, addition } of rows) {\n if (deletion == null && addition == null) {\n continue;\n }\n const missingSide =\n deletion != null && addition != null\n ? undefined\n : deletion == null\n ? 'deletions'\n : 'additions';\n\n if (missingSide == null || pendingSplitContext.side !== missingSide) {\n pendingSplitContext.flush();\n }\n\n if (deletion != null) {\n context.deletionsContentAST.push(deletion.content);\n context.pushToGutter('deletions', deletion.gutter);\n }\n\n if (addition != null) {\n context.additionsContentAST.push(addition.content);\n context.pushToGutter('additions', addition.gutter);\n }\n\n if (missingSide != null) {\n pendingSplitContext.side = missingSide;\n pendingSplitContext.increment();\n }\n\n context.incrementRowCount(1);\n }\n}\n\nfunction pushLineWithAnnotation({\n diffStyle,\n type,\n deletionLine,\n additionLine,\n unifiedSpan,\n deletionSpan,\n additionSpan,\n createAnnotationElement,\n context,\n}: PushLineWithAnnotation) {\n let hasAnnotationRow = false;\n if (diffStyle === 'unified') {\n if (additionLine != null) {\n context.unifiedContentAST.push(additionLine);\n } else if (deletionLine != null) {\n context.unifiedContentAST.push(deletionLine);\n }\n if (unifiedSpan != null) {\n const lineType =\n type === 'change'\n ? deletionLine != null\n ? 'change-deletion'\n : 'change-addition'\n : type;\n context.unifiedContentAST.push(createAnnotationElement(unifiedSpan));\n context.pushToGutter(\n 'unified',\n createGutterGap(lineType, 'annotation', 1)\n );\n hasAnnotationRow = true;\n }\n } else if (diffStyle === 'split') {\n if (deletionLine != null) {\n context.deletionsContentAST.push(deletionLine);\n }\n if (additionLine != null) {\n context.additionsContentAST.push(additionLine);\n }\n if (deletionSpan != null) {\n const lineType =\n type === 'change'\n ? deletionLine != null\n ? 'change-deletion'\n : 'context'\n : type;\n context.deletionsContentAST.push(createAnnotationElement(deletionSpan));\n context.pushToGutter(\n 'deletions',\n createGutterGap(lineType, 'annotation', 1)\n );\n hasAnnotationRow = true;\n }\n if (additionSpan != null) {\n const lineType =\n type === 'change'\n ? additionLine != null\n ? 'change-addition'\n : 'context'\n : type;\n context.additionsContentAST.push(createAnnotationElement(additionSpan));\n context.pushToGutter(\n 'additions',\n createGutterGap(lineType, 'annotation', 1)\n );\n hasAnnotationRow = true;\n }\n }\n if (hasAnnotationRow) {\n context.incrementRowCount(1);\n }\n}\n\nfunction pushSeparator(\n type: 'additions' | 'deletions' | 'unified',\n {\n hunkIndex,\n collapsedLines,\n rangeSize,\n hunkSpecs,\n isFirstHunk,\n isLastHunk,\n isExpandable,\n }: PushSeparatorProps,\n context: ProcessContext\n) {\n if (typeof collapsedLines === 'number' && collapsedLines <= 0) {\n return;\n }\n const linesAST =\n type === 'unified'\n ? context.unifiedContentAST\n : type === 'deletions'\n ? context.deletionsContentAST\n : context.additionsContentAST;\n\n if (context.hunkSeparators === 'metadata') {\n if (hunkSpecs != null) {\n context.pushToGutter(\n type,\n createSeparator({\n type: 'metadata',\n content: hunkSpecs,\n isFirstHunk,\n isLastHunk,\n })\n );\n linesAST.push(\n createSeparator({\n type: 'metadata',\n content: hunkSpecs,\n isFirstHunk,\n isLastHunk,\n })\n );\n if (type !== 'additions') {\n context.incrementRowCount(1);\n }\n }\n return;\n }\n if (context.hunkSeparators === 'simple') {\n if (hunkIndex > 0) {\n context.pushToGutter(\n type,\n createSeparator({ type: 'simple', isFirstHunk, isLastHunk: false })\n );\n linesAST.push(\n createSeparator({ type: 'simple', isFirstHunk, isLastHunk: false })\n );\n if (type !== 'additions') {\n context.incrementRowCount(1);\n }\n }\n return;\n }\n const slotName = getHunkSeparatorSlotName(type, hunkIndex);\n const chunked = rangeSize > context.expansionLineCount;\n const expandIndex = isExpandable ? hunkIndex : undefined;\n const content =\n typeof collapsedLines === 'number'\n ? getModifiedLinesString(collapsedLines)\n : 'More unchanged context may be available';\n context.pushToGutter(\n type,\n createSeparator({\n type: context.hunkSeparators,\n content,\n expandIndex,\n chunked,\n slotName,\n isFirstHunk,\n isLastHunk,\n })\n );\n linesAST.push(\n createSeparator({\n type: context.hunkSeparators,\n content,\n expandIndex,\n chunked,\n slotName,\n isFirstHunk,\n isLastHunk,\n })\n );\n if (type !== 'additions') {\n context.incrementRowCount(1);\n }\n context.hunkData.push({\n slotName,\n hunkIndex,\n lines: typeof collapsedLines === 'number' ? collapsedLines : 0,\n lineCountKnown: typeof collapsedLines === 'number',\n type,\n expandable: isExpandable\n ? { up: !isFirstHunk, down: !isLastHunk, chunked }\n : undefined,\n });\n}\n\nfunction withContentProperties(\n lineNode: ElementContent | undefined,\n contentProperties?: Properties,\n extendProperties?: Properties\n): ElementContent | undefined {\n if (\n lineNode == null ||\n lineNode.type !== 'element' ||\n (contentProperties == null && extendProperties == null)\n ) {\n return lineNode;\n }\n return {\n ...lineNode,\n properties: {\n ...lineNode.properties,\n ...contentProperties,\n ...extendProperties,\n },\n };\n}\n\n// Number of entries in a split-line array that hold document content. A\n// document ending in a line break is represented two ways during a session:\n// the parsed-diff shape (`splitFileContents`) has no entry for the empty line\n// that final break implies, while the editor-document shape\n// (`getEditorDocumentLines`) exposes it as a trailing `''` entry. Only that\n// representational tail is ever `''` — every other entry keeps its line break\n// or is the raw final line — so trimming it yields comparable content lines.\nfunction contentLineCount(lines: string[]): number {\n return lines.length > 0 && lines[lines.length - 1] === ''\n ? lines.length - 1\n : lines.length;\n}\n\n// Realigns the cached per-line addition HAST array with an edited document.\n// Cached entries are looked up by line index, so a line inserted or removed\n// mid-document must shift the surviving entries to their new indexes —\n// otherwise rows hidden during the edit (collapsed context) render another\n// line's stale tokens once they become visible. Entries outside the changed\n// window keep their highlighted content; changed rows without fresh tokens\n// become plain-text elements for the editor's next background pass.\n//\n// The bottom-up scan runs over content lines only: a session's first\n// line-count edit still has `previousLines` in the parsed-diff shape while\n// `nextLines` is editor-shaped, and comparing the raw tails would mismatch on\n// the representational trailing `''`, zero out the suffix, and plain-fill\n// every line below the tokenizer's render window.\nfunction realignAdditionHastLines<LAnnotation>(\n previousLines: string[],\n nextLines: string[],\n hastLines: ElementContent[],\n textDocument: TextDocument<'file-diff', LAnnotation>\n): ElementContent[] {\n const previousContentLength = contentLineCount(previousLines);\n const nextContentLength = contentLineCount(nextLines);\n const maxShared = Math.min(previousContentLength, nextContentLength);\n let prefix = 0;\n while (prefix < maxShared && previousLines[prefix] === nextLines[prefix]) {\n prefix++;\n }\n let suffix = 0;\n while (\n suffix < maxShared - prefix &&\n previousLines[previousContentLength - 1 - suffix] ===\n nextLines[nextContentLength - 1 - suffix]\n ) {\n suffix++;\n }\n\n const realigned: ElementContent[] = new Array(nextLines.length);\n for (let index = 0; index < prefix; index++) {\n realigned[index] = hastLines[index];\n }\n for (let offset = 0; offset < suffix; offset++) {\n realigned[nextContentLength - 1 - offset] =\n hastLines[previousContentLength - 1 - offset];\n }\n // A trailing empty entry present on both sides keeps its cached row.\n if (\n previousContentLength < previousLines.length &&\n nextContentLength < nextLines.length\n ) {\n realigned[nextLines.length - 1] = hastLines[previousLines.length - 1];\n }\n for (let index = prefix; index < nextLines.length; index++) {\n realigned[index] ??= createPlainAdditionLineElement(\n index,\n textDocument.getLineText(index)\n );\n }\n return realigned;\n}\n\n// The editor shows one empty row after a final `\\n` that the parsed diff has\n// no entry for. Text typed there is real file content only when that row is\n// the document's single extra line. A lone `\\r` also starts an editor line but\n// not a diff line, so any other count means the coordinates disagree and the\n// row cannot be appended safely.\nfunction canAppendFinalDocumentRow(\n additionLines: readonly string[],\n documentLineCount: number | undefined\n): boolean {\n return (\n documentLineCount === additionLines.length + 1 &&\n additionLines.at(-1)?.endsWith('\\n') === true\n );\n}\n\nfunction createPlainAdditionLineElement(\n lineIndex: number,\n lineText: string,\n unifiedLineIndex = lineIndex,\n splitLineIndex = lineIndex\n): HASTElement {\n return {\n type: 'element',\n tagName: 'div',\n properties: {\n 'data-line': lineIndex + 1,\n 'data-line-index': `${unifiedLineIndex},${splitLineIndex}`,\n 'data-line-type': 'context',\n },\n children: [\n {\n type: 'element',\n tagName: 'span',\n properties: {\n 'data-char': 0,\n },\n children: [\n {\n type: 'text',\n value: lineText,\n },\n ],\n },\n ],\n };\n}\n\n// Reads every document line (with its line break) plus their total character\n// count, so callers can replace `additionLines` and its count in one pass.\nfunction getEditorDocumentLines<LAnnotation>(\n textDocument: TextDocument<'file-diff', LAnnotation>\n): { lines: string[]; characterCount: number } {\n const lines: string[] = [];\n let characterCount = 0;\n for (let line = 0; line < textDocument.lineCount; line++) {\n const text = textDocument.getLineText(line, true);\n lines.push(text);\n characterCount += text.length;\n }\n return { lines, characterCount };\n}\n\n// Renames can supply 2 different languages, so lets go ahead and figure out\n// the required languages\nfunction getDiffLanguages(diff: FileDiffMetadata): SupportedLanguages[] {\n if (diff.lang != null) {\n return [diff.lang];\n }\n const deletionLang = getFiletypeFromFileName(diff.prevName ?? diff.name);\n const additionLang = getFiletypeFromFileName(diff.name);\n return deletionLang === additionLang\n ? [additionLang]\n : [deletionLang, additionLang];\n}\n\nfunction isDiffMassive(\n diff: FileDiffMetadata,\n tokenizeMaxLength: number\n): boolean {\n return (\n Math.max(diff.additionLines.length, diff.deletionLines.length) >\n tokenizeMaxLength\n );\n}\n\nfunction canHydrateCollapsedContext(\n fileDiff: FileDiffMetadata,\n hasFileLoader: boolean\n): boolean {\n return (\n fileDiff.isPartial &&\n hasFileLoader &&\n (fileDiff.type === 'change' || fileDiff.type === 'rename-changed')\n );\n}\n", "import type { DiffLineAnnotation } from '../types';\n\nexport function areDiffLineAnnotationsEqual<LAnnotation = undefined>(\n annotationA: DiffLineAnnotation<LAnnotation>,\n annotationB: DiffLineAnnotation<LAnnotation>\n): boolean {\n return (\n annotationA.lineNumber === annotationB.lineNumber &&\n annotationA.side === annotationB.side &&\n annotationA.metadata === annotationB.metadata\n );\n}\n", "import type { HunkData } from '../types';\n\nexport function areHunkDataEqual(hunkA: HunkData, hunkB: HunkData): boolean {\n return (\n hunkA.slotName === hunkB.slotName &&\n hunkA.hunkIndex === hunkB.hunkIndex &&\n hunkA.lines === hunkB.lines &&\n hunkA.lineCountKnown === hunkB.lineCountKnown &&\n hunkA.type === hunkB.type &&\n hunkA.expandable?.chunked === hunkB.expandable?.chunked &&\n hunkA.expandable?.up === hunkB.expandable?.up &&\n hunkA.expandable?.down === hunkB.expandable?.down\n );\n}\n", "export async function awaitWithTimeout(\n callback: () => Promise<unknown>,\n timeout: number = 300\n): Promise<void> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n callback(),\n new Promise<void>((resolve) => {\n timeoutId = setTimeout(resolve, timeout);\n }),\n ]);\n } finally {\n if (timeoutId != null) {\n clearTimeout(timeoutId);\n }\n }\n}\n", "import type { DiffFileInput, FileContents } from '../types';\n\ninterface GetDiffFileInputProps {\n oldFile?: FileContents | null;\n newFile?: FileContents | null;\n}\n\nexport function getDiffFileInput(\n { oldFile, newFile }: GetDiffFileInputProps,\n context: string\n): DiffFileInput | undefined {\n if (oldFile === undefined && newFile === undefined) {\n return undefined;\n }\n if (oldFile === undefined || newFile === undefined) {\n throw new Error(\n `${context}: Pass null for an intentionally missing oldFile or newFile side`\n );\n }\n if (oldFile === null) {\n if (newFile === null) {\n throw new Error(`${context}: You must pass oldFile, newFile, or both`);\n }\n return { oldFile, newFile };\n }\n if (newFile === null) {\n return { oldFile, newFile };\n }\n return { oldFile, newFile };\n}\n", "import type { FileDiffOptions } from '../components/FileDiff';\nimport type { DiffHunksRendererOptions } from '../renderers/DiffHunksRenderer';\nimport { shouldUseTokenTransformer } from './shouldUseTokenTransformer';\n\n// Build the renderer option snapshot with direct property reads. CodeView item\n// options may inherit prototype getters, so object spread can miss values.\nexport function getDiffHunksRendererOptions<LAnnotation, Caret>(\n options: FileDiffOptions<LAnnotation, Caret> | undefined\n): DiffHunksRendererOptions {\n return {\n theme: options?.theme,\n disableLineNumbers: options?.disableLineNumbers,\n overflow: options?.overflow,\n collapsed: options?.collapsed,\n disableFileHeader: options?.disableFileHeader,\n disableVirtualizationBuffers: options?.disableVirtualizationBuffers,\n stickyHeader: options?.stickyHeader,\n preferredHighlighter: options?.preferredHighlighter,\n useCSSClasses: options?.useCSSClasses,\n useTokenTransformer: shouldUseTokenTransformer<'diff'>(options),\n tokenizeMaxLineLength: options?.tokenizeMaxLineLength,\n tokenizeMaxLength: options?.tokenizeMaxLength,\n diffStyle: options?.diffStyle,\n diffIndicators: options?.diffIndicators,\n disableBackground: options?.disableBackground,\n hunkSeparators:\n typeof options?.hunkSeparators === 'function'\n ? 'custom'\n : options?.hunkSeparators,\n expandUnchanged: options?.expandUnchanged,\n loadDiffFiles: options?.loadDiffFiles,\n parseDiffOptions: options?.parseDiffOptions,\n collapsedContextThreshold: options?.collapsedContextThreshold,\n lineDiffType: options?.lineDiffType,\n maxLineDiffLength: options?.maxLineDiffLength,\n expansionLineCount: options?.expansionLineCount,\n headerRenderMode:\n options?.renderCustomHeader != null ? 'custom' : 'default',\n };\n}\n", "import type { ElementContent, Element as HASTElement } from 'hast';\n\nimport {\n CUSTOM_HEADER_SLOT_ID,\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n DEFAULT_THEMES,\n DEFAULT_TOKENIZE_MAX_LENGTH,\n DIFFS_TAG_NAME,\n EMPTY_LINE_ANNOTATIONS,\n EMPTY_RENDER_RANGE,\n HEADER_FILENAME_SUFFIX_SLOT_ID,\n HEADER_METADATA_SLOT_ID,\n HEADER_PREFIX_SLOT_ID,\n THEME_CSS_ATTRIBUTE,\n UNSAFE_CSS_ATTRIBUTE,\n} from '../constants';\nimport type { Editor } from '../editor/editor';\nimport type { TextDocument } from '../editor/textDocument';\nimport type {\n CapturedDiffSessionState,\n EditCompletionDecision,\n EditorActiveLineOptions,\n EditorChangeEvent,\n FileDiffEditCompleteEvent,\n RetainedDiffSessionSnapshot,\n} from '../editor/types';\nimport {\n getHighlighterIfLoaded,\n getSharedHighlighter,\n HighlighterDisposedError,\n} from '../highlighter/shared_highlighter';\nimport {\n type GetHoveredLineResult,\n type GetLineIndexUtility,\n InteractionManager,\n type InteractionManagerBaseOptions,\n pluckInteractionOptions,\n type SelectionWriteOptions,\n} from '../managers/InteractionManager';\nimport { ResizeManager } from '../managers/ResizeManager';\nimport { ScrollSyncManager } from '../managers/ScrollSyncManager';\nimport {\n dequeueRender,\n queueRender,\n} from '../managers/UniversalRenderingManager';\nimport {\n DiffHunksRenderer,\n type DiffHunksRendererOptions,\n type HunksRenderResult,\n} from '../renderers/DiffHunksRenderer';\nimport { SVGSpriteSheet } from '../sprite';\nexport type { FileDiffEditCompleteEvent } from '../editor/types';\nimport type {\n AppliedThemeStyleCache,\n BaseCodeOptions,\n BaseDiffOptions,\n CustomPreProperties,\n DiffLineAnnotation,\n ExpansionDirections,\n DiffsHighlighter,\n FileContents,\n FileDiffMetadata,\n HighlightedToken,\n HunkData,\n HunkSeparators,\n LineAnnotation,\n MaybeDiffFileInput,\n PostRenderPhase,\n PrePropertiesConfig,\n RenderHeaderFilenameSuffixCallback,\n RenderHeaderMetadataCallback,\n RenderHeaderPrefixCallback,\n RenderRange,\n SelectedLineRange,\n SelectionSide,\n ThemeTypes,\n} from '../types';\nimport { areDiffLineAnnotationsEqual } from '../utils/areDiffLineAnnotationsEqual';\nimport { areDiffTargetsEqual } from '../utils/areDiffTargetsEqual';\nimport { areFilesEqual } from '../utils/areFilesEqual';\nimport { areHunkDataEqual } from '../utils/areHunkDataEqual';\nimport { arePrePropertiesEqual } from '../utils/arePrePropertiesEqual';\nimport { areRenderRangesEqual } from '../utils/areRenderRangesEqual';\nimport { areThemesEqual } from '../utils/areThemesEqual';\nimport { awaitWithTimeout } from '../utils/awaitWithTimeout';\nimport {\n cloneFileDiffMetadata,\n cloneHunks,\n} from '../utils/cloneFileDiffMetadata';\nimport { createAnnotationWrapperNode } from '../utils/createAnnotationWrapperNode';\nimport { createGutterUtilityContentNode } from '../utils/createGutterUtilityContentNode';\nimport { createUnsafeCSSStyleNode } from '../utils/createUnsafeCSSStyleNode';\nimport {\n patchScrollbarGutterSize,\n wrapThemeCSS,\n wrapUnsafeCSS,\n} from '../utils/cssWrappers';\nimport {\n adoptEditSessionAnnotations,\n type EditSessionAnnotations,\n resolveEditSessionSlotName,\n writeEditSessionAnnotations,\n} from '../utils/editSessionAnnotations';\nimport {\n captureExpansionAnchors,\n finishEditSessionForDiff,\n rebuildExpansionFromAnchors,\n} from '../utils/editSessionHunks';\nimport { getDiffFileInput } from '../utils/getDiffFileInput';\nimport { getDiffHunksRendererOptions } from '../utils/getDiffHunksRendererOptions';\nimport { getFiletypeFromFileName } from '../utils/getFiletypeFromFileName';\nimport { getHunkSideStartBoundary } from '../utils/getHunkSideBoundaries';\nimport { getLineAnnotationName } from '../utils/getLineAnnotationName';\nimport { getOrCreateCodeNode } from '../utils/getOrCreateCodeNode';\nimport { getThemes } from '../utils/getThemes';\nimport { guardWebKitScrollDuringRebuild } from '../utils/guardWebKitScrollDuringRebuild';\nimport { hastToHtml } from '../utils/hastToHtml';\nimport { upsertHostThemeStyle } from '../utils/hostTheme';\nimport { hydratePartialDiff } from '../utils/hydratePartialDiff';\nimport { isDefaultRenderRange } from '../utils/isDefaultRenderRange';\nimport { isDiffPlainText } from '../utils/isDiffPlainText';\nimport { isStyleNode } from '../utils/isStyleNode';\nimport { iterateOverDiff } from '../utils/iterateOverDiff';\nimport { parseDiffFromFile } from '../utils/parseDiffFromFile';\nimport { isSafari } from '../utils/platform';\nimport { prerenderHTMLIfNecessary } from '../utils/prerenderHTMLIfNecessary';\nimport { resolvePreferredHighlighter } from '../utils/resolvePreferredHighlighter';\nimport { getMeasuredScrollbarGutter } from '../utils/scrollbarGutter';\nimport { setPreNodeProperties } from '../utils/setWrapperNodeProps';\nimport { splitFileContents } from '../utils/splitFileContents';\nimport { recomputeDiffRenderLineCounts } from '../utils/updateDiffHunks';\nimport {\n getExpandedRegion,\n getHunkAdditionLineRange,\n getNearestRenderableAdditionLine,\n getTrailingExpandedRegion,\n isAdditionLineRenderable,\n} from '../utils/virtualDiffLayout';\nimport type { WorkerPoolManager } from '../worker';\nimport { isHandledWorkerPoolError } from '../worker/errors';\nimport { DiffsContainerLoaded } from './web-components';\n\ntype LoadedPartialDiffContents = Awaited<\n ReturnType<NonNullable<BaseDiffOptions['loadDiffFiles']>>\n>;\n\ntype DeferredSelectedLinesWrite = [\n range: SelectedLineRange | null,\n options: SelectionWriteOptions | undefined,\n];\n\ntype DeferredEditorActiveLineWrite = [\n lineNumber: number | null,\n options: EditorActiveLineOptions | undefined,\n];\n\ninterface UpdateRenderCacheOptions {\n shouldRefreshDiffsView?: boolean;\n lineCountChangeInFlight?: boolean;\n changedDocumentLines?: ReadonlyMap<number, string>;\n documentLineCount?: number;\n}\n\nfunction canHydrateDiff(fileDiff: FileDiffMetadata): boolean {\n return (\n fileDiff.isPartial &&\n (fileDiff.type === 'change' ||\n fileDiff.type === 'rename-changed' ||\n fileDiff.type === 'rename-pure')\n );\n}\n\n// Edit sessions incrementally clone the diff as needed while editing,\n// initially we start with a top level fast clone\nfunction createEditSessionDiff(fileDiff: FileDiffMetadata): FileDiffMetadata {\n const editSessionDiff = { ...fileDiff };\n delete editSessionDiff.cacheKey;\n return editSessionDiff;\n}\n\nfunction shouldResetUndoState(\n prevDiff: FileDiffMetadata,\n nextDiff: FileDiffMetadata\n): boolean {\n if (prevDiff.isPartial || nextDiff.isPartial) {\n throw new Error(\n 'FileDiff.shouldResetEditorForExternalDiff: diffs must be fully hydrated'\n );\n }\n const prevLanguage = prevDiff.lang ?? getFiletypeFromFileName(prevDiff.name);\n const nextLanguage = nextDiff.lang ?? getFiletypeFromFileName(nextDiff.name);\n const prevHasOldFile = prevDiff.type !== 'new';\n const nextHasOldFile = nextDiff.type !== 'new';\n if (\n prevDiff.name !== nextDiff.name ||\n prevLanguage !== nextLanguage ||\n prevHasOldFile !== nextHasOldFile ||\n prevDiff.deletionLines.length !== nextDiff.deletionLines.length\n ) {\n return true;\n }\n return prevDiff.deletionLines.some(\n (line, index) => line !== nextDiff.deletionLines[index]\n );\n}\n\nfunction areLinesEqual(first: string[], second: string[]): boolean {\n return (\n first.length === second.length &&\n first.every((line, index) => line === second[index])\n );\n}\n\n// There are certain scenarios where if a diff changes in a certain way, we\n// cannot consider the session resumable. Basically if the old file has\n// changed in any way (name or contents), then our restored diff would be\n// completely invalid\nfunction canRestoreDiffSession(\n snapshot: RetainedDiffSessionSnapshot,\n inputDiff: FileDiffMetadata\n): boolean {\n const { oldFile } = snapshot;\n if (oldFile == null) {\n return inputDiff.type === 'new';\n }\n return (\n inputDiff.type !== 'new' &&\n oldFile.name === (inputDiff.prevName ?? inputDiff.name) &&\n areLinesEqual(oldFile.lines, inputDiff.deletionLines)\n );\n}\n\nexport interface FileDiffRenderBaseProps<LAnnotation> {\n fileDiff?: FileDiffMetadata;\n deferManagers?: boolean;\n forceRender?: boolean;\n preventEmit?: boolean;\n fileContainer?: HTMLElement;\n containerWrapper?: HTMLElement;\n lineAnnotations?: DiffLineAnnotation<LAnnotation>[];\n renderRange?: RenderRange;\n}\n\nexport type FileDiffRenderProps<LAnnotation> =\n FileDiffRenderBaseProps<LAnnotation> & MaybeDiffFileInput;\n\nexport type FileDiffHydrationProps<LAnnotation> = Omit<\n FileDiffRenderBaseProps<LAnnotation>,\n 'fileContainer'\n> &\n MaybeDiffFileInput & {\n fileContainer: HTMLElement;\n prerenderedHTML?: string;\n };\n\nexport type FileDiffType = 'file-diff' | 'unresolved-file';\n\nexport type FileDiffEditChangeHandler<LAnnotation, Caret> = (\n event: EditorChangeEvent<'file-diff', LAnnotation, Caret>\n) => void;\n\n/**\n * Decides a completed edit synchronously: return `'accept'` to install the\n * event's `fileDiff` and annotations, or `'reject'` to restore the original\n * values. The event is frozen, so re-key the accepted diff in place\n * (`event.fileDiff.cacheKey = '…'`) before accepting. The event's editor is\n * detached and returns its final state from `getViewState()`. A missing handler\n * rejects.\n */\nexport type FileDiffEditCompleteHandler<LAnnotation, Caret> = (\n event: FileDiffEditCompleteEvent<LAnnotation, Caret>\n) => EditCompletionDecision;\n\nexport interface FileDiffOptions<LAnnotation, Caret>\n extends\n Omit<BaseDiffOptions, 'hunkSeparators'>,\n InteractionManagerBaseOptions<'diff'> {\n hunkSeparators?:\n | Exclude<HunkSeparators, 'custom'> /**\n * @deprecated Custom hunk separator functions are deprecated and will be\n * removed in a future version.\n */\n | ((\n hunk: HunkData,\n instance: FileDiff<LAnnotation, Caret>\n ) => HTMLElement | DocumentFragment | null | undefined);\n disableFileHeader?: boolean;\n renderHeaderPrefix?: RenderHeaderPrefixCallback;\n renderHeaderFilenameSuffix?: RenderHeaderFilenameSuffixCallback;\n renderHeaderMetadata?: RenderHeaderMetadataCallback;\n renderCustomHeader?: RenderHeaderMetadataCallback;\n /**\n * When true, errors during rendering are rethrown instead of being caught\n * and displayed in the DOM. Useful for testing or when you want to handle\n * errors yourself.\n */\n disableErrorHandling?: boolean;\n /** Receives the matching diff, including any editor changes. */\n renderAnnotation?(\n annotation: DiffLineAnnotation<LAnnotation>,\n fileDiff: FileDiffMetadata\n ): HTMLElement | undefined;\n renderGutterUtility?(\n getHoveredRow: () => GetHoveredLineResult<'diff'> | undefined\n ): HTMLElement | null | undefined;\n\n onPostRender?(\n node: HTMLElement,\n instance: FileDiff<LAnnotation, Caret>,\n phase: PostRenderPhase\n ): unknown;\n\n /**\n * Fired for every document change of an active edit session on this\n * component, with the same `EditorChangeEvent` the editor reports through\n * its own `onChange`. Do not feed the event's file back into the component\n * while the session is active.\n */\n onEditChange?: FileDiffEditChangeHandler<LAnnotation, Caret>;\n\n /**\n * Fired when `edit` toggles false or a component unmounts, including when the\n * final contents are unchanged. If no callback is provided, the component\n * reverts to the last `fileDiff` or `oldFile`/`newFiles` and annotations\n * passed into it. The callback receives the detached editor with its final\n * pre-detach state.\n */\n onEditComplete?: FileDiffEditCompleteHandler<LAnnotation, Caret>;\n}\n\ninterface AnnotationElementCache<LAnnotation> {\n element: HTMLElement;\n annotation: DiffLineAnnotation<LAnnotation>;\n fileDiff: FileDiffMetadata;\n}\n\ninterface CustomHunkElementCache {\n element: HTMLElement;\n hunkData: HunkData;\n}\n\ninterface ColumnElements {\n gutter: HTMLElement;\n content: HTMLElement;\n}\n\ninterface TrimColumnsToOverlapProps {\n columns:\n | [ColumnElements | undefined, ColumnElements | undefined]\n | ColumnElements;\n diffStyle: 'split' | 'unified';\n overlapEnd: number;\n overlapStart: number;\n previousStart: number;\n trimEnd: number;\n trimStart: number;\n}\n\ninterface ApplyPartialRenderProps {\n fileDiff: FileDiffMetadata;\n previousRenderRange: RenderRange | undefined;\n renderRange: RenderRange | undefined;\n}\n\ninterface PendingFileLoad {\n fileDiff: FileDiffMetadata;\n promise: Promise<void>;\n}\n\ntype HydrationSetup<LAnnotation> = {\n fileDiff: FileDiffMetadata | undefined;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n} & MaybeDiffFileInput;\n\ninterface HeaderCache {\n lastRenderedHTML: string | undefined;\n html: string | undefined;\n fileDiff: FileDiffMetadata | undefined;\n}\n\nexport interface FileDiffRenderData<LAnnotation> {\n fileDiff: FileDiffMetadata;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[];\n}\n\nexport interface FileDiffRenderInput<LAnnotation> {\n fileDiff: FileDiffMetadata;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n}\n\ninterface EditSession<LAnnotation> {\n // Editable copy of the diff. Changes in the editor are written here.\n diff: FileDiffMetadata;\n // Latest input, kept separately so rejecting edits can restore it.\n inputDiff: FileDiffMetadata;\n annotations:\n | EditSessionAnnotations<DiffLineAnnotation<LAnnotation>>\n | undefined;\n // Diff still held by the editor's document until it syncs to a replacement.\n // Keep it to compare the old-file contents for undo and to save the session.\n outgoingDiff: FileDiffMetadata | undefined;\n}\n\nlet instanceId = -1;\n\nexport class FileDiff<LAnnotation = undefined, Caret = undefined> {\n // NOTE(amadeus): We sorta need this to ensure the web-component file is\n // properly loaded\n static LoadedCustomComponent: boolean = DiffsContainerLoaded;\n\n readonly __id: string = `file-diff:${++instanceId}`;\n readonly type: FileDiffType = 'file-diff';\n\n protected fileContainer: HTMLElement | undefined;\n protected spriteSVG: SVGElement | undefined;\n protected pre: HTMLPreElement | undefined;\n protected codeUnified: HTMLElement | undefined;\n protected codeDeletions: HTMLElement | undefined;\n protected codeAdditions: HTMLElement | undefined;\n protected bufferBefore: HTMLElement | undefined;\n protected bufferAfter: HTMLElement | undefined;\n protected themeCSSStyle: HTMLStyleElement | undefined;\n protected appliedThemeCSS: AppliedThemeStyleCache | undefined;\n protected hasAdoptedThemeCSS = false;\n protected unsafeCSSStyle: HTMLStyleElement | undefined;\n protected appliedUnsafeCSS: string | undefined;\n protected gutterUtilityContent: HTMLElement | undefined;\n\n protected headerElement: HTMLElement | undefined;\n protected headerPrefix: HTMLElement | undefined;\n protected headerFilenameSuffix: HTMLElement | undefined;\n protected headerMetadata: HTMLElement | undefined;\n protected headerCustom: HTMLElement | undefined;\n protected separatorCache: Map<string, CustomHunkElementCache> = new Map();\n protected errorWrapper: HTMLElement | undefined;\n protected placeHolder: HTMLElement | undefined;\n\n protected hunksRenderer: DiffHunksRenderer<LAnnotation>;\n protected resizeManager: ResizeManager;\n protected scrollSyncManager: ScrollSyncManager;\n protected interactionManager: InteractionManager<'diff'>;\n\n protected annotationCache: Map<string, AnnotationElementCache<LAnnotation>> =\n new Map();\n // Annotations for the displayed diff, stored with that diff in renderedData.\n protected get lineAnnotations(): DiffLineAnnotation<LAnnotation>[] {\n return this.renderedData?.lineAnnotations ?? EMPTY_LINE_ANNOTATIONS;\n }\n protected managersDirty = false;\n\n protected deletionFile?: FileContents | null;\n protected additionFile?: FileContents | null;\n // Latest input. Editor changes are kept in the private edit session.\n public fileDiff: FileDiffMetadata | undefined;\n private editSession: EditSession<LAnnotation> | undefined;\n // Diff and annotations currently displayed. Absent until a diff is rendered.\n private renderedData: FileDiffRenderData<LAnnotation> | undefined;\n // Keep the next diff and its annotations together until that diff renders.\n private pendingData: FileDiffRenderData<LAnnotation> | undefined;\n // Forces the next render() call, such as the one the owner makes after\n // requestOwnerRender.\n protected forceRenderOverride: true | undefined;\n protected renderRange: RenderRange | undefined;\n protected pendingFiles: PendingFileLoad | undefined;\n protected appliedPreAttributes: PrePropertiesConfig | undefined;\n protected headerCache: HeaderCache = {\n lastRenderedHTML: undefined,\n html: undefined,\n fileDiff: undefined,\n };\n protected lastRowCount: number | undefined;\n private mounted = false;\n\n protected enabled = true;\n\n protected editor: Editor<'file-diff', LAnnotation, Caret> | undefined;\n protected refreshViewTimeout: ReturnType<typeof setTimeout> | undefined;\n // Defer selected-line and editor active-line writes while a refresh rebuilds\n // the diff rows. This is separate from the timeout because the refresh can\n // escalate to a full rerender without one.\n protected lineStateRefreshPending = false;\n protected deferredSelectedLines: DeferredSelectedLinesWrite | undefined;\n protected deferredEditorActiveLine: DeferredEditorActiveLineWrite | undefined;\n\n constructor(\n public options: FileDiffOptions<LAnnotation, Caret> = {\n theme: DEFAULT_THEMES,\n },\n protected workerManager?: WorkerPoolManager | undefined,\n // Set when an owner such as React manages the container. Internal renders\n // call it, and the owner must call render().\n protected requestOwnerRender?: () => void\n ) {\n this.hunksRenderer = this.createHunksRenderer(options);\n this.resizeManager = new ResizeManager();\n this.scrollSyncManager = new ScrollSyncManager();\n this.interactionManager = new InteractionManager(\n 'diff',\n pluckInteractionOptions(\n options,\n typeof options.hunkSeparators === 'function' ||\n (options.hunkSeparators ?? 'line-info') === 'line-info' ||\n options.hunkSeparators === 'line-info-basic'\n ? this.handleExpandHunk\n : undefined,\n this.getLineIndex\n )\n );\n this.workerManager?.subscribeToThemeChanges(this);\n this.enabled = true;\n }\n\n protected handleHighlightRender = (): void => {\n this.rerender();\n };\n\n private getTheme() {\n return (\n this.workerManager?.getDiffRenderOptions().theme ??\n this.options.theme ??\n DEFAULT_THEMES\n );\n }\n\n protected getHunksRendererOptions(\n options: FileDiffOptions<LAnnotation, Caret>\n ): DiffHunksRendererOptions {\n return getDiffHunksRendererOptions(options);\n }\n\n protected createHunksRenderer(\n options: FileDiffOptions<LAnnotation, Caret>\n ): DiffHunksRenderer<LAnnotation> {\n return new DiffHunksRenderer<LAnnotation>(\n this.getHunksRendererOptions(options),\n this.getAnnotationSlotName,\n this.handleHighlightRender,\n this.workerManager\n );\n }\n\n public getLineIndex: GetLineIndexUtility = (\n lineNumber: number,\n side: SelectionSide = 'additions'\n ) => {\n return this.getLineIndexForDiff(\n this.getDiffForLineIndex(),\n lineNumber,\n side\n );\n };\n\n protected getDiffForLineIndex(): FileDiffMetadata | undefined {\n return this.getRenderedDiff();\n }\n\n // Resolve source lines against the same diff that produced the rendered\n // rows. During an asynchronous replacement, that can be the previous diff.\n protected getLineIndexForDiff(\n fileDiff: FileDiffMetadata | undefined,\n lineNumber: number,\n side: SelectionSide\n ): [number, number] | undefined {\n if (fileDiff == null) {\n return undefined;\n }\n const lastHunk = fileDiff.hunks.at(-1);\n let targetUnifiedIndex: number | undefined;\n let targetSplitIndex: number | undefined;\n hunkIterator: for (const hunk of fileDiff.hunks) {\n const hunkStart =\n side === 'deletions' ? hunk.deletionStart : hunk.additionStart;\n const hunkCount =\n side === 'deletions' ? hunk.deletionCount : hunk.additionCount;\n let currentLineNumber =\n getHunkSideStartBoundary(hunkStart, hunkCount) + 1;\n let splitIndex = hunk.splitLineStart;\n let unifiedIndex = hunk.unifiedLineStart;\n\n // If we've selected a line between or before a hunk,\n // we should grab its index here\n if (lineNumber < currentLineNumber) {\n const difference = currentLineNumber - lineNumber;\n targetUnifiedIndex = Math.max(unifiedIndex - difference, 0);\n targetSplitIndex = Math.max(splitIndex - difference, 0);\n break hunkIterator;\n }\n\n if (lineNumber >= currentLineNumber + hunkCount) {\n if (hunk === lastHunk) {\n const difference = lineNumber - (currentLineNumber + hunkCount);\n targetUnifiedIndex =\n unifiedIndex + hunk.unifiedLineCount + difference;\n targetSplitIndex = splitIndex + hunk.splitLineCount + difference;\n break hunkIterator;\n }\n continue;\n }\n\n for (const content of hunk.hunkContent) {\n if (content.type === 'context') {\n if (lineNumber < currentLineNumber + content.lines) {\n const difference = lineNumber - currentLineNumber;\n targetSplitIndex = splitIndex + difference;\n targetUnifiedIndex = unifiedIndex + difference;\n break hunkIterator;\n } else {\n currentLineNumber += content.lines;\n splitIndex += content.lines;\n unifiedIndex += content.lines;\n }\n } else {\n const sideCount =\n side === 'deletions' ? content.deletions : content.additions;\n if (lineNumber < currentLineNumber + sideCount) {\n const indexDifference = lineNumber - currentLineNumber;\n targetUnifiedIndex =\n unifiedIndex +\n (side === 'additions' ? content.deletions : 0) +\n indexDifference;\n targetSplitIndex = splitIndex + indexDifference;\n\n break hunkIterator;\n } else {\n currentLineNumber += sideCount;\n splitIndex += Math.max(content.deletions, content.additions);\n unifiedIndex += content.deletions + content.additions;\n }\n }\n }\n\n break hunkIterator;\n }\n\n if (targetUnifiedIndex == null || targetSplitIndex == null) {\n return undefined;\n }\n return [targetUnifiedIndex, targetSplitIndex];\n }\n\n // FIXME(amadeus): This is a bit of a looming issue that I'll need to resolve:\n // * Do we publicly allow merging of options or do we have individualized setters?\n // * When setting new options, we need to figure out what settings require a\n // re-render and which can just be applied more elegantly\n // * There's also an issue of options that live here on the File class and\n // those that live on the Hunk class, and it's a bit of an issue with passing\n // settings down and mirroring them (not great...)\n public setOptions(\n options: FileDiffOptions<LAnnotation, Caret> | undefined\n ): void {\n if (options == null) return;\n this.options = options;\n this.clearReusableHeader();\n this.hunksRenderer.setOptions(this.getHunksRendererOptions(options));\n this.syncInteractionOptions();\n }\n\n protected syncInteractionOptions(): void {\n this.interactionManager.setOptions(\n pluckInteractionOptions(\n this.options,\n typeof this.options.hunkSeparators === 'function' ||\n (this.options.hunkSeparators ?? 'line-info') === 'line-info' ||\n this.options.hunkSeparators === 'line-info-basic'\n ? this.handleExpandHunk\n : undefined,\n this.getLineIndex\n )\n );\n }\n\n private mergeOptions(\n options: Partial<FileDiffOptions<LAnnotation, Caret>>\n ): void {\n this.options = { ...this.options, ...options };\n }\n\n public setThemeType(themeType: ThemeTypes): void {\n if ((this.options.themeType ?? 'system') === themeType) {\n return;\n }\n this.mergeOptions({ themeType });\n this.applyCachedThemeState(themeType);\n }\n\n private applyCachedThemeState(themeType: ThemeTypes): boolean {\n if (\n typeof this.options.theme === 'string' ||\n this.fileContainer == null ||\n this.appliedThemeCSS == null\n ) {\n return false;\n }\n const effectiveThemeType = this.appliedThemeCSS.baseThemeType ?? themeType;\n if (this.appliedThemeCSS.themeType === effectiveThemeType) {\n return false;\n }\n this.applyThemeState(\n this.fileContainer,\n this.appliedThemeCSS.themeStyles,\n themeType,\n this.appliedThemeCSS.baseThemeType\n );\n return true;\n }\n\n private hasThemeChanged(): boolean {\n return (\n this.appliedThemeCSS != null &&\n !areThemesEqual(this.appliedThemeCSS.theme, this.getTheme())\n );\n }\n\n public getHoveredLine = (): GetHoveredLineResult<'diff'> | undefined => {\n return this.interactionManager.getHoveredLine();\n };\n\n public getAnnotationSlotName = (\n annotation: LineAnnotation<LAnnotation> | DiffLineAnnotation<LAnnotation>\n ): string => {\n return resolveEditSessionSlotName(\n this.editSession?.annotations,\n annotation,\n getLineAnnotationName\n );\n };\n\n // Return annotations for the working diff, including updates that haven't\n // been rendered yet.\n protected getLatestAnnotations(): DiffLineAnnotation<LAnnotation>[] {\n return (\n this.pendingData?.lineAnnotations ??\n this.editSession?.annotations?.current ??\n this.lineAnnotations\n );\n }\n\n // Use pending annotations only when their diff is selected for rendering.\n protected getAnnotationsForDiff(\n fileDiff: FileDiffMetadata\n ): DiffLineAnnotation<LAnnotation>[] {\n const { pendingData } = this;\n return pendingData != null &&\n areDiffTargetsEqual(fileDiff, pendingData.fileDiff)\n ? pendingData.lineAnnotations\n : this.lineAnnotations;\n }\n\n // Check whether the annotation array is new. Reusing a tracked array must\n // not reset positions moved by editing.\n protected isNewAnnotations(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): boolean {\n const session = this.editSession?.annotations;\n const latestAnnotations = this.getLatestAnnotations();\n if (lineAnnotations === latestAnnotations) {\n return false;\n }\n return (\n session == null ||\n (lineAnnotations !== session.provided &&\n lineAnnotations !== session.current)\n );\n }\n\n public setLineAnnotations(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): void {\n const sessionAnnotations = this.editSession?.annotations;\n if (sessionAnnotations != null) {\n if (!this.isNewAnnotations(lineAnnotations)) {\n return;\n }\n // Use the new annotations for editing, and keep their original positions\n // so rejecting the edit can restore them.\n writeEditSessionAnnotations(\n sessionAnnotations,\n lineAnnotations,\n getLineAnnotationName\n );\n }\n const fileDiff = this.getWorkingDiff();\n if (fileDiff != null) {\n this.pendingData = { fileDiff, lineAnnotations };\n }\n }\n\n // Takes annotations the editor remapped and makes them what the session\n // renders: updates the session, feeds the renderer, and re-renders\n // annotation rows. Returns true when new annotations were adopted —\n // virtualized subclasses override this and refresh their layout on true.\n //\n // The editor delivers annotations through two calls. An edit that changes\n // the line count sends them with the structural rebuild\n // (applyDocumentChange) and again with the change event (__acceptEditorChange);\n // the identity check makes the second call a no-op. An edit that keeps the\n // line count skips the rebuild, so the event is its only path here.\n //\n // The annotations the caller passed in are never touched — stale\n // re-renders keep deduping against them.\n protected syncEditSessionAnnotationsFromEditor(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): boolean {\n const session = this.editSession?.annotations;\n if (session == null || lineAnnotations === session.current) {\n return false;\n }\n session.current = lineAnnotations;\n if (this.renderedData != null) {\n this.renderedData.lineAnnotations = lineAnnotations;\n }\n this.pendingData = undefined;\n this.hunksRenderer.setLineAnnotations(lineAnnotations);\n this.renderAnnotations();\n return true;\n }\n\n private canPartiallyRender(\n forceRender: boolean,\n annotationsChanged: boolean,\n didContentChange: boolean\n ): boolean {\n if (\n forceRender ||\n annotationsChanged ||\n didContentChange ||\n typeof this.options.hunkSeparators === 'function'\n ) {\n return false;\n }\n return true;\n }\n\n public setSelectedLines(\n range: SelectedLineRange | null,\n options?: SelectionWriteOptions\n ): void {\n if (this.lineStateRefreshPending) {\n this.deferredSelectedLines = [range, options];\n } else {\n this.interactionManager.setSelection(range, options);\n }\n }\n\n public setEditorActiveLine(\n lineNumber: number | null,\n options?: EditorActiveLineOptions\n ): void {\n if (this.lineStateRefreshPending) {\n this.deferredEditorActiveLine = [lineNumber, options];\n } else {\n this.interactionManager.setEditorActiveLine(lineNumber, {\n lineNumberOnly: options?.lineNumberOnly,\n side: options?.side ?? 'additions',\n });\n }\n }\n\n // A refresh can receive selected-lines and editor active-line writes in either\n // order. Apply the latest value from each after the rows are stable.\n protected flushDeferredLineState(): void {\n const {\n deferredEditorActiveLine: editorActiveLine,\n deferredSelectedLines: selectedLines,\n } = this;\n this.lineStateRefreshPending = false;\n this.deferredEditorActiveLine = undefined;\n this.deferredSelectedLines = undefined;\n\n if (editorActiveLine != null) {\n this.setEditorActiveLine(...editorActiveLine);\n }\n if (selectedLines != null) {\n this.interactionManager.setSelection(...selectedLines);\n }\n }\n\n public flushManagers(): void {\n if (!this.managersDirty || this.pre == null) {\n this.managersDirty = false;\n return;\n }\n\n const { diffStyle = 'split', overflow = 'scroll' } = this.options;\n this.interactionManager.setup(this.pre);\n this.resizeManager.setup(this.pre, {\n disableAnnotations: overflow === 'wrap',\n columnVariables: this.shouldApplyColumnVariables(overflow)\n ? 'apply'\n : 'measure',\n });\n if (overflow === 'scroll' && diffStyle === 'split') {\n this.scrollSyncManager.setup(\n this.pre,\n this.codeDeletions,\n this.codeAdditions\n );\n } else {\n this.scrollSyncManager.cleanUp();\n }\n this.managersDirty = false;\n }\n\n protected shouldApplyColumnVariables(overflow: 'scroll' | 'wrap'): boolean {\n if (typeof this.options.hunkSeparators === 'function') {\n return true;\n }\n return (\n overflow === 'scroll' &&\n (this.lineAnnotations.length > 0 ||\n this.pre?.hasAttribute('data-has-merge-conflict') === true)\n );\n }\n\n public getCodeScrollLeft(): number {\n return Math.max(\n this.codeUnified?.scrollLeft ?? 0,\n this.codeDeletions?.scrollLeft ?? 0,\n this.codeAdditions?.scrollLeft ?? 0\n );\n }\n\n public setCodeScrollLeft(position: number): void {\n if (this.codeUnified != null) {\n this.codeUnified.scrollLeft = position;\n }\n if (this.codeAdditions != null) {\n this.codeAdditions.scrollLeft = position;\n }\n if (this.codeDeletions != null) {\n this.codeDeletions.scrollLeft = position;\n }\n }\n\n public __getEffectiveCodeOptions(): BaseCodeOptions {\n return { ...this.options, ...this.hunksRenderer.getEffectiveCodeOptions() };\n }\n\n public cleanUp(recycle: boolean = false): void {\n const { editor } = this;\n dequeueRender(this.handleEditSessionRender);\n this.emitPostRender(true);\n // Tear the editor down while the code scrollers still exist. A recycle\n // keeps its document and undo history; a full teardown drops them as the\n // session ends.\n editor?.cleanUp(recycle ? 'recycle' : 'discard');\n if (!recycle) {\n this.editor = undefined;\n }\n this.resizeManager.cleanUp();\n this.interactionManager.cleanUp();\n this.scrollSyncManager.cleanUp();\n this.managersDirty = false;\n this.workerManager?.unsubscribeToThemeChanges(this);\n this.renderRange = undefined;\n if (!recycle) {\n this.pendingFiles = undefined;\n }\n\n // Clean up the elements\n if (!this.isComponentManaged) {\n this.fileContainer?.remove();\n }\n this.fileContainer = undefined;\n this.mounted = false;\n if (!recycle) {\n this.renderedData = undefined;\n this.pendingData = undefined;\n }\n this.clearAuxiliaryNodes();\n this.annotationCache.clear();\n this.pre?.remove();\n this.pre = undefined;\n this.codeUnified = undefined;\n this.codeDeletions = undefined;\n this.codeAdditions = undefined;\n this.bufferBefore?.remove();\n this.bufferBefore = undefined;\n this.bufferAfter?.remove();\n this.bufferAfter = undefined;\n this.appliedPreAttributes = undefined;\n this.headerElement?.remove();\n this.headerElement = undefined;\n this.clearHeaderSlots();\n this.placeHolder?.remove();\n this.placeHolder = undefined;\n this.headerCache.lastRenderedHTML = undefined;\n if (!recycle) {\n this.clearReusableHeader();\n }\n this.errorWrapper?.remove();\n this.errorWrapper = undefined;\n this.spriteSVG = undefined;\n this.lastRowCount = undefined;\n this.themeCSSStyle = undefined;\n this.appliedThemeCSS = undefined;\n this.hasAdoptedThemeCSS = false;\n this.unsafeCSSStyle = undefined;\n this.appliedUnsafeCSS = undefined;\n\n if (recycle) {\n this.hunksRenderer.recycle();\n } else {\n this.hunksRenderer.cleanUp();\n this.workerManager = undefined;\n // Clean up the data\n this.fileDiff = undefined;\n this.editSession = undefined;\n this.deletionFile = undefined;\n this.additionFile = undefined;\n }\n if (this.refreshViewTimeout != null) {\n clearTimeout(this.refreshViewTimeout);\n this.refreshViewTimeout = undefined;\n }\n this.lineStateRefreshPending = false;\n this.deferredEditorActiveLine = undefined;\n this.deferredSelectedLines = undefined;\n this.enabled = false;\n }\n\n public virtualizedSetup(): void {\n this.enabled = true;\n this.workerManager?.subscribeToThemeChanges(this);\n }\n\n public hydrate({\n fileContainer,\n prerenderedHTML,\n preventEmit = false,\n lineAnnotations,\n fileDiff,\n ...fileInputProps\n }: FileDiffHydrationProps<LAnnotation>): void {\n if (!this.enabled) {\n throw new Error(\n 'FileDiff.hydrate: attempting to call hydrate after cleaned up'\n );\n }\n if (this.fileContainer != null) {\n throw new Error(\n 'FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated'\n );\n }\n const fileInput = getDiffFileInput(fileInputProps, 'FileDiff.hydrate');\n const oldFile = fileInput?.oldFile;\n const newFile = fileInput?.newFile;\n this.hydrateElements(fileContainer, prerenderedHTML);\n // An editor attached before hydration may carry a retained keyed document\n // and its session-shaped hunks. Render through that private session instead\n // of adopting external markup, so hydration cannot recompute or flash it.\n const forceEditorRender = this.editor != null;\n if (\n forceEditorRender ||\n shouldRenderCode(\n this.pre,\n hasDiffContent({ fileDiff, oldFile, newFile }),\n this.options.collapsed\n ) ||\n shouldRenderHeader(\n this.headerElement,\n hasDiffHeaderContent({ fileDiff, oldFile, newFile }),\n this.options.disableFileHeader\n )\n ) {\n this.render({\n ...fileInputProps,\n fileContainer,\n lineAnnotations,\n fileDiff,\n forceRender: forceEditorRender || fileInputProps.forceRender,\n preventEmit: true,\n });\n }\n // Otherwise orchestrate our setup\n else {\n this.hydrationSetup({\n fileDiff,\n lineAnnotations,\n ...fileInput,\n });\n }\n if (!preventEmit) {\n this.emitPostRender();\n }\n }\n\n protected hydrateElements(\n fileContainer: HTMLElement,\n prerenderedHTML: string | undefined\n ): void {\n if (this.fileContainer !== fileContainer) {\n this.emitPostRender(true);\n }\n prerenderHTMLIfNecessary(fileContainer, prerenderedHTML);\n for (const element of fileContainer.shadowRoot?.children ?? []) {\n if (element instanceof SVGElement) {\n this.spriteSVG = element;\n continue;\n }\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n if (element instanceof HTMLPreElement) {\n this.pre = element;\n for (const code of element.children) {\n if (\n !(code instanceof HTMLElement) ||\n code.tagName.toLowerCase() !== 'code'\n ) {\n continue;\n }\n if ('deletions' in code.dataset) {\n this.codeDeletions = code;\n }\n if ('additions' in code.dataset) {\n this.codeAdditions = code;\n }\n if ('unified' in code.dataset) {\n this.codeUnified = code;\n }\n }\n continue;\n }\n if ('diffsHeader' in element.dataset) {\n this.headerElement = element;\n continue;\n }\n if (\n element instanceof HTMLStyleElement &&\n element.hasAttribute(THEME_CSS_ATTRIBUTE)\n ) {\n this.themeCSSStyle = element;\n continue;\n }\n if (\n element instanceof HTMLStyleElement &&\n element.hasAttribute(UNSAFE_CSS_ATTRIBUTE)\n ) {\n this.unsafeCSSStyle = element;\n this.appliedUnsafeCSS = element.textContent;\n continue;\n }\n }\n if (this.pre != null) {\n this.syncCodeNodesFromPre(this.pre);\n this.pre.removeAttribute('data-dehydrated');\n }\n this.fileContainer = fileContainer;\n this.hydrateMeasuredScrollbar();\n }\n\n protected hydrationSetup({\n fileDiff,\n oldFile,\n newFile,\n lineAnnotations,\n }: HydrationSetup<LAnnotation>): void {\n // It's possible we are hydrating a pure-rename and therefore there will be\n // no pre element\n const hydratedAnnotations = lineAnnotations ?? this.getLatestAnnotations();\n this.pendingData = undefined;\n this.additionFile = newFile;\n this.deletionFile = oldFile;\n this.fileDiff =\n fileDiff ??\n (oldFile !== undefined && newFile !== undefined\n ? parseDiffFromFile(oldFile, newFile, this.options.parseDiffOptions)\n : undefined);\n this.renderedData =\n this.fileDiff != null\n ? { fileDiff: this.fileDiff, lineAnnotations: hydratedAnnotations }\n : undefined;\n if (this.fileDiff != null) {\n this.adoptRenderData(this.fileDiff);\n }\n\n if (this.pre == null) {\n return;\n }\n\n this.syncInteractionOptions();\n this.hunksRenderer.hydrate(this.fileDiff);\n // FIXME(amadeus): not sure how to handle this yet...\n // this.renderSeparators();\n this.renderAnnotations();\n this.renderGutterUtility();\n this.injectUnsafeCSS();\n this.managersDirty = true;\n this.flushManagers();\n }\n\n public rerender(): void {\n if (\n !this.enabled ||\n (this.getInputDiff() == null &&\n this.additionFile == null &&\n this.deletionFile == null)\n ) {\n return;\n }\n if (this.requestRender()) return;\n this.render({ forceRender: true, renderRange: this.renderRange });\n }\n\n // Editors update their rows directly. Other internal renders can be driven\n // by the owner, so React updates its children before calling render().\n protected requestRender(): boolean {\n const { requestOwnerRender } = this;\n if (this.editSession != null || requestOwnerRender == null) {\n return false;\n }\n this.forceRenderOverride = true;\n requestOwnerRender();\n return true;\n }\n\n protected get isComponentManaged(): boolean {\n return this.requestOwnerRender != null;\n }\n\n public onThemeChange(): void {\n this.hunksRenderer.clearRenderCache();\n this.rerender();\n }\n\n // This wrapper must stay separate from `expandHunk` because subclasses like\n // `VirtualizedFileDiff` replace `expandHunk` with their own instance field\n // after `super()` returns. `InteractionManager` is created in this base\n // constructor, so it needs a stable callback that resolves `this.expandHunk`\n // at click time instead of capturing the base implementation too early.\n public handleExpandHunk = (\n hunkIndex: number,\n direction: ExpansionDirections,\n expansionLineCountOverride?: number\n ): void => {\n this.expandHunk(hunkIndex, direction, expansionLineCountOverride);\n };\n\n public expandHunk = (\n hunkIndex: number,\n direction: ExpansionDirections,\n expansionLineCountOverride?: number\n ): void => {\n this.loadFilesIfNecessary();\n this.hunksRenderer.expandHunk(\n hunkIndex,\n direction,\n expansionLineCountOverride\n );\n this.rerender();\n };\n\n protected loadFilesIfNecessary(): void {\n const fileDiff = this.getInputDiff();\n const { loadDiffFiles } = this.options;\n if (\n fileDiff == null ||\n !canHydrateDiff(fileDiff) ||\n this.pendingFiles?.fileDiff === fileDiff\n ) {\n return;\n }\n if (loadDiffFiles == null) {\n throw new Error(\n 'FileDiff: loadDiffFiles is required to load full files for a partial diff'\n );\n }\n\n const promise = this.loadFilesForDiff(fileDiff, loadDiffFiles);\n const pendingFiles: PendingFileLoad = (this.pendingFiles = {\n fileDiff,\n promise,\n });\n // Track the exact request object so an older completion for the same diff\n // cannot clear a newer request.\n const clearPendingFiles = (): void => {\n if (this.pendingFiles === pendingFiles) {\n this.pendingFiles = undefined;\n }\n };\n pendingFiles.promise = promise.finally(clearPendingFiles);\n }\n\n /**\n * In order to start an edit session, you must be using a `fileDiff` that\n * includes the full contents for both files. In other words, `isPartial`\n * must be false You can use `prepareForEditing` to hydrate if\n * `loadDiffFiles` was passed in to `options`\n */\n public __canAttachEditor(): boolean {\n const fileDiff = this.getInputDiff();\n return fileDiff != null && !fileDiff.isPartial;\n }\n\n /**\n * Load a partial diff before starting a new edit session. Call this before\n * Editor.edit when the diff may still be partial; it resolves only when this\n * instance has a complete diff to edit.\n */\n public async prepareForEditing(): Promise<void> {\n if (this.__canAttachEditor()) {\n return;\n }\n const pending = this.__prepareForEditing();\n if (pending == null) {\n const fileDiff = this.getInputDiff();\n if (fileDiff?.isPartial === true && !canHydrateDiff(fileDiff)) {\n throw new Error(\n 'FileDiff.prepareForEditing: this partial diff cannot be hydrated; provide a complete diff'\n );\n }\n throw new Error(\n 'FileDiff.prepareForEditing: a partial diff requires loadDiffFiles'\n );\n }\n await pending;\n if (!this.__canAttachEditor()) {\n throw new Error(\n 'FileDiff.prepareForEditing: the diff did not finish loading'\n );\n }\n }\n\n /** Hydrate a diff if necessary */\n public __prepareForEditing(): Promise<void> | undefined {\n if (this.__canAttachEditor()) {\n return undefined;\n }\n const fileDiff = this.getInputDiff();\n if (fileDiff?.isPartial === true && !canHydrateDiff(fileDiff)) {\n throw new Error(\n 'FileDiff: this partial diff cannot be hydrated; provide a complete diff to edit'\n );\n }\n this.loadFilesIfNecessary();\n return this.pendingFiles?.promise;\n }\n\n private async loadFilesForDiff(\n fileDiff: FileDiffMetadata,\n loadDiffFiles: NonNullable<BaseDiffOptions['loadDiffFiles']>\n ): Promise<void> {\n try {\n const files = await loadDiffFiles(fileDiff);\n if (this.getInputDiff() !== fileDiff) {\n return;\n }\n\n await this.handleFilesLoaded(fileDiff, files);\n } catch (error: unknown) {\n if (this.options.disableErrorHandling === true) {\n throw error;\n }\n console.error(error);\n }\n }\n\n protected async handleFilesLoaded(\n expectedDiff: FileDiffMetadata,\n files: LoadedPartialDiffContents\n ): Promise<void> {\n if (this.getInputDiff() !== expectedDiff || !expectedDiff.isPartial) {\n return;\n }\n hydratePartialDiff('merge', expectedDiff, files);\n this.setHydratedState(files);\n if (this.installHydratedSessionDiff(expectedDiff)) {\n this.rerender();\n return;\n }\n await awaitWithTimeout(() => this.primeHighlightCache(expectedDiff));\n if (!this.enabled || this.getInputDiff() !== expectedDiff) {\n return;\n }\n this.rerender();\n }\n\n // Install a loaded replacement in the edit session before the editor syncs.\n protected installHydratedSessionDiff(\n expectedDiff: FileDiffMetadata\n ): boolean {\n if (expectedDiff.isPartial) {\n throw new Error(\n 'FileDiff.installHydratedSessionDiff: diffs cannot be partial for editing'\n );\n }\n if (this.getInputDiff() !== expectedDiff) {\n return false;\n }\n if (this.editSession?.outgoingDiff != null) {\n this.installEditSession(expectedDiff);\n return true;\n }\n return false;\n }\n\n // Store a new input. Keep the editor's previous diff until it syncs\n // so it can decide whether to keep or reset undo history for the\n // replacement. Return false if the input has not changed.\n protected updateInputDiff(\n incomingDiff: FileDiffMetadata,\n lineAnnotations?: DiffLineAnnotation<LAnnotation>[]\n ): boolean {\n if (areDiffTargetsEqual(this.getInputDiff(), incomingDiff)) {\n return false;\n }\n\n const previousAnnotations = this.getLatestAnnotations();\n this.fileDiff = incomingDiff;\n const { editSession: previousSession } = this;\n const outgoingDiff = previousSession?.outgoingDiff ?? previousSession?.diff;\n if (previousSession != null) {\n if (incomingDiff.isPartial) {\n // Keep the working diff until loading provides a complete replacement.\n previousSession.inputDiff = incomingDiff;\n } else {\n this.installEditSession(incomingDiff);\n }\n if (this.editSession != null) {\n this.editSession.outgoingDiff = outgoingDiff;\n }\n }\n if (this.editSession?.annotations != null && lineAnnotations != null) {\n // Positions supplied with a host replacement describe its new\n // document. Surviving annotations retain their frozen names from\n // the old session.\n this.editSession.annotations = adoptEditSessionAnnotations(\n lineAnnotations,\n getLineAnnotationName,\n this.editSession.annotations\n );\n }\n this.pendingData = {\n fileDiff: this.editSession?.diff ?? incomingDiff,\n lineAnnotations:\n this.editSession?.annotations?.current ??\n lineAnnotations ??\n previousAnnotations,\n };\n if (outgoingDiff != null && incomingDiff.isPartial) {\n this.loadFilesIfNecessary();\n }\n return true;\n }\n\n // When an editor opens a document saved under a document key,\n // `retainedDocument` restores its text and undo history. It is omitted when\n // replacing the diff in an open editor so the replacement is handled as a\n // new external update instead of overwriting the document being edited.\n private installEditSession(\n inputDiff: FileDiffMetadata,\n retainedDocument?: FileContents,\n retainedSession?: RetainedDiffSessionSnapshot\n ): void {\n const inputContents = inputDiff.additionLines.join('');\n const retainedLines =\n retainedDocument != null\n ? splitFileContents(retainedDocument.contents)\n : undefined;\n const restoreRetainedSession =\n retainedSession != null &&\n canRestoreDiffSession(retainedSession, inputDiff);\n if (retainedSession != null && !restoreRetainedSession) {\n throw new Error(\n 'FileDiff: retained session cannot resume against a different old file'\n );\n }\n if (\n retainedDocument != null &&\n retainedDocument.contents !== inputContents &&\n !restoreRetainedSession\n ) {\n throw new Error(\n 'FileDiff: retained edits are missing their diff session state'\n );\n }\n const usesInputDocument =\n retainedDocument == null ||\n (retainedDocument.name === inputDiff.name &&\n retainedDocument.lang === inputDiff.lang &&\n retainedDocument.contents === inputContents);\n const sessionDiff = createEditSessionDiff(inputDiff);\n if (\n retainedDocument != null &&\n retainedLines != null &&\n !usesInputDocument\n ) {\n sessionDiff.name = retainedDocument.name;\n sessionDiff.lang = retainedDocument.lang;\n }\n if (\n restoreRetainedSession &&\n retainedSession != null &&\n retainedDocument != null &&\n retainedLines != null\n ) {\n sessionDiff.additionLines = retainedLines;\n sessionDiff.additionCharacterCount = retainedDocument.contents.length;\n sessionDiff.type = retainedSession.type;\n sessionDiff.hunks = retainedSession.hunks;\n sessionDiff.editSessionDirty = true;\n recomputeDiffRenderLineCounts(sessionDiff);\n }\n // Initialize annotations when the session starts so updateInputDiff can\n // reset their positions when a replacement arrives. An existing session\n // keeps its tracked annotations.\n const annotations =\n this.editSession?.annotations ??\n adoptEditSessionAnnotations(\n this.getLatestAnnotations(),\n getLineAnnotationName\n );\n this.editSession = {\n diff: sessionDiff,\n inputDiff,\n annotations,\n outgoingDiff: this.editSession?.outgoingDiff,\n };\n this.pendingData = {\n fileDiff: sessionDiff,\n lineAnnotations: annotations.current,\n };\n this.hunksRenderer.beginEditSession(\n sessionDiff,\n usesInputDocument && !restoreRetainedSession ? inputDiff : undefined\n );\n }\n\n protected setHydratedState(files: LoadedPartialDiffContents): void {\n this.deletionFile = files.oldFile;\n this.additionFile = files.newFile;\n this.workerManager?.cleanUpTasks(this.hunksRenderer);\n this.hunksRenderer.clearRenderCache();\n }\n\n public render({\n fileDiff,\n deferManagers = false,\n forceRender = false,\n preventEmit = false,\n lineAnnotations,\n fileContainer,\n containerWrapper,\n renderRange,\n ...fileInputProps\n }: FileDiffRenderProps<LAnnotation>): boolean {\n if (!this.enabled) {\n // NOTE(amadeus): May need to be a silent failure? Making it loud for now\n // to better understand it\n throw new Error(\n 'FileDiff.render: attempting to call render after cleaned up'\n );\n }\n forceRender = this.forceRenderOverride ?? forceRender;\n this.forceRenderOverride = undefined;\n\n const fileInput = getDiffFileInput(fileInputProps, 'FileDiff.render');\n const oldFile = fileInput?.oldFile;\n const newFile = fileInput?.newFile;\n\n // postpone background tokenizing to next frame for avoiding UI freeze\n // during render\n this.editor?.__postponeBgTokenizeToNextFrame();\n\n const {\n collapsed = false,\n themeType = 'system',\n expandUnchanged = false,\n } = this.options;\n const nextRenderRange = collapsed ? undefined : renderRange;\n const themeChanged = this.hasThemeChanged();\n const hasFileInput = fileInput != null;\n const filesDidChange =\n hasFileInput &&\n (!areOptionalFilesEqual(oldFile, this.deletionFile) ||\n !areOptionalFilesEqual(newFile, this.additionFile));\n let diffDidChange =\n fileDiff != null && !areDiffTargetsEqual(fileDiff, this.getInputDiff());\n const annotationsChanged =\n lineAnnotations != null &&\n (lineAnnotations.length > 0 || this.getLatestAnnotations().length > 0)\n ? this.isNewAnnotations(lineAnnotations)\n : false;\n\n if (\n !collapsed &&\n areRenderRangesEqual(nextRenderRange, this.renderRange) &&\n !forceRender &&\n !annotationsChanged &&\n !themeChanged &&\n // If using the fileDiff API, lets check to see if they are equal to\n // avoid doing work\n ((fileDiff != null && !diffDidChange) ||\n // If using the oldFile/newFile API then lets check to see if they are\n // equal\n (fileDiff == null && !filesDidChange))\n ) {\n const rendered = this.applyCachedThemeState(themeType);\n if (rendered) {\n this.finalizeRender();\n }\n return rendered;\n }\n\n let nextParsedFileDiff: FileDiffMetadata | undefined;\n if (\n fileDiff == null &&\n hasFileInput &&\n (filesDidChange || this.getInputDiff() == null)\n ) {\n nextParsedFileDiff = parseDiffFromFile(\n fileInput.oldFile,\n fileInput.newFile,\n this.options.parseDiffOptions\n );\n }\n\n const { renderRange: previousRenderRange } = this;\n this.renderRange = nextRenderRange;\n // Store files only when this render actually carried a file input:\n // internal rerenders pass none, and wiping the pair here would defeat the\n // oldFile/newFile early-return on every later host render. An explicit\n // fileDiff input supersedes a previously parsed pair, so clear it then.\n if (hasFileInput) {\n this.deletionFile = oldFile;\n this.additionFile = newFile;\n } else if (fileDiff != null) {\n this.deletionFile = undefined;\n this.additionFile = undefined;\n }\n\n if (fileDiff != null && diffDidChange) {\n this.updateInputDiff(fileDiff, lineAnnotations);\n } else if (nextParsedFileDiff != null) {\n diffDidChange = true;\n this.updateInputDiff(nextParsedFileDiff, lineAnnotations);\n }\n if (diffDidChange) {\n this.clearReusableHeader();\n }\n\n if (lineAnnotations != null) {\n this.setLineAnnotations(lineAnnotations);\n }\n\n const workingDiff = this.getWorkingDiff();\n if (workingDiff == null) {\n return false;\n }\n // Backstop for sessions that ended without their exit hook running (e.g.\n // session-shaped metadata reused after a host teardown): restore\n // recompute-shaped hunks before rendering.\n if (\n workingDiff.editSessionDirty === true &&\n this.shouldSelfHealEditSession()\n ) {\n finishEditSessionForDiff(workingDiff, this.options.parseDiffOptions);\n void this.hunksRenderer.refreshHighlightedResult();\n }\n if (expandUnchanged) {\n this.loadFilesIfNecessary();\n }\n this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options));\n this.syncInteractionOptions();\n\n this.prepareRenderData(\n this.hunksRenderer.getDiffForNextRender(workingDiff)\n );\n\n const { disableErrorHandling = false, disableFileHeader = false } =\n this.options;\n\n if (disableFileHeader) {\n // Remove existing header from DOM\n if (this.headerElement != null) {\n this.headerElement.remove();\n this.headerElement = undefined;\n this.headerCache.lastRenderedHTML = undefined;\n }\n this.clearHeaderSlots();\n }\n fileContainer = this.getOrCreateFileContainer(\n fileContainer,\n containerWrapper\n );\n this.applyCachedThemeState(themeType);\n\n if (collapsed) {\n this.removeRenderedCode();\n this.clearAuxiliaryNodes();\n\n try {\n const hunksResult = this.hunksRenderer.renderDiff(\n workingDiff,\n EMPTY_RENDER_RANGE\n );\n if (hunksResult != null) {\n this.applyThemeState(\n fileContainer,\n hunksResult.themeStyles,\n themeType,\n hunksResult.baseThemeType\n );\n }\n if (hunksResult?.headerElement != null) {\n this.applyHeaderToDOM(\n hunksResult.headerElement,\n fileContainer,\n hunksResult.fileDiff\n );\n }\n this.renderSeparators([]);\n this.adoptRenderData(hunksResult?.fileDiff ?? workingDiff);\n this.injectUnsafeCSS();\n } catch (error: unknown) {\n if (disableErrorHandling) {\n throw error;\n }\n console.error(error);\n if (error instanceof Error) {\n this.applyErrorToDOM(error, fileContainer);\n }\n }\n this.finalizeRender();\n if (!preventEmit) {\n this.emitPostRender();\n }\n return true;\n }\n\n try {\n const pre = this.getOrCreatePreNode(fileContainer);\n\n // Attempt to partially render\n const didPartiallyRender =\n this.canPartiallyRender(\n forceRender,\n annotationsChanged,\n filesDidChange ||\n diffDidChange ||\n themeChanged ||\n !areDiffTargetsEqual(this.getRenderedDiff(), workingDiff)\n ) &&\n this.applyPartialRender({\n fileDiff: workingDiff,\n previousRenderRange,\n renderRange: nextRenderRange,\n });\n\n // If we were unable to partially render, perform a full render\n if (!didPartiallyRender) {\n const hunksResult = this.hunksRenderer.renderDiff(\n workingDiff,\n nextRenderRange\n );\n if (hunksResult == null) {\n if (\n this.workerManager?.isInitialized() === false &&\n this.workerManager.isWorkingPool()\n ) {\n void this.workerManager\n .initialize()\n .catch(() => {})\n .then(() => this.rerender());\n }\n return false;\n }\n\n this.applyThemeState(\n fileContainer,\n hunksResult.themeStyles,\n themeType,\n hunksResult.baseThemeType\n );\n\n if (hunksResult.headerElement != null) {\n this.applyHeaderToDOM(\n hunksResult.headerElement,\n fileContainer,\n hunksResult.fileDiff\n );\n }\n if (\n hunksResult.additionsContentAST != null ||\n hunksResult.deletionsContentAST != null ||\n hunksResult.unifiedContentAST != null\n ) {\n this.applyHunksToDOM(pre, hunksResult);\n } else if (this.pre != null) {\n this.pre.remove();\n this.pre = undefined;\n }\n this.renderSeparators(hunksResult.hunkData);\n this.adoptRenderData(hunksResult.fileDiff);\n } else {\n const renderedDiff = this.getRenderedDiff();\n if (renderedDiff != null) {\n this.adoptRenderData(renderedDiff);\n }\n }\n this.applyBuffers(pre, nextRenderRange);\n this.injectUnsafeCSS();\n this.renderAnnotations();\n this.renderGutterUtility();\n\n this.managersDirty = true;\n if (!deferManagers) {\n this.flushManagers();\n }\n\n this.finalizeRender();\n if (this.editor != null) {\n this.syncRenderViewToEditor();\n }\n } catch (error: unknown) {\n if (disableErrorHandling) {\n throw error;\n }\n console.error(error);\n if (error instanceof Error) {\n this.applyErrorToDOM(error, fileContainer);\n }\n }\n if (!preventEmit) {\n this.emitPostRender();\n }\n return true;\n }\n\n protected finalizeRender(): void {}\n\n protected emitPostRender(unmount = false): void {\n const {\n fileContainer,\n options: { onPostRender },\n } = this;\n\n if (unmount) {\n if (!this.mounted) {\n return;\n }\n this.mounted = false;\n if (fileContainer == null) {\n return;\n }\n this.options.onPostRender?.(fileContainer, this, 'unmount');\n return;\n }\n\n if (fileContainer == null) {\n return;\n }\n\n const phase: PostRenderPhase = this.mounted ? 'update' : 'mount';\n this.mounted = true;\n onPostRender?.(fileContainer, this, phase);\n }\n\n // Return the latest input without editor changes. It may be newer than the\n // displayed diff while a replacement is loading or being highlighted.\n protected getInputDiff(): FileDiffMetadata | undefined {\n return this.fileDiff;\n }\n\n // Return the editor's copy, including its changes, or the input when there\n // is no edit session. The editor keeps its copy while a partial input loads.\n // Use fallbackDiff if the new input is not stored yet.\n protected getWorkingDiff(\n fallbackDiff: FileDiffMetadata | undefined = this.fileDiff\n ): FileDiffMetadata | undefined {\n return this.editSession?.diff ?? fallbackDiff;\n }\n\n // Return the displayed diff. While a replacement is being highlighted,\n // this still returns the previous diff.\n protected getRenderedDiff(): FileDiffMetadata | undefined {\n return this.renderedData?.fileDiff;\n }\n\n /**\n * @internal Data the next render() with this input will display. While a\n * replacement diff is being highlighted, this is still the displayed data.\n */\n public __getNextRenderData({\n fileDiff,\n lineAnnotations,\n }: FileDiffRenderInput<LAnnotation>): FileDiffRenderData<LAnnotation> {\n const sessionAnnotations = this.editSession?.annotations;\n // Keep the supplied content during editing. The editor moves annotation\n // rows through stable slots without rerendering their React children.\n if (sessionAnnotations != null) {\n return {\n fileDiff,\n lineAnnotations:\n lineAnnotations != null && this.isNewAnnotations(lineAnnotations)\n ? lineAnnotations\n : sessionAnnotations.provided,\n };\n }\n const workingDiff = this.getWorkingDiff(fileDiff) ?? fileDiff;\n const nextDiff = this.hunksRenderer.getDiffForNextRender(workingDiff);\n return {\n fileDiff: nextDiff,\n lineAnnotations:\n lineAnnotations != null && areDiffTargetsEqual(nextDiff, workingDiff)\n ? lineAnnotations\n : this.getAnnotationsForDiff(nextDiff),\n };\n }\n\n // Build rows using annotations for the diff the renderer selected.\n // Subclasses also prepare their additional rows here.\n protected prepareRenderData(fileDiff: FileDiffMetadata): void {\n this.hunksRenderer.setLineAnnotations(this.getAnnotationsForDiff(fileDiff));\n }\n\n // Record the diff now on screen. If it matches pendingData, apply those\n // annotations and clear pendingData; otherwise keep the pending update.\n protected adoptRenderData(fileDiff: FileDiffMetadata): void {\n const { pendingData } = this;\n const matchesPending =\n pendingData != null &&\n areDiffTargetsEqual(fileDiff, pendingData.fileDiff);\n this.renderedData = {\n fileDiff,\n lineAnnotations: matchesPending\n ? pendingData.lineAnnotations\n : this.lineAnnotations,\n };\n if (matchesPending) {\n this.pendingData = undefined;\n }\n }\n\n private syncRenderViewToEditor(): void {\n const { editor, fileContainer } = this;\n const lineAnnotations = this.getLatestAnnotations();\n const renderRange = this.computeEditorRenderRange(this.renderRange);\n const fileDiff = this.getWorkingDiff();\n if (\n editor == null ||\n fileContainer == null ||\n fileDiff == null ||\n fileDiff.isPartial\n ) {\n return;\n }\n const sync = (highlighter: DiffsHighlighter): void => {\n if (\n !this.enabled ||\n this.editor !== editor ||\n this.fileContainer !== fileContainer ||\n this.getWorkingDiff() !== fileDiff\n ) {\n return;\n }\n const replacement = this.editSession?.outgoingDiff;\n const inputDiff = this.getInputDiff();\n const externalDocument =\n replacement != null && inputDiff != null && replacement !== fileDiff;\n const resetHistory =\n externalDocument && replacement != null && inputDiff != null\n ? shouldResetUndoState(replacement, inputDiff)\n : false;\n editor.__syncRenderView({\n highlighter,\n fileContainer,\n fileDiff,\n lineAnnotations,\n renderRange,\n externalDocument,\n resetHistory,\n });\n };\n const theme = this.getTheme();\n const lang = fileDiff.lang ?? getFiletypeFromFileName(fileDiff.name);\n // Sync synchronously whenever the shared highlighter is ready; otherwise\n // load it and sync once it resolves.\n const highlighter = getHighlighterIfLoaded({\n theme,\n lang,\n });\n if (highlighter != null) {\n sync(highlighter);\n } else {\n void getSharedHighlighter({\n themes: getThemes(theme),\n langs: ['text', lang],\n preferredHighlighter: resolvePreferredHighlighter(\n this.workerManager,\n this.options\n ),\n })\n .then(sync)\n .catch((error: unknown) => {\n if (!(error instanceof HighlighterDisposedError)) {\n console.error(error);\n }\n });\n }\n }\n\n // The stored render range is in rendered-row units for the windowed AST\n // pipeline, but the editor consumes render ranges in document-line units.\n // Derive the addition-side document window covered by the rendered rows:\n // startingLine = first addition line with a row in the window, totalLines =\n // last such line - first + 1, and 0 when the window holds no addition rows\n // (e.g. a pure-deletion run taller than the viewport).\n private computeEditorRenderRange(\n renderRange: RenderRange | undefined\n ): RenderRange | undefined {\n const fileDiff = this.getWorkingDiff();\n if (\n renderRange == null ||\n fileDiff == null ||\n isDefaultRenderRange(renderRange)\n ) {\n return renderRange;\n }\n const {\n diffStyle = 'split',\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n let firstLineNumber: number | undefined;\n let lastLineNumber: number | undefined;\n iterateOverDiff({\n diff: fileDiff,\n diffStyle,\n startingLine: renderRange.startingLine,\n totalLines: renderRange.totalLines,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n callback: ({ additionLine }) => {\n if (additionLine != null) {\n firstLineNumber ??= additionLine.lineNumber;\n lastLineNumber = additionLine.lineNumber;\n }\n },\n });\n if (firstLineNumber == null || lastLineNumber == null) {\n return { ...renderRange, startingLine: 0, totalLines: 0 };\n }\n return {\n ...renderRange,\n startingLine: firstLineNumber - 1,\n totalLines: lastLineNumber - firstLineNumber + 1,\n };\n }\n\n /** @internal The editor applied or edited past the pending external replacement. */\n public __acknowledgeDocumentUpdate(): void {\n if (this.editSession != null) {\n this.editSession.outgoingDiff = undefined;\n }\n }\n\n /** @internal Settle annotations locally. */\n public __acceptEditorChange(\n event: EditorChangeEvent<'file-diff', LAnnotation, Caret>\n ): void {\n const { lineAnnotations } = event;\n if (lineAnnotations != null) {\n this.syncEditSessionAnnotationsFromEditor(lineAnnotations);\n }\n }\n\n public emitEditChange(\n event: EditorChangeEvent<'file-diff', LAnnotation, Caret>\n ): void {\n const { onEditChange } = this.options;\n onEditChange?.(event);\n }\n\n /**\n * @internal Capture the current diff session, or return `undefined` when no\n * complete compatible session exists.\n *\n * When `clone` is true, the returned lines and hunks are copied.\n */\n public __captureDocumentSessionState(\n clone = true\n ): CapturedDiffSessionState | undefined {\n const fileDiff = this.getInputDiff();\n let { diff: sessionDiff, outgoingDiff } = this.editSession ?? {};\n if (outgoingDiff != null && fileDiff != null) {\n if (!fileDiff.isPartial && shouldResetUndoState(outgoingDiff, fileDiff)) {\n return undefined;\n }\n sessionDiff = outgoingDiff;\n }\n if (sessionDiff == null || sessionDiff.isPartial) {\n return undefined;\n }\n return {\n diffSession: {\n oldFile:\n sessionDiff.type !== 'new'\n ? {\n name: sessionDiff.prevName ?? sessionDiff.name,\n lines: clone\n ? [...sessionDiff.deletionLines]\n : sessionDiff.deletionLines,\n }\n : null,\n type: sessionDiff.type,\n hunks: clone ? cloneHunks(sessionDiff.hunks) : sessionDiff.hunks,\n },\n hasChanges: sessionDiff.editSessionDirty === true,\n };\n }\n\n /** @internal Associate this component with its editor for a render lifecycle. */\n public __attachEditor(\n editor: Editor<'file-diff', LAnnotation, Caret>\n ): () => void {\n // Editing is a plain file-diff concern only. Subclasses with their own\n // hunk semantics (UnresolvedFile) are not editable, so an editor must\n // never attach to them.\n if (this.type !== 'file-diff') {\n throw new Error(\n `FileDiff.__attachEditor: cannot attach an editor to a \"${this.type}\" diff`\n );\n }\n if (this.editor != null) {\n throw new Error('FileDiff.__attachEditor: an editor is already attached');\n }\n if (!this.__canAttachEditor()) {\n throw new Error(\n 'FileDiff.__attachEditor: a complete diff is required before editing'\n );\n }\n const detach = () => {\n this.editor = undefined;\n this.finishEditSession();\n };\n try {\n this.resumeEditorRendering(editor);\n return detach;\n } catch (error) {\n detach();\n throw error;\n }\n }\n\n /** @internal Resume rendering for the editor already associated with this component. */\n public __resumeEditor(editor: Editor<'file-diff', LAnnotation, Caret>): void {\n if (this.editor !== editor) {\n throw new Error('FileDiff.__resumeEditor: editor association changed');\n }\n this.resumeEditorRendering(editor);\n }\n\n private resumeEditorRendering(\n editor: Editor<'file-diff', LAnnotation, Caret>\n ): void {\n const inputDiff = this.getInputDiff();\n const pendingReplacement = this.editSession?.outgoingDiff;\n // A pending replacement whose diff was partial when it arrived installs now\n // that we are (re)attaching with a hydrated diff.\n if (\n pendingReplacement != null &&\n inputDiff != null &&\n !inputDiff.isPartial &&\n this.editSession?.diff === pendingReplacement\n ) {\n this.installEditSession(inputDiff);\n }\n const initialInputDiff =\n this.editSession == null && inputDiff != null && !inputDiff.isPartial\n ? inputDiff\n : undefined;\n if (initialInputDiff != null) {\n this.installEditSession(\n initialInputDiff,\n editor.__getDocumentContents(getAdditionFile(initialInputDiff)),\n editor.__getDocumentSessionState()\n );\n } else if (this.editSession != null) {\n this.hunksRenderer.beginEditSession(this.editSession.diff);\n }\n this.editor = editor;\n // The editor sync below refuses partial diffs (it needs the full file\n // contents); kick off hydration so the loaded re-render re-runs it.\n if (this.getInputDiff()?.isPartial === true) {\n this.loadFilesIfNecessary();\n }\n const editSessionDiff = this.editSession?.diff;\n if (this.hunksRenderer.editorRenderReady()) {\n // Compatible markup can be reused without repainting. Once the renderer\n // transfers that cache to the private session, the existing DOM belongs\n // to the session as well.\n if (\n editSessionDiff != null &&\n this.hunksRenderer.diffCache === editSessionDiff\n ) {\n this.adoptRenderData(editSessionDiff);\n }\n this.syncRenderViewToEditor();\n } else {\n // The current markup is missing the editor's token metadata, or its\n // highlight is still pending: render through the session, which also\n // syncs the render view once it paints.\n this.rerender();\n }\n }\n\n // Session exit for the live detach path.\n private finishEditSession(): void {\n this.hunksRenderer.endEditSession();\n this.finalizeEditSessionHunks();\n }\n\n /**\n * @internal\n *\n * Ends the edit session and settles which diff this component renders.\n * Requires the editor to be detached first. Does nothing when no session\n * exists, so callers can invoke it again safely after it has settled.\n *\n * `onEditComplete` receives the completed diff, current input diff,\n * complete file pair, and both annotation collections even when the final\n * text is unchanged. In `install` mode, accepting installs the completed diff\n * and its annotations; rejecting or having no handler restores the external\n * values. `discard` mode always restores the external values. An accepted\n * diff cannot reuse the replaced diff's `cacheKey`.\n */\n public __completeEditSession(\n editor: Editor<'file-diff', LAnnotation, Caret>,\n mode: 'install' | 'discard'\n ): void {\n this.settleEditSession(mode === 'install', editor);\n }\n\n private settleEditSession(\n installResult: boolean,\n editor: Editor<'file-diff', LAnnotation, Caret> | undefined\n ): void {\n const { editSession } = this;\n if (editSession == null) {\n return;\n }\n const {\n diff: editSessionDiff,\n inputDiff,\n annotations: editSessionAnnotations,\n } = editSession;\n const inputAnnotations =\n editSessionAnnotations?.provided ?? this.lineAnnotations;\n if (this.editor != null) {\n throw new Error(\n 'FileDiff.__completeEditSession: detach the editor before completing the session'\n );\n }\n this.hunksRenderer.endEditSession();\n this.finalizeEditSessionHunks();\n\n const sessionAnnotationsCurrent = editSessionAnnotations?.current;\n let acceptedDiff: FileDiffMetadata | undefined;\n let acceptedOldFile: FileContents | null = null;\n let acceptedNewFile: FileContents | null = null;\n let failed = false;\n let failure: unknown;\n if (editor == null) {\n throw new Error(\n 'FileDiff.__completeEditSession: editor is required for completion'\n );\n }\n const completedDiff = cloneFileDiffMetadata(editSessionDiff);\n const newFile: FileContents = {\n name: completedDiff.name,\n contents: completedDiff.additionLines.join(''),\n };\n if (completedDiff.lang != null) {\n newFile.lang = completedDiff.lang;\n }\n const event: FileDiffEditCompleteEvent<LAnnotation, Caret> = {\n fileDiff: completedDiff,\n editor,\n originalFileDiff: inputDiff,\n oldFile:\n completedDiff.type === 'new'\n ? null\n : {\n name: completedDiff.prevName ?? completedDiff.name,\n contents: completedDiff.deletionLines.join(''),\n },\n newFile,\n lineAnnotations: sessionAnnotationsCurrent,\n originalLineAnnotations: inputAnnotations,\n };\n // Frozen so a handler cannot swap the event's fileDiff/originalFileDiff\n // references; nested mutation (i.e. a fresh cacheKey on event.fileDiff)\n // still works.\n Object.freeze(event);\n try {\n editor.__emitEditComplete(event);\n const decision = this.options.onEditComplete?.(event);\n if (decision === 'accept') {\n if (\n completedDiff.cacheKey != null &&\n completedDiff.cacheKey === inputDiff.cacheKey\n ) {\n throw new Error(\n 'FileDiff.__completeEditSession: an accepted diff must not reuse the replaced diff cacheKey'\n );\n }\n acceptedDiff = completedDiff;\n acceptedOldFile = event.oldFile;\n acceptedNewFile = event.newFile;\n }\n } catch (error) {\n failed = true;\n failure = error;\n }\n\n if (installResult && acceptedDiff != null) {\n // Callers using the oldFile/newFile API get the stored pair\n // refreshed so their next render with the event's files does not\n // reparse over the accepted diff. Every editable pair has a new\n // side (deleted files cannot be edited), so that is the check.\n if (this.additionFile != null) {\n this.deletionFile = acceptedOldFile;\n this.additionFile = acceptedNewFile;\n }\n }\n this.editSession = undefined;\n this.fileDiff =\n installResult && acceptedDiff != null ? acceptedDiff : inputDiff;\n this.pendingData = {\n fileDiff: this.fileDiff,\n lineAnnotations:\n installResult && acceptedDiff != null\n ? (sessionAnnotationsCurrent ?? inputAnnotations)\n : inputAnnotations,\n };\n if (installResult && this.fileContainer != null) {\n this.rerender();\n }\n if (failed) {\n throw failure;\n }\n }\n\n /**\n * Run the session-end recompute: restore recompute-shaped hunks (a\n * context-only region collapses away, boundaries re-derive), preserve\n * expansion state best-effort via old-side anchors, and repaint through\n * the session render path — which also invalidates virtualized layout,\n * since nothing else does at exit now that editing does not flip\n * expandUnchanged. Marker-guarded and idempotent; CodeView also calls this\n * when ending a session whose detach closure was consumed by a recycle.\n * Safe on a cleaned-up instance: the recompute is pure metadata work and\n * the deferred rerender is enabled-guarded. Returns true when a recompute\n * ran.\n */\n public finalizeEditSessionHunks(): boolean {\n const fileDiff = this.getWorkingDiff();\n if (fileDiff == null || fileDiff.editSessionDirty !== true) {\n return false;\n }\n const { collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD } =\n this.options;\n const anchors = captureExpansionAnchors(\n fileDiff,\n this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold\n );\n finishEditSessionForDiff(fileDiff, this.options.parseDiffOptions);\n this.hunksRenderer.setExpandedHunksMap(\n rebuildExpansionFromAnchors(fileDiff, anchors)\n );\n void this.hunksRenderer.refreshHighlightedResult();\n this.escalateEditSessionRender();\n return true;\n }\n\n // normally triggered by the host when the document line count changes\n public applyDocumentChange(\n textDocument: TextDocument<'file-diff', LAnnotation>,\n newLineAnnotations?: DiffLineAnnotation<LAnnotation>[]\n ): void {\n const editSessionDiff = this.editSession?.diff;\n if (editSessionDiff == null) {\n throw new Error(\n 'FileDiff.applyDocumentChange: requires an active edit session'\n );\n }\n this.detachAdditionLines();\n this.hunksRenderer.beginEditSession(editSessionDiff);\n this.hunksRenderer.applyDocumentChange(textDocument);\n if (newLineAnnotations != null) {\n this.syncEditSessionAnnotationsFromEditor(newLineAnnotations);\n }\n this.rerender();\n this.interactionManager.setSelectionDirty();\n }\n\n /** Update the private diff without editor DOM, then rehighlight on return. */\n public applySuspendedDocumentChange(\n textDocument: TextDocument<'file-diff', LAnnotation>,\n newLineAnnotations?: DiffLineAnnotation<LAnnotation>[]\n ): void {\n this.applyDocumentChange(textDocument, newLineAnnotations);\n this.hunksRenderer.clearRenderCache();\n }\n\n public updateRenderCache(\n dirtyLines: Map<number, Array<HighlightedToken>>,\n themeType: 'dark' | 'light',\n options: UpdateRenderCacheOptions = {}\n ): void {\n const editSessionDiff = this.editSession?.diff;\n if (editSessionDiff == null) {\n throw new Error(\n 'FileDiff.updateRenderCache: requires an active edit session'\n );\n }\n this.detachAdditionLines();\n this.hunksRenderer.beginEditSession(editSessionDiff);\n const { shouldRefreshDiffsView, lineCountChangeInFlight } = options;\n const regionsChanged = this.hunksRenderer.updateRenderCache(\n dirtyLines,\n themeType,\n lineCountChangeInFlight,\n options.changedDocumentLines,\n options.documentLineCount\n );\n // A same-line-count edit that reshaped the session regions (an edit into\n // a collapsed gap) changes the rendered row set, which the debounced\n // line-type refresh below cannot express. Escalate to a deferred full\n // re-render — never a synchronous one, since this runs mid-editor-pass\n // and rebuilding rows the editor is about to touch detaches its geometry\n // caches.\n if (regionsChanged) {\n if (this.refreshViewTimeout != null) {\n clearTimeout(this.refreshViewTimeout);\n this.refreshViewTimeout = undefined;\n }\n this.lineStateRefreshPending = true;\n this.escalateEditSessionRender();\n return;\n }\n if (shouldRefreshDiffsView === true) {\n if (this.refreshViewTimeout != null) {\n clearTimeout(this.refreshViewTimeout);\n }\n this.lineStateRefreshPending = true;\n this.refreshViewTimeout = setTimeout(() => {\n this.refreshViewTimeout = undefined;\n if (this.options.diffStyle === 'split') {\n this.refreshSplitDiffView();\n } else {\n this.refreshUnifiedDiffView();\n }\n this.flushDeferredLineState();\n }, 150);\n }\n }\n\n private detachAdditionLines(): void {\n const { diff: editSessionDiff, inputDiff } = this.editSession ?? {};\n if (\n editSessionDiff != null &&\n (editSessionDiff.additionLines === inputDiff?.additionLines ||\n editSessionDiff.additionLines === editSessionDiff.deletionLines)\n ) {\n editSessionDiff.additionLines = [...editSessionDiff.additionLines];\n }\n }\n\n // Editor-facing visibility oracle: whether a one-based new-file line has\n // (or will have on scroll) a rendered row under the current expansion\n // state. See isAdditionLineRenderable.\n public isLineRenderable(lineNumber: number): boolean {\n const fileDiff = this.getRenderedDiff();\n if (fileDiff == null) {\n return true;\n }\n const {\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n return isAdditionLineRenderable({\n fileDiff,\n lineNumber,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n });\n }\n\n // Fold-skip companion to isLineRenderable: the nearest renderable one-based\n // new-file line at or beyond lineNumber in the given direction.\n public getNearestRenderableLine(\n lineNumber: number,\n direction: 'up' | 'down'\n ): number | undefined {\n const fileDiff = this.getRenderedDiff();\n if (fileDiff == null) {\n return lineNumber;\n }\n const {\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n return getNearestRenderableAdditionLine({\n fileDiff,\n lineNumber,\n direction,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n });\n }\n\n // Expand collapsed context so a one-based new-file line can render: one\n // deterministic expansion from the nearest gap edge, sized to reach the\n // target plus the normal expansion step (clamped to the gap at render).\n // Routed through expandHunk so subclass expansion flows (CodeView's\n // deferred pendingExpansions) apply.\n public revealLine(lineNumber: number): boolean {\n const fileDiff = this.getRenderedDiff();\n const {\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n expansionLineCount = 100,\n } = this.options;\n if (fileDiff == null || fileDiff.isPartial || expandUnchanged) {\n return false;\n }\n const expandedHunks = this.hunksRenderer.getExpandedHunksMap();\n\n for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {\n const [hunkStart, hunkEnd] = getHunkAdditionLineRange(hunk);\n if (lineNumber < hunkStart) {\n const region = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const gapStart = hunkStart - region.rangeSize;\n if (\n region.renderAll ||\n lineNumber < gapStart + region.fromStart ||\n lineNumber >= hunkStart - region.fromEnd\n ) {\n return false;\n }\n const fromStartDistance =\n lineNumber - (gapStart + region.fromStart) + 1;\n const fromEndDistance = hunkStart - region.fromEnd - lineNumber;\n if (fromStartDistance <= fromEndDistance) {\n this.expandHunk(\n hunkIndex,\n 'up',\n fromStartDistance + expansionLineCount\n );\n } else {\n this.expandHunk(\n hunkIndex,\n 'down',\n fromEndDistance + expansionLineCount\n );\n }\n return true;\n }\n if (lineNumber < hunkEnd) {\n return false;\n }\n }\n\n const trailingRegion = getTrailingExpandedRegion({\n fileDiff,\n hunkIndex: fileDiff.hunks.length - 1,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'FileDiff.revealLine',\n });\n if (trailingRegion == null || trailingRegion.renderAll) {\n return false;\n }\n const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];\n const [, trailingStart] = getHunkAdditionLineRange(lastHunk);\n if (\n lineNumber < trailingStart + trailingRegion.fromStart ||\n lineNumber >= trailingStart + trailingRegion.rangeSize\n ) {\n return false;\n }\n this.expandHunk(\n fileDiff.hunks.length,\n 'up',\n lineNumber -\n (trailingStart + trailingRegion.fromStart) +\n 1 +\n expansionLineCount\n );\n return true;\n }\n\n // Whether render() may run the session-exit recompute on dirty metadata.\n // False while an editor is attached (the session is live). CodeView-managed\n // instances override this: their sessions survive recycling with no editor\n // attached, and CodeView runs the exit recompute itself when it reaps a\n // session.\n protected shouldSelfHealEditSession(): boolean {\n return this.editor == null;\n }\n\n // Deferred full re-render for session region changes. The subsequent\n // render() ends in syncRenderViewToEditor, which resets the editor's\n // geometry caches against the rebuilt rows. VirtualizedFileDiff overrides\n // this to also invalidate its layout caches.\n protected escalateEditSessionRender(): void {\n queueRender(this.handleEditSessionRender);\n }\n\n private handleEditSessionRender = (): void => {\n this.rerender();\n this.flushDeferredLineState();\n };\n\n private removeRenderedCode(): void {\n this.resizeManager.cleanUp();\n this.scrollSyncManager.cleanUp();\n this.interactionManager.cleanUp();\n\n this.bufferBefore?.remove();\n this.bufferBefore = undefined;\n this.bufferAfter?.remove();\n this.bufferAfter = undefined;\n\n this.codeUnified?.remove();\n this.codeUnified = undefined;\n this.codeDeletions?.remove();\n this.codeDeletions = undefined;\n this.codeAdditions?.remove();\n this.codeAdditions = undefined;\n\n this.pre?.remove();\n this.pre = undefined;\n\n this.appliedPreAttributes = undefined;\n this.lastRowCount = undefined;\n }\n\n private clearAuxiliaryNodes(): void {\n for (const { element } of this.separatorCache.values()) {\n element.remove();\n }\n this.separatorCache.clear();\n\n for (const { element } of this.annotationCache.values()) {\n element.remove();\n }\n this.annotationCache.clear();\n\n this.gutterUtilityContent?.remove();\n this.gutterUtilityContent = undefined;\n }\n\n public renderPlaceholder(height: number): boolean {\n if (this.fileContainer == null) {\n return false;\n }\n this.emitPostRender(true);\n this.cleanChildNodes();\n\n if (this.placeHolder == null) {\n const shadowRoot =\n this.fileContainer.shadowRoot ??\n this.fileContainer.attachShadow({ mode: 'open' });\n this.placeHolder = document.createElement('div');\n this.placeHolder.dataset.placeholder = '';\n shadowRoot.appendChild(this.placeHolder);\n }\n return this.setPlaceholderHeight(height);\n }\n\n protected setPlaceholderHeight(height: number): boolean {\n if (this.placeHolder == null) {\n return false;\n }\n this.placeHolder.style.setProperty('height', `${height}px`);\n return true;\n }\n\n public async primeHighlightCache(\n fileDiff: FileDiffMetadata | undefined = this.getInputDiff()\n ): Promise<void> {\n const { workerManager } = this;\n if (\n fileDiff == null ||\n workerManager == null ||\n !workerManager.isWorkingPool() ||\n fileDiff.cacheKey == null ||\n isDiffPlainText(fileDiff)\n ) {\n return;\n }\n const tokenizeMaxLength =\n this.options.tokenizeMaxLength ?? DEFAULT_TOKENIZE_MAX_LENGTH;\n if (\n Math.max(fileDiff.additionLines.length, fileDiff.deletionLines.length) >\n tokenizeMaxLength\n ) {\n return;\n }\n\n await workerManager\n .primeDiffHighlightCache(fileDiff)\n .catch((error: unknown) => {\n if (isHandledWorkerPoolError(error)) {\n return;\n }\n console.error(error);\n });\n }\n\n private cleanChildNodes() {\n this.resizeManager.cleanUp();\n this.scrollSyncManager.cleanUp();\n this.interactionManager.cleanUp();\n this.clearAuxiliaryNodes();\n\n this.bufferAfter?.remove();\n this.bufferBefore?.remove();\n this.codeAdditions?.remove();\n this.codeDeletions?.remove();\n this.codeUnified?.remove();\n this.errorWrapper?.remove();\n this.headerElement?.remove();\n this.headerPrefix?.remove();\n this.headerFilenameSuffix?.remove();\n this.headerMetadata?.remove();\n this.headerCustom?.remove();\n this.pre?.remove();\n this.spriteSVG?.remove();\n this.themeCSSStyle?.remove();\n this.unsafeCSSStyle?.remove();\n\n this.bufferAfter = undefined;\n this.bufferBefore = undefined;\n this.codeAdditions = undefined;\n this.codeDeletions = undefined;\n this.codeUnified = undefined;\n this.errorWrapper = undefined;\n this.headerElement = undefined;\n this.headerPrefix = undefined;\n this.headerFilenameSuffix = undefined;\n this.headerMetadata = undefined;\n this.headerCustom = undefined;\n this.pre = undefined;\n this.spriteSVG = undefined;\n this.themeCSSStyle = undefined;\n this.appliedThemeCSS = undefined;\n this.hasAdoptedThemeCSS = false;\n this.unsafeCSSStyle = undefined;\n this.appliedUnsafeCSS = undefined;\n\n this.headerCache.lastRenderedHTML = undefined;\n this.lastRowCount = undefined;\n this.mounted = false;\n }\n\n private renderSeparators(hunkData: HunkData[]): void {\n const { hunkSeparators } = this.options;\n if (\n this.isComponentManaged ||\n this.fileContainer == null ||\n typeof hunkSeparators !== 'function'\n ) {\n for (const { element } of this.separatorCache.values()) {\n element.remove();\n }\n this.separatorCache.clear();\n return;\n }\n const staleSeparators = new Map(this.separatorCache);\n for (const hunk of hunkData) {\n const id = hunk.slotName;\n let cache = this.separatorCache.get(id);\n if (cache == null || !areHunkDataEqual(hunk, cache.hunkData)) {\n cache?.element.remove();\n const element = document.createElement('div');\n element.style.display = 'contents';\n element.slot = hunk.slotName;\n const child = hunkSeparators(hunk, this);\n if (child != null) {\n element.appendChild(child);\n }\n this.fileContainer.appendChild(element);\n cache = { element, hunkData: hunk };\n this.separatorCache.set(id, cache);\n }\n staleSeparators.delete(id);\n }\n for (const [id, { element }] of staleSeparators.entries()) {\n this.separatorCache.delete(id);\n element.remove();\n }\n }\n\n protected renderAnnotations(): void {\n if (this.isComponentManaged || this.fileContainer == null) {\n for (const { element } of this.annotationCache.values()) {\n element.remove();\n }\n this.annotationCache.clear();\n return;\n }\n const staleAnnotations = new Map(this.annotationCache);\n const {\n renderedData,\n options: { renderAnnotation },\n } = this;\n if (renderAnnotation != null && renderedData != null) {\n const { fileDiff, lineAnnotations } = renderedData;\n for (const [index, annotation] of lineAnnotations.entries()) {\n const name = this.getAnnotationSlotName(annotation);\n const id = `${index}-${name}`;\n let cache = this.annotationCache.get(id);\n if (\n cache == null ||\n cache.fileDiff !== fileDiff ||\n !areDiffLineAnnotationsEqual(annotation, cache.annotation)\n ) {\n cache?.element.remove();\n const content = renderAnnotation(annotation, fileDiff);\n // If we can't render anything, then we should not render anything\n // and clear the annotation cache if necessary.\n if (content == null) {\n continue;\n }\n cache = {\n element: createAnnotationWrapperNode(name),\n annotation,\n fileDiff,\n };\n cache.element.appendChild(content);\n this.fileContainer.appendChild(cache.element);\n this.annotationCache.set(id, cache);\n }\n staleAnnotations.delete(id);\n }\n }\n for (const [id, { element }] of staleAnnotations.entries()) {\n this.annotationCache.delete(id);\n element.remove();\n }\n }\n\n protected renderGutterUtility(): void {\n const { renderGutterUtility } = this.options;\n if (this.fileContainer == null || renderGutterUtility == null) {\n this.gutterUtilityContent?.remove();\n this.gutterUtilityContent = undefined;\n return;\n }\n const element = renderGutterUtility(this.interactionManager.getHoveredLine);\n if (element != null && this.gutterUtilityContent != null) {\n return;\n } else if (element == null) {\n this.gutterUtilityContent?.remove();\n this.gutterUtilityContent = undefined;\n return;\n }\n const gutterUtilityContent = createGutterUtilityContentNode();\n gutterUtilityContent.appendChild(element);\n this.fileContainer.appendChild(gutterUtilityContent);\n this.gutterUtilityContent = gutterUtilityContent;\n }\n\n protected getOrCreateFileContainer(\n fileContainer?: HTMLElement,\n parentNode?: HTMLElement\n ): HTMLElement {\n const { fileContainer: previousContainer } = this;\n const nextContainer =\n fileContainer ??\n previousContainer ??\n document.createElement(DIFFS_TAG_NAME);\n const containerChanged = previousContainer !== nextContainer;\n if (previousContainer != null && containerChanged) {\n this.editor?.__captureFocusForDOMReplacement();\n }\n if (containerChanged) {\n this.emitPostRender(true);\n }\n this.fileContainer = nextContainer;\n if (previousContainer != null && containerChanged) {\n this.headerCache.lastRenderedHTML = undefined;\n this.headerElement = undefined;\n }\n if (parentNode != null && this.fileContainer.parentNode !== parentNode) {\n parentNode.appendChild(this.fileContainer);\n }\n if (containerChanged) {\n this.adoptReusableShellElements(this.fileContainer);\n }\n this.ensureSpriteSVG(this.fileContainer);\n return this.fileContainer;\n }\n\n // NOTE(amadeus): Technically this method is not safe for use outside of\n // the CodeView component, however I don't think in practice it really\n // should matter, but maybe there's some system we need in place to prevent\n // this from running outside of that environment?\n //\n // It's making very specific assumptions that all the elements will have the\n // correct content based on CodeView global options\n private adoptReusableShellElements(fileContainer: HTMLElement): void {\n const { shadowRoot } = fileContainer;\n if (shadowRoot == null) {\n return;\n }\n\n for (const element of shadowRoot.children) {\n if (element instanceof SVGElement) {\n this.spriteSVG ??= element;\n } else if (\n isStyleNode(element) &&\n element.hasAttribute(THEME_CSS_ATTRIBUTE)\n ) {\n this.themeCSSStyle ??= element;\n this.hasAdoptedThemeCSS = true;\n } else if (\n isStyleNode(element) &&\n element.hasAttribute(UNSAFE_CSS_ATTRIBUTE)\n ) {\n this.unsafeCSSStyle ??= element;\n this.appliedUnsafeCSS ??= this.options.unsafeCSS ?? undefined;\n }\n }\n }\n\n private ensureSpriteSVG(fileContainer: HTMLElement): void {\n const shadowRoot =\n fileContainer.shadowRoot ?? fileContainer.attachShadow({ mode: 'open' });\n if (this.spriteSVG == null) {\n const fragment = document.createElement('div');\n fragment.innerHTML = SVGSpriteSheet;\n const firstChild = fragment.firstChild;\n if (firstChild instanceof SVGElement) {\n this.spriteSVG = firstChild;\n }\n }\n if (this.spriteSVG != null && this.spriteSVG.parentNode !== shadowRoot) {\n shadowRoot.appendChild(this.spriteSVG);\n }\n }\n\n private getOrCreatePreNode(container: HTMLElement): HTMLPreElement {\n const shadowRoot =\n container.shadowRoot ?? container.attachShadow({ mode: 'open' });\n // If we haven't created a pre element yet, lets go ahead and do that\n if (this.pre == null) {\n this.pre = document.createElement('pre');\n this.appliedPreAttributes = undefined;\n this.codeUnified = undefined;\n this.codeDeletions = undefined;\n this.codeAdditions = undefined;\n shadowRoot.appendChild(this.pre);\n }\n // If we have a new parent container for the pre element, lets go ahead and\n // move it into the new container\n else if (this.pre.parentNode !== shadowRoot) {\n this.editor?.__captureFocusForDOMReplacement();\n shadowRoot.appendChild(this.pre);\n this.appliedPreAttributes = undefined;\n }\n\n this.placeHolder?.remove();\n this.placeHolder = undefined;\n\n return this.pre;\n }\n\n protected syncCodeNodesFromPre(pre: HTMLPreElement): void {\n this.codeUnified = undefined;\n this.codeDeletions = undefined;\n this.codeAdditions = undefined;\n for (const child of Array.from(pre.children)) {\n if (!(child instanceof HTMLElement)) {\n continue;\n }\n if (child.hasAttribute('data-unified')) {\n this.codeUnified = child;\n } else if (child.hasAttribute('data-deletions')) {\n this.codeDeletions = child;\n } else if (child.hasAttribute('data-additions')) {\n this.codeAdditions = child;\n }\n }\n }\n\n private applyHeaderToDOM(\n headerAST: HASTElement,\n container: HTMLElement,\n fileDiff: FileDiffMetadata\n ): void {\n this.cleanupErrorWrapper();\n this.placeHolder?.remove();\n this.placeHolder = undefined;\n // Session metadata changes in place, so an HTML cache created from the\n // input diff cannot describe the current edit-session header.\n const {\n headerCache: {\n fileDiff: cachedHeaderDiff,\n html: cachedHeaderHTML,\n lastRenderedHTML,\n },\n } = this;\n const editSessionDiff = this.editSession?.diff;\n const reusableHeaderHTML =\n fileDiff !== editSessionDiff &&\n areDiffTargetsEqual(cachedHeaderDiff, fileDiff)\n ? cachedHeaderHTML\n : undefined;\n const headerHTML = reusableHeaderHTML ?? hastToHtml(headerAST);\n this.headerCache.html = headerHTML;\n this.headerCache.fileDiff = fileDiff;\n if (headerHTML !== lastRenderedHTML) {\n const tempDiv = document.createElement('div');\n tempDiv.innerHTML = headerHTML;\n const newHeader = tempDiv.firstElementChild;\n if (!(newHeader instanceof HTMLElement)) {\n return;\n }\n if (this.headerElement != null) {\n container.shadowRoot?.replaceChild(newHeader, this.headerElement);\n } else {\n container.shadowRoot?.prepend(newHeader);\n }\n this.headerElement = newHeader;\n this.headerCache.lastRenderedHTML = headerHTML;\n }\n\n if (this.isComponentManaged) {\n return;\n }\n\n const {\n renderCustomHeader,\n renderHeaderPrefix,\n renderHeaderFilenameSuffix,\n renderHeaderMetadata,\n } = this.options;\n\n if (renderCustomHeader != null) {\n const content = renderCustomHeader(fileDiff) ?? undefined;\n this.headerCustom = this.upsertHeaderSlotElement(\n container,\n this.headerCustom,\n CUSTOM_HEADER_SLOT_ID,\n content\n );\n this.headerPrefix?.remove();\n this.headerFilenameSuffix?.remove();\n this.headerMetadata?.remove();\n this.headerPrefix = undefined;\n this.headerFilenameSuffix = undefined;\n this.headerMetadata = undefined;\n return;\n }\n\n const prefix = renderHeaderPrefix?.(fileDiff) ?? undefined;\n const suffix = renderHeaderFilenameSuffix?.(fileDiff) ?? undefined;\n const content = renderHeaderMetadata?.(fileDiff) ?? undefined;\n this.headerPrefix = this.upsertHeaderSlotElement(\n container,\n this.headerPrefix,\n HEADER_PREFIX_SLOT_ID,\n prefix\n );\n this.headerFilenameSuffix = this.upsertHeaderSlotElement(\n container,\n this.headerFilenameSuffix,\n HEADER_FILENAME_SUFFIX_SLOT_ID,\n suffix\n );\n this.headerMetadata = this.upsertHeaderSlotElement(\n container,\n this.headerMetadata,\n HEADER_METADATA_SLOT_ID,\n content\n );\n this.headerCustom?.remove();\n this.headerCustom = undefined;\n }\n\n protected clearReusableHeader(): void {\n this.headerCache.html = undefined;\n this.headerCache.fileDiff = undefined;\n }\n\n private clearHeaderSlots(): void {\n this.headerPrefix?.remove();\n this.headerFilenameSuffix?.remove();\n this.headerMetadata?.remove();\n this.headerCustom?.remove();\n this.headerPrefix = undefined;\n this.headerFilenameSuffix = undefined;\n this.headerMetadata = undefined;\n this.headerCustom = undefined;\n }\n\n // Header slot callbacks are presence-based render hooks, not reactive views.\n private upsertHeaderSlotElement(\n container: HTMLElement,\n current: HTMLElement | undefined,\n slot: string,\n content: Element | string | number | undefined\n ): HTMLElement | undefined {\n if (content == null) {\n current?.remove();\n return undefined;\n }\n const element = current ?? this.createHeaderSlotElement(slot);\n if (current == null) {\n container.appendChild(element);\n }\n this.replaceHeaderSlotContent(element, content);\n return element;\n }\n\n private replaceHeaderSlotContent(\n element: HTMLElement,\n content: Element | string | number\n ): void {\n element.replaceChildren();\n if (content instanceof Element) {\n element.appendChild(content);\n } else {\n element.innerText = `${content}`;\n }\n }\n\n private createHeaderSlotElement(slot: string): HTMLElement {\n const element = document.createElement('div');\n element.slot = slot;\n return element;\n }\n\n protected injectUnsafeCSS(): void {\n const { unsafeCSS } = this.options;\n this.pre?.toggleAttribute('data-custom-styles', Boolean(unsafeCSS));\n const shadowRoot = this.fileContainer?.shadowRoot;\n if (shadowRoot == null) {\n return;\n }\n\n if (unsafeCSS == null || unsafeCSS === '') {\n if (this.unsafeCSSStyle != null) {\n this.unsafeCSSStyle.remove();\n this.unsafeCSSStyle = undefined;\n }\n this.appliedUnsafeCSS = undefined;\n return;\n }\n\n if (\n this.unsafeCSSStyle?.parentNode === shadowRoot &&\n this.appliedUnsafeCSS === unsafeCSS\n ) {\n return;\n }\n\n // Create or update the style element\n this.unsafeCSSStyle ??= createUnsafeCSSStyleNode();\n if (this.unsafeCSSStyle.parentNode !== shadowRoot) {\n shadowRoot.appendChild(this.unsafeCSSStyle);\n }\n // Wrap in @layer unsafe to match SSR behavior\n this.unsafeCSSStyle.textContent = wrapUnsafeCSS(unsafeCSS);\n this.appliedUnsafeCSS = unsafeCSS;\n }\n\n private applyThemeState(\n container: HTMLElement,\n themeStyles: string,\n themeType: ThemeTypes,\n baseThemeType?: 'light' | 'dark'\n ): void {\n const shadowRoot =\n container.shadowRoot ?? container.attachShadow({ mode: 'open' });\n const effectiveThemeType = baseThemeType ?? themeType;\n const currentTheme = this.getTheme();\n const theme =\n typeof currentTheme === 'string' ? currentTheme : { ...currentTheme };\n const scrollbarGutter = getMeasuredScrollbarGutter(shadowRoot);\n if (\n this.themeCSSStyle?.parentNode === shadowRoot &&\n this.appliedThemeCSS?.themeStyles === themeStyles &&\n this.appliedThemeCSS.themeType === effectiveThemeType &&\n this.appliedThemeCSS.scrollbarGutter === scrollbarGutter\n ) {\n this.appliedThemeCSS.theme = theme;\n return;\n }\n if (\n this.hasAdoptedThemeCSS &&\n this.themeCSSStyle?.parentNode === shadowRoot\n ) {\n this.hasAdoptedThemeCSS = false;\n this.appliedThemeCSS = {\n theme,\n themeStyles,\n themeType: effectiveThemeType,\n baseThemeType,\n scrollbarGutter,\n };\n return;\n }\n this.themeCSSStyle = upsertHostThemeStyle({\n shadowRoot,\n currentNode: this.themeCSSStyle,\n themeCSS: wrapThemeCSS(themeStyles, effectiveThemeType, scrollbarGutter),\n });\n this.appliedThemeCSS =\n this.themeCSSStyle != null\n ? {\n theme,\n themeStyles,\n themeType: effectiveThemeType,\n baseThemeType,\n scrollbarGutter,\n }\n : undefined;\n }\n\n private hydrateMeasuredScrollbar(): void {\n const shadowRoot = this.fileContainer?.shadowRoot;\n if (shadowRoot == null || this.themeCSSStyle == null) {\n return;\n }\n this.themeCSSStyle.textContent = patchScrollbarGutterSize(\n this.themeCSSStyle.textContent ?? '',\n getMeasuredScrollbarGutter(shadowRoot)\n );\n }\n\n // A boolean check to ensure that edit mode in WebKit doesn't cause potential\n // scroll jumps to due bugs with WebKit. The workarounds have performance\n // implications so we avoid running the workarounds on browsers or scenarios\n // where they are not applicable\n protected shouldGuardRebuildScroll(): boolean {\n return this.editor != null && isSafari();\n }\n\n private applyHunksToDOM(\n pre: HTMLPreElement,\n result: HunksRenderResult\n ): void {\n if (this.shouldGuardRebuildScroll()) {\n guardWebKitScrollDuringRebuild(pre, () =>\n this.replaceCodeColumns(pre, result)\n );\n } else {\n this.replaceCodeColumns(pre, result);\n }\n }\n\n // Renders a code column's AST into an existing elements without replacing\n // the gutter and content parents. Identity matters in edit mode: the content\n // element is the focused contenteditable, and replacing it ends the\n // browser's editing session — focus tears down and restores, and iOS\n // answers every session restart with an animated caret reveal.\n //\n // Returns false when the element has no column pair yet (initial render,\n // or a diff-style switch built a fresh element); the caller then assigns\n // the full innerHTML.\n private applyCodeColumnsInPlace(\n code: HTMLElement,\n ast: ElementContent[],\n rowCount: number\n ): boolean {\n const columns = this.getColumnPair(code);\n if (columns == null) {\n return false;\n }\n const gutterChildren = getElementChildren(ast[0]);\n const contentChildren = getElementChildren(ast[1]);\n if (gutterChildren == null || contentChildren == null) {\n return false;\n }\n columns.gutter.innerHTML = hastToHtml(gutterChildren);\n columns.content.innerHTML = hastToHtml(contentChildren);\n if (rowCount !== this.lastRowCount) {\n columns.gutter.style.setProperty('grid-row', `span ${rowCount}`);\n columns.content.style.setProperty('grid-row', `span ${rowCount}`);\n }\n return true;\n }\n\n private replaceCodeColumns(\n pre: HTMLPreElement,\n result: HunksRenderResult\n ): void {\n const { overflow = 'scroll' } = this.options;\n const containerSize =\n (this.options.hunkSeparators ?? 'line-info') === 'line-info';\n const rowSpan = overflow === 'wrap' ? result.rowCount : undefined;\n this.cleanupErrorWrapper();\n this.applyPreNodeAttributes(pre, result);\n\n let shouldReplace = false;\n // Create code elements and insert HTML content\n const codeElements: HTMLElement[] = [];\n const unifiedAST = this.hunksRenderer.renderCodeAST('unified', result);\n const deletionsAST = this.hunksRenderer.renderCodeAST('deletions', result);\n const additionsAST = this.hunksRenderer.renderCodeAST('additions', result);\n this.editor?.__captureFocusForDOMReplacement();\n if (unifiedAST != null) {\n shouldReplace =\n this.codeUnified == null ||\n this.codeAdditions != null ||\n this.codeDeletions != null;\n\n // Clean up addition/deletion elements if necessary\n this.codeDeletions?.remove();\n this.codeDeletions = undefined;\n this.codeAdditions?.remove();\n this.codeAdditions = undefined;\n\n this.codeUnified = getOrCreateCodeNode({\n code: this.codeUnified,\n columnType: 'unified',\n rowSpan,\n containerSize,\n });\n if (\n !this.applyCodeColumnsInPlace(\n this.codeUnified,\n unifiedAST,\n result.rowCount\n )\n ) {\n this.codeUnified.innerHTML =\n this.hunksRenderer.renderPartialHTML(unifiedAST);\n }\n codeElements.push(this.codeUnified);\n } else if (deletionsAST != null || additionsAST != null) {\n if (deletionsAST != null) {\n shouldReplace = this.codeDeletions == null || this.codeUnified != null;\n\n // Clean up unified column if necessary\n this.codeUnified?.remove();\n this.codeUnified = undefined;\n\n this.codeDeletions = getOrCreateCodeNode({\n code: this.codeDeletions,\n columnType: 'deletions',\n rowSpan,\n containerSize,\n });\n if (\n !this.applyCodeColumnsInPlace(\n this.codeDeletions,\n deletionsAST,\n result.rowCount\n )\n ) {\n this.codeDeletions.innerHTML =\n this.hunksRenderer.renderPartialHTML(deletionsAST);\n }\n codeElements.push(this.codeDeletions);\n } else {\n // If we have no deletion column, lets clean it up if it exists\n this.codeDeletions?.remove();\n this.codeDeletions = undefined;\n }\n\n if (additionsAST != null) {\n shouldReplace =\n shouldReplace ||\n this.codeAdditions == null ||\n this.codeUnified != null;\n\n // Clean up unified column if necessary\n this.codeUnified?.remove();\n this.codeUnified = undefined;\n\n this.codeAdditions = getOrCreateCodeNode({\n code: this.codeAdditions,\n columnType: 'additions',\n rowSpan,\n containerSize,\n });\n if (\n !this.applyCodeColumnsInPlace(\n this.codeAdditions,\n additionsAST,\n result.rowCount\n )\n ) {\n this.codeAdditions.innerHTML =\n this.hunksRenderer.renderPartialHTML(additionsAST);\n }\n codeElements.push(this.codeAdditions);\n } else {\n // If we have no addition column, lets clean it up if it exists\n this.codeAdditions?.remove();\n this.codeAdditions = undefined;\n }\n } else {\n // if we get in here, there's no content to render, so lets just clean\n // everything up\n this.codeUnified?.remove();\n this.codeUnified = undefined;\n this.codeDeletions?.remove();\n this.codeDeletions = undefined;\n this.codeAdditions?.remove();\n this.codeAdditions = undefined;\n }\n\n if (codeElements.length === 0) {\n pre.textContent = '';\n } else if (shouldReplace) {\n pre.replaceChildren(...codeElements);\n }\n\n this.lastRowCount = result.rowCount;\n }\n\n private applyPartialRender({\n fileDiff,\n previousRenderRange,\n renderRange,\n }: ApplyPartialRenderProps): boolean {\n const {\n pre,\n codeUnified,\n codeAdditions,\n codeDeletions,\n options: { diffStyle = 'split' },\n } = this;\n if (\n pre == null ||\n // We must have a current and previous render range to do a partial render\n previousRenderRange == null ||\n renderRange == null ||\n // Neither render range may be infinite\n !Number.isFinite(previousRenderRange.totalLines) ||\n !Number.isFinite(renderRange.totalLines) ||\n this.lastRowCount == null\n ) {\n return false;\n }\n const codeElements = this.getCodeColumns(\n diffStyle,\n codeUnified,\n codeDeletions,\n codeAdditions\n );\n if (codeElements == null) {\n return false;\n }\n\n const previousStart = previousRenderRange.startingLine;\n const nextStart = renderRange.startingLine;\n const previousEnd = previousStart + previousRenderRange.totalLines;\n const nextEnd = nextStart + renderRange.totalLines;\n\n const overlapStart = Math.max(previousStart, nextStart);\n const overlapEnd = Math.min(previousEnd, nextEnd);\n if (overlapEnd <= overlapStart) {\n return false;\n }\n\n const trimStart = Math.max(0, overlapStart - previousStart);\n const trimEnd = Math.max(0, previousEnd - overlapEnd);\n\n const trimResult = this.trimColumns({\n columns: codeElements,\n trimStart,\n trimEnd,\n previousStart,\n overlapStart,\n overlapEnd,\n diffStyle,\n });\n if (trimResult < 0) {\n throw new Error('FileDiff.applyPartialRender: failed to trim to overlap');\n }\n\n if (this.lastRowCount < trimResult) {\n throw new Error(\n 'FileDiff.applyPartialRender: trimmed beyond DOM row count'\n );\n }\n\n let rowCount = this.lastRowCount - trimResult;\n const renderChunk = (\n startingLine: number,\n totalLines: number\n ): HunksRenderResult | undefined => {\n if (totalLines <= 0) {\n return undefined;\n }\n return this.hunksRenderer.renderDiff(fileDiff, {\n startingLine,\n totalLines,\n bufferBefore: 0,\n bufferAfter: 0,\n });\n };\n\n const prependResult = renderChunk(\n nextStart,\n Math.max(overlapStart - nextStart, 0)\n );\n if (prependResult == null && nextStart < overlapStart) {\n return false;\n }\n\n const appendResult = renderChunk(\n overlapEnd,\n Math.max(nextEnd - overlapEnd, 0)\n );\n if (appendResult == null && nextEnd > overlapEnd) {\n return false;\n }\n\n const applyChunk = (\n result: HunksRenderResult | undefined,\n insertPosition: 'afterbegin' | 'beforeend'\n ) => {\n if (result == null) {\n return;\n }\n if (diffStyle === 'unified' && !Array.isArray(codeElements)) {\n this.insertPartialHTML(diffStyle, codeElements, result, insertPosition);\n } else if (diffStyle === 'split' && Array.isArray(codeElements)) {\n this.insertPartialHTML(diffStyle, codeElements, result, insertPosition);\n } else {\n throw new Error(\n 'FileDiff.applyPartialRender.applyChunk: invalid chunk application'\n );\n }\n rowCount += result.rowCount;\n this.adoptRenderData(result.fileDiff);\n };\n\n this.cleanupErrorWrapper();\n applyChunk(prependResult, 'afterbegin');\n applyChunk(appendResult, 'beforeend');\n\n if (this.lastRowCount !== rowCount) {\n this.applyRowSpan(diffStyle, codeElements, rowCount);\n this.lastRowCount = rowCount;\n }\n\n return true;\n }\n\n private insertPartialHTML(\n diffStyle: 'unified',\n columns: ColumnElements,\n result: HunksRenderResult,\n insertPosition: 'afterbegin' | 'beforeend'\n ): void;\n private insertPartialHTML(\n diffStyle: 'split',\n columns: [ColumnElements | undefined, ColumnElements | undefined],\n result: HunksRenderResult,\n insertPosition: 'afterbegin' | 'beforeend'\n ): void;\n private insertPartialHTML(\n diffStyle: 'split' | 'unified',\n columns:\n | [ColumnElements | undefined, ColumnElements | undefined]\n | ColumnElements,\n result: HunksRenderResult,\n insertPosition: 'afterbegin' | 'beforeend'\n ): void {\n if (diffStyle === 'unified' && !Array.isArray(columns)) {\n const unifiedAST = this.hunksRenderer.renderCodeAST('unified', result);\n this.renderPartialColumn(columns, unifiedAST, insertPosition);\n } else if (diffStyle === 'split' && Array.isArray(columns)) {\n const deletionsAST = this.hunksRenderer.renderCodeAST(\n 'deletions',\n result\n );\n const additionsAST = this.hunksRenderer.renderCodeAST(\n 'additions',\n result\n );\n this.renderPartialColumn(columns[0], deletionsAST, insertPosition);\n this.renderPartialColumn(columns[1], additionsAST, insertPosition);\n } else {\n throw new Error(\n 'FileDiff.insertPartialHTML: Invalid argument composition'\n );\n }\n }\n\n // fast refresh diff view via updating the `data-line-type` after an edit.\n // only for split view.\n private refreshSplitDiffView(): void {\n const fileDiff = this.getWorkingDiff();\n if (this.options.diffStyle !== 'split' || fileDiff == null) {\n return;\n }\n\n const hunksResult = this.hunksRenderer.renderDiff(\n fileDiff,\n this.renderRange\n );\n if (hunksResult == null) {\n return;\n }\n\n const columns = this.getCodeColumns(\n 'split',\n this.codeUnified,\n this.codeDeletions,\n this.codeAdditions\n );\n if (!Array.isArray(columns)) {\n return;\n }\n\n const applyLineType = (\n type: 'deletions' | 'additions',\n column: ColumnElements | undefined\n ) => {\n if (column == null) {\n return;\n }\n const ast = this.hunksRenderer.renderCodeAST(type, hunksResult);\n const gutterChildren = getElementChildren(ast?.[0]);\n const contentChildren = getElementChildren(ast?.[1]);\n for (const [el, astChildren] of [\n [column.gutter, gutterChildren],\n [column.content, contentChildren],\n ] as const) {\n if (\n astChildren != null &&\n el.childElementCount === astChildren.length\n ) {\n for (let i = 0; i < astChildren.length; i++) {\n const gutterElement = el.children[i] as HTMLElement;\n const gutterChild = astChildren[i] as HASTElement;\n const lineType = gutterChild.properties['data-line-type'] as\n | string\n | undefined;\n if (\n lineType != null &&\n gutterElement.dataset.lineType !== lineType\n ) {\n gutterElement.dataset.lineType = lineType;\n }\n }\n }\n }\n };\n\n applyLineType('deletions', columns[0]);\n applyLineType('additions', columns[1]);\n this.adoptRenderData(hunksResult.fileDiff);\n }\n\n // full diff view re-rendering\n // only for unified view.\n private refreshUnifiedDiffView(): void {\n const fileDiff = this.getWorkingDiff();\n if (this.options.diffStyle !== 'unified' || fileDiff == null) {\n return;\n }\n\n const hunksResult = this.hunksRenderer.renderDiff(\n fileDiff,\n this.renderRange\n );\n if (hunksResult == null) {\n return;\n }\n\n const columns = this.getCodeColumns(\n 'unified',\n this.codeUnified,\n this.codeDeletions,\n this.codeAdditions\n );\n if (columns == null || Array.isArray(columns)) {\n return;\n }\n\n const ast = this.hunksRenderer.renderCodeAST('unified', hunksResult);\n const gutterChildren = getElementChildren(ast?.[0]);\n const contentChildren = getElementChildren(ast?.[1]);\n const applyColumns = () => {\n for (const [el, astChildren] of [\n [columns.gutter, gutterChildren],\n [columns.content, contentChildren],\n ] as const) {\n if (astChildren != null) {\n el.innerHTML = hastToHtml(astChildren);\n }\n }\n\n if (hunksResult.rowCount !== this.lastRowCount) {\n this.applyRowSpan('unified', columns, hunksResult.rowCount);\n this.lastRowCount = hunksResult.rowCount;\n }\n this.adoptRenderData(hunksResult.fileDiff);\n };\n if (this.shouldGuardRebuildScroll()) {\n guardWebKitScrollDuringRebuild(this.pre, applyColumns);\n } else {\n applyColumns();\n }\n this.renderSeparators(hunksResult.hunkData);\n\n this.managersDirty = true;\n this.flushManagers();\n\n // sync the render view to the editor\n this.syncRenderViewToEditor();\n }\n\n private renderPartialColumn(\n column: ColumnElements | undefined,\n ast: ElementContent[] | undefined,\n insertPosition: 'afterbegin' | 'beforeend'\n ) {\n if (column == null || ast == null) {\n return;\n }\n const gutterChildren = getElementChildren(ast[0]);\n const contentChildren = getElementChildren(ast[1]);\n if (gutterChildren == null || contentChildren == null) {\n throw new Error('FileDiff.insertPartialHTML: Unexpected AST structure');\n }\n const firstHASTElement = contentChildren.at(0);\n if (\n insertPosition === 'beforeend' &&\n firstHASTElement?.type === 'element' &&\n typeof firstHASTElement.properties['data-buffer-size'] === 'number'\n ) {\n this.mergeBuffersIfNecessary(\n firstHASTElement.properties['data-buffer-size'],\n column.content.children[column.content.children.length - 1],\n column.gutter.children[column.gutter.children.length - 1],\n gutterChildren,\n contentChildren,\n true\n );\n }\n const lastHASTElement = contentChildren.at(-1);\n if (\n insertPosition === 'afterbegin' &&\n lastHASTElement?.type === 'element' &&\n typeof lastHASTElement.properties['data-buffer-size'] === 'number'\n ) {\n this.mergeBuffersIfNecessary(\n lastHASTElement.properties['data-buffer-size'],\n column.content.children[0],\n column.gutter.children[0],\n gutterChildren,\n contentChildren,\n false\n );\n }\n\n column.gutter.insertAdjacentHTML(\n insertPosition,\n this.hunksRenderer.renderPartialHTML(gutterChildren)\n );\n column.content.insertAdjacentHTML(\n insertPosition,\n this.hunksRenderer.renderPartialHTML(contentChildren)\n );\n }\n\n private mergeBuffersIfNecessary(\n adjustmentSize: number,\n contentElement: Element,\n gutterElement: Element,\n gutterChildren: ElementContent[],\n contentChildren: ElementContent[],\n fromStart: boolean\n ) {\n if (\n !(contentElement instanceof HTMLElement) ||\n !(gutterElement instanceof HTMLElement)\n ) {\n return;\n }\n const currentSize = this.getBufferSize(contentElement.dataset);\n if (currentSize == null) {\n return;\n }\n if (fromStart) {\n gutterChildren.shift();\n contentChildren.shift();\n } else {\n gutterChildren.pop();\n contentChildren.pop();\n }\n this.updateBufferSize(contentElement, currentSize + adjustmentSize);\n this.updateBufferSize(gutterElement, currentSize + adjustmentSize);\n }\n\n private applyRowSpan(\n diffStyle: 'split' | 'unified',\n columns:\n | [ColumnElements | undefined, ColumnElements | undefined]\n | ColumnElements,\n rowCount: number\n ): void {\n const applySpan = (column: ColumnElements | undefined) => {\n if (column == null) {\n return;\n }\n column.gutter.style.setProperty('grid-row', `span ${rowCount}`);\n column.content.style.setProperty('grid-row', `span ${rowCount}`);\n };\n if (diffStyle === 'unified' && !Array.isArray(columns)) {\n applySpan(columns);\n } else if (diffStyle === 'split' && Array.isArray(columns)) {\n applySpan(columns[0]);\n applySpan(columns[1]);\n } else {\n throw new Error('dun fuuuuked up');\n }\n }\n\n private trimColumnRows(\n columns: ColumnElements | undefined,\n preTrimCount: number,\n postTrimStart: number\n ): number {\n let visibleLineIndex = 0;\n let rowCount = 0;\n let rowIndex = 0;\n let pendingMetadataTrim = false;\n const hasPostTrim = postTrimStart >= 0;\n\n if (columns == null) {\n return 0;\n }\n const contentChildren = Array.from(columns.content.children);\n const gutterChildren = Array.from(columns.gutter.children);\n if (contentChildren.length !== gutterChildren.length) {\n throw new Error('FileDiff.trimColumnRows: columns do not match');\n }\n\n while (rowIndex < contentChildren.length) {\n if (preTrimCount <= 0 && !hasPostTrim && !pendingMetadataTrim) {\n break;\n }\n const gutterElement = gutterChildren[rowIndex];\n const contentElement = contentChildren[rowIndex];\n rowIndex++;\n\n if (\n !(gutterElement instanceof HTMLElement) ||\n !(contentElement instanceof HTMLElement)\n ) {\n console.error({ gutterElement, contentElement });\n throw new Error('FileDiff.trimColumnRows: invalid row elements');\n }\n\n if (pendingMetadataTrim) {\n pendingMetadataTrim = false;\n if (\n (gutterElement.dataset.gutterBuffer === 'annotation' &&\n 'lineAnnotation' in contentElement.dataset) ||\n (gutterElement.dataset.gutterBuffer === 'metadata' &&\n 'noNewline' in contentElement.dataset)\n ) {\n gutterElement.remove();\n contentElement.remove();\n rowCount++;\n continue;\n }\n }\n\n // If we found a line element, lets trim it if necessary\n if (\n 'lineIndex' in gutterElement.dataset &&\n 'lineIndex' in contentElement.dataset\n ) {\n if (\n preTrimCount > 0 ||\n (hasPostTrim && visibleLineIndex >= postTrimStart)\n ) {\n gutterElement.remove();\n contentElement.remove();\n if (preTrimCount > 0) {\n preTrimCount--;\n if (preTrimCount === 0) {\n pendingMetadataTrim = true;\n }\n }\n rowCount++;\n }\n visibleLineIndex++;\n continue;\n }\n\n // Separators should be removed, but don't count towards line indices\n if (\n 'separator' in gutterElement.dataset &&\n 'separator' in contentElement.dataset\n ) {\n if (\n preTrimCount > 0 ||\n (hasPostTrim && visibleLineIndex >= postTrimStart)\n ) {\n gutterElement.remove();\n contentElement.remove();\n rowCount++;\n }\n continue;\n }\n\n // Annotations should be removed, but don't count towards line indices\n if (\n gutterElement.dataset.gutterBuffer === 'annotation' &&\n 'lineAnnotation' in contentElement.dataset\n ) {\n if (\n preTrimCount > 0 ||\n (hasPostTrim && visibleLineIndex >= postTrimStart)\n ) {\n gutterElement.remove();\n contentElement.remove();\n rowCount++;\n }\n continue;\n }\n\n if (\n gutterElement.dataset.gutterBuffer === 'metadata' &&\n 'noNewline' in contentElement.dataset\n ) {\n if (\n preTrimCount > 0 ||\n (hasPostTrim && visibleLineIndex >= postTrimStart)\n ) {\n gutterElement.remove();\n contentElement.remove();\n rowCount++;\n }\n continue;\n }\n\n if (\n gutterElement.dataset.gutterBuffer === 'buffer' &&\n 'contentBuffer' in contentElement.dataset\n ) {\n const totalRows = this.getBufferSize(contentElement.dataset);\n if (totalRows == null) {\n throw new Error('FileDiff.trimColumnRows: invalid element');\n }\n if (preTrimCount > 0) {\n const rowsToRemove = Math.min(preTrimCount, totalRows);\n const newSize = totalRows - rowsToRemove;\n if (newSize > 0) {\n this.updateBufferSize(gutterElement, newSize);\n this.updateBufferSize(contentElement, newSize);\n rowCount += rowsToRemove;\n } else {\n gutterElement.remove();\n contentElement.remove();\n rowCount += totalRows;\n }\n preTrimCount -= rowsToRemove;\n if (preTrimCount === 0 && newSize === 0) {\n pendingMetadataTrim = true;\n }\n }\n // If we are in a post clip era...\n else if (hasPostTrim) {\n const bufferStart = visibleLineIndex;\n const bufferEnd = visibleLineIndex + totalRows - 1;\n if (postTrimStart <= bufferStart) {\n gutterElement.remove();\n contentElement.remove();\n rowCount += totalRows;\n } else if (postTrimStart <= bufferEnd) {\n const rowsToRemove = bufferEnd - postTrimStart + 1;\n const newSize = totalRows - rowsToRemove;\n this.updateBufferSize(gutterElement, newSize);\n this.updateBufferSize(contentElement, newSize);\n rowCount += rowsToRemove;\n }\n }\n visibleLineIndex += totalRows;\n continue;\n }\n\n console.error({ gutterElement, contentElement });\n throw new Error('FileDiff.trimColumnRows: unknown row elements');\n }\n\n return rowCount;\n }\n\n private trimColumns({\n columns,\n diffStyle,\n overlapEnd,\n overlapStart,\n previousStart,\n trimEnd,\n trimStart,\n // NOTE(amadeus): If we return -1 it means something went wrong\n // with the trim...\n // oxlint-disable-next-line no-redundant-type-constituents\n }: TrimColumnsToOverlapProps): number | -1 {\n const preTrimCount = Math.max(0, overlapStart - previousStart);\n const postTrimStart = overlapEnd - previousStart;\n if (postTrimStart < 0) {\n throw new Error('FileDiff.trimColumns: overlap ends before previous');\n }\n const shouldTrimStart = trimStart > 0;\n const shouldTrimEnd = trimEnd > 0;\n if (!shouldTrimStart && !shouldTrimEnd) {\n return 0;\n }\n const effectivePreTrimCount = shouldTrimStart ? preTrimCount : 0;\n const effectivePostTrimStart = shouldTrimEnd ? postTrimStart : -1;\n\n if (diffStyle === 'unified' && !Array.isArray(columns)) {\n const removedRows = this.trimColumnRows(\n columns,\n effectivePreTrimCount,\n effectivePostTrimStart\n );\n return removedRows;\n } else if (diffStyle === 'split' && Array.isArray(columns)) {\n const deletionsTrim = this.trimColumnRows(\n columns[0],\n effectivePreTrimCount,\n effectivePostTrimStart\n );\n const additionsTrim = this.trimColumnRows(\n columns[1],\n effectivePreTrimCount,\n effectivePostTrimStart\n );\n // We should avoid the trim validation if we are split but\n // there's only one side\n if (\n columns[0] != null &&\n columns[1] != null &&\n deletionsTrim !== additionsTrim\n ) {\n throw new Error('FileDiff.trimColumns: split columns out of sync');\n }\n return columns[0] != null ? deletionsTrim : additionsTrim;\n } else {\n console.error({ diffStyle, columns });\n throw new Error('FileDiff.trimColumns: Invalid columns for diffType');\n }\n }\n\n private getBufferSize(properties: DOMStringMap): number | undefined {\n const parsed = Number.parseInt(properties?.bufferSize ?? '', 10);\n return Number.isNaN(parsed) ? undefined : parsed;\n }\n\n private updateBufferSize(element: HTMLElement, size: number): void {\n element.dataset.bufferSize = `${size}`;\n element.style.setProperty('grid-row', `span ${size}`);\n element.style.setProperty('min-height', `calc(${size} * 1lh)`);\n }\n\n private getColumnPair(\n code: HTMLElement | undefined\n ): ColumnElements | undefined {\n if (code == null) {\n return undefined;\n }\n const gutter = code.children[0];\n const content = code.children[1];\n if (\n !(gutter instanceof HTMLElement) ||\n !(content instanceof HTMLElement) ||\n gutter.dataset.gutter == null ||\n content.dataset.content == null\n ) {\n return undefined;\n }\n return { gutter, content };\n }\n\n private getCodeColumns(\n diffStyle: 'split' | 'unified',\n codeUnified: HTMLElement | undefined,\n codeDeletions: HTMLElement | undefined,\n codeAdditions: HTMLElement | undefined\n ):\n | [ColumnElements | undefined, ColumnElements | undefined]\n | ColumnElements\n | undefined {\n if (diffStyle === 'unified') {\n return this.getColumnPair(codeUnified);\n } else {\n const deletions = this.getColumnPair(codeDeletions);\n const additions = this.getColumnPair(codeAdditions);\n return deletions != null || additions != null\n ? [deletions, additions]\n : undefined;\n }\n }\n\n protected updateBuffers(renderRange: RenderRange): void {\n if (this.pre != null) {\n this.applyBuffers(this.pre, renderRange);\n }\n }\n\n private applyBuffers(\n pre: HTMLPreElement,\n renderRange: RenderRange | undefined\n ) {\n if (renderRange == null || this.shouldDisableVirtualizationBuffers()) {\n if (this.bufferBefore != null) {\n this.bufferBefore.remove();\n this.bufferBefore = undefined;\n }\n if (this.bufferAfter != null) {\n this.bufferAfter.remove();\n this.bufferAfter = undefined;\n }\n return;\n }\n // NOTE(amadeus): A very hacky pass at buffers outside the pre elements...\n // i may need to improve this...\n if (renderRange.bufferBefore > 0) {\n if (this.bufferBefore == null) {\n this.bufferBefore = document.createElement('div');\n this.bufferBefore.dataset.virtualizerBuffer = 'before';\n pre.before(this.bufferBefore);\n }\n this.bufferBefore.style.setProperty(\n 'height',\n `${renderRange.bufferBefore}px`\n );\n this.bufferBefore.style.setProperty('contain', 'strict');\n } else if (this.bufferBefore != null) {\n this.bufferBefore.remove();\n this.bufferBefore = undefined;\n }\n\n if (renderRange.bufferAfter > 0) {\n if (this.bufferAfter == null) {\n this.bufferAfter = document.createElement('div');\n this.bufferAfter.dataset.virtualizerBuffer = 'after';\n pre.after(this.bufferAfter);\n }\n this.bufferAfter.style.setProperty(\n 'height',\n `${renderRange.bufferAfter}px`\n );\n this.bufferAfter.style.setProperty('contain', 'strict');\n } else if (this.bufferAfter != null) {\n this.bufferAfter.remove();\n this.bufferAfter = undefined;\n }\n }\n\n protected shouldDisableVirtualizationBuffers(): boolean {\n return this.options.disableVirtualizationBuffers ?? false;\n }\n\n protected applyPreNodeAttributes(\n pre: HTMLPreElement,\n { additionsContentAST, deletionsContentAST, totalLines }: HunksRenderResult,\n customProperties?: CustomPreProperties\n ): void {\n const {\n diffIndicators = 'bars',\n disableBackground = false,\n disableLineNumbers = false,\n overflow = 'scroll',\n diffStyle = 'split',\n } = this.options;\n const preProperties: PrePropertiesConfig = {\n type: 'diff',\n diffIndicators,\n disableBackground,\n disableLineNumbers,\n overflow,\n split:\n diffStyle === 'unified'\n ? false\n : additionsContentAST != null && deletionsContentAST != null,\n totalLines,\n customProperties,\n };\n if (arePrePropertiesEqual(preProperties, this.appliedPreAttributes)) {\n return;\n }\n setPreNodeProperties(pre, preProperties);\n this.appliedPreAttributes = preProperties;\n }\n\n private applyErrorToDOM(error: Error, container: HTMLElement) {\n this.cleanupErrorWrapper();\n this.pre?.remove();\n this.pre = undefined;\n this.appliedPreAttributes = undefined;\n const shadowRoot =\n container.shadowRoot ?? container.attachShadow({ mode: 'open' });\n this.errorWrapper ??= document.createElement('div');\n this.errorWrapper.dataset.errorWrapper = '';\n this.errorWrapper.textContent = '';\n shadowRoot.appendChild(this.errorWrapper);\n const errorMessage = document.createElement('div');\n errorMessage.dataset.errorMessage = '';\n errorMessage.innerText = error.message;\n this.errorWrapper.appendChild(errorMessage);\n const errorStack = document.createElement('pre');\n errorStack.dataset.errorStack = '';\n errorStack.innerText = error.stack ?? 'No Error Stack';\n this.errorWrapper.appendChild(errorStack);\n }\n\n private cleanupErrorWrapper() {\n this.errorWrapper?.remove();\n this.errorWrapper = undefined;\n }\n}\n\ninterface HasContentProps {\n fileDiff: FileDiffMetadata | undefined;\n oldFile: FileContents | null | undefined;\n newFile: FileContents | null | undefined;\n}\n\nfunction getAdditionFile(fileDiff: FileDiffMetadata): FileContents {\n return {\n name: fileDiff.name,\n lang: fileDiff.lang,\n contents: fileDiff.additionLines.join(''),\n };\n}\n\nfunction areOptionalFilesEqual(\n fileA: FileContents | null | undefined,\n fileB: FileContents | null | undefined\n): boolean {\n if (fileA == null || fileB == null) {\n return fileA == null && fileB == null;\n }\n return areFilesEqual(fileA, fileB);\n}\n\nfunction hasDiffContent({\n fileDiff,\n oldFile,\n newFile,\n}: HasContentProps): boolean {\n return (\n (fileDiff != null && fileDiff.hunks.length > 0) ||\n oldFile != null ||\n newFile != null\n );\n}\n\nfunction hasDiffHeaderContent({\n fileDiff,\n oldFile,\n newFile,\n}: HasContentProps): boolean {\n return fileDiff != null || oldFile != null || newFile != null;\n}\n\nfunction shouldRenderCode(\n pre: HTMLPreElement | undefined,\n hasContent: boolean,\n collapsed = false\n): boolean {\n return !collapsed && pre == null && hasContent;\n}\n\nfunction shouldRenderHeader(\n headerElement: HTMLElement | undefined,\n hasContent: boolean,\n disableFileHeader = false\n): boolean {\n return headerElement == null && hasContent && !disableFileHeader;\n}\n\nfunction getElementChildren(\n node: ElementContent | undefined\n): ElementContent[] | undefined {\n if (node == null || node.type !== 'element') {\n return undefined;\n }\n return node.children ?? [];\n}\n", "import type {\n ChangeContent,\n FileDiffMetadata,\n Hunk,\n HunkExpansionRegion,\n HunkSeparators,\n VirtualFileMetrics,\n} from '../types';\nimport {\n getVirtualFileHeaderRegion,\n getVirtualFilePaddingBottom,\n} from './computeVirtualFileMetrics';\nimport {\n getExpandedRegion,\n getLeadingHunkSeparatorLayout,\n getTrailingExpandedRegion,\n getTrailingHunkSeparatorLayout,\n} from './virtualDiffLayout';\n\nexport interface ComputeEstimatedDiffHeightsOptions {\n fileDiff: FileDiffMetadata;\n metrics: VirtualFileMetrics;\n disableFileHeader: boolean;\n hunkSeparators: HunkSeparators;\n expandUnchanged: boolean;\n expandedHunks: Map<number, HunkExpansionRegion> | true | undefined;\n collapsedContextThreshold: number;\n canHydratePartialDiff: boolean;\n}\n\nexport interface EstimatedDiffHeights {\n splitHeight: number;\n unifiedHeight: number;\n}\n\n// Computes both split and unified baseline heights from hunk-level metadata so\n// callers can avoid replaying the detailed rendered-line iterator.\nexport function computeEstimatedDiffHeights({\n fileDiff,\n metrics,\n disableFileHeader,\n hunkSeparators,\n expandUnchanged,\n expandedHunks: configuredExpandedHunks,\n collapsedContextThreshold,\n canHydratePartialDiff,\n}: ComputeEstimatedDiffHeightsOptions): EstimatedDiffHeights {\n let splitHeight = getVirtualFileHeaderRegion(metrics, disableFileHeader);\n let unifiedHeight = splitHeight;\n const expandedHunks = expandUnchanged ? true : configuredExpandedHunks;\n const finalHunkIndex = fileDiff.hunks.length - 1;\n\n for (let hunkIndex = 0; hunkIndex < fileDiff.hunks.length; hunkIndex++) {\n const hunk = fileDiff.hunks[hunkIndex];\n if (hunk == null) {\n throw new Error('computeEstimatedDiffHeights: invalid hunk index');\n }\n\n const leadingRegion = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const leadingExpandedHeight =\n (leadingRegion.fromStart + leadingRegion.fromEnd) * metrics.lineHeight;\n splitHeight += leadingExpandedHeight;\n unifiedHeight += leadingExpandedHeight;\n\n if (leadingRegion.collapsedLines > 0) {\n const separatorHeight =\n getLeadingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics,\n hunkIndex,\n hunkSpecs: hunk.hunkSpecs,\n })?.totalHeight ?? 0;\n splitHeight += separatorHeight;\n unifiedHeight += separatorHeight;\n }\n\n splitHeight += hunk.splitLineCount * metrics.lineHeight;\n unifiedHeight += hunk.unifiedLineCount * metrics.lineHeight;\n\n const metadataLineCounts = getNoNewlineMetadataLineCounts(hunk);\n splitHeight += metadataLineCounts.split * metrics.lineHeight;\n unifiedHeight += metadataLineCounts.unified * metrics.lineHeight;\n\n const trailingRegion =\n hunkIndex === finalHunkIndex\n ? getTrailingExpandedRegion({\n fileDiff,\n hunkIndex,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'computeEstimatedDiffHeights',\n })\n : undefined;\n if (trailingRegion != null) {\n const trailingExpandedHeight =\n (trailingRegion.fromStart + trailingRegion.fromEnd) *\n metrics.lineHeight;\n splitHeight += trailingExpandedHeight;\n unifiedHeight += trailingExpandedHeight;\n\n if (trailingRegion.collapsedLines > 0) {\n const separatorHeight =\n getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics,\n })?.totalHeight ?? 0;\n splitHeight += separatorHeight;\n unifiedHeight += separatorHeight;\n }\n } else if (\n hunkIndex === finalHunkIndex &&\n fileDiff.isPartial &&\n canHydratePartialDiff\n ) {\n const separatorHeight =\n getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics,\n })?.totalHeight ?? 0;\n splitHeight += separatorHeight;\n unifiedHeight += separatorHeight;\n }\n }\n\n if (fileDiff.hunks.length > 0) {\n const paddingBottom = getVirtualFilePaddingBottom(metrics);\n splitHeight += paddingBottom;\n unifiedHeight += paddingBottom;\n }\n\n return { splitHeight, unifiedHeight };\n}\n\nfunction getNoNewlineMetadataLineCounts(hunk: Hunk): {\n split: number;\n unified: number;\n} {\n if (!hunk.noEOFCRAdditions && !hunk.noEOFCRDeletions) {\n return { split: 0, unified: 0 };\n }\n\n const lastContent = hunk.hunkContent.at(-1);\n if (lastContent == null) {\n return { split: 0, unified: 0 };\n }\n\n if (lastContent.type === 'context') {\n const metadataRows = lastContent.lines > 0 ? 1 : 0;\n return { split: metadataRows, unified: metadataRows };\n }\n\n return getChangeNoNewlineMetadataLineCounts(hunk, lastContent);\n}\nfunction getChangeNoNewlineMetadataLineCounts(\n hunk: Hunk,\n content: ChangeContent\n): { split: number; unified: number } {\n const unified =\n (content.deletions > 0 && hunk.noEOFCRDeletions ? 1 : 0) +\n (content.additions > 0 && hunk.noEOFCRAdditions ? 1 : 0);\n const splitDeletionHasMetadata =\n content.deletions > 0 && hunk.noEOFCRDeletions;\n const splitAdditionHasMetadata =\n content.additions > 0 && hunk.noEOFCRAdditions;\n const split = splitDeletionHasMetadata || splitAdditionHasMetadata ? 1 : 0;\n\n return { split, unified };\n}\n", "import { DEFAULT_COLLAPSED_CONTEXT_THRESHOLD } from '../constants';\nimport type { TextDocument } from '../editor/textDocument';\nimport type {\n BaseDiffOptions,\n DiffLineAnnotation,\n ExpansionDirections,\n FileContents,\n FileDiffMetadata,\n Hunk,\n HunkSeparators,\n NumericScrollLineAnchor,\n PendingCodeViewLayoutReset,\n RenderRange,\n RenderWindow,\n SelectionSide,\n StickySpecs,\n ThemeTypes,\n VirtualFileMetrics,\n} from '../types';\nimport { areDiffTargetsEqual } from '../utils/areDiffTargetsEqual';\nimport { areFilesEqual } from '../utils/areFilesEqual';\nimport { areObjectsEqual } from '../utils/areObjectsEqual';\nimport { areOptionsEqual } from '../utils/areOptionsEqual';\nimport { awaitWithTimeout } from '../utils/awaitWithTimeout';\nimport { computeEstimatedDiffHeights } from '../utils/computeEstimatedDiffHeights';\nimport {\n computeVirtualFileMetrics,\n getVirtualFileHeaderHeight,\n getVirtualFileHeaderRegion,\n getVirtualFilePaddingBottom,\n} from '../utils/computeVirtualFileMetrics';\nimport { getDiffFileInput } from '../utils/getDiffFileInput';\nimport { hydratePartialDiff } from '../utils/hydratePartialDiff';\nimport {\n FILE_ANNOTATION_DOM_KEY,\n FILE_ANNOTATION_LINE_NUMBER,\n includesFileAnnotations,\n shouldRenderFileAnnotations,\n} from '../utils/includesFileAnnotations';\nimport { iterateOverDiff } from '../utils/iterateOverDiff';\nimport { parseDiffFromFile } from '../utils/parseDiffFromFile';\nimport {\n getExpandedRegion,\n getLeadingHunkSeparatorLayout,\n getTrailingExpandedRegion,\n getTrailingHunkSeparatorLayout,\n isAdditionLineRenderable,\n} from '../utils/virtualDiffLayout';\nimport type { WorkerPoolManager } from '../worker';\nimport type { CodeView } from './CodeView';\nimport {\n FileDiff,\n type FileDiffOptions,\n type FileDiffRenderProps,\n} from './FileDiff';\nimport type { Virtualizer } from './Virtualizer';\n\ntype LoadedPartialDiffContents = Awaited<\n ReturnType<NonNullable<BaseDiffOptions['loadDiffFiles']>>\n>;\n\ninterface DiffLayoutCheckpoint {\n renderedLineIndex: number;\n lineIndex: number;\n top: number;\n}\n\ninterface DiffLayoutCache {\n // Sparse map: view-specific line index -> measured height delta from the\n // baseline line height. Only stores lines that differ from the estimate.\n heightDeltas: Map<number, number>;\n // Aggregate delta from estimated height, including source row deltas and the\n // zero-baseline file annotation row height.\n measuredHeightDeltaTotal: number;\n // Baseline estimated heights for the active diff content. These are preserved\n // across style/collapse toggles and cleared only when estimate inputs change.\n estimatedSplitHeight: number | undefined;\n estimatedUnifiedHeight: number | undefined;\n // Sparse measured positions used to resume deep geometry scans near a target\n // diff line, rendered row, or scroll offset instead of replaying layout from\n // the first hunk.\n checkpoints: DiffLayoutCheckpoint[];\n // Total renderable diff rows for the current diff style and expansion state.\n totalLines: number;\n // Measured height for the file annotation row. Starts at 0 so\n // unmeasured annotations behave like all other unmeasured annotations.\n fileAnnotationHeight: number;\n // Ghost text rows folded into `heightDeltas`. `ghostTextRows` is the editor's\n // own map (zero-based new-file line -> rows), replaced rather than mutated, so\n // identity alone says whether anything changed. `ghostTextRowsByIndex` is the\n // same data keyed by this view's row index, which the deltas use.\n ghostTextRows: ReadonlyMap<number, number>;\n ghostTextRowsByIndex: Map<number, number>;\n}\n\ninterface ResetLayoutCacheOptions {\n forceSimpleRecompute?: boolean;\n includeEstimatedHeights?: boolean;\n resetRenderRange?: boolean;\n}\n\ninterface PendingLoadedDiff {\n expectedDiff: FileDiffMetadata;\n nextDiff: FileDiffMetadata;\n files: LoadedPartialDiffContents;\n}\n\ninterface PendingExpansion {\n hunkIndex: number;\n direction: ExpansionDirections;\n expansionLineCountOverride: number | undefined;\n}\n\ninterface PendingRender {\n // Diff requested for the next render, including editor changes.\n workingDiff: FileDiffMetadata;\n // Diff selected by the renderer. Highlighting can keep this on the old diff.\n diff: FileDiffMetadata;\n}\n\nexport const VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL = 3_000;\nconst NO_GHOST_TEXT_ROWS: ReadonlyMap<number, number> = new Map();\n\nlet instanceId = -1;\n\nexport class VirtualizedFileDiff<\n LAnnotation = undefined,\n Caret = undefined,\n> extends FileDiff<LAnnotation, Caret> {\n override readonly __id: string = `little-virtualized-file-diff:${++instanceId}`;\n public readonly renderType = 'virtualized';\n\n public top: number | undefined;\n public height: number = 0;\n private metrics: VirtualFileMetrics;\n private cache: DiffLayoutCache = {\n heightDeltas: new Map(),\n measuredHeightDeltaTotal: 0,\n estimatedSplitHeight: undefined,\n estimatedUnifiedHeight: undefined,\n checkpoints: [],\n totalLines: 0,\n fileAnnotationHeight: 0,\n ghostTextRows: NO_GHOST_TEXT_ROWS,\n ghostTextRowsByIndex: new Map(),\n };\n private isVisible: boolean = false;\n private isSetup: boolean = false;\n private virtualizer: Virtualizer | CodeView<LAnnotation, Caret>;\n private layoutDirty = true;\n private currentCollapsed: boolean | undefined;\n private pendingHydratedDiff: PendingLoadedDiff | undefined;\n private pendingExpansions: PendingExpansion[] | undefined;\n // Remember which diff the layout was calculated from, even when only a\n // placeholder is rendered. Async highlighting clears this through rerender()\n // so layout can use the newly available content. CodeView updates it during\n // its layout pass.\n private pendingRender: PendingRender | undefined;\n\n constructor(\n options: FileDiffOptions<LAnnotation, Caret> | undefined,\n virtualizer: Virtualizer | CodeView<LAnnotation, Caret>,\n metrics?: Partial<VirtualFileMetrics>,\n workerManager?: WorkerPoolManager,\n requestOwnerRender?: () => void\n ) {\n super(options, workerManager, requestOwnerRender);\n this.virtualizer = virtualizer;\n this.metrics = computeVirtualFileMetrics(metrics);\n }\n\n public setMetrics(\n metrics?: Partial<VirtualFileMetrics>,\n force = false\n ): void {\n const nextMetrics = computeVirtualFileMetrics(metrics);\n if (!force && areObjectsEqual(this.metrics, nextMetrics)) {\n return;\n }\n\n this.metrics = nextMetrics;\n this.resetLayoutCache({ includeEstimatedHeights: true });\n }\n\n override setLineAnnotations(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): void {\n if (this.syncLineAnnotations(lineAnnotations)) {\n this.forceRenderOverride = true;\n }\n }\n\n // Keep measured row heights as estimates when annotations change; rendering\n // will replace them with the updated heights without discarding other rows.\n private syncLineAnnotations(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined\n ): boolean {\n if (\n lineAnnotations == null ||\n !this.isNewAnnotations(lineAnnotations) ||\n (lineAnnotations.length === 0 && this.getLatestAnnotations().length === 0)\n ) {\n return false;\n }\n super.setLineAnnotations(lineAnnotations);\n return true;\n }\n\n protected override syncEditSessionAnnotationsFromEditor(\n lineAnnotations: DiffLineAnnotation<LAnnotation>[]\n ): boolean {\n if (super.syncEditSessionAnnotationsFromEditor(lineAnnotations)) {\n this.forceRenderOverride = true;\n return true;\n }\n return false;\n }\n\n private setFileAnnotationHeight(nextHeight: number): boolean {\n const previousHeight = this.cache.fileAnnotationHeight;\n if (nextHeight === previousHeight) {\n return false;\n }\n\n this.cache.fileAnnotationHeight = nextHeight;\n this.cache.measuredHeightDeltaTotal += nextHeight - previousHeight;\n return true;\n }\n\n private hasFileAnnotations(fileDiff: FileDiffMetadata): boolean {\n const lineAnnotations = this.getLayoutAnnotations();\n if (!includesFileAnnotations(lineAnnotations)) {\n return false;\n }\n return lineAnnotations.some((annotation) => {\n if (annotation.lineNumber !== FILE_ANNOTATION_LINE_NUMBER) {\n return false;\n }\n // Lets ensure for singled sided diffs that the sides match\n if (fileDiff.type === 'new') {\n return annotation.side === 'additions';\n }\n if (fileDiff.type === 'deleted') {\n return annotation.side === 'deletions';\n }\n return true;\n });\n }\n\n // Get the height for a line, using cached value if available.\n // If not cached and hasMetadataLine is true, adds lineHeight for the metadata.\n private getLineHeight(lineIndex: number, hasMetadataLine = false): number {\n return (\n this.getEstimatedLineHeight(hasMetadataLine) +\n (this.cache.heightDeltas.get(lineIndex) ?? 0)\n );\n }\n\n private getEstimatedLineHeight(hasMetadataLine = false): number {\n const multiplier = hasMetadataLine ? 2 : 1;\n return this.metrics.lineHeight * multiplier;\n }\n\n override setOptions(\n options: FileDiffOptions<LAnnotation, Caret> | undefined\n ): void {\n if (this.isAdvancedMode()) {\n throw new Error(\n 'VirtualizedFileDiff.setOptions cannot be used inside CodeView. Update CodeView options instead.'\n );\n }\n\n if (options == null) return;\n const { options: previousOptions } = this;\n const optionsChanged = !areOptionsEqual(previousOptions, options);\n const layoutChanged =\n optionsChanged && hasDiffLayoutOptionChanged(previousOptions, options);\n\n super.setOptions(options);\n\n if (layoutChanged) {\n this.resetLayoutCache({\n forceSimpleRecompute: true,\n includeEstimatedHeights: hasDiffEstimateOptionChanged(\n previousOptions,\n options\n ),\n });\n }\n // Any option can affect rendered DOM; only layout-affecting options clear\n // the measured height cache above.\n if (optionsChanged) {\n this.forceRenderOverride = true;\n }\n if (optionsChanged && this.isSimpleMode()) {\n this.virtualizer.instanceChanged(this, layoutChanged);\n }\n }\n\n override setThemeType(themeType: ThemeTypes): void {\n if (this.isAdvancedMode()) {\n throw new Error(\n 'VirtualizedFileDiff.setThemeType cannot be used inside CodeView. Update CodeView options instead.'\n );\n }\n\n super.setThemeType(themeType);\n }\n\n private resetLayoutCache({\n forceSimpleRecompute = false,\n includeEstimatedHeights = false,\n resetRenderRange = true,\n }: ResetLayoutCacheOptions = {}): void {\n this.layoutDirty = true;\n this.cache.fileAnnotationHeight = 0;\n this.cache.heightDeltas.clear();\n this.cache.measuredHeightDeltaTotal = 0;\n this.cache.ghostTextRows = NO_GHOST_TEXT_ROWS;\n if (this.cache.ghostTextRowsByIndex.size > 0) {\n this.cache.ghostTextRowsByIndex.clear();\n }\n this.invalidateDerivedLayoutCache(\n includeEstimatedHeights,\n resetRenderRange\n );\n // NOTE(amadeus): In CodeView we intentionally batch computes to all happen\n // at the same time, so we shouldn't trigger this there.\n if (forceSimpleRecompute && this.isSimpleMode()) {\n this.computeApproximateSize();\n }\n }\n\n private invalidateDerivedLayoutCache(\n includeEstimatedHeights: boolean,\n resetRenderRange = true\n ): void {\n this.layoutDirty = true;\n if (this.cache.checkpoints.length > 0) {\n this.cache.checkpoints.length = 0;\n }\n if (this.cache.totalLines !== 0) {\n this.cache.totalLines = 0;\n }\n if (includeEstimatedHeights) {\n this.cache.estimatedSplitHeight = undefined;\n this.cache.estimatedUnifiedHeight = undefined;\n }\n if (this.renderRange != null && resetRenderRange) {\n this.renderRange = undefined;\n }\n }\n\n // Fold the ghost text rows the editor is showing below lines into the height\n // deltas. Ghost text sits in a margin below the row, which measuring never\n // includes, so the rows are added here on top of the row's own height, and\n // removed again when the ghost text changes or goes away, even for rows that\n // are not rendered right now. The editor keys by new-file line; the deltas\n // are keyed by this view's row index, so lines are translated the same way\n // getLinePosition does. The editor only reports lines that have a rendered\n // row (it draws a prediction all or nothing); the translation is undefined\n // only for a diff without hunks.\n private applyGhostTextRows(\n fileDiff: FileDiffMetadata,\n ghostTextRows: ReadonlyMap<number, number>\n ): boolean {\n const {\n cache: {\n heightDeltas,\n ghostTextRows: folded,\n ghostTextRowsByIndex: previous,\n },\n metrics: { lineHeight },\n } = this;\n if (folded === ghostTextRows) {\n return false;\n }\n const diffStyle = this.getDiffStyle();\n const next = new Map<number, number>();\n for (const [line, rows] of ghostTextRows) {\n const indexes = this.getLineIndexForDiff(fileDiff, line + 1, 'additions');\n if (indexes == null) {\n continue;\n }\n next.set(diffStyle === 'split' ? indexes[1] : indexes[0], rows);\n }\n let changed = false;\n for (const rowIndex of new Set([...previous.keys(), ...next.keys()])) {\n const delta =\n ((next.get(rowIndex) ?? 0) - (previous.get(rowIndex) ?? 0)) *\n lineHeight;\n if (delta === 0) {\n continue;\n }\n const nextDelta = (heightDeltas.get(rowIndex) ?? 0) + delta;\n if (nextDelta === 0) {\n heightDeltas.delete(rowIndex);\n } else {\n heightDeltas.set(rowIndex, nextDelta);\n }\n this.cache.measuredHeightDeltaTotal += delta;\n changed = true;\n }\n this.cache.ghostTextRows = ghostTextRows;\n this.cache.ghostTextRowsByIndex = next;\n return changed;\n }\n\n // Measure rendered lines and update height cache.\n // Called after render to reconcile estimated vs actual heights.\n // Definitely need to optimize this in cases where there aren't any custom\n // line heights or in cases of extremely large files...\n public reconcileHeights(): boolean {\n let hasHeightChange = false;\n const {\n options: { overflow = 'scroll' },\n metrics: { lineHeight },\n } = this;\n // A placeholder may have a prepared layout before any content has\n // rendered.\n const fileDiff =\n this.placeHolder != null ? this.getLayoutDiff() : this.getRenderedDiff();\n if (this.fileContainer == null || fileDiff == null) {\n if (this.height !== 0) {\n hasHeightChange = true;\n }\n this.height = 0;\n return hasHeightChange;\n }\n this.top = this.getVirtualizedTop();\n hasHeightChange = this.applyGhostTextRows(\n fileDiff,\n this.editor?.__getGhostTextRows() ?? NO_GHOST_TEXT_ROWS\n );\n // Folding replaces the row-index map; measure against the newly folded\n // counts so reconciliation does not overwrite their height contribution.\n const { ghostTextRowsByIndex } = this.cache;\n const measureAllRows =\n overflow !== 'scroll' ||\n this.lineAnnotations.length > 0 ||\n this.isResizeDebuggingEnabled();\n // Ghost-row changes affect placeholders too, but placeholders have no DOM\n // rows to measure. After the last annotation is removed, keep measuring\n // rendered rows until their previously cached heights have been corrected.\n if (\n this.placeHolder != null ||\n (!measureAllRows &&\n this.cache.heightDeltas.size === 0 &&\n this.cache.fileAnnotationHeight === 0)\n ) {\n if (hasHeightChange) {\n this.computeApproximateSize(true);\n this.setPlaceholderHeight(this.height);\n }\n return hasHeightChange;\n }\n const diffStyle = this.getDiffStyle();\n const codeGroups =\n diffStyle === 'split'\n ? [this.codeDeletions, this.codeAdditions]\n : [this.codeUnified];\n\n // Keep offscreen file annotation measurements consistent with the buffers\n // computed for this render. A rendered top row can confirm their removal.\n if (\n this.renderRange != null &&\n shouldRenderFileAnnotations(this.renderRange)\n ) {\n const fileAnnotationHeight = measureFileAnnotationHeight(codeGroups);\n const nextFileAnnotationHeight = fileAnnotationHeight ?? 0;\n if (this.setFileAnnotationHeight(nextFileAnnotationHeight)) {\n hasHeightChange = true;\n }\n }\n\n for (const codeGroup of codeGroups) {\n if (codeGroup == null) continue;\n const content = codeGroup.children[1];\n if (!(content instanceof HTMLElement)) continue;\n // The ghost prediction margin sits on the additions row. When the two\n // split columns share one grid, the deletions row stretches to that\n // taller track, so measuring it would count the rows twice; the\n // additions row is authoritative for a row pair with ghost text.\n const skipsGhostRows =\n diffStyle === 'split' && codeGroup === this.codeDeletions;\n for (const line of content.children) {\n if (!(line instanceof HTMLElement)) continue;\n\n const lineIndexAttr = line.dataset.lineIndex;\n if (lineIndexAttr == null) continue;\n\n const lineIndex = parseLineIndex(lineIndexAttr, diffStyle);\n const ghostRows = ghostTextRowsByIndex.get(lineIndex) ?? 0;\n if (skipsGhostRows && ghostRows > 0) continue;\n const previousDelta = this.cache.heightDeltas.get(lineIndex) ?? 0;\n // With no annotations or wrapping, only stale custom measurements need\n // DOM reads. Ghost rows already have known heights from the editor.\n if (!measureAllRows && previousDelta === ghostRows * lineHeight) {\n continue;\n }\n let measuredHeight =\n line.getBoundingClientRect().height + ghostRows * lineHeight;\n let hasMetadata = false;\n // Annotations or noNewline metadata increase the size of the their\n // attached line\n if (\n line.nextElementSibling instanceof HTMLElement &&\n ('lineAnnotation' in line.nextElementSibling.dataset ||\n 'noNewline' in line.nextElementSibling.dataset)\n ) {\n if ('noNewline' in line.nextElementSibling.dataset) {\n hasMetadata = true;\n }\n measuredHeight +=\n line.nextElementSibling.getBoundingClientRect().height;\n }\n const estimatedHeight = this.getEstimatedLineHeight(hasMetadata);\n const nextDelta = measuredHeight - estimatedHeight;\n\n if (nextDelta === previousDelta) {\n continue;\n }\n\n hasHeightChange = true;\n this.cache.measuredHeightDeltaTotal += nextDelta - previousDelta;\n if (nextDelta === 0) {\n this.cache.heightDeltas.delete(lineIndex);\n } else {\n this.cache.heightDeltas.set(lineIndex, nextDelta);\n }\n }\n }\n\n if (hasHeightChange || this.isResizeDebuggingEnabled()) {\n this.computeApproximateSize(true);\n }\n return hasHeightChange;\n }\n\n public onRender = (dirty: boolean): boolean => {\n if (this.fileContainer == null) {\n return false;\n }\n if (dirty) {\n this.top = this.getVirtualizedTop();\n }\n return this.render();\n };\n\n // Virtualized renders bypass FileDiff's queued render handler. Apply line\n // state deferred during the refresh once managers target the rebuilt rows.\n public override flushManagers(): void {\n super.flushManagers();\n if (this.lineStateRefreshPending) {\n this.flushDeferredLineState();\n }\n }\n\n // CodeView positions every item before updating the DOM. Recalculate this\n // item's layout whenever its content or position changes.\n public updateCodeViewLayout(\n fileDiff: FileDiffMetadata,\n top: number,\n reset?: PendingCodeViewLayoutReset,\n lineAnnotations?: DiffLineAnnotation<LAnnotation>[]\n ): number {\n let resetLayoutCache = false;\n let resetEstimatedHeights = false;\n const {\n pendingExpansions,\n pendingHydratedDiff,\n options: { collapsed = false },\n } = this;\n\n // Hydrate the `isPartial: true` diff if we have a pending hydration\n if (pendingHydratedDiff != null) {\n this.pendingHydratedDiff = undefined;\n if (pendingHydratedDiff.expectedDiff === fileDiff) {\n // We intentionally keep diff equality referential,\n // and treat it as a mutation\n Object.assign(fileDiff, pendingHydratedDiff.nextDiff);\n this.setHydratedState(pendingHydratedDiff.files);\n this.installHydratedSessionDiff(fileDiff);\n this.forceRenderOverride = true;\n resetLayoutCache = true;\n resetEstimatedHeights = true;\n }\n }\n\n // Go ahead and apply any queued expansion changes\n if (pendingExpansions != null) {\n this.pendingExpansions = undefined;\n for (const {\n hunkIndex,\n direction,\n expansionLineCountOverride,\n } of pendingExpansions) {\n this.hunksRenderer.expandHunk(\n hunkIndex,\n direction,\n expansionLineCountOverride\n );\n this.forceRenderOverride = true;\n resetEstimatedHeights = true;\n }\n }\n\n const diffChanged = this.updateInputDiff(fileDiff, lineAnnotations);\n const {\n pendingRenderDiff,\n layoutDiffChanged,\n renderedDiffChanged,\n annotationsChanged,\n } = this.updatePendingRender(fileDiff, lineAnnotations);\n if (\n !this.forceRenderOverride &&\n (diffChanged || renderedDiffChanged || annotationsChanged)\n ) {\n this.forceRenderOverride = true;\n }\n\n if (reset?.resetDiffLayoutCache === true || layoutDiffChanged) {\n resetLayoutCache = true;\n }\n if (\n layoutDiffChanged ||\n (reset?.resetDiffLayoutCache === true &&\n reset.includeEstimatedDiffHeights)\n ) {\n resetEstimatedHeights = true;\n }\n if (reset?.metrics != null) {\n this.metrics = computeVirtualFileMetrics(reset.metrics);\n resetLayoutCache = true;\n resetEstimatedHeights = true;\n }\n if (this.currentCollapsed !== collapsed) {\n this.currentCollapsed = collapsed;\n resetLayoutCache = true;\n }\n if (resetLayoutCache) {\n this.resetLayoutCache({ includeEstimatedHeights: resetEstimatedHeights });\n } else if (resetEstimatedHeights) {\n this.invalidateDerivedLayoutCache(true);\n }\n\n this.top = top;\n this.computeApproximateSize(false, pendingRenderDiff);\n return this.height;\n }\n\n public getLinePosition(\n lineNumber: number,\n side: SelectionSide = 'additions'\n ): { top: number; height: number } | undefined {\n const fileDiff = this.getLayoutDiff();\n if (fileDiff == null || lineNumber < 1) {\n return undefined;\n }\n\n const targetLineIndexes = this.getLineIndexForDiff(\n fileDiff,\n lineNumber,\n side\n );\n if (targetLineIndexes == null) {\n return undefined;\n }\n\n const {\n disableFileHeader = false,\n expandUnchanged = false,\n collapsed = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const diffStyle = this.getDiffStyle();\n const hunkSeparators = this.getHunkSeparatorType();\n const targetLineIndex =\n diffStyle === 'split' ? targetLineIndexes[1] : targetLineIndexes[0];\n this.approximateLayoutCheckpoints(fileDiff);\n const headerRegion = getVirtualFileHeaderRegion(\n this.metrics,\n disableFileHeader\n );\n const checkpoint = this.getLayoutCheckpointBeforeLineIndex(targetLineIndex);\n let top = checkpoint?.top ?? headerRegion + this.cache.fileAnnotationHeight;\n\n if (collapsed) {\n return {\n top: getVirtualFileHeaderHeight(this.metrics, disableFileHeader),\n height: 0,\n };\n }\n\n let position: { top: number; height: number } | undefined;\n iterateOverDiff({\n diff: fileDiff,\n diffStyle,\n startingLine: checkpoint?.renderedLineIndex ?? 0,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n callback: ({\n hunkIndex,\n hunk,\n collapsedBefore,\n collapsedAfter,\n deletionLine,\n additionLine,\n }) => {\n const lineIndex =\n diffStyle === 'split'\n ? (additionLine?.splitLineIndex ?? deletionLine?.splitLineIndex)\n : (additionLine?.unifiedLineIndex ??\n deletionLine?.unifiedLineIndex);\n if (lineIndex == null) {\n throw new Error(\n 'VirtualizedFileDiff.getLinePosition: missing line index data'\n );\n }\n\n if (collapsedBefore > 0) {\n const separator = getLeadingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n hunkIndex,\n hunkSpecs: hunk?.hunkSpecs,\n });\n if (separator != null) {\n top += separator.gapBefore;\n if (\n targetLineIndex >= lineIndex - collapsedBefore &&\n targetLineIndex < lineIndex\n ) {\n position = {\n top,\n height: separator.height,\n };\n return true;\n }\n top += separator.height + separator.gapAfter;\n }\n }\n\n const lineHeight = this.getLineHeight(\n lineIndex,\n (additionLine?.noEOFCR ?? false) || (deletionLine?.noEOFCR ?? false)\n );\n if (lineIndex === targetLineIndex) {\n position = {\n top,\n height: lineHeight,\n };\n return true;\n }\n top += lineHeight;\n\n if (collapsedAfter > 0) {\n const separator = getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n });\n if (separator != null) {\n if (\n targetLineIndex > lineIndex &&\n targetLineIndex <= lineIndex + collapsedAfter\n ) {\n position = {\n top: top + separator.gapBefore,\n height: separator.height,\n };\n return true;\n }\n top += separator.totalHeight;\n }\n }\n\n return false;\n },\n });\n\n return position;\n }\n\n public getEditorViewport(): HTMLElement | Document | undefined {\n return this.virtualizer.type === 'simple'\n ? this.virtualizer.getRoot()\n : this.virtualizer.getContainerElement();\n }\n\n public getNumericScrollAnchor(\n localViewportTop: number\n ): NumericScrollLineAnchor | undefined {\n const fileDiff = this.getLayoutDiff();\n if (fileDiff == null) {\n return undefined;\n }\n\n const {\n disableFileHeader = false,\n expandUnchanged = false,\n collapsed = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n if (collapsed) {\n return undefined;\n }\n\n const diffStyle = this.getDiffStyle();\n const hunkSeparators = this.getHunkSeparatorType();\n\n this.approximateLayoutCheckpoints(fileDiff);\n const checkpoint = this.getLayoutCheckpointBeforeTop(localViewportTop);\n let top =\n checkpoint?.top ??\n getVirtualFileHeaderRegion(this.metrics, disableFileHeader) +\n this.cache.fileAnnotationHeight;\n let anchor: NumericScrollLineAnchor | undefined;\n\n // This may end up being quite expensive on extremely large files, we may\n // need to figure out how to anchor on different regions, or utilize\n // renderRange to shortcut this for us somehow\n iterateOverDiff({\n diff: fileDiff,\n diffStyle,\n startingLine: checkpoint?.renderedLineIndex ?? 0,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n callback: ({\n hunkIndex,\n hunk,\n collapsedBefore,\n collapsedAfter,\n deletionLine,\n additionLine,\n }) => {\n const lineIndex =\n diffStyle === 'split'\n ? (additionLine?.splitLineIndex ?? deletionLine?.splitLineIndex)\n : (additionLine?.unifiedLineIndex ??\n deletionLine?.unifiedLineIndex);\n if (lineIndex == null) {\n throw new Error(\n 'VirtualizedFileDiff.getNumericScrollAnchor: missing line index data'\n );\n }\n\n if (collapsedBefore > 0) {\n const separator = getLeadingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n hunkIndex,\n hunkSpecs: hunk?.hunkSpecs,\n });\n if (separator != null) {\n top += separator.totalHeight;\n }\n }\n\n if (top >= localViewportTop) {\n if (deletionLine != null) {\n anchor = {\n lineNumber: deletionLine.lineNumber,\n side: 'deletions',\n top,\n };\n } else if (additionLine != null) {\n anchor = {\n lineNumber: additionLine.lineNumber,\n side: 'additions',\n top,\n };\n }\n if (anchor != null) {\n return true;\n }\n }\n\n const lineHeight = this.getLineHeight(\n lineIndex,\n (additionLine?.noEOFCR ?? false) || (deletionLine?.noEOFCR ?? false)\n );\n top += lineHeight;\n\n if (collapsedAfter > 0) {\n const separator = getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n });\n if (separator != null) {\n top += separator.totalHeight;\n }\n }\n\n return false;\n },\n });\n\n return anchor;\n }\n\n public getVirtualizedHeight(): number {\n return this.height;\n }\n\n public getAdvancedStickySpecs(\n windowSpecs?: RenderWindow\n ): StickySpecs | undefined {\n const fileDiff = this.getLayoutDiff();\n if (this.top == null || fileDiff == null) {\n return undefined;\n }\n if (this.options.collapsed === true) {\n return { topOffset: this.top, height: this.height };\n }\n const renderRange =\n windowSpecs != null\n ? this.computeRenderRangeFromWindow(fileDiff, this.top, windowSpecs)\n : this.renderRange;\n if (renderRange == null) {\n return undefined;\n }\n const { bufferBefore, bufferAfter, totalLines } = renderRange;\n // Rendered items flow contiguously in the sticky container with no buffer\n // spacers, so a header-only item (totalLines === 0, none of its rows fall\n // inside the window) must report where its header actually sits in that\n // flow, which depends on which side of the window its content is on:\n // - content ABOVE the window (item starts above window.top): the header\n // sits at the item's bottom so the following item connects, so offset by\n // bufferAfter.\n // - content BELOW the window (item starts at/after window.top, e.g. a\n // trailing header peeking in at the bottom): the header renders at the\n // item's top with nothing after it, so no offset. Always adding\n // bufferAfter here made getStickyBounds over-measure the sticky\n // container for that trailing case.\n let headerOnlyOffset = 0;\n if (totalLines === 0) {\n const activeWindow = windowSpecs ?? this.virtualizer.getWindowSpecs();\n if (this.top < activeWindow.top) {\n headerOnlyOffset = bufferAfter;\n }\n }\n return {\n topOffset: this.top + bufferBefore + headerOnlyOffset,\n height: this.height - (bufferBefore + bufferAfter),\n };\n }\n\n override cleanUp(recycle = false): void {\n const hadGhostTextRows = this.cache.ghostTextRows.size > 0;\n if (hadGhostTextRows) {\n this.layoutDirty = true;\n }\n const shouldRecomputeLayout =\n recycle &&\n this.isAdvancedMode() &&\n this.fileContainer != null &&\n (hadGhostTextRows ||\n !areDiffTargetsEqual(this.getRenderedDiff(), this.getWorkingDiff()));\n if (this.fileContainer != null && this.isSimpleMode()) {\n this.getSimpleVirtualizer()?.disconnect(this.fileContainer);\n }\n if (!recycle) {\n this.resetLayoutCache({ includeEstimatedHeights: true });\n this.pendingExpansions = undefined;\n this.pendingHydratedDiff = undefined;\n }\n this.pendingRender = undefined;\n this.isSetup = false;\n super.cleanUp(recycle);\n if (shouldRecomputeLayout) {\n this.virtualizer.instanceChanged(this, true);\n }\n }\n\n override expandHunk = (\n hunkIndex: number,\n direction: ExpansionDirections,\n expansionLineCountOverride?: number\n ): void => {\n if (this.getInputDiff() == null) {\n return;\n }\n this.loadFilesIfNecessary();\n if (this.isAdvancedMode()) {\n this.pendingExpansions ??= [];\n this.pendingExpansions.push({\n hunkIndex,\n direction,\n expansionLineCountOverride,\n });\n } else {\n this.hunksRenderer.expandHunk(\n hunkIndex,\n direction,\n expansionLineCountOverride\n );\n this.resetLayoutCache({ includeEstimatedHeights: true });\n this.computeApproximateSize();\n }\n this.forceRenderOverride = true;\n this.virtualizer.instanceChanged(this, true);\n };\n\n protected override async handleFilesLoaded(\n expectedDiff: FileDiffMetadata,\n files: LoadedPartialDiffContents\n ): Promise<void> {\n if (this.getInputDiff() !== expectedDiff || !expectedDiff.isPartial) {\n return;\n }\n // CodeView component requires careful control for anchor\n // fixing on re-renders, and thus we cannot apply the\n // next diff immediately. Instead we clone and stage it for\n // CodeView layout to consume at render time.\n if (this.isAdvancedMode()) {\n const nextDiff = hydratePartialDiff('clone', expectedDiff, files);\n await awaitWithTimeout(() => this.primeHighlightCache(nextDiff));\n if (this.getInputDiff() !== expectedDiff) {\n return;\n }\n this.pendingHydratedDiff = {\n expectedDiff,\n nextDiff,\n files,\n };\n } else {\n hydratePartialDiff('merge', expectedDiff, files);\n this.setHydratedState(files);\n if (!this.installHydratedSessionDiff(expectedDiff)) {\n await awaitWithTimeout(() => this.primeHighlightCache(expectedDiff));\n if (this.getInputDiff() !== expectedDiff) {\n return;\n }\n }\n this.resetLayoutCache({ includeEstimatedHeights: true });\n this.computeApproximateSize();\n }\n this.forceRenderOverride = true;\n this.virtualizer.instanceChanged(this, true);\n }\n\n protected override loadFilesIfNecessary(): void {\n if (this.pendingHydratedDiff != null) {\n if (this.pendingHydratedDiff.expectedDiff === this.getInputDiff()) {\n return;\n }\n this.pendingHydratedDiff = undefined;\n }\n\n super.loadFilesIfNecessary();\n }\n\n // In advanced (CodeView) mode, expansions are staged in pendingExpansions\n // until the next layout consume, so the renderer's expansion map lags a\n // just-requested reveal. Account for the staged expansions so callers (the\n // editor's caret-scroll retry) see the post-consume visibility.\n override isLineRenderable(lineNumber: number): boolean {\n if (super.isLineRenderable(lineNumber)) {\n return true;\n }\n const { pendingExpansions } = this;\n const fileDiff = this.getRenderedDiff();\n if (\n pendingExpansions == null ||\n pendingExpansions.length === 0 ||\n fileDiff == null\n ) {\n return false;\n }\n const {\n expansionLineCount = 100,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const staged = new Map(this.hunksRenderer.getExpandedHunksMap());\n for (const expansion of pendingExpansions) {\n const region = {\n ...(staged.get(expansion.hunkIndex) ?? { fromStart: 0, fromEnd: 0 }),\n };\n const count = expansion.expansionLineCountOverride ?? expansionLineCount;\n if (expansion.direction === 'up' || expansion.direction === 'both') {\n region.fromStart += count;\n }\n if (expansion.direction === 'down' || expansion.direction === 'both') {\n region.fromEnd += count;\n }\n staged.set(expansion.hunkIndex, region);\n }\n return isAdditionLineRenderable({\n fileDiff,\n lineNumber,\n expandedHunks: staged,\n collapsedContextThreshold,\n });\n }\n\n /**\n * Invalidate layout after an edit session changed the rendered row set\n * without a line-count change (a mid-session region change or the exit\n * recompute): estimated heights bake the hunk shapes in, and nothing else\n * invalidates them now that editing does not flip expandUnchanged. Public\n * so CodeView can run it when reaping a session whose instance was already\n * released.\n */\n public invalidateEditSessionLayout(): void {\n this.getSimpleVirtualizer()?.markDOMDirty();\n this.resetLayoutCache({\n forceSimpleRecompute: this.isSimpleMode(),\n includeEstimatedHeights: true,\n resetRenderRange: false,\n });\n if (!this.isSimpleMode()) {\n this.computeApproximateSize(true);\n }\n this.getSimpleVirtualizer()?.requestHeightReconcile(this);\n }\n\n // Session region changes need the same invalidation a document change\n // gets. The virtualizer is told the layout changed (rendered rows and\n // heights moved) and defers the actual render through its own queue; a\n // released instance stops at the cache invalidation and the host relayout\n // covers it.\n protected override escalateEditSessionRender(): void {\n this.invalidateEditSessionLayout();\n if (!this.enabled || this.getInputDiff() == null) {\n return;\n }\n this.forceRenderOverride = true;\n this.virtualizer.instanceChanged(this, true);\n }\n\n protected override shouldSelfHealEditSession(): boolean {\n // CodeView sessions retain their editor association while rendering is\n // suspended; CodeView itself runs the exit recompute when it reaps one.\n return !this.isAdvancedMode() && super.shouldSelfHealEditSession();\n }\n\n public setVisibility(visible: boolean): void {\n if (this.isAdvancedMode() || this.fileContainer == null) {\n return;\n }\n this.renderRange = undefined;\n if (visible && !this.isVisible) {\n this.top = this.getVirtualizedTop();\n this.isVisible = true;\n } else if (!visible && this.isVisible) {\n this.isVisible = false;\n this.rerender();\n }\n }\n\n override rerender(): void {\n if (\n !this.enabled ||\n (this.getInputDiff() == null &&\n this.additionFile == null &&\n this.deletionFile == null)\n ) {\n return;\n }\n const workingDiff = this.getWorkingDiff();\n const nextRenderDiff =\n workingDiff == null\n ? undefined\n : this.hunksRenderer.getDiffForNextRender(workingDiff);\n // A completed async highlight can change which diff the next simple\n // virtualizer render will commit. CodeView refreshes this during layout.\n if (this.isSimpleMode()) {\n this.pendingRender = undefined;\n }\n this.forceRenderOverride = true;\n if (this.isSimpleMode() && this.requestRender()) return;\n this.virtualizer.instanceChanged(\n this,\n !areDiffTargetsEqual(this.getRenderedDiff(), nextRenderDiff)\n );\n }\n\n // CodeView items are component-managed whenever their CodeView is.\n protected override get isComponentManaged(): boolean {\n return (\n this.getAdvancedVirtualizer()?.isComponentManaged ??\n super.isComponentManaged\n );\n }\n\n // The editor changed the ghost text rows it shows below lines. Ask the\n // virtualizer for a layout pass, which folds them in (see\n // applyGhostTextRows). Layout state only changes inside that pass.\n public syncGhostTextRows(): void {\n const codeView = this.getAdvancedVirtualizer();\n if (codeView != null) {\n codeView.capturePendingLayoutAnchor();\n this.layoutDirty = true;\n codeView.instanceChanged(this, true);\n } else {\n this.getSimpleVirtualizer()?.requestHeightReconcile(this);\n }\n }\n\n // Normally triggered by the host when the document line count changes.\n override applyDocumentChange(\n textDocument: TextDocument<'file-diff', LAnnotation>,\n newLineAnnotations?: DiffLineAnnotation<LAnnotation>[],\n shouldUpdateBuffer = false\n ): void {\n const { renderRange: previousRenderRange } = this;\n // Capture the scroll anchor before the synchronous hunk rebuild and\n // measured-height wipe below; the host's next frame resolves it against\n // the new geometry so on-screen rows do not shift.\n this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor();\n super.applyDocumentChange(textDocument, newLineAnnotations);\n this.getSimpleVirtualizer()?.markDOMDirty();\n this.resetLayoutCache({\n forceSimpleRecompute: this.isSimpleMode(),\n includeEstimatedHeights: true,\n resetRenderRange: false,\n });\n\n const fileDiff = this.getRenderedDiff();\n if (!this.isSimpleMode()) {\n this.computeApproximateSize(true);\n } else if (\n shouldUpdateBuffer &&\n previousRenderRange != null &&\n fileDiff != null\n ) {\n // Update the buffers caused by the line-count change to ensure the host\n // scrolls to the correct position before re-rendering.\n const windowSpecs = this.virtualizer.getWindowSpecs();\n const renderRange = this.computeRenderRangeFromWindow(\n fileDiff,\n this.top ?? 0,\n windowSpecs\n );\n if (renderRange.bufferAfter !== previousRenderRange.bufferAfter) {\n this.updateBuffers(renderRange);\n }\n }\n\n this.forceRenderOverride = true;\n this.virtualizer.instanceChanged(this, true);\n }\n\n // Compute the approximate size from the cached baseline estimate plus any\n // measured height deltas observed in rendered rows.\n // The reason we refer to this as `approximate size` is because heights my\n // dynamically change for a number of reasons so we can never be fully sure\n // if the height is 100% accurate\n private computeApproximateSize(\n force = false,\n fileDiff: FileDiffMetadata | undefined = this.getLayoutDiff()\n ): void {\n const shouldValidateSize = this.isResizeDebuggingEnabled();\n if (!force && !this.layoutDirty && !shouldValidateSize) {\n return;\n }\n\n const isFirstCompute = this.height === 0;\n this.height = 0;\n this.cache.checkpoints = [];\n this.cache.totalLines = 0;\n if (fileDiff == null) {\n this.layoutDirty = false;\n return;\n }\n this.applyGhostTextRows(\n fileDiff,\n this.editor?.__getGhostTextRows() ?? NO_GHOST_TEXT_ROWS\n );\n\n const { disableFileHeader = false, collapsed = false } = this.options;\n if (collapsed) {\n this.height += getVirtualFileHeaderHeight(\n this.metrics,\n disableFileHeader\n );\n this.layoutDirty = false;\n return;\n }\n\n this.height =\n this.getActiveEstimatedHeight(fileDiff) +\n this.cache.measuredHeightDeltaTotal;\n\n if (shouldValidateSize && !isFirstCompute) {\n this.validateComputedHeight(fileDiff);\n }\n this.layoutDirty = false;\n }\n\n // CodeView calculates its next layout before updating the DOM. This keeps every\n // layout calculation within that frame tied to the same diff.\n private getLayoutDiff(): FileDiffMetadata | undefined {\n return this.pendingRender?.diff ?? this.getRenderedDiff();\n }\n\n // Annotations paired with the content layout is prepared for.\n private getLayoutAnnotations(): DiffLineAnnotation<LAnnotation>[] {\n const { pendingRender } = this;\n return pendingRender != null\n ? this.getAnnotationsForDiff(pendingRender.diff)\n : this.lineAnnotations;\n }\n\n private getActiveEstimatedHeight(\n fileDiff: FileDiffMetadata | undefined = this.getLayoutDiff()\n ): number {\n this.ensureEstimatedDiffHeights(fileDiff);\n const estimatedHeight =\n this.getDiffStyle() === 'split'\n ? this.cache.estimatedSplitHeight\n : this.cache.estimatedUnifiedHeight;\n if (estimatedHeight == null) {\n throw new Error(\n 'VirtualizedFileDiff.getActiveEstimatedHeight: missing estimated height'\n );\n }\n return estimatedHeight;\n }\n\n private ensureEstimatedDiffHeights(\n fileDiff: FileDiffMetadata | undefined = this.getLayoutDiff()\n ): void {\n if (fileDiff == null) {\n this.cache.estimatedSplitHeight = undefined;\n this.cache.estimatedUnifiedHeight = undefined;\n return;\n }\n if (\n this.cache.estimatedSplitHeight != null &&\n this.cache.estimatedUnifiedHeight != null\n ) {\n return;\n }\n\n const {\n disableFileHeader = false,\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const { splitHeight, unifiedHeight } = computeEstimatedDiffHeights({\n fileDiff,\n metrics: this.metrics,\n disableFileHeader,\n hunkSeparators: this.getHunkSeparatorType(),\n expandUnchanged,\n expandedHunks: this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n canHydratePartialDiff: canHydrateCollapsedContext(\n fileDiff,\n this.options.loadDiffFiles != null\n ),\n });\n this.cache.estimatedSplitHeight = splitHeight;\n this.cache.estimatedUnifiedHeight = unifiedHeight;\n }\n\n private validateComputedHeight(\n fileDiff: FileDiffMetadata | undefined = this.getLayoutDiff()\n ): void {\n if (this.fileContainer == null || fileDiff == null) {\n return;\n }\n\n const rect = this.fileContainer.getBoundingClientRect();\n if (rect.height !== this.height) {\n console.log(\n 'VirtualizedFileDiff.computeApproximateSize: computed height doesnt match',\n {\n name: fileDiff.name,\n elementHeight: rect.height,\n computedHeight: this.height,\n }\n );\n } else {\n console.log(\n 'VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT'\n );\n }\n }\n\n override render({\n fileContainer,\n fileDiff,\n forceRender = false,\n lineAnnotations,\n ...fileInputProps\n }: FileDiffRenderProps<LAnnotation> = {}): boolean {\n const fileInput = getDiffFileInput(\n fileInputProps,\n 'VirtualizedFileDiff.render'\n );\n const hasFileInput = fileInput != null;\n const oldFile = fileInput?.oldFile;\n const newFile = fileInput?.newFile;\n const filesDidChange =\n hasFileInput &&\n (!areOptionalFilesEqual(oldFile, this.deletionFile) ||\n !areOptionalFilesEqual(newFile, this.additionFile));\n let nextFileDiff = fileDiff ?? this.getInputDiff();\n if (\n fileDiff == null &&\n hasFileInput &&\n (filesDidChange || this.getInputDiff() == null)\n ) {\n nextFileDiff = parseDiffFromFile(\n fileInput.oldFile,\n fileInput.newFile,\n this.options.parseDiffOptions\n );\n }\n const { forceRenderOverride, isSetup } = this;\n this.forceRenderOverride = undefined;\n const targetChanged =\n nextFileDiff != null &&\n !areDiffTargetsEqual(this.getInputDiff(), nextFileDiff);\n const dataChanged = targetChanged || filesDidChange;\n\n fileContainer = this.getOrCreateFileContainer(fileContainer);\n\n if (nextFileDiff == null) {\n console.error(\n 'VirtualizedFileDiff.render: attempting to virtually render when we dont have the correct data'\n );\n return false;\n }\n if (targetChanged) {\n this.updateInputDiff(nextFileDiff, lineAnnotations);\n }\n\n const {\n pendingRenderDiff,\n layoutDiffChanged,\n renderedDiffChanged,\n annotationsChanged,\n } = (() => {\n if (\n this.pendingRender != null &&\n this.pendingRender.workingDiff ===\n (this.getWorkingDiff(nextFileDiff) ?? nextFileDiff)\n ) {\n return {\n pendingRenderDiff: this.pendingRender.diff,\n layoutDiffChanged: false,\n renderedDiffChanged: false,\n annotationsChanged: this.syncLineAnnotations(lineAnnotations),\n };\n }\n return this.updatePendingRender(nextFileDiff, lineAnnotations);\n })();\n\n if (layoutDiffChanged) {\n this.resetLayoutCache({\n includeEstimatedHeights: true,\n });\n }\n\n if (!isSetup) {\n this.computeApproximateSize(false, pendingRenderDiff);\n const virtualizer = this.getSimpleVirtualizer();\n this.top ??= this.getVirtualizedTop();\n if (this.isAdvancedMode()) {\n this.isVisible = true;\n } else {\n if (virtualizer == null) {\n throw new Error(\n 'VirtualizedFileDiff.render: simple virtualizer is not available'\n );\n }\n virtualizer.connect(fileContainer, this);\n this.isVisible = virtualizer.isInstanceVisible(\n this.top ?? 0,\n this.height\n );\n }\n this.isSetup = true;\n } else {\n this.top ??= this.getVirtualizedTop();\n if (this.layoutDirty && this.isSimpleMode()) {\n this.getSimpleVirtualizer()?.markDOMDirty();\n this.computeApproximateSize(false, pendingRenderDiff);\n }\n }\n\n if (!this.isVisible && this.isSimpleMode() && (!dataChanged || !isSetup)) {\n if (fileInput != null) {\n this.deletionFile = oldFile;\n this.additionFile = newFile;\n }\n if (targetChanged) {\n this.clearReusableHeader();\n }\n return this.renderPlaceholder(this.height);\n }\n\n const windowSpecs = this.virtualizer.getWindowSpecs();\n const fileTop = this.top ?? 0;\n const renderRange = this.computeRenderRangeFromWindow(\n pendingRenderDiff,\n fileTop,\n windowSpecs\n );\n return super.render({\n fileDiff: nextFileDiff,\n fileContainer,\n renderRange,\n lineAnnotations,\n forceRender:\n (forceRenderOverride ?? forceRender) ||\n annotationsChanged ||\n renderedDiffChanged ||\n targetChanged,\n ...fileInput,\n ...fileInputProps,\n });\n }\n\n protected override finalizeRender(): void {\n if (\n !areDiffTargetsEqual(this.getRenderedDiff(), this.pendingRender?.diff)\n ) {\n throw new Error(\n 'VirtualizedFileDiff.render: rendered a different diff than its prepared layout'\n );\n }\n this.pendingRender = undefined;\n // Renders can be driven from outside the virtualizer (host/React render\n // calls, async highlight completions), and the virtualizer only\n // auto-reconciles renders it initiated. Queue a measured-height\n // reconciliation for every applied content render so line deltas\n // (wrapped lines, annotation heights) survive layout resets.\n if (this.isSimpleMode()) {\n this.getSimpleVirtualizer()?.requestHeightReconcile(this);\n }\n }\n\n private updatePendingRender(\n nextFileDiff: FileDiffMetadata,\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined\n ) {\n const workingDiff = this.getWorkingDiff(nextFileDiff) ?? nextFileDiff;\n const previousRenderedDiff = this.getRenderedDiff();\n const { pendingRender } = this;\n const previousLayoutDiff = pendingRender?.diff ?? previousRenderedDiff;\n const pendingRenderDiff =\n this.hunksRenderer.getDiffForNextRender(workingDiff);\n\n this.pendingRender = { workingDiff, diff: pendingRenderDiff };\n\n return {\n pendingRenderDiff,\n annotationsChanged: this.syncLineAnnotations(lineAnnotations),\n layoutDiffChanged: !areDiffTargetsEqual(\n previousLayoutDiff,\n pendingRenderDiff\n ),\n renderedDiffChanged: !areDiffTargetsEqual(\n previousRenderedDiff,\n pendingRenderDiff\n ),\n };\n }\n\n public syncVirtualizedTop(): void {\n this.top = this.getVirtualizedTop();\n }\n\n protected override shouldDisableVirtualizationBuffers(): boolean {\n return this.isAdvancedMode() || super.shouldDisableVirtualizationBuffers();\n }\n\n // This WebKit dom manipulation scroll fix is not applicable in virtualized\n // environments, so we avoid the performance hit even on Webkit\n protected override shouldGuardRebuildScroll(): boolean {\n return false;\n }\n\n private isSimpleMode(): boolean {\n return this.virtualizer.type === 'simple';\n }\n\n private isAdvancedMode(): boolean {\n return this.virtualizer.type === 'advanced';\n }\n\n private getVirtualizedTop(): number {\n if (this.virtualizer.type === 'advanced') {\n return this.virtualizer.getLocalTopForInstance(this);\n }\n return this.fileContainer != null\n ? this.virtualizer.getOffsetInScrollContainer(this.fileContainer)\n : 0;\n }\n\n private getSimpleVirtualizer(): Virtualizer | undefined {\n return this.virtualizer.type === 'simple' ? this.virtualizer : undefined;\n }\n\n private getAdvancedVirtualizer(): CodeView<LAnnotation, Caret> | undefined {\n return this.virtualizer.type === 'advanced' ? this.virtualizer : undefined;\n }\n\n private isResizeDebuggingEnabled(): boolean {\n return this.getSimpleVirtualizer()?.config.resizeDebugging ?? false;\n }\n\n private getDiffStyle(): 'split' | 'unified' {\n return this.options.diffStyle ?? 'split';\n }\n\n private getHunkSeparatorType(): HunkSeparators {\n return getOptionHunkSeparatorType(this.options.hunkSeparators);\n }\n\n private approximateLayoutCheckpoints(fileDiff: FileDiffMetadata): void {\n if (\n (!this.layoutDirty && this.cache.checkpoints.length > 0) ||\n fileDiff.hunks.length === 0 ||\n this.options.collapsed === true\n ) {\n return;\n }\n\n const {\n disableFileHeader = false,\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const finalHunkIndex = fileDiff.hunks.length - 1;\n const canHydratePartialDiff = canHydrateCollapsedContext(\n fileDiff,\n this.options.loadDiffFiles != null\n );\n const diffStyle = this.getDiffStyle();\n const hunkSeparators = this.getHunkSeparatorType();\n const expandedHunks = expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap();\n const heightDeltaPrefix = createHeightDeltaPrefix(this.cache.heightDeltas);\n let top =\n getVirtualFileHeaderRegion(this.metrics, disableFileHeader) +\n this.cache.fileAnnotationHeight;\n let renderedLineIndex = 0;\n\n const processRows = ({\n rowCount,\n startLineIndex,\n preSeparatorHeight = 0,\n postSeparatorHeight = 0,\n metadataOffsets = [],\n }: {\n rowCount: number;\n startLineIndex: number;\n preSeparatorHeight?: number;\n postSeparatorHeight?: number;\n metadataOffsets?: number[];\n }) => {\n if (rowCount <= 0) {\n return;\n }\n\n const blockStart = renderedLineIndex;\n const blockEnd = renderedLineIndex + rowCount;\n let nextCheckpoint = getNextCheckpointIndex(blockStart);\n while (nextCheckpoint < blockEnd) {\n const offset = nextCheckpoint - blockStart;\n const checkpointTop =\n top +\n (offset > 0 ? preSeparatorHeight : 0) +\n offset * this.metrics.lineHeight +\n countMetadataOffsetsBefore(metadataOffsets, offset) *\n this.metrics.lineHeight +\n sumHeightDeltas(\n heightDeltaPrefix,\n startLineIndex,\n startLineIndex + offset\n );\n this.cache.checkpoints.push({\n renderedLineIndex: nextCheckpoint,\n lineIndex: startLineIndex + offset,\n top: checkpointTop,\n });\n nextCheckpoint += VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL;\n }\n\n top +=\n preSeparatorHeight +\n rowCount * this.metrics.lineHeight +\n metadataOffsets.length * this.metrics.lineHeight +\n sumHeightDeltas(\n heightDeltaPrefix,\n startLineIndex,\n startLineIndex + rowCount\n ) +\n postSeparatorHeight;\n renderedLineIndex = blockEnd;\n };\n\n for (let hunkIndex = 0; hunkIndex < fileDiff.hunks.length; hunkIndex++) {\n const hunk = fileDiff.hunks[hunkIndex];\n if (hunk == null) {\n throw new Error(\n 'VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index'\n );\n }\n\n const leadingRegion = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: hunk.collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n const leadingSeparatorHeight =\n leadingRegion.collapsedLines > 0\n ? (getLeadingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n hunkIndex,\n hunkSpecs: hunk.hunkSpecs,\n })?.totalHeight ?? 0)\n : 0;\n\n processRows({\n rowCount: leadingRegion.fromStart,\n startLineIndex:\n (diffStyle === 'split'\n ? hunk.splitLineStart\n : hunk.unifiedLineStart) - leadingRegion.rangeSize,\n });\n\n let pendingLeadingSeparatorHeight = leadingSeparatorHeight;\n processRows({\n rowCount: leadingRegion.fromEnd,\n startLineIndex:\n (diffStyle === 'split'\n ? hunk.splitLineStart\n : hunk.unifiedLineStart) - leadingRegion.fromEnd,\n preSeparatorHeight: pendingLeadingSeparatorHeight,\n });\n if (leadingRegion.fromEnd > 0) {\n pendingLeadingSeparatorHeight = 0;\n }\n\n const trailingRegion =\n hunkIndex === finalHunkIndex\n ? getTrailingExpandedRegion({\n fileDiff,\n hunkIndex,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'VirtualizedFileDiff',\n })\n : undefined;\n const trailingSeparatorHeight =\n trailingRegion != null && trailingRegion.collapsedLines > 0\n ? (getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n })?.totalHeight ?? 0)\n : hunkIndex === finalHunkIndex && canHydratePartialDiff\n ? (getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n })?.totalHeight ?? 0)\n : 0;\n const trailingExpandedCount =\n trailingRegion != null\n ? trailingRegion.fromStart + trailingRegion.fromEnd\n : 0;\n\n const hunkBodyRowCount =\n diffStyle === 'split' ? hunk.splitLineCount : hunk.unifiedLineCount;\n const hunkBodyStartLineIndex =\n diffStyle === 'split' ? hunk.splitLineStart : hunk.unifiedLineStart;\n processRows({\n rowCount: hunkBodyRowCount,\n startLineIndex: hunkBodyStartLineIndex,\n preSeparatorHeight: pendingLeadingSeparatorHeight,\n postSeparatorHeight:\n trailingExpandedCount === 0 ? trailingSeparatorHeight : 0,\n metadataOffsets: getHunkMetadataOffsets({\n diffStyle,\n hunk,\n rowCount: hunkBodyRowCount,\n }),\n });\n\n if (trailingRegion != null && trailingExpandedCount > 0) {\n processRows({\n rowCount: trailingExpandedCount,\n startLineIndex: hunkBodyStartLineIndex + hunkBodyRowCount,\n postSeparatorHeight: trailingSeparatorHeight,\n });\n }\n }\n\n this.cache.totalLines = renderedLineIndex;\n }\n\n // Find the nearest sparse layout checkpoint at or before an active\n // diff-style line index. Diff checkpoints also store the dense rendered-row\n // index, so deep line-position lookups can resume iteration from that\n // rendered row and replay only the nearby layout work instead of walking\n // from the first hunk.\n private getLayoutCheckpointBeforeLineIndex(\n lineIndex: number\n ): DiffLayoutCheckpoint | undefined {\n if (lineIndex <= 0 || this.cache.checkpoints.length === 0) {\n return undefined;\n }\n\n let low = 0;\n let high = this.cache.checkpoints.length - 1;\n let result: DiffLayoutCheckpoint | undefined;\n\n while (low <= high) {\n const mid = (low + high) >> 1;\n const checkpoint = this.cache.checkpoints[mid];\n if (checkpoint == null) {\n throw new Error('VirtualizedFileDiff: invalid checkpoint index');\n }\n if (checkpoint.lineIndex <= lineIndex) {\n result = checkpoint;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return result;\n }\n\n // Find the nearest sparse layout checkpoint at or before a scroll offset.\n // Render-range scans start from this checkpoint so variable-height diffs\n // only replay nearby rows. When `hunkLineCount` is provided, step backward\n // to a rendered hunk boundary so buffer calculations can reuse absolute hunk\n // offsets safely.\n private getLayoutCheckpointBeforeTop(\n top: number,\n hunkLineCount?: number\n ): DiffLayoutCheckpoint | undefined {\n let low = 0;\n let high = this.cache.checkpoints.length - 1;\n let resultIndex = -1;\n\n while (low <= high) {\n const mid = (low + high) >> 1;\n const checkpoint = this.cache.checkpoints[mid];\n if (checkpoint == null) {\n throw new Error('VirtualizedFileDiff: invalid checkpoint index');\n }\n if (checkpoint.top <= top) {\n resultIndex = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n if (hunkLineCount == null) {\n return resultIndex >= 0 ? this.cache.checkpoints[resultIndex] : undefined;\n }\n\n for (let index = resultIndex; index >= 0; index--) {\n const checkpoint = this.cache.checkpoints[index];\n if (checkpoint == null) {\n throw new Error('VirtualizedFileDiff: invalid checkpoint index');\n }\n if (checkpoint.renderedLineIndex % hunkLineCount === 0) {\n return checkpoint;\n }\n }\n\n return undefined;\n }\n\n private getExpandedLineCount(\n fileDiff: FileDiffMetadata,\n diffStyle: 'split' | 'unified'\n ): number {\n let count = 0;\n if (fileDiff.isPartial) {\n for (const hunk of fileDiff.hunks) {\n count +=\n diffStyle === 'split' ? hunk.splitLineCount : hunk.unifiedLineCount;\n }\n return count;\n }\n\n const {\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const expandedHunks = expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap();\n\n for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {\n const hunkCount =\n diffStyle === 'split' ? hunk.splitLineCount : hunk.unifiedLineCount;\n count += hunkCount;\n const collapsedBefore = Math.max(hunk.collapsedBefore, 0);\n const { fromStart, fromEnd, renderAll } = getExpandedRegion({\n isPartial: fileDiff.isPartial,\n rangeSize: collapsedBefore,\n expandedHunks,\n hunkIndex,\n collapsedContextThreshold,\n });\n if (collapsedBefore > 0) {\n count += renderAll ? collapsedBefore : fromStart + fromEnd;\n }\n }\n\n const trailingRegion = getTrailingExpandedRegion({\n fileDiff,\n hunkIndex: fileDiff.hunks.length - 1,\n expandedHunks,\n collapsedContextThreshold,\n errorPrefix: 'VirtualizedFileDiff',\n });\n if (trailingRegion != null) {\n count += trailingRegion.fromStart + trailingRegion.fromEnd;\n }\n\n return count;\n }\n\n // Row total used to clamp render-range scrolling. Sparse layout checkpoints can\n // still hold a smaller pre-edit count until they are rebuilt, so always take\n // the max against the live diff metadata (including additionLines.length).\n private getLayoutLineCount(\n fileDiff: FileDiffMetadata,\n diffStyle: 'split' | 'unified'\n ): number {\n const expandedLineCount = this.getExpandedLineCount(fileDiff, diffStyle);\n const metadataLineCount =\n diffStyle === 'split'\n ? fileDiff.splitLineCount\n : fileDiff.unifiedLineCount;\n return Math.max(\n expandedLineCount,\n metadataLineCount,\n fileDiff.additionLines.length,\n fileDiff.deletionLines.length,\n this.cache.totalLines\n );\n }\n\n private computeRenderRangeFromWindow(\n fileDiff: FileDiffMetadata,\n fileTop: number,\n { top, bottom }: RenderWindow\n ): RenderRange {\n const {\n disableFileHeader = false,\n expandUnchanged = false,\n collapsedContextThreshold = DEFAULT_COLLAPSED_CONTEXT_THRESHOLD,\n } = this.options;\n const { hunkLineCount, lineHeight } = this.metrics;\n const diffStyle = this.getDiffStyle();\n const hunkSeparators = this.getHunkSeparatorType();\n const canHydratePartialDiff = canHydrateCollapsedContext(\n fileDiff,\n this.options.loadDiffFiles != null\n );\n const fileHeight = this.height;\n let lineCount = this.getLayoutLineCount(fileDiff, diffStyle);\n\n const headerRegion = getVirtualFileHeaderRegion(\n this.metrics,\n disableFileHeader\n );\n const paddingBottom =\n fileDiff.hunks.length > 0 ? getVirtualFilePaddingBottom(this.metrics) : 0;\n const { fileAnnotationHeight } = this.cache;\n const codeRegionTop = headerRegion + fileAnnotationHeight;\n const codeHeight = Math.max(\n 0,\n fileHeight - headerRegion - fileAnnotationHeight - paddingBottom\n );\n const hasFileAnnotations = this.hasFileAnnotations(fileDiff);\n const fileAnnotationTop = fileTop + headerRegion;\n const measuredFileAnnotationVisible =\n fileAnnotationHeight > 0 &&\n hasFileAnnotations &&\n fileAnnotationTop < bottom &&\n fileAnnotationTop + fileAnnotationHeight > top;\n\n // File is outside render window\n if (fileTop < top - fileHeight || fileTop > bottom) {\n return {\n startingLine: 0,\n totalLines: 0,\n bufferBefore: 0,\n bufferAfter: fileHeight - headerRegion - paddingBottom,\n };\n }\n\n // Whole file is under hunkLineCount, just render it all\n if (lineCount <= hunkLineCount || fileDiff.hunks.length === 0) {\n return {\n startingLine: 0,\n totalLines: hunkLineCount,\n bufferBefore: 0,\n bufferAfter: 0,\n };\n }\n\n this.approximateLayoutCheckpoints(fileDiff);\n lineCount = this.getLayoutLineCount(fileDiff, diffStyle);\n\n const estimatedTargetLines = Math.ceil(\n Math.max(bottom - top, 0) / lineHeight\n );\n const totalLines =\n Math.ceil(estimatedTargetLines / hunkLineCount) * hunkLineCount +\n hunkLineCount;\n const totalHunks = totalLines / hunkLineCount;\n const overflowHunks = totalHunks;\n const hunkOffsets: number[] = [];\n // Halfway between top & bottom, represented as an absolute position\n const viewportCenter = (top + bottom) / 2;\n // Start the scan before the viewport so we collect hunk offsets that may be\n // needed for bufferBefore. This only chooses the scan origin; the returned\n // render range is still computed from the visible window below.\n const checkpoint = this.getLayoutCheckpointBeforeTop(\n Math.max(0, top - fileTop - totalLines * lineHeight * 2),\n hunkLineCount\n );\n\n let absoluteLineTop = fileTop + (checkpoint?.top ?? codeRegionTop);\n let currentLine = checkpoint?.renderedLineIndex ?? 0;\n let firstVisibleHunk: number | undefined;\n let centerHunk: number | undefined;\n let overflowCounter: number | undefined;\n\n iterateOverDiff({\n diff: fileDiff,\n diffStyle,\n startingLine: checkpoint?.renderedLineIndex ?? 0,\n expandedHunks: expandUnchanged\n ? true\n : this.hunksRenderer.getExpandedHunksMap(),\n collapsedContextThreshold,\n callback: ({\n hunkIndex,\n hunk,\n collapsedBefore,\n collapsedAfter,\n deletionLine,\n additionLine,\n }) => {\n const splitLineIndex =\n additionLine != null\n ? additionLine.splitLineIndex\n : deletionLine.splitLineIndex;\n const unifiedLineIndex =\n additionLine != null\n ? additionLine.unifiedLineIndex\n : deletionLine.unifiedLineIndex;\n const hasMetadata =\n (additionLine?.noEOFCR ?? false) || (deletionLine?.noEOFCR ?? false);\n const isFinalHunkRow =\n hunkIndex === fileDiff.hunks.length - 1 &&\n hunk != null &&\n (diffStyle === 'split'\n ? splitLineIndex === hunk.splitLineStart + hunk.splitLineCount - 1\n : unifiedLineIndex ===\n hunk.unifiedLineStart + hunk.unifiedLineCount - 1);\n const leadingSeparator =\n collapsedBefore > 0\n ? getLeadingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n hunkIndex,\n hunkSpecs: hunk?.hunkSpecs,\n })\n : undefined;\n const gapAdjustment = leadingSeparator?.totalHeight ?? 0;\n\n absoluteLineTop += gapAdjustment;\n\n const isAtHunkBoundary = currentLine % hunkLineCount === 0;\n const currentHunk = Math.floor(currentLine / hunkLineCount);\n\n // Track the boundary positional offset at a hunk\n if (isAtHunkBoundary) {\n hunkOffsets[currentHunk] =\n absoluteLineTop - (fileTop + codeRegionTop + gapAdjustment);\n\n // Check if we should bail (overflow complete)\n if (overflowCounter != null) {\n if (overflowCounter <= 0) {\n return true;\n }\n overflowCounter--;\n }\n }\n\n const lineHeight = this.getLineHeight(\n diffStyle === 'split' ? splitLineIndex : unifiedLineIndex,\n hasMetadata\n );\n\n // Track visible region\n if (absoluteLineTop > top - lineHeight && absoluteLineTop < bottom) {\n firstVisibleHunk ??= currentHunk;\n }\n\n // Track which hunk contains the viewport center\n // If viewport center is above this line and we haven't set centerHunk yet,\n // this is the first line at or past the center\n if (\n centerHunk == null &&\n absoluteLineTop + lineHeight > viewportCenter\n ) {\n centerHunk = currentHunk;\n }\n\n // Start overflow when we are out of the viewport at a hunk boundary\n if (\n overflowCounter == null &&\n absoluteLineTop >= bottom &&\n isAtHunkBoundary\n ) {\n overflowCounter = overflowHunks;\n }\n\n currentLine++;\n absoluteLineTop += lineHeight;\n\n if (collapsedAfter > 0 || (isFinalHunkRow && canHydratePartialDiff)) {\n const trailingSeparator = getTrailingHunkSeparatorLayout({\n type: hunkSeparators,\n metrics: this.metrics,\n });\n if (trailingSeparator != null) {\n if (\n absoluteLineTop < bottom &&\n absoluteLineTop + trailingSeparator.totalHeight > top\n ) {\n firstVisibleHunk ??= currentHunk;\n }\n if (\n centerHunk == null &&\n absoluteLineTop + trailingSeparator.totalHeight > viewportCenter\n ) {\n centerHunk = currentHunk;\n }\n absoluteLineTop += trailingSeparator.totalHeight;\n }\n }\n\n return false;\n },\n });\n\n // No visible lines found\n if (firstVisibleHunk == null) {\n if (measuredFileAnnotationVisible) {\n firstVisibleHunk = 0;\n centerHunk = 0;\n } else {\n return {\n startingLine: 0,\n totalLines: 0,\n bufferBefore: 0,\n bufferAfter: fileHeight - headerRegion - paddingBottom,\n };\n }\n }\n\n // Calculate balanced startingLine centered around the viewport center\n // Fall back to firstVisibleHunk if center wasn't found (e.g., center in a gap)\n centerHunk ??= firstVisibleHunk;\n const idealStartHunk = Math.round(centerHunk - totalHunks / 2);\n\n // Clamp startHunk: at the beginning, reduce totalLines; at the end, shift startHunk back\n const maxStartHunk = Math.max(\n 0,\n Math.ceil(lineCount / hunkLineCount) - totalHunks\n );\n const startHunk = Math.max(0, Math.min(idealStartHunk, maxStartHunk));\n const startingLine = startHunk * hunkLineCount;\n\n // If we wanted to start before 0, reduce totalLines by the clamped amount\n const clampedTotalLines =\n idealStartHunk < 0\n ? totalLines + idealStartHunk * hunkLineCount\n : totalLines;\n\n // Use hunkOffsets array for efficient buffer calculations\n const codeBufferBefore = hunkOffsets[startHunk] ?? 0;\n const bufferBefore =\n startingLine === 0 ? 0 : fileAnnotationHeight + codeBufferBefore;\n\n // Calculate bufferAfter using hunkOffset if available, otherwise use cumulative height\n const finalHunkIndex = startHunk + clampedTotalLines / hunkLineCount;\n const bufferAfter =\n finalHunkIndex < hunkOffsets.length\n ? codeHeight - hunkOffsets[finalHunkIndex]\n : // We stopped early, calculate from current position\n codeHeight - (absoluteLineTop - fileTop - codeRegionTop);\n\n return {\n startingLine,\n totalLines: clampedTotalLines,\n bufferBefore,\n bufferAfter: Math.max(0, bufferAfter),\n };\n }\n}\n\nfunction measureFileAnnotationHeight(\n codeGroups: (HTMLElement | undefined)[]\n): number | undefined {\n let height: number | undefined;\n for (const codeGroup of codeGroups) {\n if (codeGroup == null) continue;\n const content = codeGroup.children[1];\n if (!(content instanceof HTMLElement)) continue;\n for (const child of content.children) {\n if (!(child instanceof HTMLElement)) continue;\n if (child.dataset.lineAnnotation !== FILE_ANNOTATION_DOM_KEY) {\n continue;\n }\n height = Math.max(height ?? 0, child.getBoundingClientRect().height);\n }\n }\n return height;\n}\n\ninterface HeightDeltaPrefix {\n lineIndexes: number[];\n prefixTotals: number[];\n}\n\nfunction createHeightDeltaPrefix(\n heightDeltas: Map<number, number>\n): HeightDeltaPrefix {\n const entries = Array.from(heightDeltas).sort((a, b) => a[0] - b[0]);\n const lineIndexes: number[] = [];\n const prefixTotals = [0];\n let total = 0;\n for (const [lineIndex, delta] of entries) {\n lineIndexes.push(lineIndex);\n total += delta;\n prefixTotals.push(total);\n }\n return { lineIndexes, prefixTotals };\n}\n\nfunction sumHeightDeltas(\n { lineIndexes, prefixTotals }: HeightDeltaPrefix,\n startLineIndex: number,\n endLineIndex: number\n): number {\n if (startLineIndex >= endLineIndex || lineIndexes.length === 0) {\n return 0;\n }\n const start = lowerBound(lineIndexes, startLineIndex);\n const end = lowerBound(lineIndexes, endLineIndex);\n return (prefixTotals[end] ?? 0) - (prefixTotals[start] ?? 0);\n}\n\nfunction lowerBound(values: number[], target: number): number {\n let low = 0;\n let high = values.length;\n while (low < high) {\n const mid = (low + high) >> 1;\n const value = values[mid];\n if (value == null) {\n throw new Error('VirtualizedFileDiff: invalid prefix index');\n }\n if (value < target) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n}\n\nfunction getNextCheckpointIndex(renderedLineIndex: number): number {\n return (\n Math.ceil(\n renderedLineIndex / VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL\n ) * VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL\n );\n}\n\nfunction countMetadataOffsetsBefore(\n metadataOffsets: number[],\n offset: number\n): number {\n let count = 0;\n for (const metadataOffset of metadataOffsets) {\n if (metadataOffset < offset) {\n count++;\n }\n }\n return count;\n}\n\nfunction getHunkMetadataOffsets({\n diffStyle,\n hunk,\n rowCount,\n}: {\n diffStyle: 'split' | 'unified';\n hunk: Hunk;\n rowCount: number;\n}): number[] {\n if (rowCount <= 0 || (!hunk.noEOFCRAdditions && !hunk.noEOFCRDeletions)) {\n return [];\n }\n\n const lastContent = hunk.hunkContent.at(-1);\n if (lastContent == null) {\n return [];\n }\n\n if (lastContent.type === 'context') {\n return [rowCount - 1];\n }\n\n const splitCount = Math.max(lastContent.deletions, lastContent.additions);\n const unifiedCount = lastContent.deletions + lastContent.additions;\n if (diffStyle === 'split') {\n return splitCount > 0 && (hunk.noEOFCRAdditions || hunk.noEOFCRDeletions)\n ? [rowCount - 1]\n : [];\n }\n\n const offsets: number[] = [];\n const contentStartOffset = rowCount - unifiedCount;\n if (lastContent.deletions > 0 && hunk.noEOFCRDeletions) {\n offsets.push(contentStartOffset + lastContent.deletions - 1);\n }\n if (lastContent.additions > 0 && hunk.noEOFCRAdditions) {\n offsets.push(rowCount - 1);\n }\n return offsets;\n}\n\nfunction hasDiffLayoutOptionChanged<LAnnotation, Caret>(\n previousOptions: FileDiffOptions<LAnnotation, Caret>,\n nextOptions: FileDiffOptions<LAnnotation, Caret>\n): boolean {\n return (\n (previousOptions.diffStyle ?? 'split') !==\n (nextOptions.diffStyle ?? 'split') ||\n (previousOptions.overflow ?? 'scroll') !==\n (nextOptions.overflow ?? 'scroll') ||\n (previousOptions.collapsed ?? false) !== (nextOptions.collapsed ?? false) ||\n (previousOptions.disableLineNumbers ?? false) !==\n (nextOptions.disableLineNumbers ?? false) ||\n (previousOptions.disableFileHeader ?? false) !==\n (nextOptions.disableFileHeader ?? false) ||\n (previousOptions.diffIndicators ?? 'bars') !==\n (nextOptions.diffIndicators ?? 'bars') ||\n (previousOptions.hunkSeparators ?? 'line-info') !==\n (nextOptions.hunkSeparators ?? 'line-info') ||\n Boolean(previousOptions.loadDiffFiles) !==\n Boolean(nextOptions.loadDiffFiles) ||\n (previousOptions.expandUnchanged ?? false) !==\n (nextOptions.expandUnchanged ?? false) ||\n (previousOptions.collapsedContextThreshold ??\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD) !==\n (nextOptions.collapsedContextThreshold ??\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD) ||\n previousOptions.unsafeCSS !== nextOptions.unsafeCSS\n );\n}\n\nfunction hasDiffEstimateOptionChanged<LAnnotation, Caret>(\n previousOptions: FileDiffOptions<LAnnotation, Caret>,\n nextOptions: FileDiffOptions<LAnnotation, Caret>\n): boolean {\n return (\n (previousOptions.disableFileHeader ?? false) !==\n (nextOptions.disableFileHeader ?? false) ||\n (previousOptions.hunkSeparators ?? 'line-info') !==\n (nextOptions.hunkSeparators ?? 'line-info') ||\n Boolean(previousOptions.loadDiffFiles) !==\n Boolean(nextOptions.loadDiffFiles) ||\n (previousOptions.expandUnchanged ?? false) !==\n (nextOptions.expandUnchanged ?? false) ||\n (previousOptions.collapsedContextThreshold ??\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD) !==\n (nextOptions.collapsedContextThreshold ??\n DEFAULT_COLLAPSED_CONTEXT_THRESHOLD)\n );\n}\n\nfunction canHydrateCollapsedContext(\n fileDiff: FileDiffMetadata,\n hasFileLoader: boolean\n): boolean {\n return (\n fileDiff.isPartial &&\n hasFileLoader &&\n (fileDiff.type === 'change' || fileDiff.type === 'rename-changed')\n );\n}\n\nfunction getOptionHunkSeparatorType<LAnnotation, Caret>(\n hunkSeparators:\n | FileDiffOptions<LAnnotation, Caret>['hunkSeparators']\n | undefined\n): HunkSeparators {\n return typeof hunkSeparators === 'function'\n ? 'custom'\n : (hunkSeparators ?? 'line-info');\n}\n\nfunction areOptionalFilesEqual(\n fileA: FileContents | null | undefined,\n fileB: FileContents | null | undefined\n): boolean {\n if (fileA == null || fileB == null) {\n return fileA == null && fileB == null;\n }\n return areFilesEqual(fileA, fileB);\n}\n\n// Extracts the view-specific line index from the data-line-index attribute.\n// Format is \"unifiedIndex,splitIndex\"\nfunction parseLineIndex(\n lineIndexAttr: string,\n diffStyle: 'split' | 'unified'\n): number {\n const [unifiedIndex, splitIndex] = lineIndexAttr.split(',').map(Number);\n return diffStyle === 'split' ? splitIndex : unifiedIndex;\n}\n", "import type { VirtualWindowSpecs } from '../types';\n\nexport function areVirtualWindowSpecsEqual(\n windowSpecsA: VirtualWindowSpecs | undefined,\n windowSpecsB: VirtualWindowSpecs | undefined\n): boolean {\n if (windowSpecsA == null || windowSpecsB == null) {\n return windowSpecsA === windowSpecsB;\n }\n return (\n windowSpecsA.top === windowSpecsB.top &&\n windowSpecsA.bottom === windowSpecsB.bottom\n );\n}\n", "import {\n dequeueRender,\n queueRender,\n} from '../managers/UniversalRenderingManager';\nimport type { VirtualWindowSpecs } from '../types';\nimport { areVirtualWindowSpecsEqual } from '../utils/areVirtualWindowSpecsEqual';\nimport { createWindowFromScrollPosition } from '../utils/createWindowFromScrollPosition';\n\ninterface SubscribedInstance {\n onRender(dirty: boolean): boolean;\n reconcileHeights(): boolean;\n setVisibility(visible: boolean): void;\n}\n\ninterface ScrollAnchor {\n fileElement: HTMLElement;\n fileTypeOffset: 'top' | 'bottom';\n fileOffset: number;\n lineIndex: string | undefined;\n lineOffset: number | undefined;\n}\n\n// 800 seems like the healthy overscan required to\n// keep safari from blanking... if we catch it tho, maybe 900\nconst DEFAULT_OVERSCROLL_SIZE = 1000;\nconst INTERSECTION_OBSERVER_MARGIN = DEFAULT_OVERSCROLL_SIZE * 4;\nconst INTERSECTION_OBSERVER_THRESHOLD = [0, 0.000001, 0.99999, 1];\n\nexport interface VirtualizerConfig {\n /** Extra pixels rendered above and below the viewport to reduce blanking during fast scrolls. */\n overscrollSize: number;\n /** Margin used by IntersectionObserver to decide when items should be considered visible. */\n intersectionObserverMargin: number;\n /** Enables noisy resize logs to help tune metrics and investigate scroll jitter. */\n resizeDebugging: boolean;\n}\n\nexport interface VirtualizerScrollOptions {\n top: number;\n behavior?: ScrollBehavior;\n}\n\nconst DEFAULT_VIRTUALIZER_CONFIG: VirtualizerConfig = {\n overscrollSize: DEFAULT_OVERSCROLL_SIZE,\n intersectionObserverMargin: INTERSECTION_OBSERVER_MARGIN,\n resizeDebugging: false,\n};\n\nlet lastSize = 0;\n\nlet instance = -1;\n\nexport class Virtualizer {\n static __STOP: boolean = false;\n static __lastScrollPosition = 0;\n\n public readonly __id: string = `virtualizer-${++instance}`;\n public readonly config: VirtualizerConfig;\n public type = 'simple' as const;\n private intersectionObserver: IntersectionObserver | undefined;\n private scrollTop: number = 0;\n private height: number = 0;\n private scrollHeight: number = 0;\n private windowSpecs: VirtualWindowSpecs = { top: 0, bottom: 0 };\n private root: HTMLElement | Document | undefined;\n private contentContainer: HTMLElement | undefined;\n\n private resizeObserver: ResizeObserver | undefined;\n private observers: Map<HTMLElement, SubscribedInstance> = new Map();\n private visibleInstances: Map<HTMLElement, SubscribedInstance> = new Map();\n private visibleInstancesDirty: boolean = false;\n private instancesChanged: Set<SubscribedInstance> = new Set();\n // Instances whose content was (re)painted outside a virtualizer-driven\n // onRender — host/React render calls, async highlight completions — and\n // still need a measured-height reconciliation pass. See\n // requestHeightReconcile.\n private reconcileQueue: Set<SubscribedInstance> = new Set();\n\n private scrollDirty = true;\n private heightDirty = true;\n private scrollHeightDirty = true;\n private renderedObservers = 0;\n private connectQueue: Map<HTMLElement, SubscribedInstance> = new Map();\n\n constructor(config?: Partial<VirtualizerConfig>) {\n this.config = { ...DEFAULT_VIRTUALIZER_CONFIG, ...config };\n }\n\n setup(root: HTMLElement | Document, contentContainer?: Element): void {\n if (this.root != null) {\n return;\n }\n this.root = root;\n this.resizeObserver = new ResizeObserver(this.handleContainerResize);\n this.intersectionObserver = new IntersectionObserver(\n this.handleIntersectionChange,\n {\n root: this.root,\n threshold: INTERSECTION_OBSERVER_THRESHOLD,\n rootMargin: `${this.config.intersectionObserverMargin}px 0px ${this.config.intersectionObserverMargin}px 0px`,\n // FIXME(amadeus): Figure out the other settings we'll want in here, or\n // if we should make them configurable...\n }\n );\n if (root instanceof Document) {\n this.setupWindow();\n } else {\n this.setupElement(contentContainer);\n }\n\n // FIXME(amadeus): Remove me before release\n window.__INSTANCE = this;\n window.__TOGGLE = () => {\n if (Virtualizer.__STOP) {\n Virtualizer.__STOP = false;\n const scroller = this.getScrollContainerElement() ?? window;\n scroller.scrollTo({ top: Virtualizer.__lastScrollPosition });\n queueRender(this.computeRenderRangeAndEmit);\n } else {\n Virtualizer.__lastScrollPosition = this.getScrollTop();\n Virtualizer.__STOP = true;\n }\n };\n for (const [container, instance] of this.connectQueue.entries()) {\n this.connect(container, instance);\n }\n this.connectQueue.clear();\n this.markDOMDirty();\n queueRender(this.computeRenderRangeAndEmit);\n }\n\n instanceChanged(instance: SubscribedInstance, domDirty: boolean): void {\n this.instancesChanged.add(instance);\n if (domDirty) {\n this.markDOMDirty();\n }\n queueRender(this.computeRenderRangeAndEmit);\n }\n\n // The render loop only reconciles heights for instances it repainted\n // itself, but content can also land outside a virtualizer pass (a\n // host/React-driven render call, an async highlight completion). Those\n // renders queue themselves here so their measured line deltas — wrapped\n // lines, annotation heights — are re-captured; otherwise a layout reset\n // (e.g. an edit-session exit recompute) leaves the instance stuck on its\n // baseline estimate and its placeholder renders the wrong height.\n requestHeightReconcile(instance: SubscribedInstance): void {\n this.reconcileQueue.add(instance);\n queueRender(this.computeRenderRangeAndEmit);\n }\n\n getWindowSpecs(): VirtualWindowSpecs {\n if (this.windowSpecs.top === 0 && this.windowSpecs.bottom === 0) {\n this.windowSpecs = createWindowFromScrollPosition({\n scrollTop: this.getScrollTop(),\n height: this.getHeight(),\n scrollHeight: this.getScrollHeight(),\n overscrollSize: this.config.overscrollSize,\n });\n }\n return this.windowSpecs;\n }\n\n getRoot(): HTMLElement | Document | undefined {\n return this.root;\n }\n\n isInstanceVisible(elementTop: number, elementHeight: number): boolean {\n const scrollTop = this.getScrollTop();\n const height = this.getHeight();\n const margin = this.config.intersectionObserverMargin;\n const top = scrollTop - margin;\n const bottom = scrollTop + height + margin;\n return !(elementTop < top - elementHeight || elementTop > bottom);\n }\n\n private handleContainerResize = (entries: ResizeObserverEntry[]) => {\n if (this.root == null) return;\n let shouldQueueUpdate = false;\n for (const entry of entries) {\n const blockSize = entry.borderBoxSize[0].blockSize;\n if (this.root instanceof Document) {\n if (blockSize !== this.scrollHeight) {\n this.scrollHeightDirty = true;\n shouldQueueUpdate = true;\n if (this.config.resizeDebugging) {\n console.log('Virtualizer: content size change', this.__id, {\n sizeChange: blockSize - lastSize,\n newSize: blockSize,\n });\n lastSize = blockSize;\n }\n }\n } else {\n if (entry.target === this.root) {\n if (blockSize !== this.height) {\n this.heightDirty = true;\n shouldQueueUpdate = true;\n }\n } else if (entry.target === this.contentContainer) {\n this.scrollHeightDirty = true;\n shouldQueueUpdate = true;\n if (this.config.resizeDebugging) {\n console.log('Virtualizer: scroller size change', this.__id, {\n sizeChange: blockSize - lastSize,\n newSize: blockSize,\n });\n lastSize = blockSize;\n }\n }\n }\n }\n\n if (shouldQueueUpdate) {\n queueRender(this.computeRenderRangeAndEmit);\n }\n };\n\n private setupWindow() {\n if (this.root == null || !(this.root instanceof Document)) {\n throw new Error('Virtualizer.setupWindow: Invalid setup method');\n }\n window.addEventListener('scroll', this.handleWindowScroll, {\n passive: true,\n });\n window.addEventListener('resize', this.handleWindowResize, {\n passive: true,\n });\n this.resizeObserver?.observe(this.root.documentElement);\n }\n\n private setupElement(contentContainer: Element | undefined) {\n if (this.root == null || this.root instanceof Document) {\n throw new Error('Virtualizer.setupElement: Invalid setup method');\n }\n this.root.addEventListener('scroll', this.handleElementScroll, {\n passive: true,\n });\n this.resizeObserver?.observe(this.root);\n contentContainer ??= this.root.firstElementChild ?? undefined;\n if (contentContainer instanceof HTMLElement) {\n this.contentContainer = contentContainer;\n this.resizeObserver?.observe(contentContainer);\n }\n }\n\n cleanUp(): void {\n dequeueRender(this.computeRenderRangeAndEmit);\n this.resizeObserver?.disconnect();\n this.resizeObserver = undefined;\n this.intersectionObserver?.disconnect();\n this.intersectionObserver = undefined;\n this.root?.removeEventListener('scroll', this.handleElementScroll);\n window.removeEventListener('scroll', this.handleWindowScroll);\n window.removeEventListener('resize', this.handleWindowResize);\n this.root = undefined;\n this.contentContainer = undefined;\n this.observers.clear();\n this.visibleInstances.clear();\n this.instancesChanged.clear();\n this.reconcileQueue.clear();\n this.connectQueue.clear();\n this.visibleInstancesDirty = false;\n this.windowSpecs = { top: 0, bottom: 0 };\n this.scrollTop = 0;\n this.height = 0;\n this.scrollHeight = 0;\n this.scrollDirty = true;\n this.heightDirty = true;\n this.scrollHeightDirty = true;\n }\n\n getOffsetInScrollContainer(element: HTMLElement): number {\n return (\n this.getScrollTop() +\n getRelativeBoundingTop(element, this.getScrollContainerElement())\n );\n }\n\n connect(container: HTMLElement, instance: SubscribedInstance): () => void {\n if (this.observers.has(container)) {\n throw new Error('Virtualizer.connect: instance is already connected...');\n }\n // If we are racing against the intersectionObserver, then we should just\n // queue up the connection for when the observer does get set up\n if (this.intersectionObserver == null) {\n this.connectQueue.set(container, instance);\n } else {\n // FIXME(amadeus): Go through the connection phase a bit more closely...\n this.intersectionObserver.observe(container);\n this.observers.set(container, instance);\n this.instancesChanged.add(instance);\n this.markDOMDirty();\n queueRender(this.computeRenderRangeAndEmit);\n }\n return () => this.disconnect(container);\n }\n\n disconnect(container: HTMLElement): void {\n const instance = this.observers.get(container);\n this.connectQueue.delete(container);\n if (instance == null) {\n return;\n }\n this.intersectionObserver?.unobserve(container);\n this.observers.delete(container);\n this.instancesChanged.delete(instance);\n this.reconcileQueue.delete(instance);\n if (this.visibleInstances.delete(container)) {\n this.visibleInstancesDirty = true;\n }\n this.markDOMDirty();\n queueRender(this.computeRenderRangeAndEmit);\n }\n\n private handleWindowResize = () => {\n if (Virtualizer.__STOP || window.innerHeight === this.height) {\n return;\n }\n this.heightDirty = true;\n queueRender(this.computeRenderRangeAndEmit);\n };\n\n private handleWindowScroll = () => {\n if (\n Virtualizer.__STOP ||\n this.root == null ||\n !(this.root instanceof Document)\n ) {\n return;\n }\n this.scrollDirty = true;\n queueRender(this.computeRenderRangeAndEmit);\n };\n\n private handleElementScroll = () => {\n if (\n Virtualizer.__STOP ||\n this.root == null ||\n this.root instanceof Document\n ) {\n return;\n }\n this.scrollDirty = true;\n queueRender(this.computeRenderRangeAndEmit);\n };\n\n private computeRenderRangeAndEmit = () => {\n if (Virtualizer.__STOP) {\n return;\n }\n const wrapperDirty = this.heightDirty || this.scrollHeightDirty;\n let instancesHaveChanged = this.instancesChanged.size > 0;\n\n // If we got an emitted update from a bunch of instances, we should skip\n // the window check first and attempt to render with existing logic first\n // and then queue up a corrected render after\n if (this.instancesChanged.size === 0) {\n const windowSpecs = createWindowFromScrollPosition({\n scrollTop: this.getScrollTop(),\n height: this.getHeight(),\n scrollHeight: this.getScrollHeight(),\n overscrollSize: this.config.overscrollSize,\n });\n if (\n !wrapperDirty &&\n areVirtualWindowSpecsEqual(this.windowSpecs, windowSpecs) &&\n this.renderedObservers === this.observers.size &&\n !this.visibleInstancesDirty &&\n this.reconcileQueue.size === 0\n ) {\n return;\n }\n this.windowSpecs = windowSpecs;\n }\n this.visibleInstancesDirty = false;\n this.renderedObservers = this.observers.size;\n const anchor = this.getScrollAnchor(this.height);\n const updatedInstances = new Set<SubscribedInstance>();\n // NOTE(amadeus): If the wrapper is dirty, we need to force every component\n // to re-render\n for (const instance of wrapperDirty\n ? this.observers.values()\n : this.visibleInstances.values()) {\n if (instance.onRender(wrapperDirty)) {\n updatedInstances.add(instance);\n }\n }\n for (const instance of this.instancesChanged) {\n if (updatedInstances.has(instance)) continue;\n if (instance.onRender(wrapperDirty)) {\n updatedInstances.add(instance);\n }\n }\n\n this.scrollFix(anchor);\n\n for (const instance of updatedInstances) {\n this.reconcileQueue.delete(instance);\n instance.reconcileHeights();\n }\n // Reconcile externally-rendered instances that may have new heights\n for (const instance of this.reconcileQueue) {\n if (instance.reconcileHeights()) {\n instancesHaveChanged = true;\n }\n }\n this.reconcileQueue.clear();\n instancesHaveChanged ||= this.instancesChanged.size > 0;\n\n // Reconciliation reads virtualized offsets and can consume dirty geometry\n // flags, so mark after it when an instance update needs a corrected pass.\n if (instancesHaveChanged) {\n this.markDOMDirty();\n }\n\n if (instancesHaveChanged || wrapperDirty) {\n queueRender(this.computeRenderRangeAndEmit);\n }\n updatedInstances.clear();\n this.instancesChanged.clear();\n };\n\n private scrollFix(anchor: ScrollAnchor | undefined) {\n if (anchor == null) {\n return;\n }\n const scrollContainer = this.getScrollContainerElement();\n const { lineIndex, lineOffset, fileElement, fileOffset, fileTypeOffset } =\n anchor;\n if (lineIndex != null && lineOffset != null) {\n const element = fileElement.shadowRoot?.querySelector(\n `[data-line][data-line-index=\"${lineIndex}\"]`\n );\n if (element instanceof HTMLElement) {\n const top = getRelativeBoundingTop(element, scrollContainer);\n if (top !== lineOffset) {\n const scrollOffset = top - lineOffset;\n this.applyScrollFix(scrollOffset);\n }\n return;\n }\n }\n const top = getRelativeBoundingTop(fileElement, scrollContainer);\n if (fileTypeOffset === 'top') {\n if (top !== fileOffset) {\n this.applyScrollFix(top - fileOffset);\n }\n } else {\n const bottom = top + fileElement.getBoundingClientRect().height;\n if (bottom !== fileOffset) {\n this.applyScrollFix(bottom - fileOffset);\n }\n }\n }\n\n private applyScrollFix(scrollOffset: number) {\n if (this.root == null || this.root instanceof Document) {\n window.scrollTo({\n top: window.scrollY + scrollOffset,\n behavior: 'instant',\n });\n } else {\n this.root.scrollTo({\n top: this.root.scrollTop + scrollOffset,\n behavior: 'instant',\n });\n }\n // Because we fixed our scroll positions, it means something resized or\n // moved around, so we should mark everything as dirty so the\n // reconciliation call will get the latest data when figuring calling\n // .getOffsetInScrollContainer\n this.markDOMDirty();\n }\n\n // This function tries to figure out the closest file or line to the viewport\n // top that's visible to use as a relative marker for how to fix scroll\n // position after issuing dom updates\n private getScrollAnchor(viewportHeight: number): ScrollAnchor | undefined {\n const scrollContainer = this.getScrollContainerElement();\n let bestAnchor: ScrollAnchor | undefined;\n\n for (const [fileElement] of this.visibleInstances.entries()) {\n const fileTop = getRelativeBoundingTop(fileElement, scrollContainer);\n const fileBottom = fileTop + fileElement.offsetHeight;\n\n // Determine file offset and type based on position\n // Only use bottom anchor when entire file is above viewport\n let fileOffset: number;\n let fileTypeOffset: 'top' | 'bottom';\n if (fileBottom <= 0) {\n // Entire file is above viewport - use bottom as anchor\n fileOffset = fileBottom;\n fileTypeOffset = 'bottom';\n } else {\n // File is at least partially visible or below - use top\n fileOffset = fileTop;\n fileTypeOffset = 'top';\n }\n\n // Find the best line (first fully visible) within this file\n let bestLineIndex: string | undefined;\n let bestLineOffset: number | undefined;\n\n // Only search for lines if file potentially intersects viewport\n if (fileBottom > 0 && fileTop < viewportHeight) {\n for (const line of fileElement.shadowRoot?.querySelectorAll(\n '[data-line][data-line-index]'\n ) ?? []) {\n if (!(line instanceof HTMLElement)) continue;\n const lineIndex = line.dataset.lineIndex;\n if (lineIndex == null) continue;\n\n const lineOffset = getRelativeBoundingTop(line, scrollContainer);\n\n // Ignore lines with negative offsets (above viewport top)\n if (lineOffset < 0) continue;\n\n // First visible line in DOM order is the best one because\n // querySelectorAll will grab lines in order as they appear in the\n // DOM\n bestLineIndex = lineIndex;\n bestLineOffset = lineOffset;\n break;\n }\n }\n\n // If we already have an anchor with a visible line, skip files without one\n if (bestAnchor?.lineOffset != null && bestLineOffset == null) {\n continue;\n }\n\n // Decide if this file should become the new best anchor\n let shouldReplace = false;\n // If we don't already have an anchor we should set one\n if (bestAnchor == null) {\n shouldReplace = true;\n }\n // If we found a better line anchor, we should replace the old one\n else if (\n bestLineOffset != null &&\n (bestAnchor.lineOffset == null ||\n bestLineOffset < bestAnchor.lineOffset)\n ) {\n shouldReplace = true;\n }\n // Otherwise we need to compare file only anchors\n else if (bestLineOffset == null && bestAnchor.lineOffset == null) {\n // Favor files with their tops in view\n if (\n fileOffset >= 0 &&\n (bestAnchor.fileOffset < 0 || fileOffset < bestAnchor.fileOffset)\n ) {\n shouldReplace = true;\n }\n // Or the closest file\n else if (\n fileOffset < 0 &&\n bestAnchor.fileOffset < 0 &&\n fileOffset > bestAnchor.fileOffset\n ) {\n shouldReplace = true;\n }\n }\n\n if (shouldReplace) {\n bestAnchor = {\n fileElement,\n fileTypeOffset,\n fileOffset,\n lineIndex: bestLineIndex,\n lineOffset: bestLineOffset,\n };\n }\n }\n\n return bestAnchor;\n }\n\n private handleIntersectionChange = (\n entries: IntersectionObserverEntry[]\n ): void => {\n this.scrollDirty = true;\n for (const { target, isIntersecting } of entries) {\n if (!(target instanceof HTMLElement)) {\n throw new Error(\n 'Virtualizer.handleIntersectionChange: target not an HTMLElement'\n );\n }\n const instance = this.observers.get(target);\n // IntersectionObserver delivers entries asynchronously, so an entry can\n // arrive after the target was unobserved via disconnect() or releaseElement().\n if (instance == null) {\n continue;\n }\n if (isIntersecting && !this.visibleInstances.has(target)) {\n instance.setVisibility(true);\n this.visibleInstances.set(target, instance);\n this.visibleInstancesDirty = true;\n } else if (!isIntersecting && this.visibleInstances.has(target)) {\n instance.setVisibility(false);\n this.visibleInstances.delete(target);\n this.visibleInstancesDirty = true;\n }\n }\n\n if (this.visibleInstancesDirty) {\n // Since this call is already debounced, should we just call\n // computeRenderRangeAndEmit directly?\n queueRender(this.computeRenderRangeAndEmit);\n }\n // Debug logging for visible instances\n // console.log(\n // 'handleIntersectionChange',\n // ...Array.from(this.visibleInstances.keys())\n // );\n };\n\n /** Return the logical vertical position for the scroll container */\n public getScrollTop(): number {\n if (!this.scrollDirty) {\n return this.scrollTop;\n }\n this.scrollDirty = false;\n let scrollTop = (() => {\n if (this.root == null) {\n return 0;\n }\n if (this.root instanceof Document) {\n return window.scrollY;\n }\n return this.root.scrollTop;\n })();\n\n // Lets always make sure to clamp scroll position cases of\n // over/bounce scroll\n scrollTop = this.clampScrollTop(scrollTop);\n this.scrollTop = scrollTop;\n return scrollTop;\n }\n\n /** Scroll to a logical vertical position and queue the normal render pass. */\n public scrollTo({ top, behavior = 'auto' }: VirtualizerScrollOptions): void {\n const { root } = this;\n if (root == null) {\n return;\n }\n\n const scrollTop = this.clampScrollTop(top);\n if (root instanceof Document) {\n window.scrollTo({ top: scrollTop, behavior });\n } else {\n root.scrollTo({ top: scrollTop, behavior });\n }\n this.scrollDirty = true;\n queueRender(this.computeRenderRangeAndEmit);\n }\n\n private clampScrollTop(scrollTop: number): number {\n return Math.max(\n 0,\n Math.min(scrollTop, this.getScrollHeight() - this.getHeight())\n );\n }\n\n private getScrollHeight() {\n if (!this.scrollHeightDirty) {\n return this.scrollHeight;\n }\n this.scrollHeightDirty = false;\n this.scrollHeight = (() => {\n if (this.root == null) {\n return 0;\n }\n if (this.root instanceof Document) {\n return this.root.documentElement.scrollHeight;\n }\n return this.root.scrollHeight;\n })();\n return this.scrollHeight;\n }\n\n private getHeight() {\n if (!this.heightDirty) {\n return this.height;\n }\n this.heightDirty = false;\n this.height = (() => {\n if (this.root == null) {\n return 0;\n }\n if (this.root instanceof Document) {\n return globalThis.innerHeight;\n }\n return this.root.getBoundingClientRect().height;\n })();\n return this.height;\n }\n\n markDOMDirty(): void {\n this.scrollDirty = true;\n this.scrollHeightDirty = true;\n this.heightDirty = true;\n }\n\n private getScrollContainerElement(): HTMLElement | undefined {\n return this.root == null || this.root instanceof Document\n ? undefined\n : this.root;\n }\n}\n\n// This function is like a generalized getBoundingClientRect for it's relative\n// scroll container\nfunction getRelativeBoundingTop(\n element: HTMLElement,\n scrollContainer: HTMLElement | undefined\n) {\n const rect = element.getBoundingClientRect();\n const scrollContainerTop = scrollContainer?.getBoundingClientRect().top ?? 0;\n return rect.top - scrollContainerTop;\n}\n", "import type { Page } from \"@ovvi/plugin-api\"\nimport {\n type FileDiffMetadata,\n type FileDiffOptions,\n parsePatchFiles,\n preloadHighlighter,\n VirtualizedFileDiff,\n Virtualizer,\n} from \"@pierre/diffs\"\nimport {\n coalesce, element, failed as toast, fileIcon, home, type How, how, keep, kept, menu, nameAndFolder, open, ovvi, sf,\n} from \"./lib\"\n\nconst MARGIN = 1500\nconst letters = { change: \"M\", \"rename-pure\": \"R\", \"rename-changed\": \"R\", new: \"A\", deleted: \"D\" }\n/** pierre lays out on the next frame. */\nconst afterLayout = (fn: () => void) => requestAnimationFrame(() => requestAnimationFrame(fn))\n\ntype Box = { diff: FileDiffMetadata; node: HTMLElement; row: HTMLElement; lines: HTMLElement; folded: boolean\n near?: boolean; view?: VirtualizedFileDiff<undefined> }\n\nfunction ago(date: Date) {\n const seconds = (date.getTime() - Date.now()) / 1000\n const units: [Intl.RelativeTimeFormatUnit, number][] = [[\"year\", 31536000], [\"month\", 2592000], [\"week\", 604800],\n [\"day\", 86400], [\"hour\", 3600], [\"minute\", 60]]\n const [unit, size] = units.find(([, size]) => Math.abs(seconds) >= size) ?? [\"second\", 1]\n return new Intl.RelativeTimeFormat(undefined, { numeric: \"auto\" }).format(Math.round(seconds / size), unit)\n}\n\nfunction sums(file: FileDiffMetadata) {\n let added = 0\n let removed = 0\n for (const hunk of file.hunks) {\n added += hunk.additionLines\n removed += hunk.deletionLines\n }\n return { added, removed }\n}\n\nfunction counts(file: FileDiffMetadata) {\n const { added, removed } = sums(file)\n return [\n element(\"span\", \"added\", added ? `+${added}` : \"\"),\n element(\"span\", \"removed\", removed ? `\u2212${removed}` : \"\"),\n ]\n}\n\nfunction letter(file: FileDiffMetadata) {\n return element(\"span\", `letter ${letters[file.type]}`, letters[file.type])\n}\n\nfunction blocks(file: FileDiffMetadata) {\n return file.hunks.flatMap((hunk) => {\n let line = hunk.additionStart\n let old = hunk.deletionStart\n return hunk.hunkContent.flatMap((content) => {\n if (content.type === \"context\") {\n line += content.lines\n old += content.lines\n return []\n }\n const place = content.additions\n ? { id: file.name, lineNumber: line, side: \"additions\" as const }\n : { id: file.name, lineNumber: old, side: \"deletions\" as const }\n line += content.additions\n old += content.deletions\n return [place]\n })\n })\n}\n\nfunction newLine(file: FileDiffMetadata, number: number) {\n for (const hunk of file.hunks) {\n let line = hunk.additionStart\n let old = hunk.deletionStart\n for (const content of hunk.hunkContent) {\n const context = content.type === \"context\"\n const span = context ? content.lines : content.deletions\n if (number >= old && number < old + span) return context ? line + number - old : line + content.additions\n line += context ? content.lines : content.additions\n old += span\n }\n }\n}\n\nfunction text(file: FileDiffMetadata) {\n return `${file.deletionLines.join(\"\")}\\0${file.additionLines.join(\"\")}`\n}\n\nexport async function make(place: Page, root: string, source: string) {\n const api = place.ovvi\n const page = element(\"div\")\n page.id = \"diff\"\n const nav = element(\"nav\", \"list ovvi-sidebar\")\n const main = element(\"main\", \"diff\")\n const content = element(\"div\", \"content\")\n const failure = element(\"p\", \"failure\")\n const clean = element(\"div\", \"placeholder\")\n clean.hidden = true\n clean.innerHTML = `<span class=\"symbol\"></span><h2></h2>`\n const find = element(\"div\", \"find\")\n find.hidden = true\n find.innerHTML = `<input class=\"find-field\" placeholder=\"Filter\" aria-label=\"Filter\" spellcheck=\"false\"><span\n class=\"find-count\" role=\"status\"></span><button class=\"find-icon\" aria-label=\"Close Filter\" title=\"Close\"></button>`\n const field = find.querySelector(\"input\")!, count = find.querySelector<HTMLElement>(\".find-count\")!\n const about = element(\"header\", \"about\")\n content.append(about)\n main.append(content)\n page.append(nav, main, failure, clean, find)\n place.element.append(page)\n\n let patch: string | undefined\n let files: FileDiffMetadata[] = []\n let boxes = new Map<string, Box>()\n let changes: { id: string; lineNumber: number; side: \"additions\" | \"deletions\" }[] = []\n let change = -1\n let filter = \"\"\n const viewed = new Map<string, string>()\n const own = kept()\n let split = (own.layout ?? ovvi.settings.get(\"diff-layout\")) === \"split\"\n let wrap = own.wrap ?? ovvi.settings.get<boolean>(\"wrap\")\n let list = own.list ?? ovvi.settings.get<boolean>(\"file-list\")\n nav.toggleAttribute(\"data-closed\", !list)\n\n // A box keeps the whole file's height, so its header is sticky in CSS alone.\n const virtualizer = new Virtualizer()\n virtualizer.setup(main, content)\n // Each view costs about 1.5 ms (pierre puts its icons in each box): 1.5 s for 1,000 files at once.\n const owners = new WeakMap<Element, Box>()\n const nearby = new IntersectionObserver((entries) => steady(() => {\n for (const entry of entries) {\n const box = owners.get(entry.target)\n if (!entry.isIntersecting || !box || box.near) continue\n box.near = true\n show(box)\n }\n }), { root: main, rootMargin: `${MARGIN}px 0px` })\n place.keep(() => {\n nearby.disconnect()\n for (const box of boxes.values()) box.view?.cleanUp()\n virtualizer.cleanUp()\n })\n\n const options: FileDiffOptions<undefined, undefined> = {\n theme: { dark: \"pierre-dark\", light: \"pierre-light\" },\n themeType: ovvi.theme.dark ? \"dark\" : \"light\",\n diffStyle: split ? \"split\" : \"unified\",\n overflow: overflow(),\n lineDiffType: \"word\",\n // `N unmodified lines`, not expandable: that needs each file's whole text.\n hunkSeparators: \"line-info-basic\",\n disableFileHeader: true,\n unsafeCSS: `\n :host {\n --diffs-light-bg: transparent !important;\n --diffs-dark-bg: transparent !important;\n --diffs-addition-color-override: var(--finished);\n --diffs-deletion-color-override: var(--error);\n --diffs-modified-color-override: var(--working);\n --diffs-bg-separator-override: transparent;\n }\n [data-line-type=change-addition] {\n --diffs-computed-diff-line-bg: color-mix(in srgb, var(--finished) 10%, transparent) !important;\n }\n [data-line-type=change-deletion] {\n --diffs-computed-diff-line-bg: color-mix(in srgb, var(--error) 10%, transparent) !important;\n }\n [data-line-type=change-addition] [data-diff-span] {\n background-color: color-mix(in srgb, var(--finished) 28%, transparent) !important;\n }\n [data-line-type=change-deletion] [data-diff-span] {\n background-color: color-mix(in srgb, var(--error) 28%, transparent) !important;\n }\n [data-separator] { border-block: 0.5px solid var(--divider) }\n [data-separator-content] { background: none !important; color: var(--dim) }`,\n }\n\n function fileOptions(box: Box): FileDiffOptions<undefined, undefined> {\n return {\n ...options,\n onLineClick: ({ event, lineNumber, annotationSide }) => {\n if ((event.metaKey || event.altKey) && box.diff.type !== \"deleted\") {\n openFile(box.diff.name, annotationSide === \"additions\" ? lineNumber : newLine(box.diff, lineNumber), how(event))\n }\n },\n }\n }\n\n function fileRow(box: Box) {\n const diff = box.diff, row = element(\"div\", \"file\"), disclosure = element(\"button\", \"disclosure\", \"\u203A\")\n disclosure.ariaLabel = \"Show or hide the file\"\n disclosure.onclick = () => collapse(diff.name, !box.folded)\n const [base, dir] = nameAndFolder(diff.name)\n const name = element(\"span\", \"name\", base)\n const folder = element(\"span\", \"folder\", diff.prevName && diff.prevName !== diff.name ? `from ${diff.prevName}` : dir)\n row.title = diff.name\n row.append(disclosure, fileIcon(diff.name), name, folder, ...counts(diff), letter(diff), actions(diff))\n return row\n }\n\n function actions(diff: FileDiffMetadata) {\n const box = element(\"span\", \"actions\"), label = element(\"label\", \"mark\")\n const check = element(\"input\")\n check.type = \"checkbox\"\n check.ariaLabel = `Viewed ${diff.name}`\n check.checked = viewed.has(diff.name)\n check.onchange = () => {\n if (check.checked) viewed.set(diff.name, text(diff))\n else viewed.delete(diff.name)\n collapse(diff.name, check.checked)\n nav.querySelector(`[data-id=\"${CSS.escape(diff.name)}\"]`)?.classList.toggle(\"viewed\", check.checked)\n }\n label.append(check, \"Viewed\")\n box.append(label)\n if (diff.type !== \"deleted\") {\n const open = element(\"button\", \"open\", \"Open File\")\n open.ariaLabel = `Open ${diff.name}`\n open.onclick = (event) => openFile(diff.name, undefined, how(event))\n open.oncontextmenu = (event) => void menu(event, `${root}/${diff.name}`, {})\n box.append(open)\n }\n return box\n }\n\n /** pierre's heights: 20 pt a row, 32 pt a hunk's gap, 8 pt above and below; the wrap is made up when it draws. */\n function show(box: Box) {\n const bare = box.folded || !box.diff.hunks.length\n box.node.classList.toggle(\"folded\", bare)\n box.lines.hidden = bare\n box.row.querySelector(\".disclosure\")!.classList.toggle(\"shut\", box.folded)\n if (bare || box.view) return\n if (!box.near) {\n box.lines.style.height = `${(split ? box.diff.splitLineCount : box.diff.unifiedLineCount) * 20 + box.diff.hunks.length * 32 + 16}px`\n return\n }\n box.lines.style.height = \"\"\n box.view = new VirtualizedFileDiff(fileOptions(box), virtualizer)\n box.view.render({ fileDiff: box.diff, fileContainer: box.lines })\n }\n\n /** A box above the first box in view that changes height moves it. pierre's own anchor comes a frame later;\n * `overflow-anchor` is off, as it would move it twice. */\n function steady(work: () => void) {\n if (!main.scrollTop) return work()\n const view = main.getBoundingClientRect().top\n const anchor = [...boxes.values()].find((box) => box.node.getBoundingClientRect().bottom > view)\n const offset = anchor ? top(anchor.node) - main.scrollTop : 0\n work()\n if (anchor?.node.isConnected) main.scrollTop = anchor.node.hidden ? 0 : top(anchor.node) - offset\n }\n\n function describe(facts: Awaited<ReturnType<typeof ovvi.git.show>> | undefined) {\n about.replaceChildren()\n document.title = facts?.subject ?? \"\"\n if (!facts) return\n const date = new Date(facts.date), list = element(\"dl\")\n const fact = (term: string, ...value: (Node | string)[]) => {\n const line = element(\"dd\")\n line.append(...value)\n list.append(element(\"dt\", \"\", term), line)\n }\n fact(\"Author\", facts.author, element(\"span\", \"dim\", ` <${facts.email}>`))\n fact(\"Date\", ago(date), element(\"span\", \"dim\", ` \u00B7 ${date.toLocaleString(undefined, { dateStyle: \"medium\", timeStyle: \"short\" })}`))\n const copy = element(\"button\", \"hash\", facts.hash.slice(0, 10))\n copy.title = \"Copy\"\n copy.ariaLabel = `Copy ${facts.hash}`\n copy.onclick = () => ovvi.clipboard.write(facts.hash).then(() => {\n copy.textContent = \"Copied\"\n setTimeout(() => (copy.textContent = facts.hash.slice(0, 10)), 1200)\n }, toast)\n fact(\"Commit\", copy)\n if (facts.parents.length) {\n fact(facts.parents.length > 1 ? \"Parents\" : \"Parent\", ...facts.parents.map((parent) => {\n const button = element(\"button\", \"hash\", parent.slice(0, 10))\n button.ariaLabel = `Parent ${parent}`\n button.onclick = (event) => open(`${home(root)} ${parent}`, { how: how(event, false), plugin: \"git\" })\n button.oncontextmenu = (event) => void menu(event, `${home(root)} ${parent}`, { plugin: \"git\" })\n return button\n }))\n }\n about.append(element(\"h1\", \"\", facts.subject), ...(facts.body ? [element(\"p\", \"body\", facts.body)] : []), list)\n }\n\n function draw(next: string) {\n patch = next\n files = parsePatchFiles(patch).flatMap((parsed) => parsed.files)\n steady(() => put(files))\n listFiles(files)\n sift()\n }\n\n function sift() {\n const shows = (name: string) => name.toLowerCase().includes(filter)\n steady(() => {\n for (const [name, box] of boxes) box.node.hidden = !shows(name)\n })\n for (const node of nav.querySelectorAll<HTMLElement>(\".row\")) node.hidden = !shows(node.dataset.id!)\n const kept = files.filter((file) => shows(file.name))\n count.textContent = filter ? String(kept.length) : \"\"\n changes = kept.flatMap(blocks)\n shown(files.length > 0 && !kept.length)\n }\n\n function put(files: FileDiffMetadata[]) {\n const was = boxes, drawn: Box[] = []\n boxes = new Map()\n for (const file of files) {\n let box = was.get(file.name)\n was.delete(file.name)\n if (!box) {\n const { added, removed } = sums(file), node = element(\"section\", \"box\")\n node.hidden = !file.name.toLowerCase().includes(filter)\n box = { diff: file, node, row: node, lines: document.createElement(\"diffs-container\"), folded: added + removed > 2000 }\n owners.set(node, box)\n nearby.observe(node)\n } else if (text(box.diff) !== text(file) || box.diff.type !== file.type || box.diff.prevName !== file.prevName) {\n box.diff = file\n if (viewed.delete(file.name)) box.folded = false\n drawn.push(box)\n } else {\n boxes.set(file.name, box)\n continue\n }\n box.row = fileRow(box)\n box.node.replaceChildren(box.row, box.lines)\n boxes.set(file.name, box)\n }\n for (const [name, box] of was) {\n viewed.delete(name)\n nearby.unobserve(box.node)\n box.view?.cleanUp()\n }\n // Moved only when the order changed: a move lays the box out again.\n const order = [about, ...[...boxes.values()].map((box) => box.node)]\n if (order.some((node, index) => content.children[index] !== node) || content.children.length !== order.length) {\n content.replaceChildren(...order)\n }\n // Once in place: a file's lines draw by where its box sits.\n for (const box of boxes.values()) show(box)\n const { top: from, bottom: to } = main.getBoundingClientRect()\n const near = [...boxes.values()].filter((box) => {\n const { top, bottom } = box.node.getBoundingClientRect()\n return !box.near && bottom > from - MARGIN && top < to + MARGIN\n })\n for (const box of near) {\n box.near = true\n show(box)\n }\n for (const box of drawn) box.view?.render({ fileDiff: box.diff, fileContainer: box.lines })\n }\n\n function listFiles(files: FileDiffMetadata[]) {\n const title = element(\"header\", \"title\")\n title.append(element(\"h2\", \"\", \"Files\"), element(\"span\", \"count\", files.length ? String(files.length) : \"\"))\n nav.replaceChildren(title)\n for (const file of files) {\n const button = element(\"button\", viewed.has(file.name) ? \"row viewed\" : \"row\")\n button.dataset.id = file.name\n const [name, folder] = nameAndFolder(file.name)\n button.append(\n fileIcon(file.name),\n element(\"span\", \"name\", name),\n element(\"span\", \"folder\", folder),\n ...counts(file),\n letter(file),\n )\n button.title = file.name\n button.ariaLabel = file.name\n button.onclick = () => reveal(file.name)\n nav.append(button)\n }\n }\n\n function shown(none: boolean) {\n nav.hidden = !files.length\n clean.hidden = (Boolean(files.length) || patch === undefined) && !none\n clean.querySelector(\"h2\")!.textContent = none ? \"No matching files\" : \"No changes\"\n clean.style.setProperty(\"--symbol\", `var(${sf(none ? \"magnifyingglass\" : \"checkmark.circle\")})`)\n listButton()\n }\n\n /** Its symbol says whether the list shows: with no files, none does. */\n function listButton() {\n api.controls.set(\"diff.file-list\", { enabled: files.length > 0, value: list && files.length > 0 })\n }\n\n function openFile(name: string, line: number | undefined, how: How) {\n open(`${root}/${name}`, { how, at: line ? String(line) : undefined })\n }\n\n function top(node: HTMLElement) {\n return node.getBoundingClientRect().top - main.getBoundingClientRect().top + main.scrollTop\n }\n\n let moves = 0\n let stepped = 0\n main.addEventListener(\"wheel\", () => moves++, { passive: true })\n main.addEventListener(\"pointerdown\", () => moves++)\n\n function where(block: (typeof changes)[number]) {\n const box = boxes.get(block.id)!\n const line = box.folded ? undefined : box.view?.getLinePosition(block.lineNumber, block.side)\n return line ? top(box.lines) + line.top + line.height / 2 : top(box.node)\n }\n\n /** Wrapped lines take their heights once drawn, a frame later: then once more. */\n function scrollToChange(block: (typeof changes)[number]) {\n const box = boxes.get(block.id)\n if (!box) return\n if (box.folded) collapse(block.id, false)\n box.near = true\n show(box)\n const aim = () => (main.scrollTop = where(block) - main.clientHeight / 2)\n aim()\n // Not after another step or the user's scroll meanwhile (pierre's own fixes of the scroll still aim again).\n const was = { change, moves }\n if (options.overflow === \"wrap\") {\n afterLayout(() => change === was.change && moves === was.moves && aim())\n }\n }\n\n function keepChange() {\n if (changes[change]) scrollToChange(changes[change])\n }\n\n function collapse(id: string, folded: boolean) {\n const box = boxes.get(id)!\n box.folded = folded\n show(box)\n if (folded && top(box.node) < main.scrollTop) main.scrollTop = top(box.node)\n }\n\n function reveal(id: string) {\n const box = boxes.get(id)!\n if (box.node.hidden) closeFind()\n if (box.folded) collapse(id, false)\n main.scrollTop = top(box.node)\n const order = (name: string) => files.findIndex((file) => file.name === name)\n const next = changes.findIndex((block) => order(block.id) >= order(id))\n change = (next < 0 ? changes.length : next) - 0.5\n stepped = moves\n }\n\n api.on(\"theme\", (theme) => {\n options.themeType = theme.dark ? \"dark\" : \"light\"\n for (const box of boxes.values()) box.view?.setThemeType(options.themeType)\n })\n\n const refresh = coalesce(async () => apply(await read()))\n\n const read = () => ovvi.git.diff(root, source).catch((error: Error) => error)\n\n function apply(next: string | Error) {\n if (!(next instanceof Error)) {\n if (next !== patch) draw(next)\n } else if (patch === undefined) failure.textContent = next.message\n }\n\n /** Side by Side always wraps: a line scrolled past its narrow column is cut off where a click lands. */\n function overflow() {\n return split || wrap ? \"wrap\" : \"scroll\"\n }\n\n function layout(next: { split?: boolean; wrap?: boolean }) {\n split = next.split ?? split\n wrap = next.wrap ?? wrap\n api.controls.set(\"diff.wrap\", { enabled: !split })\n options.diffStyle = split ? \"split\" : \"unified\"\n options.overflow = overflow()\n steady(() => {\n for (const box of boxes.values()) {\n if (box.view) box.view.setOptions(fileOptions(box))\n else show(box)\n }\n })\n // Once the files have their new heights: pierre lays them out on the next frame.\n afterLayout(keepChange)\n }\n\n function toggleList(chosen = true) {\n list = !list\n nav.toggleAttribute(\"data-closed\", !list)\n if (chosen) keep({ list })\n listButton()\n // With Reduce Motion there is no slide to wait for.\n if (matchMedia(\"(prefers-reduced-motion: reduce)\").matches) afterLayout(keepChange)\n }\n // After the slide: once, not for each of its properties.\n nav.addEventListener(\"transitionend\", (event) => event.target === nav && event.propertyName === \"visibility\" && keepChange())\n\n function step(by: 1 | -1) {\n if (!changes.length) return\n const view = main.scrollTop + 32, at = changes[change] ? where(changes[change]) : -1\n if (stepped !== moves && (at <= view || at >= main.scrollTop + main.clientHeight)) {\n const below = changes.findIndex((block) => where(block) > view)\n change = (below < 0 ? changes.length : below) - 0.5\n }\n stepped = moves\n const next = by > 0 ? Math.floor(change) + 1 : Math.ceil(change) - 1\n change = Math.min(Math.max(next, 0), changes.length - 1)\n scrollToChange(changes[change])\n }\n\n function stepFile(by: 1 | -1) {\n // At the end: the files left all show, and a reveal could not move the view.\n if (by > 0 && main.scrollTop >= main.scrollHeight - main.clientHeight - 1) return\n const tops = [...boxes].filter(([, box]) => !box.node.hidden).map(([id, box]) => ({ id, at: top(box.node) }))\n const to = by > 0 ? tops.find(({ at }) => at > main.scrollTop + 1) : tops.findLast(({ at }) => at < main.scrollTop - 1)\n if (to) reveal(to.id)\n }\n\n api.on(\"control\", ({ id, value }) => {\n if (id === \"diff.home\") ovvi.card.go(home(root))\n else if (id === \"diff.layout\") {\n keep({ layout: String(value) })\n layout({ split: value === \"split\" })\n } else if (id === \"diff.wrap\") {\n keep({ wrap: value === true })\n layout({ wrap: value === true })\n } else if (id === \"diff.file-list\") toggleList()\n else if (id === \"diff.previous\") step(-1)\n else if (id === \"diff.next\") step(1)\n })\n\n api.on(\"findNext\", () => step(1))\n api.on(\"findPrevious\", () => step(-1))\n api.on(\"find\", () => {\n find.hidden = false\n field.select()\n field.focus()\n })\n function closeFind() {\n find.hidden = true\n field.value = \"\"\n field.blur()\n filtered()\n }\n function filtered() {\n if (filter === field.value.toLowerCase()) return\n filter = field.value.toLowerCase()\n change = -1\n stepped = -1\n sift()\n }\n field.oninput = filtered\n field.onkeydown = (event) => {\n if (event.key === \"Escape\") closeFind()\n else if (event.key === \"Enter\") field.blur()\n else return\n event.preventDefault()\n }\n find.querySelector(\"button\")!.onclick = closeFind\n const keys = (event: KeyboardEvent) => {\n if (!place.shown || event.metaKey || event.ctrlKey || event.target === field) return\n if (event.key === \"]\") step(1)\n else if (event.key === \"[\") step(-1)\n else if (event.key === \"}\") stepFile(1)\n else if (event.key === \"{\") stepFile(-1)\n else if (event.key === \"Escape\" && !find.hidden) closeFind()\n else return\n event.preventDefault()\n }\n document.addEventListener(\"keydown\", keys)\n place.keep(() => document.removeEventListener(\"keydown\", keys))\n // Only the working tree changes.\n api.files.watch(root, () => (source === \"uncommitted\" || patch === undefined) && void refresh())\n listButton()\n api.controls.set(\"diff.wrap\", { enabled: !split, value: wrap })\n api.controls.set(\"diff.layout\", { value: split ? \"split\" : \"unified\" })\n api.on(\"settings\", (changed) => {\n const own = kept()\n if (\"diff-layout\" in changed && own.layout === undefined) {\n api.controls.set(\"diff.layout\", { value: String(changed[\"diff-layout\"]) })\n layout({ split: changed[\"diff-layout\"] === \"split\" })\n }\n if (\"wrap\" in changed && own.wrap === undefined) {\n api.controls.set(\"diff.wrap\", { value: changed.wrap === true })\n layout({ wrap: changed.wrap === true })\n }\n if (\"file-list\" in changed && own.list === undefined && (changed[\"file-list\"] === true) !== list) toggleList(false)\n })\n // Read first, then draw all of it in one go: the shown page stays until then. The themes first too: a file takes its\n // height only once they are in.\n const [next, facts] = await Promise.all([read(), source === \"uncommitted\"\n ? undefined\n : ovvi.git.show(root, source).catch(() => undefined),\n preloadHighlighter({ themes: [...new Set(Object.values(options.theme!))], langs: [] }).catch(console.error)])\n describe(facts)\n apply(next)\n if (place.at && files.some((file) => file.name === place.at)) reveal(place.at)\n api.on(\"place\", ({ at }) => at && files.some((file) => file.name === at) && reveal(at))\n}\n"],
5
- "mappings": "snBAGA,SAAgBA,GACdC,EAAsCC,GACnB,CACnB,IAAMC,EAA+B,CAAC,EACtC,OAAI,OAAOF,GAAU,SACnBE,EAAU,KAAKF,CAAK,GAEpBE,EAAU,KAAKF,EAAM,IAAI,EACzBE,EAAU,KAAKF,EAAM,KAAK,GAErBE,CACT,CCJA,SAAgBC,GACdC,EACAC,EAAmDC,GAAuB,EACjE,CAET,OAAI,OAAOD,GAAgB,UAAYA,EAAY,WAC1C,IAGP,OAAOA,GAAgB,SACnBE,GAAy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eResolver", "getThemes", "highlighter", "createHighlighter", "type", "resolvedType", "resolveHighlighterType", "acquireHighlighterType", "HighlightsHighlighter", "ShikiHighlighter", "releaseHighlighterType", "getSharedHighlighter", "themes", "langs", "preferredHighlighter", "dropDisposedHighlighter", "cached", "getHighlighterType", "instance", "error", "HighlighterDisposedError", "getHighlighterIfLoaded", "theme", "lang", "langs", "dropDisposedHighlighter", "instance", "highlighter", "areThemesAttached", "preloadHighlighter", "options", "getSharedHighlighter", "callbacks", "frameId", "queueRender", "callback", "render", "dequeueRender", "render", "time", "toIterate", "callbacks", "callback", "error", "frameId", "areObjectsEqual", "objA", "objB", "omitKeys", "omitSet", "keysA", "keysBSet", "key", "areThemesEqual", "themeA", "themeB", "areOptionsEqual", "optionsA", "optionsB", "themeA", "DEFAULT_THEMES", "themeB", "diffOptsA", "getParseDiffOptions", "diffOptsB", "areThemesEqual", "areObjectsEqual", "options", "areSelectionsEqual", "selectionA", "selectionB", "createWindowFromScrollPosition", "scrollTop", "scrollHeight", "height", "fitPerfectly", "fitPerfectlyOverscroll", "overscrollSize", "windowHeight", "effectiveHeight", "top", "bottom", "createGutterUtilityElement", "createHastElement", "createIconElement", "areSelectionPointsEqual", "a", "b", "isGutterUtilityPath", "path", "element", "InteractionManager", "mode", "options", "dequeueRender", "pre", "usesCustomGutterUtility", "enableGutterUtility", "range", "isRangeChange", "areSelectionsEqual", "lineNumberOnly", "isStyleChange", "lineNumber", "side", "isLineChange", "gutterUtilityLine", "event", "onHunkExpand", "onLineClick", "onLineNumberClick", "onTokenClick", "onMergeConflictActionClick", "isGutterUtilityPath", "debugLogIfEnabled", "lineHoverHighlight", "onLineEnter", "onLineLeave", "onTokenEnter", "onTokenLeave", "__debugPointerEvents", "eventType", "composedPath", "target", "sameLine", "isHoverableLinePointerTarget", "isTokenPointerTarget", "isMergeConflictActionPointerTarget", "isExpandoPointerTarget", "eventBase", "enableLineSelection", "onGutterUtilityClick", "enableGutterSelection", "shouldAttachPointerListeners", "reasons", "hasActiveLineSelectionSession", "hasActiveGutterSelectionSession", "shouldHaveInteractiveLines", "shouldHaveInteractiveLineNumbers", "path", "pointerInfo", "eventSide", "lineIndex", "rowRange", "useStart", "point", "selectedEndpoints", "anchor", "areSelectionPointsEqual", "session", "completedRange", "hoveredLine", "hoveredToken", "useCustomGutterUtility", "tempDiv", "hastToHtml", "createGutterUtilityElement", "utilityButton", "isLinePointerTarget", "endpoints", "line", "start", "end", "startIndex", "endIndex", "indexes", "candidates", "element", "getElementPath", "requireNumberColumn", "excludeUtility", "coordinatePath", "coordinateTarget", "row", "closestSelectableRow", "annotatedLine", "annotationRowFromSlot", "selectionPointFromAnnotationSlotName", "getAnnotationSlotName", "root", "elementFromPointRoot", "hasElementFromPoint", "getLineIndex", "currentLine", "emitChange", "previousRange", "nextRange", "anchorSide", "anchorLine", "queueRender", "selectedRange", "split", "startIndexes", "finalIndexes", "state", "source", "selectedLines", "selectedRowRange", "editorActiveLine", "editorRowRange", "codeElements", "columns", "code", "renderSelectedLines", "renderEditorActiveLine", "gutter", "content", "renderState", "selectedLinesChanged", "areLineRenderStatesEqual", "editorActiveLineChanged", "selectedLinesComplete", "column", "editorActiveLineComplete", "selectedFirst", "selectedLast", "selectedIsSingle", "editorLineIndex", "finalLineIndex", "len", "i", "contentElement", "gutterElement", "attributeValue", "lineCharEnd", "lineCharStart", "tokenElement", "tokenText", "current", "endSide", "numberColumn", "lineType", "codeElement", "lineElement", "lineIndexValue", "numberElement", "tokenInfo", "expandInfo", "mergeConflictActionTarget", "resolutionValue", "conflictIndexValue", "conflictIndex", "isMergeConflictResolution", "startAttr", "columnNumber", "getLineTypeFromElement", "lineAttr", "expandIndexValue", "expandIndex", "queryHTMLElement", "splitLineIndex", "getAnnotationSide", "lineIndexes", "value", "pluckInteractionOptions", "enableTokenInteractionsOnWhitespace", "renderGutterUtility", "controlledSelection", "onLineSelected", "onLineSelectionStart", "onLineSelectionChange", "onLineSelectionEnd", "resolveEnableGutterUtilityOption", "parent", "query", "annotationRow", "previousRow", "slotted", "slottedElement", "slotName", "match", "areSelectionRangesEqual", "first", "second", "debugLogType", "logIfType", "args", "ResizeManager", "resizeObserver", "entries", "entriesByManager", "entry", "manager", "managerEntries", "pre", "disableAnnotations", "columnVariables", "annotationUpdates", "applyColumnVariables", "columnCount", "observedNodes", "element", "codeElement", "item", "numberElement", "syncColumnVariableMode", "annotationElements", "elementMap", "lineAnnotation", "pairs", "key", "pair", "container1", "container2", "child1", "child2", "child1Height", "child2Height", "pendingUpdate", "cleanupStaleCodeItem", "cleanupStaleAnnotationItem", "managersByElement", "owner", "codeUpdates", "target", "borderBoxSize", "contentBoxSize", "column", "update", "inlineSize", "queuedUpdates", "nextCodeWidth", "resolveCodeWidth", "nextNumberWidth", "resolveNumberWidth", "codeWidthChanged", "numberWidthChanged", "applyCodeColumnVariables", "newHeight", "width", "removeCodeColumnVariables", "codeWidth", "numberWidth", "targetWidth", "areLanguagesAttached", "languages", "highlighter", "names", "name", "AttachedLanguages", "areRenderRangesEqual", "renderRangeA", "renderRangeB", "createAnnotationElement", "span", "createHastElement", "slotId", "getIconForType", "type", "createFileHeaderElement", "fileOrDiff", "mode", "stickyHeader", "fileDiff", "properties", "createHastElement", "CUSTOM_HEADER_SLOT_ID", "createHeaderElement", "createMetadataElement", "name", "prevName", "iconType", "children", "HEADER_PREFIX_SLOT_ID", "createIconElement", "getIconForType", "createTextNodeElement", "HEADER_FILENAME_SUFFIX_SLOT_ID", "additions", "deletions", "hunk", "HEADER_METADATA_SLOT_ID", "createPreElement", "options", "createHastElement", "createPreWrapperProperties", "diffIndicators", "disableBackground", "disableLineNumbers", "overflow", "split", "totalLines", "type", "customProperties", "CUSTOM_EXTENSION_TO_FILE_FORMAT", "EXTENSION_TO_FILE_FORMAT", "getFiletypeFromFileName", "fileName", "format", "matchFiletypeFromName", "baseName", "CUSTOM_EXTENSION_TO_FILE_FORMAT", "compoundMatch", "simpleMatch", "getHighlighterOptions", "lang", "theme", "preferredHighlighter", "getThemes", "resolveHighlighterType", "getLineAnnotationName", "annotation", "isDefaultRenderRange", "renderRange", "HEX_TRANSPARENT_RE", "ALPHA_ZERO_RE", "getFunctionalAlpha", "color", "openParen", "fn", "inner", "slashIndex", "parts", "parseHexRgba", "match", "hex", "expanded", "alpha", "c", "relativeLuminance", "rgba", "r", "g", "b", "channel", "v", "isFullyTransparent", "color", "normalized", "HEX_TRANSPARENT_RE", "alpha", "getFunctionalAlpha", "ALPHA_ZERO_RE", "hoverWouldEraseText", "hover", "bg", "fg", "hoverL", "relativeLuminance", "bgL", "fgL", "cache", "normalizeThemeColors", "theme", "cached", "originalColors", "colors", "editorBackground", "editorForeground", "sidebarBackground", "sidebarForeground", "fill", "firstColor", "focusRing", "isFullyTransparent", "hover", "matchesSurface", "hoverWouldEraseText", "result", "key", "value", "candidates", "candidate", "color", "surface", "getHighlighterThemeStyles", "theme", "DEFAULT_THEMES", "highlighter", "prefix", "styles", "themeData", "normalized", "getThemeColors", "formatCSSVariablePrefix", "getGitVariables", "normalizeThemeColors", "modePrefix", "additionGreen", "deletionRed", "modifiedBlue", "getTokenOptions", "lang", "theme", "tokenizeMaxLineLength", "formatCSSVariablePrefix", "resolvePreferredHighlighter", "workerManager", "options", "FILE_ANNOTATION_DOM_KEY", "includesFileAnnotations", "annotations", "annotation", "getFileAnnotations", "fileAnnotations", "shouldRenderFileAnnotations", "renderRange", "applyLineTextWithNewline", "line", "lineText", "createContentColumn", "children", "rowCount", "createHastElement", "SVGSpriteSheet", "arePrePropertiesEqual", "propsA", "propsB", "areCustomPropertiesEqual", "EMPTY_CUSTOM_PROPERTIES", "customPropertiesA", "customPropertiesB", "keysA", "keysB", "key", "createAnnotationWrapperNode", "slot", "wrapper", "createGutterUtilityContentNode", "gutterUtilityContent", "createUnsafeCSSStyleNode", "node", "UNSAFE_CSS_ATTRIBUTE", "style_default", "measuredScrollbarGutter", "getMeasuredScrollbarGutter", "shadowRoot", "host", "wrapper", "DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE", "child", "createMeasuredScrollbarGutterDeclaration", "scrollbarGutter", "value", "DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY", "LAYER_ORDER", "SCROLLBAR_GUTTER_DECLARATION_PATTERN", "escapeRegExp", "DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY", "wrapUnsafeCSS", "unsafeCSS", "LAYER_ORDER", "wrapThemeCSS", "themeCSS", "themeType", "scrollbarGutter", "colorSchemeRule", "scrollbarGutterVar", "createMeasuredScrollbarGutterDeclaration", "tokenFontStyles", "type", "styles", "patchScrollbarGutterSize", "scrollbarGutterRule", "SCROLLBAR_GUTTER_DECLARATION_PATTERN", "escapeRegExp", "value", "lineAnnotationSources", "getLineAnnotationSource", "annotation", "source", "getOrCreateCodeNode", "code", "pre", "columnType", "rowSpan", "containerSize", "prerenderHTMLIfNecessary", "element", "html", "shadowRoot", "setPreNodeProperties", "pre", "type", "diffIndicators", "disableBackground", "disableLineNumbers", "overflow", "split", "totalLines", "customProperties", "key", "value", "isStyleNode", "element", "tagName", "_isSafari", "isSafari", "_isSafari", "adoptEditSessionAnnotations", "annotations", "getName", "previousSession", "slotNames", "annotation", "source", "getLineAnnotationSource", "writeEditSessionAnnotations", "session", "resolveEditSessionSlotName", "name", "shouldUseTokenTransformer", "options", "guardWebKitScrollDuringRebuild", "pre", "rebuild", "height", "upsertHostThemeStyle", "shadowRoot", "currentNode", "themeCSS", "createHostThemeStyleNode", "node", "THEME_CSS_ATTRIBUTE", "WorkerPoolTerminatedError", "WorkerPoolTaskCanceledError", "WorkerPoolWorkerError", "message", "options", "reportedWorkerErrors", "isWorkerPoolCancellation", "error", "WorkerPoolTerminatedError", "WorkerPoolTaskCanceledError", "isHandledWorkerPoolError", "WorkerPoolWorkerError", "reportedWorkerErrors", "sheet", "FileDiffContainer", "shadowRoot", "styles", "getMeasuredScrollbarGutter", "DIFFS_TAG_NAME", "computeVirtualFileMetrics", "metrics", "DEFAULT_VIRTUAL_FILE_METRICS", "getVirtualFileHeaderRegion", "disableFileHeader", "getVirtualFileHeaderHeight", "getVirtualFilePaddingTop", "getVirtualFilePaddingBottom", "getDefaultHunkSeparatorHeight", "type", "areDiffTargetsEqual", "diffA", "diffB", "areFilesEqual", "fileA", "fileB", "cloneHunks", "hunks", "hunk", "content", "cloneFileDiffMetadata", "fileDiff", "getHunkSideStartBoundary", "start", "count", "getHunkSideEndBoundary", "composeCacheKey", "scope", "segments", "splitFileContents", "contents", "SPLIT_WITH_NEWLINES", "hydratePartialDiff", "type", "fileDiff", "files", "targetFileDiff", "cloneFileDiffMetadata", "hydrateTwoSidedFileDiff", "requireOldFile", "requireNewFile", "newFile", "requireMissingOldFile", "lines", "splitFileContents", "setHydratedCacheKey", "oldFile", "deletionLines", "additionLines", "hunks", "splitLineCount", "unifiedLineCount", "hydrateHunks", "totalAdditionLines", "lastHunkAdditionEnd", "hydratedHunks", "hunk", "additionLineIndex", "deletionLineIndex", "contentAdditionLineIndex", "contentDeletionLineIndex", "hunkAdditionLines", "hunkDeletionLines", "hunkSplitLineCount", "hunkUnifiedLineCount", "hunkContent", "content", "collapsedBefore", "getHunkSideStartBoundary", "getHunkSideEndBoundary", "lastHunk", "lastHunkEnd", "collapsedAfter", "getHydratedCacheKey", "getLoadedFileCacheKey", "cacheKey", "composeCacheKey", "cleanLastNewline", "contents", "end", "stringDetachEncoder", "stringDetachDecoder", "SURROGATE_CODE_UNIT_PATTERN", "STRING_DETACH_INITIAL_BUFFER_SIZE", "stringDetachBuffer", "releaseStringDetachBuffer", "detachString", "value", "requiredByteLength", "written", "filenameDecoder", "NAMED_ESCAPES", "parseQuotedDiffFileName", "input", "fileName", "index", "char", "escaped", "bytes", "byte", "readOctalByte", "first", "second", "third", "realignChangeContentBySimilarity", "diff", "hunk", "index", "content", "replacement", "realignChangeBlock", "slideBlankBoundaryBlocksUp", "resolveSlide", "hunkContent", "block", "previous", "isInsert", "lines", "blockStart", "blockLength", "unit", "uniform", "offset", "slide", "blockAdditionEnd", "blockDeletionEnd", "next", "deletions", "additions", "deletionLineIndex", "additionLineIndex", "pairCount", "surplus", "strippedDeletions", "line", "stripWhitespace", "strippedAdditions", "additionsAreLonger", "bestOffset", "bestScore", "score", "pair", "lineSimilarity", "blocks", "pushBlock", "blockDeletions", "blockAdditions", "blockDeletionIndex", "blockAdditionIndex", "WHITESPACE", "a", "b", "maxLength", "minLength", "prefix", "suffix", "GIT_DIFF_HEADER_FILENAMES", "_processPatch", "data", "cacheKeyPrefix", "throwOnError", "patchIndex", "isGitDiff", "isGitDiffPatch", "rawFiles", "splitGitDiffFiles", "splitUnifiedDiffFiles", "patchMetadata", "files", "fileOrPatchMetadata", "GIT_DIFF_FILE_BREAK_REGEX", "detachString", "startsWithUnifiedDiffFileHeader", "currentFile", "_processFile", "composeCacheKey", "processFile", "fileDiffString", "options", "releaseStringDetachBuffer", "cacheKey", "oldFile", "newFile", "lastHunkEnd", "hunks", "splitAtLinePrefix", "isPartial", "deletionLineIndex", "additionLineIndex", "hunk", "lines", "splitWithNewlines", "firstLine", "fileHeader", "parseHunkHeader", "additionLines", "deletionLines", "splitFileContents", "maybeDetachOptionalString", "line", "filenameMatch", "GIT_DIFF_HEADER_FILENAMES", "prevName", "decodeDiffFileName", "name", "FILENAME_HEADER_REGEX", "type", "rawFileName", "fileName", "detachedFileName", "prevObjectId", "newObjectId", "mode", "INDEX_LINE_METADATA", "currentContent", "lastLineType", "additionStart", "deletionStart", "hunkData", "parsedAdditionLines", "parsedDeletionLines", "lineIndex", "rawLine", "isHunkBodyLine", "isFormatPatchVersionSeparator", "firstChar", "parseRawLineType", "getParsedLineContent", "createContentGroup", "lastIndex", "cleanedLine", "cleanLastNewline", "repairedAdditionStart", "getHunkSideStartBoundary", "repairedDeletionStart", "additionStartDelta", "deletionStartDelta", "content", "getHunkSideEndBoundary", "lastHunk", "totalFileLines", "collapsedAfter", "realignChangeContentBySimilarity", "parsePatchFiles", "patches", "rawPatches", "hasCommitMetadataBoundary", "COMMIT_METADATA_SPLIT", "patch", "error", "value", "stripGitPrefix", "rawName", "parseQuotedDiffFileName", "contents", "index", "startIndex", "newlineIndex", "parts", "partStartIndex", "lineStartIndex", "remainingDeletionLines", "remainingAdditionLines", "hasOpenedUnifiedFile", "nextLineStartIndex", "getNextLineStartIndex", "isUnifiedDiffFileHeaderAt", "isUnifiedDiffHeaderLineAt", "prefix", "separator", "char", "deletionStartResult", "readPositiveInteger", "deletionCount", "deletionCountResult", "additionStartResult", "additionCount", "additionCountResult", "hunkContext", "contextStartIndex", "trimLineEnd", "parsedValue", "digit", "newlinePrefix", "firstBoundaryIndex", "findLinePrefixIndex", "nextBoundaryIndex", "fromIndex", "processedLine", "Diff", "oldStr", "newStr", "options", "callback", "oldString", "newString", "oldTokens", "newTokens", "_a", "done", "value", "newLen", "oldLen", "editLength", "maxEditLength", "maxExecutionTime", "abortAfterTimestamp", "bestPath", "newPos", "minDiagonalToConsider", "maxDiagonalToConsider", "execEditLength", "diagonalPath", "basePath", "removePath", "addPath", "canAdd", "addPathNewPos", "canRemove", "exec", "ret", "path", "added", "removed", "oldPosInc", "last", "oldPos", "commonCount", "left", "right", "array", "i", "chars", "changeObjects", "lastComponent", "components", "nextComponent", "componentLen", "componentPos", "component", "oldValue", "CharacterDiff", "Diff", "characterDiff", "diffChars", "oldStr", "newStr", "options", "longestCommonPrefix", "str1", "str2", "longestCommonSuffix", "replacePrefix", "string", "oldPrefix", "newPrefix", "replaceSuffix", "oldSuffix", "newSuffix", "removePrefix", "removeSuffix", "maximumOverlap", "string1", "string2", "overlapCount", "a", "b", "startA", "endB", "map", "k", "j", "i", "segment", "string", "segmenter", "parts", "segmentObj", "trailingWs", "leadingAndTrailingWs", "leadingWs", "match", "segments", "firstSeg", "lastSeg", "head", "tail", "extendedWordChars", "tokenizeIncludingWhitespace", "WordDiff", "Diff", "left", "right", "options", "value", "parts", "segmenter", "segment", "tokens", "prevPart", "part", "token", "i", "changes", "lastKeep", "insertion", "deletion", "change", "dedupeWhitespaceInChangeObjects", "wordDiff", "dedupeWhitespaceInChangeObjects", "startKeep", "deletion", "insertion", "endKeep", "segmenter", "oldWsPrefix", "oldWsSuffix", "leadingAndTrailingWs", "newWsPrefix", "newWsSuffix", "commonWsPrefix", "longestCommonPrefix", "replaceSuffix", "removePrefix", "commonWsSuffix", "longestCommonSuffix", "replacePrefix", "removeSuffix", "ws", "leadingWs", "newWsFull", "delWsStart", "delWsEnd", "newWsStart", "newWsEnd", "endKeepWsPrefix", "deletionWsSuffix", "trailingWs", "overlap", "maximumOverlap", "startKeepWsSuffix", "deletionWsPrefix", "WordsWithSpaceDiff", "Diff", "value", "regex", "extendedWordChars", "wordsWithSpaceDiff", "diffWordsWithSpace", "oldStr", "newStr", "options", "LineDiff", "Diff", "tokenize", "left", "right", "options", "lineDiff", "diffLines", "oldStr", "newStr", "tokenize", "value", "options", "retLines", "linesAndNewlines", "i", "line", "needsQuoting", "s", "i", "quoteFileNameIfNeeded", "result", "bytes", "b", "INCLUDE_HEADERS", "structuredPatch", "oldFileName", "newFileName", "oldStr", "newStr", "oldHeader", "newHeader", "options", "optionsObj", "context", "callback", "diffLines", "diff", "patch", "diffLinesResultToPatch", "contextLines", "lines", "entry", "hunks", "oldRangeStart", "newRangeStart", "curRange", "oldLine", "newLine", "i", "current", "splitLines", "prev", "line", "contextSize", "hunk", "formatPatch", "headerOptions", "_a", "_b", "_c", "_d", "_e", "_f", "INCLUDE_HEADERS", "p", "ret", "gitOldName", "gitNewName", "quoteFileNameIfNeeded", "hasHunks", "oldStart", "newStart", "createTwoFilesPatch", "patchObj", "splitLines", "text", "hasTrailingNl", "result", "line", "MISSING_FILE_NAME", "parseDiffFromFile", "oldFile", "newFile", "options", "throwOnError", "resolvedOldFile", "createMissingFile", "resolvedNewFile", "patch", "createTwoFilesPatch", "fileData", "processFile", "oldCacheKey", "newCacheKey", "composeCacheKey", "language", "ScrollSyncManager", "pre", "codeDeletions", "codeAdditions", "element", "areDiffRenderOptionsEqual", "optionsA", "optionsB", "areThemesEqual", "createEmptyRowBuffer", "size", "createHastElement", "createNoNewlineElement", "type", "createHastElement", "createTextNodeElement", "createExpandButton", "type", "createHastElement", "createIconElement", "createSeparator", "content", "expandIndex", "chunked", "slotName", "isFirstHunk", "isLastHunk", "buttonCount", "children", "createTextNodeElement", "contentChildren", "getHunkSeparatorSlotName", "type", "hunkIndex", "getTotalLineCountFromHunks", "hunks", "lastHunk", "getHunkSideEndBoundary", "createDiffSpanDecoration", "line", "spanStart", "spanLength", "pushOrJoinSpan", "item", "arr", "enableJoin", "isNeutral", "isLastItem", "lastItem", "isLastItemNeutral", "getHunkAdditionLineRange", "hunk", "getHunkSideStartBoundary", "getHunkSideEndBoundary", "getExpandedRegion", "isPartial", "rangeSize", "expandedHunks", "hunkIndex", "collapsedContextThreshold", "normalizedRangeSize", "region", "fromStart", "fromEnd", "expandedCount", "renderAll", "hasTrailingContextMismatch", "fileDiff", "lastHunk", "additionRemaining", "getHunkSideEndBoundary", "deletionRemaining", "getTrailingContextRangeSize", "errorPrefix", "getTrailingExpandedRegion", "hunkIndex", "expandedHunks", "collapsedContextThreshold", "trailingRangeSize", "region", "fromStart", "isAdditionLineRenderable", "lineNumber", "hunk", "hunkStart", "hunkEnd", "getHunkAdditionLineRange", "getExpandedRegion", "gapStart", "trailingRegion", "trailingStart", "getNearestRenderableAdditionLine", "direction", "ranges", "modeledEnd", "start", "end", "index", "getHunkSeparatorHeight", "type", "metrics", "getDefaultHunkSeparatorHeight", "getHunkSeparatorGap", "hasLeadingHunkSeparator", "hunkSpecs", "hasTrailingHunkSeparator", "getLeadingHunkSeparatorLayout", "height", "gap", "gapBefore", "gapAfter", "getTrailingHunkSeparatorLayout", "iterateOverDiff", "diff", "diffStyle", "startingLine", "totalLines", "expandedHunks", "collapsedContextThreshold", "callback", "iterationStart", "getIterationStartState", "state", "breakUnified", "breakSplit", "unifiedCount", "splitCount", "skipUnified", "skipSplit", "unifiedValue", "splitValue", "unifiedHeight", "splitHeight", "unifiedInWindow", "splitInWindow", "props", "silent", "hunkIterator", "hunkIndex", "getTrailingCollapsedAfter", "unifiedLineIndex", "splitLineIndex", "trailingRegion", "hunk", "consumePendingCollapsed", "consumedCollapsed", "leadingRegion", "deletionBoundary", "getHunkSideStartBoundary", "additionBoundary", "deletionStartIndex", "additionStartIndex", "getExpandedRegion", "getTrailingExpandedRegion", "expandedLineCount", "deletionLineIndex", "additionLineIndex", "deletionLineNumber", "additionLineNumber", "walkContextLines", "index", "lastContent", "content", "isLastContent", "isLastLine", "unifiedRowIndex", "splitRowIndex", "iterationRanges", "getChangeIterationRanges", "rangeStart", "rangeEnd", "collapsedAfter", "getChangeLineData", "collapsedLines", "fromStart", "fromEnd", "len", "prefixCounts", "getHunkPrefixCounts", "low", "high", "result", "mid", "counts", "finalHunkIndex", "leadingCount", "trailingCount", "getContextLineIterationBounds", "count", "ranges", "pushRange", "currentCount", "start", "end", "range", "onSkippedStart", "shouldBreak", "startIndex", "endIndex", "useUnified", "useSplit", "iterationSpace", "getVisibleRange", "visibleStart", "visibleEnd", "mapRangeToIteration", "kind", "a", "b", "merged", "last", "collapsedBefore", "unifiedDeletionLineIndex", "unifiedAdditionLineIndex", "resolvedSplitLineIndex", "deletionLineIndexValue", "deletionLineNumberValue", "additionLineIndexValue", "additionLineNumberValue", "noEOFCRDeletion", "noEOFCRAddition", "deletionLine", "additionLine", "DEFAULT_PLAIN_TEXT_OPTIONS", "renderDiffWithHighlighter", "diff", "highlighter", "options", "forcePlainText", "lazyLineAST", "startingLine", "totalLines", "expandedHunks", "collapsedContextThreshold", "isWindowedHighlight", "baseThemeType", "themeStyles", "getHighlighterThemeStyles", "lineDiffType", "code", "maxLineDiffLength", "shouldGroupAll", "expandedHunksForIteration", "buckets", "getBucketForHunk", "hunkIndex", "index", "bucket", "createBucket", "appendContent", "lineContent", "lineIndex", "segments", "contentWrapper", "segment", "iterateOverDiff", "additionLine", "deletionLine", "type", "splitLineIndex", "computeLineDiffDecorations", "deletionFile", "additionFile", "deletionLines", "additionLines", "renderTwoFiles", "target", "lines", "offset", "setDeferredArrayItem", "appendItems", "pushWordLineDecorations", "lineDiff", "deletionLineIndex", "additionLineIndex", "deletionDecorations", "additionDecorations", "deletionOffset", "additionOffset", "deletionStart", "deletionEnd", "additionStart", "additionEnd", "value", "added", "removed", "createDiffSpanDecoration", "cleanLastNewline", "diffChars", "diffWordsWithSpace", "deletionSpans", "additionSpans", "enableJoin", "lastItem", "item", "isLastItem", "pushOrJoinSpan", "spanIndex", "span", "deletionInfo", "additionInfo", "languageOverride", "theme", "useTokenTransformer", "tokenizeMaxLineLength", "renderFile", "file", "lineInfo", "decorations", "renderTokenLines", "getTokenOptions", "getFiletypeFromFileName", "recomputeDiffHunks", "diff", "parseDiffOptions", "recomputed", "parseDiffFromFile", "buildTopAlignedAdditionSentinel", "lineCount", "deletionContents", "count", "sentinel", "_", "index", "hasOnlyBlankAdditionContents", "additionLines", "line", "shouldTopAlignAdditionRecompute", "recomputeTopAlignedAdditionDiff", "additionCharacterCount", "additionSentinel", "recomputeEmptyDocumentDiff", "recomputeDiffHunksForEdit", "preserveTrailingEditorBlankLine", "hasTrailingEditorBlankLine", "extraLineCount", "extraAdditionLineIndex", "lastHunk", "getHunkSideEndBoundary", "content", "recomputeDiffRenderLineCounts", "updateDiffHunks", "changedAdditionLineIndexes", "applyHunkUpdateResult", "changedLines", "additionLine", "deletionLine", "cleanLastNewline", "affectedHunkIndexes", "getAffectedHunkIndexes", "hunkIndex", "reparseHunkRegion", "hasTrailingContextMismatch", "result", "indexes", "findHunkIndexForAdditionLine", "hunk", "end", "deletionSlice", "additionSlice", "reparsed", "reparsedHunk", "applyReparsedHunk", "syncHunkNoEOFCRFromFullFile", "lastAdditionLine", "lastDeletionLine", "target", "parsed", "additionOffset", "deletionOffset", "offsetHunkContent", "recomputeHunkRenderLineCounts", "splitLineCount", "unifiedLineCount", "splitTotal", "unifiedTotal", "lastHunkAdditionEnd", "getHunkSideStartBoundary", "collapsedAfter", "deletionLineSetCache", "normalizeEditorLines", "lines", "findDivergenceCore", "deletionLines", "additionLines", "maxStart", "start", "deletionEnd", "additionEnd", "rebuildSessionHunks", "diff", "parseDiffOptions", "getPreviousAdditionLine", "previousHunks", "editorAdditionLines", "canonicalAdditionLines", "canonicalDiff", "plans", "buildRegionPlans", "parseSessionChangeBlocks", "nextHunks", "buildRegionHunks", "finalizeSessionHunks", "preserveTrailingEditorBlankLine", "hasRegionOrSplitLayoutChanged", "plan", "applySessionChangedLines", "changedAdditionLineIndexes", "previousAdditionLines", "changedLines", "line", "a", "b", "index", "hunks", "regionIndex", "hunkIndex", "hunk", "getHunkAdditionStart", "canRetainCanonicalBlocks", "deletionLineSet", "getDeletionLineSet", "isPureChange", "previousLine", "additionLine", "insideBalancedChange", "content", "cached", "set", "remapExpandedHunksForRegionChange", "expandedHunks", "change", "remapped", "regions", "key", "previous", "next", "fromStartSource", "fromEndSource", "fromStart", "fromEnd", "captureExpansionAnchors", "collapsedContextThreshold", "anchors", "region", "getExpandedRegion", "gapEnd", "getHunkDeletionStart", "gapStart", "trailingRegion", "getTrailingExpandedRegion", "lastHunk", "rebuildExpansionFromAnchors", "rebuilt", "applyGap", "end", "finishEditSessionForDiff", "recomputeDiffHunks", "recomputeDiffHunksForEdit", "parsed", "parseDiffFromFile", "previousBlocks", "resolveSlide", "block", "maxSlide", "collectPureChangeBlocks", "offset", "blocks", "coveredAdditions", "coveredDeletions", "slideBlankBoundaryBlocksUp", "contextLines", "offsetHunkContent", "deletionLineCount", "previousPlans", "deletionStart", "previousIndex", "blockStart", "blockEnd", "blockTouchesRegion", "mergeRegionPlans", "previousEnd", "nextStart", "target", "source", "deletionCursor", "additionCursor", "contextBefore", "additionStart", "hunkContent", "canonicalBlock", "deletionContext", "additionContext", "pushContext", "trailingContext", "createRegionHunk", "bounds", "additionCount", "deletionCount", "getUnifiedStart", "getUnifiedLineIndex", "recomputeHunkRenderLineCounts", "additionLineIndex", "deletionLineIndex", "previousHunk", "nextHunk", "haveSameSplitRowMapping", "previousRows", "iterateSplitRowMapping", "nextRows", "previousRow", "nextRow", "rowCount", "getHunkSideStartBoundary", "lineIndex", "count", "recomputeDiffRenderLineCounts", "syncHunkNoEOFCRFromFullFile", "isDiffPlainText", "diff", "computedLang", "getFiletypeFromFileName", "computedPreviousLang", "instanceId", "DiffHunksRenderer", "options", "DEFAULT_THEMES", "annotationSlotName", "getLineAnnotationName", "onRenderUpdate", "workerManager", "diff", "externalDiff", "wasAlreadyActive", "renderCache", "recomputeEmptyDocumentDiff", "cacheBelongsToSession", "cacheBelongsToExternal", "areDiffTargetsEqual", "result", "areDiffRenderOptionsEqual", "isDiffPlainText", "isDiffMassive", "error", "isHandledWorkerPoolError", "fresh", "currentDiff", "index", "direction", "expansionLineCount", "region", "hunkIndex", "DEFAULT_EXPANDED_REGION", "expandedHunks", "lineAnnotations", "annotation", "map", "arr", "dirtyLines", "themeType", "lineCountChangeInFlight", "changedDocumentLines", "documentLineCount", "hastLines", "pendingStructuralRows", "changedAdditionLines", "previousAdditionLines", "additionLineCount", "canAppendFinalRow", "canAppendFinalDocumentRow", "line", "text", "previous", "createPlainAdditionLineElement", "cleanLastNewline", "tokens", "prevProps", "lineText", "a", "canSyncDiffLine", "prevLine", "prevText", "nextLine", "applyLineTextWithNewline", "row", "char", "fg", "regionsChanged", "shouldTopAlignAdditionRecompute", "recomputeTopAlignedAdditionDiff", "change", "applySessionChangedLines", "updateDiffHunks", "remapExpandedHunksForRegionChange", "textDocument", "lines", "characterCount", "getEditorDocumentLines", "realignAdditionHastLines", "recomputeDiffHunksForEdit", "parseDiffOptions", "rawLines", "rebuildSessionHunks", "update", "sessionType", "lineType", "side", "type", "span", "createDefaultAnnotationElement", "diffIndicators", "diffStyle", "disableBackground", "disableFileHeader", "disableLineNumbers", "disableVirtualizationBuffers", "collapsed", "expandUnchanged", "collapsedContextThreshold", "hunkSeparators", "lineDiffType", "maxLineDiffLength", "overflow", "stickyHeader", "theme", "headerRenderMode", "tokenizeMaxLineLength", "tokenizeMaxLength", "DEFAULT_TOKENIZE_MAX_LENGTH", "useTokenTransformer", "useCSSClasses", "getSharedHighlighter", "getHighlighterOptions", "resolvePreferredHighlighter", "massiveDiff", "cache", "getHighlighterIfLoaded", "getDiffLanguages", "HighlighterDisposedError", "editSessionActive", "renderResult", "poolOptions", "forcePlainText", "renderRange", "DEFAULT_RENDER_RANGE", "forceHighlight", "readyResult", "hasContent", "canRenderDiff", "newContent", "newRenderRange", "areRenderRangesEqual", "preserveHydratedContent", "isDefaultRenderRange", "highlighter", "hasThemes", "areThemesAttached", "hasLangs", "areLanguagesAttached", "canHighlight", "lazyLineAST", "split", "totalLines", "customProperties", "createPreElement", "renderDiffWithHighlighter", "fallbackLine", "iterateOverDiff", "additionLine", "highlighted", "pendingHighlightResult", "workerCache", "fileDiff", "code", "themeStyles", "baseThemeType", "isRenderCacheDirty", "unified", "canHydrateContext", "canHydrateCollapsedContext", "isExpandableDiff", "additionsContentAST", "deletionsContentAST", "unifiedContentAST", "hunkData", "additionLines", "deletionLines", "context", "createGutterWrapper", "count", "element", "trailingRangeSize", "getTrailingContextRangeSize", "pendingSplitContext", "createGutterGap", "createEmptyRowBuffer", "pushGutterLineNumber", "lineNumber", "lineIndex", "gutterProperties", "createGutterItem", "pushSeparators", "props", "pushSeparator", "hunk", "collapsedBefore", "collapsedAfter", "deletionLine", "splitLineIndex", "unifiedLineIndex", "renderedLineContext", "injectedRows", "pushUnifiedInjectedRows", "deletionLineContent", "additionLineContent", "errorMessage", "lineDecoration", "withContentProperties", "pushLineWithAnnotation", "pushSplitInjectedRows", "deletionLineDecoration", "additionLineDecoration", "missingSide", "annotationSpans", "deletionLineDecorated", "additionLineDecorated", "isFinalSplitHunkRow", "isFinalHunkRow", "splitNoEOFCRDeletion", "splitNoEOFCRAddition", "noEOFCRDeletion", "noEOFCRAddition", "noEOFType", "createNoNewlineElement", "getTotalLineCountFromHunks", "hasBuffer", "shouldIncludeAdditions", "shouldIncludeDeletions", "preNode", "gutterAST", "contentAST", "gutter", "createContentColumn", "children", "containerSize", "unifiedAST", "createHastElement", "deletionsAST", "additionsAST", "tempChildren", "hastToHtml", "columnType", "shouldRenderFileAnnotations", "deletionAnnotationNames", "getFileAnnotations", "additionAnnotationNames", "createAnnotationElement", "deletionLineNumber", "additionLineNumber", "deletionSpan", "anno", "additionSpan", "annotations", "createFileHeaderElement", "EN_PLURAL_RULES", "getModifiedLinesString", "rows", "deletion", "addition", "unifiedSpan", "hasAnnotationRow", "collapsedLines", "rangeSize", "hunkSpecs", "isFirstHunk", "isLastHunk", "isExpandable", "linesAST", "createSeparator", "slotName", "getHunkSeparatorSlotName", "chunked", "expandIndex", "content", "lineNode", "contentProperties", "extendProperties", "contentLineCount", "previousLines", "nextLines", "previousContentLength", "nextContentLength", "maxShared", "prefix", "suffix", "realigned", "offset", "deletionLang", "getFiletypeFromFileName", "additionLang", "hasFileLoader", "areDiffLineAnnotationsEqual", "annotationA", "annotationB", "areHunkDataEqual", "hunkA", "hunkB", "awaitWithTimeout", "callback", "timeout", "timeoutId", "resolve", "getDiffFileInput", "oldFile", "newFile", "context", "getDiffHunksRendererOptions", "options", "shouldUseTokenTransformer", "canHydrateDiff", "fileDiff", "createEditSessionDiff", "editSessionDiff", "shouldResetUndoState", "prevDiff", "nextDiff", "prevLanguage", "getFiletypeFromFileName", "nextLanguage", "prevHasOldFile", "nextHasOldFile", "line", "index", "areLinesEqual", "first", "second", "canRestoreDiffSession", "snapshot", "inputDiff", "oldFile", "instanceId", "FileDiff", "EMPTY_LINE_ANNOTATIONS", "options", "DEFAULT_THEMES", "workerManager", "requestOwnerRender", "ResizeManager", "ScrollSyncManager", "InteractionManager", "pluckInteractionOptions", "getDiffHunksRendererOptions", "DiffHunksRenderer", "lineNumber", "side", "lastHunk", "targetUnifiedIndex", "targetSplitIndex", "hunkIterator", "hunk", "hunkStart", "hunkCount", "currentLineNumber", "getHunkSideStartBoundary", "splitIndex", "unifiedIndex", "difference", "content", "sideCount", "indexDifference", "themeType", "effectiveThemeType", "areThemesEqual", "annotation", "resolveEditSessionSlotName", "getLineAnnotationName", "pendingData", "areDiffTargetsEqual", "lineAnnotations", "session", "sessionAnnotations", "writeEditSessionAnnotations", "forceRender", "annotationsChanged", "didContentChange", "range", "editorActiveLine", "selectedLines", "diffStyle", "overflow", "position", "recycle", "editor", "dequeueRender", "fileContainer", "prerenderedHTML", "preventEmit", "fileInputProps", "fileInput", "getDiffFileInput", "newFile", "forceEditorRender", "shouldRenderCode", "hasDiffContent", "shouldRenderHeader", "hasDiffHeaderContent", "prerenderHTMLIfNecessary", "element", "code", "hydratedAnnotations", "parseDiffFromFile", "hunkIndex", "direction", "expansionLineCountOverride", "loadDiffFiles", "promise", "pendingFiles", "clearPendingFiles", "pending", "files", "error", "expectedDiff", "hydratePartialDiff", "awaitWithTimeout", "incomingDiff", "previousAnnotations", "previousSession", "outgoingDiff", "adoptEditSessionAnnotations", "retainedDocument", "retainedSession", "inputContents", "retainedLines", "splitFileContents", "restoreRetainedSession", "usesInputDocument", "sessionDiff", "recomputeDiffRenderLineCounts", "annotations", "deferManagers", "containerWrapper", "renderRange", "collapsed", "expandUnchanged", "nextRenderRange", "themeChanged", "hasFileInput", "filesDidChange", "areOptionalFilesEqual", "diffDidChange", "areRenderRangesEqual", "rendered", "nextParsedFileDiff", "previousRenderRange", "workingDiff", "finishEditSessionForDiff", "disableErrorHandling", "disableFileHeader", "hunksResult", "EMPTY_RENDER_RANGE", "pre", "renderedDiff", "unmount", "onPostRender", "phase", "fallbackDiff", "matchesPending", "sync", "highlighter", "replacement", "externalDocument", "resetHistory", "theme", "lang", "getHighlighterIfLoaded", "getSharedHighlighter", "getThemes", "resolvePreferredHighlighter", "HighlighterDisposedError", "isDefaultRenderRange", "collapsedContextThreshold", "firstLineNumber", "lastLineNumber", "iterateOverDiff", "additionLine", "event", "onEditChange", "clone", "cloneHunks", "detach", "pendingReplacement", "initialInputDiff", "getAdditionFile", "mode", "installResult", "editSession", "editSessionAnnotations", "inputAnnotations", "sessionAnnotationsCurrent", "acceptedDiff", "acceptedOldFile", "acceptedNewFile", "failed", "failure", "completedDiff", "cloneFileDiffMetadata", "anchors", "captureExpansionAnchors", "rebuildExpansionFromAnchors", "textDocument", "newLineAnnotations", "dirtyLines", "shouldRefreshDiffsView", "lineCountChangeInFlight", "isAdditionLineRenderable", "getNearestRenderableAdditionLine", "expansionLineCount", "expandedHunks", "hunkEnd", "getHunkAdditionLineRange", "region", "getExpandedRegion", "gapStart", "fromStartDistance", "fromEndDistance", "trailingRegion", "getTrailingExpandedRegion", "trailingStart", "queueRender", "height", "shadowRoot", "isDiffPlainText", "tokenizeMaxLength", "isHandledWorkerPoolError", "hunkData", "hunkSeparators", "staleSeparators", "id", "cache", "areHunkDataEqual", "child", "staleAnnotations", "renderedData", "renderAnnotation", "name", "areDiffLineAnnotationsEqual", "createAnnotationWrapperNode", "renderGutterUtility", "gutterUtilityContent", "createGutterUtilityContentNode", "parentNode", "previousContainer", "nextContainer", "containerChanged", "isStyleNode", "fragment", "SVGSpriteSheet", "firstChild", "container", "headerAST", "cachedHeaderDiff", "cachedHeaderHTML", "lastRenderedHTML", "headerHTML", "hastToHtml", "tempDiv", "newHeader", "renderCustomHeader", "renderHeaderPrefix", "renderHeaderFilenameSuffix", "renderHeaderMetadata", "CUSTOM_HEADER_SLOT_ID", "prefix", "suffix", "HEADER_PREFIX_SLOT_ID", "HEADER_FILENAME_SUFFIX_SLOT_ID", "HEADER_METADATA_SLOT_ID", "current", "slot", "unsafeCSS", "createUnsafeCSSStyleNode", "wrapUnsafeCSS", "themeStyles", "baseThemeType", "currentTheme", "scrollbarGutter", "getMeasuredScrollbarGutter", "upsertHostThemeStyle", "wrapThemeCSS", "patchScrollbarGutterSize", "isSafari", "result", "guardWebKitScrollDuringRebuild", "ast", "rowCount", "columns", "gutterChildren", "getElementChildren", "contentChildren", "containerSize", "rowSpan", "shouldReplace", "codeElements", "unifiedAST", "deletionsAST", "additionsAST", "getOrCreateCodeNode", "codeUnified", "codeAdditions", "codeDeletions", "previousStart", "nextStart", "previousEnd", "nextEnd", "overlapStart", "overlapEnd", "trimStart", "trimEnd", "trimResult", "renderChunk", "startingLine", "totalLines", "prependResult", "appendResult", "applyChunk", "insertPosition", "applyLineType", "type", "column", "el", "astChildren", "i", "gutterElement", "lineType", "applyColumns", "firstHASTElement", "lastHASTElement", "adjustmentSize", "contentElement", "fromStart", "currentSize", "applySpan", "preTrimCount", "postTrimStart", "visibleLineIndex", "rowIndex", "pendingMetadataTrim", "hasPostTrim", "totalRows", "rowsToRemove", "newSize", "bufferStart", "bufferEnd", "shouldTrimStart", "shouldTrimEnd", "effectivePreTrimCount", "effectivePostTrimStart", "deletionsTrim", "additionsTrim", "properties", "parsed", "size", "gutter", "deletions", "additions", "additionsContentAST", "deletionsContentAST", "customProperties", "diffIndicators", "disableBackground", "disableLineNumbers", "preProperties", "arePrePropertiesEqual", "setPreNodeProperties", "errorMessage", "errorStack", "fileA", "fileB", "areFilesEqual", "hasContent", "headerElement", "node", "computeEstimatedDiffHeights", "fileDiff", "metrics", "disableFileHeader", "hunkSeparators", "expandUnchanged", "configuredExpandedHunks", "collapsedContextThreshold", "canHydratePartialDiff", "splitHeight", "getVirtualFileHeaderRegion", "unifiedHeight", "expandedHunks", "finalHunkIndex", "hunkIndex", "hunk", "leadingRegion", "getExpandedRegion", "leadingExpandedHeight", "separatorHeight", "getLeadingHunkSeparatorLayout", "metadataLineCounts", "getNoNewlineMetadataLineCounts", "trailingRegion", "getTrailingExpandedRegion", "trailingExpandedHeight", "getTrailingHunkSeparatorLayout", "paddingBottom", "getVirtualFilePaddingBottom", "lastContent", "metadataRows", "getChangeNoNewlineMetadataLineCounts", "content", "unified", "splitDeletionHasMetadata", "splitAdditionHasMetadata", "VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL", "NO_GHOST_TEXT_ROWS", "instanceId", "VirtualizedFileDiff", "FileDiff", "options", "virtualizer", "metrics", "workerManager", "requestOwnerRender", "computeVirtualFileMetrics", "force", "nextMetrics", "areObjectsEqual", "lineAnnotations", "nextHeight", "previousHeight", "fileDiff", "includesFileAnnotations", "annotation", "lineIndex", "hasMetadataLine", "multiplier", "previousOptions", "optionsChanged", "areOptionsEqual", "layoutChanged", "hasDiffLayoutOptionChanged", "hasDiffEstimateOptionChanged", "themeType", "forceSimpleRecompute", "includeEstimatedHeights", "resetRenderRange", "ghostTextRows", "heightDeltas", "folded", "previous", "lineHeight", "diffStyle", "next", "line", "rows", "indexes", "changed", "rowIndex", "delta", "nextDelta", "hasHeightChange", "overflow", "ghostTextRowsByIndex", "measureAllRows", "codeGroups", "shouldRenderFileAnnotations", "nextFileAnnotationHeight", "measureFileAnnotationHeight", "codeGroup", "content", "skipsGhostRows", "lineIndexAttr", "parseLineIndex", "ghostRows", "previousDelta", "measuredHeight", "hasMetadata", "estimatedHeight", "dirty", "top", "reset", "resetLayoutCache", "resetEstimatedHeights", "pendingExpansions", "pendingHydratedDiff", "collapsed", "hunkIndex", "direction", "expansionLineCountOverride", "diffChanged", "pendingRenderDiff", "layoutDiffChanged", "renderedDiffChanged", "annotationsChanged", "lineNumber", "side", "targetLineIndexes", "disableFileHeader", "expandUnchanged", "collapsedContextThreshold", "hunkSeparators", "targetLineIndex", "headerRegion", "getVirtualFileHeaderRegion", "checkpoint", "getVirtualFileHeaderHeight", "position", "iterateOverDiff", "hunk", "collapsedBefore", "collapsedAfter", "deletionLine", "additionLine", "separator", "getLeadingHunkSeparatorLayout", "getTrailingHunkSeparatorLayout", "localViewportTop", "anchor", "windowSpecs", "renderRange", "bufferBefore", "bufferAfter", "totalLines", "headerOnlyOffset", "activeWindow", "recycle", "hadGhostTextRows", "shouldRecomputeLayout", "areDiffTargetsEqual", "expectedDiff", "files", "nextDiff", "hydratePartialDiff", "awaitWithTimeout", "expansionLineCount", "staged", "expansion", "region", "count", "isAdditionLineRenderable", "visible", "workingDiff", "nextRenderDiff", "codeView", "textDocument", "newLineAnnotations", "shouldUpdateBuffer", "previousRenderRange", "shouldValidateSize", "isFirstCompute", "pendingRender", "splitHeight", "unifiedHeight", "computeEstimatedDiffHeights", "canHydrateCollapsedContext", "rect", "fileContainer", "forceRender", "fileInputProps", "fileInput", "getDiffFileInput", "hasFileInput", "oldFile", "newFile", "filesDidChange", "areOptionalFilesEqual", "nextFileDiff", "parseDiffFromFile", "forceRenderOverride", "isSetup", "targetChanged", "dataChanged", "fileTop", "previousRenderedDiff", "previousLayoutDiff", "getOptionHunkSeparatorType", "finalHunkIndex", "canHydratePartialDiff", "expandedHunks", "heightDeltaPrefix", "createHeightDeltaPrefix", "renderedLineIndex", "processRows", "rowCount", "startLineIndex", "preSeparatorHeight", "postSeparatorHeight", "metadataOffsets", "blockStart", "blockEnd", "nextCheckpoint", "getNextCheckpointIndex", "offset", "checkpointTop", "countMetadataOffsetsBefore", "sumHeightDeltas", "leadingRegion", "getExpandedRegion", "leadingSeparatorHeight", "pendingLeadingSeparatorHeight", "trailingRegion", "getTrailingExpandedRegion", "trailingSeparatorHeight", "trailingExpandedCount", "hunkBodyRowCount", "hunkBodyStartLineIndex", "getHunkMetadataOffsets", "low", "high", "result", "mid", "hunkLineCount", "resultIndex", "index", "hunkCount", "fromStart", "fromEnd", "renderAll", "expandedLineCount", "metadataLineCount", "bottom", "fileHeight", "lineCount", "paddingBottom", "getVirtualFilePaddingBottom", "fileAnnotationHeight", "codeRegionTop", "codeHeight", "hasFileAnnotations", "fileAnnotationTop", "measuredFileAnnotationVisible", "estimatedTargetLines", "totalHunks", "overflowHunks", "hunkOffsets", "viewportCenter", "absoluteLineTop", "currentLine", "firstVisibleHunk", "centerHunk", "overflowCounter", "splitLineIndex", "unifiedLineIndex", "isFinalHunkRow", "gapAdjustment", "isAtHunkBoundary", "currentHunk", "trailingSeparator", "idealStartHunk", "maxStartHunk", "startHunk", "startingLine", "clampedTotalLines", "codeBufferBefore", "height", "child", "FILE_ANNOTATION_DOM_KEY", "entries", "a", "b", "lineIndexes", "prefixTotals", "total", "endLineIndex", "start", "lowerBound", "values", "target", "value", "metadataOffset", "lastContent", "splitCount", "unifiedCount", "offsets", "contentStartOffset", "nextOptions", "hasFileLoader", "fileA", "fileB", "areFilesEqual", "unifiedIndex", "splitIndex", "areVirtualWindowSpecsEqual", "windowSpecsA", "windowSpecsB", "DEFAULT_OVERSCROLL_SIZE", "INTERSECTION_OBSERVER_MARGIN", "INTERSECTION_OBSERVER_THRESHOLD", "DEFAULT_VIRTUALIZER_CONFIG", "lastSize", "instance", "Virtualizer", "config", "root", "contentContainer", "queueRender", "container", "domDirty", "createWindowFromScrollPosition", "elementTop", "elementHeight", "scrollTop", "height", "margin", "top", "bottom", "entries", "shouldQueueUpdate", "entry", "blockSize", "dequeueRender", "element", "getRelativeBoundingTop", "wrapperDirty", "instancesHaveChanged", "windowSpecs", "areVirtualWindowSpecsEqual", "anchor", "updatedInstances", "scrollContainer", "lineIndex", "lineOffset", "fileElement", "fileOffset", "fileTypeOffset", "scrollOffset", "viewportHeight", "bestAnchor", "fileTop", "fileBottom", "bestLineIndex", "bestLineOffset", "line", "shouldReplace", "target", "isIntersecting", "behavior", "rect", "scrollContainerTop", "MARGIN", "letters", "afterLayout", "fn", "ago", "date", "seconds", "units", "unit", "size", "sums", "file", "added", "removed", "hunk", "counts", "element", "letter", "blocks", "line", "old", "content", "place", "newLine", "number", "context", "span", "text", "make", "root", "source", "api", "page", "nav", "main", "failure", "clean", "find", "field", "count", "about", "patch", "files", "boxes", "changes", "change", "filter", "viewed", "own", "kept", "split", "ovvi", "wrap", "list", "virtualizer", "Virtualizer", "owners", "nearby", "entries", "steady", "entry", "box", "show", "options", "overflow", "fileOptions", "event", "lineNumber", "annotationSide", "openFile", "how", "fileRow", "diff", "row", "disclosure", "collapse", "base", "dir", "nameAndFolder", "name", "folder", "fileIcon", "actions", "label", "check", "open", "menu", "bare", "VirtualizedFileDiff", "work", "view", "anchor", "offset", "top", "describe", "facts", "fact", "term", "value", "copy", "failed", "parent", "button", "home", "draw", "next", "parsePatchFiles", "parsed", "put", "listFiles", "sift", "shows", "node", "shown", "was", "drawn", "order", "index", "from", "to", "near", "bottom", "title", "reveal", "none", "sf", "listButton", "moves", "stepped", "where", "block", "scrollToChange", "aim", "keepChange", "id", "folded", "closeFind", "theme", "refresh", "coalesce", "apply", "read", "error", "layout", "toggleList", "chosen", "keep", "step", "by", "at", "below", "stepFile", "tops", "filtered", "keys", "changed", "preloadHighlighter"]
7
- }