@pierre/diffs 1.4.2 → 1.5.0
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.
- package/dist/components/CodeView.d.ts +2 -4
- package/dist/components/CodeView.d.ts.map +1 -1
- package/dist/components/CodeView.js +23 -12
- package/dist/components/CodeView.js.map +1 -1
- package/dist/components/File.d.ts +3 -0
- package/dist/components/File.d.ts.map +1 -1
- package/dist/components/File.js +10 -0
- package/dist/components/File.js.map +1 -1
- package/dist/components/FileDiff.d.ts +19 -1
- package/dist/components/FileDiff.d.ts.map +1 -1
- package/dist/components/FileDiff.js +51 -15
- package/dist/components/FileDiff.js.map +1 -1
- package/dist/components/VirtualizedFile.d.ts.map +1 -1
- package/dist/components/VirtualizedFile.js +18 -19
- package/dist/components/VirtualizedFile.js.map +1 -1
- package/dist/components/VirtualizedFileDiff.d.ts.map +1 -1
- package/dist/components/VirtualizedFileDiff.js +25 -22
- package/dist/components/VirtualizedFileDiff.js.map +1 -1
- package/dist/constants.d.ts +1 -3
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +1 -3
- package/dist/constants.js.map +1 -1
- package/dist/editor/editor.d.ts.map +1 -1
- package/dist/editor/editor.js +21 -10
- package/dist/editor/editor.js.map +1 -1
- package/dist/editor/textMeasure.d.ts.map +1 -1
- package/dist/editor/textMeasure.js +27 -3
- package/dist/editor/textMeasure.js.map +1 -1
- package/dist/highlighter/languages/attachResolvedLanguages.js +8 -1
- package/dist/highlighter/languages/attachResolvedLanguages.js.map +1 -1
- package/dist/highlighter/languages/registerCustomLanguage.d.ts +3 -1
- package/dist/highlighter/languages/registerCustomLanguage.d.ts.map +1 -1
- package/dist/highlighter/languages/registerCustomLanguage.js +3 -1
- package/dist/highlighter/languages/registerCustomLanguage.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/react/utils/useFileDiffInstance.d.ts.map +1 -1
- package/dist/react/utils/useFileDiffInstance.js +47 -11
- package/dist/react/utils/useFileDiffInstance.js.map +1 -1
- package/dist/renderers/DiffHunksRenderer.d.ts.map +1 -1
- package/dist/renderers/DiffHunksRenderer.js +20 -13
- package/dist/renderers/DiffHunksRenderer.js.map +1 -1
- package/dist/renderers/FileRenderer.d.ts.map +1 -1
- package/dist/renderers/FileRenderer.js +30 -11
- package/dist/renderers/FileRenderer.js.map +1 -1
- package/dist/sprite.d.ts +2 -2
- package/dist/sprite.d.ts.map +1 -1
- package/dist/sprite.js +57 -0
- package/dist/sprite.js.map +1 -1
- package/dist/utils/editSessionHunks.d.ts +5 -4
- package/dist/utils/editSessionHunks.d.ts.map +1 -1
- package/dist/utils/editSessionHunks.js +32 -9
- package/dist/utils/editSessionHunks.js.map +1 -1
- package/dist/utils/parsePatchFiles.d.ts.map +1 -1
- package/dist/utils/parsePatchFiles.js +21 -13
- package/dist/utils/parsePatchFiles.js.map +1 -1
- package/dist/utils/parseQuotedDiffFileName.d.ts +8 -0
- package/dist/utils/parseQuotedDiffFileName.d.ts.map +1 -0
- package/dist/utils/parseQuotedDiffFileName.js +54 -0
- package/dist/utils/parseQuotedDiffFileName.js.map +1 -0
- package/dist/utils/realignChangeContent.d.ts +13 -10
- package/dist/utils/realignChangeContent.d.ts.map +1 -1
- package/dist/utils/realignChangeContent.js +23 -19
- package/dist/utils/realignChangeContent.js.map +1 -1
- package/dist/worker/WorkerPoolManager.d.ts.map +1 -1
- package/dist/worker/WorkerPoolManager.js +40 -38
- package/dist/worker/WorkerPoolManager.js.map +1 -1
- package/dist/worker/worker-portable.js +8 -1
- package/dist/worker/worker-portable.js.map +1 -1
- package/dist/worker/worker.js +8 -1
- package/dist/worker/worker.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"textMeasure.d.ts","names":[],"sources":["../../src/editor/textMeasure.ts"],"mappings":";cAUa;;;
|
|
1
|
+
{"version":3,"file":"textMeasure.d.ts","names":[],"sources":["../../src/editor/textMeasure.ts"],"mappings":";cAUa;;;EAUX;;EAEA;;EAEA;;EAEA;;EAGA,KAAK,MAAM;;;;;;;;;;;;;;;;EA+DX;;EAwCA,iBAAiB;;;;;EA0CjB,iBACE,kBACA,sBACA;;EAoBF,uBAAuB;;;;;;EAYvB,oBAAoB;;;;;;EAiDpB;;;iBAYc,wBAAwB;;iBAiBxB,gCACd,cACA;;iBA6Cc,6BACd;;;;;;iBA2Bc,4BACd,cACA"}
|
|
@@ -4,6 +4,7 @@ const TEXT_WIDTH_CACHE_LIMIT = 4096;
|
|
|
4
4
|
const COMBINING_MARK_PATTERN = /\p{Mark}/u;
|
|
5
5
|
var Metrics = class {
|
|
6
6
|
#root;
|
|
7
|
+
#canvas;
|
|
7
8
|
#canvasCtx;
|
|
8
9
|
#font;
|
|
9
10
|
#textWidthCache = /* @__PURE__ */ new Map();
|
|
@@ -19,7 +20,8 @@ var Metrics = class {
|
|
|
19
20
|
init(root) {
|
|
20
21
|
if (this.#root === root && this.#canvasCtx !== void 0 && this.ch !== -1) return;
|
|
21
22
|
this.#root = root;
|
|
22
|
-
this.#
|
|
23
|
+
this.#canvas ??= h("canvas", { style: { display: "none" } });
|
|
24
|
+
this.#canvasCtx ??= this.#canvas.getContext("2d") ?? void 0;
|
|
23
25
|
if (this.#canvasCtx === void 0) throw new Error("Could not get canvas context");
|
|
24
26
|
const parent = root.parentElement;
|
|
25
27
|
if (parent !== null) {
|
|
@@ -32,7 +34,7 @@ var Metrics = class {
|
|
|
32
34
|
const font = fontSize + " " + fontFamily;
|
|
33
35
|
if (this.#font !== font || this.ch === -1) {
|
|
34
36
|
this.#font = font;
|
|
35
|
-
this.#
|
|
37
|
+
this.#setCanvasFont(font);
|
|
36
38
|
this.ch = this.canvasMeasureTextWidth("0");
|
|
37
39
|
this.clearTextWidthCache();
|
|
38
40
|
}
|
|
@@ -56,13 +58,35 @@ var Metrics = class {
|
|
|
56
58
|
*/
|
|
57
59
|
remeasureCharacterWidth() {
|
|
58
60
|
if (this.#canvasCtx === void 0 || this.#font === void 0) return false;
|
|
59
|
-
this.#
|
|
61
|
+
this.#setCanvasFont(this.#font);
|
|
60
62
|
const ch = this.canvasMeasureTextWidth("0");
|
|
61
63
|
const characterWidthChanged = ch !== this.ch;
|
|
62
64
|
if (characterWidthChanged) this.ch = ch;
|
|
63
65
|
const textWidthCacheCleared = this.#clearTextWidthCache();
|
|
64
66
|
return characterWidthChanged || textWidthCacheCleared;
|
|
65
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Set the canvas font while the canvas is connected to the document.
|
|
70
|
+
*
|
|
71
|
+
* WebKit resolves a canvas font from the canvas element's computed style at
|
|
72
|
+
* assignment. A detached canvas has none, so WebKit ignores user-installed
|
|
73
|
+
* fonts and measures the fallback family while the DOM renders the real font,
|
|
74
|
+
* shifting every caret and selection in hosts that allow user-installed fonts
|
|
75
|
+
* (WKWebView, Playwright WebKit). Connecting the canvas for the assignment
|
|
76
|
+
* makes it measure the same font the DOM renders.
|
|
77
|
+
*/
|
|
78
|
+
#setCanvasFont(font) {
|
|
79
|
+
const root = this.#root;
|
|
80
|
+
const canvas = this.#canvas;
|
|
81
|
+
const canvasCtx = this.#canvasCtx;
|
|
82
|
+
if (root == null || canvas == null || canvasCtx == null) throw new Error("Metrics not initialized");
|
|
83
|
+
root.append(canvas);
|
|
84
|
+
try {
|
|
85
|
+
canvasCtx.font = font;
|
|
86
|
+
} finally {
|
|
87
|
+
canvas.remove();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
66
90
|
/** measure the width of the text */
|
|
67
91
|
measureTextWidth(text) {
|
|
68
92
|
if (!text.includes(" ")) return this.#measureTextWidthWithoutTabs(text);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"textMeasure.js","names":[],"sources":["../../src/editor/textMeasure.ts"],"sourcesContent":["import { getGraphemeSegmenter, h, round } from './utils';\n\n// Upper bound on cached DOM text-width measurements. The cache only holds\n// non-ASCII runs (emoji, ZWJ sequences, variation selectors, combining marks),\n// so it stays small for ordinary code, but capping it prevents unbounded growth\n// on emoji-heavy documents. Past the cap the oldest entry is evicted.\nconst TEXT_WIDTH_CACHE_LIMIT = 4096;\n\nconst COMBINING_MARK_PATTERN = /\\p{Mark}/u;\n\nexport class Metrics {\n #root?: HTMLElement;\n #canvasCtx?: CanvasRenderingContext2D;\n #font?: string;\n\n // Memoizes domMeasureTextWidth() results\n #textWidthCache = new Map<string, number>();\n\n /** Width of the '0' character. */\n ch: number = -1;\n /** Size of a tab(\\t) character. */\n tabSize: number = 2;\n /** Height of the code line. */\n lineHeight: number = 20;\n /** Padding top of the root element. */\n paddingTop: number = 0;\n\n /** initialize the metrics */\n init(root: HTMLElement): void {\n if (\n this.#root === root &&\n this.#canvasCtx !== undefined &&\n this.ch !== -1\n ) {\n // already initialized\n return;\n }\n\n this.#root = root;\n this.#canvasCtx ??=\n document.createElement('canvas').getContext('2d') ?? undefined;\n if (this.#canvasCtx === undefined) {\n throw new Error('Could not get canvas context');\n }\n\n const parent = root.parentElement;\n if (parent !== null) {\n const { paddingTop } = getComputedStyle(parent);\n if (paddingTop.endsWith('px')) {\n this.paddingTop = parseFloat(paddingTop.slice(0, -2));\n }\n }\n\n const { fontSize, fontFamily, tabSize, lineHeight } =\n getComputedStyle(root);\n if (lineHeight.endsWith('px')) {\n this.lineHeight = parseFloat(lineHeight.slice(0, -2));\n } else if (fontSize.endsWith('px')) {\n this.lineHeight = round(\n parseFloat(fontSize.slice(0, -2)) * parseFloat(lineHeight)\n );\n }\n const font = fontSize + ' ' + fontFamily;\n if (this.#font !== font || this.ch === -1) {\n this.#font = font;\n this.#canvasCtx.font = font;\n this.ch = this.canvasMeasureTextWidth('0');\n // Cached DOM widths were measured against the previous font.\n this.clearTextWidthCache();\n }\n const nextTabSize = parseInt(tabSize, 10);\n if (!Number.isNaN(nextTabSize)) {\n this.tabSize = nextTabSize;\n }\n }\n\n /**\n * Re-measure the '0' character width against the font that is loaded right\n * now, returning true when measurement-dependent UI should refresh.\n *\n * A custom web font can finish loading after the editor first renders.\n * Until then canvas measureText reports the fallback font's width, and\n * getComputedStyle returns the same font-family string before and after the\n * file arrives, so init()'s font guard never re-measures on its own. Call\n * this once fonts have settled (e.g. on document.fonts.ready) to replace a\n * width measured against the fallback font with the real glyph width. Font\n * completion can also change DOM-measured emoji/ZWJ widths while leaving the\n * ASCII width unchanged, and the computed font string stays the same in both\n * cases. The boolean return lets the caller skip re-rendering when there is no\n * measured state to refresh.\n */\n remeasureCharacterWidth(): boolean {\n if (this.#canvasCtx === undefined || this.#font === undefined) {\n return false;\n }\n this.#canvasCtx.font = this.#font;\n const ch = this.canvasMeasureTextWidth('0');\n const characterWidthChanged = ch !== this.ch;\n if (characterWidthChanged) {\n this.ch = ch;\n }\n const textWidthCacheCleared = this.#clearTextWidthCache();\n return characterWidthChanged || textWidthCacheCleared;\n }\n\n /** measure the width of the text */\n measureTextWidth(text: string): number {\n if (!text.includes('\\t')) {\n return this.#measureTextWidthWithoutTabs(text);\n }\n if (this.#canvasCtx === undefined) {\n throw new Error('Metrics not initialized');\n }\n const asciiColumns = getExpandedAsciiTextColumns(text, this.tabSize);\n if (asciiColumns !== -1) {\n return asciiColumns * this.ch;\n }\n\n let width = 0;\n let runStart = 0;\n const tabStopWidth = this.tabSize * this.ch;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) !== /* '\\t' */ 9) {\n continue;\n }\n\n if (i > runStart) {\n width += this.#measureTextWidthWithoutTabs(text.slice(runStart, i));\n }\n // CSS tab stops are pixel positions, so wide glyphs before a tab must\n // contribute their measured width rather than one logical column.\n if (tabStopWidth > 0) {\n const remainder = width % tabStopWidth;\n width += remainder === 0 ? tabStopWidth : tabStopWidth - remainder;\n }\n runStart = i + 1;\n }\n\n if (runStart < text.length) {\n width += this.#measureTextWidthWithoutTabs(text.slice(runStart));\n }\n return round(width);\n }\n\n /**\n * Pixel width from a wrapped segment's start up to a character. Tabs advance\n * from the segment start so their stops line up with the rendered text.\n */\n segmentTextWidth(\n lineText: string,\n segmentStart: number,\n character: number\n ): number {\n if (character <= segmentStart) {\n return 0;\n }\n const segmentText = lineText.slice(segmentStart, character);\n const asciiColumns = getExpandedAsciiTextColumns(segmentText, this.tabSize);\n return asciiColumns !== -1\n ? asciiColumns * this.ch\n : this.measureTextWidth(segmentText);\n }\n\n #measureTextWidthWithoutTabs(text: string): number {\n if (needsDomTextMeasurement(text)) {\n return this.domMeasureTextWidth(text);\n }\n return this.canvasMeasureTextWidth(text);\n }\n\n /** measure the width of the text using the canvas measureText API */\n canvasMeasureTextWidth(text: string): number {\n if (this.#canvasCtx === undefined) {\n throw new Error('Metrics not initialized');\n }\n return round(this.#canvasCtx.measureText(text).width);\n }\n\n /**\n * measure the width of the text using the DOM\n * this is slow because it cause a reflow, use it for non-ascii text;\n * results are memoized per text so repeated measurements skip the reflow\n */\n domMeasureTextWidth(text: string): number {\n if (this.#root === undefined) {\n throw new Error('Metrics not initialized');\n }\n const cacheKey = text + '|' + this.#font;\n const cached = this.#textWidthCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n const measureEl = h(\n 'span',\n {\n style: {\n position: 'absolute',\n top: '0',\n left: '0',\n visibility: 'hidden',\n pointerEvents: 'none',\n whiteSpace: 'pre',\n font: 'inherit',\n },\n textContent: text,\n },\n this.#root\n );\n let width: number;\n try {\n // round() to match canvasMeasureTextWidth and ch; otherwise the DOM path\n // returns raw sub-pixel widths and caret/selection offsets drift between\n // ASCII and non-ASCII runs on the same line.\n width = round(measureEl.getBoundingClientRect().width);\n } finally {\n measureEl.remove();\n }\n if (this.#textWidthCache.size >= TEXT_WIDTH_CACHE_LIMIT) {\n const oldestKey = this.#textWidthCache.keys().next().value;\n if (oldestKey !== undefined) {\n this.#textWidthCache.delete(oldestKey);\n }\n }\n this.#textWidthCache.set(cacheKey, width);\n return width;\n }\n\n /**\n * discard memoized DOM text widths\n * call this when the inherited font may have changed without re-running\n * init(), e.g. on a layout reflow, so stale widths are not reused\n */\n clearTextWidthCache(): void {\n this.#clearTextWidthCache();\n }\n\n #clearTextWidthCache(): boolean {\n const hadCachedTextWidths = this.#textWidthCache.size > 0;\n this.#textWidthCache.clear();\n return hadCachedTextWidths;\n }\n}\n\n/** Check if the text needs DOM text measurement. */\nexport function needsDomTextMeasurement(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (\n (code >= 0xd800 && code <= 0xdfff) ||\n code === 0x200d ||\n code === 0xfe0e ||\n code === 0xfe0f ||\n (code > 0x7f && COMBINING_MARK_PATTERN.test(text.charAt(i)))\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** snap the text offset to the Unicode boundary */\nexport function snapTextOffsetToUnicodeBoundary(\n text: string,\n offset: number\n): number {\n const boundedOffset = Math.max(0, Math.min(offset, text.length));\n if (\n boundedOffset === 0 ||\n boundedOffset === text.length ||\n !needsDomTextMeasurement(text)\n ) {\n return boundedOffset;\n }\n // Avoid measuring a caret position inside one visual emoji/grapheme.\n // Browser caret movement can report offsets around UTF-16 surrogate\n // pairs and emoji joiners; measuring a partial sequence gives a\n // replacement-glyph width.\n const segmenter = getGraphemeSegmenter();\n if (segmenter !== undefined) {\n for (const segment of segmenter.segment(text)) {\n const segmentStart = segment.index;\n const segmentEnd = segmentStart + segment.segment.length;\n if (boundedOffset > segmentStart && boundedOffset < segmentEnd) {\n return segmentEnd;\n }\n if (boundedOffset <= segmentStart) {\n break;\n }\n }\n return boundedOffset;\n }\n // Degraded path for engines lacking Intl.Segmenter: snap out of a\n // surrogate pair by stepping over code points.\n let segmentStart = 0;\n for (const codePoint of text) {\n const segmentEnd = segmentStart + codePoint.length;\n if (boundedOffset > segmentStart && boundedOffset < segmentEnd) {\n return segmentEnd;\n }\n if (boundedOffset <= segmentStart) {\n break;\n }\n segmentStart = segmentEnd;\n }\n return boundedOffset;\n}\n\n/** get the offsets of the Unicode grapheme clusters in the text */\nexport function getUnicodeMeasurementOffsets(\n text: string\n): number[] | undefined {\n if (!needsDomTextMeasurement(text)) {\n return undefined;\n }\n const offsets = [0];\n const segmenter = getGraphemeSegmenter();\n if (segmenter !== undefined) {\n for (const segment of segmenter.segment(text)) {\n offsets.push(segment.index + segment.segment.length);\n }\n return offsets;\n }\n // Degraded path for engines lacking Intl.Segmenter: step by code point.\n let offset = 0;\n for (const codePoint of text) {\n offset += codePoint.length;\n offsets.push(offset);\n }\n return offsets;\n}\n\n/**\n * Count the rendered columns of ASCII text, advancing each tab to the next\n * fixed tab stop (a multiple of tabSize) to match CSS `tab-size`. Returns -1\n * for non-ASCII text, which must be measured glyph-by-glyph instead.\n */\nexport function getExpandedAsciiTextColumns(\n text: string,\n tabSize: number\n): number {\n let columns = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code > 127) {\n return -1;\n }\n columns += code === /* '\\t' */ 9 ? tabSize - (columns % tabSize) : 1;\n }\n return columns;\n}\n"],"mappings":";;AAMA,MAAM,yBAAyB;AAE/B,MAAM,yBAAyB;AAE/B,IAAa,UAAb,MAAqB;CACnB;CACA;CACA;CAGA,kCAAkB,IAAI,IAAoB;;CAG1C,KAAa;;CAEb,UAAkB;;CAElB,aAAqB;;CAErB,aAAqB;;CAGrB,KAAK,MAAyB;EAC5B,IACE,KAAK,UAAU,QACf,KAAK,eAAe,KAAA,KACpB,KAAK,OAAO,IAGZ;EAGF,KAAK,QAAQ;EACb,KAAK,eACH,SAAS,cAAc,QAAQ,CAAC,CAAC,WAAW,IAAI,KAAK,KAAA;EACvD,IAAI,KAAK,eAAe,KAAA,GACtB,MAAM,IAAI,MAAM,8BAA8B;EAGhD,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,MAAM;GACnB,MAAM,EAAE,eAAe,iBAAiB,MAAM;GAC9C,IAAI,WAAW,SAAS,IAAI,GAC1B,KAAK,aAAa,WAAW,WAAW,MAAM,GAAG,EAAE,CAAC;EAExD;EAEA,MAAM,EAAE,UAAU,YAAY,SAAS,eACrC,iBAAiB,IAAI;EACvB,IAAI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YAClD,OAAO;EAET,IAAI,iBAAiB,cACnB;EAEF,eAAe;CACjB;CACA,OAAO;AACT;;AAGA,SAAgB,6BACd,MACsB;CACtB,IAAI,CAAC,wBAAwB,IAAI,GAC/B;CAEF,MAAM,UAAU,CAAC,CAAC;CAClB,MAAM,YAAY,qBAAqB;CACvC,IAAI,cAAc,KAAA,GAAW;EAC3B,KAAK,MAAM,WAAW,UAAU,QAAQ,IAAI,GAC1C,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,QAAQ,MAAM;EAErD,OAAO;CACT;CAEA,IAAI,SAAS;CACb,KAAK,MAAM,aAAa,MAAM;EAC5B,UAAU,UAAU;EACpB,QAAQ,KAAK,MAAM;CACrB;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,4BACd,MACA,SACQ;CACR,IAAI,UAAU;CACd,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,OAAO,KAAK,WAAW,CAAC;EAC9B,IAAI,OAAO,KACT,OAAO;EAET,WAAW,SAAoB,IAAI,UAAW,UAAU,UAAW;CACrE;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"textMeasure.js","names":[],"sources":["../../src/editor/textMeasure.ts"],"sourcesContent":["import { getGraphemeSegmenter, h, round } from './utils';\n\n// Upper bound on cached DOM text-width measurements. The cache only holds\n// non-ASCII runs (emoji, ZWJ sequences, variation selectors, combining marks),\n// so it stays small for ordinary code, but capping it prevents unbounded growth\n// on emoji-heavy documents. Past the cap the oldest entry is evicted.\nconst TEXT_WIDTH_CACHE_LIMIT = 4096;\n\nconst COMBINING_MARK_PATTERN = /\\p{Mark}/u;\n\nexport class Metrics {\n #root?: HTMLElement;\n #canvas?: HTMLCanvasElement;\n #canvasCtx?: CanvasRenderingContext2D;\n #font?: string;\n\n // Memoizes domMeasureTextWidth() results\n #textWidthCache = new Map<string, number>();\n\n /** Width of the '0' character. */\n ch: number = -1;\n /** Size of a tab(\\t) character. */\n tabSize: number = 2;\n /** Height of the code line. */\n lineHeight: number = 20;\n /** Padding top of the root element. */\n paddingTop: number = 0;\n\n /** initialize the metrics */\n init(root: HTMLElement): void {\n if (\n this.#root === root &&\n this.#canvasCtx !== undefined &&\n this.ch !== -1\n ) {\n // already initialized\n return;\n }\n\n this.#root = root;\n this.#canvas ??= h('canvas', { style: { display: 'none' } });\n this.#canvasCtx ??= this.#canvas.getContext('2d') ?? undefined;\n if (this.#canvasCtx === undefined) {\n throw new Error('Could not get canvas context');\n }\n\n const parent = root.parentElement;\n if (parent !== null) {\n const { paddingTop } = getComputedStyle(parent);\n if (paddingTop.endsWith('px')) {\n this.paddingTop = parseFloat(paddingTop.slice(0, -2));\n }\n }\n\n const { fontSize, fontFamily, tabSize, lineHeight } =\n getComputedStyle(root);\n if (lineHeight.endsWith('px')) {\n this.lineHeight = parseFloat(lineHeight.slice(0, -2));\n } else if (fontSize.endsWith('px')) {\n this.lineHeight = round(\n parseFloat(fontSize.slice(0, -2)) * parseFloat(lineHeight)\n );\n }\n const font = fontSize + ' ' + fontFamily;\n if (this.#font !== font || this.ch === -1) {\n this.#font = font;\n this.#setCanvasFont(font);\n this.ch = this.canvasMeasureTextWidth('0');\n // Cached DOM widths were measured against the previous font.\n this.clearTextWidthCache();\n }\n const nextTabSize = parseInt(tabSize, 10);\n if (!Number.isNaN(nextTabSize)) {\n this.tabSize = nextTabSize;\n }\n }\n\n /**\n * Re-measure the '0' character width against the font that is loaded right\n * now, returning true when measurement-dependent UI should refresh.\n *\n * A custom web font can finish loading after the editor first renders.\n * Until then canvas measureText reports the fallback font's width, and\n * getComputedStyle returns the same font-family string before and after the\n * file arrives, so init()'s font guard never re-measures on its own. Call\n * this once fonts have settled (e.g. on document.fonts.ready) to replace a\n * width measured against the fallback font with the real glyph width. Font\n * completion can also change DOM-measured emoji/ZWJ widths while leaving the\n * ASCII width unchanged, and the computed font string stays the same in both\n * cases. The boolean return lets the caller skip re-rendering when there is no\n * measured state to refresh.\n */\n remeasureCharacterWidth(): boolean {\n if (this.#canvasCtx === undefined || this.#font === undefined) {\n return false;\n }\n this.#setCanvasFont(this.#font);\n const ch = this.canvasMeasureTextWidth('0');\n const characterWidthChanged = ch !== this.ch;\n if (characterWidthChanged) {\n this.ch = ch;\n }\n const textWidthCacheCleared = this.#clearTextWidthCache();\n return characterWidthChanged || textWidthCacheCleared;\n }\n\n /**\n * Set the canvas font while the canvas is connected to the document.\n *\n * WebKit resolves a canvas font from the canvas element's computed style at\n * assignment. A detached canvas has none, so WebKit ignores user-installed\n * fonts and measures the fallback family while the DOM renders the real font,\n * shifting every caret and selection in hosts that allow user-installed fonts\n * (WKWebView, Playwright WebKit). Connecting the canvas for the assignment\n * makes it measure the same font the DOM renders.\n */\n #setCanvasFont(font: string): void {\n const root = this.#root;\n const canvas = this.#canvas;\n const canvasCtx = this.#canvasCtx;\n if (root == null || canvas == null || canvasCtx == null) {\n throw new Error('Metrics not initialized');\n }\n root.append(canvas);\n try {\n canvasCtx.font = font;\n } finally {\n canvas.remove();\n }\n }\n\n /** measure the width of the text */\n measureTextWidth(text: string): number {\n if (!text.includes('\\t')) {\n return this.#measureTextWidthWithoutTabs(text);\n }\n if (this.#canvasCtx === undefined) {\n throw new Error('Metrics not initialized');\n }\n const asciiColumns = getExpandedAsciiTextColumns(text, this.tabSize);\n if (asciiColumns !== -1) {\n return asciiColumns * this.ch;\n }\n\n let width = 0;\n let runStart = 0;\n const tabStopWidth = this.tabSize * this.ch;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) !== /* '\\t' */ 9) {\n continue;\n }\n\n if (i > runStart) {\n width += this.#measureTextWidthWithoutTabs(text.slice(runStart, i));\n }\n // CSS tab stops are pixel positions, so wide glyphs before a tab must\n // contribute their measured width rather than one logical column.\n if (tabStopWidth > 0) {\n const remainder = width % tabStopWidth;\n width += remainder === 0 ? tabStopWidth : tabStopWidth - remainder;\n }\n runStart = i + 1;\n }\n\n if (runStart < text.length) {\n width += this.#measureTextWidthWithoutTabs(text.slice(runStart));\n }\n return round(width);\n }\n\n /**\n * Pixel width from a wrapped segment's start up to a character. Tabs advance\n * from the segment start so their stops line up with the rendered text.\n */\n segmentTextWidth(\n lineText: string,\n segmentStart: number,\n character: number\n ): number {\n if (character <= segmentStart) {\n return 0;\n }\n const segmentText = lineText.slice(segmentStart, character);\n const asciiColumns = getExpandedAsciiTextColumns(segmentText, this.tabSize);\n return asciiColumns !== -1\n ? asciiColumns * this.ch\n : this.measureTextWidth(segmentText);\n }\n\n #measureTextWidthWithoutTabs(text: string): number {\n if (needsDomTextMeasurement(text)) {\n return this.domMeasureTextWidth(text);\n }\n return this.canvasMeasureTextWidth(text);\n }\n\n /** measure the width of the text using the canvas measureText API */\n canvasMeasureTextWidth(text: string): number {\n if (this.#canvasCtx === undefined) {\n throw new Error('Metrics not initialized');\n }\n return round(this.#canvasCtx.measureText(text).width);\n }\n\n /**\n * measure the width of the text using the DOM\n * this is slow because it cause a reflow, use it for non-ascii text;\n * results are memoized per text so repeated measurements skip the reflow\n */\n domMeasureTextWidth(text: string): number {\n if (this.#root === undefined) {\n throw new Error('Metrics not initialized');\n }\n const cacheKey = text + '|' + this.#font;\n const cached = this.#textWidthCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n const measureEl = h(\n 'span',\n {\n style: {\n position: 'absolute',\n top: '0',\n left: '0',\n visibility: 'hidden',\n pointerEvents: 'none',\n whiteSpace: 'pre',\n font: 'inherit',\n },\n textContent: text,\n },\n this.#root\n );\n let width: number;\n try {\n // round() to match canvasMeasureTextWidth and ch; otherwise the DOM path\n // returns raw sub-pixel widths and caret/selection offsets drift between\n // ASCII and non-ASCII runs on the same line.\n width = round(measureEl.getBoundingClientRect().width);\n } finally {\n measureEl.remove();\n }\n if (this.#textWidthCache.size >= TEXT_WIDTH_CACHE_LIMIT) {\n const oldestKey = this.#textWidthCache.keys().next().value;\n if (oldestKey !== undefined) {\n this.#textWidthCache.delete(oldestKey);\n }\n }\n this.#textWidthCache.set(cacheKey, width);\n return width;\n }\n\n /**\n * discard memoized DOM text widths\n * call this when the inherited font may have changed without re-running\n * init(), e.g. on a layout reflow, so stale widths are not reused\n */\n clearTextWidthCache(): void {\n this.#clearTextWidthCache();\n }\n\n #clearTextWidthCache(): boolean {\n const hadCachedTextWidths = this.#textWidthCache.size > 0;\n this.#textWidthCache.clear();\n return hadCachedTextWidths;\n }\n}\n\n/** Check if the text needs DOM text measurement. */\nexport function needsDomTextMeasurement(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (\n (code >= 0xd800 && code <= 0xdfff) ||\n code === 0x200d ||\n code === 0xfe0e ||\n code === 0xfe0f ||\n (code > 0x7f && COMBINING_MARK_PATTERN.test(text.charAt(i)))\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** snap the text offset to the Unicode boundary */\nexport function snapTextOffsetToUnicodeBoundary(\n text: string,\n offset: number\n): number {\n const boundedOffset = Math.max(0, Math.min(offset, text.length));\n if (\n boundedOffset === 0 ||\n boundedOffset === text.length ||\n !needsDomTextMeasurement(text)\n ) {\n return boundedOffset;\n }\n // Avoid measuring a caret position inside one visual emoji/grapheme.\n // Browser caret movement can report offsets around UTF-16 surrogate\n // pairs and emoji joiners; measuring a partial sequence gives a\n // replacement-glyph width.\n const segmenter = getGraphemeSegmenter();\n if (segmenter !== undefined) {\n for (const segment of segmenter.segment(text)) {\n const segmentStart = segment.index;\n const segmentEnd = segmentStart + segment.segment.length;\n if (boundedOffset > segmentStart && boundedOffset < segmentEnd) {\n return segmentEnd;\n }\n if (boundedOffset <= segmentStart) {\n break;\n }\n }\n return boundedOffset;\n }\n // Degraded path for engines lacking Intl.Segmenter: snap out of a\n // surrogate pair by stepping over code points.\n let segmentStart = 0;\n for (const codePoint of text) {\n const segmentEnd = segmentStart + codePoint.length;\n if (boundedOffset > segmentStart && boundedOffset < segmentEnd) {\n return segmentEnd;\n }\n if (boundedOffset <= segmentStart) {\n break;\n }\n segmentStart = segmentEnd;\n }\n return boundedOffset;\n}\n\n/** get the offsets of the Unicode grapheme clusters in the text */\nexport function getUnicodeMeasurementOffsets(\n text: string\n): number[] | undefined {\n if (!needsDomTextMeasurement(text)) {\n return undefined;\n }\n const offsets = [0];\n const segmenter = getGraphemeSegmenter();\n if (segmenter !== undefined) {\n for (const segment of segmenter.segment(text)) {\n offsets.push(segment.index + segment.segment.length);\n }\n return offsets;\n }\n // Degraded path for engines lacking Intl.Segmenter: step by code point.\n let offset = 0;\n for (const codePoint of text) {\n offset += codePoint.length;\n offsets.push(offset);\n }\n return offsets;\n}\n\n/**\n * Count the rendered columns of ASCII text, advancing each tab to the next\n * fixed tab stop (a multiple of tabSize) to match CSS `tab-size`. Returns -1\n * for non-ASCII text, which must be measured glyph-by-glyph instead.\n */\nexport function getExpandedAsciiTextColumns(\n text: string,\n tabSize: number\n): number {\n let columns = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code > 127) {\n return -1;\n }\n columns += code === /* '\\t' */ 9 ? tabSize - (columns % tabSize) : 1;\n }\n return columns;\n}\n"],"mappings":";;AAMA,MAAM,yBAAyB;AAE/B,MAAM,yBAAyB;AAE/B,IAAa,UAAb,MAAqB;CACnB;CACA;CACA;CACA;CAGA,kCAAkB,IAAI,IAAoB;;CAG1C,KAAa;;CAEb,UAAkB;;CAElB,aAAqB;;CAErB,aAAqB;;CAGrB,KAAK,MAAyB;EAC5B,IACE,KAAK,UAAU,QACf,KAAK,eAAe,KAAA,KACpB,KAAK,OAAO,IAGZ;EAGF,KAAK,QAAQ;EACb,KAAK,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,OAAO,EAAE,CAAC;EAC3D,KAAK,eAAe,KAAK,QAAQ,WAAW,IAAI,KAAK,KAAA;EACrD,IAAI,KAAK,eAAe,KAAA,GACtB,MAAM,IAAI,MAAM,8BAA8B;EAGhD,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,MAAM;GACnB,MAAM,EAAE,eAAe,iBAAiB,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ResolvedLanguages.set(resolvedLang.name, lang);
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
const grammar = lang.data.find((grammar) => grammar.name === lang.name || grammar.aliases?.includes(lang.name) === true);
|
|
13
|
+
if (grammar == null) throw new Error(`attachResolvedLanguages: No returned grammar declares "${lang.name}" as its name or an alias.`);
|
|
13
14
|
highlighter.loadLanguageSync(lang.data);
|
|
15
|
+
try {
|
|
16
|
+
highlighter.getLanguage(lang.name);
|
|
17
|
+
} catch {
|
|
18
|
+
throw new Error(`attachResolvedLanguages: "${grammar.name}" is already loaded without alias "${lang.name}". Load the alias first or give the grammar a unique name.`);
|
|
19
|
+
}
|
|
20
|
+
AttachedLanguages.add(lang.name);
|
|
14
21
|
}
|
|
15
22
|
}
|
|
16
23
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachResolvedLanguages.js","names":[],"sources":["../../../src/highlighter/languages/attachResolvedLanguages.ts"],"sourcesContent":["import type { DiffsHighlighter } from '../../types';\nimport type { ResolvedLanguage } from '../../worker';\nimport { AttachedLanguages, ResolvedLanguages } from './constants';\n\nexport function attachResolvedLanguages(\n resolvedLanguages: ResolvedLanguage | ResolvedLanguage[],\n highlighter: DiffsHighlighter\n): void {\n resolvedLanguages = Array.isArray(resolvedLanguages)\n ? resolvedLanguages\n : [resolvedLanguages];\n\n for (const resolvedLang of resolvedLanguages) {\n if (AttachedLanguages.has(resolvedLang.name)) continue;\n let lang = ResolvedLanguages.get(resolvedLang.name);\n if (lang == null) {\n lang = resolvedLang;\n ResolvedLanguages.set(resolvedLang.name, lang);\n }\n
|
|
1
|
+
{"version":3,"file":"attachResolvedLanguages.js","names":[],"sources":["../../../src/highlighter/languages/attachResolvedLanguages.ts"],"sourcesContent":["import type { DiffsHighlighter } from '../../types';\nimport type { ResolvedLanguage } from '../../worker';\nimport { AttachedLanguages, ResolvedLanguages } from './constants';\n\nexport function attachResolvedLanguages(\n resolvedLanguages: ResolvedLanguage | ResolvedLanguage[],\n highlighter: DiffsHighlighter\n): void {\n resolvedLanguages = Array.isArray(resolvedLanguages)\n ? resolvedLanguages\n : [resolvedLanguages];\n\n for (const resolvedLang of resolvedLanguages) {\n if (AttachedLanguages.has(resolvedLang.name)) continue;\n let lang = ResolvedLanguages.get(resolvedLang.name);\n if (lang == null) {\n lang = resolvedLang;\n ResolvedLanguages.set(resolvedLang.name, lang);\n }\n const grammar = lang.data.find(\n (grammar) =>\n grammar.name === lang.name ||\n grammar.aliases?.includes(lang.name) === true\n );\n if (grammar == null) {\n throw new Error(\n `attachResolvedLanguages: No returned grammar declares \"${lang.name}\" as its name or an alias.`\n );\n }\n highlighter.loadLanguageSync(lang.data);\n // Shiki can skip an already-loaded grammar, including any newly added aliases.\n try {\n highlighter.getLanguage(lang.name);\n } catch {\n throw new Error(\n `attachResolvedLanguages: \"${grammar.name}\" is already loaded without alias \"${lang.name}\". Load the alias first or give the grammar a unique name.`\n );\n }\n AttachedLanguages.add(lang.name);\n }\n}\n"],"mappings":";;AAIA,SAAgB,wBACd,mBACA,aACM;CACN,oBAAoB,MAAM,QAAQ,iBAAiB,IAC/C,oBACA,CAAC,iBAAiB;CAEtB,KAAK,MAAM,gBAAgB,mBAAmB;EAC5C,IAAI,kBAAkB,IAAI,aAAa,IAAI,GAAG;EAC9C,IAAI,OAAO,kBAAkB,IAAI,aAAa,IAAI;EAClD,IAAI,QAAQ,MAAM;GAChB,OAAO;GACP,kBAAkB,IAAI,aAAa,MAAM,IAAI;EAC/C;EACA,MAAM,UAAU,KAAK,KAAK,MACvB,YACC,QAAQ,SAAS,KAAK,QACtB,QAAQ,SAAS,SAAS,KAAK,IAAI,MAAM,IAC7C;EACA,IAAI,WAAW,MACb,MAAM,IAAI,MACR,0DAA0D,KAAK,KAAK,2BACtE;EAEF,YAAY,iBAAiB,KAAK,IAAI;EAEtC,IAAI;GACF,YAAY,YAAY,KAAK,IAAI;EACnC,QAAQ;GACN,MAAM,IAAI,MACR,6BAA6B,QAAQ,KAAK,qCAAqC,KAAK,KAAK,2DAC3F;EACF;EACA,kBAAkB,IAAI,KAAK,IAAI;CACjC;AACF"}
|
|
@@ -2,7 +2,9 @@ import { DynamicImportLanguageRegistration } from "shiki";
|
|
|
2
2
|
//#region src/highlighter/languages/registerCustomLanguage.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Register a custom language loader and optionally map it to
|
|
5
|
-
* file names or extensions.
|
|
5
|
+
* file names or extensions. The registered name must match a returned
|
|
6
|
+
* grammar's name or aliases; registering a loader does not automatically add a
|
|
7
|
+
* grammar alias.
|
|
6
8
|
*/
|
|
7
9
|
declare function registerCustomLanguage(lang: string, loader: DynamicImportLanguageRegistration,
|
|
8
10
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerCustomLanguage.d.ts","names":[],"sources":["../../../src/highlighter/languages/registerCustomLanguage.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"registerCustomLanguage.d.ts","names":[],"sources":["../../../src/highlighter/languages/registerCustomLanguage.ts"],"mappings":";;;;;;;;iBAWgB,uBACd,cACA,QAAQ,mCAOR;;;;;;;AAAA"}
|
|
@@ -3,7 +3,9 @@ import { setCustomExtension } from "../../utils/getFiletypeFromFileName.js";
|
|
|
3
3
|
//#region src/highlighter/languages/registerCustomLanguage.ts
|
|
4
4
|
/**
|
|
5
5
|
* Register a custom language loader and optionally map it to
|
|
6
|
-
* file names or extensions.
|
|
6
|
+
* file names or extensions. The registered name must match a returned
|
|
7
|
+
* grammar's name or aliases; registering a loader does not automatically add a
|
|
8
|
+
* grammar alias.
|
|
7
9
|
*/
|
|
8
10
|
function registerCustomLanguage(lang, loader, extensionsOrFilenames = []) {
|
|
9
11
|
if (lang === "text" || lang === "ansi") throw new Error("registerCustomLanguage: 'text' and 'ansi' are reserved language names");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerCustomLanguage.js","names":[],"sources":["../../../src/highlighter/languages/registerCustomLanguage.ts"],"sourcesContent":["import type { DynamicImportLanguageRegistration } from 'shiki';\n\nimport { setCustomExtension } from '../../utils/getFiletypeFromFileName';\nimport { RegisteredCustomLanguages } from './constants';\n\n/**\n * Register a custom language loader and optionally map it to\n * file names or extensions.\n */\nexport function registerCustomLanguage(\n lang: string,\n loader: DynamicImportLanguageRegistration,\n /**\n * File names or extensions to map to this language. Use exact filenames\n * (e.g., \"Dockerfile\", \"CMakeLists.txt\") or extension tokens without a dot\n * (e.g., \"proto\", \"foo\"). Compound extensions are supported\n * (e.g., \"blade.php\").\n */\n extensionsOrFilenames: string[] = []\n): void {\n if (lang === 'text' || lang === 'ansi') {\n throw new Error(\n \"registerCustomLanguage: 'text' and 'ansi' are reserved language names\"\n );\n }\n if (RegisteredCustomLanguages.has(lang)) {\n console.error(\n `registerCustomLanguage: lang: ${lang} is already registered`\n );\n return;\n }\n RegisteredCustomLanguages.set(lang, loader);\n for (const extension of extensionsOrFilenames) {\n setCustomExtension(extension, lang);\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"registerCustomLanguage.js","names":[],"sources":["../../../src/highlighter/languages/registerCustomLanguage.ts"],"sourcesContent":["import type { DynamicImportLanguageRegistration } from 'shiki';\n\nimport { setCustomExtension } from '../../utils/getFiletypeFromFileName';\nimport { RegisteredCustomLanguages } from './constants';\n\n/**\n * Register a custom language loader and optionally map it to\n * file names or extensions. The registered name must match a returned\n * grammar's name or aliases; registering a loader does not automatically add a\n * grammar alias.\n */\nexport function registerCustomLanguage(\n lang: string,\n loader: DynamicImportLanguageRegistration,\n /**\n * File names or extensions to map to this language. Use exact filenames\n * (e.g., \"Dockerfile\", \"CMakeLists.txt\") or extension tokens without a dot\n * (e.g., \"proto\", \"foo\"). Compound extensions are supported\n * (e.g., \"blade.php\").\n */\n extensionsOrFilenames: string[] = []\n): void {\n if (lang === 'text' || lang === 'ansi') {\n throw new Error(\n \"registerCustomLanguage: 'text' and 'ansi' are reserved language names\"\n );\n }\n if (RegisteredCustomLanguages.has(lang)) {\n console.error(\n `registerCustomLanguage: lang: ${lang} is already registered`\n );\n return;\n }\n RegisteredCustomLanguages.set(lang, loader);\n for (const extension of extensionsOrFilenames) {\n setCustomExtension(extension, lang);\n }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,uBACd,MACA,QAOA,wBAAkC,CAAC,GAC7B;CACN,IAAI,SAAS,UAAU,SAAS,QAC9B,MAAM,IAAI,MACR,uEACF;CAEF,IAAI,0BAA0B,IAAI,IAAI,GAAG;EACvC,QAAQ,MACN,iCAAiC,KAAK,uBACxC;EACA;CACF;CACA,0BAA0B,IAAI,MAAM,MAAM;CAC1C,KAAK,MAAM,aAAa,uBACtB,mBAAmB,WAAW,IAAI;AAEtC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { Virtualizer, VirtualizerConfig, VirtualizerScrollOptions } from "./comp
|
|
|
11
11
|
import { VirtualizedFile } from "./components/VirtualizedFile.js";
|
|
12
12
|
import { VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL, VirtualizedFileDiff } from "./components/VirtualizedFileDiff.js";
|
|
13
13
|
import { CODE_VIEW_DIFF_OPTION_KEYS, CODE_VIEW_FILE_OPTION_KEYS, CodeView, CodeViewCoordinator, CodeViewCreateEditorOptions, CodeViewItemEditCompleteEventMap, CodeViewItemEditCompleteHandler, CodeViewLineSelection, CodeViewMode, CodeViewModeItemMap, CodeViewOptions, CodeViewRenderedDiffItem, CodeViewRenderedFileItem, CodeViewRenderedItem, CodeViewScrollListener, CodeViewSlotSnapshot } from "./components/CodeView.js";
|
|
14
|
-
import {
|
|
14
|
+
import { CODE_VIEW_FOOTER_ATTRIBUTE, CODE_VIEW_HEADER_ATTRIBUTE, COMMIT_METADATA_SPLIT, CORE_CSS_ATTRIBUTE, CUSTOM_HEADER_SLOT_ID, DEFAULT_CODE_VIEW_FILE_METRICS, DEFAULT_CODE_VIEW_LAYOUT, DEFAULT_COLLAPSED_CONTEXT_THRESHOLD, DEFAULT_EXPANDED_REGION, DEFAULT_RENDER_RANGE, DEFAULT_SMOOTH_SCROLL_SETTINGS, DEFAULT_THEMES, DEFAULT_TOKENIZE_MAX_LENGTH, DEFAULT_VIRTUAL_FILE_METRICS, DIFFS_DEVELOPMENT_BUILD, DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY, DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, DIFFS_TAG_NAME, EMPTY_RENDER_RANGE, FILENAME_HEADER_REGEX, FILE_CONTEXT_BLOB, GIT_DIFF_FILE_BREAK_REGEX, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID, HUNK_HEADER, INDEX_LINE_METADATA, MERGE_CONFLICT_BASE_MARKER_REGEX, MERGE_CONFLICT_END_MARKER_REGEX, MERGE_CONFLICT_SEPARATOR_MARKER_REGEX, MERGE_CONFLICT_START_MARKER_REGEX, SPLIT_WITH_NEWLINES, THEME_CSS_ATTRIBUTE, UNIFIED_DIFF_FILE_BREAK_REGEX, UNSAFE_CSS_ATTRIBUTE } from "./constants.js";
|
|
15
15
|
import { CodeToTokenTransformStreamOptions, RecallToken, ShikiStreamTokenizerEnqueueResult, ShikiStreamTokenizerOptions } from "./shiki-stream/types.js";
|
|
16
16
|
import { ShikiStreamTokenizer } from "./shiki-stream/tokenizer.js";
|
|
17
17
|
import { CodeToTokenTransformStream } from "./shiki-stream/stream.js";
|
|
@@ -111,4 +111,4 @@ import { setLanguageOverride } from "./utils/setLanguageOverride.js";
|
|
|
111
111
|
import { setPreNodeProperties } from "./utils/setWrapperNodeProps.js";
|
|
112
112
|
import { trimPatchContext } from "./utils/trimPatchContext.js";
|
|
113
113
|
import { codeToHtml, createCssVariablesTheme as createCSSVariablesTheme } from "shiki";
|
|
114
|
-
export {
|
|
114
|
+
export { type AnnotationLineMap, type AnnotationSide, type AnnotationSpan, type AppliedThemeStyleCache, AttachedLanguages, AttachedThemes, type BaseCodeOptions, type BaseDiffOptions, type BaseDiffOptionsWithDefaults, type BundledLanguage, CODE_VIEW_DIFF_OPTION_KEYS, CODE_VIEW_FILE_OPTION_KEYS, CODE_VIEW_FOOTER_ATTRIBUTE, CODE_VIEW_HEADER_ATTRIBUTE, COMMIT_METADATA_SPLIT, CORE_CSS_ATTRIBUTE, CUSTOM_HEADER_SLOT_ID, type ChangeContent, type ChangeTypes, type CodeColumnType, type CodeToHastOptions, CodeToTokenTransformStream, CodeToTokenTransformStreamOptions, CodeView, CodeViewCoordinator, CodeViewCreateEditorOptions, type CodeViewDiffItem, type CodeViewFileItem, type CodeViewItem, CodeViewItemEditCompleteEventMap, CodeViewItemEditCompleteHandler, type CodeViewItemScrollTarget, type CodeViewLayout, type CodeViewLineScrollTarget, CodeViewLineSelection, CodeViewMode, CodeViewModeItemMap, CodeViewOptions, type CodeViewPositionScrollTarget, type CodeViewRangeScrollTarget, CodeViewRenderedDiffItem, CodeViewRenderedFileItem, CodeViewRenderedItem, type CodeViewScrollBehavior, CodeViewScrollListener, type CodeViewScrollTarget, CodeViewSlotSnapshot, type ConflictResolverTypes, type ContextContent, CreateFileHeaderElementProps, type CreatePatchOptionsNonabortable, type CustomPreProperties, CustomThemeLoader, DEFAULT_CODE_VIEW_FILE_METRICS, DEFAULT_CODE_VIEW_LAYOUT, DEFAULT_COLLAPSED_CONTEXT_THRESHOLD, DEFAULT_EXPANDED_REGION, DEFAULT_RENDER_RANGE, DEFAULT_SMOOTH_SCROLL_SETTINGS, DEFAULT_THEMES, DEFAULT_TOKENIZE_MAX_LENGTH, DEFAULT_VIRTUAL_FILE_METRICS, DIFFS_DEVELOPMENT_BUILD, DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY, DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, DIFFS_TAG_NAME, type DecorationItem, type DiffAcceptRejectHunkConfig, type DiffAcceptRejectHunkType, type DiffFileInput, DiffHunksRenderer, DiffHunksRendererOptions, DiffHunksRendererOptionsWithDefaults, type DiffIndicators, type DiffLineAnnotation, type DiffLineEventBaseProps, type DiffTokenEventBaseProps, type DiffsHighlighter, type DiffsThemeNames, EMPTY_RENDER_RANGE, EXTENSION_TO_FILE_FORMAT, type ExpansionDirections, type ExtensionFormatMap, FILENAME_HEADER_REGEX, FILE_CONTEXT_BLOB, File, type FileContents, FileDiff, type FileDiffContentsLoader, FileDiffEditChangeHandler, type FileDiffEditCompleteEvent, FileDiffEditCompleteHandler, FileDiffHydrationProps, type FileDiffLoadedChangedFiles, type FileDiffLoadedFiles, type FileDiffLoadedPureRenamedFile, type FileDiffMetadata, FileDiffOptions, FileDiffRenderBaseProps, FileDiffRenderProps, FileDiffType, FileEditChangeHandler, type FileEditCompleteEvent, FileEditCompleteHandler, type FileHeaderRenderMode, FileHydrateProps, FileOptions, FileRenderProps, FileRenderResult, FileRenderer, FileRendererOptions, FileStream, FileStreamOptions, type ForceDiffPlainTextOptions, type ForceFilePlainTextOptions, GIT_DIFF_FILE_BREAK_REGEX, type GapSpan, GetHoveredLineResult, GetLineIndexUtility, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID, HUNK_HEADER, type HighlightedToken, type HighlighterTypes, type Hunk, type HunkData, type HunkExpansionRegion, type HunkLineType, type HunkSeparators, HunksRenderResult, INDEX_LINE_METADATA, InjectedRow, InteractionManager, InteractionManagerBaseOptions, InteractionManagerMode, InteractionManagerOptions, type LanguageRegistration, type LineAnnotation, LineAnnotationPosition, LineDecoration, type LineDiffTypes, type LineEventBaseProps, type LineInfo, type LineSpans, type LineTypes, LogTypes, MERGE_CONFLICT_BASE_MARKER_REGEX, MERGE_CONFLICT_END_MARKER_REGEX, MERGE_CONFLICT_SEPARATOR_MARKER_REGEX, MERGE_CONFLICT_START_MARKER_REGEX, type MaybeDiffFileInput, type MergeConflictActionPayload, MergeConflictActionTarget, MergeConflictActionsTypeOption, type MergeConflictMarkerRow, type MergeConflictMarkerRowType, type MergeConflictRegion, type MergeConflictResolution, type NumericScrollLineAnchor, type ObservedAnnotationNodes, type ObservedGridNodes, OnDiffLineClickProps, OnDiffLineEnterLeaveProps, OnLineClickProps, OnLineEnterLeaveProps, OnTokenEventProps, ParsedLine, type ParsedPatch, type PendingCodeViewLayoutReset, type PostRenderPhase, type PrePropertiesConfig, type ProcessFileConflictData, RecallToken, RegisteredCustomLanguages, type RenderDiffFilesResult, type RenderDiffOptions, type RenderDiffResult, type RenderFileMetadata, type RenderFileOptions, type RenderFileResult, type RenderHeaderFilenameSuffixCallback, type RenderHeaderMetadataCallback, type RenderHeaderPrefixCallback, RenderMergeConflictActions, type RenderRange, type RenderWindow, type RenderedDiffASTCache, type RenderedFileASTCache, RenderedLineContext, ResizeManager, ResizeManagerColumnVariableMode, ResizeManagerSetupOptions, ResolvedLanguages, ResolvingLanguages, SPLIT_WITH_NEWLINES, SVGSpriteNames, SVGSpriteSheet, ScrollSyncManager, type SelectedLineRange, type SelectionPoint, type SelectionSide, SelectionWriteOptions, type SharedRenderState, ShikiStreamTokenizer, ShikiStreamTokenizerEnqueueResult, ShikiStreamTokenizerOptions, type ShikiTransformer, type SmoothScrollSettings, SplitInjectedRow, SplitInjectedRowPlacement, SplitLineDecorationProps, type StickySpecs, type SupportedLanguages, THEME_CSS_ATTRIBUTE, type ThemeRegistration, type ThemeRegistrationResolved, type ThemeTypes, type ThemedDiffResult, type ThemedFileResult, type ThemedToken, type ThemesType, type TokenEventBase, UNIFIED_DIFF_FILE_BREAK_REGEX, UNSAFE_CSS_ATTRIBUTE, UnifiedInjectedRowPlacement, UnifiedLineDecorationProps, UnresolvedFile, UnresolvedFileHydrationProps, UnresolvedFileOptions, UnresolvedFileRenderProps, VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL, type VirtualFileMetrics, type VirtualWindowSpecs, VirtualizedFile, VirtualizedFileDiff, Virtualizer, VirtualizerConfig, VirtualizerScrollOptions, areDiffLineAnnotationsEqual, areDiffRenderOptionsEqual, areDiffTargetsEqual, areFileRenderOptionsEqual, areFilesEqual, areHunkDataEqual, areLanguagesAttached, areLineAnnotationsEqual, areObjectsEqual, areOptionsEqual, arePrePropertiesEqual, areRenderRangesEqual, areSelectionsEqual, areThemesAttached, areThemesEqual, areVirtualWindowSpecsEqual, areWorkerStatsEqual, attachResolvedLanguages, attachResolvedThemes, cleanLastNewline, cleanUpResolvedLanguages, cleanUpResolvedThemes, clearRenderQueue, cloneFileDiffMetadata, cloneHunks, codeToHtml, createAnnotationElement, createAnnotationWrapperNode, createCSSVariablesTheme, createDiffSpanDecoration, createEmptyRowBuffer, createFileHeaderElement, createGutterGap, createGutterItem, createGutterUtilityContentNode, createGutterUtilityElement, createGutterWrapper, createHastElement, createIconElement, createNoNewlineElement, createPreElement, createPreWrapperProperties, createRowNodes, createSeparator, createSpanFromToken, createStyleElement, createTextNodeElement, createThemeStyleElement, createTransformerWithState, createUnsafeCSSStyleNode, createWindowFromScrollPosition, dequeueRender, detachString, diffAcceptRejectHunk, disposeHighlighter, findCodeElement, formatCSSVariablePrefix, getCustomExtensionsMap, getCustomExtensionsVersion, getFiletypeFromFileName, getHighlighterIfLoaded, getHighlighterOptions, getHighlighterThemeStyles, getHunkSeparatorSlotName, getIconForType, getLineAnnotationName, getLineAnnotationSource, getLineEndingType, getLineNodes, getOrCreateCodeNode, getResolvedLanguages, getResolvedOrResolveLanguage, getResolvedOrResolveTheme, getResolvedThemes, getSharedHighlighter, getSingularPatch, getThemes, getTotalLineCountFromHunks, getUnresolvedDiffHunksRendererOptions, hasResolvedLanguages, hasResolvedThemes, hydratePartialDiff, isDefaultRenderRange, isDiffAnnotation, isDiffAnnotationCollection, isFileAnnotation, isFileAnnotationCollection, isHighlighterLoaded, isHighlighterLoading, isHighlighterNull, isWorkerContext, parseDiffFromFile, parseLineType, parsePatchFiles, patchScrollbarGutterSize, pluckInteractionOptions, prefersReducedMotion, preloadHighlighter, prerenderHTMLIfNecessary, processFile, processLine, processPatch, pushOrJoinSpan, queueRender, recordLineAnnotationSource, registerCustomCSSVariableTheme, registerCustomLanguage, registerCustomTheme, releaseStringDetachBuffer, renderDiffWithHighlighter, renderFileWithHighlighter, replaceCustomExtensions, resolveConflict, resolveLanguage, resolveLanguages, resolveRegion, resolveTheme, resolveThemes, setCustomExtension, setLanguageOverride, setPreNodeProperties, trimPatchContext, wrapCoreCSS, wrapThemeCSS, wrapUnsafeCSS };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CODE_VIEW_FOOTER_ATTRIBUTE, CODE_VIEW_HEADER_ATTRIBUTE, COMMIT_METADATA_SPLIT, CORE_CSS_ATTRIBUTE, CUSTOM_HEADER_SLOT_ID, DEFAULT_CODE_VIEW_FILE_METRICS, DEFAULT_CODE_VIEW_LAYOUT, DEFAULT_COLLAPSED_CONTEXT_THRESHOLD, DEFAULT_EXPANDED_REGION, DEFAULT_RENDER_RANGE, DEFAULT_SMOOTH_SCROLL_SETTINGS, DEFAULT_THEMES, DEFAULT_TOKENIZE_MAX_LENGTH, DEFAULT_VIRTUAL_FILE_METRICS, DIFFS_DEVELOPMENT_BUILD, DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY, DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, DIFFS_TAG_NAME, EMPTY_RENDER_RANGE, FILENAME_HEADER_REGEX, FILE_CONTEXT_BLOB, GIT_DIFF_FILE_BREAK_REGEX, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID, HUNK_HEADER, INDEX_LINE_METADATA, MERGE_CONFLICT_BASE_MARKER_REGEX, MERGE_CONFLICT_END_MARKER_REGEX, MERGE_CONFLICT_SEPARATOR_MARKER_REGEX, MERGE_CONFLICT_START_MARKER_REGEX, SPLIT_WITH_NEWLINES, THEME_CSS_ATTRIBUTE, UNIFIED_DIFF_FILE_BREAK_REGEX, UNSAFE_CSS_ATTRIBUTE } from "./constants.js";
|
|
2
2
|
import { AttachedLanguages, RegisteredCustomLanguages, ResolvedLanguages, ResolvingLanguages } from "./highlighter/languages/constants.js";
|
|
3
3
|
import { areLanguagesAttached } from "./highlighter/languages/areLanguagesAttached.js";
|
|
4
4
|
import { attachResolvedLanguages } from "./highlighter/languages/attachResolvedLanguages.js";
|
|
@@ -107,4 +107,4 @@ import { parseLineType } from "./utils/parseLineType.js";
|
|
|
107
107
|
import { setLanguageOverride } from "./utils/setLanguageOverride.js";
|
|
108
108
|
import { trimPatchContext } from "./utils/trimPatchContext.js";
|
|
109
109
|
import { codeToHtml, createCssVariablesTheme as createCSSVariablesTheme } from "shiki";
|
|
110
|
-
export {
|
|
110
|
+
export { AttachedLanguages, AttachedThemes, CODE_VIEW_DIFF_OPTION_KEYS, CODE_VIEW_FILE_OPTION_KEYS, CODE_VIEW_FOOTER_ATTRIBUTE, CODE_VIEW_HEADER_ATTRIBUTE, COMMIT_METADATA_SPLIT, CORE_CSS_ATTRIBUTE, CUSTOM_HEADER_SLOT_ID, CodeToTokenTransformStream, CodeView, DEFAULT_CODE_VIEW_FILE_METRICS, DEFAULT_CODE_VIEW_LAYOUT, DEFAULT_COLLAPSED_CONTEXT_THRESHOLD, DEFAULT_EXPANDED_REGION, DEFAULT_RENDER_RANGE, DEFAULT_SMOOTH_SCROLL_SETTINGS, DEFAULT_THEMES, DEFAULT_TOKENIZE_MAX_LENGTH, DEFAULT_VIRTUAL_FILE_METRICS, DIFFS_DEVELOPMENT_BUILD, DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY, DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, DIFFS_TAG_NAME, DiffHunksRenderer, EMPTY_RENDER_RANGE, EXTENSION_TO_FILE_FORMAT, FILENAME_HEADER_REGEX, FILE_CONTEXT_BLOB, File, FileDiff, FileRenderer, FileStream, GIT_DIFF_FILE_BREAK_REGEX, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID, HUNK_HEADER, INDEX_LINE_METADATA, InteractionManager, MERGE_CONFLICT_BASE_MARKER_REGEX, MERGE_CONFLICT_END_MARKER_REGEX, MERGE_CONFLICT_SEPARATOR_MARKER_REGEX, MERGE_CONFLICT_START_MARKER_REGEX, RegisteredCustomLanguages, ResizeManager, ResolvedLanguages, ResolvingLanguages, SPLIT_WITH_NEWLINES, SVGSpriteSheet, ScrollSyncManager, ShikiStreamTokenizer, THEME_CSS_ATTRIBUTE, UNIFIED_DIFF_FILE_BREAK_REGEX, UNSAFE_CSS_ATTRIBUTE, UnresolvedFile, VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL, VirtualizedFile, VirtualizedFileDiff, Virtualizer, areDiffLineAnnotationsEqual, areDiffRenderOptionsEqual, areDiffTargetsEqual, areFileRenderOptionsEqual, areFilesEqual, areHunkDataEqual, areLanguagesAttached, areLineAnnotationsEqual, areObjectsEqual, areOptionsEqual, arePrePropertiesEqual, areRenderRangesEqual, areSelectionsEqual, areThemesAttached, areThemesEqual, areVirtualWindowSpecsEqual, areWorkerStatsEqual, attachResolvedLanguages, attachResolvedThemes, cleanLastNewline, cleanUpResolvedLanguages, cleanUpResolvedThemes, clearRenderQueue, cloneFileDiffMetadata, cloneHunks, codeToHtml, createAnnotationElement, createAnnotationWrapperNode, createCSSVariablesTheme, createDiffSpanDecoration, createEmptyRowBuffer, createFileHeaderElement, createGutterGap, createGutterItem, createGutterUtilityContentNode, createGutterUtilityElement, createGutterWrapper, createHastElement, createIconElement, createNoNewlineElement, createPreElement, createPreWrapperProperties, createRowNodes, createSeparator, createSpanFromToken, createStyleElement, createTextNodeElement, createThemeStyleElement, createTransformerWithState, createUnsafeCSSStyleNode, createWindowFromScrollPosition, dequeueRender, detachString, diffAcceptRejectHunk, disposeHighlighter, findCodeElement, formatCSSVariablePrefix, getCustomExtensionsMap, getCustomExtensionsVersion, getFiletypeFromFileName, getHighlighterIfLoaded, getHighlighterOptions, getHighlighterThemeStyles, getHunkSeparatorSlotName, getIconForType, getLineAnnotationName, getLineAnnotationSource, getLineEndingType, getLineNodes, getOrCreateCodeNode, getResolvedLanguages, getResolvedOrResolveLanguage, getResolvedOrResolveTheme, getResolvedThemes, getSharedHighlighter, getSingularPatch, getThemes, getTotalLineCountFromHunks, getUnresolvedDiffHunksRendererOptions, hasResolvedLanguages, hasResolvedThemes, hydratePartialDiff, isDefaultRenderRange, isDiffAnnotation, isDiffAnnotationCollection, isFileAnnotation, isFileAnnotationCollection, isHighlighterLoaded, isHighlighterLoading, isHighlighterNull, isWorkerContext, parseDiffFromFile, parseLineType, parsePatchFiles, patchScrollbarGutterSize, pluckInteractionOptions, prefersReducedMotion, preloadHighlighter, prerenderHTMLIfNecessary, processFile, processLine, processPatch, pushOrJoinSpan, queueRender, recordLineAnnotationSource, registerCustomCSSVariableTheme, registerCustomLanguage, registerCustomTheme, releaseStringDetachBuffer, renderDiffWithHighlighter, renderFileWithHighlighter, replaceCustomExtensions, resolveConflict, resolveLanguage, resolveLanguages, resolveRegion, resolveTheme, resolveThemes, setCustomExtension, setLanguageOverride, setPreNodeProperties, trimPatchContext, wrapCoreCSS, wrapThemeCSS, wrapUnsafeCSS };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFileDiffInstance.d.ts","names":[],"sources":["../../../src/react/utils/useFileDiffInstance.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"useFileDiffInstance.d.ts","names":[],"sources":["../../../src/react/utils/useFileDiffInstance.ts"],"mappings":";;;;;;UA+DU,yBAAyB,aAAa;EAC9C,WAAW;EACX,UAAU;EACV,UAAU;EACV,SAAS,gBAAgB,aAAa;EACtC,eAAe,2BAA2B,aAAa;EACvD;EACA,iBAAiB,mBAAmB;EACpC,eAAe;EACf;EACA,UAAU;EACV;EACA;EACA;EACA;EACA,eAAe,0BAA0B,aAAa;EACtD,iBAAiB,4BAA4B,aAAa;;UAGlD,0BAA0B;EAClC,UAAU;EACV,IAAI,MAAM;EACV,kBAAkB;EAClB,sBAAsB,YAAY,mBAAmB;;iBAGvC,oBAAoB,aAAa,SAC/C,UACA,SACA,SACA,SACA,eACA,cACA,iBACA,eACA,iBACA,SACA,wBACA,iBACA,mBACA,MACA,cAAc,eACd,gBAAgB,mBACf,yBACD,aACA,SACE,0BAA0B"}
|
|
@@ -10,7 +10,7 @@ import { useCreateEditor } from "../EditContext.js";
|
|
|
10
10
|
import { noopRender } from "../constants.js";
|
|
11
11
|
import { WorkerPoolContext } from "../WorkerPoolContext.js";
|
|
12
12
|
import { useVirtualizer } from "../Virtualizer.js";
|
|
13
|
-
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef } from "react";
|
|
13
|
+
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
14
14
|
//#region src/react/utils/useFileDiffInstance.ts
|
|
15
15
|
const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
|
|
16
16
|
function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOptions, editStateKey, lineAnnotations, selectedLines, prerenderedHTML, metrics, hasGutterRenderUtility, hasCustomHeader, disableWorkerPool, edit, onEditChange: _onEditChange, onEditComplete: _onEditComplete }) {
|
|
@@ -18,6 +18,7 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
18
18
|
const controlledSelection = selectedLines !== void 0;
|
|
19
19
|
const poolManager = useContext(WorkerPoolContext);
|
|
20
20
|
const createEditor = useCreateEditor();
|
|
21
|
+
const [asyncAttachError, setAsyncAttachError] = useState();
|
|
21
22
|
const handleOnEditChange = useStableCallback((event) => _onEditChange?.(event));
|
|
22
23
|
const onEditChange = _onEditChange != null ? handleOnEditChange : void 0;
|
|
23
24
|
const acceptedCache = useRef(null);
|
|
@@ -56,6 +57,7 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
56
57
|
});
|
|
57
58
|
const instanceRef = useRef(null);
|
|
58
59
|
const disposeEditorRef = useRef(null);
|
|
60
|
+
const pendingAttachRef = useRef(null);
|
|
59
61
|
const getEditor = useStableCallback(() => {
|
|
60
62
|
if (createEditor == null) throw new Error("FileDiff: EditContext is not attached");
|
|
61
63
|
return createEditor("file-diff", editorOptions ?? {}, editStateKey);
|
|
@@ -79,7 +81,6 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
79
81
|
onEditComplete,
|
|
80
82
|
options
|
|
81
83
|
}), !disableWorkerPool ? poolManager : void 0, true);
|
|
82
|
-
if (edit && disposeEditorRef.current == null) disposeEditorRef.current = applyEdit(instanceRef.current, getEditor);
|
|
83
84
|
instanceRef.current.hydrate({
|
|
84
85
|
fileDiff: effectiveFileDiff,
|
|
85
86
|
fileContainer,
|
|
@@ -88,6 +89,7 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
88
89
|
});
|
|
89
90
|
} else {
|
|
90
91
|
if (instanceRef.current == null) throw new Error("useFileDiffInstance: A FileDiff instance should exist when unmounting");
|
|
92
|
+
pendingAttachRef.current = null;
|
|
91
93
|
instanceRef.current.cleanUp();
|
|
92
94
|
instanceRef.current = null;
|
|
93
95
|
disposeEditorRef.current = null;
|
|
@@ -106,10 +108,13 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
106
108
|
});
|
|
107
109
|
const forceRender = newOptions !== void 0 && !areOptionsEqual(instance.options, newOptions);
|
|
108
110
|
instance.setOptions(newOptions);
|
|
109
|
-
if (!edit
|
|
110
|
-
|
|
111
|
-
disposeEditorRef.current
|
|
112
|
-
|
|
111
|
+
if (!edit) {
|
|
112
|
+
pendingAttachRef.current = null;
|
|
113
|
+
if (disposeEditorRef.current != null) {
|
|
114
|
+
const { current: disposeEditor } = disposeEditorRef;
|
|
115
|
+
disposeEditorRef.current = null;
|
|
116
|
+
disposeEditor();
|
|
117
|
+
}
|
|
113
118
|
}
|
|
114
119
|
const resolved = resolveAcceptedValues(effectiveFileDiff, lineAnnotations, acceptedCache);
|
|
115
120
|
instance.render({
|
|
@@ -118,15 +123,46 @@ function useFileDiffInstance({ fileDiff, oldFile, newFile, options, editorOption
|
|
|
118
123
|
lineAnnotations: resolved.lineAnnotations
|
|
119
124
|
});
|
|
120
125
|
if (selectedLines !== void 0) instance.setSelectedLines(selectedLines);
|
|
121
|
-
if (edit
|
|
126
|
+
if (!edit || disposeEditorRef.current != null) return;
|
|
127
|
+
if (createEditor == null) throw new Error("FileDiff: EditContext is not attached");
|
|
128
|
+
const attach = () => {
|
|
129
|
+
if (instanceRef.current !== instance || disposeEditorRef.current != null || !instance.__canAttachEditor()) return;
|
|
130
|
+
disposeEditorRef.current = applyEdit(instance, getEditor);
|
|
131
|
+
};
|
|
132
|
+
if (instance.__canAttachEditor()) {
|
|
133
|
+
pendingAttachRef.current = null;
|
|
134
|
+
attach();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const promise = instance.__prepareForEditing();
|
|
138
|
+
if (promise == null) {
|
|
139
|
+
pendingAttachRef.current = null;
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (pendingAttachRef.current?.promise === promise) return;
|
|
143
|
+
const pending = { promise };
|
|
144
|
+
pendingAttachRef.current = pending;
|
|
145
|
+
promise.then(() => {
|
|
146
|
+
if (pendingAttachRef.current !== pending) return;
|
|
147
|
+
attach();
|
|
148
|
+
pendingAttachRef.current = null;
|
|
149
|
+
}).catch((error) => {
|
|
150
|
+
if (pendingAttachRef.current === pending) {
|
|
151
|
+
pendingAttachRef.current = null;
|
|
152
|
+
setAsyncAttachError(error);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
122
155
|
});
|
|
156
|
+
const getHoveredLine = useCallback(() => {
|
|
157
|
+
return instanceRef.current?.getHoveredLine();
|
|
158
|
+
}, []);
|
|
159
|
+
const getAnnotationSlotName = useCallback((annotation) => instanceRef.current?.getAnnotationSlotName(annotation) ?? getLineAnnotationName(annotation), []);
|
|
160
|
+
if (asyncAttachError != null) throw asyncAttachError;
|
|
123
161
|
return {
|
|
124
162
|
fileDiff: effectiveFileDiff,
|
|
125
163
|
ref,
|
|
126
|
-
getHoveredLine
|
|
127
|
-
|
|
128
|
-
}, []),
|
|
129
|
-
getAnnotationSlotName: useCallback((annotation) => instanceRef.current?.getAnnotationSlotName(annotation) ?? getLineAnnotationName(annotation), [])
|
|
164
|
+
getHoveredLine,
|
|
165
|
+
getAnnotationSlotName
|
|
130
166
|
};
|
|
131
167
|
}
|
|
132
168
|
function useEffectiveFileDiff({ acceptedCache, fileDiff, newFile, oldFile, parseDiffOptions }) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFileDiffInstance.js","names":[],"sources":["../../../src/react/utils/useFileDiffInstance.ts"],"sourcesContent":["import {\n type RefObject,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from 'react';\n\nimport {\n FileDiff,\n type FileDiffEditChangeHandler,\n type FileDiffEditCompleteEvent,\n type FileDiffEditCompleteHandler,\n type FileDiffOptions,\n} from '../../components/FileDiff';\nimport { VirtualizedFileDiff } from '../../components/VirtualizedFileDiff';\nimport type { Editor, EditorChangeEvent, EditorOptions } from '../../edit';\nimport type { GetHoveredLineResult } from '../../managers/InteractionManager';\nimport type {\n DiffLineAnnotation,\n FileContents,\n FileDiffMetadata,\n SelectedLineRange,\n VirtualFileMetrics,\n} from '../../types';\nimport { areDiffTargetsEqual } from '../../utils/areDiffTargetsEqual';\nimport { areFileTargetsEqual } from '../../utils/areFileTargetsEqual';\nimport { areOptionsEqual } from '../../utils/areOptionsEqual';\nimport { getLineAnnotationName } from '../../utils/getLineAnnotationName';\nimport { parseDiffFromFile } from '../../utils/parseDiffFromFile';\nimport { noopRender } from '../constants';\nimport { useCreateEditor } from '../EditContext';\nimport { useVirtualizer } from '../Virtualizer';\nimport { WorkerPoolContext } from '../WorkerPoolContext';\nimport { useStableCallback } from './useStableCallback';\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\ninterface AcceptedFilePair {\n oldFile: FileContents | null;\n newFile: FileContents | null;\n}\n\ninterface AcceptedCompletion<LAnnotation> {\n fileDiff: {\n installed: FileDiffMetadata;\n stale: FileDiffMetadata;\n } | null;\n filePair: {\n fileDiff: FileDiffMetadata;\n installed: AcceptedFilePair;\n stale: AcceptedFilePair;\n } | null;\n annotations: {\n installed: DiffLineAnnotation<LAnnotation>[] | undefined;\n stale: DiffLineAnnotation<LAnnotation>[];\n } | null;\n}\n\ninterface UseFileDiffInstanceProps<LAnnotation, Caret> {\n fileDiff?: FileDiffMetadata;\n oldFile?: FileContents | null;\n newFile?: FileContents | null;\n options: FileDiffOptions<LAnnotation, Caret> | undefined;\n editorOptions: EditorOptions<'file-diff', LAnnotation, Caret> | undefined;\n editStateKey: string | undefined;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n selectedLines: SelectedLineRange | null | undefined;\n prerenderedHTML: string | undefined;\n metrics?: VirtualFileMetrics;\n hasGutterRenderUtility: boolean;\n hasCustomHeader: boolean;\n disableWorkerPool: boolean;\n edit: boolean;\n onEditChange?: FileDiffEditChangeHandler<LAnnotation, Caret>;\n onEditComplete?: FileDiffEditCompleteHandler<LAnnotation, Caret>;\n}\n\ninterface UseFileDiffInstanceReturn<LAnnotation> {\n fileDiff: FileDiffMetadata;\n ref(node: HTMLElement | null): void;\n getHoveredLine(): GetHoveredLineResult<'diff'> | undefined;\n getAnnotationSlotName(annotation: DiffLineAnnotation<LAnnotation>): string;\n}\n\nexport function useFileDiffInstance<LAnnotation, Caret>({\n fileDiff,\n oldFile,\n newFile,\n options,\n editorOptions,\n editStateKey,\n lineAnnotations,\n selectedLines,\n prerenderedHTML,\n metrics,\n hasGutterRenderUtility,\n hasCustomHeader,\n disableWorkerPool,\n edit,\n onEditChange: _onEditChange,\n onEditComplete: _onEditComplete,\n}: UseFileDiffInstanceProps<\n LAnnotation,\n Caret\n>): UseFileDiffInstanceReturn<LAnnotation> {\n const simpleVirtualizer = useVirtualizer();\n const controlledSelection = selectedLines !== undefined;\n const poolManager = useContext(WorkerPoolContext);\n const createEditor = useCreateEditor<LAnnotation, Caret>();\n const handleOnEditChange = useStableCallback(\n (event: EditorChangeEvent<'file-diff', LAnnotation, Caret>) =>\n _onEditChange?.(event)\n );\n const onEditChange = _onEditChange != null ? handleOnEditChange : undefined;\n // An accepted completion installs its diff on the instance immediately,\n // but the fileDiff/lineAnnotations props stay pre-edit until the owner's\n // state update lands. This holds the accepted values so the renders in\n // between do not repaint pre-edit state.\n const acceptedCache = useRef<AcceptedCompletion<LAnnotation> | null>(null);\n const handleOnEditComplete = useStableCallback(\n (event: FileDiffEditCompleteEvent<LAnnotation, Caret>) => {\n const decision = _onEditComplete?.(event) ?? 'reject';\n if (decision === 'accept') {\n acceptedCache.current = {\n fileDiff: {\n installed: event.fileDiff,\n stale: event.originalFileDiff,\n },\n filePair:\n fileDiff == null\n ? {\n fileDiff: event.fileDiff,\n installed: { oldFile: event.oldFile, newFile: event.newFile },\n stale: { oldFile: oldFile ?? null, newFile: newFile ?? null },\n }\n : null,\n annotations: {\n installed: event.lineAnnotations,\n stale: event.originalLineAnnotations,\n },\n };\n }\n return decision;\n }\n );\n const onEditComplete =\n _onEditComplete != null ? handleOnEditComplete : undefined;\n // File-pair inputs parse here. While the file props still match the pair\n // from acceptance time (stale) or the completion event's files (installed),\n // the parse is the accepted diff itself; any other pair clears the record\n // and parses fresh.\n const effectiveFileDiff = useEffectiveFileDiff({\n acceptedCache,\n fileDiff,\n newFile,\n oldFile,\n parseDiffOptions: options?.parseDiffOptions,\n });\n const instanceRef = useRef<\n | FileDiff<LAnnotation, Caret>\n | VirtualizedFileDiff<LAnnotation, Caret>\n | null\n >(null);\n const disposeEditorRef = useRef<() => void>(null);\n const getEditor = useStableCallback(() => {\n if (createEditor == null) {\n throw new Error('FileDiff: EditContext is not attached');\n }\n return createEditor('file-diff', editorOptions ?? {}, editStateKey);\n });\n const ref = useStableCallback((fileContainer: HTMLElement | null) => {\n if (fileContainer != null) {\n if (instanceRef.current != null) {\n throw new Error(\n 'useFileDiffInstance: An instance should not already exist when a node is created'\n );\n }\n if (simpleVirtualizer != null) {\n instanceRef.current = new VirtualizedFileDiff(\n mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n }),\n simpleVirtualizer,\n metrics,\n !disableWorkerPool ? poolManager : undefined,\n true\n );\n } else {\n instanceRef.current = new FileDiff(\n mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n }),\n !disableWorkerPool ? poolManager : undefined,\n true\n );\n }\n if (edit && disposeEditorRef.current == null) {\n disposeEditorRef.current = applyEdit(instanceRef.current, getEditor);\n }\n void instanceRef.current.hydrate({\n fileDiff: effectiveFileDiff,\n fileContainer,\n lineAnnotations,\n prerenderedHTML,\n });\n } else {\n if (instanceRef.current == null) {\n throw new Error(\n 'useFileDiffInstance: A FileDiff instance should exist when unmounting'\n );\n }\n instanceRef.current.cleanUp();\n instanceRef.current = null;\n disposeEditorRef.current = null;\n }\n });\n\n useIsomorphicLayoutEffect(() => {\n const { current: instance } = instanceRef;\n if (instance == null) return;\n const newOptions = mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n });\n // setOptions(undefined) is a no-op, so an undefined merge result never\n // requires a forced render — comparing it against the instance's\n // constructor-default options would force a full render on every commit.\n const forceRender =\n newOptions !== undefined &&\n !areOptionsEqual(instance.options, newOptions);\n instance.setOptions(newOptions);\n // Detach editor before rendering if required\n if (!edit && disposeEditorRef.current != null) {\n const { current: disposeEditor } = disposeEditorRef;\n disposeEditorRef.current = null;\n disposeEditor();\n }\n const resolved = resolveAcceptedValues(\n effectiveFileDiff,\n lineAnnotations,\n acceptedCache\n );\n void instance.render({\n forceRender,\n fileDiff: resolved.fileDiff,\n lineAnnotations: resolved.lineAnnotations,\n });\n if (selectedLines !== undefined) {\n instance.setSelectedLines(selectedLines);\n }\n // Attach editor after rendering if required\n if (edit && disposeEditorRef.current == null) {\n disposeEditorRef.current = applyEdit(instance, getEditor);\n }\n });\n\n const getHoveredLine = useCallback(():\n | GetHoveredLineResult<'diff'>\n | undefined => {\n return instanceRef.current?.getHoveredLine();\n }, []);\n const getAnnotationSlotName = useCallback(\n (annotation: DiffLineAnnotation<LAnnotation>): string =>\n instanceRef.current?.getAnnotationSlotName(annotation) ??\n getLineAnnotationName(annotation),\n []\n );\n\n return {\n fileDiff: effectiveFileDiff,\n ref,\n getHoveredLine,\n getAnnotationSlotName,\n };\n}\n\ninterface UseEffectiveFileDiffProps<LAnnotation, Caret> {\n acceptedCache: RefObject<AcceptedCompletion<LAnnotation> | null>;\n fileDiff: FileDiffMetadata | undefined;\n newFile: FileContents | null | undefined;\n oldFile: FileContents | null | undefined;\n parseDiffOptions: FileDiffOptions<LAnnotation, Caret>['parseDiffOptions'];\n}\n\n// Resolves the diff the instance renders: the `fileDiff` prop when given;\n// otherwise the accepted edit's cached diff while the file props still name the\n// pair it was accepted against; otherwise a fresh parse of the file props. A\n// cached pair that no longer matches is dropped on the way. Kept in its own hook\n// because the render-time ref read and write are deliberate; the boundary lets\n// the calling hook stay compilable.\nfunction useEffectiveFileDiff<LAnnotation, Caret>({\n acceptedCache,\n fileDiff,\n newFile,\n oldFile,\n parseDiffOptions,\n}: UseEffectiveFileDiffProps<LAnnotation, Caret>): FileDiffMetadata {\n /* oxlint-disable react/immutability react/refs -- accepted edit output must\n * replace stale file-pair props during render */\n const effectiveFileDiff = useMemo(() => {\n if (fileDiff != null) {\n return fileDiff;\n }\n const { current: accepted } = acceptedCache;\n const filePair = accepted?.filePair;\n if (accepted != null && filePair != null) {\n if (\n isSameFilePair(oldFile, newFile, filePair.stale) ||\n isSameFilePair(oldFile, newFile, filePair.installed)\n ) {\n return filePair.fileDiff;\n }\n accepted.filePair = null;\n }\n return parseDiffFromFile(\n oldFile ?? null,\n newFile ?? null,\n parseDiffOptions\n );\n }, [acceptedCache, fileDiff, oldFile, newFile, parseDiffOptions]);\n /* oxlint-enable react/immutability react/refs */\n\n return effectiveFileDiff;\n}\n\n// Whether the file props name the same files as a recorded pair.\nfunction isSameFilePair(\n oldFile: FileContents | null | undefined,\n newFile: FileContents | null | undefined,\n filePair: AcceptedFilePair\n): boolean {\n return (\n areFileTargetsEqual(oldFile ?? undefined, filePair.oldFile ?? undefined) &&\n areFileTargetsEqual(newFile ?? undefined, filePair.newFile ?? undefined)\n );\n}\n\n// Render the installed values in place of props that still match their stale\n// counterparts. Any other prop value clears its slot — filePair settles in\n// the parse memo instead — and the ref clears once all three have.\nfunction resolveAcceptedValues<LAnnotation>(\n fileDiff: FileDiffMetadata,\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined,\n acceptedCache: RefObject<AcceptedCompletion<LAnnotation> | null>\n): {\n fileDiff: FileDiffMetadata;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n} {\n const { current: accepted } = acceptedCache;\n if (accepted == null) {\n return { fileDiff, lineAnnotations };\n }\n const { fileDiff: acceptedDiff, annotations: acceptedAnnotations } = accepted;\n let resolvedFileDiff = fileDiff;\n if (acceptedDiff != null) {\n if (areDiffTargetsEqual(fileDiff, acceptedDiff.stale)) {\n resolvedFileDiff = acceptedDiff.installed;\n } else {\n accepted.fileDiff = null;\n }\n }\n let resolvedAnnotations = lineAnnotations;\n if (acceptedAnnotations != null) {\n if (lineAnnotations === acceptedAnnotations.stale) {\n resolvedAnnotations = acceptedAnnotations.installed;\n } else {\n accepted.annotations = null;\n }\n }\n if (\n accepted.fileDiff == null &&\n accepted.annotations == null &&\n accepted.filePair == null\n ) {\n acceptedCache.current = null;\n }\n return { fileDiff: resolvedFileDiff, lineAnnotations: resolvedAnnotations };\n}\n\ninterface MergeFileDiffOptionsProps<LAnnotation, Caret> {\n controlledSelection: boolean;\n hasCustomHeader: boolean;\n hasGutterRenderUtility: boolean;\n onEditChange?: FileDiffEditChangeHandler<LAnnotation, Caret>;\n onEditComplete?: FileDiffEditCompleteHandler<LAnnotation, Caret>;\n options: FileDiffOptions<LAnnotation, Caret> | undefined;\n}\n\nfunction mergeFileDiffOptions<LAnnotation, Caret>({\n options,\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n}: MergeFileDiffOptionsProps<LAnnotation, Caret>):\n | FileDiffOptions<LAnnotation, Caret>\n | undefined {\n const needsReactOverrides =\n controlledSelection ||\n hasGutterRenderUtility ||\n hasCustomHeader ||\n onEditChange != null ||\n onEditComplete != null;\n\n if (!needsReactOverrides) {\n return options;\n }\n\n return {\n ...options,\n controlledSelection,\n renderCustomHeader: hasCustomHeader\n ? noopRender\n : options?.renderCustomHeader,\n renderGutterUtility: hasGutterRenderUtility\n ? noopRender\n : options?.renderGutterUtility,\n onEditChange,\n onEditComplete,\n };\n}\n\nfunction applyEdit<LAnnotation, Caret>(\n instance: FileDiff<LAnnotation, Caret>,\n getEditor: () => Editor<'file-diff', LAnnotation, Caret>\n): () => void {\n const editor = getEditor();\n try {\n return editor.edit(instance);\n } catch (error) {\n editor.cleanUp();\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,MAAM,4BACJ,OAAO,WAAW,cAAc,YAAY;AAiD9C,SAAgB,oBAAwC,EACtD,UACA,SACA,SACA,SACA,eACA,cACA,iBACA,eACA,iBACA,SACA,wBACA,iBACA,mBACA,MACA,cAAc,eACd,gBAAgB,mBAIyB;CACzC,MAAM,oBAAoB,eAAe;CACzC,MAAM,sBAAsB,kBAAkB,KAAA;CAC9C,MAAM,cAAc,WAAW,iBAAiB;CAChD,MAAM,eAAe,gBAAoC;CACzD,MAAM,qBAAqB,mBACxB,UACC,gBAAgB,KAAK,CACzB;CACA,MAAM,eAAe,iBA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,UAAU;CACzB,IAAI;EACF,OAAO,OAAO,KAAK,QAAQ;CAC7B,SAAS,OAAO;EACd,OAAO,QAAQ;EACf,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"useFileDiffInstance.js","names":[],"sources":["../../../src/react/utils/useFileDiffInstance.ts"],"sourcesContent":["import {\n type RefObject,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport {\n FileDiff,\n type FileDiffEditChangeHandler,\n type FileDiffEditCompleteEvent,\n type FileDiffEditCompleteHandler,\n type FileDiffOptions,\n} from '../../components/FileDiff';\nimport { VirtualizedFileDiff } from '../../components/VirtualizedFileDiff';\nimport type { Editor, EditorChangeEvent, EditorOptions } from '../../edit';\nimport type { GetHoveredLineResult } from '../../managers/InteractionManager';\nimport type {\n DiffLineAnnotation,\n FileContents,\n FileDiffMetadata,\n SelectedLineRange,\n VirtualFileMetrics,\n} from '../../types';\nimport { areDiffTargetsEqual } from '../../utils/areDiffTargetsEqual';\nimport { areFileTargetsEqual } from '../../utils/areFileTargetsEqual';\nimport { areOptionsEqual } from '../../utils/areOptionsEqual';\nimport { getLineAnnotationName } from '../../utils/getLineAnnotationName';\nimport { parseDiffFromFile } from '../../utils/parseDiffFromFile';\nimport { noopRender } from '../constants';\nimport { useCreateEditor } from '../EditContext';\nimport { useVirtualizer } from '../Virtualizer';\nimport { WorkerPoolContext } from '../WorkerPoolContext';\nimport { useStableCallback } from './useStableCallback';\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\ninterface AcceptedFilePair {\n oldFile: FileContents | null;\n newFile: FileContents | null;\n}\n\ninterface AcceptedCompletion<LAnnotation> {\n fileDiff: {\n installed: FileDiffMetadata;\n stale: FileDiffMetadata;\n } | null;\n filePair: {\n fileDiff: FileDiffMetadata;\n installed: AcceptedFilePair;\n stale: AcceptedFilePair;\n } | null;\n annotations: {\n installed: DiffLineAnnotation<LAnnotation>[] | undefined;\n stale: DiffLineAnnotation<LAnnotation>[];\n } | null;\n}\n\ninterface UseFileDiffInstanceProps<LAnnotation, Caret> {\n fileDiff?: FileDiffMetadata;\n oldFile?: FileContents | null;\n newFile?: FileContents | null;\n options: FileDiffOptions<LAnnotation, Caret> | undefined;\n editorOptions: EditorOptions<'file-diff', LAnnotation, Caret> | undefined;\n editStateKey: string | undefined;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n selectedLines: SelectedLineRange | null | undefined;\n prerenderedHTML: string | undefined;\n metrics?: VirtualFileMetrics;\n hasGutterRenderUtility: boolean;\n hasCustomHeader: boolean;\n disableWorkerPool: boolean;\n edit: boolean;\n onEditChange?: FileDiffEditChangeHandler<LAnnotation, Caret>;\n onEditComplete?: FileDiffEditCompleteHandler<LAnnotation, Caret>;\n}\n\ninterface UseFileDiffInstanceReturn<LAnnotation> {\n fileDiff: FileDiffMetadata;\n ref(node: HTMLElement | null): void;\n getHoveredLine(): GetHoveredLineResult<'diff'> | undefined;\n getAnnotationSlotName(annotation: DiffLineAnnotation<LAnnotation>): string;\n}\n\nexport function useFileDiffInstance<LAnnotation, Caret>({\n fileDiff,\n oldFile,\n newFile,\n options,\n editorOptions,\n editStateKey,\n lineAnnotations,\n selectedLines,\n prerenderedHTML,\n metrics,\n hasGutterRenderUtility,\n hasCustomHeader,\n disableWorkerPool,\n edit,\n onEditChange: _onEditChange,\n onEditComplete: _onEditComplete,\n}: UseFileDiffInstanceProps<\n LAnnotation,\n Caret\n>): UseFileDiffInstanceReturn<LAnnotation> {\n const simpleVirtualizer = useVirtualizer();\n const controlledSelection = selectedLines !== undefined;\n const poolManager = useContext(WorkerPoolContext);\n const createEditor = useCreateEditor<LAnnotation, Caret>();\n const [asyncAttachError, setAsyncAttachError] = useState<unknown>();\n const handleOnEditChange = useStableCallback(\n (event: EditorChangeEvent<'file-diff', LAnnotation, Caret>) =>\n _onEditChange?.(event)\n );\n const onEditChange = _onEditChange != null ? handleOnEditChange : undefined;\n // An accepted completion installs its diff on the instance immediately,\n // but the fileDiff/lineAnnotations props stay pre-edit until the owner's\n // state update lands. This holds the accepted values so the renders in\n // between do not repaint pre-edit state.\n const acceptedCache = useRef<AcceptedCompletion<LAnnotation> | null>(null);\n const handleOnEditComplete = useStableCallback(\n (event: FileDiffEditCompleteEvent<LAnnotation, Caret>) => {\n const decision = _onEditComplete?.(event) ?? 'reject';\n if (decision === 'accept') {\n acceptedCache.current = {\n fileDiff: {\n installed: event.fileDiff,\n stale: event.originalFileDiff,\n },\n filePair:\n fileDiff == null\n ? {\n fileDiff: event.fileDiff,\n installed: { oldFile: event.oldFile, newFile: event.newFile },\n stale: { oldFile: oldFile ?? null, newFile: newFile ?? null },\n }\n : null,\n annotations: {\n installed: event.lineAnnotations,\n stale: event.originalLineAnnotations,\n },\n };\n }\n return decision;\n }\n );\n const onEditComplete =\n _onEditComplete != null ? handleOnEditComplete : undefined;\n // File-pair inputs parse here. While the file props still match the pair\n // from acceptance time (stale) or the completion event's files (installed),\n // the parse is the accepted diff itself; any other pair clears the record\n // and parses fresh.\n const effectiveFileDiff = useEffectiveFileDiff({\n acceptedCache,\n fileDiff,\n newFile,\n oldFile,\n parseDiffOptions: options?.parseDiffOptions,\n });\n const instanceRef = useRef<\n | FileDiff<LAnnotation, Caret>\n | VirtualizedFileDiff<LAnnotation, Caret>\n | null\n >(null);\n const disposeEditorRef = useRef<() => void>(null);\n const pendingAttachRef = useRef<{ promise: Promise<void> } | null>(null);\n const getEditor = useStableCallback(() => {\n if (createEditor == null) {\n throw new Error('FileDiff: EditContext is not attached');\n }\n return createEditor('file-diff', editorOptions ?? {}, editStateKey);\n });\n const ref = useStableCallback((fileContainer: HTMLElement | null) => {\n if (fileContainer != null) {\n if (instanceRef.current != null) {\n throw new Error(\n 'useFileDiffInstance: An instance should not already exist when a node is created'\n );\n }\n if (simpleVirtualizer != null) {\n instanceRef.current = new VirtualizedFileDiff(\n mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n }),\n simpleVirtualizer,\n metrics,\n !disableWorkerPool ? poolManager : undefined,\n true\n );\n } else {\n instanceRef.current = new FileDiff(\n mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n }),\n !disableWorkerPool ? poolManager : undefined,\n true\n );\n }\n void instanceRef.current.hydrate({\n fileDiff: effectiveFileDiff,\n fileContainer,\n lineAnnotations,\n prerenderedHTML,\n });\n } else {\n if (instanceRef.current == null) {\n throw new Error(\n 'useFileDiffInstance: A FileDiff instance should exist when unmounting'\n );\n }\n pendingAttachRef.current = null;\n instanceRef.current.cleanUp();\n instanceRef.current = null;\n disposeEditorRef.current = null;\n }\n });\n\n useIsomorphicLayoutEffect(() => {\n const { current: instance } = instanceRef;\n if (instance == null) return;\n const newOptions = mergeFileDiffOptions({\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n options,\n });\n // setOptions(undefined) is a no-op, so an undefined merge result never\n // requires a forced render — comparing it against the instance's\n // constructor-default options would force a full render on every commit.\n const forceRender =\n newOptions !== undefined &&\n !areOptionsEqual(instance.options, newOptions);\n instance.setOptions(newOptions);\n // Detach editor before rendering if required\n if (!edit) {\n pendingAttachRef.current = null;\n if (disposeEditorRef.current != null) {\n const { current: disposeEditor } = disposeEditorRef;\n disposeEditorRef.current = null;\n disposeEditor();\n }\n }\n const resolved = resolveAcceptedValues(\n effectiveFileDiff,\n lineAnnotations,\n acceptedCache\n );\n void instance.render({\n forceRender,\n fileDiff: resolved.fileDiff,\n lineAnnotations: resolved.lineAnnotations,\n });\n if (selectedLines !== undefined) {\n instance.setSelectedLines(selectedLines);\n }\n if (!edit || disposeEditorRef.current != null) {\n return;\n }\n if (createEditor == null) {\n throw new Error('FileDiff: EditContext is not attached');\n }\n\n const attach = (): void => {\n if (\n instanceRef.current !== instance ||\n disposeEditorRef.current != null ||\n !instance.__canAttachEditor()\n ) {\n return;\n }\n disposeEditorRef.current = applyEdit(instance, getEditor);\n };\n // If we're all ready to attach the editor, lets go ahead\n // and do that synchronously\n if (instance.__canAttachEditor()) {\n pendingAttachRef.current = null;\n attach();\n return;\n }\n const promise = instance.__prepareForEditing();\n // If we can't hydrate the files... this will come back undefined,\n // which means there's nothing we can do\n if (promise == null) {\n pendingAttachRef.current = null;\n return;\n }\n // If we are already waiting on a hydration to finish, then there's nothing\n // we need to do\n if (pendingAttachRef.current?.promise === promise) {\n return;\n }\n const pending = { promise };\n pendingAttachRef.current = pending;\n void promise\n .then(() => {\n if (pendingAttachRef.current !== pending) {\n return;\n }\n attach();\n pendingAttachRef.current = null;\n })\n .catch((error: unknown) => {\n if (pendingAttachRef.current === pending) {\n pendingAttachRef.current = null;\n setAsyncAttachError(error);\n }\n });\n });\n\n const getHoveredLine = useCallback(():\n | GetHoveredLineResult<'diff'>\n | undefined => {\n return instanceRef.current?.getHoveredLine();\n }, []);\n const getAnnotationSlotName = useCallback(\n (annotation: DiffLineAnnotation<LAnnotation>): string =>\n instanceRef.current?.getAnnotationSlotName(annotation) ??\n getLineAnnotationName(annotation),\n []\n );\n\n if (asyncAttachError != null) {\n throw asyncAttachError;\n }\n\n return {\n fileDiff: effectiveFileDiff,\n ref,\n getHoveredLine,\n getAnnotationSlotName,\n };\n}\n\ninterface UseEffectiveFileDiffProps<LAnnotation, Caret> {\n acceptedCache: RefObject<AcceptedCompletion<LAnnotation> | null>;\n fileDiff: FileDiffMetadata | undefined;\n newFile: FileContents | null | undefined;\n oldFile: FileContents | null | undefined;\n parseDiffOptions: FileDiffOptions<LAnnotation, Caret>['parseDiffOptions'];\n}\n\n// Resolves the diff the instance renders: the `fileDiff` prop when given;\n// otherwise the accepted edit's cached diff while the file props still name the\n// pair it was accepted against; otherwise a fresh parse of the file props. A\n// cached pair that no longer matches is dropped on the way. Kept in its own hook\n// because the render-time ref read and write are deliberate; the boundary lets\n// the calling hook stay compilable.\nfunction useEffectiveFileDiff<LAnnotation, Caret>({\n acceptedCache,\n fileDiff,\n newFile,\n oldFile,\n parseDiffOptions,\n}: UseEffectiveFileDiffProps<LAnnotation, Caret>): FileDiffMetadata {\n /* oxlint-disable react/immutability react/refs -- accepted edit output must\n * replace stale file-pair props during render */\n const effectiveFileDiff = useMemo(() => {\n if (fileDiff != null) {\n return fileDiff;\n }\n const { current: accepted } = acceptedCache;\n const filePair = accepted?.filePair;\n if (accepted != null && filePair != null) {\n if (\n isSameFilePair(oldFile, newFile, filePair.stale) ||\n isSameFilePair(oldFile, newFile, filePair.installed)\n ) {\n return filePair.fileDiff;\n }\n accepted.filePair = null;\n }\n return parseDiffFromFile(\n oldFile ?? null,\n newFile ?? null,\n parseDiffOptions\n );\n }, [acceptedCache, fileDiff, oldFile, newFile, parseDiffOptions]);\n /* oxlint-enable react/immutability react/refs */\n\n return effectiveFileDiff;\n}\n\n// Whether the file props name the same files as a recorded pair.\nfunction isSameFilePair(\n oldFile: FileContents | null | undefined,\n newFile: FileContents | null | undefined,\n filePair: AcceptedFilePair\n): boolean {\n return (\n areFileTargetsEqual(oldFile ?? undefined, filePair.oldFile ?? undefined) &&\n areFileTargetsEqual(newFile ?? undefined, filePair.newFile ?? undefined)\n );\n}\n\n// Render the installed values in place of props that still match their stale\n// counterparts. Any other prop value clears its slot — filePair settles in\n// the parse memo instead — and the ref clears once all three have.\nfunction resolveAcceptedValues<LAnnotation>(\n fileDiff: FileDiffMetadata,\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined,\n acceptedCache: RefObject<AcceptedCompletion<LAnnotation> | null>\n): {\n fileDiff: FileDiffMetadata;\n lineAnnotations: DiffLineAnnotation<LAnnotation>[] | undefined;\n} {\n const { current: accepted } = acceptedCache;\n if (accepted == null) {\n return { fileDiff, lineAnnotations };\n }\n const { fileDiff: acceptedDiff, annotations: acceptedAnnotations } = accepted;\n let resolvedFileDiff = fileDiff;\n if (acceptedDiff != null) {\n if (areDiffTargetsEqual(fileDiff, acceptedDiff.stale)) {\n resolvedFileDiff = acceptedDiff.installed;\n } else {\n accepted.fileDiff = null;\n }\n }\n let resolvedAnnotations = lineAnnotations;\n if (acceptedAnnotations != null) {\n if (lineAnnotations === acceptedAnnotations.stale) {\n resolvedAnnotations = acceptedAnnotations.installed;\n } else {\n accepted.annotations = null;\n }\n }\n if (\n accepted.fileDiff == null &&\n accepted.annotations == null &&\n accepted.filePair == null\n ) {\n acceptedCache.current = null;\n }\n return { fileDiff: resolvedFileDiff, lineAnnotations: resolvedAnnotations };\n}\n\ninterface MergeFileDiffOptionsProps<LAnnotation, Caret> {\n controlledSelection: boolean;\n hasCustomHeader: boolean;\n hasGutterRenderUtility: boolean;\n onEditChange?: FileDiffEditChangeHandler<LAnnotation, Caret>;\n onEditComplete?: FileDiffEditCompleteHandler<LAnnotation, Caret>;\n options: FileDiffOptions<LAnnotation, Caret> | undefined;\n}\n\nfunction mergeFileDiffOptions<LAnnotation, Caret>({\n options,\n controlledSelection,\n hasCustomHeader,\n hasGutterRenderUtility,\n onEditChange,\n onEditComplete,\n}: MergeFileDiffOptionsProps<LAnnotation, Caret>):\n | FileDiffOptions<LAnnotation, Caret>\n | undefined {\n const needsReactOverrides =\n controlledSelection ||\n hasGutterRenderUtility ||\n hasCustomHeader ||\n onEditChange != null ||\n onEditComplete != null;\n\n if (!needsReactOverrides) {\n return options;\n }\n\n return {\n ...options,\n controlledSelection,\n renderCustomHeader: hasCustomHeader\n ? noopRender\n : options?.renderCustomHeader,\n renderGutterUtility: hasGutterRenderUtility\n ? noopRender\n : options?.renderGutterUtility,\n onEditChange,\n onEditComplete,\n };\n}\n\nfunction applyEdit<LAnnotation, Caret>(\n instance: FileDiff<LAnnotation, Caret>,\n getEditor: () => Editor<'file-diff', LAnnotation, Caret>\n): () => void {\n const editor = getEditor();\n try {\n return editor.edit(instance);\n } catch (error) {\n editor.cleanUp();\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;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1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DiffHunksRenderer.d.ts","names":[],"sources":["../../src/renderers/DiffHunksRenderer.ts"],"mappings":";;;;;;;UAoJiB,iCAAiC;EAChD,mBAAmB;;UAGJ,6CAA6C,KAC5D;EAGA,kBAAkB;;UAGH;EACf;EACA,UAAU;EACV;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;;UAUL;EACf;EACA;EACA;EACA;EACA;EACA,eAAe;EACf,eAAe;;UAGA;EACf,SAAS;EACT,QAAQ;;UAGO;EACf,UAAU;EACV,UAAU;;UAGK;EACf,SAAS;EACT,QAAQ;;UAGO;EACf,SAAS;EACT,QAAQ;;UAGO;EACf,UAAU;EACV,kBAAkB;EAClB,mBAAmB;EACnB,oBAAoB;EACpB,qBAAqB;EACrB,oBAAoB;EACpB,qBAAqB;EACrB,UAAU;EACV;EACA,SAAS;EACT,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;;cAKW,kBAAkB;EAgCpB,SAAS;UACR;UAGA;UACA;WApCD;UAED;UAIA;UAEA;UAEA;UACA;UAEA;UACA;UAGA;UAGA;UAQA;EAER,YACS,UAAS,0BACR,sBACN,YAAY,mBAAmB,yBAEzB,8CACA,gBAAgB;EASnB;
|
|
1
|
+
{"version":3,"file":"DiffHunksRenderer.d.ts","names":[],"sources":["../../src/renderers/DiffHunksRenderer.ts"],"mappings":";;;;;;;UAoJiB,iCAAiC;EAChD,mBAAmB;;UAGJ,6CAA6C,KAC5D;EAGA,kBAAkB;;UAGH;EACf;EACA,UAAU;EACV;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;;UAUL;EACf;EACA;EACA;EACA;EACA;EACA,eAAe;EACf,eAAe;;UAGA;EACf,SAAS;EACT,QAAQ;;UAGO;EACf,UAAU;EACV,UAAU;;UAGK;EACf,SAAS;EACT,QAAQ;;UAGO;EACf,SAA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