blob: 38d29b05cdc6c6bebb5c8cab85315e37a7b34f66 [file] [log] [blame]
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001// sketch-diff-range-picker.ts
2// Component for selecting commit range for diffs
3
4import { css, html, LitElement } from "lit";
5import { customElement, property, state } from "lit/decorators.js";
6import { GitDataService, DefaultGitDataService } from "./git-data-service";
7import { GitLogEntry } from "../types";
8
9/**
10 * Range type for diff views
11 */
Autoformatter8c463622025-05-16 21:54:17 +000012export type DiffRange =
13 | { type: "range"; from: string; to: string }
14 | { type: "single"; commit: string };
Philip Zeyliger272a90e2025-05-16 14:49:51 -070015
16/**
17 * Component for selecting commit range for diffs
18 */
19@customElement("sketch-diff-range-picker")
20export class SketchDiffRangePicker extends LitElement {
21 @property({ type: Array })
22 commits: GitLogEntry[] = [];
23
24 @state()
Autoformatter8c463622025-05-16 21:54:17 +000025 private rangeType: "range" | "single" = "range";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070026
27 @state()
Autoformatter8c463622025-05-16 21:54:17 +000028 private fromCommit: string = "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070029
30 @state()
Autoformatter8c463622025-05-16 21:54:17 +000031 private toCommit: string = "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070032
33 @state()
Autoformatter8c463622025-05-16 21:54:17 +000034 private singleCommit: string = "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070035
36 @state()
37 private loading: boolean = true;
38
39 @state()
40 private error: string | null = null;
Autoformatter8c463622025-05-16 21:54:17 +000041
Philip Zeyliger272a90e2025-05-16 14:49:51 -070042 @property({ attribute: false, type: Object })
43 gitService!: GitDataService;
Autoformatter8c463622025-05-16 21:54:17 +000044
Philip Zeyliger272a90e2025-05-16 14:49:51 -070045 constructor() {
46 super();
Autoformatter8c463622025-05-16 21:54:17 +000047 console.log("SketchDiffRangePicker initialized");
Philip Zeyliger272a90e2025-05-16 14:49:51 -070048 }
49
50 static styles = css`
51 :host {
52 display: block;
53 width: 100%;
54 font-family: var(--font-family, system-ui, sans-serif);
55 color: var(--text-color, #333);
56 }
57
58 .range-picker {
59 display: flex;
60 flex-direction: row;
61 align-items: center;
62 gap: 12px;
63 padding: 12px;
64 background-color: var(--background-light, #f8f8f8);
65 border-radius: 4px;
66 border: 1px solid var(--border-color, #e0e0e0);
67 flex-wrap: wrap; /* Allow wrapping on small screens */
68 width: 100%;
69 box-sizing: border-box;
70 }
71
72 .range-type-selector {
73 display: flex;
74 gap: 16px;
75 flex-shrink: 0;
76 }
77
78 .range-type-option {
79 display: flex;
80 align-items: center;
81 gap: 6px;
82 cursor: pointer;
83 white-space: nowrap;
84 }
85
86 .commit-selectors {
87 display: flex;
88 flex-direction: row;
89 align-items: center;
90 gap: 12px;
91 flex: 1;
92 flex-wrap: wrap; /* Allow wrapping on small screens */
93 }
94
95 .commit-selector {
96 display: flex;
97 align-items: center;
98 gap: 8px;
99 flex: 1;
100 min-width: 200px;
101 max-width: calc(50% - 12px); /* Half width minus half the gap */
102 overflow: hidden;
103 }
104
105 select {
106 padding: 6px 8px;
107 border-radius: 4px;
108 border: 1px solid var(--border-color, #e0e0e0);
109 background-color: var(--background, #fff);
110 max-width: 100%;
111 overflow: hidden;
112 text-overflow: ellipsis;
113 white-space: nowrap;
114 }
115
116 label {
117 font-weight: 500;
118 font-size: 14px;
119 }
120
121 .loading {
122 font-style: italic;
123 color: var(--text-muted, #666);
124 }
125
126 .error {
127 color: var(--error-color, #dc3545);
128 font-size: 14px;
129 }
Autoformatter8c463622025-05-16 21:54:17 +0000130
Philip Zeyligere89b3082025-05-29 03:16:06 +0000131 .refresh-button {
132 padding: 6px 12px;
133 background-color: #f0f0f0;
134 color: var(--text-color, #333);
135 border: 1px solid var(--border-color, #e0e0e0);
136 border-radius: 4px;
137 cursor: pointer;
138 font-size: 14px;
139 transition: background-color 0.2s;
140 white-space: nowrap;
141 display: flex;
142 align-items: center;
143 gap: 4px;
144 }
145
146 .refresh-button:hover {
147 background-color: #e0e0e0;
148 }
149
150 .refresh-button:disabled {
151 background-color: #f8f8f8;
152 color: #999;
153 cursor: not-allowed;
154 }
155
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700156 @media (max-width: 768px) {
157 .commit-selector {
158 max-width: 100%;
159 }
160 }
161 `;
162
163 connectedCallback() {
164 super.connectedCallback();
165 // Wait for DOM to be fully loaded to ensure proper initialization order
Autoformatter8c463622025-05-16 21:54:17 +0000166 if (document.readyState === "complete") {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700167 this.loadCommits();
168 } else {
Autoformatter8c463622025-05-16 21:54:17 +0000169 window.addEventListener("load", () => {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700170 setTimeout(() => this.loadCommits(), 0); // Give time for provider initialization
171 });
172 }
David Crawshaw938d2dc2025-06-14 22:17:33 +0000173
174 // Listen for popstate events to handle browser back/forward navigation
175 window.addEventListener('popstate', this.handlePopState.bind(this));
176 }
177
178 disconnectedCallback() {
179 super.disconnectedCallback();
180 window.removeEventListener('popstate', this.handlePopState.bind(this));
181 }
182
183 /**
184 * Handle browser back/forward navigation
185 */
186 private handlePopState() {
187 // Re-initialize from URL parameters when user navigates
188 if (this.commits.length > 0) {
189 const initializedFromUrl = this.initializeFromUrlParams();
190 if (initializedFromUrl) {
191 // Force re-render and dispatch event
192 this.requestUpdate();
193 this.dispatchRangeEvent();
194 }
195 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700196 }
197
198 render() {
199 return html`
200 <div class="range-picker">
201 ${this.loading
202 ? html`<div class="loading">Loading commits...</div>`
203 : this.error
Autoformatter8c463622025-05-16 21:54:17 +0000204 ? html`<div class="error">${this.error}</div>`
205 : this.renderRangePicker()}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700206 </div>
207 `;
208 }
209
210 renderRangePicker() {
211 return html`
212 <div class="range-type-selector">
213 <label class="range-type-option">
214 <input
215 type="radio"
216 name="rangeType"
217 value="range"
Autoformatter8c463622025-05-16 21:54:17 +0000218 ?checked=${this.rangeType === "range"}
219 @change=${() => this.setRangeType("range")}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700220 />
221 Commit Range
222 </label>
223 <label class="range-type-option">
224 <input
225 type="radio"
226 name="rangeType"
227 value="single"
Autoformatter8c463622025-05-16 21:54:17 +0000228 ?checked=${this.rangeType === "single"}
229 @change=${() => this.setRangeType("single")}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700230 />
231 Single Commit
232 </label>
233 </div>
234
235 <div class="commit-selectors">
Autoformatter8c463622025-05-16 21:54:17 +0000236 ${this.rangeType === "range"
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700237 ? this.renderRangeSelectors()
Autoformatter8c463622025-05-16 21:54:17 +0000238 : this.renderSingleSelector()}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700239 </div>
Philip Zeyligere89b3082025-05-29 03:16:06 +0000240
241 <button
242 class="refresh-button"
243 @click="${this.handleRefresh}"
244 ?disabled="${this.loading}"
245 title="Refresh commit list"
246 >
247 🔄 Refresh
248 </button>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700249 `;
250 }
251
252 renderRangeSelectors() {
253 return html`
254 <div class="commit-selector">
255 <label for="fromCommit">From:</label>
256 <select
257 id="fromCommit"
258 .value=${this.fromCommit}
259 @change=${this.handleFromChange}
260 >
261 ${this.commits.map(
Autoformatter8c463622025-05-16 21:54:17 +0000262 (commit) => html`
263 <option
264 value=${commit.hash}
265 ?selected=${commit.hash === this.fromCommit}
266 >
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700267 ${this.formatCommitOption(commit)}
268 </option>
Autoformatter8c463622025-05-16 21:54:17 +0000269 `,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700270 )}
271 </select>
272 </div>
273 <div class="commit-selector">
274 <label for="toCommit">To:</label>
275 <select
276 id="toCommit"
277 .value=${this.toCommit}
278 @change=${this.handleToChange}
279 >
Autoformatter8c463622025-05-16 21:54:17 +0000280 <option value="" ?selected=${this.toCommit === ""}>
281 Uncommitted Changes
282 </option>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700283 ${this.commits.map(
Autoformatter8c463622025-05-16 21:54:17 +0000284 (commit) => html`
285 <option
286 value=${commit.hash}
287 ?selected=${commit.hash === this.toCommit}
288 >
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700289 ${this.formatCommitOption(commit)}
290 </option>
Autoformatter8c463622025-05-16 21:54:17 +0000291 `,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700292 )}
293 </select>
294 </div>
295 `;
296 }
297
298 renderSingleSelector() {
299 return html`
300 <div class="commit-selector">
301 <label for="singleCommit">Commit:</label>
302 <select
303 id="singleCommit"
304 .value=${this.singleCommit}
305 @change=${this.handleSingleChange}
306 >
307 ${this.commits.map(
Autoformatter8c463622025-05-16 21:54:17 +0000308 (commit) => html`
309 <option
310 value=${commit.hash}
311 ?selected=${commit.hash === this.singleCommit}
312 >
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700313 ${this.formatCommitOption(commit)}
314 </option>
Autoformatter8c463622025-05-16 21:54:17 +0000315 `,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700316 )}
317 </select>
318 </div>
319 `;
320 }
321
322 /**
323 * Format a commit for display in the dropdown
324 */
325 formatCommitOption(commit: GitLogEntry): string {
326 const shortHash = commit.hash.substring(0, 7);
327 let label = `${shortHash} ${commit.subject}`;
Autoformatter8c463622025-05-16 21:54:17 +0000328
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700329 if (commit.refs && commit.refs.length > 0) {
Autoformatter8c463622025-05-16 21:54:17 +0000330 label += ` (${commit.refs.join(", ")})`;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700331 }
Autoformatter8c463622025-05-16 21:54:17 +0000332
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700333 return label;
334 }
335
336 /**
337 * Load commits from the Git data service
338 */
339 async loadCommits() {
340 this.loading = true;
341 this.error = null;
342
343 if (!this.gitService) {
Autoformatter8c463622025-05-16 21:54:17 +0000344 console.error("GitService was not provided to sketch-diff-range-picker");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700345 throw Error();
346 }
347
348 try {
349 // Get the base commit reference
350 const baseCommitRef = await this.gitService.getBaseCommitRef();
Autoformatter8c463622025-05-16 21:54:17 +0000351
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700352 // Load commit history
353 this.commits = await this.gitService.getCommitHistory(baseCommitRef);
Autoformatter8c463622025-05-16 21:54:17 +0000354
David Crawshaw938d2dc2025-06-14 22:17:33 +0000355 // Check if we should initialize from URL parameters first
356 const initializedFromUrl = this.initializeFromUrlParams();
357
358 // Set default selections only if not initialized from URL
359 if (this.commits.length > 0 && !initializedFromUrl) {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700360 // For range, default is base to HEAD
361 // TODO: is sketch-base right in the unsafe context, where it's sketch-base-...
362 // should this be startswith?
Autoformatter8c463622025-05-16 21:54:17 +0000363 const baseCommit = this.commits.find(
364 (c) => c.refs && c.refs.some((ref) => ref.includes("sketch-base")),
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700365 );
Autoformatter8c463622025-05-16 21:54:17 +0000366
367 this.fromCommit = baseCommit
368 ? baseCommit.hash
369 : this.commits[this.commits.length - 1].hash;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700370 // Default to Uncommitted Changes by setting toCommit to empty string
Autoformatter8c463622025-05-16 21:54:17 +0000371 this.toCommit = ""; // Empty string represents uncommitted changes
372
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700373 // For single, default to HEAD
374 this.singleCommit = this.commits[0].hash;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700375 }
David Crawshaw938d2dc2025-06-14 22:17:33 +0000376
377 // Always dispatch range event to ensure diff view is updated
378 this.dispatchRangeEvent();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700379 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000380 console.error("Error loading commits:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700381 this.error = `Error loading commits: ${error.message}`;
382 } finally {
383 this.loading = false;
384 }
385 }
386
387 /**
388 * Handle range type change
389 */
Autoformatter8c463622025-05-16 21:54:17 +0000390 setRangeType(type: "range" | "single") {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700391 this.rangeType = type;
David Crawshaw938d2dc2025-06-14 22:17:33 +0000392
393 // If switching to range mode and we don't have valid commits set,
394 // initialize with sensible defaults
395 if (type === 'range' && (!this.fromCommit || !this.toCommit === undefined)) {
396 if (this.commits.length > 0) {
397 const baseCommit = this.commits.find(
398 (c) => c.refs && c.refs.some((ref) => ref.includes("sketch-base")),
399 );
400 if (!this.fromCommit) {
401 this.fromCommit = baseCommit
402 ? baseCommit.hash
403 : this.commits[this.commits.length - 1].hash;
404 }
405 if (this.toCommit === undefined) {
406 this.toCommit = ''; // Default to uncommitted changes
407 }
408 }
409 }
410
411 // If switching to single mode and we don't have a valid commit set,
412 // initialize with HEAD
413 if (type === 'single' && !this.singleCommit && this.commits.length > 0) {
414 this.singleCommit = this.commits[0].hash;
415 }
416
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700417 this.dispatchRangeEvent();
418 }
419
420 /**
421 * Handle From commit change
422 */
423 handleFromChange(event: Event) {
424 const select = event.target as HTMLSelectElement;
425 this.fromCommit = select.value;
426 this.dispatchRangeEvent();
427 }
428
429 /**
430 * Handle To commit change
431 */
432 handleToChange(event: Event) {
433 const select = event.target as HTMLSelectElement;
434 this.toCommit = select.value;
435 this.dispatchRangeEvent();
436 }
437
438 /**
439 * Handle Single commit change
440 */
441 handleSingleChange(event: Event) {
442 const select = event.target as HTMLSelectElement;
443 this.singleCommit = select.value;
444 this.dispatchRangeEvent();
445 }
446
447 /**
Philip Zeyligere89b3082025-05-29 03:16:06 +0000448 * Handle refresh button click
449 */
450 handleRefresh() {
451 this.loadCommits();
452 }
453
454 /**
David Crawshaw938d2dc2025-06-14 22:17:33 +0000455 * Validate that a commit hash exists in the loaded commits
456 */
457 private isValidCommitHash(hash: string): boolean {
458 if (!hash || hash.trim() === '') return true; // Empty is valid (uncommitted changes)
459 return this.commits.some(commit => commit.hash.startsWith(hash) || commit.hash === hash);
460 }
461
462 /**
463 * Dispatch range change event and update URL parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700464 */
465 dispatchRangeEvent() {
Autoformatter8c463622025-05-16 21:54:17 +0000466 const range: DiffRange =
467 this.rangeType === "range"
468 ? { type: "range", from: this.fromCommit, to: this.toCommit }
469 : { type: "single", commit: this.singleCommit };
470
David Crawshaw938d2dc2025-06-14 22:17:33 +0000471 // Update URL parameters
472 this.updateUrlParams(range);
473
Autoformatter8c463622025-05-16 21:54:17 +0000474 const event = new CustomEvent("range-change", {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700475 detail: { range },
476 bubbles: true,
Autoformatter8c463622025-05-16 21:54:17 +0000477 composed: true,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700478 });
Autoformatter8c463622025-05-16 21:54:17 +0000479
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700480 this.dispatchEvent(event);
481 }
David Crawshaw938d2dc2025-06-14 22:17:33 +0000482
483 /**
484 * Update URL parameters for from and to commits
485 */
486 private updateUrlParams(range: DiffRange) {
487 const url = new URL(window.location.href);
488
489 // Remove existing range parameters
490 url.searchParams.delete('from');
491 url.searchParams.delete('to');
492 url.searchParams.delete('commit');
493
494 if (range.type === 'range') {
495 // Add from parameter if not empty
496 if (range.from && range.from.trim() !== '') {
497 url.searchParams.set('from', range.from);
498 }
499 // Add to parameter if not empty (empty string means uncommitted changes)
500 if (range.to && range.to.trim() !== '') {
501 url.searchParams.set('to', range.to);
502 }
503 } else {
504 // Single commit mode
505 if (range.commit && range.commit.trim() !== '') {
506 url.searchParams.set('commit', range.commit);
507 }
508 }
509
510 // Update the browser history without reloading the page
511 window.history.replaceState(window.history.state, '', url.toString());
512 }
513
514 /**
515 * Initialize from URL parameters if available
516 */
517 private initializeFromUrlParams() {
518 const url = new URL(window.location.href);
519 const fromParam = url.searchParams.get('from');
520 const toParam = url.searchParams.get('to');
521 const commitParam = url.searchParams.get('commit');
522
523 // If commit parameter is present, switch to single commit mode
524 if (commitParam) {
525 this.rangeType = 'single';
526 this.singleCommit = commitParam;
527 return true; // Indicate that we initialized from URL
528 }
529
530 // If from or to parameters are present, use range mode
531 if (fromParam || toParam) {
532 this.rangeType = 'range';
533 if (fromParam) {
534 this.fromCommit = fromParam;
535 }
536 if (toParam) {
537 this.toCommit = toParam;
538 } else {
539 // If no 'to' param, default to uncommitted changes (empty string)
540 this.toCommit = '';
541 }
542 return true; // Indicate that we initialized from URL
543 }
544
545 return false; // No URL params found
546 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700547}
548
549declare global {
550 interface HTMLElementTagNameMap {
551 "sketch-diff-range-picker": SketchDiffRangePicker;
552 }
553}