blob: 185db7b554e52cffce7fbb1bd068992114e3a264 [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;
194 min-width: 0;
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
355 .file-count {
356 font-size: 14px;
357 color: var(--text-secondary-color, #666);
358 font-weight: 500;
359 padding: 8px 12px;
360 background-color: var(--background-light, #f8f8f8);
361 border-radius: 4px;
362 border: 1px solid var(--border-color, #e0e0e0);
David Crawshawdbca8972025-06-14 23:46:58 +0000363 white-space: nowrap;
364 flex-shrink: 0;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700365 }
366
Autoformatter8c463622025-05-16 21:54:17 +0000367 .loading,
368 .empty-diff {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700369 display: flex;
370 align-items: center;
371 justify-content: center;
372 height: 100%;
373 font-family: var(--font-family, system-ui, sans-serif);
374 }
Autoformatter8c463622025-05-16 21:54:17 +0000375
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700376 .empty-diff {
377 color: var(--text-secondary-color, #666);
378 font-size: 16px;
379 text-align: center;
380 }
381
382 .error {
383 color: var(--error-color, #dc3545);
384 padding: 16px;
385 font-family: var(--font-family, system-ui, sans-serif);
386 }
387
388 sketch-monaco-view {
389 --editor-width: 100%;
390 --editor-height: 100%;
David Crawshaw26f3f342025-06-14 19:58:32 +0000391 display: flex;
392 flex-direction: column;
393 width: 100%;
394 min-height: 200px;
395 /* Ensure Monaco view takes full container space */
396 flex: 1;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700397 }
398 `;
399
400 @property({ attribute: false, type: Object })
401 gitService!: GitDataService;
Autoformatter8c463622025-05-16 21:54:17 +0000402
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700403 // The gitService must be passed from parent to ensure proper dependency injection
404
405 constructor() {
406 super();
Autoformatter8c463622025-05-16 21:54:17 +0000407 console.log("SketchDiff2View initialized");
408
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700409 // Fix for monaco-aria-container positioning
410 // Add a global style to ensure proper positioning of aria containers
Autoformatter8c463622025-05-16 21:54:17 +0000411 const styleElement = document.createElement("style");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700412 styleElement.textContent = `
413 .monaco-aria-container {
414 position: absolute !important;
415 top: 0 !important;
416 left: 0 !important;
417 width: 1px !important;
418 height: 1px !important;
419 overflow: hidden !important;
420 clip: rect(1px, 1px, 1px, 1px) !important;
421 white-space: nowrap !important;
422 margin: 0 !important;
423 padding: 0 !important;
424 border: 0 !important;
425 z-index: -1 !important;
426 }
427 `;
428 document.head.appendChild(styleElement);
429 }
430
431 connectedCallback() {
432 super.connectedCallback();
433 // Initialize with default range and load data
434 // Get base commit if not set
Autoformatter8c463622025-05-16 21:54:17 +0000435 if (
436 this.currentRange.type === "range" &&
437 !("from" in this.currentRange && this.currentRange.from)
438 ) {
439 this.gitService
440 .getBaseCommitRef()
441 .then((baseRef) => {
442 this.currentRange = { type: "range", from: baseRef, to: "HEAD" };
443 this.loadDiffData();
444 })
445 .catch((error) => {
446 console.error("Error getting base commit ref:", error);
447 // Use default range
448 this.loadDiffData();
449 });
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700450 } else {
451 this.loadDiffData();
452 }
453 }
454
David Crawshaw26f3f342025-06-14 19:58:32 +0000455 // Toggle hideUnchangedRegions setting for a specific file
456 private toggleFileExpansion(filePath: string) {
457 const currentState = this.fileExpandStates.get(filePath) ?? false;
458 const newState = !currentState;
459 this.fileExpandStates.set(filePath, newState);
Autoformatter9abf8032025-06-14 23:24:08 +0000460
David Crawshaw26f3f342025-06-14 19:58:32 +0000461 // Apply to the specific Monaco view component for this file
Autoformatter9abf8032025-06-14 23:24:08 +0000462 const monacoView = this.shadowRoot?.querySelector(
463 `sketch-monaco-view[data-file-path="${filePath}"]`,
464 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700465 if (monacoView) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000466 (monacoView as any).toggleHideUnchangedRegions(!newState); // inverted because true means "hide unchanged"
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700467 }
Autoformatter9abf8032025-06-14 23:24:08 +0000468
David Crawshaw26f3f342025-06-14 19:58:32 +0000469 // Force a re-render to update the button state
470 this.requestUpdate();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700471 }
Autoformatter8c463622025-05-16 21:54:17 +0000472
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700473 render() {
474 return html`
475 <div class="controls">
476 <div class="controls-container">
477 <div class="range-row">
478 <sketch-diff-range-picker
479 .gitService="${this.gitService}"
480 @range-change="${this.handleRangeChange}"
481 ></sketch-diff-range-picker>
David Crawshaw26f3f342025-06-14 19:58:32 +0000482 <div class="file-count">
Autoformatter9abf8032025-06-14 23:24:08 +0000483 ${this.files.length > 0
David Crawshawdbca8972025-06-14 23:46:58 +0000484 ? `${this.files.length} file${this.files.length === 1 ? "" : "s"}`
Autoformatter9abf8032025-06-14 23:24:08 +0000485 : "No files"}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700486 </div>
487 </div>
488 </div>
489 </div>
490
491 <div class="diff-container">
Autoformatter8c463622025-05-16 21:54:17 +0000492 <div class="diff-content">${this.renderDiffContent()}</div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700493 </div>
494 `;
495 }
496
497 renderDiffContent() {
498 if (this.loading) {
499 return html`<div class="loading">Loading diff...</div>`;
500 }
501
502 if (this.error) {
503 return html`<div class="error">${this.error}</div>`;
504 }
505
506 if (this.files.length === 0) {
507 return html`<sketch-diff-empty-view></sketch-diff-empty-view>`;
508 }
Autoformatter8c463622025-05-16 21:54:17 +0000509
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700510 return html`
David Crawshaw26f3f342025-06-14 19:58:32 +0000511 <div class="multi-file-diff-container">
512 ${this.files.map((file, index) => this.renderFileDiff(file, index))}
513 </div>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700514 `;
515 }
516
517 /**
518 * Load diff data for the current range
519 */
520 async loadDiffData() {
521 this.loading = true;
522 this.error = null;
523
524 try {
525 // Initialize files as empty array if undefined
526 if (!this.files) {
527 this.files = [];
528 }
529
530 // Load diff data based on the current range type
Autoformatter8c463622025-05-16 21:54:17 +0000531 if (this.currentRange.type === "single") {
532 this.files = await this.gitService.getCommitDiff(
533 this.currentRange.commit,
534 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700535 } else {
Autoformatter8c463622025-05-16 21:54:17 +0000536 this.files = await this.gitService.getDiff(
537 this.currentRange.from,
538 this.currentRange.to,
539 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700540 }
541
542 // Ensure files is always an array, even when API returns null
543 if (!this.files) {
544 this.files = [];
545 }
Autoformatter8c463622025-05-16 21:54:17 +0000546
David Crawshaw26f3f342025-06-14 19:58:32 +0000547 // Load content for all files
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700548 if (this.files.length > 0) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000549 // Initialize expand states for new files (default to collapsed)
Autoformatter9abf8032025-06-14 23:24:08 +0000550 this.files.forEach((file) => {
David Crawshaw26f3f342025-06-14 19:58:32 +0000551 if (!this.fileExpandStates.has(file.path)) {
552 this.fileExpandStates.set(file.path, false); // false = collapsed (hide unchanged regions)
553 }
554 });
555 await this.loadAllFileContents();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700556 } else {
557 // No files to display - reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000558 this.selectedFilePath = "";
David Crawshaw26f3f342025-06-14 19:58:32 +0000559 this.fileContents.clear();
560 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700561 }
562 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000563 console.error("Error loading diff data:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700564 this.error = `Error loading diff data: ${error.message}`;
565 // Ensure files is an empty array when an error occurs
566 this.files = [];
567 // Reset the view to initial state
Autoformatter8c463622025-05-16 21:54:17 +0000568 this.selectedFilePath = "";
David Crawshaw26f3f342025-06-14 19:58:32 +0000569 this.fileContents.clear();
570 this.fileExpandStates.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700571 } finally {
572 this.loading = false;
573 }
574 }
575
576 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000577 * Load content for all files in the diff
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700578 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000579 async loadAllFileContents() {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700580 this.loading = true;
581 this.error = null;
David Crawshaw26f3f342025-06-14 19:58:32 +0000582 this.fileContents.clear();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700583
584 try {
585 let fromCommit: string;
586 let toCommit: string;
587 let isUnstagedChanges = false;
Autoformatter8c463622025-05-16 21:54:17 +0000588
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700589 // Determine the commits to compare based on the current range
Autoformatter8c463622025-05-16 21:54:17 +0000590 if (this.currentRange.type === "single") {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700591 fromCommit = `${this.currentRange.commit}^`;
592 toCommit = this.currentRange.commit;
593 } else {
594 fromCommit = this.currentRange.from;
595 toCommit = this.currentRange.to;
596 // Check if this is an unstaged changes view
Autoformatter8c463622025-05-16 21:54:17 +0000597 isUnstagedChanges = toCommit === "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700598 }
599
David Crawshaw26f3f342025-06-14 19:58:32 +0000600 // Load content for all files
601 const promises = this.files.map(async (file) => {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700602 try {
David Crawshaw26f3f342025-06-14 19:58:32 +0000603 let originalCode = "";
604 let modifiedCode = "";
605 let editable = isUnstagedChanges;
Autoformatter8c463622025-05-16 21:54:17 +0000606
David Crawshaw26f3f342025-06-14 19:58:32 +0000607 // Load the original code based on file status
608 if (file.status !== "A") {
609 // For modified, renamed, or deleted files: load original content
610 originalCode = await this.gitService.getFileContent(
611 file.old_hash || "",
612 );
613 }
614
615 // For modified code, always use working copy when editable
616 if (editable) {
617 try {
618 // Always use working copy when editable, regardless of diff status
619 modifiedCode = await this.gitService.getWorkingCopyContent(
620 file.path,
621 );
622 } catch (error) {
623 if (file.status === "D") {
624 // For deleted files, silently use empty content
625 console.warn(
626 `Could not get working copy for deleted file ${file.path}, using empty content`,
627 );
628 modifiedCode = "";
629 } else {
630 // For any other file status, propagate the error
631 console.error(
632 `Failed to get working copy for ${file.path}:`,
633 error,
634 );
635 throw error;
636 }
637 }
638 } else {
639 // For non-editable view, use git content based on file status
640 if (file.status === "D") {
641 // Deleted file: empty modified
642 modifiedCode = "";
643 } else {
644 // Added/modified/renamed: use the content from git
645 modifiedCode = await this.gitService.getFileContent(
646 file.new_hash || "",
647 );
648 }
649 }
650
651 // Don't make deleted files editable
652 if (file.status === "D") {
653 editable = false;
654 }
655
656 this.fileContents.set(file.path, {
657 original: originalCode,
658 modified: modifiedCode,
659 editable,
660 });
661 } catch (error) {
662 console.error(`Error loading content for file ${file.path}:`, error);
663 // Store empty content for failed files to prevent blocking
664 this.fileContents.set(file.path, {
665 original: "",
666 modified: "",
667 editable: false,
668 });
669 }
670 });
671
672 await Promise.all(promises);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700673 } catch (error) {
David Crawshaw26f3f342025-06-14 19:58:32 +0000674 console.error("Error loading file contents:", error);
675 this.error = `Error loading file contents: ${error.message}`;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700676 } finally {
677 this.loading = false;
678 }
679 }
680
681 /**
682 * Handle range change event from the range picker
683 */
684 handleRangeChange(event: CustomEvent) {
685 const { range } = event.detail;
Autoformatter8c463622025-05-16 21:54:17 +0000686 console.log("Range changed:", range);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700687 this.currentRange = range;
Autoformatter8c463622025-05-16 21:54:17 +0000688
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700689 // Load diff data for the new range
690 this.loadDiffData();
691 }
692
693 /**
David Crawshaw26f3f342025-06-14 19:58:32 +0000694 * Render a single file diff section
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700695 */
David Crawshaw26f3f342025-06-14 19:58:32 +0000696 renderFileDiff(file: GitDiffFile, index: number) {
697 const content = this.fileContents.get(file.path);
698 if (!content) {
699 return html`
700 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000701 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000702 <div class="loading">Loading ${file.path}...</div>
703 </div>
704 `;
705 }
706
707 return html`
708 <div class="file-diff-section">
Autoformatter9abf8032025-06-14 23:24:08 +0000709 <div class="file-header">${this.renderFileHeader(file)}</div>
David Crawshaw26f3f342025-06-14 19:58:32 +0000710 <div class="file-diff-editor">
711 <sketch-monaco-view
712 .originalCode="${content.original}"
713 .modifiedCode="${content.modified}"
714 .originalFilename="${file.path}"
715 .modifiedFilename="${file.path}"
716 ?readOnly="${!content.editable}"
717 ?editable-right="${content.editable}"
718 @monaco-comment="${this.handleMonacoComment}"
719 @monaco-save="${this.handleMonacoSave}"
720 @monaco-height-changed="${this.handleMonacoHeightChange}"
721 data-file-index="${index}"
722 data-file-path="${file.path}"
723 ></sketch-monaco-view>
724 </div>
725 </div>
726 `;
727 }
728
729 /**
730 * Render file header with status and path info
731 */
732 renderFileHeader(file: GitDiffFile) {
733 const statusClass = this.getFileStatusClass(file.status);
734 const statusText = this.getFileStatusText(file.status);
735 const changesInfo = this.getChangesInfo(file);
736 const pathInfo = this.getPathInfo(file);
737
738 const isExpanded = this.fileExpandStates.get(file.path) ?? false;
Autoformatter9abf8032025-06-14 23:24:08 +0000739
David Crawshaw26f3f342025-06-14 19:58:32 +0000740 return html`
741 <div class="file-header-left">
742 <span class="file-status ${statusClass}">${statusText}</span>
743 <span class="file-path">${pathInfo}</span>
Autoformatter9abf8032025-06-14 23:24:08 +0000744 ${changesInfo
745 ? html`<span class="file-changes">${changesInfo}</span>`
746 : ""}
David Crawshaw26f3f342025-06-14 19:58:32 +0000747 </div>
748 <div class="file-header-right">
749 <button
750 class="file-expand-button"
751 @click="${() => this.toggleFileExpansion(file.path)}"
752 title="${isExpanded
753 ? "Collapse: Hide unchanged regions to focus on changes"
754 : "Expand: Show all lines including unchanged regions"}"
755 >
Autoformatter9abf8032025-06-14 23:24:08 +0000756 ${isExpanded ? this.renderCollapseIcon() : this.renderExpandAllIcon()}
David Crawshaw26f3f342025-06-14 19:58:32 +0000757 </button>
758 </div>
759 `;
760 }
761
762 /**
763 * Get CSS class for file status
764 */
765 getFileStatusClass(status: string): string {
766 switch (status.toUpperCase()) {
767 case "A":
768 return "added";
769 case "M":
770 return "modified";
771 case "D":
772 return "deleted";
773 case "R":
774 default:
775 if (status.toUpperCase().startsWith("R")) {
776 return "renamed";
777 }
778 return "modified";
779 }
780 }
781
782 /**
783 * Get display text for file status
784 */
785 getFileStatusText(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 changes information (+/-) for display
804 */
805 getChangesInfo(file: GitDiffFile): string {
806 const additions = file.additions || 0;
807 const deletions = file.deletions || 0;
808
809 if (additions === 0 && deletions === 0) {
810 return "";
811 }
812
813 const parts = [];
814 if (additions > 0) {
815 parts.push(`+${additions}`);
816 }
817 if (deletions > 0) {
818 parts.push(`-${deletions}`);
819 }
820
821 return `(${parts.join(", ")})`;
822 }
823
824 /**
825 * Get path information for display, handling renames
826 */
827 getPathInfo(file: GitDiffFile): string {
828 if (file.old_path && file.old_path !== "") {
829 // For renames, show old_path → new_path
830 return `${file.old_path} → ${file.path}`;
831 }
832 // For regular files, just show the path
833 return file.path;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700834 }
835
836 /**
Philip Zeyligere89b3082025-05-29 03:16:06 +0000837 * Render expand all icon (dotted line with arrows pointing away)
838 */
839 renderExpandAllIcon() {
840 return html`
841 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
842 <!-- Dotted line in the middle -->
843 <line
844 x1="2"
845 y1="8"
846 x2="14"
847 y2="8"
848 stroke="currentColor"
849 stroke-width="1"
850 stroke-dasharray="2,1"
851 />
852 <!-- Large arrow pointing up -->
853 <path d="M8 2 L5 6 L11 6 Z" fill="currentColor" />
854 <!-- Large arrow pointing down -->
855 <path d="M8 14 L5 10 L11 10 Z" fill="currentColor" />
856 </svg>
857 `;
858 }
859
860 /**
861 * Render collapse icon (arrows pointing towards dotted line)
862 */
863 renderCollapseIcon() {
864 return html`
865 <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
866 <!-- Dotted line in the middle -->
867 <line
868 x1="2"
869 y1="8"
870 x2="14"
871 y2="8"
872 stroke="currentColor"
873 stroke-width="1"
874 stroke-dasharray="2,1"
875 />
876 <!-- Large arrow pointing down towards line -->
877 <path d="M8 6 L5 2 L11 2 Z" fill="currentColor" />
878 <!-- Large arrow pointing up towards line -->
879 <path d="M8 10 L5 14 L11 14 Z" fill="currentColor" />
880 </svg>
881 `;
882 }
883
884 /**
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700885 * Refresh the diff view by reloading commits and diff data
Autoformatter8c463622025-05-16 21:54:17 +0000886 *
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700887 * This is called when the Monaco diff tab is activated to ensure:
888 * 1. Branch information from git/recentlog is current (branches can change frequently)
889 * 2. The diff content is synchronized with the latest repository state
890 * 3. Users always see up-to-date information without manual refresh
891 */
892 refreshDiffView() {
893 // First refresh the range picker to get updated branch information
Autoformatter8c463622025-05-16 21:54:17 +0000894 const rangePicker = this.shadowRoot?.querySelector(
895 "sketch-diff-range-picker",
896 );
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700897 if (rangePicker) {
898 (rangePicker as any).loadCommits();
899 }
Autoformatter8c463622025-05-16 21:54:17 +0000900
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700901 if (this.commit) {
Autoformatter8c463622025-05-16 21:54:17 +0000902 this.currentRange = { type: "single", commit: this.commit };
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700903 }
Autoformatter8c463622025-05-16 21:54:17 +0000904
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700905 // Then reload diff data based on the current range
906 this.loadDiffData();
907 }
908}
909
910declare global {
911 interface HTMLElementTagNameMap {
912 "sketch-diff2-view": SketchDiff2View;
913 }
914}