@in-the-loop-labs/pair-review 4.1.1 → 5.0.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/README.md +81 -13
- package/package.json +6 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/skills/loop/SKILL.md +17 -8
- package/public/css/ai-summary-modal.css +1 -1
- package/public/css/analysis-config.css +33 -49
- package/public/css/council-card.css +118 -0
- package/public/css/council-dropdown.css +164 -0
- package/public/css/pr.css +666 -394
- package/public/css/repo-settings.css +15 -305
- package/public/css/settings.css +1141 -0
- package/public/css/snippet-manager.css +233 -0
- package/public/index.html +40 -59
- package/public/js/components/AIPanel.js +82 -16
- package/public/js/components/ChatPanel.js +401 -5
- package/public/js/components/CouncilCard.js +202 -0
- package/public/js/components/CouncilDropdown.js +292 -0
- package/public/js/components/DiffOptionsDropdown.js +177 -4
- package/public/js/components/SnippetManager.js +463 -0
- package/public/js/index.js +7 -30
- package/public/js/local.js +20 -2
- package/public/js/modules/comment-manager.js +8 -1
- package/public/js/modules/comment-minimizer.js +249 -190
- package/public/js/modules/external-comment-manager.js +414 -48
- package/public/js/modules/file-comment-manager.js +28 -21
- package/public/js/modules/hunk-summary-renderer.js +155 -29
- package/public/js/modules/pierre-bridge.js +2513 -0
- package/public/js/modules/pierre-context.js +345 -0
- package/public/js/modules/suggestion-manager.js +176 -20
- package/public/js/modules/tour-renderer.js +400 -184
- package/public/js/pr.js +1434 -150
- package/public/js/repo-settings.js +60 -284
- package/public/js/settings.js +1086 -0
- package/public/js/theme-bootstrap.js +40 -0
- package/public/js/theme.js +247 -0
- package/public/js/utils/provider-model.js +3 -3
- package/public/js/utils/suggestion-ui.js +157 -8
- package/public/local.html +20 -31
- package/public/pr.html +14 -23
- package/public/repo-settings.html +24 -14
- package/public/settings.html +138 -0
- package/public/setup.html +8 -13
- package/src/chat/api-reference.js +9 -5
- package/src/chat/prompt-builder.js +8 -1
- package/src/config.js +15 -6
- package/src/database.js +307 -14
- package/src/external/github-adapter.js +39 -5
- package/src/headless/delegate.js +682 -0
- package/src/local-review.js +10 -10
- package/src/local-scope.js +9 -0
- package/src/main.js +276 -157
- package/src/mcp-stdio.js +24 -1
- package/src/review-config.js +93 -25
- package/src/routes/chat.js +2 -2
- package/src/routes/config.js +12 -10
- package/src/routes/external-comments.js +5 -1
- package/src/routes/local.js +2 -4
- package/src/routes/mcp.js +18 -13
- package/src/routes/reviews.js +223 -4
- package/src/routes/settings.js +252 -0
- package/src/routes/setup.js +80 -1
- package/src/routes/shared.js +31 -29
- package/src/routes/snippets.js +154 -0
- package/src/routes/stack-analysis.js +17 -14
- package/src/server.js +86 -18
- package/src/settings/global-settings-service.js +472 -0
- package/src/settings/registry.js +624 -0
- package/src/utils/db-identity.js +44 -0
|
@@ -0,0 +1,2513 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* PierreBridge - Adapter between @pierre/diffs and pair-review
|
|
4
|
+
*
|
|
5
|
+
* Manages FileDiff instances per file, annotation rendering (comments, suggestions, forms),
|
|
6
|
+
* gap expansion, diffPosition tracking, and theme management.
|
|
7
|
+
*
|
|
8
|
+
* Depends on: window.PierreDiffs (from vendor bundle)
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
class PierreBridge {
|
|
12
|
+
/**
|
|
13
|
+
* @param {Object} options
|
|
14
|
+
* @param {string} options.theme - 'light' or 'dark'
|
|
15
|
+
* @param {Function} options.onCommentClick - (fileName, lineNumber, side) => void
|
|
16
|
+
* @param {Function} options.onChatClick - (fileName, lineNumber, side, range?) => void
|
|
17
|
+
* @param {Function} options.onLineSelect - (fileName, range) => void
|
|
18
|
+
* @param {Function} options.onHunkExpand - (fileName, hunkIndex, direction, lineCount) => void
|
|
19
|
+
*/
|
|
20
|
+
constructor(options = {}) {
|
|
21
|
+
if (!window.PierreDiffs) {
|
|
22
|
+
console.warn('[PierreBridge] window.PierreDiffs not loaded — @pierre/diffs bundle missing. Falling back to legacy rendering.');
|
|
23
|
+
this._disabled = true;
|
|
24
|
+
}
|
|
25
|
+
this.options = options;
|
|
26
|
+
this.theme = options.theme || PierreBridge.detectTheme();
|
|
27
|
+
|
|
28
|
+
// Diff layout: 'unified' (single column) or 'split' (side-by-side).
|
|
29
|
+
// Stored as instance state so every FileDiff instance (including lazily
|
|
30
|
+
// created / rebuilt ones) inherits the current style. Toggled at runtime
|
|
31
|
+
// via setDiffStyle(). Invalid values fall back to 'unified'.
|
|
32
|
+
this.diffStyle = PierreBridge.isValidDiffStyle(options.diffStyle)
|
|
33
|
+
? options.diffStyle
|
|
34
|
+
: 'unified';
|
|
35
|
+
|
|
36
|
+
// Per-file state: { instance: FileDiff, metadata: FileDiffMetadata, container: HTMLElement,
|
|
37
|
+
// annotations: DiffLineAnnotation[], diffPositions: Map, formElements: Map }
|
|
38
|
+
this.files = new Map();
|
|
39
|
+
|
|
40
|
+
// CSS to inject into Shadow DOM for annotations, comments, suggestions
|
|
41
|
+
this._unsafeCSS = null;
|
|
42
|
+
|
|
43
|
+
// Monotonic counter for unique annotation IDs
|
|
44
|
+
this._annotationCounter = 0;
|
|
45
|
+
|
|
46
|
+
// Cache for gutter button containers — keyed by fileName.
|
|
47
|
+
// Stored here instead of on fileState because renderGutterUtility fires
|
|
48
|
+
// during instance.render(), before fileState is set on this.files.
|
|
49
|
+
this._gutterContainers = new Map();
|
|
50
|
+
this._gutterRowGetters = new Map();
|
|
51
|
+
this._hoveredRows = new Map();
|
|
52
|
+
|
|
53
|
+
// Shared options for all FileDiff instances
|
|
54
|
+
this._sharedOptions = null;
|
|
55
|
+
|
|
56
|
+
// Shared @pierre/diffs worker pool. Without this, FileDiff falls back to
|
|
57
|
+
// Shiki highlighting on the main thread, which can freeze large reviews.
|
|
58
|
+
this.workerManager = this._createWorkerManager();
|
|
59
|
+
this._workerReady = !this.workerManager;
|
|
60
|
+
this._workersFailed = false;
|
|
61
|
+
this._workerInitTimer = null;
|
|
62
|
+
this._workerStatsUnsubscribe = null;
|
|
63
|
+
this._lastPointerPosition = null;
|
|
64
|
+
this._trackPointerPosition = (event) => {
|
|
65
|
+
if (event.isPrimary === false) return;
|
|
66
|
+
this._lastPointerPosition = {
|
|
67
|
+
clientX: event.clientX,
|
|
68
|
+
clientY: event.clientY,
|
|
69
|
+
screenX: event.screenX,
|
|
70
|
+
screenY: event.screenY,
|
|
71
|
+
pointerId: event.pointerId || 1,
|
|
72
|
+
pointerType: event.pointerType || 'mouse',
|
|
73
|
+
};
|
|
74
|
+
this._sweepStaleFallbackGutters();
|
|
75
|
+
};
|
|
76
|
+
document.addEventListener('pointermove', this._trackPointerPosition, { passive: true });
|
|
77
|
+
document.addEventListener('mousemove', this._trackPointerPosition, { passive: true });
|
|
78
|
+
// Fallback-positioned gutter buttons are position:fixed (viewport
|
|
79
|
+
// coordinates), so any scroll detaches them from their line. Clear on
|
|
80
|
+
// scroll and re-derive from the live pointer position (capture: true
|
|
81
|
+
// catches scrolls of inner containers too).
|
|
82
|
+
this._onAnyScroll = () => {
|
|
83
|
+
if (this._scrollSweepScheduled) return;
|
|
84
|
+
this._scrollSweepScheduled = true;
|
|
85
|
+
const schedule = typeof requestAnimationFrame === 'function'
|
|
86
|
+
? requestAnimationFrame
|
|
87
|
+
: (callback) => setTimeout(callback, 0);
|
|
88
|
+
schedule(() => {
|
|
89
|
+
this._scrollSweepScheduled = false;
|
|
90
|
+
for (const [fileName, container] of this._gutterContainers) {
|
|
91
|
+
if (container?.dataset?.fallbackPositioned === undefined) continue;
|
|
92
|
+
this._clearFallbackGutterPosition(fileName);
|
|
93
|
+
const fileState = this.files.get(fileName);
|
|
94
|
+
if (fileState) this._restoreHoverAfterRender(fileState);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
if (typeof window.addEventListener === 'function') {
|
|
99
|
+
window.addEventListener('scroll', this._onAnyScroll, { capture: true, passive: true });
|
|
100
|
+
}
|
|
101
|
+
if (this.workerManager?.subscribeToStatChanges) {
|
|
102
|
+
this._workerStatsUnsubscribe = this.workerManager.subscribeToStatChanges((stats) => {
|
|
103
|
+
this._handleWorkerStats(stats);
|
|
104
|
+
});
|
|
105
|
+
this._startWorkerInitTimeout();
|
|
106
|
+
const init = this.workerManager.initialize?.();
|
|
107
|
+
if (init?.catch) {
|
|
108
|
+
init.catch((err) => {
|
|
109
|
+
this._fallbackToMainThreadRendering('worker startup failed', err);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ─── Theme ────────────────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
static detectTheme() {
|
|
118
|
+
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
getThemeConfig() {
|
|
122
|
+
return {
|
|
123
|
+
dark: 'github-dark',
|
|
124
|
+
light: 'github-light',
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
_getWorkerRenderOptions() {
|
|
129
|
+
return {
|
|
130
|
+
theme: this.getThemeConfig(),
|
|
131
|
+
useTokenTransformer: false,
|
|
132
|
+
lineDiffType: 'word',
|
|
133
|
+
maxLineDiffLength: 1000,
|
|
134
|
+
tokenizeMaxLineLength: 1000,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
setTheme(theme) {
|
|
139
|
+
this.theme = theme;
|
|
140
|
+
if (this.workerManager?.setRenderOptions) {
|
|
141
|
+
const update = this.workerManager.setRenderOptions(this._getWorkerRenderOptions());
|
|
142
|
+
if (update?.catch) {
|
|
143
|
+
update.catch(err => {
|
|
144
|
+
console.warn('[PierreBridge] Failed to update @pierre/diffs worker theme.', err);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const [, fileState] of this.files) {
|
|
149
|
+
if (fileState.instance) {
|
|
150
|
+
fileState.instance.setThemeType(theme);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ─── Diff Style (unified / split) ─────────────────────────────────
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {*} style
|
|
159
|
+
* @returns {boolean} true when `style` is a supported diff layout.
|
|
160
|
+
*/
|
|
161
|
+
static isValidDiffStyle(style) {
|
|
162
|
+
return style === 'unified' || style === 'split';
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Current diff layout.
|
|
167
|
+
* @returns {'unified'|'split'}
|
|
168
|
+
*/
|
|
169
|
+
getDiffStyle() {
|
|
170
|
+
return this.diffStyle;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Switch every rendered file between unified and split (side-by-side) layout.
|
|
175
|
+
*
|
|
176
|
+
* Mirrors setTheme: validate, no-op when unchanged, update instance state,
|
|
177
|
+
* then re-render every FileDiff instance. Unlike theme, diffStyle is NOT a
|
|
178
|
+
* worker render option (it controls layout, not highlighting), so the worker
|
|
179
|
+
* pool is untouched here — only the per-instance FileDiff options change.
|
|
180
|
+
*
|
|
181
|
+
* `setOptions` replaces the instance's whole options object AND re-derives
|
|
182
|
+
* the hunks/interaction sub-managers, so we spread the instance's current
|
|
183
|
+
* options to preserve everything else (theme, gutter, selection, etc.). The
|
|
184
|
+
* instance keeps its stored lineAnnotations across setOptions, and rerender()
|
|
185
|
+
* re-runs the renderAnnotation callback, so user comments, AI suggestions,
|
|
186
|
+
* forms, and external threads survive the switch (they also live in
|
|
187
|
+
* fileState.annotations as the source of truth).
|
|
188
|
+
*
|
|
189
|
+
* @param {'unified'|'split'} style
|
|
190
|
+
*/
|
|
191
|
+
setDiffStyle(style) {
|
|
192
|
+
if (!PierreBridge.isValidDiffStyle(style)) {
|
|
193
|
+
console.warn(`[PierreBridge] Ignoring invalid diffStyle "${style}"; expected 'unified' or 'split'.`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (style === this.diffStyle) return;
|
|
197
|
+
this.diffStyle = style;
|
|
198
|
+
|
|
199
|
+
for (const [fileName, fileState] of this.files) {
|
|
200
|
+
const instance = fileState?.instance;
|
|
201
|
+
if (!instance) continue;
|
|
202
|
+
if (typeof instance.setOptions === 'function') {
|
|
203
|
+
instance.setOptions({ ...(instance.options || {}), diffStyle: style });
|
|
204
|
+
} else if (typeof instance.mergeOptions === 'function') {
|
|
205
|
+
instance.mergeOptions({ diffStyle: style });
|
|
206
|
+
}
|
|
207
|
+
instance.rerender?.();
|
|
208
|
+
this._syncSplitAnnotationLayout(fileName);
|
|
209
|
+
// The layout swap moves every line; a fallback-positioned gutter
|
|
210
|
+
// container would keep floating at its old viewport coordinates.
|
|
211
|
+
this._clearFallbackGutterPosition(fileName);
|
|
212
|
+
this._restoreHoverAfterRender(fileState);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Clear any fallback-positioned gutter buttons the pointer has abandoned.
|
|
218
|
+
*
|
|
219
|
+
* The fallback positioner pins the buttons with position:fixed, and the
|
|
220
|
+
* only teardown used to be a pointerleave listener on the shadow ROOT —
|
|
221
|
+
* a non-element that never receives pointerleave — so buttons hovered in
|
|
222
|
+
* one spot could float there forever (over unrelated content after a
|
|
223
|
+
* scroll or a layout toggle). Runs from the document-level pointer
|
|
224
|
+
* tracker: keep the buttons while the pointer is over the file or the
|
|
225
|
+
* buttons themselves; clear otherwise.
|
|
226
|
+
* @private
|
|
227
|
+
*/
|
|
228
|
+
_sweepStaleFallbackGutters() {
|
|
229
|
+
for (const [fileName, container] of this._gutterContainers) {
|
|
230
|
+
if (container?.dataset?.fallbackPositioned === undefined) continue;
|
|
231
|
+
if (this._isPointerInsideFile(this.files.get(fileName))) continue;
|
|
232
|
+
const pos = this._lastPointerPosition;
|
|
233
|
+
const rect = container.getBoundingClientRect?.();
|
|
234
|
+
if (pos && rect &&
|
|
235
|
+
pos.clientX >= rect.left && pos.clientX <= rect.right &&
|
|
236
|
+
pos.clientY >= rect.top && pos.clientY <= rect.bottom) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
this._clearFallbackGutterPosition(fileName);
|
|
240
|
+
this._hoveredRows.delete(fileName);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ─── CSS Injection ────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Build CSS to inject into Shadow DOM for annotation content (comments, suggestions, forms).
|
|
248
|
+
* Called lazily on first use.
|
|
249
|
+
*/
|
|
250
|
+
getUnsafeCSS() {
|
|
251
|
+
if (this._unsafeCSS !== null) return this._unsafeCSS;
|
|
252
|
+
this._unsafeCSS = PierreBridge.ANNOTATION_CSS;
|
|
253
|
+
return this._unsafeCSS;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Create the shared worker pool used by @pierre/diffs for syntax highlighting.
|
|
258
|
+
* The main thread still produces the initial plain-text AST, while expensive
|
|
259
|
+
* language highlighting happens off-thread and streams back through rerender().
|
|
260
|
+
* @returns {Object|null}
|
|
261
|
+
* @private
|
|
262
|
+
*/
|
|
263
|
+
_createWorkerManager() {
|
|
264
|
+
if (!window.PierreDiffs?.WorkerPoolManager || typeof Worker === 'undefined') {
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
try {
|
|
269
|
+
const hardwareConcurrency = window.navigator?.hardwareConcurrency || 2;
|
|
270
|
+
const poolSize = Math.max(1, Math.min(2, Math.floor(hardwareConcurrency / 2) || 1));
|
|
271
|
+
return new window.PierreDiffs.WorkerPoolManager({
|
|
272
|
+
workerFactory: () => {
|
|
273
|
+
const worker = new Worker('/js/vendor/pierre-diffs-worker.js');
|
|
274
|
+
worker.addEventListener('error', (event) => {
|
|
275
|
+
if (!this._workerReady) {
|
|
276
|
+
this._fallbackToMainThreadRendering('worker failed to load', event.error || event.message || event);
|
|
277
|
+
}
|
|
278
|
+
}, { once: true });
|
|
279
|
+
return worker;
|
|
280
|
+
},
|
|
281
|
+
poolSize,
|
|
282
|
+
totalASTLRUCacheSize: 50,
|
|
283
|
+
}, {
|
|
284
|
+
langs: ['text'],
|
|
285
|
+
...this._getWorkerRenderOptions(),
|
|
286
|
+
preferredHighlighter: 'shiki-js',
|
|
287
|
+
});
|
|
288
|
+
} catch (err) {
|
|
289
|
+
console.warn('[PierreBridge] Failed to initialize @pierre/diffs worker pool; falling back to main-thread rendering.', err);
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ─── Patch Parsing & diffPosition Computation ─────────────────────
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Parse a unified diff patch for a single file.
|
|
298
|
+
* @param {string} patch - Unified diff patch text (the part after the file header)
|
|
299
|
+
* @returns {import('@pierre/diffs').FileDiffMetadata}
|
|
300
|
+
*/
|
|
301
|
+
parsePatch(patch) {
|
|
302
|
+
if (!patch) return null;
|
|
303
|
+
|
|
304
|
+
// The patch may already include git diff headers (from parseUnifiedDiff)
|
|
305
|
+
// or may be just hunk content starting with @@.
|
|
306
|
+
// parsePatchFiles handles both formats.
|
|
307
|
+
let input = patch;
|
|
308
|
+
if (!patch.startsWith('diff --git ')) {
|
|
309
|
+
// Bare hunk content — wrap with minimal git diff header
|
|
310
|
+
input = `diff --git a/file b/file\n--- a/file\n+++ b/file\n${patch}`;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const parsed = window.PierreDiffs.parsePatchFiles(input);
|
|
314
|
+
if (parsed && parsed.length > 0 && parsed[0].files && parsed[0].files.length > 0) {
|
|
315
|
+
return parsed[0].files[0];
|
|
316
|
+
}
|
|
317
|
+
// Fallback: try getSingularPatch
|
|
318
|
+
return window.PierreDiffs.getSingularPatch(patch);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Compute GitHub diffPosition mapping for a patch.
|
|
323
|
+
* diffPosition is a 1-indexed consecutive counter: each hunk header and each line counts.
|
|
324
|
+
*
|
|
325
|
+
* renderFile already parses the patch once (parsePatch → Pierre metadata), so
|
|
326
|
+
* when that metadata is supplied we derive positions from its ordered
|
|
327
|
+
* `hunkContent` segments instead of parsing the patch a SECOND time. The
|
|
328
|
+
* derivation is identical to the raw-patch walk because git's unified diff
|
|
329
|
+
* always emits a change region's deletions before its additions, which is the
|
|
330
|
+
* order Pierre's `hunkContent` records (verified equal across mixed /
|
|
331
|
+
* add-only / del-only / multi-hunk / no-trailing-newline patches). Metadata
|
|
332
|
+
* without `hunkContent` (older bundle, getSingularPatch fallback, null) falls
|
|
333
|
+
* back to parsing the raw patch.
|
|
334
|
+
*
|
|
335
|
+
* @param {string} patch - Unified diff patch text
|
|
336
|
+
* @param {Object} [metadata] - Pre-parsed Pierre FileDiffMetadata (optional)
|
|
337
|
+
* @returns {Map<string, number>} Map of "side:lineNumber" → diffPosition
|
|
338
|
+
*/
|
|
339
|
+
computeDiffPositions(patch, metadata) {
|
|
340
|
+
if (metadata) {
|
|
341
|
+
const fromMeta = this._diffPositionsFromMetadata(metadata);
|
|
342
|
+
if (fromMeta) return fromMeta;
|
|
343
|
+
}
|
|
344
|
+
return this._diffPositionsFromPatch(patch);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Derive the diffPosition map from pre-parsed Pierre metadata's ordered
|
|
349
|
+
* `hunkContent` segments. Returns null (signalling "fall back to parsing the
|
|
350
|
+
* raw patch") when any hunk lacks `hunkContent` or carries a segment type we
|
|
351
|
+
* do not recognize, so an unexpected bundle shape can never yield a partial
|
|
352
|
+
* / wrong map.
|
|
353
|
+
* @param {Object} metadata - Pierre FileDiffMetadata
|
|
354
|
+
* @returns {Map<string, number>|null}
|
|
355
|
+
* @private
|
|
356
|
+
*/
|
|
357
|
+
_diffPositionsFromMetadata(metadata) {
|
|
358
|
+
if (!metadata || !Array.isArray(metadata.hunks)) return null;
|
|
359
|
+
|
|
360
|
+
const positions = new Map();
|
|
361
|
+
let diffPosition = 0;
|
|
362
|
+
|
|
363
|
+
for (const hunk of metadata.hunks) {
|
|
364
|
+
if (!Array.isArray(hunk.hunkContent)) return null;
|
|
365
|
+
diffPosition++; // Hunk header counts as a position
|
|
366
|
+
|
|
367
|
+
let oldLineNum = hunk.deletionStart;
|
|
368
|
+
let newLineNum = hunk.additionStart;
|
|
369
|
+
|
|
370
|
+
for (const segment of hunk.hunkContent) {
|
|
371
|
+
if (segment.type === 'context') {
|
|
372
|
+
for (let i = 0; i < segment.lines; i++) {
|
|
373
|
+
diffPosition++;
|
|
374
|
+
positions.set(`RIGHT:${newLineNum}`, diffPosition);
|
|
375
|
+
positions.set(`LEFT:${oldLineNum}`, diffPosition);
|
|
376
|
+
oldLineNum++;
|
|
377
|
+
newLineNum++;
|
|
378
|
+
}
|
|
379
|
+
} else if (segment.type === 'change') {
|
|
380
|
+
// git emits all deletions before all additions within a change.
|
|
381
|
+
for (let i = 0; i < (segment.deletions || 0); i++) {
|
|
382
|
+
diffPosition++;
|
|
383
|
+
positions.set(`LEFT:${oldLineNum}`, diffPosition);
|
|
384
|
+
oldLineNum++;
|
|
385
|
+
}
|
|
386
|
+
for (let i = 0; i < (segment.additions || 0); i++) {
|
|
387
|
+
diffPosition++;
|
|
388
|
+
positions.set(`RIGHT:${newLineNum}`, diffPosition);
|
|
389
|
+
newLineNum++;
|
|
390
|
+
}
|
|
391
|
+
} else {
|
|
392
|
+
// Unknown segment type — bail to the raw-patch parser rather than
|
|
393
|
+
// emit a map that silently skips lines.
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return positions;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Compute the diffPosition map by parsing the raw patch string. Fallback for
|
|
404
|
+
* computeDiffPositions when no usable metadata is available.
|
|
405
|
+
* @param {string} patch - Unified diff patch text
|
|
406
|
+
* @returns {Map<string, number>}
|
|
407
|
+
* @private
|
|
408
|
+
*/
|
|
409
|
+
_diffPositionsFromPatch(patch) {
|
|
410
|
+
const positions = new Map();
|
|
411
|
+
if (!patch) return positions;
|
|
412
|
+
|
|
413
|
+
// Use HunkParser if available for consistent parsing
|
|
414
|
+
const blocks = window.HunkParser
|
|
415
|
+
? window.HunkParser.parseDiffIntoBlocks(patch)
|
|
416
|
+
: this._parseBlocksFallback(patch);
|
|
417
|
+
|
|
418
|
+
let diffPosition = 0;
|
|
419
|
+
|
|
420
|
+
blocks.forEach(block => {
|
|
421
|
+
diffPosition++; // Hunk header counts as a position
|
|
422
|
+
|
|
423
|
+
let oldLineNum = block.oldStart;
|
|
424
|
+
let newLineNum = block.newStart;
|
|
425
|
+
|
|
426
|
+
block.lines.forEach(line => {
|
|
427
|
+
if (!line && line !== '') return;
|
|
428
|
+
diffPosition++;
|
|
429
|
+
|
|
430
|
+
if (line.startsWith('+')) {
|
|
431
|
+
positions.set(`RIGHT:${newLineNum}`, diffPosition);
|
|
432
|
+
newLineNum++;
|
|
433
|
+
} else if (line.startsWith('-')) {
|
|
434
|
+
positions.set(`LEFT:${oldLineNum}`, diffPosition);
|
|
435
|
+
oldLineNum++;
|
|
436
|
+
} else {
|
|
437
|
+
// Context line: addressable from both sides
|
|
438
|
+
positions.set(`RIGHT:${newLineNum}`, diffPosition);
|
|
439
|
+
positions.set(`LEFT:${oldLineNum}`, diffPosition);
|
|
440
|
+
oldLineNum++;
|
|
441
|
+
newLineNum++;
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
return positions;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Get diffPosition for a file + line + side.
|
|
451
|
+
* @param {string} fileName
|
|
452
|
+
* @param {number} lineNumber
|
|
453
|
+
* @param {string} side - 'LEFT' or 'RIGHT' (or 'additions'/'deletions')
|
|
454
|
+
* @returns {number|null}
|
|
455
|
+
*/
|
|
456
|
+
getDiffPosition(fileName, lineNumber, side) {
|
|
457
|
+
const fileState = this.files.get(fileName);
|
|
458
|
+
if (!fileState) return null;
|
|
459
|
+
const normalizedSide = PierreBridge.normalizeSide(side);
|
|
460
|
+
return fileState.diffPositions.get(`${normalizedSide}:${lineNumber}`) || null;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
_handleWorkerStats(stats) {
|
|
464
|
+
if (!stats) return;
|
|
465
|
+
|
|
466
|
+
if (stats.workersFailed || /fail|error/i.test(stats.managerState || '')) {
|
|
467
|
+
this._fallbackToMainThreadRendering('worker startup failed', stats);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
if (stats.managerState !== 'initialized' || this._workerReady) return;
|
|
472
|
+
this._workerReady = true;
|
|
473
|
+
this._clearWorkerInitTimeout();
|
|
474
|
+
const schedule = typeof requestAnimationFrame === 'function'
|
|
475
|
+
? requestAnimationFrame
|
|
476
|
+
: (callback) => setTimeout(callback, 0);
|
|
477
|
+
schedule(() => {
|
|
478
|
+
// A fallback (timeout / worker error) can land between scheduling this
|
|
479
|
+
// callback and running it, nulling the worker manager. If so, there is
|
|
480
|
+
// nothing to attach — bail out rather than rebuild with a dead pool.
|
|
481
|
+
if (this._workersFailed || !this.workerManager) return;
|
|
482
|
+
for (const [fileName, fileState] of [...this.files]) {
|
|
483
|
+
if (fileState.usesWorkerManager) {
|
|
484
|
+
// Already worker-backed — a bare rerender picks up the highlighter.
|
|
485
|
+
fileState.instance?.rerender?.();
|
|
486
|
+
} else if (!fileState.forcePlainText) {
|
|
487
|
+
// Rendered before the pool was ready, so its FileDiff was built with
|
|
488
|
+
// an undefined manager and can never gain worker highlighting from a
|
|
489
|
+
// bare rerender(). Reconstruct it through the worker path. Skip
|
|
490
|
+
// forcePlainText (large/plain) files — they are deliberately plain.
|
|
491
|
+
this._rebuildFileInstance(fileName, fileState, { useWorkerManager: true });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
_startWorkerInitTimeout() {
|
|
498
|
+
this._clearWorkerInitTimeout();
|
|
499
|
+
if (!this.workerManager || this._workerReady) return;
|
|
500
|
+
this._workerInitTimer = setTimeout(() => {
|
|
501
|
+
if (!this._workerReady) {
|
|
502
|
+
this._fallbackToMainThreadRendering('worker startup timed out');
|
|
503
|
+
}
|
|
504
|
+
}, PierreBridge.WORKER_INIT_TIMEOUT_MS);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
_clearWorkerInitTimeout() {
|
|
508
|
+
if (this._workerInitTimer) {
|
|
509
|
+
clearTimeout(this._workerInitTimer);
|
|
510
|
+
this._workerInitTimer = null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
_fallbackToMainThreadRendering(reason, detail) {
|
|
515
|
+
if (!this.workerManager) return false;
|
|
516
|
+
|
|
517
|
+
console.warn(`[PierreBridge] @pierre/diffs ${reason}; falling back to main-thread rendering.`, detail || '');
|
|
518
|
+
this._workersFailed = true;
|
|
519
|
+
this._workerReady = true;
|
|
520
|
+
this._clearWorkerInitTimeout();
|
|
521
|
+
if (this._workerStatsUnsubscribe) {
|
|
522
|
+
this._workerStatsUnsubscribe();
|
|
523
|
+
this._workerStatsUnsubscribe = null;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const failedManager = this.workerManager;
|
|
527
|
+
this.workerManager = null;
|
|
528
|
+
if (failedManager?.terminate) {
|
|
529
|
+
try {
|
|
530
|
+
failedManager.terminate();
|
|
531
|
+
} catch (err) {
|
|
532
|
+
console.warn('[PierreBridge] Failed to terminate @pierre/diffs worker pool.', err);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
for (const [fileName, fileState] of [...this.files]) {
|
|
537
|
+
if (!fileState.usesWorkerManager) continue;
|
|
538
|
+
this._rebuildFileInstance(fileName, fileState, { useWorkerManager: false });
|
|
539
|
+
}
|
|
540
|
+
return true;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
_createFileDiffInstance(fileName, formElements, renderOptions = {}) {
|
|
544
|
+
const workerManager = renderOptions.useWorkerManager === false
|
|
545
|
+
? undefined
|
|
546
|
+
: this.workerManager || undefined;
|
|
547
|
+
return new window.PierreDiffs.FileDiff({
|
|
548
|
+
theme: this.getThemeConfig(),
|
|
549
|
+
themeType: this.theme,
|
|
550
|
+
disableFileHeader: true,
|
|
551
|
+
diffStyle: this.diffStyle,
|
|
552
|
+
diffIndicators: 'bars',
|
|
553
|
+
overflow: 'wrap',
|
|
554
|
+
lineHoverHighlight: 'line',
|
|
555
|
+
lineDiffType: 'word',
|
|
556
|
+
enableGutterUtility: true,
|
|
557
|
+
enableLineSelection: true,
|
|
558
|
+
unsafeCSS: this.getUnsafeCSS(),
|
|
559
|
+
hunkSeparators: 'line-info',
|
|
560
|
+
expansionLineCount: 20,
|
|
561
|
+
collapsedContextThreshold: 5,
|
|
562
|
+
collapsed: renderOptions.collapsed || false,
|
|
563
|
+
|
|
564
|
+
// Custom gutter render — dual buttons (chat + comment) matching legacy UI.
|
|
565
|
+
// Cannot combine with onGutterUtilityClick; use one gutter API at a time.
|
|
566
|
+
renderGutterUtility: (getHoveredRow) => {
|
|
567
|
+
return this._createGutterButtons(fileName, getHoveredRow);
|
|
568
|
+
},
|
|
569
|
+
|
|
570
|
+
onLineClick: (props) => {
|
|
571
|
+
if (this.options.onLineClick) {
|
|
572
|
+
this.options.onLineClick(fileName, {
|
|
573
|
+
lineNumber: props.lineNumber,
|
|
574
|
+
side: props.annotationSide === 'deletions' ? 'LEFT' : 'RIGHT',
|
|
575
|
+
lineType: props.lineType,
|
|
576
|
+
element: props.lineElement,
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
},
|
|
580
|
+
|
|
581
|
+
onLineSelected: (range) => {
|
|
582
|
+
if (this.options.onLineSelect) {
|
|
583
|
+
this.options.onLineSelect(fileName, range);
|
|
584
|
+
}
|
|
585
|
+
},
|
|
586
|
+
|
|
587
|
+
onLineSelectionEnd: (range) => {
|
|
588
|
+
if (this.options.onLineSelectionEnd) {
|
|
589
|
+
this.options.onLineSelectionEnd(fileName, range);
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
|
|
593
|
+
onHunkExpand: (hunkIndex, direction, lineCount) => {
|
|
594
|
+
if (this.options.onHunkExpand) {
|
|
595
|
+
this.options.onHunkExpand(fileName, hunkIndex, direction, lineCount);
|
|
596
|
+
}
|
|
597
|
+
// Expansion can widen the line-number gutter (digit growth) and
|
|
598
|
+
// rebuilds shadow rows — re-sync split card stretching.
|
|
599
|
+
this._syncSplitAnnotationLayout(fileName);
|
|
600
|
+
},
|
|
601
|
+
|
|
602
|
+
renderAnnotation: (annotation) => {
|
|
603
|
+
return this._renderAnnotation(annotation, fileName, formElements);
|
|
604
|
+
},
|
|
605
|
+
|
|
606
|
+
onPostRender: (node, inst) => {
|
|
607
|
+
// Store reference to shadow root for DOM access
|
|
608
|
+
const fileState = this.files.get(fileName);
|
|
609
|
+
if (fileState) {
|
|
610
|
+
fileState.shadowHost = node;
|
|
611
|
+
}
|
|
612
|
+
this._syncSplitAnnotationLayout(fileName);
|
|
613
|
+
},
|
|
614
|
+
}, workerManager);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Tear down a file's FileDiff instance and rebuild it from scratch, selecting
|
|
619
|
+
* whether the new instance is worker-backed via `useWorkerManager`.
|
|
620
|
+
*
|
|
621
|
+
* This is the shared multi-step sequence used in BOTH directions:
|
|
622
|
+
* - Fallback: rebuild WITHOUT workers (`useWorkerManager: false`) when the
|
|
623
|
+
* worker pool fails/times out (see `_fallbackToMainThreadRendering`).
|
|
624
|
+
* - Init success: rebuild WITH workers (`useWorkerManager: true`) for files
|
|
625
|
+
* that rendered before the worker pool finished initializing (see
|
|
626
|
+
* `_handleWorkerStats`).
|
|
627
|
+
*
|
|
628
|
+
* Both paths need identical cleanup, re-parse, payload reconstruction (including
|
|
629
|
+
* the upgraded oldFile/newFile + contextRanges case), and hover restoration —
|
|
630
|
+
* only the manager differs, so the logic lives here once.
|
|
631
|
+
*
|
|
632
|
+
* @param {string} fileName
|
|
633
|
+
* @param {Object} fileState
|
|
634
|
+
* @param {Object} opts
|
|
635
|
+
* @param {boolean} opts.useWorkerManager - true to attach the worker pool,
|
|
636
|
+
* false to rebuild on the main thread.
|
|
637
|
+
* @returns {boolean} true if a render occurred
|
|
638
|
+
* @private
|
|
639
|
+
*/
|
|
640
|
+
_rebuildFileInstance(fileName, fileState, { useWorkerManager } = {}) {
|
|
641
|
+
if (!fileState?.container || !fileState.patch) return false;
|
|
642
|
+
|
|
643
|
+
try {
|
|
644
|
+
fileState.instance?.cleanUp();
|
|
645
|
+
} catch (err) {
|
|
646
|
+
console.warn(`[PierreBridge] Failed to clean up existing diff instance for ${fileName}.`, err);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
this._gutterContainers.delete(fileName);
|
|
650
|
+
fileState.container.innerHTML = '';
|
|
651
|
+
const renderOptions = {
|
|
652
|
+
collapsed: fileState.collapsed,
|
|
653
|
+
forcePlainText: fileState.forcePlainText,
|
|
654
|
+
useWorkerManager,
|
|
655
|
+
};
|
|
656
|
+
const metadata = this.parsePatch(fileState.patch);
|
|
657
|
+
if (metadata) {
|
|
658
|
+
metadata.name = fileName;
|
|
659
|
+
if (renderOptions.forcePlainText) {
|
|
660
|
+
metadata.lang = 'text';
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
const instance = this._createFileDiffInstance(fileName, fileState.formElements, renderOptions);
|
|
664
|
+
fileState.instance = instance;
|
|
665
|
+
fileState.metadata = metadata;
|
|
666
|
+
fileState.shadowHost = null;
|
|
667
|
+
fileState.usesWorkerManager = useWorkerManager === true && !!this.workerManager;
|
|
668
|
+
|
|
669
|
+
const payload = fileState.oldFile || fileState.newFile
|
|
670
|
+
? {
|
|
671
|
+
oldFile: fileState.oldFile,
|
|
672
|
+
newFile: fileState.newFile,
|
|
673
|
+
fileDiff: this._effectiveContextRanges(fileState).length && fileState.baseMetadata
|
|
674
|
+
? window.PierreContext?.mergeContextRanges?.(fileState.baseMetadata, this._effectiveContextRanges(fileState)) || fileState.baseMetadata
|
|
675
|
+
: fileState.baseMetadata || metadata,
|
|
676
|
+
lineAnnotations: fileState.annotations,
|
|
677
|
+
containerWrapper: fileState.container,
|
|
678
|
+
}
|
|
679
|
+
: {
|
|
680
|
+
fileDiff: metadata,
|
|
681
|
+
containerWrapper: fileState.container,
|
|
682
|
+
lineAnnotations: fileState.annotations,
|
|
683
|
+
};
|
|
684
|
+
const rendered = instance.render(payload);
|
|
685
|
+
fileState.shadowHost = fileState.container.querySelector('diffs-container') || fileState.container.firstElementChild;
|
|
686
|
+
if (rendered) this._installFallbackHoverTracking(fileName, fileState);
|
|
687
|
+
if (rendered) this._restoreHoverAfterRender(fileState);
|
|
688
|
+
return rendered;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
_isPointerInsideFile(fileState) {
|
|
692
|
+
const pos = this._lastPointerPosition;
|
|
693
|
+
if (!pos || !fileState?.container?.isConnected) return false;
|
|
694
|
+
|
|
695
|
+
const rect = fileState.container.getBoundingClientRect();
|
|
696
|
+
return (
|
|
697
|
+
pos.clientX >= rect.left &&
|
|
698
|
+
pos.clientX <= rect.right &&
|
|
699
|
+
pos.clientY >= rect.top &&
|
|
700
|
+
pos.clientY <= rect.bottom
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
isPointerOverFile(fileName) {
|
|
705
|
+
return this._isPointerInsideFile(this.files.get(fileName));
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
_restoreHoverAfterRender(fileState) {
|
|
709
|
+
const pos = this._lastPointerPosition;
|
|
710
|
+
if (!pos || !this._isPointerInsideFile(fileState)) return;
|
|
711
|
+
|
|
712
|
+
const schedule = typeof requestAnimationFrame === 'function'
|
|
713
|
+
? requestAnimationFrame
|
|
714
|
+
: (callback) => setTimeout(callback, 0);
|
|
715
|
+
schedule(() => {
|
|
716
|
+
if (!this._isPointerInsideFile(fileState)) return;
|
|
717
|
+
|
|
718
|
+
const shadowRoot = fileState.shadowHost?.shadowRoot
|
|
719
|
+
|| fileState.container.querySelector('diffs-container')?.shadowRoot;
|
|
720
|
+
const target = shadowRoot?.elementFromPoint?.(pos.clientX, pos.clientY)
|
|
721
|
+
|| document.elementFromPoint(pos.clientX, pos.clientY);
|
|
722
|
+
if (!target) return;
|
|
723
|
+
|
|
724
|
+
const eventInit = {
|
|
725
|
+
bubbles: true,
|
|
726
|
+
cancelable: true,
|
|
727
|
+
composed: true,
|
|
728
|
+
clientX: pos.clientX,
|
|
729
|
+
clientY: pos.clientY,
|
|
730
|
+
screenX: pos.screenX || 0,
|
|
731
|
+
screenY: pos.screenY || 0,
|
|
732
|
+
pointerId: pos.pointerId || 1,
|
|
733
|
+
pointerType: pos.pointerType || 'mouse',
|
|
734
|
+
isPrimary: true,
|
|
735
|
+
};
|
|
736
|
+
if (typeof window.PointerEvent === 'function') {
|
|
737
|
+
target.dispatchEvent(new window.PointerEvent('pointermove', eventInit));
|
|
738
|
+
}
|
|
739
|
+
target.dispatchEvent(new MouseEvent('mousemove', eventInit));
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
_getHoveredRow(fileName) {
|
|
744
|
+
const getter = this._gutterRowGetters.get(fileName);
|
|
745
|
+
if (getter) {
|
|
746
|
+
try {
|
|
747
|
+
const hovered = getter();
|
|
748
|
+
if (hovered) return hovered;
|
|
749
|
+
} catch (_err) {
|
|
750
|
+
// The cached gutter buttons can outlive a FileDiff instance during a
|
|
751
|
+
// rerender. Fall through to the bridge-tracked hover row.
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return this._hoveredRows.get(fileName) || null;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Derive the annotation side ('deletions'|'additions') for a hovered gutter
|
|
759
|
+
* line cell.
|
|
760
|
+
*
|
|
761
|
+
* Unified view stamps only one column, so the line-type string
|
|
762
|
+
* (change-deletion vs change-addition) is authoritative; context lines are
|
|
763
|
+
* addressable from the right (additions) side by convention.
|
|
764
|
+
*
|
|
765
|
+
* Split view renders two independent code columns and a context line's
|
|
766
|
+
* gutter carries a neutral 'context' line-type in BOTH columns — the string
|
|
767
|
+
* can no longer disambiguate. Derive the side from the enclosing
|
|
768
|
+
* `code[data-deletions]` / `code[data-additions]` column instead, falling
|
|
769
|
+
* back to the line-type string if (defensively) neither ancestor is found.
|
|
770
|
+
* @param {Element} lineCell - hovered gutter cell (has data-column-number)
|
|
771
|
+
* @returns {'deletions'|'additions'}
|
|
772
|
+
* @private
|
|
773
|
+
*/
|
|
774
|
+
_deriveHoverSide(lineCell) {
|
|
775
|
+
if (this.diffStyle === 'split') {
|
|
776
|
+
if (lineCell.closest?.('code[data-deletions]')) return 'deletions';
|
|
777
|
+
if (lineCell.closest?.('code[data-additions]')) return 'additions';
|
|
778
|
+
}
|
|
779
|
+
const lineType = lineCell.dataset?.lineType || '';
|
|
780
|
+
return lineType.includes('deletion') ? 'deletions' : 'additions';
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
_installFallbackHoverTracking(fileName, fileState) {
|
|
784
|
+
fileState._fallbackHoverCleanup?.();
|
|
785
|
+
|
|
786
|
+
const shadowRoot = fileState.shadowHost?.shadowRoot
|
|
787
|
+
|| fileState.container?.querySelector('diffs-container')?.shadowRoot;
|
|
788
|
+
if (!shadowRoot) return;
|
|
789
|
+
|
|
790
|
+
const onPointerMove = (event) => {
|
|
791
|
+
const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
|
|
792
|
+
const lineCell = path.find(node =>
|
|
793
|
+
node?.nodeType === 1 &&
|
|
794
|
+
node.dataset?.columnNumber != null &&
|
|
795
|
+
node.dataset?.lineType != null
|
|
796
|
+
);
|
|
797
|
+
if (!lineCell) return;
|
|
798
|
+
|
|
799
|
+
const lineNumber = parseInt(lineCell.dataset.columnNumber, 10);
|
|
800
|
+
if (!Number.isFinite(lineNumber)) return;
|
|
801
|
+
|
|
802
|
+
this._hoveredRows.set(fileName, {
|
|
803
|
+
lineNumber,
|
|
804
|
+
side: this._deriveHoverSide(lineCell),
|
|
805
|
+
});
|
|
806
|
+
this._positionFallbackGutter(fileName, lineCell);
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
const onPointerLeave = () => {
|
|
810
|
+
this._hoveredRows.delete(fileName);
|
|
811
|
+
this._clearFallbackGutterPosition(fileName);
|
|
812
|
+
};
|
|
813
|
+
|
|
814
|
+
shadowRoot.addEventListener('pointermove', onPointerMove);
|
|
815
|
+
shadowRoot.addEventListener('mousemove', onPointerMove);
|
|
816
|
+
shadowRoot.addEventListener('pointerleave', onPointerLeave);
|
|
817
|
+
fileState._fallbackHoverCleanup = () => {
|
|
818
|
+
shadowRoot.removeEventListener('pointermove', onPointerMove);
|
|
819
|
+
shadowRoot.removeEventListener('mousemove', onPointerMove);
|
|
820
|
+
shadowRoot.removeEventListener('pointerleave', onPointerLeave);
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
_positionFallbackGutter(fileName, lineCell) {
|
|
825
|
+
const container = this._gutterContainers.get(fileName);
|
|
826
|
+
if (!container) return;
|
|
827
|
+
|
|
828
|
+
for (const [otherFileName, otherContainer] of this._gutterContainers) {
|
|
829
|
+
if (otherFileName === fileName || !otherContainer.parentElement) continue;
|
|
830
|
+
otherContainer._pierreFallbackParent = otherContainer._pierreFallbackParent || otherContainer.parentElement;
|
|
831
|
+
otherContainer.remove();
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const rect = lineCell.getBoundingClientRect();
|
|
835
|
+
if (!rect.width || !rect.height) return;
|
|
836
|
+
|
|
837
|
+
const fileState = this.files.get(fileName);
|
|
838
|
+
const fallbackParent = fileState?.container?.closest?.('[data-file-name]') || fileState?.container;
|
|
839
|
+
container.dataset.fallbackPositioned = '';
|
|
840
|
+
if (fallbackParent && container.parentElement !== fallbackParent) {
|
|
841
|
+
container._pierreFallbackParent = container._pierreFallbackParent || container.parentElement;
|
|
842
|
+
fallbackParent.prepend(container);
|
|
843
|
+
}
|
|
844
|
+
container.style.position = 'fixed';
|
|
845
|
+
container.style.left = `${rect.right - 12}px`;
|
|
846
|
+
container.style.right = 'auto';
|
|
847
|
+
container.style.top = `${rect.top + (rect.height / 2)}px`;
|
|
848
|
+
container.style.transform = 'translateY(-50%)';
|
|
849
|
+
container.style.zIndex = '1000';
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
_clearFallbackGutterPosition(fileName) {
|
|
853
|
+
const container = this._gutterContainers.get(fileName);
|
|
854
|
+
// The marker is set as an empty string (falsy!) — presence-check it.
|
|
855
|
+
if (container?.dataset?.fallbackPositioned === undefined) return;
|
|
856
|
+
|
|
857
|
+
delete container.dataset.fallbackPositioned;
|
|
858
|
+
const fallbackParent = container._pierreFallbackParent;
|
|
859
|
+
if (fallbackParent?.isConnected && container.parentElement !== fallbackParent) {
|
|
860
|
+
fallbackParent.appendChild(container);
|
|
861
|
+
}
|
|
862
|
+
container._pierreFallbackParent = null;
|
|
863
|
+
container.style.removeProperty('position');
|
|
864
|
+
container.style.removeProperty('left');
|
|
865
|
+
container.style.removeProperty('right');
|
|
866
|
+
container.style.removeProperty('top');
|
|
867
|
+
container.style.removeProperty('transform');
|
|
868
|
+
container.style.removeProperty('z-index');
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// ─── File Rendering ───────────────────────────────────────────────
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Create and render a FileDiff instance for a file.
|
|
875
|
+
* @param {string} fileName - File path
|
|
876
|
+
* @param {HTMLElement} container - DOM container to render into
|
|
877
|
+
* @param {string} patch - Unified diff patch text
|
|
878
|
+
* @param {Object} [renderOptions] - Additional render options
|
|
879
|
+
* @param {boolean} [renderOptions.collapsed] - Start collapsed
|
|
880
|
+
* @returns {Object} The file state object
|
|
881
|
+
*/
|
|
882
|
+
renderFile(fileName, container, patch, renderOptions = {}) {
|
|
883
|
+
if (this._disabled) return null;
|
|
884
|
+
|
|
885
|
+
// Clean up existing instance
|
|
886
|
+
this.destroyFile(fileName);
|
|
887
|
+
|
|
888
|
+
const metadata = this.parsePatch(patch);
|
|
889
|
+
// Override the file name in metadata to match pair-review's name
|
|
890
|
+
if (metadata) {
|
|
891
|
+
metadata.name = fileName;
|
|
892
|
+
if (renderOptions.forcePlainText) {
|
|
893
|
+
metadata.lang = 'text';
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// Reuse the metadata parsed just above — computeDiffPositions derives the
|
|
898
|
+
// diffPosition map from it instead of parsing the same patch a second time.
|
|
899
|
+
const diffPositions = this.computeDiffPositions(patch, metadata);
|
|
900
|
+
const annotations = [];
|
|
901
|
+
const formElements = new Map();
|
|
902
|
+
|
|
903
|
+
const useWorkerManager = !!(this.workerManager && this._workerReady);
|
|
904
|
+
const instance = this._createFileDiffInstance(fileName, formElements, {
|
|
905
|
+
...renderOptions,
|
|
906
|
+
useWorkerManager,
|
|
907
|
+
});
|
|
908
|
+
|
|
909
|
+
const rendered = instance.render({
|
|
910
|
+
fileDiff: metadata,
|
|
911
|
+
containerWrapper: container,
|
|
912
|
+
lineAnnotations: annotations,
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
const fileState = {
|
|
916
|
+
instance,
|
|
917
|
+
fileName,
|
|
918
|
+
metadata,
|
|
919
|
+
container,
|
|
920
|
+
patch,
|
|
921
|
+
annotations,
|
|
922
|
+
diffPositions,
|
|
923
|
+
formElements,
|
|
924
|
+
shadowHost: container.querySelector('diffs-container') || container.firstElementChild,
|
|
925
|
+
// Context range support
|
|
926
|
+
oldFile: null,
|
|
927
|
+
newFile: null,
|
|
928
|
+
baseMetadata: null, // metadata before context range merging
|
|
929
|
+
contextRanges: [], // [{startLine, endLine}] in NEW file coords
|
|
930
|
+
// Lines the ORIGINAL PATCH rendered, captured at content upgrade. The
|
|
931
|
+
// full-contents re-diff can produce narrower context than the patch;
|
|
932
|
+
// these spans are merged into every render so the upgrade never
|
|
933
|
+
// un-renders visible lines (which would orphan annotations anchored to
|
|
934
|
+
// them). Unlike contextRanges, they survive clearContextRanges.
|
|
935
|
+
patchParityRanges: null,
|
|
936
|
+
forcePlainText: !!renderOptions.forcePlainText,
|
|
937
|
+
collapsed: !!renderOptions.collapsed,
|
|
938
|
+
usesWorkerManager: useWorkerManager,
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
this.files.set(fileName, fileState);
|
|
942
|
+
fileState.shadowHost = fileState.container.querySelector('diffs-container') || fileState.container.firstElementChild;
|
|
943
|
+
if (rendered) this._installFallbackHoverTracking(fileName, fileState);
|
|
944
|
+
return fileState;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* Upgrade a patch-only render with full file contents to enable hunk expansion.
|
|
949
|
+
* Calls render() again on the existing FileDiff instance — the library detects
|
|
950
|
+
* new content via areFilesEqual() and re-renders with isPartial: false.
|
|
951
|
+
* @param {string} fileName
|
|
952
|
+
* @param {{ name: string, contents: string }|null} oldFile
|
|
953
|
+
* @param {{ name: string, contents: string }|null} newFile
|
|
954
|
+
* @returns {boolean} true if re-render occurred
|
|
955
|
+
*/
|
|
956
|
+
upgradeFileContents(fileName, oldFile, newFile) {
|
|
957
|
+
const fileState = this.files.get(fileName);
|
|
958
|
+
if (!fileState || !fileState.instance) return false;
|
|
959
|
+
const nextOldFile = fileState.forcePlainText && oldFile
|
|
960
|
+
? { ...oldFile, lang: 'text' }
|
|
961
|
+
: oldFile;
|
|
962
|
+
const nextNewFile = fileState.forcePlainText && newFile
|
|
963
|
+
? { ...newFile, lang: 'text' }
|
|
964
|
+
: newFile;
|
|
965
|
+
|
|
966
|
+
// Snapshot the currently-rendered hunk spans BEFORE render() replaces
|
|
967
|
+
// instance.fileDiff: the full-contents re-diff can compute narrower
|
|
968
|
+
// context than the original patch, silently un-rendering lines that
|
|
969
|
+
// annotations, comments, and the user's eyes are anchored to.
|
|
970
|
+
const prevHunks = fileState.instance.fileDiff?.hunks;
|
|
971
|
+
|
|
972
|
+
const rendered = fileState.instance.render({
|
|
973
|
+
oldFile: nextOldFile,
|
|
974
|
+
newFile: nextNewFile,
|
|
975
|
+
lineAnnotations: fileState.annotations,
|
|
976
|
+
containerWrapper: fileState.container,
|
|
977
|
+
});
|
|
978
|
+
// Cache full-file contents for re-render calls (context ranges, etc.)
|
|
979
|
+
fileState.oldFile = nextOldFile;
|
|
980
|
+
fileState.newFile = nextNewFile;
|
|
981
|
+
// Snapshot metadata whenever the instance has a fileDiff,
|
|
982
|
+
// even if render() returned false (e.g. files-equal early exit)
|
|
983
|
+
if (fileState.instance.fileDiff) {
|
|
984
|
+
fileState.baseMetadata = fileState.instance.fileDiff;
|
|
985
|
+
if (!fileState.patchParityRanges && Array.isArray(prevHunks) && prevHunks.length) {
|
|
986
|
+
fileState.patchParityRanges = prevHunks
|
|
987
|
+
.filter(h => h.additionCount > 0)
|
|
988
|
+
.map(h => ({
|
|
989
|
+
startLine: h.additionStart,
|
|
990
|
+
endLine: h.additionStart + h.additionCount - 1,
|
|
991
|
+
}));
|
|
992
|
+
}
|
|
993
|
+
if (this._effectiveContextRanges(fileState).length) this._applyContextRanges(fileName);
|
|
994
|
+
}
|
|
995
|
+
if (rendered) this._installFallbackHoverTracking(fileName, fileState);
|
|
996
|
+
if (rendered) this._restoreHoverAfterRender(fileState);
|
|
997
|
+
return rendered;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Render a binary file placeholder (no diff).
|
|
1002
|
+
* @param {HTMLElement} container
|
|
1003
|
+
* @param {string} message
|
|
1004
|
+
*/
|
|
1005
|
+
renderBinaryFile(container, message = 'Binary file') {
|
|
1006
|
+
container.innerHTML = `<div class="pierre-binary-file">${message}</div>`;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Collapse/expand a file's diff rendering.
|
|
1011
|
+
* @param {string} fileName
|
|
1012
|
+
* @param {boolean} collapsed
|
|
1013
|
+
*/
|
|
1014
|
+
setCollapsed(fileName, collapsed) {
|
|
1015
|
+
const fileState = this.files.get(fileName);
|
|
1016
|
+
if (!fileState) return;
|
|
1017
|
+
const wasCollapsed = fileState.collapsed;
|
|
1018
|
+
fileState.collapsed = collapsed;
|
|
1019
|
+
// Vendor setOptions REPLACES the whole options object (it does not
|
|
1020
|
+
// merge), so a bare { collapsed } would silently drop diffStyle, theme,
|
|
1021
|
+
// renderAnnotation, and every other option — spread the live options in.
|
|
1022
|
+
fileState.instance.setOptions({ ...(fileState.instance.options || {}), collapsed });
|
|
1023
|
+
// A file rendered while collapsed has zero shadow-DOM lines (the vendor
|
|
1024
|
+
// skips line rendering for collapsed instances). Flipping the option
|
|
1025
|
+
// alone leaves the body empty on expand — force a rerender so the lines
|
|
1026
|
+
// materialize. Cheap no-op when the lines already exist, and rerender
|
|
1027
|
+
// re-applies fileState.annotations so nothing is lost.
|
|
1028
|
+
if (wasCollapsed && !collapsed && typeof fileState.instance.rerender === 'function') {
|
|
1029
|
+
fileState.instance.rerender();
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* Destroy a file's FileDiff instance and clean up.
|
|
1035
|
+
* @param {string} fileName
|
|
1036
|
+
*/
|
|
1037
|
+
destroyFile(fileName) {
|
|
1038
|
+
const fileState = this.files.get(fileName);
|
|
1039
|
+
if (!fileState) return;
|
|
1040
|
+
const gutterContainer = this._gutterContainers.get(fileName);
|
|
1041
|
+
if (fileState.instance) {
|
|
1042
|
+
fileState.instance.cleanUp();
|
|
1043
|
+
}
|
|
1044
|
+
fileState._fallbackHoverCleanup?.();
|
|
1045
|
+
this._clearFallbackGutterPosition(fileName);
|
|
1046
|
+
gutterContainer?.remove();
|
|
1047
|
+
fileState.formElements.clear();
|
|
1048
|
+
this._gutterContainers.delete(fileName);
|
|
1049
|
+
this._gutterRowGetters.delete(fileName);
|
|
1050
|
+
this._hoveredRows.delete(fileName);
|
|
1051
|
+
this.files.delete(fileName);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* Destroy all file instances.
|
|
1056
|
+
*/
|
|
1057
|
+
destroyAll() {
|
|
1058
|
+
for (const [fileName] of this.files) {
|
|
1059
|
+
this.destroyFile(fileName);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// ─── Context Ranges ──────────────────────────────────────────────
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* Add context ranges to reveal non-contiguous lines in a file's diff.
|
|
1067
|
+
* Ranges are in NEW file coordinates (1-indexed).
|
|
1068
|
+
* If file contents aren't loaded yet, ranges are queued for later application.
|
|
1069
|
+
* @param {string} fileName
|
|
1070
|
+
* @param {Array<{startLine: number, endLine: number}>} ranges
|
|
1071
|
+
* @returns {boolean} true if ranges were applied immediately
|
|
1072
|
+
*/
|
|
1073
|
+
addContextRanges(fileName, ranges) {
|
|
1074
|
+
const fileState = this.files.get(fileName);
|
|
1075
|
+
if (!fileState || !fileState.instance) return false;
|
|
1076
|
+
|
|
1077
|
+
const { mergeOverlapping } = window.PierreContext || {};
|
|
1078
|
+
if (!mergeOverlapping) {
|
|
1079
|
+
console.warn('[PierreBridge] window.PierreContext not loaded — cannot add context ranges');
|
|
1080
|
+
return false;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// Merge with existing context ranges (deduplicate)
|
|
1084
|
+
const existing = fileState.contextRanges || [];
|
|
1085
|
+
fileState.contextRanges = mergeOverlapping([...existing, ...ranges]);
|
|
1086
|
+
|
|
1087
|
+
// If file contents aren't loaded yet, ranges will be applied in upgradeFileContents
|
|
1088
|
+
if (!fileState.baseMetadata) return false;
|
|
1089
|
+
|
|
1090
|
+
return this._applyContextRanges(fileName);
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* Re-render a file with new fileDiff metadata, preserving cached file contents.
|
|
1095
|
+
* Clears expandedHunks to avoid stale hunk-index references.
|
|
1096
|
+
* @param {Object} fileState
|
|
1097
|
+
* @param {Object} fileDiff - merged or base metadata
|
|
1098
|
+
* @returns {boolean}
|
|
1099
|
+
* @private
|
|
1100
|
+
*/
|
|
1101
|
+
_renderWithFileDiff(fileState, fileDiff) {
|
|
1102
|
+
fileState.instance.hunksRenderer?.expandedHunks?.clear();
|
|
1103
|
+
const rendered = fileState.instance.render({
|
|
1104
|
+
oldFile: fileState.oldFile,
|
|
1105
|
+
newFile: fileState.newFile,
|
|
1106
|
+
fileDiff,
|
|
1107
|
+
lineAnnotations: fileState.annotations,
|
|
1108
|
+
containerWrapper: fileState.container,
|
|
1109
|
+
});
|
|
1110
|
+
if (rendered) this._installFallbackHoverTracking(fileState.fileName, fileState);
|
|
1111
|
+
if (rendered) this._restoreHoverAfterRender(fileState);
|
|
1112
|
+
return rendered;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* All ranges that must be visible: patch-parity spans (immutable, captured
|
|
1117
|
+
* at content upgrade) plus dynamically added context ranges.
|
|
1118
|
+
* @param {Object} fileState
|
|
1119
|
+
* @returns {Array<{startLine: number, endLine: number}>}
|
|
1120
|
+
* @private
|
|
1121
|
+
*/
|
|
1122
|
+
_effectiveContextRanges(fileState) {
|
|
1123
|
+
return [
|
|
1124
|
+
...(fileState?.patchParityRanges || []),
|
|
1125
|
+
...(fileState?.contextRanges || []),
|
|
1126
|
+
];
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
_applyContextRanges(fileName) {
|
|
1130
|
+
const fileState = this.files.get(fileName);
|
|
1131
|
+
if (!fileState?.baseMetadata) return false;
|
|
1132
|
+
const ranges = this._effectiveContextRanges(fileState);
|
|
1133
|
+
if (!ranges.length) return false;
|
|
1134
|
+
|
|
1135
|
+
const { mergeContextRanges } = window.PierreContext || {};
|
|
1136
|
+
if (!mergeContextRanges) return false;
|
|
1137
|
+
|
|
1138
|
+
const merged = mergeContextRanges(fileState.baseMetadata, ranges);
|
|
1139
|
+
return this._renderWithFileDiff(fileState, merged);
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/**
|
|
1143
|
+
* Remove specific context ranges from a file.
|
|
1144
|
+
* @param {string} fileName
|
|
1145
|
+
* @param {Array<{startLine: number, endLine: number}>} ranges
|
|
1146
|
+
* @returns {boolean} true if re-render occurred
|
|
1147
|
+
*/
|
|
1148
|
+
removeContextRanges(fileName, ranges) {
|
|
1149
|
+
const fileState = this.files.get(fileName);
|
|
1150
|
+
if (!fileState) return false;
|
|
1151
|
+
|
|
1152
|
+
const { subtractRanges } = window.PierreContext || {};
|
|
1153
|
+
if (!subtractRanges) return false;
|
|
1154
|
+
|
|
1155
|
+
fileState.contextRanges = subtractRanges(fileState.contextRanges || [], ranges);
|
|
1156
|
+
|
|
1157
|
+
if (!fileState.baseMetadata) return false;
|
|
1158
|
+
if (this._effectiveContextRanges(fileState).length === 0) {
|
|
1159
|
+
return this._renderWithFileDiff(fileState, fileState.baseMetadata);
|
|
1160
|
+
}
|
|
1161
|
+
return this._applyContextRanges(fileName);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* Remove all context ranges for a file, restoring original diff view.
|
|
1166
|
+
* @param {string} fileName
|
|
1167
|
+
* @returns {boolean} true if re-render occurred
|
|
1168
|
+
*/
|
|
1169
|
+
clearContextRanges(fileName) {
|
|
1170
|
+
const fileState = this.files.get(fileName);
|
|
1171
|
+
if (!fileState) return false;
|
|
1172
|
+
|
|
1173
|
+
fileState.contextRanges = [];
|
|
1174
|
+
|
|
1175
|
+
if (!fileState.baseMetadata) return false;
|
|
1176
|
+
// Patch-parity spans are not "context ranges" — clearing must never
|
|
1177
|
+
// shrink the view below what the original patch rendered.
|
|
1178
|
+
if (this._effectiveContextRanges(fileState).length) {
|
|
1179
|
+
return this._applyContextRanges(fileName);
|
|
1180
|
+
}
|
|
1181
|
+
return this._renderWithFileDiff(fileState, fileState.baseMetadata);
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/**
|
|
1185
|
+
* Convert OLD-file (deletion-side) line numbers to NEW-file coordinates.
|
|
1186
|
+
* Delegates to PierreContext using the file's baseMetadata for offset computation.
|
|
1187
|
+
* @param {string} fileName
|
|
1188
|
+
* @param {number} oldStart - OLD-file line (1-indexed)
|
|
1189
|
+
* @param {number} oldEnd - OLD-file line (1-indexed)
|
|
1190
|
+
* @returns {{startLine: number, endLine: number}|null}
|
|
1191
|
+
*/
|
|
1192
|
+
convertOldToNew(fileName, oldStart, oldEnd) {
|
|
1193
|
+
const fileState = this.files.get(fileName);
|
|
1194
|
+
if (!fileState?.baseMetadata) return null;
|
|
1195
|
+
const { convertOldToNew } = window.PierreContext || {};
|
|
1196
|
+
if (!convertOldToNew) return null;
|
|
1197
|
+
return convertOldToNew(fileState.baseMetadata, oldStart, oldEnd);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// ─── Gutter Buttons ───────────────────────────────────────────────
|
|
1201
|
+
|
|
1202
|
+
/**
|
|
1203
|
+
* Chat button SVG icon (GitHub-style speech bubble, matches legacy DiffRenderer).
|
|
1204
|
+
* @private
|
|
1205
|
+
*/
|
|
1206
|
+
static CHAT_SVG = `<svg viewBox="0 0 16 16" fill="currentColor" width="14" height="14"><path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"/></svg>`;
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Create dual gutter buttons (chat + comment) for renderGutterUtility.
|
|
1210
|
+
*
|
|
1211
|
+
* @pierre/diffs calls this once per render. The returned element is placed
|
|
1212
|
+
* in the light DOM and slotted into Shadow DOM. The library moves it to
|
|
1213
|
+
* follow the hovered line's number cell automatically.
|
|
1214
|
+
*
|
|
1215
|
+
* @param {string} fileName
|
|
1216
|
+
* @param {Function} getHoveredRow - () => { lineNumber, side } | undefined
|
|
1217
|
+
* @returns {HTMLElement}
|
|
1218
|
+
* @private
|
|
1219
|
+
*/
|
|
1220
|
+
/**
|
|
1221
|
+
* Get the active line selection for a file, if any.
|
|
1222
|
+
* Reads directly from @pierre/diffs' InteractionManager.
|
|
1223
|
+
* @param {string} fileName
|
|
1224
|
+
* @returns {{ start: number, end: number, side: string }|null}
|
|
1225
|
+
*/
|
|
1226
|
+
getLineSelection(fileName) {
|
|
1227
|
+
const fileState = this.files.get(fileName);
|
|
1228
|
+
if (!fileState || !fileState.instance) return null;
|
|
1229
|
+
const range = fileState.instance.interactionManager.getSelection();
|
|
1230
|
+
if (!range) return null;
|
|
1231
|
+
return {
|
|
1232
|
+
start: range.start,
|
|
1233
|
+
end: range.end,
|
|
1234
|
+
side: range.side === 'deletions' ? 'LEFT' : 'RIGHT',
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* Clear the active line selection for a file.
|
|
1240
|
+
* @param {string} fileName
|
|
1241
|
+
*/
|
|
1242
|
+
clearLineSelection(fileName) {
|
|
1243
|
+
const fileState = this.files.get(fileName);
|
|
1244
|
+
if (!fileState || !fileState.instance) return;
|
|
1245
|
+
fileState.instance.setSelectedLines(null);
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* Scroll to a specific line in a Pierre-rendered file.
|
|
1250
|
+
*
|
|
1251
|
+
* Line number cells live inside the @pierre/diffs shadow root, so light-DOM
|
|
1252
|
+
* queries for `.line-num2`/`tr` return nothing. This reaches into the shadow
|
|
1253
|
+
* DOM, resolves the line by index (via the instance's `getLineIndex`), scrolls
|
|
1254
|
+
* it into view, and applies a brief highlight flash.
|
|
1255
|
+
*
|
|
1256
|
+
* @param {string} fileName
|
|
1257
|
+
* @param {number} lineNumber
|
|
1258
|
+
* @param {string} [side] - 'LEFT' or 'RIGHT' (defaults to 'RIGHT')
|
|
1259
|
+
* @returns {boolean} true if the line was found and scrolled to
|
|
1260
|
+
*/
|
|
1261
|
+
scrollToLine(fileName, lineNumber, side = 'RIGHT', shouldScroll = true) {
|
|
1262
|
+
const fileState = this.files.get(fileName);
|
|
1263
|
+
if (!fileState || !fileState.instance) return false;
|
|
1264
|
+
const instance = fileState.instance;
|
|
1265
|
+
|
|
1266
|
+
const pierreSide = PierreBridge.toPierreSide(side);
|
|
1267
|
+
const indices = typeof instance.getLineIndex === 'function'
|
|
1268
|
+
? instance.getLineIndex(lineNumber, pierreSide)
|
|
1269
|
+
: undefined;
|
|
1270
|
+
const lineEl = PierreBridge._queryLineElement(instance, indices, pierreSide);
|
|
1271
|
+
if (!lineEl) return false;
|
|
1272
|
+
|
|
1273
|
+
// Use scrollIntoView on the shadow DOM element — it still scrolls the
|
|
1274
|
+
// host document relative to the viewport.
|
|
1275
|
+
if (shouldScroll) {
|
|
1276
|
+
const rect = lineEl.getBoundingClientRect();
|
|
1277
|
+
const isVisible = rect.top >= 0 && rect.bottom <= window.innerHeight;
|
|
1278
|
+
if (!isVisible) {
|
|
1279
|
+
lineEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// Brief highlight flash so the user can locate the target line.
|
|
1284
|
+
// The class is styled by ANNOTATION_CSS (injected into shadow DOM).
|
|
1285
|
+
lineEl.classList.remove('pierre-line-highlight');
|
|
1286
|
+
void lineEl.offsetWidth; // force reflow to restart animation
|
|
1287
|
+
lineEl.classList.add('pierre-line-highlight');
|
|
1288
|
+
lineEl.addEventListener('animationend', () => {
|
|
1289
|
+
lineEl.classList.remove('pierre-line-highlight');
|
|
1290
|
+
}, { once: true });
|
|
1291
|
+
|
|
1292
|
+
return true;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
_createGutterButtons(fileName, getHoveredRow) {
|
|
1296
|
+
this._gutterRowGetters.set(fileName, getHoveredRow);
|
|
1297
|
+
// Reuse existing container if already created for this file
|
|
1298
|
+
if (this._gutterContainers.has(fileName)) return this._gutterContainers.get(fileName);
|
|
1299
|
+
|
|
1300
|
+
const container = document.createElement('div');
|
|
1301
|
+
container.className = 'pierre-gutter-buttons';
|
|
1302
|
+
// Mark as utility so @pierre/diffs recognizes it in pointer path checks
|
|
1303
|
+
container.setAttribute('data-utility-button', '');
|
|
1304
|
+
|
|
1305
|
+
/**
|
|
1306
|
+
* Resolve the target for a gutter button click.
|
|
1307
|
+
*
|
|
1308
|
+
* Rules:
|
|
1309
|
+
* - If a multi-line range is active AND the button is currently over a
|
|
1310
|
+
* line inside that range (same side), apply the action to the range
|
|
1311
|
+
* and clear the selection.
|
|
1312
|
+
* - If a multi-line range is active but the button has moved to a line
|
|
1313
|
+
* OUTSIDE the range, cancel the range and apply the action to the
|
|
1314
|
+
* single hovered line.
|
|
1315
|
+
* - Otherwise, apply the action to the single hovered line.
|
|
1316
|
+
*/
|
|
1317
|
+
const resolveClickTarget = () => {
|
|
1318
|
+
const hovered = this._getHoveredRow(fileName);
|
|
1319
|
+
const hoveredSide = hovered
|
|
1320
|
+
? (hovered.side === 'deletions' ? 'LEFT' : 'RIGHT')
|
|
1321
|
+
: null;
|
|
1322
|
+
const sel = this.getLineSelection(fileName);
|
|
1323
|
+
|
|
1324
|
+
if (sel && sel.start !== sel.end) {
|
|
1325
|
+
const inRange = hovered
|
|
1326
|
+
&& hoveredSide === sel.side
|
|
1327
|
+
&& hovered.lineNumber >= sel.start
|
|
1328
|
+
&& hovered.lineNumber <= sel.end;
|
|
1329
|
+
// Either we consume the range or we cancel it — in both cases clear.
|
|
1330
|
+
this.clearLineSelection(fileName);
|
|
1331
|
+
if (inRange) {
|
|
1332
|
+
return { start: sel.start, end: sel.end, side: sel.side, isRange: true };
|
|
1333
|
+
}
|
|
1334
|
+
// Fall through to single-line resolution on the hovered line.
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
if (!hovered) return null;
|
|
1338
|
+
return {
|
|
1339
|
+
start: hovered.lineNumber,
|
|
1340
|
+
end: hovered.lineNumber,
|
|
1341
|
+
side: hoveredSide,
|
|
1342
|
+
isRange: false,
|
|
1343
|
+
};
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
// Wire a gutter button so that:
|
|
1347
|
+
// - A plain click triggers the action for the hovered line (or active
|
|
1348
|
+
// multi-line selection).
|
|
1349
|
+
// - Press-and-drag creates a multi-line selection (same UX as dragging
|
|
1350
|
+
// from a line number) WITHOUT triggering the action on release.
|
|
1351
|
+
//
|
|
1352
|
+
// Why this is needed:
|
|
1353
|
+
// @pierre/diffs cannot start line selection from button clicks — its
|
|
1354
|
+
// resolvePointerTarget fails because `data-code` is missing from the
|
|
1355
|
+
// composed path through the shadow DOM slot. So we implement the drag
|
|
1356
|
+
// ourselves, calling setSelectedLines to set the selection in the
|
|
1357
|
+
// library. We also stopPropagation on pointerdown to prevent the
|
|
1358
|
+
// library from interfering, and track whether a drag occurred to
|
|
1359
|
+
// suppress the spurious click that fires when the button DOM element
|
|
1360
|
+
// follows the hover and ends up under the cursor at the release point.
|
|
1361
|
+
const wrapButton = (btn, handler) => {
|
|
1362
|
+
let dragInfo = null;
|
|
1363
|
+
|
|
1364
|
+
btn.addEventListener('pointerdown', (e) => {
|
|
1365
|
+
e.stopPropagation(); // library can't handle buttons; avoid interference
|
|
1366
|
+
const hovered = this._getHoveredRow(fileName);
|
|
1367
|
+
if (!hovered) return;
|
|
1368
|
+
dragInfo = {
|
|
1369
|
+
startLine: hovered.lineNumber,
|
|
1370
|
+
side: hovered.side, // 'additions' | 'deletions'
|
|
1371
|
+
pointerId: e.pointerId,
|
|
1372
|
+
dragged: false,
|
|
1373
|
+
};
|
|
1374
|
+
|
|
1375
|
+
const onMove = (me) => {
|
|
1376
|
+
if (!dragInfo || me.pointerId !== dragInfo.pointerId) return;
|
|
1377
|
+
const cur = this._getHoveredRow(fileName);
|
|
1378
|
+
if (!cur || cur.lineNumber === dragInfo.startLine) return;
|
|
1379
|
+
dragInfo.dragged = true;
|
|
1380
|
+
const fileState = this.files.get(fileName);
|
|
1381
|
+
if (fileState?.instance) {
|
|
1382
|
+
const start = Math.min(dragInfo.startLine, cur.lineNumber);
|
|
1383
|
+
const end = Math.max(dragInfo.startLine, cur.lineNumber);
|
|
1384
|
+
fileState.instance.setSelectedLines({
|
|
1385
|
+
start, end, side: dragInfo.side,
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
|
|
1390
|
+
const onUp = (ue) => {
|
|
1391
|
+
if (!dragInfo || ue.pointerId !== dragInfo.pointerId) return;
|
|
1392
|
+
document.removeEventListener('pointermove', onMove);
|
|
1393
|
+
document.removeEventListener('pointerup', onUp);
|
|
1394
|
+
document.removeEventListener('pointercancel', onUp);
|
|
1395
|
+
// dragInfo.dragged is consumed by onclick below
|
|
1396
|
+
};
|
|
1397
|
+
|
|
1398
|
+
document.addEventListener('pointermove', onMove);
|
|
1399
|
+
document.addEventListener('pointerup', onUp);
|
|
1400
|
+
// Touch/pen pointers can be canceled by the OS (edge gestures, palm
|
|
1401
|
+
// rejection) in which case no pointerup fires. Clean up on cancel
|
|
1402
|
+
// too so the document-level listeners don't leak.
|
|
1403
|
+
document.addEventListener('pointercancel', onUp);
|
|
1404
|
+
});
|
|
1405
|
+
|
|
1406
|
+
btn.onclick = (e) => {
|
|
1407
|
+
e.preventDefault();
|
|
1408
|
+
e.stopPropagation();
|
|
1409
|
+
if (!dragInfo) return; // no pointerdown on this button (e.g. line-number drag landed here)
|
|
1410
|
+
if (dragInfo.dragged) { // suppress click that ends a button-initiated drag
|
|
1411
|
+
dragInfo = null;
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
dragInfo = null;
|
|
1415
|
+
const target = resolveClickTarget();
|
|
1416
|
+
if (!target) return;
|
|
1417
|
+
handler(target);
|
|
1418
|
+
};
|
|
1419
|
+
};
|
|
1420
|
+
|
|
1421
|
+
// Chat button (left)
|
|
1422
|
+
if (this.options.onChatClick) {
|
|
1423
|
+
const chatBtn = document.createElement('button');
|
|
1424
|
+
chatBtn.className = 'pierre-gutter-btn pierre-chat-btn';
|
|
1425
|
+
chatBtn.title = 'Chat about this line';
|
|
1426
|
+
chatBtn.innerHTML = PierreBridge.CHAT_SVG;
|
|
1427
|
+
wrapButton(chatBtn, (target) => {
|
|
1428
|
+
this.options.onChatClick(fileName, target.start, target.side, target);
|
|
1429
|
+
});
|
|
1430
|
+
container.appendChild(chatBtn);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
// Comment button (right)
|
|
1434
|
+
const commentBtn = document.createElement('button');
|
|
1435
|
+
commentBtn.className = 'pierre-gutter-btn pierre-comment-btn';
|
|
1436
|
+
commentBtn.title = 'Add comment';
|
|
1437
|
+
commentBtn.textContent = '+';
|
|
1438
|
+
wrapButton(commentBtn, (target) => {
|
|
1439
|
+
if (this.options.onCommentClick) {
|
|
1440
|
+
this.options.onCommentClick(fileName, target.start, target.side, target);
|
|
1441
|
+
}
|
|
1442
|
+
});
|
|
1443
|
+
container.appendChild(commentBtn);
|
|
1444
|
+
|
|
1445
|
+
// Cache so we return the same element on rerender
|
|
1446
|
+
this._gutterContainers.set(fileName, container);
|
|
1447
|
+
|
|
1448
|
+
return container;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// ─── Annotations (Comments, Suggestions, Forms) ───────────────────
|
|
1452
|
+
|
|
1453
|
+
/**
|
|
1454
|
+
* Add an annotation for a comment, suggestion, or form.
|
|
1455
|
+
* @param {string} fileName
|
|
1456
|
+
* @param {Object} annotation - { lineNumber, side, type, data }
|
|
1457
|
+
* side: 'LEFT'/'RIGHT' or 'additions'/'deletions'
|
|
1458
|
+
* type: 'comment' | 'suggestion' | 'comment-form'
|
|
1459
|
+
* data: type-specific data (comment object, suggestion object, form config)
|
|
1460
|
+
*/
|
|
1461
|
+
addAnnotation(fileName, annotation) {
|
|
1462
|
+
const fileState = this.files.get(fileName);
|
|
1463
|
+
if (!fileState) return;
|
|
1464
|
+
|
|
1465
|
+
this._pushAnnotation(fileState, annotation);
|
|
1466
|
+
this._updateAnnotations(fileName);
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
/**
|
|
1470
|
+
* Add many annotations to a file with a SINGLE rerender + split-layout sync.
|
|
1471
|
+
*
|
|
1472
|
+
* Functionally equivalent to calling addAnnotation() once per item, but the
|
|
1473
|
+
* expensive part — setLineAnnotations + a full instance.rerender() (a shadow
|
|
1474
|
+
* DOM rebuild) + _syncSplitAnnotationLayout — runs once for the whole batch
|
|
1475
|
+
* instead of K times. Loop callers that anchor many comments/suggestions to
|
|
1476
|
+
* one file (see loadUserComments in pr.js and SuggestionManager) should use
|
|
1477
|
+
* this; single-item callers keep using addAnnotation.
|
|
1478
|
+
*
|
|
1479
|
+
* Not-yet-rendered / missing file: mirrors addAnnotation exactly — a no-op
|
|
1480
|
+
* (no fileState → return). The lazy-render path stores nothing here, so no
|
|
1481
|
+
* annotations are lost or duplicated.
|
|
1482
|
+
*
|
|
1483
|
+
* @param {string} fileName
|
|
1484
|
+
* @param {Array<Object>} annotations - each { lineNumber, side, type, data, id? }
|
|
1485
|
+
*/
|
|
1486
|
+
addAnnotations(fileName, annotations) {
|
|
1487
|
+
const fileState = this.files.get(fileName);
|
|
1488
|
+
if (!fileState) return;
|
|
1489
|
+
if (!Array.isArray(annotations) || annotations.length === 0) return;
|
|
1490
|
+
|
|
1491
|
+
for (const annotation of annotations) {
|
|
1492
|
+
this._pushAnnotation(fileState, annotation);
|
|
1493
|
+
}
|
|
1494
|
+
this._updateAnnotations(fileName);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* Push a single annotation onto a file's annotation list WITHOUT triggering a
|
|
1499
|
+
* rerender. Shared by addAnnotation (one item) and addAnnotations (batch) so
|
|
1500
|
+
* the annotation shape / id-generation lives in exactly one place.
|
|
1501
|
+
* @param {Object} fileState
|
|
1502
|
+
* @param {Object} annotation - { lineNumber, side, type, data, id? }
|
|
1503
|
+
* @private
|
|
1504
|
+
*/
|
|
1505
|
+
_pushAnnotation(fileState, annotation) {
|
|
1506
|
+
const pierreSide = PierreBridge.toPierreSide(annotation.side);
|
|
1507
|
+
fileState.annotations.push({
|
|
1508
|
+
side: pierreSide,
|
|
1509
|
+
lineNumber: annotation.lineNumber,
|
|
1510
|
+
metadata: {
|
|
1511
|
+
type: annotation.type,
|
|
1512
|
+
data: annotation.data,
|
|
1513
|
+
id: annotation.id || `${annotation.type}-${annotation.lineNumber}-${pierreSide}-${++this._annotationCounter}`,
|
|
1514
|
+
},
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* Remove an annotation by id.
|
|
1520
|
+
* @param {string} fileName
|
|
1521
|
+
* @param {string} annotationId
|
|
1522
|
+
*/
|
|
1523
|
+
removeAnnotation(fileName, annotationId) {
|
|
1524
|
+
const fileState = this.files.get(fileName);
|
|
1525
|
+
if (!fileState) return;
|
|
1526
|
+
|
|
1527
|
+
fileState.annotations = fileState.annotations.filter(
|
|
1528
|
+
a => a.metadata.id !== annotationId
|
|
1529
|
+
);
|
|
1530
|
+
// Clean up form element if it was a form
|
|
1531
|
+
fileState.formElements.delete(annotationId);
|
|
1532
|
+
|
|
1533
|
+
this._updateAnnotations(fileName);
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
/**
|
|
1537
|
+
* Remove all annotations of a given type for a file.
|
|
1538
|
+
* @param {string} fileName
|
|
1539
|
+
* @param {string} type - 'comment' | 'suggestion' | 'comment-form'
|
|
1540
|
+
*/
|
|
1541
|
+
removeAnnotationsByType(fileName, type) {
|
|
1542
|
+
const fileState = this.files.get(fileName);
|
|
1543
|
+
if (!fileState) return;
|
|
1544
|
+
|
|
1545
|
+
const removed = fileState.annotations.filter(a => a.metadata.type === type);
|
|
1546
|
+
fileState.annotations = fileState.annotations.filter(a => a.metadata.type !== type);
|
|
1547
|
+
|
|
1548
|
+
// Clean up form elements
|
|
1549
|
+
for (const ann of removed) {
|
|
1550
|
+
fileState.formElements.delete(ann.metadata.id);
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
this._updateAnnotations(fileName);
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
/**
|
|
1557
|
+
* Get all annotations for a file, optionally filtered by type.
|
|
1558
|
+
* @param {string} fileName
|
|
1559
|
+
* @param {string} [type]
|
|
1560
|
+
* @returns {Array}
|
|
1561
|
+
*/
|
|
1562
|
+
getAnnotations(fileName, type) {
|
|
1563
|
+
const fileState = this.files.get(fileName);
|
|
1564
|
+
if (!fileState) return [];
|
|
1565
|
+
if (type) {
|
|
1566
|
+
return fileState.annotations.filter(a => a.metadata.type === type);
|
|
1567
|
+
}
|
|
1568
|
+
return [...fileState.annotations];
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/**
|
|
1572
|
+
* Update annotations on the FileDiff instance.
|
|
1573
|
+
* @private
|
|
1574
|
+
*/
|
|
1575
|
+
_updateAnnotations(fileName) {
|
|
1576
|
+
const fileState = this.files.get(fileName);
|
|
1577
|
+
if (!fileState || !fileState.instance) return;
|
|
1578
|
+
// Sort so that at the same line, suggestions appear before comments.
|
|
1579
|
+
// This matches the legacy rendering order where the suggestion row is
|
|
1580
|
+
// inserted first, then the adopted comment row appears below it.
|
|
1581
|
+
// Hunk summaries and tour stops describe the surrounding code, so they
|
|
1582
|
+
// stack above suggestion/comment feedback anchored to the same line.
|
|
1583
|
+
const typeOrder = {
|
|
1584
|
+
'hunk-summary': -2,
|
|
1585
|
+
'tour-stop': -1,
|
|
1586
|
+
'suggestion': 0,
|
|
1587
|
+
'comment-form': 1,
|
|
1588
|
+
'comment': 2,
|
|
1589
|
+
// External (host-synced) threads stack below user comments on the same
|
|
1590
|
+
// line, mirroring the legacy insertion order (AI → user → external).
|
|
1591
|
+
'external-comment': 3,
|
|
1592
|
+
};
|
|
1593
|
+
const sorted = [...fileState.annotations].sort((a, b) => {
|
|
1594
|
+
if (a.lineNumber !== b.lineNumber) return a.lineNumber - b.lineNumber;
|
|
1595
|
+
if (a.side !== b.side) return a.side < b.side ? -1 : 1;
|
|
1596
|
+
return (typeOrder[a.metadata.type] ?? 1) - (typeOrder[b.metadata.type] ?? 1);
|
|
1597
|
+
});
|
|
1598
|
+
fileState.instance.setLineAnnotations(sorted);
|
|
1599
|
+
// setLineAnnotations only stores data — rerender() is needed to
|
|
1600
|
+
// trigger the renderAnnotation callback and slot elements into the
|
|
1601
|
+
// light DOM of the <diffs-container> host.
|
|
1602
|
+
fileState.instance.rerender();
|
|
1603
|
+
this._syncSplitAnnotationLayout(fileName);
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
/**
|
|
1607
|
+
* Split view: stretch annotation cards across both columns.
|
|
1608
|
+
*
|
|
1609
|
+
* The vendor renders each annotation into ONE side's column plus an empty
|
|
1610
|
+
* paired cell in the other column on the same shared grid row (split+wrap
|
|
1611
|
+
* is a single four-track grid with display:contents columns), so a lone
|
|
1612
|
+
* card only gets half the width. This pass:
|
|
1613
|
+
* 1. Measures the middle (additions) gutter track — it is min-content
|
|
1614
|
+
* sized, so pure CSS cannot know its width — and publishes it on the
|
|
1615
|
+
* <pre> as --pr-split-gutter-width for ANNOTATION_CSS calc()s.
|
|
1616
|
+
* 2. Marks cards whose opposite cell is empty with
|
|
1617
|
+
* .pr-annotation-fullwidth. When BOTH sides of a row hold cards
|
|
1618
|
+
* (LEFT + RIGHT annotation on the same row pair), neither is marked
|
|
1619
|
+
* and they stay half-width side by side.
|
|
1620
|
+
*
|
|
1621
|
+
* Entirely added/removed files get the same treatment: the vendor emits a
|
|
1622
|
+
* lone code column stamped data-diff-type="single", which ANNOTATION_CSS
|
|
1623
|
+
* boxes into one half of the split grid. Its own gutter is the measured
|
|
1624
|
+
* track there, and every slotted card is lone by construction, so the same
|
|
1625
|
+
* marking pass stretches them across both halves.
|
|
1626
|
+
*
|
|
1627
|
+
* Vendor renders wipe shadow-DOM classes/inline vars, so this is invoked
|
|
1628
|
+
* (rAF-debounced per file) after every pass that can rebuild the shadow
|
|
1629
|
+
* DOM: initial render (onPostRender), annotation updates, diffStyle
|
|
1630
|
+
* switches, and hunk expansion. In unified mode it no-ops (every pre is
|
|
1631
|
+
* "single" there too — one unified column — so the bridge's own diffStyle
|
|
1632
|
+
* is the gate, not the attribute).
|
|
1633
|
+
* @private
|
|
1634
|
+
*/
|
|
1635
|
+
_syncSplitAnnotationLayout(fileName) {
|
|
1636
|
+
const fileState = this.files.get(fileName);
|
|
1637
|
+
if (!fileState || fileState._splitLayoutRaf != null) return;
|
|
1638
|
+
const raf = typeof requestAnimationFrame === 'function'
|
|
1639
|
+
? requestAnimationFrame
|
|
1640
|
+
: (fn) => setTimeout(fn, 16);
|
|
1641
|
+
fileState._splitLayoutRaf = raf(() => {
|
|
1642
|
+
fileState._splitLayoutRaf = null;
|
|
1643
|
+
this._applySplitAnnotationLayout(fileName);
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/**
|
|
1648
|
+
* Synchronous body of _syncSplitAnnotationLayout — see its doc comment.
|
|
1649
|
+
* @private
|
|
1650
|
+
*/
|
|
1651
|
+
_applySplitAnnotationLayout(fileName) {
|
|
1652
|
+
if (this.diffStyle !== 'split') return;
|
|
1653
|
+
const fileState = this.files.get(fileName);
|
|
1654
|
+
const shadowRoot = fileState?.shadowHost?.shadowRoot;
|
|
1655
|
+
if (!shadowRoot) return;
|
|
1656
|
+
const pre = shadowRoot.querySelector(
|
|
1657
|
+
'pre[data-diff-type="split"], pre[data-diff-type="single"]'
|
|
1658
|
+
);
|
|
1659
|
+
if (!pre) return;
|
|
1660
|
+
|
|
1661
|
+
// Two-sided pre: measure the MIDDLE (additions) gutter track — it sits
|
|
1662
|
+
// against the seam. One-sided pre: only one gutter exists; measure it.
|
|
1663
|
+
const gutter = pre.getAttribute('data-diff-type') === 'split'
|
|
1664
|
+
? pre.querySelector('[data-additions] [data-gutter]')
|
|
1665
|
+
: pre.querySelector('[data-gutter]');
|
|
1666
|
+
const gutterWidth = gutter?.getBoundingClientRect?.().width || 0;
|
|
1667
|
+
if (gutterWidth > 0) {
|
|
1668
|
+
pre.style.setProperty('--pr-split-gutter-width', `${gutterWidth}px`);
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
// Paired cells share the same "hunkIndex,lineIndex" attribute value.
|
|
1672
|
+
const byRow = new Map();
|
|
1673
|
+
for (const cell of pre.querySelectorAll('[data-line-annotation]')) {
|
|
1674
|
+
const key = cell.getAttribute('data-line-annotation');
|
|
1675
|
+
if (!byRow.has(key)) byRow.set(key, []);
|
|
1676
|
+
byRow.get(key).push(cell);
|
|
1677
|
+
}
|
|
1678
|
+
for (const cells of byRow.values()) {
|
|
1679
|
+
const withContent = cells.filter((cell) => cell.querySelector('slot'));
|
|
1680
|
+
for (const cell of cells) {
|
|
1681
|
+
cell.classList.toggle(
|
|
1682
|
+
'pr-annotation-fullwidth',
|
|
1683
|
+
withContent.length === 1 && cell === withContent[0]
|
|
1684
|
+
);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// ─── Gap Expansion ────────────────────────────────────────────────
|
|
1690
|
+
|
|
1691
|
+
/**
|
|
1692
|
+
* Expand a hunk in a file's diff.
|
|
1693
|
+
* @param {string} fileName
|
|
1694
|
+
* @param {number} hunkIndex
|
|
1695
|
+
* @param {string} direction - 'up' | 'down' | 'both'
|
|
1696
|
+
* @param {number} [lineCount] - Override default expansion count
|
|
1697
|
+
*/
|
|
1698
|
+
expandHunk(fileName, hunkIndex, direction, lineCount) {
|
|
1699
|
+
const fileState = this.files.get(fileName);
|
|
1700
|
+
if (!fileState || !fileState.instance) return;
|
|
1701
|
+
fileState.instance.expandHunk(hunkIndex, direction, lineCount);
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/**
|
|
1705
|
+
* Check if a line is visible (not in a collapsed gap) in a file's diff.
|
|
1706
|
+
* @param {string} fileName
|
|
1707
|
+
* @param {number} lineNumber
|
|
1708
|
+
* @param {string} side - 'LEFT'/'RIGHT' or 'additions'/'deletions'
|
|
1709
|
+
* @returns {boolean}
|
|
1710
|
+
*/
|
|
1711
|
+
isLineVisible(fileName, lineNumber, side) {
|
|
1712
|
+
const fileState = this.files.get(fileName);
|
|
1713
|
+
if (!fileState || !fileState.instance) return false;
|
|
1714
|
+
// A collapsed file renders zero code lines regardless of metadata.
|
|
1715
|
+
if (fileState.collapsed) return false;
|
|
1716
|
+
const instance = fileState.instance;
|
|
1717
|
+
const hunks = instance.fileDiff?.hunks;
|
|
1718
|
+
if (!Array.isArray(hunks) || hunks.length === 0) return false;
|
|
1719
|
+
|
|
1720
|
+
// Decide from the instance's CURRENT logical state, never the DOM.
|
|
1721
|
+
// render()/rerender() paint asynchronously (worker highlighting), so the
|
|
1722
|
+
// shadow DOM lags behind the latest render call — a DOM query here returns
|
|
1723
|
+
// stale answers (e.g. a line still on screen right after
|
|
1724
|
+
// clearContextRanges dropped it). instance.fileDiff is assigned
|
|
1725
|
+
// synchronously inside render(), so hunk membership reflects the state the
|
|
1726
|
+
// in-flight paint will converge to. A line is rendered iff it falls inside
|
|
1727
|
+
// a hunk of the current (context-range-merged) metadata, widened by any
|
|
1728
|
+
// user gap expansion tracked per hunk in hunksRenderer.expandedHunks.
|
|
1729
|
+
const sideKey = PierreBridge.toPierreSide(side) === 'deletions' ? 'deletion' : 'addition';
|
|
1730
|
+
for (let i = 0; i < hunks.length; i++) {
|
|
1731
|
+
const hunk = hunks[i];
|
|
1732
|
+
const count = hunk[`${sideKey}Count`];
|
|
1733
|
+
if (!count) continue;
|
|
1734
|
+
const start = hunk[`${sideKey}Start`];
|
|
1735
|
+
const expanded = instance.hunksRenderer?.getExpandedHunk?.(i);
|
|
1736
|
+
const from = start - (expanded?.fromStart || 0);
|
|
1737
|
+
const to = start + count - 1 + (expanded?.fromEnd || 0);
|
|
1738
|
+
if (lineNumber >= from && lineNumber <= to) return true;
|
|
1739
|
+
}
|
|
1740
|
+
return false;
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
/**
|
|
1744
|
+
* Resolve the rendered shadow-DOM element for a line from the indices
|
|
1745
|
+
* returned by instance.getLineIndex(). The vendor stamps data-line-index
|
|
1746
|
+
* as a composite "unifiedIndex,splitIndex" key on content lines in BOTH
|
|
1747
|
+
* unified and split layouts (see @pierre/diffs renderDiffWithHighlighter);
|
|
1748
|
+
* fall back to the bare unified index for bundle versions that stamped a
|
|
1749
|
+
* single number.
|
|
1750
|
+
*
|
|
1751
|
+
* Column scoping avoids matching ghost lines from other files rendered in
|
|
1752
|
+
* the same document, and — in split view — targets the requested side:
|
|
1753
|
+
* - unified: the single `code[data-unified]` column.
|
|
1754
|
+
* - split: `code[data-deletions]` (LEFT) or `code[data-additions]`
|
|
1755
|
+
* (RIGHT). A context line exists in BOTH columns with the SAME composite
|
|
1756
|
+
* key, so we search the requested side first and fall back to the other.
|
|
1757
|
+
* @param {Object} instance - FileDiff instance
|
|
1758
|
+
* @param {Array<number>|undefined} indices - [unifiedIndex, splitIndex]
|
|
1759
|
+
* @param {'deletions'|'additions'} [side] - preferred split column
|
|
1760
|
+
* @returns {Element|null}
|
|
1761
|
+
* @private
|
|
1762
|
+
*/
|
|
1763
|
+
static _queryLineElement(instance, indices, side) {
|
|
1764
|
+
if (!indices) return null;
|
|
1765
|
+
const [unifiedIndex] = indices;
|
|
1766
|
+
if (unifiedIndex == null) return null;
|
|
1767
|
+
const pre = instance.pre;
|
|
1768
|
+
if (!pre) return null;
|
|
1769
|
+
const compositeKey = Array.isArray(indices) ? indices.join(',') : String(unifiedIndex);
|
|
1770
|
+
for (const codeEl of PierreBridge._codeColumnsForSide(instance, pre, side)) {
|
|
1771
|
+
if (!codeEl) continue;
|
|
1772
|
+
const el = codeEl.querySelector(`[data-line][data-line-index="${compositeKey}"]`)
|
|
1773
|
+
|| codeEl.querySelector(`[data-line][data-line-index="${unifiedIndex}"]`);
|
|
1774
|
+
if (el) return el;
|
|
1775
|
+
}
|
|
1776
|
+
return null;
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
/**
|
|
1780
|
+
* Ordered list of code-column elements to search for a line, scoped to a
|
|
1781
|
+
* single FileDiff instance. Unified returns the one unified column; split
|
|
1782
|
+
* returns both columns with the requested `side` first. Falls back to the
|
|
1783
|
+
* whole `pre` when no column element is resolvable.
|
|
1784
|
+
* @param {Object} instance
|
|
1785
|
+
* @param {Element} pre
|
|
1786
|
+
* @param {'deletions'|'additions'} [side]
|
|
1787
|
+
* @returns {Array<Element|null>}
|
|
1788
|
+
* @private
|
|
1789
|
+
*/
|
|
1790
|
+
static _codeColumnsForSide(instance, pre, side) {
|
|
1791
|
+
const unified = instance.codeUnified || pre.querySelector('code[data-unified]');
|
|
1792
|
+
if (unified) return [unified];
|
|
1793
|
+
const deletions = instance.codeDeletions || pre.querySelector('code[data-deletions]');
|
|
1794
|
+
const additions = instance.codeAdditions || pre.querySelector('code[data-additions]');
|
|
1795
|
+
if (deletions || additions) {
|
|
1796
|
+
return side === 'deletions' ? [deletions, additions] : [additions, deletions];
|
|
1797
|
+
}
|
|
1798
|
+
return [pre];
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/**
|
|
1802
|
+
* Expand collapsed gaps so that the given line becomes visible.
|
|
1803
|
+
* Iterates over hunks to find which gap the line falls in, then
|
|
1804
|
+
* expands that hunk upward/downward by enough lines to reveal it.
|
|
1805
|
+
* @param {string} fileName
|
|
1806
|
+
* @param {number} lineNumber
|
|
1807
|
+
* @param {string} side - 'LEFT'/'RIGHT'
|
|
1808
|
+
*/
|
|
1809
|
+
expandToLine(fileName, lineNumber, side = 'RIGHT') {
|
|
1810
|
+
const fileState = this.files.get(fileName);
|
|
1811
|
+
if (!fileState || !fileState.instance) return;
|
|
1812
|
+
const instance = fileState.instance;
|
|
1813
|
+
if (!instance.fileDiff || !instance.fileDiff.hunks) return;
|
|
1814
|
+
|
|
1815
|
+
const hunks = instance.fileDiff.hunks;
|
|
1816
|
+
const sideKey = PierreBridge.toPierreSide(side) === 'deletions' ? 'deletion' : 'addition';
|
|
1817
|
+
|
|
1818
|
+
for (let i = 0; i < hunks.length; i++) {
|
|
1819
|
+
const hunk = hunks[i];
|
|
1820
|
+
const hunkStart = hunk[`${sideKey}Start`];
|
|
1821
|
+
const hunkEnd = hunkStart + hunk[`${sideKey}Count`] - 1;
|
|
1822
|
+
|
|
1823
|
+
// Target line is before this hunk — it's in the collapsed gap above
|
|
1824
|
+
if (lineNumber < hunkStart) {
|
|
1825
|
+
instance.expandHunk(i, 'up', hunk.collapsedBefore);
|
|
1826
|
+
instance.rerender();
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
// Target line is within this hunk — already visible (or should be)
|
|
1831
|
+
if (lineNumber <= hunkEnd) {
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
// If this is the last hunk and the line is after it — expand down
|
|
1836
|
+
if (i === hunks.length - 1 && lineNumber > hunkEnd) {
|
|
1837
|
+
instance.expandHunk(i, 'down', lineNumber - hunkEnd);
|
|
1838
|
+
instance.rerender();
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
// ─── Shadow DOM Access ────────────────────────────────────────────
|
|
1845
|
+
|
|
1846
|
+
/**
|
|
1847
|
+
* Get the shadow root of a file's diff, if accessible.
|
|
1848
|
+
* @param {string} fileName
|
|
1849
|
+
* @returns {ShadowRoot|null}
|
|
1850
|
+
*/
|
|
1851
|
+
getShadowRoot(fileName) {
|
|
1852
|
+
const fileState = this.files.get(fileName);
|
|
1853
|
+
if (!fileState || !fileState.shadowHost) return null;
|
|
1854
|
+
return fileState.shadowHost.shadowRoot || null;
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
/**
|
|
1858
|
+
* Get the FileDiff instance for a file.
|
|
1859
|
+
* @param {string} fileName
|
|
1860
|
+
* @returns {FileDiff|null}
|
|
1861
|
+
*/
|
|
1862
|
+
getInstance(fileName) {
|
|
1863
|
+
const fileState = this.files.get(fileName);
|
|
1864
|
+
return fileState ? fileState.instance : null;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
/**
|
|
1868
|
+
* Get the currently hovered line info for a file.
|
|
1869
|
+
* @param {string} fileName
|
|
1870
|
+
* @returns {Object|undefined} { lineNumber, side }
|
|
1871
|
+
*/
|
|
1872
|
+
getHoveredLine(fileName) {
|
|
1873
|
+
const fileState = this.files.get(fileName);
|
|
1874
|
+
if (!fileState || !fileState.instance) return undefined;
|
|
1875
|
+
return fileState.instance.getHoveredLine();
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
// ─── Internal Rendering Callbacks ─────────────────────────────────
|
|
1879
|
+
|
|
1880
|
+
/**
|
|
1881
|
+
* Render an annotation element (comment, suggestion, or form).
|
|
1882
|
+
* Reuses form DOM elements to preserve user input.
|
|
1883
|
+
* @private
|
|
1884
|
+
*/
|
|
1885
|
+
_renderAnnotation(annotation, fileName, formElements) {
|
|
1886
|
+
const { type, data, id } = annotation.metadata;
|
|
1887
|
+
|
|
1888
|
+
switch (type) {
|
|
1889
|
+
case 'comment':
|
|
1890
|
+
return this._renderCommentAnnotation(data, id);
|
|
1891
|
+
case 'suggestion':
|
|
1892
|
+
return this._renderSuggestionAnnotation(data, id);
|
|
1893
|
+
case 'comment-form':
|
|
1894
|
+
return this._renderFormAnnotation(data, id, formElements, fileName);
|
|
1895
|
+
default: {
|
|
1896
|
+
// Custom annotation types (e.g. 'tour-stop', 'hunk-summary') are
|
|
1897
|
+
// rendered by externally registered renderers so feature modules can
|
|
1898
|
+
// plug in without modifying the bridge.
|
|
1899
|
+
const customRenderer = this._annotationRenderers?.get(type);
|
|
1900
|
+
if (customRenderer) {
|
|
1901
|
+
try {
|
|
1902
|
+
return customRenderer(data, id, fileName) || undefined;
|
|
1903
|
+
} catch (err) {
|
|
1904
|
+
console.error(`[PierreBridge] custom annotation renderer for "${type}" failed:`, err);
|
|
1905
|
+
return undefined;
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
return undefined;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
/**
|
|
1914
|
+
* Register a renderer for a custom annotation type. The callback receives
|
|
1915
|
+
* (data, id, fileName) and must return a DOM element (or null to skip).
|
|
1916
|
+
* Elements are slotted into the light DOM below their anchor line, so page
|
|
1917
|
+
* CSS and inline event handlers work as they do for comments/suggestions.
|
|
1918
|
+
* @param {string} type - Annotation type (e.g. 'tour-stop', 'hunk-summary')
|
|
1919
|
+
* @param {Function} renderFn - (data, id, fileName) => Element|null
|
|
1920
|
+
*/
|
|
1921
|
+
registerAnnotationRenderer(type, renderFn) {
|
|
1922
|
+
if (!this._annotationRenderers) this._annotationRenderers = new Map();
|
|
1923
|
+
this._annotationRenderers.set(type, renderFn);
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
/**
|
|
1927
|
+
* Remove a previously registered custom annotation renderer.
|
|
1928
|
+
* @param {string} type
|
|
1929
|
+
*/
|
|
1930
|
+
unregisterAnnotationRenderer(type) {
|
|
1931
|
+
this._annotationRenderers?.delete(type);
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
/**
|
|
1935
|
+
* Render a user comment annotation using the legacy comment UI.
|
|
1936
|
+
* Produces DOM matching CommentManager.displayUserComment() so all existing
|
|
1937
|
+
* CSS and event handling applies. Elements live in the light DOM (slotted).
|
|
1938
|
+
* @private
|
|
1939
|
+
*/
|
|
1940
|
+
_renderCommentAnnotation(comment, id) {
|
|
1941
|
+
const escapeHtml = window.prManager?.escapeHtml?.bind(window.prManager) || ((s) => s);
|
|
1942
|
+
|
|
1943
|
+
const lineInfo = comment.line_end && comment.line_end !== comment.line_start
|
|
1944
|
+
? `Lines ${comment.line_start}-${comment.line_end}`
|
|
1945
|
+
: `Line ${comment.line_start}`;
|
|
1946
|
+
|
|
1947
|
+
// Build metadata display for adopted comments (praise badge + title)
|
|
1948
|
+
let metadataHTML = '';
|
|
1949
|
+
if (comment.parent_id && comment.type && comment.type !== 'comment') {
|
|
1950
|
+
const badgeHTML = comment.type === 'praise'
|
|
1951
|
+
? `<span class="adopted-praise-badge" title="Nice Work"><svg viewBox="0 0 16 16" width="12" height="12"><path d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25z"/></svg>Nice Work</span>`
|
|
1952
|
+
: '';
|
|
1953
|
+
metadataHTML = `
|
|
1954
|
+
${badgeHTML}
|
|
1955
|
+
${comment.title ? `<span class="adopted-title">${escapeHtml(comment.title)}</span>` : ''}
|
|
1956
|
+
`;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
// Icon based on origin (AI-adopted vs user-originated)
|
|
1960
|
+
const commentIcon = comment.parent_id
|
|
1961
|
+
? `<svg class="octicon octicon-comment-ai" viewBox="0 0 16 16" width="16" height="16">
|
|
1962
|
+
<path d="M7.75 1a.75.75 0 0 1 0 1.5h-5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2c.199 0 .39.079.53.22.141.14.22.331.22.53v2.19l2.72-2.72a.747.747 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-2a.75.75 0 0 1 1.5 0v2c0 .464-.184.909-.513 1.237A1.746 1.746 0 0 1 13.25 12H9.06l-2.573 2.573A1.457 1.457 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25v-7.5C1 1.784 1.784 1 2.75 1h5Zm4.519-.837a.248.248 0 0 1 .466 0l.238.648a3.726 3.726 0 0 0 2.218 2.219l.649.238a.249.249 0 0 1 0 .467l-.649.238a3.725 3.725 0 0 0-2.218 2.218l-.238.649a.248.248 0 0 1-.466 0l-.239-.649a3.725 3.725 0 0 0-2.218-2.218l-.649-.238a.249.249 0 0 1 0-.467l.649-.238A3.726 3.726 0 0 0 12.03.811l.239-.648Z"/>
|
|
1963
|
+
</svg>`
|
|
1964
|
+
: `<svg class="octicon octicon-person" viewBox="0 0 16 16" width="16" height="16">
|
|
1965
|
+
<path d="M10.561 8.073a6.005 6.005 0 0 1 3.432 5.142.75.75 0 1 1-1.498.07 4.5 4.5 0 0 0-8.99 0 .75.75 0 0 1-1.498-.07 6.004 6.004 0 0 1 3.431-5.142 3.999 3.999 0 1 1 5.123 0ZM10.5 5a2.5 2.5 0 1 0-5 0 2.5 2.5 0 0 0 5 0Z"/>
|
|
1966
|
+
</svg>`;
|
|
1967
|
+
|
|
1968
|
+
const baseClasses = ['user-comment'];
|
|
1969
|
+
if (comment.parent_id) {
|
|
1970
|
+
baseClasses.push('adopted-comment', 'comment-ai-origin');
|
|
1971
|
+
} else {
|
|
1972
|
+
baseClasses.push('comment-user-origin');
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
const container = document.createElement('div');
|
|
1976
|
+
container.className = 'user-comment-row';
|
|
1977
|
+
container.dataset.commentId = comment.id;
|
|
1978
|
+
container.dataset.file = comment.file;
|
|
1979
|
+
container.dataset.lineStart = comment.line_start;
|
|
1980
|
+
container.dataset.lineEnd = comment.line_end || comment.line_start;
|
|
1981
|
+
if (comment.side) container.dataset.side = comment.side;
|
|
1982
|
+
|
|
1983
|
+
container.innerHTML = `
|
|
1984
|
+
<div class="${baseClasses.join(' ')}">
|
|
1985
|
+
<div class="user-comment-header">
|
|
1986
|
+
<div class="user-comment-header-left">
|
|
1987
|
+
<span class="comment-origin-icon">${commentIcon}</span>
|
|
1988
|
+
<span class="user-comment-line-info">${lineInfo}</span>
|
|
1989
|
+
${metadataHTML}
|
|
1990
|
+
</div>
|
|
1991
|
+
<div class="user-comment-actions">
|
|
1992
|
+
<button class="btn-chat-comment" title="Chat about comment"
|
|
1993
|
+
data-chat-comment-id="${comment.id}"
|
|
1994
|
+
data-chat-file="${escapeHtml(comment.file || '')}"
|
|
1995
|
+
data-chat-line-start="${comment.line_start ?? ''}"
|
|
1996
|
+
data-chat-line-end="${comment.line_end || comment.line_start || ''}"
|
|
1997
|
+
data-chat-parent-id="${comment.parent_id || ''}">
|
|
1998
|
+
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"/></svg>
|
|
1999
|
+
</button>
|
|
2000
|
+
<button class="btn-edit-comment" onclick="prManager.editUserComment(${comment.id})" title="Edit comment">
|
|
2001
|
+
<svg class="octicon" viewBox="0 0 16 16" width="16" height="16">
|
|
2002
|
+
<path fill-rule="evenodd" d="M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25a1.75 1.75 0 01.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 000-.354l-1.086-1.086zM11.189 6.25L9.75 4.81l-6.286 6.287a.25.25 0 00-.064.108l-.558 1.953 1.953-.558a.249.249 0 00.108-.064l6.286-6.286z"></path>
|
|
2003
|
+
</svg>
|
|
2004
|
+
</button>
|
|
2005
|
+
<button class="btn-delete-comment" onclick="prManager.deleteUserComment(${comment.id})" title="Dismiss comment">
|
|
2006
|
+
<svg class="octicon" viewBox="0 0 16 16" width="16" height="16">
|
|
2007
|
+
<path fill-rule="evenodd" d="M6.5 1.75a.25.25 0 01.25-.25h2.5a.25.25 0 01.25.25V3h-3V1.75zm4.5 0V3h2.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75zM4.496 6.675a.75.75 0 10-1.492.15l.66 6.6A1.75 1.75 0 005.405 15h5.19c.9 0 1.652-.681 1.741-1.576l.66-6.6a.75.75 0 00-1.492-.149l-.66 6.6a.25.25 0 01-.249.225h-5.19a.25.25 0 01-.249-.225l-.66-6.6z"></path>
|
|
2008
|
+
</svg>
|
|
2009
|
+
</button>
|
|
2010
|
+
</div>
|
|
2011
|
+
</div>
|
|
2012
|
+
<div class="user-comment-body" data-original-markdown="${window.escapeHtmlAttribute ? window.escapeHtmlAttribute(comment.body) : ''}">${window.renderMarkdown ? window.renderMarkdown(comment.body || '') : escapeHtml(comment.body || '')}</div>
|
|
2013
|
+
</div>
|
|
2014
|
+
`;
|
|
2015
|
+
|
|
2016
|
+
return container;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/**
|
|
2020
|
+
* Render an AI suggestion annotation using the legacy suggestion UI.
|
|
2021
|
+
* Delegates to SuggestionManager.createSuggestionRow() for zero duplication,
|
|
2022
|
+
* then extracts the inner .ai-suggestion div. The element lives in the light
|
|
2023
|
+
* DOM (slotted) so all existing CSS and document.querySelector() navigation
|
|
2024
|
+
* works unchanged.
|
|
2025
|
+
* @private
|
|
2026
|
+
*/
|
|
2027
|
+
_renderSuggestionAnnotation(suggestion, id) {
|
|
2028
|
+
const suggestionManager = window.prManager?.suggestionManager;
|
|
2029
|
+
if (suggestionManager) {
|
|
2030
|
+
const targetInfo = {
|
|
2031
|
+
fileName: suggestion.file || '',
|
|
2032
|
+
lineNumber: suggestion.line_start || suggestion.line_end || '',
|
|
2033
|
+
side: suggestion.side || 'RIGHT',
|
|
2034
|
+
diffPosition: suggestion.diff_position || '',
|
|
2035
|
+
isFileLevel: !suggestion.line_start && !suggestion.line_end,
|
|
2036
|
+
};
|
|
2037
|
+
|
|
2038
|
+
const row = suggestionManager.createSuggestionRow([suggestion], targetInfo);
|
|
2039
|
+
const suggestionDiv = row.querySelector('.ai-suggestion');
|
|
2040
|
+
if (suggestionDiv) {
|
|
2041
|
+
return suggestionDiv;
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
// Fallback: minimal rendering if SuggestionManager unavailable
|
|
2046
|
+
return this._renderSuggestionFallback(suggestion, id);
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
/**
|
|
2050
|
+
* Fallback suggestion rendering when SuggestionManager is unavailable.
|
|
2051
|
+
* @private
|
|
2052
|
+
*/
|
|
2053
|
+
_renderSuggestionFallback(suggestion, id) {
|
|
2054
|
+
const container = document.createElement('div');
|
|
2055
|
+
container.className = `ai-suggestion ai-type-${suggestion.type || 'info'}`;
|
|
2056
|
+
container.dataset.suggestionId = suggestion.id || '';
|
|
2057
|
+
|
|
2058
|
+
const escapeHtml = window.prManager?.escapeHtml?.bind(window.prManager) || ((s) => s);
|
|
2059
|
+
const displayBody = suggestion.formattedBody || suggestion.body || '';
|
|
2060
|
+
const bodyHTML = window.renderMarkdown ? window.renderMarkdown(displayBody) : escapeHtml(displayBody);
|
|
2061
|
+
|
|
2062
|
+
container.innerHTML = `
|
|
2063
|
+
<div class="ai-suggestion-header">
|
|
2064
|
+
<div class="ai-suggestion-header-left">
|
|
2065
|
+
<span class="ai-suggestion-category">${escapeHtml(suggestion.type || '')}</span>
|
|
2066
|
+
<span class="ai-title">${escapeHtml(suggestion.title || '')}</span>
|
|
2067
|
+
</div>
|
|
2068
|
+
</div>
|
|
2069
|
+
<div class="ai-suggestion-body">${bodyHTML}</div>
|
|
2070
|
+
<div class="ai-suggestion-actions">
|
|
2071
|
+
<button class="ai-action ai-action-adopt" onclick="prManager.adoptSuggestion(${suggestion.id})">Adopt</button>
|
|
2072
|
+
<button class="ai-action ai-action-dismiss" onclick="prManager.dismissSuggestion(${suggestion.id})">Dismiss</button>
|
|
2073
|
+
</div>
|
|
2074
|
+
`;
|
|
2075
|
+
return container;
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
/**
|
|
2079
|
+
* Suggestion toolbar icon SVG (GitHub Primer file-diff-16 octicon).
|
|
2080
|
+
* Matches CommentManager.SUGGESTION_ICON_SVG.
|
|
2081
|
+
* @private
|
|
2082
|
+
*/
|
|
2083
|
+
static SUGGESTION_ICON_SVG = `<svg class="octicon" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M1 1.75C1 .784 1.784 0 2.75 0h7.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16H2.75A1.75 1.75 0 0 1 1 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V4.664a.25.25 0 0 0-.073-.177l-2.914-2.914a.25.25 0 0 0-.177-.073ZM8 3.25a.75.75 0 0 1 .75.75v1.5h1.5a.75.75 0 0 1 0 1.5h-1.5v1.5a.75.75 0 0 1-1.5 0V7h-1.5a.75.75 0 0 1 0-1.5h1.5V4A.75.75 0 0 1 8 3.25Zm-3 8a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75Z"></path></svg>`;
|
|
2084
|
+
|
|
2085
|
+
/**
|
|
2086
|
+
* Chat icon SVG for comment form (matches legacy CommentManager).
|
|
2087
|
+
* @private
|
|
2088
|
+
*/
|
|
2089
|
+
static CHAT_FORM_SVG = `<svg viewBox="0 0 16 16" fill="currentColor" width="16" height="16"><path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"/></svg>`;
|
|
2090
|
+
|
|
2091
|
+
/**
|
|
2092
|
+
* Render a comment form annotation.
|
|
2093
|
+
* Reuses existing form DOM if available to preserve user input.
|
|
2094
|
+
* Elements live in the light DOM (slotted) and use legacy comment form
|
|
2095
|
+
* classes so page CSS applies.
|
|
2096
|
+
* @private
|
|
2097
|
+
*/
|
|
2098
|
+
_renderFormAnnotation(data, id, formElements, fileName) {
|
|
2099
|
+
// Reuse existing form element to preserve textarea content
|
|
2100
|
+
if (formElements.has(id)) {
|
|
2101
|
+
return formElements.get(id);
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
const container = document.createElement('div');
|
|
2105
|
+
container.className = 'pierre-annotation user-comment-form';
|
|
2106
|
+
container.dataset.annotationId = id;
|
|
2107
|
+
|
|
2108
|
+
// Header — matches legacy comment form
|
|
2109
|
+
const header = document.createElement('div');
|
|
2110
|
+
header.className = 'comment-form-header';
|
|
2111
|
+
const icon = document.createElement('span');
|
|
2112
|
+
icon.className = 'comment-icon';
|
|
2113
|
+
icon.textContent = '\uD83D\uDCAC'; // 💬
|
|
2114
|
+
header.appendChild(icon);
|
|
2115
|
+
const title = document.createElement('span');
|
|
2116
|
+
title.className = 'comment-title';
|
|
2117
|
+
title.textContent = data.headerTitle || 'Add comment';
|
|
2118
|
+
header.appendChild(title);
|
|
2119
|
+
if (data.lineStart && data.lineEnd && data.lineEnd !== data.lineStart) {
|
|
2120
|
+
const rangeLabel = document.createElement('span');
|
|
2121
|
+
rangeLabel.className = 'line-range-indicator';
|
|
2122
|
+
rangeLabel.textContent = `Lines ${data.lineStart}-${data.lineEnd}`;
|
|
2123
|
+
header.appendChild(rangeLabel);
|
|
2124
|
+
}
|
|
2125
|
+
container.appendChild(header);
|
|
2126
|
+
|
|
2127
|
+
// Suggestion toolbar — suggestionBtn is declared in the outer scope so
|
|
2128
|
+
// the textarea input listener below can re-evaluate its disabled state.
|
|
2129
|
+
let suggestionBtn = null;
|
|
2130
|
+
if (data.showSuggestionBtn) {
|
|
2131
|
+
const toolbar = document.createElement('div');
|
|
2132
|
+
toolbar.className = 'comment-form-toolbar';
|
|
2133
|
+
suggestionBtn = document.createElement('button');
|
|
2134
|
+
suggestionBtn.type = 'button';
|
|
2135
|
+
suggestionBtn.className = 'btn btn-sm suggestion-btn';
|
|
2136
|
+
suggestionBtn.title = 'Insert a suggestion';
|
|
2137
|
+
suggestionBtn.innerHTML = PierreBridge.SUGGESTION_ICON_SVG;
|
|
2138
|
+
suggestionBtn.addEventListener('click', () => {
|
|
2139
|
+
if (!suggestionBtn.disabled && this.options.onSuggestionInsert) {
|
|
2140
|
+
this.options.onSuggestionInsert(textarea, suggestionBtn);
|
|
2141
|
+
}
|
|
2142
|
+
});
|
|
2143
|
+
toolbar.appendChild(suggestionBtn);
|
|
2144
|
+
container.appendChild(toolbar);
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
// Textarea
|
|
2148
|
+
const textarea = document.createElement('textarea');
|
|
2149
|
+
textarea.className = 'comment-textarea';
|
|
2150
|
+
textarea.placeholder = 'Leave a comment... (Cmd/Ctrl+Enter to save)';
|
|
2151
|
+
textarea.dataset.line = data.lineStart || '';
|
|
2152
|
+
textarea.dataset.lineEnd = data.lineEnd || data.lineStart || '';
|
|
2153
|
+
textarea.dataset.file = fileName;
|
|
2154
|
+
textarea.dataset.diffPosition = data.diffPosition || '';
|
|
2155
|
+
textarea.dataset.side = data.side || 'RIGHT';
|
|
2156
|
+
if (data.initialValue) {
|
|
2157
|
+
textarea.value = data.initialValue;
|
|
2158
|
+
}
|
|
2159
|
+
container.appendChild(textarea);
|
|
2160
|
+
|
|
2161
|
+
// Actions — order matches legacy: Save, Chat, Cancel
|
|
2162
|
+
const actions = document.createElement('div');
|
|
2163
|
+
actions.className = 'comment-form-actions';
|
|
2164
|
+
|
|
2165
|
+
const saveBtn = document.createElement('button');
|
|
2166
|
+
saveBtn.className = 'btn btn-sm btn-primary save-comment-btn';
|
|
2167
|
+
saveBtn.textContent = 'Save';
|
|
2168
|
+
// Sync disabled state with initial textarea content — when `initialValue`
|
|
2169
|
+
// is set programmatically above, the `input` event does not fire, so we
|
|
2170
|
+
// must compute this here rather than relying on the listener.
|
|
2171
|
+
saveBtn.disabled = !textarea.value.trim();
|
|
2172
|
+
// Guard against duplicate submits from rapid clicks or repeated
|
|
2173
|
+
// Cmd+Enter. Parity with CommentManager.saveComment which notes:
|
|
2174
|
+
// "Prevent duplicate saves from rapid clicks or Cmd+Enter".
|
|
2175
|
+
saveBtn.addEventListener('click', async () => {
|
|
2176
|
+
if (saveBtn.dataset.saving === 'true') return;
|
|
2177
|
+
if (!this.options.onCommentFormSubmit) return;
|
|
2178
|
+
saveBtn.dataset.saving = 'true';
|
|
2179
|
+
saveBtn.disabled = true;
|
|
2180
|
+
try {
|
|
2181
|
+
await this.options.onCommentFormSubmit(fileName, id, data, textarea.value);
|
|
2182
|
+
} finally {
|
|
2183
|
+
// On success the form annotation has been removed and the button
|
|
2184
|
+
// is detached; only touch the button if it's still connected.
|
|
2185
|
+
if (saveBtn.isConnected) {
|
|
2186
|
+
saveBtn.dataset.saving = 'false';
|
|
2187
|
+
saveBtn.disabled = !textarea.value.trim();
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
});
|
|
2191
|
+
actions.appendChild(saveBtn);
|
|
2192
|
+
|
|
2193
|
+
const chatBtn = document.createElement('button');
|
|
2194
|
+
chatBtn.className = 'ai-action ai-action-chat btn-chat-from-comment';
|
|
2195
|
+
chatBtn.title = 'Chat about these lines';
|
|
2196
|
+
chatBtn.innerHTML = PierreBridge.CHAT_FORM_SVG + ' Chat';
|
|
2197
|
+
chatBtn.addEventListener('click', () => {
|
|
2198
|
+
if (!window.chatPanel) return;
|
|
2199
|
+
if (this.options.onCommentFormCancel) {
|
|
2200
|
+
this.options.onCommentFormCancel(fileName, id, data);
|
|
2201
|
+
}
|
|
2202
|
+
window.chatPanel.open({
|
|
2203
|
+
commentContext: {
|
|
2204
|
+
type: 'line',
|
|
2205
|
+
body: textarea.value.trim() || null,
|
|
2206
|
+
file: fileName || '',
|
|
2207
|
+
line_start: parseInt(textarea.dataset.line) || null,
|
|
2208
|
+
line_end: parseInt(textarea.dataset.lineEnd) || parseInt(textarea.dataset.line) || null,
|
|
2209
|
+
side: textarea.dataset.side || 'RIGHT',
|
|
2210
|
+
source: 'user'
|
|
2211
|
+
}
|
|
2212
|
+
});
|
|
2213
|
+
});
|
|
2214
|
+
actions.appendChild(chatBtn);
|
|
2215
|
+
|
|
2216
|
+
const cancelBtn = document.createElement('button');
|
|
2217
|
+
cancelBtn.className = 'btn btn-sm btn-secondary cancel-comment-btn';
|
|
2218
|
+
cancelBtn.textContent = 'Cancel';
|
|
2219
|
+
cancelBtn.addEventListener('click', () => {
|
|
2220
|
+
if (this.options.onCommentFormCancel) {
|
|
2221
|
+
this.options.onCommentFormCancel(fileName, id, data);
|
|
2222
|
+
}
|
|
2223
|
+
});
|
|
2224
|
+
actions.appendChild(cancelBtn);
|
|
2225
|
+
|
|
2226
|
+
container.appendChild(actions);
|
|
2227
|
+
|
|
2228
|
+
// Enable/disable save button and re-evaluate suggestion button on input.
|
|
2229
|
+
// Mirrors CommentManager.updateSuggestionButtonState so that manually
|
|
2230
|
+
// deleting a ```suggestion block re-enables the toolbar button.
|
|
2231
|
+
const hasSuggestionBlock = (text) => /^\s*(`{3,})suggestion\s*$/m.test(text);
|
|
2232
|
+
textarea.addEventListener('input', () => {
|
|
2233
|
+
saveBtn.disabled = !textarea.value.trim();
|
|
2234
|
+
if (suggestionBtn) {
|
|
2235
|
+
const hasSuggestion = hasSuggestionBlock(textarea.value);
|
|
2236
|
+
suggestionBtn.disabled = hasSuggestion;
|
|
2237
|
+
suggestionBtn.title = hasSuggestion
|
|
2238
|
+
? 'Only one suggestion per comment'
|
|
2239
|
+
: 'Insert a suggestion';
|
|
2240
|
+
}
|
|
2241
|
+
// Auto-resize
|
|
2242
|
+
textarea.style.height = 'auto';
|
|
2243
|
+
textarea.style.height = textarea.scrollHeight + 'px';
|
|
2244
|
+
});
|
|
2245
|
+
|
|
2246
|
+
// Keyboard shortcuts (Cmd/Ctrl+Enter, Escape) are handled by the
|
|
2247
|
+
// delegated listener in PRManager.setupCommentFormDelegation() which
|
|
2248
|
+
// matches .comment-textarea — no inline handler needed here.
|
|
2249
|
+
|
|
2250
|
+
// Cache form element for reuse
|
|
2251
|
+
formElements.set(id, container);
|
|
2252
|
+
|
|
2253
|
+
// Focus textarea and attach emoji picker after it's in the DOM.
|
|
2254
|
+
// Matches parity with legacy CommentManager.showCommentForm — emoji
|
|
2255
|
+
// autocomplete (typing `:`) should work in Pierre-rendered forms too.
|
|
2256
|
+
requestAnimationFrame(() => {
|
|
2257
|
+
textarea.focus();
|
|
2258
|
+
if (window.emojiPicker) window.emojiPicker.attach(textarea);
|
|
2259
|
+
// Initial auto-resize for pre-filled content (input event doesn't
|
|
2260
|
+
// fire for programmatic .value assignment).
|
|
2261
|
+
if (data.initialValue) {
|
|
2262
|
+
textarea.style.height = 'auto';
|
|
2263
|
+
textarea.style.height = textarea.scrollHeight + 'px';
|
|
2264
|
+
// Sync suggestion button disabled state with pre-filled content —
|
|
2265
|
+
// the input event listener doesn't fire for programmatic .value.
|
|
2266
|
+
if (suggestionBtn) {
|
|
2267
|
+
const has = hasSuggestionBlock(textarea.value);
|
|
2268
|
+
suggestionBtn.disabled = has;
|
|
2269
|
+
if (has) suggestionBtn.title = 'Only one suggestion per comment';
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
});
|
|
2273
|
+
|
|
2274
|
+
return container;
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
// ─── Code Extraction ──────────────────────────────────────────────
|
|
2278
|
+
|
|
2279
|
+
/**
|
|
2280
|
+
* Get code content from stored metadata for a line range.
|
|
2281
|
+
* Used by the suggestion button to pre-fill suggestion blocks.
|
|
2282
|
+
* @param {string} fileName
|
|
2283
|
+
* @param {number} startLine - 1-based start line
|
|
2284
|
+
* @param {number} endLine - 1-based end line
|
|
2285
|
+
* @param {string} side - 'LEFT' or 'RIGHT'
|
|
2286
|
+
* @returns {string|null} Code text, or null if file not found
|
|
2287
|
+
*/
|
|
2288
|
+
getCodeFromLines(fileName, startLine, endLine, side) {
|
|
2289
|
+
const fileState = this.files.get(fileName);
|
|
2290
|
+
if (!fileState || !fileState.metadata) return null;
|
|
2291
|
+
|
|
2292
|
+
const metadata = fileState.baseMetadata || fileState.metadata;
|
|
2293
|
+
const useAdditions = (side || 'RIGHT') === 'RIGHT';
|
|
2294
|
+
const lines = useAdditions ? metadata.additionLines : metadata.deletionLines;
|
|
2295
|
+
const hunks = metadata.hunks;
|
|
2296
|
+
if (!lines || !hunks) return null;
|
|
2297
|
+
|
|
2298
|
+
const codeLines = [];
|
|
2299
|
+
for (const hunk of hunks) {
|
|
2300
|
+
const hunkStart = useAdditions ? hunk.additionStart : hunk.deletionStart;
|
|
2301
|
+
const hunkCount = useAdditions ? hunk.additionCount : hunk.deletionCount;
|
|
2302
|
+
const hunkLineIndex = useAdditions ? hunk.additionLineIndex : hunk.deletionLineIndex;
|
|
2303
|
+
const hunkEnd = hunkStart + hunkCount - 1;
|
|
2304
|
+
|
|
2305
|
+
// Skip hunks entirely outside the requested range
|
|
2306
|
+
if (hunkEnd < startLine || hunkStart > endLine) continue;
|
|
2307
|
+
|
|
2308
|
+
// Walk lines in this hunk
|
|
2309
|
+
for (let i = 0; i < hunkCount; i++) {
|
|
2310
|
+
const lineNum = hunkStart + i;
|
|
2311
|
+
if (lineNum >= startLine && lineNum <= endLine) {
|
|
2312
|
+
const idx = hunkLineIndex + i;
|
|
2313
|
+
if (idx < lines.length) {
|
|
2314
|
+
codeLines.push(lines[idx]);
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
return codeLines.length > 0 ? codeLines.join('\n') : null;
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
// ─── Utility ──────────────────────────────────────────────────────
|
|
2324
|
+
|
|
2325
|
+
/**
|
|
2326
|
+
* Normalize side from pair-review ('LEFT'/'RIGHT') to @pierre/diffs ('deletions'/'additions').
|
|
2327
|
+
*/
|
|
2328
|
+
static toPierreSide(side) {
|
|
2329
|
+
if (side === 'LEFT' || side === 'deletions') return 'deletions';
|
|
2330
|
+
return 'additions';
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
/**
|
|
2334
|
+
* Normalize side from @pierre/diffs to pair-review format.
|
|
2335
|
+
*/
|
|
2336
|
+
static toPairReviewSide(side) {
|
|
2337
|
+
if (side === 'deletions' || side === 'LEFT') return 'LEFT';
|
|
2338
|
+
return 'RIGHT';
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
/**
|
|
2342
|
+
* Normalize side to pair-review format for diffPosition lookup.
|
|
2343
|
+
*/
|
|
2344
|
+
static normalizeSide(side) {
|
|
2345
|
+
if (side === 'deletions' || side === 'LEFT') return 'LEFT';
|
|
2346
|
+
return 'RIGHT';
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
/**
|
|
2350
|
+
* Fallback patch parser if HunkParser is not available.
|
|
2351
|
+
* @private
|
|
2352
|
+
*/
|
|
2353
|
+
_parseBlocksFallback(patch) {
|
|
2354
|
+
const blocks = [];
|
|
2355
|
+
const lines = patch.split('\n');
|
|
2356
|
+
let currentBlock = null;
|
|
2357
|
+
|
|
2358
|
+
for (const line of lines) {
|
|
2359
|
+
const hunkMatch = line.match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)/);
|
|
2360
|
+
if (hunkMatch) {
|
|
2361
|
+
if (currentBlock) blocks.push(currentBlock);
|
|
2362
|
+
currentBlock = {
|
|
2363
|
+
header: line,
|
|
2364
|
+
oldStart: parseInt(hunkMatch[1], 10),
|
|
2365
|
+
newStart: parseInt(hunkMatch[2], 10),
|
|
2366
|
+
lines: [],
|
|
2367
|
+
};
|
|
2368
|
+
} else if (currentBlock && (line.startsWith('+') || line.startsWith('-') || line.startsWith(' '))) {
|
|
2369
|
+
currentBlock.lines.push(line);
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
if (currentBlock) blocks.push(currentBlock);
|
|
2373
|
+
return blocks;
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
// ─── CSS for Annotations ──────────────────────────────────────────
|
|
2377
|
+
|
|
2378
|
+
// Annotation CSS injected into Shadow DOM via unsafeCSS.
|
|
2379
|
+
// Suggestions and comments use legacy classes (.ai-suggestion, .user-comment)
|
|
2380
|
+
// styled by the page stylesheet. Only the comment form annotation lives
|
|
2381
|
+
// entirely within the shadow DOM and needs styles here.
|
|
2382
|
+
//
|
|
2383
|
+
// Split layout: @pierre/diffs anchors each annotation to ONE code column —
|
|
2384
|
+
// a 'deletions' annotation renders in the LEFT column, an 'additions'
|
|
2385
|
+
// annotation in the RIGHT column — and emits an EMPTY paired cell in the
|
|
2386
|
+
// opposite column on the same shared grid row (see getAnnotations()/
|
|
2387
|
+
// pushLineWithAnnotation in DiffHunksRenderer). A lone card would only get
|
|
2388
|
+
// half the width, so _syncSplitAnnotationLayout marks such cards with
|
|
2389
|
+
// .pr-annotation-fullwidth and the rules below stretch them across both
|
|
2390
|
+
// content tracks (the tracks are equal 1fr shares, so 200% + the measured
|
|
2391
|
+
// middle-gutter width spans exactly to the far edge). min-width:0 lets
|
|
2392
|
+
// unstretched cards (both sides annotated on one row) wrap inside their
|
|
2393
|
+
// half-width cell rather than force horizontal overflow.
|
|
2394
|
+
static ANNOTATION_CSS = `
|
|
2395
|
+
.pierre-annotation {
|
|
2396
|
+
padding: 8px 12px;
|
|
2397
|
+
margin: 4px 0;
|
|
2398
|
+
border-radius: 6px;
|
|
2399
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
|
|
2400
|
+
font-size: 13px;
|
|
2401
|
+
line-height: 1.5;
|
|
2402
|
+
}
|
|
2403
|
+
/* Let annotation cards wrap within a split column instead of overflowing. */
|
|
2404
|
+
[data-line-annotation] { min-width: 0; }
|
|
2405
|
+
[data-annotation-content] { min-width: 0; }
|
|
2406
|
+
/* Split view: stretch a lone card across both columns. The class and
|
|
2407
|
+
--pr-split-gutter-width are maintained by _syncSplitAnnotationLayout
|
|
2408
|
+
(the middle gutter track is min-content sized — unknowable in pure
|
|
2409
|
+
CSS). Without the var the card degrades to stopping at the seam.
|
|
2410
|
+
z-index clears the middle gutter, which the vendor paints at 3. */
|
|
2411
|
+
[data-diff-type='split'] .pr-annotation-fullwidth {
|
|
2412
|
+
position: relative;
|
|
2413
|
+
z-index: 4;
|
|
2414
|
+
width: calc(200% + var(--pr-split-gutter-width, 0px));
|
|
2415
|
+
}
|
|
2416
|
+
/* Right-column cards anchor at the additions track; pull them back to
|
|
2417
|
+
the left content track's start edge. */
|
|
2418
|
+
[data-diff-type='split'] [data-additions] .pr-annotation-fullwidth {
|
|
2419
|
+
margin-left: calc(-100% - var(--pr-split-gutter-width, 0px));
|
|
2420
|
+
}
|
|
2421
|
+
/* Split view, entirely added/removed file: the vendor emits ONE code
|
|
2422
|
+
column stamped data-diff-type='single' and ships no rule for it, so
|
|
2423
|
+
it stretches full width. Box it into the split layout instead:
|
|
2424
|
+
deletions in the left half, additions in the right, other half empty.
|
|
2425
|
+
The lone <code> keeps its internal gutter+content grid, so gutter and
|
|
2426
|
+
content both live inside their 1fr half and can never cross the
|
|
2427
|
+
center seam. The :has() guard skips unified mode, where every pre is
|
|
2428
|
+
'single' but its code column is data-unified. */
|
|
2429
|
+
[data-diff-type='single']:has(> [data-additions], > [data-deletions]) {
|
|
2430
|
+
display: grid;
|
|
2431
|
+
grid-template-columns: 1fr 1fr;
|
|
2432
|
+
}
|
|
2433
|
+
[data-diff-type='single'] > [data-deletions] {
|
|
2434
|
+
grid-column: 1;
|
|
2435
|
+
border-right: 1px solid var(--diffs-bg);
|
|
2436
|
+
}
|
|
2437
|
+
[data-diff-type='single'] > [data-additions] {
|
|
2438
|
+
grid-column: 2;
|
|
2439
|
+
border-left: 1px solid var(--diffs-bg);
|
|
2440
|
+
}
|
|
2441
|
+
/* The vendor's [data-code] ships overflow: scroll clip AND
|
|
2442
|
+
contain: content. Both must be neutralized here, for different reasons:
|
|
2443
|
+
- overflow: scroll clip is a scroll/clip box that would clip the
|
|
2444
|
+
stretched cards; reset to visible (lines wrap in wrap mode, so
|
|
2445
|
+
there is nothing to scroll).
|
|
2446
|
+
- contain: content implies contain: PAINT, which clips descendant
|
|
2447
|
+
paint to the code column's own border box REGARDLESS of overflow.
|
|
2448
|
+
The .pr-annotation-fullwidth cards below reach past this box (a
|
|
2449
|
+
right-half card sits at margin-left: calc(-100% - 2g)), so paint
|
|
2450
|
+
containment would hide their left portion — header text and body —
|
|
2451
|
+
while the right-aligned action buttons, which fall inside the box,
|
|
2452
|
+
still paint (the "empty card" bug). Drop paint containment; keep
|
|
2453
|
+
layout+style containment (cheap, no visual effect) so the vendor's
|
|
2454
|
+
perf intent is mostly preserved.
|
|
2455
|
+
Two-sided split columns escape both: they are display: contents and
|
|
2456
|
+
generate no box, so neither overflow nor contain has anything to clip —
|
|
2457
|
+
which is why this only bites one-sided (single) files, whose columns
|
|
2458
|
+
ARE real boxes (display: grid children, above). */
|
|
2459
|
+
[data-diff-type='single'][data-overflow='wrap'] > [data-deletions],
|
|
2460
|
+
[data-diff-type='single'][data-overflow='wrap'] > [data-additions] {
|
|
2461
|
+
overflow: visible;
|
|
2462
|
+
contain: layout style;
|
|
2463
|
+
}
|
|
2464
|
+
/* One-sided file: every card is lone, stretch across both halves.
|
|
2465
|
+
Geometry (g = the file's own gutter, published by
|
|
2466
|
+
_applySplitAnnotationLayout as --pr-split-gutter-width; 100% = the
|
|
2467
|
+
content track = half minus g): a left-half card starts after its
|
|
2468
|
+
gutter, so 200% + g reaches the far edge; a right-half card must
|
|
2469
|
+
also cross the empty left half AND its own gutter — shift back by
|
|
2470
|
+
100% + 2g and span 200% + 2g. */
|
|
2471
|
+
[data-diff-type='single'] .pr-annotation-fullwidth {
|
|
2472
|
+
position: relative;
|
|
2473
|
+
z-index: 4;
|
|
2474
|
+
}
|
|
2475
|
+
[data-diff-type='single'] [data-deletions] .pr-annotation-fullwidth {
|
|
2476
|
+
width: calc(200% + var(--pr-split-gutter-width, 0px));
|
|
2477
|
+
}
|
|
2478
|
+
[data-diff-type='single'] [data-additions] .pr-annotation-fullwidth {
|
|
2479
|
+
width: calc(200% + 2 * var(--pr-split-gutter-width, 0px));
|
|
2480
|
+
margin-left: calc(-100% - 2 * var(--pr-split-gutter-width, 0px));
|
|
2481
|
+
}
|
|
2482
|
+
/* Brief flash applied by PierreBridge.scrollToLine. Generic [data-line]
|
|
2483
|
+
match so it flashes whichever column (unified/deletions/additions) the
|
|
2484
|
+
target line resolves to. */
|
|
2485
|
+
[data-line].pierre-line-highlight {
|
|
2486
|
+
animation: pierre-line-highlight-flash 3.5s ease-out forwards;
|
|
2487
|
+
}
|
|
2488
|
+
@keyframes pierre-line-highlight-flash {
|
|
2489
|
+
0% {
|
|
2490
|
+
background-color: rgba(227, 179, 65, var(--pierre-highlight-start, 0.20));
|
|
2491
|
+
box-shadow: inset 3px 0 0 #e3b341;
|
|
2492
|
+
}
|
|
2493
|
+
57% {
|
|
2494
|
+
background-color: rgba(227, 179, 65, var(--pierre-highlight-mid, 0.08));
|
|
2495
|
+
box-shadow: inset 3px 0 0 #e3b341;
|
|
2496
|
+
}
|
|
2497
|
+
100% {
|
|
2498
|
+
background-color: transparent;
|
|
2499
|
+
box-shadow: inset 3px 0 0 transparent;
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
`;
|
|
2503
|
+
|
|
2504
|
+
static WORKER_INIT_TIMEOUT_MS = 15000;
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
// Export as global
|
|
2508
|
+
window.PierreBridge = PierreBridge;
|
|
2509
|
+
|
|
2510
|
+
// Also export for CommonJS test environments
|
|
2511
|
+
if (typeof module !== 'undefined') {
|
|
2512
|
+
module.exports = PierreBridge;
|
|
2513
|
+
}
|