blob: f20dd5759385c699f41989f2a65f98604a0f0a24 [file] [log] [blame]
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001import { css, html, LitElement } from "lit";
2import { customElement, property, state } from "lit/decorators.js";
3import "./sketch-monaco-view";
4import "./sketch-diff-range-picker";
David Crawshaw26f3f342025-06-14 19:58:32 +00005// import "./sketch-diff-file-picker"; // No longer needed for multi-file view
Philip Zeyliger272a90e2025-05-16 14:49:51 -07006import "./sketch-diff-empty-view";
Autoformatter8c463622025-05-16 21:54:17 +00007import {
8 GitDiffFile,
9 GitDataService,
10 DefaultGitDataService,
11} from "./git-data-service";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070012import { DiffRange } from "./sketch-diff-range-picker";
13
14/**
15 * A component that displays diffs using Monaco editor with range and file pickers
16 */
17@customElement("sketch-diff2-view")
18export class SketchDiff2View extends LitElement {
19 /**
20 * Handles comment events from the Monaco editor and forwards them to the chat input
21 * using the same event format as the original diff view for consistency.
22 */
23 private handleMonacoComment(event: CustomEvent) {
24 try {
25 // Validate incoming data
26 if (!event.detail || !event.detail.formattedComment) {
Autoformatter8c463622025-05-16 21:54:17 +000027 console.error("Invalid comment data received");
Philip Zeyliger272a90e2025-05-16 14:49:51 -070028 return;
29 }
Autoformatter8c463622025-05-16 21:54:17 +000030
Philip Zeyliger272a90e2025-05-16 14:49:51 -070031 // Create and dispatch event using the standardized format
Autoformatter8c463622025-05-16 21:54:17 +000032 const commentEvent = new CustomEvent("diff-comment", {
Philip Zeyliger272a90e2025-05-16 14:49:51 -070033 detail: { comment: event.detail.formattedComment },
34 bubbles: true,
Autoformatter8c463622025-05-16 21:54:17 +000035 composed: true,
Philip Zeyliger272a90e2025-05-16 14:49:51 -070036 });
Autoformatter8c463622025-05-16 21:54:17 +000037
Philip Zeyliger272a90e2025-05-16 14:49:51 -070038 this.dispatchEvent(commentEvent);
39 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +000040 console.error("Error handling Monaco comment:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -070041 }
42 }
Autoformatter8c463622025-05-16 21:54:17 +000043
Philip Zeyliger272a90e2025-05-16 14:49:51 -070044 /**
David Crawshaw26f3f342025-06-14 19:58:32 +000045 * Handle height change events from the Monaco editor
46 */
47 private handleMonacoHeightChange(event: CustomEvent) {
48 try {
49 // Get the monaco view that emitted the event
50 const monacoView = event.target as HTMLElement;
51 if (!monacoView) return;
Autoformatter9abf8032025-06-14 23:24:08 +000052
David Crawshaw26f3f342025-06-14 19:58:32 +000053 // Find the parent file-diff-editor container
Autoformatter9abf8032025-06-14 23:24:08 +000054 const fileDiffEditor = monacoView.closest(
55 ".file-diff-editor",
56 ) as HTMLElement;
David Crawshaw26f3f342025-06-14 19:58:32 +000057 if (!fileDiffEditor) return;
Autoformatter9abf8032025-06-14 23:24:08 +000058
David Crawshaw26f3f342025-06-14 19:58:32 +000059 // Get the new height from the event
60 const newHeight = event.detail.height;
Autoformatter9abf8032025-06-14 23:24:08 +000061
David Crawshaw26f3f342025-06-14 19:58:32 +000062 // Only update if the height actually changed to avoid unnecessary layout
63 const currentHeight = fileDiffEditor.style.height;
64 const newHeightStr = `${newHeight}px`;
Autoformatter9abf8032025-06-14 23:24:08 +000065
David Crawshaw26f3f342025-06-14 19:58:32 +000066 if (currentHeight !== newHeightStr) {
67 // Update the file-diff-editor height to match monaco's height
68 fileDiffEditor.style.height = newHeightStr;
Autoformatter9abf8032025-06-14 23:24:08 +000069
David Crawshaw26f3f342025-06-14 19:58:32 +000070 // Remove any previous min-height constraint that might interfere
Autoformatter9abf8032025-06-14 23:24:08 +000071 fileDiffEditor.style.minHeight = "auto";
72
David Crawshaw26f3f342025-06-14 19:58:32 +000073 // IMPORTANT: Tell Monaco to relayout after its container size changed
74 // Monaco has automaticLayout: false, so it won't detect container changes
75 setTimeout(() => {
76 const monacoComponent = monacoView as any;
77 if (monacoComponent && monacoComponent.editor) {
78 // Force layout with explicit dimensions to ensure Monaco fills the space
79 const editorWidth = fileDiffEditor.offsetWidth;
80 monacoComponent.editor.layout({
81 width: editorWidth,
Autoformatter9abf8032025-06-14 23:24:08 +000082 height: newHeight,
David Crawshaw26f3f342025-06-14 19:58:32 +000083 });
84 }
85 }, 0);
86 }
David Crawshaw26f3f342025-06-14 19:58:32 +000087 } catch (error) {
Autoformatter9abf8032025-06-14 23:24:08 +000088 console.error("Error handling Monaco height change:", error);
David Crawshaw26f3f342025-06-14 19:58:32 +000089 }
90 }
91
92 /**
Philip Zeyliger272a90e2025-05-16 14:49:51 -070093 * Handle save events from the Monaco editor
94 */
95 private async handleMonacoSave(event: CustomEvent) {
96 try {
97 // Validate incoming data
Autoformatter8c463622025-05-16 21:54:17 +000098 if (
99 !event.detail ||
100 !event.detail.path ||
101 event.detail.content === undefined
102 ) {
103 console.error("Invalid save data received");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700104 return;
105 }
Autoformatter8c463622025-05-16 21:54:17 +0000106
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700107 const { path, content } = event.detail;
Autoformatter8c463622025-05-16 21:54:17 +0000108
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700109 // Get Monaco view component
Autoformatter8c463622025-05-16 21:54:17 +0000110 const monacoView = this.shadowRoot?.querySelector("sketch-monaco-view");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700111 if (!monacoView) {
Autoformatter8c463622025-05-16 21:54:17 +0000112 console.error("Monaco view not found");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700113 return;
114 }
Autoformatter8c463622025-05-16 21:54:17 +0000115
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700116 try {
117 await this.gitService?.saveFileContent(path, content);
118 console.log(`File saved: ${path}`);
119 (monacoView as any).notifySaveComplete(true);
120 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000121 console.error(
122 `Error saving file: ${error instanceof Error ? error.message : String(error)}`,
123 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700124 (monacoView as any).notifySaveComplete(false);
125 }
126 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000127 console.error("Error handling save:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700128 }
129 }
130 @property({ type: String })
131 initialCommit: string = "";
Autoformatter8c463622025-05-16 21:54:17 +0000132
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700133 // The commit to show - used when showing a specific commit from timeline
134 @property({ type: String })
135 commit: string = "";
136
137 @property({ type: String })
138 selectedFilePath: string = "";
139
140 @state()
141 private files: GitDiffFile[] = [];
Autoformatter8c463622025-05-16 21:54:17 +0000142
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700143 @state()
Autoformatter8c463622025-05-16 21:54:17 +0000144 private currentRange: DiffRange = { type: "range", from: "", to: "HEAD" };
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700145
146 @state()
Autoformatter9abf8032025-06-14 23:24:08 +0000147 private fileContents: Map<
148 string,
149 { original: string; modified: string; editable: boolean }
150 > = new Map();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700151
152 @state()
David Crawshaw26f3f342025-06-14 19:58:32 +0000153 private fileExpandStates: Map<string, boolean> = new Map();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700154
155 @state()
156 private loading: boolean = false;
157
158 @state()
159 private error: string | null = null;
160
David Crawshaw4cd01292025-06-15 18:59:13 +0000161 @state()
162 private selectedFile: string = ""; // Empty string means "All files"
163
164 @state()
165 private viewMode: "all" | "single" = "all";
166
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700167 static styles = css`
168 :host {
169 display: flex;
170 height: 100%;
171 flex: 1;
172 flex-direction: column;
173 min-height: 0; /* Critical for flex child behavior */
174 overflow: hidden;
175 position: relative; /* Establish positioning context */
176 }
177
178 .controls {
179 padding: 8px 16px;
180 border-bottom: 1px solid var(--border-color, #e0e0e0);
181 background-color: var(--background-light, #f8f8f8);
182 flex-shrink: 0; /* Prevent controls from shrinking */
183 }
Autoformatter8c463622025-05-16 21:54:17 +0000184
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700185 .controls-container {
186 display: flex;
187 flex-direction: column;
188 gap: 12px;
189 }
Autoformatter8c463622025-05-16 21:54:17 +0000190
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700191 .range-row {
192 width: 100%;
193 display: flex;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700194 align-items: center;
David Crawshawdbca8972025-06-14 23:46:58 +0000195 gap: 12px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700196 }
Autoformatter8c463622025-05-16 21:54:17 +0000197
David Crawshaw4cd01292025-06-15 18:59:13 +0000198 .file-selector {
199 min-width: 200px;
200 padding: 8px 12px;
201 border: 1px solid var(--border-color, #ccc);
202 border-radius: 4px;
203 background-color: var(--background-color, #fff);
204 font-family: var(--font-family, system-ui, sans-serif);
205 font-size: 14px;
206 cursor: pointer;
207 }
208
209 .file-selector:focus {
210 outline: none;
211 border-color: var(--accent-color, #007acc);
212 box-shadow: 0 0 0 2px var(--accent-color-light, rgba(0, 122, 204, 0.2));
213 }
214
David Crawshaw5c6d8292025-06-15 19:09:19 +0000215 .file-selector:disabled {
216 background-color: var(--background-disabled, #f5f5f5);
217 color: var(--text-disabled, #999);
218 cursor: not-allowed;
219 }
220
221 .spacer {
222 flex: 1;
223 }
224
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700225 sketch-diff-range-picker {
David Crawshawdbca8972025-06-14 23:46:58 +0000226 flex: 1;
David Crawshawe2954ce2025-06-15 00:06:34 +0000227 min-width: 400px; /* Ensure minimum width for range picker */
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700228 }
Autoformatter8c463622025-05-16 21:54:17 +0000229
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700230 sketch-diff-file-picker {
231 flex: 1;
232 }
Autoformatter8c463622025-05-16 21:54:17 +0000233
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700234 .view-toggle-button {
235 background-color: #f0f0f0;
236 border: 1px solid #ccc;
237 border-radius: 4px;
Philip Zeyligere89b3082025-05-29 03:16:06 +0000238 padding: 8px;
239 font-size: 16px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700240 cursor: pointer;
241 white-space: nowrap;
242 transition: background-color 0.2s;
Philip Zeyligere89b3082025-05-29 03:16:06 +0000243 display: flex;
244 align-items: center;
245 justify-content: center;
246 min-width: 36px;
247 min-height: 36px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700248 }
Autoformatter8c463622025-05-16 21:54:17 +0000249
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700250 .view-toggle-button:hover {
251 background-color: #e0e0e0;
252 }
253
254 .diff-container {
255 flex: 1;
David Crawshaw26f3f342025-06-14 19:58:32 +0000256 overflow: auto;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700257 display: flex;
258 flex-direction: column;
David Crawshaw26f3f342025-06-14 19:58:32 +0000259 min-height: 0;
260 position: relative;
261 height: 100%;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700262 }
263
264 .diff-content {
265 flex: 1;
David Crawshaw26f3f342025-06-14 19:58:32 +0000266 overflow: auto;
267 min-height: 0;
268 display: flex;
269 flex-direction: column;
270 position: relative;
271 height: 100%;
272 }
273
274 .multi-file-diff-container {
275 display: flex;
276 flex-direction: column;
277 width: 100%;
278 min-height: 100%;
279 }
280
281 .file-diff-section {
282 display: flex;
283 flex-direction: column;
284 border-bottom: 3px solid var(--border-color, #e0e0e0);
285 margin-bottom: 0;
286 }
287
288 .file-diff-section:last-child {
289 border-bottom: none;
290 }
291
292 .file-header {
293 background-color: var(--background-light, #f8f8f8);
294 border-bottom: 1px solid var(--border-color, #e0e0e0);
David Crawshawdbca8972025-06-14 23:46:58 +0000295 padding: 8px 16px;
David Crawshaw26f3f342025-06-14 19:58:32 +0000296 font-family: var(--font-family, system-ui, sans-serif);
297 font-weight: 500;
298 font-size: 14px;
299 color: var(--text-primary-color, #333);
300 position: sticky;
301 top: 0;
302 z-index: 10;
303 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
304 display: flex;
305 justify-content: space-between;
306 align-items: center;
307 }
308
309 .file-header-left {
310 display: flex;
311 align-items: center;
312 gap: 8px;
313 }
314
315 .file-header-right {
316 display: flex;
317 align-items: center;
318 }
319
320 .file-expand-button {
321 background-color: transparent;
322 border: 1px solid var(--border-color, #e0e0e0);
323 border-radius: 4px;
324 padding: 4px 8px;
325 font-size: 14px;
326 cursor: pointer;
327 transition: background-color 0.2s;
328 display: flex;
329 align-items: center;
330 justify-content: center;
331 min-width: 32px;
332 min-height: 32px;
333 }
334
335 .file-expand-button:hover {
336 background-color: var(--background-hover, #e8e8e8);
337 }
338
339 .file-path {
340 font-family: monospace;
341 font-weight: normal;
342 color: var(--text-secondary-color, #666);
343 }
344
345 .file-status {
346 display: inline-block;
347 padding: 2px 6px;
348 border-radius: 3px;
349 font-size: 12px;
350 font-weight: bold;
351 margin-right: 8px;
352 }
353
354 .file-status.added {
355 background-color: #d4edda;
356 color: #155724;
357 }
358
359 .file-status.modified {
360 background-color: #fff3cd;
361 color: #856404;
362 }
363
364 .file-status.deleted {
365 background-color: #f8d7da;
366 color: #721c24;
367 }
368
369 .file-status.renamed {
370 background-color: #d1ecf1;
371 color: #0c5460;
372 }
373
374 .file-changes {
375 margin-left: 8px;
376 font-size: 12px;
377 color: var(--text-secondary-color, #666);
378 }
379
380 .file-diff-editor {
381 display: flex;
382 flex-direction: column;
383 min-height: 200px;
384 /* Height will be set dynamically by monaco editor */
385 overflow: visible; /* Ensure content is not clipped */
386 }
387
David Crawshaw216d2fc2025-06-15 18:45:53 +0000388
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700389
Autoformatter8c463622025-05-16 21:54:17 +0000390 .loading,
391 .empty-diff {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700392 display: flex;
393 align-items: center;
394 justify-content: center;
395 height: 100%;
396 font-family: var(--font-family, system-ui, sans-serif);
397 }
Autoformatter8c463622025-05-16 21:54:17 +0000398
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700399 .empty-diff {
400 color: var(--text-secondary-color, #666);
401 font-size: 16px;
402 text-align: center;
403 }
404
405 .error {
406 color: var(--error-color, #dc3545);
407 padding: 16px;
408 font-family: var(--font-family, system-ui, sans-serif);
409 }
410
411 sketch-monaco-view {
412 --editor-width: 100%;
413 --editor-height: 100%;
David Crawshaw26f3f342025-06-14 19:58:32 +0000414 display: flex;
415 flex-direction: column;
416 width: 100%;
417 min-height: 200px;
418 /* Ensure Monaco view takes full container space */
419 flex: 1;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700420 }
David Crawshaw4cd01292025-06-15 18:59:13 +0000421
422 /* Single file view styles */
423 .single-file-view {
424 flex: 1;
425 display: flex;
426 flex-direction: column;
427 height: 100%;
428 min-height: 0;
429 }
430
431 .single-file-monaco {
432 flex: 1;
433 width: 100%;
434 height: 100%;
435 min-height: 0;
436 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700437 `;
438
439 @property({ attribute: false, type: Object })
440 gitService!: GitDataService;
Autoformatter8c463622025-05-16 21:54:17 +0000441
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700442 // The gitService must be passed from parent to ensure proper dependency injection
443
444 constructor() {
445 super();
Autoformatter8c463622025-05-16 21:54:17 +0000446 console.log("SketchDiff2View initialized");
447
David Crawshawe2954ce2025-06-15 00:06:34 +0000448 // Fix for monaco-aria-container positioning and hide scrollbars globally
449 // Add a global style to ensure proper positioning of aria containers and hide scrollbars
Autoformatter8c463622025-05-16 21:54:17 +0000450 const styleElement = document.createElement("style");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700451 styleElement.textContent = `
452 .monaco-aria-container {
453 position: absolute !important;
454 top: 0 !important;
455 left: 0 !important;
456 width: 1px !important;
457 height: 1px !important;
458 overflow: hidden !important;
459 clip: rect(1px, 1px, 1px, 1px) !important;
460 white-space: nowrap !important;
461 margin: 0 !important;
462 padding: 0 !important;
463 border: 0 !important;
464 z-index: -1 !important;
465 }
David Crawshawe2954ce2025-06-15 00:06:34 +0000466
467 /* Aggressively hide all Monaco scrollbar elements */
468 .monaco-editor .scrollbar,
469 .monaco-editor .scroll-decoration,
470 .monaco-editor .invisible.scrollbar,
471 .monaco-editor .slider,
472 .monaco-editor .vertical.scrollbar,
473 .monaco-editor .horizontal.scrollbar,
474 .monaco-diff-editor .scrollbar,
475 .monaco-diff-editor .scroll-decoration,
476 .monaco-diff-editor .invisible.scrollbar,
477 .monaco-diff-editor .slider,
478 .monaco-diff-editor .vertical.scrollbar,
479 .monaco-diff-editor .horizontal.scrollbar {
480 display: none !important;
481 visibility: hidden !important;
482 width: 0 !important;
483 height: 0 !important;
484 opacity: 0 !important;
485 }
486
487 /* Target the specific scrollbar classes that Monaco uses */
488 .monaco-scrollable-element > .scrollbar,
489 .monaco-scrollable-element > .scroll-decoration,
490 .monaco-scrollable-element .slider {
491 display: none !important;
492 visibility: hidden !important;
493 width: 0 !important;
494 height: 0 !important;
495 }
496
497 /* Remove scrollbar space/padding from content area */
498 .monaco-editor .monaco-scrollable-element,
499 .monaco-diff-editor .monaco-scrollable-element {
500 padding-right: 0 !important;
501 padding-bottom: 0 !important;
502 margin-right: 0 !important;
503 margin-bottom: 0 !important;
504 }
505
506 /* Ensure the diff content takes full width without scrollbar space */
507 .monaco-diff-editor .editor.modified,
508 .monaco-diff-editor .editor.original {
509 margin-right: 0 !important;
510 padding-right: 0 !important;
511 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700512 `;
513 document.head.appendChild(styleElement);
514 }
515
516 connectedCallback() {
517 super.connectedCallback();
518 // Initialize with default range and load data
519 // Get base commit if not set
Autoformatter8c463622025-05-16 21:54:17 +0000520 if (
521 this.currentRange.type === "range" &&
522 !("from" in this.currentRange && this.currentRange.from)
523 ) {
524 this.gitService
525 .getBaseCommitRef()
526 .then((baseRef) => {
527 this.currentRange = { type: "range", from: baseRef, to: "HEAD" };
528 this.loadDiffData();
529 })
530 .catch((error) => {
531 console.error("Error getting base commit ref:", error);
532 // Use default range
533 this.loadDiffData();
534 });
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700535 } else {
536 this.loadDiffData();
537 }
538 }
539
David Crawshaw26f3f342025-06-14 19:58:32 +0000540 // Toggle hideUnchangedRegions setting for a specific file
541 private toggleFileExpansion(filePath: string) {
542 const currentState = this.fileExpandStates.get(filePath) ?? false;
543 const newState = !currentState;
544 this.fileExpandStates.set(filePath, newState);
Autoformatter9abf8032025-06-14 23:24:08 +0000545
David Crawshaw26f3f342025-06-14 19:58:32 +0000546 // Apply to the specific Monaco view component for this file
Autoformatter9abf8032025-06-14 23:24:08 +0000547 const monacoView = this.shadowRoot?.querySelector(
548 `sketch-monaco-view[data-file-path="${filePath}"]`,
549 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700550 if (monacoView) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000551 (monacoView as any).toggleHideUnchangedRegions(!newState); // inverted because true means "hide unchanged"
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700552 }
Autoformatter9abf8032025-06-14 23:24:08 +0000553
David Crawshaw26f3f342025-06-14 19:58:32 +0000554 // Force a re-render to update the button state
555 this.requestUpdate();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700556 }
Autoformatter8c463622025-05-16 21:54:17 +0000557
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700558 render() {
559 return html`
560 <div class="controls">
561 <div class="controls-container">
562 <div class="range-row">
David Crawshaw5c6d8292025-06-15 19:09:19 +0000563 ${this.renderFileSelector()}
564 <div class="spacer"></div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700565 <sketch-diff-range-picker
566 .gitService="${this.gitService}"
567 @range-change="${this.handleRangeChange}"
568 ></sketch-diff-range-picker>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700569 </div>
570 </div>
571 </div>
572
573 <div class="diff-container">
Autoformatter8c463622025-05-16 21:54:17 +0000574 <div class="diff-content">${this.renderDiffContent()}</div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700575 </div>
576 `;
577 }
578
David Crawshaw4cd01292025-06-15 18:59:13 +0000579 renderFileSelector() {
David Crawshaw5c6d8292025-06-15 19:09:19 +0000580 const fileCount = this.files.length;
581
David Crawshaw4cd01292025-06-15 18:59:13 +0000582 return html`
583 <select
584 class="file-selector"
585 .value="${this.selectedFile}"
586 @change="${this.handleFileSelection}"
David Crawshaw5c6d8292025-06-15 19:09:19 +0000587 ?disabled="${fileCount === 0}"
David Crawshaw4cd01292025-06-15 18:59:13 +0000588 >
David Crawshaw5c6d8292025-06-15 19:09:19 +0000589 <option value="">All files (${fileCount})</option>
David Crawshaw4cd01292025-06-15 18:59:13 +0000590 ${this.files.map(
591 (file) => html`
592 <option value="${file.path}">
593 ${this.getFileDisplayName(file)}
594 </option>
595 `,
596 )}
597 </select>
598 `;
599 }
600
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700601 renderDiffContent() {
602 if (this.loading) {
603 return html`<div class="loading">Loading diff...</div>`;
604 }
605
606 if (this.error) {
607 return html`<div class="error">${this.error}</div>`;
608 }
609
610 if (this.files.length === 0) {
611 return html`<sketch-diff-empty-view></sketch-diff-empty-view>`;
612 }
Autoformatter8c463622025-05-16 21:54:17 +0000613
David Crawshaw4cd01292025-06-15 18:59:13 +0000614 // Render single file view if a specific file is selected
615 if (this.selectedFile && this.viewMode === "single") {
616 return this.renderSingleFileView();
617 }
618
619 // Render multi-file view
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700620 return html`
David Crawshaw26f3f342025-06-14 19:58:32 +0000621 <div class="multi-file-diff-container">
622 ${this.files.map((file, index) => this.renderFileDiff(file, index))}
623 </div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700624 `;
625 }
626
627 /**
628 * Load diff data for the current range
629 */
630 async loadDiffData() {
631 this.loading = true;
632 this.error = null;
633
634 try {
635 // Initialize files as empty array if undefined
636 if (!this.files) {
637 this.files = [];
638 }
639
David Crawshaw216d2fc2025-06-15 18:45:53 +0000640 // Load diff data for the range
641 this.files = await this.gitService.getDiff(
642 this.currentRange.from,
643 this.currentRange.to,
644 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700645
646 // Ensure files is always an array, even when API returns null
647 if (!this.files) {
648 this.files = [];
649 }
Autoformatter8c463622025-05-16 21:54:17 +0000650
David Crawshaw26f3f342025-06-14 19:58:32 +0000651 // Load content for all files
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700652 if (this.files.length > 0) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000653 // Initialize expand states for new files (default to collapsed)
Autoformatter9abf8032025-06-14 23:24:08 +0000654 this.files.forEach((file) => {
David Crawshaw26f3f342025-06-14 19:58:32 +0000655 if (!this.fileExpandStates.has(file.path)) {
656 this.fileExpandStates.set(file.path, false); // false = collapsed (hide unchanged regions)
657 }
658 });
659 await this.loadAllFileContents();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700660 } else {
661 // No files to display - reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000662 this.selectedFilePath = "";
David Crawshaw4cd01292025-06-15 18:59:13 +0000663 this.selectedFile = "";
664 this.viewMode = "all";
David Crawshaw26f3f342025-06-14 19:58:32 +0000665 this.fileContents.clear();
666 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700667 }
668 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000669 console.error("Error loading diff data:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700670 this.error = `Error loading diff data: ${error.message}`;
671 // Ensure files is an empty array when an error occurs
672 this.files = [];
673 // Reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000674 this.selectedFilePath = "";
David Crawshaw4cd01292025-06-15 18:59:13 +0000675 this.selectedFile = "";
676 this.viewMode = "all";
David Crawshaw26f3f342025-06-14 19:58:32 +0000677 this.fileContents.clear();
678 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700679 } finally {
680 this.loading = false;
681 }
682 }
683
684 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000685 * Load content for all files in the diff
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700686 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000687 async loadAllFileContents() {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700688 this.loading = true;
689 this.error = null;
David Crawshaw26f3f342025-06-14 19:58:32 +0000690 this.fileContents.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700691
692 try {
693 let fromCommit: string;
694 let toCommit: string;
695 let isUnstagedChanges = false;
Autoformatter8c463622025-05-16 21:54:17 +0000696
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700697 // Determine the commits to compare based on the current range
David Crawshaw216d2fc2025-06-15 18:45:53 +0000698 fromCommit = this.currentRange.from;
699 toCommit = this.currentRange.to;
700 // Check if this is an unstaged changes view
701 isUnstagedChanges = toCommit === "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700702
David Crawshaw26f3f342025-06-14 19:58:32 +0000703 // Load content for all files
704 const promises = this.files.map(async (file) => {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700705 try {
David Crawshaw26f3f342025-06-14 19:58:32 +0000706 let originalCode = "";
707 let modifiedCode = "";
708 let editable = isUnstagedChanges;
Autoformatter8c463622025-05-16 21:54:17 +0000709
David Crawshaw26f3f342025-06-14 19:58:32 +0000710 // Load the original code based on file status
711 if (file.status !== "A") {
712 // For modified, renamed, or deleted files: load original content
713 originalCode = await this.gitService.getFileContent(
714 file.old_hash || "",
715 );
716 }
717
718 // For modified code, always use working copy when editable
719 if (editable) {
720 try {
721 // Always use working copy when editable, regardless of diff status
722 modifiedCode = await this.gitService.getWorkingCopyContent(
723 file.path,
724 );
725 } catch (error) {
726 if (file.status === "D") {
727 // For deleted files, silently use empty content
728 console.warn(
729 `Could not get working copy for deleted file ${file.path}, using empty content`,
730 );
731 modifiedCode = "";
732 } else {
733 // For any other file status, propagate the error
734 console.error(
735 `Failed to get working copy for ${file.path}:`,
736 error,
737 );
738 throw error;
739 }
740 }
741 } else {
742 // For non-editable view, use git content based on file status
743 if (file.status === "D") {
744 // Deleted file: empty modified
745 modifiedCode = "";
746 } else {
747 // Added/modified/renamed: use the content from git
748 modifiedCode = await this.gitService.getFileContent(
749 file.new_hash || "",
750 );
751 }
752 }
753
754 // Don't make deleted files editable
755 if (file.status === "D") {
756 editable = false;
757 }
758
759 this.fileContents.set(file.path, {
760 original: originalCode,
761 modified: modifiedCode,
762 editable,
763 });
764 } catch (error) {
765 console.error(`Error loading content for file ${file.path}:`, error);
766 // Store empty content for failed files to prevent blocking
767 this.fileContents.set(file.path, {
768 original: "",
769 modified: "",
770 editable: false,
771 });
772 }
773 });
774
775 await Promise.all(promises);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700776 } catch (error) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000777 console.error("Error loading file contents:", error);
778 this.error = `Error loading file contents: ${error.message}`;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700779 } finally {
780 this.loading = false;
781 }
782 }
783
784 /**
785 * Handle range change event from the range picker
786 */
787 handleRangeChange(event: CustomEvent) {
788 const { range } = event.detail;
Autoformatter8c463622025-05-16 21:54:17 +0000789 console.log("Range changed:", range);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700790 this.currentRange = range;
Autoformatter8c463622025-05-16 21:54:17 +0000791
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700792 // Load diff data for the new range
793 this.loadDiffData();
794 }
795
796 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000797 * Render a single file diff section
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700798 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000799 renderFileDiff(file: GitDiffFile, index: number) {
800 const content = this.fileContents.get(file.path);
801 if (!content) {
802 return html`
803 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000804 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000805 <div class="loading">Loading ${file.path}...</div>
806 </div>
807 `;
808 }
809
810 return html`
811 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000812 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000813 <div class="file-diff-editor">
814 <sketch-monaco-view
815 .originalCode="${content.original}"
816 .modifiedCode="${content.modified}"
817 .originalFilename="${file.path}"
818 .modifiedFilename="${file.path}"
819 ?readOnly="${!content.editable}"
820 ?editable-right="${content.editable}"
821 @monaco-comment="${this.handleMonacoComment}"
822 @monaco-save="${this.handleMonacoSave}"
823 @monaco-height-changed="${this.handleMonacoHeightChange}"
824 data-file-index="${index}"
825 data-file-path="${file.path}"
826 ></sketch-monaco-view>
827 </div>
828 </div>
829 `;
830 }
831
832 /**
833 * Render file header with status and path info
834 */
835 renderFileHeader(file: GitDiffFile) {
836 const statusClass = this.getFileStatusClass(file.status);
837 const statusText = this.getFileStatusText(file.status);
838 const changesInfo = this.getChangesInfo(file);
839 const pathInfo = this.getPathInfo(file);
840
841 const isExpanded = this.fileExpandStates.get(file.path) ?? false;
Autoformatter9abf8032025-06-14 23:24:08 +0000842
David Crawshaw26f3f342025-06-14 19:58:32 +0000843 return html`
844 <div class="file-header-left">
845 <span class="file-status ${statusClass}">${statusText}</span>
846 <span class="file-path">${pathInfo}</span>
Autoformatter9abf8032025-06-14 23:24:08 +0000847 ${changesInfo
848 ? html`<span class="file-changes">${changesInfo}</span>`
849 : ""}
David Crawshaw26f3f342025-06-14 19:58:32 +0000850 </div>
851 <div class="file-header-right">
852 <button
853 class="file-expand-button"
854 @click="${() => this.toggleFileExpansion(file.path)}"
855 title="${isExpanded
856 ? "Collapse: Hide unchanged regions to focus on changes"
857 : "Expand: Show all lines including unchanged regions"}"
858 >
Autoformatter9abf8032025-06-14 23:24:08 +0000859 ${isExpanded ? this.renderCollapseIcon() : this.renderExpandAllIcon()}
David Crawshaw26f3f342025-06-14 19:58:32 +0000860 </button>
861 </div>
862 `;
863 }
864
865 /**
866 * Get CSS class for file status
867 */
868 getFileStatusClass(status: string): string {
869 switch (status.toUpperCase()) {
870 case "A":
871 return "added";
872 case "M":
873 return "modified";
874 case "D":
875 return "deleted";
876 case "R":
877 default:
878 if (status.toUpperCase().startsWith("R")) {
879 return "renamed";
880 }
881 return "modified";
882 }
883 }
884
885 /**
886 * Get display text for file status
887 */
888 getFileStatusText(status: string): string {
889 switch (status.toUpperCase()) {
890 case "A":
891 return "Added";
892 case "M":
893 return "Modified";
894 case "D":
895 return "Deleted";
896 case "R":
897 default:
898 if (status.toUpperCase().startsWith("R")) {
899 return "Renamed";
900 }
901 return "Modified";
902 }
903 }
904
905 /**
906 * Get changes information (+/-) for display
907 */
908 getChangesInfo(file: GitDiffFile): string {
909 const additions = file.additions || 0;
910 const deletions = file.deletions || 0;
911
912 if (additions === 0 && deletions === 0) {
913 return "";
914 }
915
916 const parts = [];
917 if (additions > 0) {
918 parts.push(`+${additions}`);
919 }
920 if (deletions > 0) {
921 parts.push(`-${deletions}`);
922 }
923
924 return `(${parts.join(", ")})`;
925 }
926
927 /**
928 * Get path information for display, handling renames
929 */
930 getPathInfo(file: GitDiffFile): string {
931 if (file.old_path && file.old_path !== "") {
932 // For renames, show old_path → new_path
933 return `${file.old_path} → ${file.path}`;
934 }
935 // For regular files, just show the path
936 return file.path;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700937 }
938
939 /**
Philip Zeyligere89b3082025-05-29 03:16:06 +0000940 * Render expand all icon (dotted line with arrows pointing away)
941 */
942 renderExpandAllIcon() {
943 return html`
944 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
945 <!-- Dotted line in the middle -->
946 <line
947 x1="2"
948 y1="8"
949 x2="14"
950 y2="8"
951 stroke="currentColor"
952 stroke-width="1"
953 stroke-dasharray="2,1"
954 />
955 <!-- Large arrow pointing up -->
956 <path d="M8 2 L5 6 L11 6 Z" fill="currentColor" />
957 <!-- Large arrow pointing down -->
958 <path d="M8 14 L5 10 L11 10 Z" fill="currentColor" />
959 </svg>
960 `;
961 }
962
963 /**
964 * Render collapse icon (arrows pointing towards dotted line)
965 */
966 renderCollapseIcon() {
967 return html`
968 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
969 <!-- Dotted line in the middle -->
970 <line
971 x1="2"
972 y1="8"
973 x2="14"
974 y2="8"
975 stroke="currentColor"
976 stroke-width="1"
977 stroke-dasharray="2,1"
978 />
979 <!-- Large arrow pointing down towards line -->
980 <path d="M8 6 L5 2 L11 2 Z" fill="currentColor" />
981 <!-- Large arrow pointing up towards line -->
982 <path d="M8 10 L5 14 L11 14 Z" fill="currentColor" />
983 </svg>
984 `;
985 }
986
987 /**
David Crawshaw4cd01292025-06-15 18:59:13 +0000988 * Handle file selection change from the dropdown
989 */
990 handleFileSelection(event: Event) {
991 const selectElement = event.target as HTMLSelectElement;
992 const selectedValue = selectElement.value;
993
994 this.selectedFile = selectedValue;
995 this.viewMode = selectedValue ? "single" : "all";
996
997 // Force re-render
998 this.requestUpdate();
999 }
1000
1001 /**
1002 * Get display name for file in the selector
1003 */
1004 getFileDisplayName(file: GitDiffFile): string {
1005 const status = this.getFileStatusText(file.status);
1006 const pathInfo = this.getPathInfo(file);
1007 return `${status}: ${pathInfo}`;
1008 }
1009
1010 /**
1011 * Render single file view with full-screen Monaco editor
1012 */
1013 renderSingleFileView() {
1014 const selectedFileData = this.files.find(f => f.path === this.selectedFile);
1015 if (!selectedFileData) {
1016 return html`<div class="error">Selected file not found</div>`;
1017 }
1018
1019 const content = this.fileContents.get(this.selectedFile);
1020 if (!content) {
1021 return html`<div class="loading">Loading ${this.selectedFile}...</div>`;
1022 }
1023
1024 return html`
1025 <div class="single-file-view">
1026 <sketch-monaco-view
1027 class="single-file-monaco"
1028 .originalCode="${content.original}"
1029 .modifiedCode="${content.modified}"
1030 .originalFilename="${selectedFileData.path}"
1031 .modifiedFilename="${selectedFileData.path}"
1032 ?readOnly="${!content.editable}"
1033 ?editable-right="${content.editable}"
1034 @monaco-comment="${this.handleMonacoComment}"
1035 @monaco-save="${this.handleMonacoSave}"
1036 data-file-path="${selectedFileData.path}"
1037 ></sketch-monaco-view>
1038 </div>
1039 `;
1040 }
1041
1042 /**
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001043 * Refresh the diff view by reloading commits and diff data
Autoformatter8c463622025-05-16 21:54:17 +00001044 *
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001045 * This is called when the Monaco diff tab is activated to ensure:
1046 * 1. Branch information from git/recentlog is current (branches can change frequently)
1047 * 2. The diff content is synchronized with the latest repository state
1048 * 3. Users always see up-to-date information without manual refresh
1049 */
1050 refreshDiffView() {
1051 // First refresh the range picker to get updated branch information
Autoformatter8c463622025-05-16 21:54:17 +00001052 const rangePicker = this.shadowRoot?.querySelector(
1053 "sketch-diff-range-picker",
1054 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001055 if (rangePicker) {
1056 (rangePicker as any).loadCommits();
1057 }
Autoformatter8c463622025-05-16 21:54:17 +00001058
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001059 if (this.commit) {
David Crawshaw216d2fc2025-06-15 18:45:53 +00001060 // Convert single commit to range (commit^ to commit)
1061 this.currentRange = { type: "range", from: `${this.commit}^`, to: this.commit };
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001062 }
Autoformatter8c463622025-05-16 21:54:17 +00001063
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001064 // Then reload diff data based on the current range
1065 this.loadDiffData();
1066 }
1067}
1068
1069declare global {
1070 interface HTMLElementTagNameMap {
1071 "sketch-diff2-view": SketchDiff2View;
1072 }
1073}