blob: e13948e5c968e77b10316b4d13f65157b2d71344 [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
161 static styles = css`
162 :host {
163 display: flex;
164 height: 100%;
165 flex: 1;
166 flex-direction: column;
167 min-height: 0; /* Critical for flex child behavior */
168 overflow: hidden;
169 position: relative; /* Establish positioning context */
170 }
171
172 .controls {
173 padding: 8px 16px;
174 border-bottom: 1px solid var(--border-color, #e0e0e0);
175 background-color: var(--background-light, #f8f8f8);
176 flex-shrink: 0; /* Prevent controls from shrinking */
177 }
Autoformatter8c463622025-05-16 21:54:17 +0000178
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700179 .controls-container {
180 display: flex;
181 flex-direction: column;
182 gap: 12px;
183 }
Autoformatter8c463622025-05-16 21:54:17 +0000184
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700185 .range-row {
186 width: 100%;
187 display: flex;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700188 align-items: center;
David Crawshawdbca8972025-06-14 23:46:58 +0000189 gap: 12px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700190 }
Autoformatter8c463622025-05-16 21:54:17 +0000191
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700192 sketch-diff-range-picker {
David Crawshawdbca8972025-06-14 23:46:58 +0000193 flex: 1;
David Crawshawe2954ce2025-06-15 00:06:34 +0000194 min-width: 400px; /* Ensure minimum width for range picker */
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700195 }
Autoformatter8c463622025-05-16 21:54:17 +0000196
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700197 sketch-diff-file-picker {
198 flex: 1;
199 }
Autoformatter8c463622025-05-16 21:54:17 +0000200
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700201 .view-toggle-button {
202 background-color: #f0f0f0;
203 border: 1px solid #ccc;
204 border-radius: 4px;
Philip Zeyligere89b3082025-05-29 03:16:06 +0000205 padding: 8px;
206 font-size: 16px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700207 cursor: pointer;
208 white-space: nowrap;
209 transition: background-color 0.2s;
Philip Zeyligere89b3082025-05-29 03:16:06 +0000210 display: flex;
211 align-items: center;
212 justify-content: center;
213 min-width: 36px;
214 min-height: 36px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700215 }
Autoformatter8c463622025-05-16 21:54:17 +0000216
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700217 .view-toggle-button:hover {
218 background-color: #e0e0e0;
219 }
220
221 .diff-container {
222 flex: 1;
David Crawshaw26f3f342025-06-14 19:58:32 +0000223 overflow: auto;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700224 display: flex;
225 flex-direction: column;
David Crawshaw26f3f342025-06-14 19:58:32 +0000226 min-height: 0;
227 position: relative;
228 height: 100%;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700229 }
230
231 .diff-content {
232 flex: 1;
David Crawshaw26f3f342025-06-14 19:58:32 +0000233 overflow: auto;
234 min-height: 0;
235 display: flex;
236 flex-direction: column;
237 position: relative;
238 height: 100%;
239 }
240
241 .multi-file-diff-container {
242 display: flex;
243 flex-direction: column;
244 width: 100%;
245 min-height: 100%;
246 }
247
248 .file-diff-section {
249 display: flex;
250 flex-direction: column;
251 border-bottom: 3px solid var(--border-color, #e0e0e0);
252 margin-bottom: 0;
253 }
254
255 .file-diff-section:last-child {
256 border-bottom: none;
257 }
258
259 .file-header {
260 background-color: var(--background-light, #f8f8f8);
261 border-bottom: 1px solid var(--border-color, #e0e0e0);
David Crawshawdbca8972025-06-14 23:46:58 +0000262 padding: 8px 16px;
David Crawshaw26f3f342025-06-14 19:58:32 +0000263 font-family: var(--font-family, system-ui, sans-serif);
264 font-weight: 500;
265 font-size: 14px;
266 color: var(--text-primary-color, #333);
267 position: sticky;
268 top: 0;
269 z-index: 10;
270 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
271 display: flex;
272 justify-content: space-between;
273 align-items: center;
274 }
275
276 .file-header-left {
277 display: flex;
278 align-items: center;
279 gap: 8px;
280 }
281
282 .file-header-right {
283 display: flex;
284 align-items: center;
285 }
286
287 .file-expand-button {
288 background-color: transparent;
289 border: 1px solid var(--border-color, #e0e0e0);
290 border-radius: 4px;
291 padding: 4px 8px;
292 font-size: 14px;
293 cursor: pointer;
294 transition: background-color 0.2s;
295 display: flex;
296 align-items: center;
297 justify-content: center;
298 min-width: 32px;
299 min-height: 32px;
300 }
301
302 .file-expand-button:hover {
303 background-color: var(--background-hover, #e8e8e8);
304 }
305
306 .file-path {
307 font-family: monospace;
308 font-weight: normal;
309 color: var(--text-secondary-color, #666);
310 }
311
312 .file-status {
313 display: inline-block;
314 padding: 2px 6px;
315 border-radius: 3px;
316 font-size: 12px;
317 font-weight: bold;
318 margin-right: 8px;
319 }
320
321 .file-status.added {
322 background-color: #d4edda;
323 color: #155724;
324 }
325
326 .file-status.modified {
327 background-color: #fff3cd;
328 color: #856404;
329 }
330
331 .file-status.deleted {
332 background-color: #f8d7da;
333 color: #721c24;
334 }
335
336 .file-status.renamed {
337 background-color: #d1ecf1;
338 color: #0c5460;
339 }
340
341 .file-changes {
342 margin-left: 8px;
343 font-size: 12px;
344 color: var(--text-secondary-color, #666);
345 }
346
347 .file-diff-editor {
348 display: flex;
349 flex-direction: column;
350 min-height: 200px;
351 /* Height will be set dynamically by monaco editor */
352 overflow: visible; /* Ensure content is not clipped */
353 }
354
David Crawshaw216d2fc2025-06-15 18:45:53 +0000355
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700356
Autoformatter8c463622025-05-16 21:54:17 +0000357 .loading,
358 .empty-diff {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700359 display: flex;
360 align-items: center;
361 justify-content: center;
362 height: 100%;
363 font-family: var(--font-family, system-ui, sans-serif);
364 }
Autoformatter8c463622025-05-16 21:54:17 +0000365
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700366 .empty-diff {
367 color: var(--text-secondary-color, #666);
368 font-size: 16px;
369 text-align: center;
370 }
371
372 .error {
373 color: var(--error-color, #dc3545);
374 padding: 16px;
375 font-family: var(--font-family, system-ui, sans-serif);
376 }
377
378 sketch-monaco-view {
379 --editor-width: 100%;
380 --editor-height: 100%;
David Crawshaw26f3f342025-06-14 19:58:32 +0000381 display: flex;
382 flex-direction: column;
383 width: 100%;
384 min-height: 200px;
385 /* Ensure Monaco view takes full container space */
386 flex: 1;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700387 }
388 `;
389
390 @property({ attribute: false, type: Object })
391 gitService!: GitDataService;
Autoformatter8c463622025-05-16 21:54:17 +0000392
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700393 // The gitService must be passed from parent to ensure proper dependency injection
394
395 constructor() {
396 super();
Autoformatter8c463622025-05-16 21:54:17 +0000397 console.log("SketchDiff2View initialized");
398
David Crawshawe2954ce2025-06-15 00:06:34 +0000399 // Fix for monaco-aria-container positioning and hide scrollbars globally
400 // Add a global style to ensure proper positioning of aria containers and hide scrollbars
Autoformatter8c463622025-05-16 21:54:17 +0000401 const styleElement = document.createElement("style");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700402 styleElement.textContent = `
403 .monaco-aria-container {
404 position: absolute !important;
405 top: 0 !important;
406 left: 0 !important;
407 width: 1px !important;
408 height: 1px !important;
409 overflow: hidden !important;
410 clip: rect(1px, 1px, 1px, 1px) !important;
411 white-space: nowrap !important;
412 margin: 0 !important;
413 padding: 0 !important;
414 border: 0 !important;
415 z-index: -1 !important;
416 }
David Crawshawe2954ce2025-06-15 00:06:34 +0000417
418 /* Aggressively hide all Monaco scrollbar elements */
419 .monaco-editor .scrollbar,
420 .monaco-editor .scroll-decoration,
421 .monaco-editor .invisible.scrollbar,
422 .monaco-editor .slider,
423 .monaco-editor .vertical.scrollbar,
424 .monaco-editor .horizontal.scrollbar,
425 .monaco-diff-editor .scrollbar,
426 .monaco-diff-editor .scroll-decoration,
427 .monaco-diff-editor .invisible.scrollbar,
428 .monaco-diff-editor .slider,
429 .monaco-diff-editor .vertical.scrollbar,
430 .monaco-diff-editor .horizontal.scrollbar {
431 display: none !important;
432 visibility: hidden !important;
433 width: 0 !important;
434 height: 0 !important;
435 opacity: 0 !important;
436 }
437
438 /* Target the specific scrollbar classes that Monaco uses */
439 .monaco-scrollable-element > .scrollbar,
440 .monaco-scrollable-element > .scroll-decoration,
441 .monaco-scrollable-element .slider {
442 display: none !important;
443 visibility: hidden !important;
444 width: 0 !important;
445 height: 0 !important;
446 }
447
448 /* Remove scrollbar space/padding from content area */
449 .monaco-editor .monaco-scrollable-element,
450 .monaco-diff-editor .monaco-scrollable-element {
451 padding-right: 0 !important;
452 padding-bottom: 0 !important;
453 margin-right: 0 !important;
454 margin-bottom: 0 !important;
455 }
456
457 /* Ensure the diff content takes full width without scrollbar space */
458 .monaco-diff-editor .editor.modified,
459 .monaco-diff-editor .editor.original {
460 margin-right: 0 !important;
461 padding-right: 0 !important;
462 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700463 `;
464 document.head.appendChild(styleElement);
465 }
466
467 connectedCallback() {
468 super.connectedCallback();
469 // Initialize with default range and load data
470 // Get base commit if not set
Autoformatter8c463622025-05-16 21:54:17 +0000471 if (
472 this.currentRange.type === "range" &&
473 !("from" in this.currentRange && this.currentRange.from)
474 ) {
475 this.gitService
476 .getBaseCommitRef()
477 .then((baseRef) => {
478 this.currentRange = { type: "range", from: baseRef, to: "HEAD" };
479 this.loadDiffData();
480 })
481 .catch((error) => {
482 console.error("Error getting base commit ref:", error);
483 // Use default range
484 this.loadDiffData();
485 });
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700486 } else {
487 this.loadDiffData();
488 }
489 }
490
David Crawshaw26f3f342025-06-14 19:58:32 +0000491 // Toggle hideUnchangedRegions setting for a specific file
492 private toggleFileExpansion(filePath: string) {
493 const currentState = this.fileExpandStates.get(filePath) ?? false;
494 const newState = !currentState;
495 this.fileExpandStates.set(filePath, newState);
Autoformatter9abf8032025-06-14 23:24:08 +0000496
David Crawshaw26f3f342025-06-14 19:58:32 +0000497 // Apply to the specific Monaco view component for this file
Autoformatter9abf8032025-06-14 23:24:08 +0000498 const monacoView = this.shadowRoot?.querySelector(
499 `sketch-monaco-view[data-file-path="${filePath}"]`,
500 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700501 if (monacoView) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000502 (monacoView as any).toggleHideUnchangedRegions(!newState); // inverted because true means "hide unchanged"
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700503 }
Autoformatter9abf8032025-06-14 23:24:08 +0000504
David Crawshaw26f3f342025-06-14 19:58:32 +0000505 // Force a re-render to update the button state
506 this.requestUpdate();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700507 }
Autoformatter8c463622025-05-16 21:54:17 +0000508
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700509 render() {
510 return html`
511 <div class="controls">
512 <div class="controls-container">
513 <div class="range-row">
514 <sketch-diff-range-picker
515 .gitService="${this.gitService}"
516 @range-change="${this.handleRangeChange}"
517 ></sketch-diff-range-picker>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700518 </div>
519 </div>
520 </div>
521
522 <div class="diff-container">
Autoformatter8c463622025-05-16 21:54:17 +0000523 <div class="diff-content">${this.renderDiffContent()}</div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700524 </div>
525 `;
526 }
527
528 renderDiffContent() {
529 if (this.loading) {
530 return html`<div class="loading">Loading diff...</div>`;
531 }
532
533 if (this.error) {
534 return html`<div class="error">${this.error}</div>`;
535 }
536
537 if (this.files.length === 0) {
538 return html`<sketch-diff-empty-view></sketch-diff-empty-view>`;
539 }
Autoformatter8c463622025-05-16 21:54:17 +0000540
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700541 return html`
David Crawshaw26f3f342025-06-14 19:58:32 +0000542 <div class="multi-file-diff-container">
543 ${this.files.map((file, index) => this.renderFileDiff(file, index))}
544 </div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700545 `;
546 }
547
548 /**
549 * Load diff data for the current range
550 */
551 async loadDiffData() {
552 this.loading = true;
553 this.error = null;
554
555 try {
556 // Initialize files as empty array if undefined
557 if (!this.files) {
558 this.files = [];
559 }
560
David Crawshaw216d2fc2025-06-15 18:45:53 +0000561 // Load diff data for the range
562 this.files = await this.gitService.getDiff(
563 this.currentRange.from,
564 this.currentRange.to,
565 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700566
567 // Ensure files is always an array, even when API returns null
568 if (!this.files) {
569 this.files = [];
570 }
Autoformatter8c463622025-05-16 21:54:17 +0000571
David Crawshaw26f3f342025-06-14 19:58:32 +0000572 // Load content for all files
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700573 if (this.files.length > 0) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000574 // Initialize expand states for new files (default to collapsed)
Autoformatter9abf8032025-06-14 23:24:08 +0000575 this.files.forEach((file) => {
David Crawshaw26f3f342025-06-14 19:58:32 +0000576 if (!this.fileExpandStates.has(file.path)) {
577 this.fileExpandStates.set(file.path, false); // false = collapsed (hide unchanged regions)
578 }
579 });
580 await this.loadAllFileContents();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700581 } else {
582 // No files to display - reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000583 this.selectedFilePath = "";
David Crawshaw26f3f342025-06-14 19:58:32 +0000584 this.fileContents.clear();
585 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700586 }
587 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000588 console.error("Error loading diff data:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700589 this.error = `Error loading diff data: ${error.message}`;
590 // Ensure files is an empty array when an error occurs
591 this.files = [];
592 // Reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000593 this.selectedFilePath = "";
David Crawshaw26f3f342025-06-14 19:58:32 +0000594 this.fileContents.clear();
595 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700596 } finally {
597 this.loading = false;
598 }
599 }
600
601 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000602 * Load content for all files in the diff
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700603 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000604 async loadAllFileContents() {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700605 this.loading = true;
606 this.error = null;
David Crawshaw26f3f342025-06-14 19:58:32 +0000607 this.fileContents.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700608
609 try {
610 let fromCommit: string;
611 let toCommit: string;
612 let isUnstagedChanges = false;
Autoformatter8c463622025-05-16 21:54:17 +0000613
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700614 // Determine the commits to compare based on the current range
David Crawshaw216d2fc2025-06-15 18:45:53 +0000615 fromCommit = this.currentRange.from;
616 toCommit = this.currentRange.to;
617 // Check if this is an unstaged changes view
618 isUnstagedChanges = toCommit === "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700619
David Crawshaw26f3f342025-06-14 19:58:32 +0000620 // Load content for all files
621 const promises = this.files.map(async (file) => {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700622 try {
David Crawshaw26f3f342025-06-14 19:58:32 +0000623 let originalCode = "";
624 let modifiedCode = "";
625 let editable = isUnstagedChanges;
Autoformatter8c463622025-05-16 21:54:17 +0000626
David Crawshaw26f3f342025-06-14 19:58:32 +0000627 // Load the original code based on file status
628 if (file.status !== "A") {
629 // For modified, renamed, or deleted files: load original content
630 originalCode = await this.gitService.getFileContent(
631 file.old_hash || "",
632 );
633 }
634
635 // For modified code, always use working copy when editable
636 if (editable) {
637 try {
638 // Always use working copy when editable, regardless of diff status
639 modifiedCode = await this.gitService.getWorkingCopyContent(
640 file.path,
641 );
642 } catch (error) {
643 if (file.status === "D") {
644 // For deleted files, silently use empty content
645 console.warn(
646 `Could not get working copy for deleted file ${file.path}, using empty content`,
647 );
648 modifiedCode = "";
649 } else {
650 // For any other file status, propagate the error
651 console.error(
652 `Failed to get working copy for ${file.path}:`,
653 error,
654 );
655 throw error;
656 }
657 }
658 } else {
659 // For non-editable view, use git content based on file status
660 if (file.status === "D") {
661 // Deleted file: empty modified
662 modifiedCode = "";
663 } else {
664 // Added/modified/renamed: use the content from git
665 modifiedCode = await this.gitService.getFileContent(
666 file.new_hash || "",
667 );
668 }
669 }
670
671 // Don't make deleted files editable
672 if (file.status === "D") {
673 editable = false;
674 }
675
676 this.fileContents.set(file.path, {
677 original: originalCode,
678 modified: modifiedCode,
679 editable,
680 });
681 } catch (error) {
682 console.error(`Error loading content for file ${file.path}:`, error);
683 // Store empty content for failed files to prevent blocking
684 this.fileContents.set(file.path, {
685 original: "",
686 modified: "",
687 editable: false,
688 });
689 }
690 });
691
692 await Promise.all(promises);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700693 } catch (error) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000694 console.error("Error loading file contents:", error);
695 this.error = `Error loading file contents: ${error.message}`;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700696 } finally {
697 this.loading = false;
698 }
699 }
700
701 /**
702 * Handle range change event from the range picker
703 */
704 handleRangeChange(event: CustomEvent) {
705 const { range } = event.detail;
Autoformatter8c463622025-05-16 21:54:17 +0000706 console.log("Range changed:", range);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700707 this.currentRange = range;
Autoformatter8c463622025-05-16 21:54:17 +0000708
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700709 // Load diff data for the new range
710 this.loadDiffData();
711 }
712
713 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000714 * Render a single file diff section
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700715 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000716 renderFileDiff(file: GitDiffFile, index: number) {
717 const content = this.fileContents.get(file.path);
718 if (!content) {
719 return html`
720 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000721 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000722 <div class="loading">Loading ${file.path}...</div>
723 </div>
724 `;
725 }
726
727 return html`
728 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000729 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000730 <div class="file-diff-editor">
731 <sketch-monaco-view
732 .originalCode="${content.original}"
733 .modifiedCode="${content.modified}"
734 .originalFilename="${file.path}"
735 .modifiedFilename="${file.path}"
736 ?readOnly="${!content.editable}"
737 ?editable-right="${content.editable}"
738 @monaco-comment="${this.handleMonacoComment}"
739 @monaco-save="${this.handleMonacoSave}"
740 @monaco-height-changed="${this.handleMonacoHeightChange}"
741 data-file-index="${index}"
742 data-file-path="${file.path}"
743 ></sketch-monaco-view>
744 </div>
745 </div>
746 `;
747 }
748
749 /**
750 * Render file header with status and path info
751 */
752 renderFileHeader(file: GitDiffFile) {
753 const statusClass = this.getFileStatusClass(file.status);
754 const statusText = this.getFileStatusText(file.status);
755 const changesInfo = this.getChangesInfo(file);
756 const pathInfo = this.getPathInfo(file);
757
758 const isExpanded = this.fileExpandStates.get(file.path) ?? false;
Autoformatter9abf8032025-06-14 23:24:08 +0000759
David Crawshaw26f3f342025-06-14 19:58:32 +0000760 return html`
761 <div class="file-header-left">
762 <span class="file-status ${statusClass}">${statusText}</span>
763 <span class="file-path">${pathInfo}</span>
Autoformatter9abf8032025-06-14 23:24:08 +0000764 ${changesInfo
765 ? html`<span class="file-changes">${changesInfo}</span>`
766 : ""}
David Crawshaw26f3f342025-06-14 19:58:32 +0000767 </div>
768 <div class="file-header-right">
769 <button
770 class="file-expand-button"
771 @click="${() => this.toggleFileExpansion(file.path)}"
772 title="${isExpanded
773 ? "Collapse: Hide unchanged regions to focus on changes"
774 : "Expand: Show all lines including unchanged regions"}"
775 >
Autoformatter9abf8032025-06-14 23:24:08 +0000776 ${isExpanded ? this.renderCollapseIcon() : this.renderExpandAllIcon()}
David Crawshaw26f3f342025-06-14 19:58:32 +0000777 </button>
778 </div>
779 `;
780 }
781
782 /**
783 * Get CSS class for file status
784 */
785 getFileStatusClass(status: string): string {
786 switch (status.toUpperCase()) {
787 case "A":
788 return "added";
789 case "M":
790 return "modified";
791 case "D":
792 return "deleted";
793 case "R":
794 default:
795 if (status.toUpperCase().startsWith("R")) {
796 return "renamed";
797 }
798 return "modified";
799 }
800 }
801
802 /**
803 * Get display text for file status
804 */
805 getFileStatusText(status: string): string {
806 switch (status.toUpperCase()) {
807 case "A":
808 return "Added";
809 case "M":
810 return "Modified";
811 case "D":
812 return "Deleted";
813 case "R":
814 default:
815 if (status.toUpperCase().startsWith("R")) {
816 return "Renamed";
817 }
818 return "Modified";
819 }
820 }
821
822 /**
823 * Get changes information (+/-) for display
824 */
825 getChangesInfo(file: GitDiffFile): string {
826 const additions = file.additions || 0;
827 const deletions = file.deletions || 0;
828
829 if (additions === 0 && deletions === 0) {
830 return "";
831 }
832
833 const parts = [];
834 if (additions > 0) {
835 parts.push(`+${additions}`);
836 }
837 if (deletions > 0) {
838 parts.push(`-${deletions}`);
839 }
840
841 return `(${parts.join(", ")})`;
842 }
843
844 /**
845 * Get path information for display, handling renames
846 */
847 getPathInfo(file: GitDiffFile): string {
848 if (file.old_path && file.old_path !== "") {
849 // For renames, show old_path → new_path
850 return `${file.old_path} → ${file.path}`;
851 }
852 // For regular files, just show the path
853 return file.path;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700854 }
855
856 /**
Philip Zeyligere89b3082025-05-29 03:16:06 +0000857 * Render expand all icon (dotted line with arrows pointing away)
858 */
859 renderExpandAllIcon() {
860 return html`
861 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
862 <!-- Dotted line in the middle -->
863 <line
864 x1="2"
865 y1="8"
866 x2="14"
867 y2="8"
868 stroke="currentColor"
869 stroke-width="1"
870 stroke-dasharray="2,1"
871 />
872 <!-- Large arrow pointing up -->
873 <path d="M8 2 L5 6 L11 6 Z" fill="currentColor" />
874 <!-- Large arrow pointing down -->
875 <path d="M8 14 L5 10 L11 10 Z" fill="currentColor" />
876 </svg>
877 `;
878 }
879
880 /**
881 * Render collapse icon (arrows pointing towards dotted line)
882 */
883 renderCollapseIcon() {
884 return html`
885 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
886 <!-- Dotted line in the middle -->
887 <line
888 x1="2"
889 y1="8"
890 x2="14"
891 y2="8"
892 stroke="currentColor"
893 stroke-width="1"
894 stroke-dasharray="2,1"
895 />
896 <!-- Large arrow pointing down towards line -->
897 <path d="M8 6 L5 2 L11 2 Z" fill="currentColor" />
898 <!-- Large arrow pointing up towards line -->
899 <path d="M8 10 L5 14 L11 14 Z" fill="currentColor" />
900 </svg>
901 `;
902 }
903
904 /**
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700905 * Refresh the diff view by reloading commits and diff data
Autoformatter8c463622025-05-16 21:54:17 +0000906 *
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700907 * This is called when the Monaco diff tab is activated to ensure:
908 * 1. Branch information from git/recentlog is current (branches can change frequently)
909 * 2. The diff content is synchronized with the latest repository state
910 * 3. Users always see up-to-date information without manual refresh
911 */
912 refreshDiffView() {
913 // First refresh the range picker to get updated branch information
Autoformatter8c463622025-05-16 21:54:17 +0000914 const rangePicker = this.shadowRoot?.querySelector(
915 "sketch-diff-range-picker",
916 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700917 if (rangePicker) {
918 (rangePicker as any).loadCommits();
919 }
Autoformatter8c463622025-05-16 21:54:17 +0000920
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700921 if (this.commit) {
David Crawshaw216d2fc2025-06-15 18:45:53 +0000922 // Convert single commit to range (commit^ to commit)
923 this.currentRange = { type: "range", from: `${this.commit}^`, to: this.commit };
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700924 }
Autoformatter8c463622025-05-16 21:54:17 +0000925
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700926 // Then reload diff data based on the current range
927 this.loadDiffData();
928 }
929}
930
931declare global {
932 interface HTMLElementTagNameMap {
933 "sketch-diff2-view": SketchDiff2View;
934 }
935}