blob: c62078c48980ef851899bbc95f55a9550bc4e9b5 [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 */
David Crawshaw216d2fc2025-06-15 18:45:53 +000012export type DiffRange = { type: "range"; from: string; to: string };
Philip Zeyliger272a90e2025-05-16 14:49:51 -070013
14/**
15 * Component for selecting commit range for diffs
16 */
17@customElement("sketch-diff-range-picker")
18export class SketchDiffRangePicker extends LitElement {
19 @property({ type: Array })
20 commits: GitLogEntry[] = [];
21
22 @state()
Autoformatter8c463622025-05-16 21:54:17 +000023 private fromCommit: string = "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070024
25 @state()
Autoformatter8c463622025-05-16 21:54:17 +000026 private toCommit: string = "";
Philip Zeyliger272a90e2025-05-16 14:49:51 -070027
28 @state()
David Crawshaw216d2fc2025-06-15 18:45:53 +000029 private commitsExpanded: boolean = false;
Philip Zeyliger272a90e2025-05-16 14:49:51 -070030
31 @state()
32 private loading: boolean = true;
33
34 @state()
35 private error: string | null = null;
Autoformatter8c463622025-05-16 21:54:17 +000036
Philip Zeyliger272a90e2025-05-16 14:49:51 -070037 @property({ attribute: false, type: Object })
38 gitService!: GitDataService;
Autoformatter8c463622025-05-16 21:54:17 +000039
Philip Zeyliger272a90e2025-05-16 14:49:51 -070040 constructor() {
41 super();
Autoformatter8c463622025-05-16 21:54:17 +000042 console.log("SketchDiffRangePicker initialized");
Philip Zeyliger272a90e2025-05-16 14:49:51 -070043 }
44
45 static styles = css`
46 :host {
47 display: block;
48 width: 100%;
49 font-family: var(--font-family, system-ui, sans-serif);
50 color: var(--text-color, #333);
51 }
52
53 .range-picker {
54 display: flex;
David Crawshaw216d2fc2025-06-15 18:45:53 +000055 flex-direction: column;
Philip Zeyliger272a90e2025-05-16 14:49:51 -070056 gap: 12px;
Philip Zeyliger272a90e2025-05-16 14:49:51 -070057 width: 100%;
58 box-sizing: border-box;
59 }
60
David Crawshaw216d2fc2025-06-15 18:45:53 +000061 .commits-header {
Philip Zeyliger272a90e2025-05-16 14:49:51 -070062 display: flex;
63 align-items: center;
David Crawshaw216d2fc2025-06-15 18:45:53 +000064 width: 100%;
Philip Zeyliger272a90e2025-05-16 14:49:51 -070065 }
66
David Crawshaw216d2fc2025-06-15 18:45:53 +000067 .commits-toggle {
68 background-color: transparent;
69 border: 1px solid var(--border-color, #e0e0e0);
70 border-radius: 4px;
71 padding: 8px 12px;
72 cursor: pointer;
73 font-size: 14px;
74 font-weight: 500;
75 transition: background-color 0.2s;
76 display: flex;
77 align-items: center;
78 gap: 8px;
79 color: var(--text-color, #333);
80 }
81
82 .commits-toggle:hover {
83 background-color: var(--background-hover, #e8e8e8);
84 }
85
Philip Zeyliger272a90e2025-05-16 14:49:51 -070086 .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
Philip Zeyligere89b3082025-05-29 03:16:06 +0000132
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700133 @media (max-width: 768px) {
134 .commit-selector {
135 max-width: 100%;
136 }
137 }
138 `;
139
140 connectedCallback() {
141 super.connectedCallback();
142 // Wait for DOM to be fully loaded to ensure proper initialization order
Autoformatter8c463622025-05-16 21:54:17 +0000143 if (document.readyState === "complete") {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700144 this.loadCommits();
145 } else {
Autoformatter8c463622025-05-16 21:54:17 +0000146 window.addEventListener("load", () => {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700147 setTimeout(() => this.loadCommits(), 0); // Give time for provider initialization
148 });
149 }
Autoformatter9abf8032025-06-14 23:24:08 +0000150
David Crawshaw938d2dc2025-06-14 22:17:33 +0000151 // Listen for popstate events to handle browser back/forward navigation
Autoformatter9abf8032025-06-14 23:24:08 +0000152 window.addEventListener("popstate", this.handlePopState.bind(this));
David Crawshaw938d2dc2025-06-14 22:17:33 +0000153 }
154
155 disconnectedCallback() {
156 super.disconnectedCallback();
Autoformatter9abf8032025-06-14 23:24:08 +0000157 window.removeEventListener("popstate", this.handlePopState.bind(this));
David Crawshaw938d2dc2025-06-14 22:17:33 +0000158 }
159
160 /**
161 * Handle browser back/forward navigation
162 */
163 private handlePopState() {
164 // Re-initialize from URL parameters when user navigates
165 if (this.commits.length > 0) {
166 const initializedFromUrl = this.initializeFromUrlParams();
167 if (initializedFromUrl) {
168 // Force re-render and dispatch event
169 this.requestUpdate();
170 this.dispatchRangeEvent();
171 }
172 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700173 }
174
175 render() {
176 return html`
177 <div class="range-picker">
178 ${this.loading
179 ? html`<div class="loading">Loading commits...</div>`
180 : this.error
Autoformatter8c463622025-05-16 21:54:17 +0000181 ? html`<div class="error">${this.error}</div>`
182 : this.renderRangePicker()}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700183 </div>
184 `;
185 }
186
187 renderRangePicker() {
188 return html`
David Crawshaw216d2fc2025-06-15 18:45:53 +0000189 <div class="commits-header">
190 <button
191 class="commits-toggle"
192 @click="${this.toggleCommitsExpansion}"
193 title="${this.commitsExpanded ? 'Hide' : 'Show'} commit range selection"
194 >
195 ${this.commitsExpanded ? 'â–¼' : 'â–¶'} Commits
196 </button>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700197 </div>
David Crawshaw216d2fc2025-06-15 18:45:53 +0000198
199 ${this.commitsExpanded
200 ? html`
201 <div class="commit-selectors">
202 ${this.renderRangeSelectors()}
203 </div>
204 `
205 : ''}
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700206 `;
207 }
208
209 renderRangeSelectors() {
210 return html`
211 <div class="commit-selector">
212 <label for="fromCommit">From:</label>
213 <select
214 id="fromCommit"
215 .value=${this.fromCommit}
216 @change=${this.handleFromChange}
217 >
218 ${this.commits.map(
Autoformatter8c463622025-05-16 21:54:17 +0000219 (commit) => html`
220 <option
221 value=${commit.hash}
222 ?selected=${commit.hash === this.fromCommit}
223 >
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700224 ${this.formatCommitOption(commit)}
225 </option>
Autoformatter8c463622025-05-16 21:54:17 +0000226 `,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700227 )}
228 </select>
229 </div>
230 <div class="commit-selector">
231 <label for="toCommit">To:</label>
232 <select
233 id="toCommit"
234 .value=${this.toCommit}
235 @change=${this.handleToChange}
236 >
Autoformatter8c463622025-05-16 21:54:17 +0000237 <option value="" ?selected=${this.toCommit === ""}>
238 Uncommitted Changes
239 </option>
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700240 ${this.commits.map(
Autoformatter8c463622025-05-16 21:54:17 +0000241 (commit) => html`
242 <option
243 value=${commit.hash}
244 ?selected=${commit.hash === this.toCommit}
245 >
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700246 ${this.formatCommitOption(commit)}
247 </option>
Autoformatter8c463622025-05-16 21:54:17 +0000248 `,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700249 )}
250 </select>
251 </div>
252 `;
253 }
254
David Crawshaw216d2fc2025-06-15 18:45:53 +0000255
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700256
257 /**
258 * Format a commit for display in the dropdown
259 */
260 formatCommitOption(commit: GitLogEntry): string {
261 const shortHash = commit.hash.substring(0, 7);
Autoformatter8c463622025-05-16 21:54:17 +0000262
David Crawshawdbca8972025-06-14 23:46:58 +0000263 // Truncate subject if it's too long
264 let subject = commit.subject;
265 if (subject.length > 50) {
266 subject = subject.substring(0, 47) + "...";
267 }
268
269 let label = `${shortHash} ${subject}`;
270
271 // Add refs but keep them concise
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700272 if (commit.refs && commit.refs.length > 0) {
David Crawshawdbca8972025-06-14 23:46:58 +0000273 const refs = commit.refs.map((ref) => {
274 // Shorten common prefixes
275 if (ref.startsWith("origin/")) {
276 return ref.substring(7);
277 }
278 if (ref.startsWith("refs/heads/")) {
279 return ref.substring(11);
280 }
281 if (ref.startsWith("refs/remotes/origin/")) {
282 return ref.substring(20);
283 }
284 return ref;
285 });
286
287 // Limit to first 2 refs to avoid overcrowding
288 const displayRefs = refs.slice(0, 2);
289 if (refs.length > 2) {
290 displayRefs.push(`+${refs.length - 2} more`);
291 }
292
293 label += ` (${displayRefs.join(", ")})`;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700294 }
Autoformatter8c463622025-05-16 21:54:17 +0000295
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700296 return label;
297 }
298
299 /**
300 * Load commits from the Git data service
301 */
302 async loadCommits() {
303 this.loading = true;
304 this.error = null;
305
306 if (!this.gitService) {
Autoformatter8c463622025-05-16 21:54:17 +0000307 console.error("GitService was not provided to sketch-diff-range-picker");
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700308 throw Error();
309 }
310
311 try {
312 // Get the base commit reference
313 const baseCommitRef = await this.gitService.getBaseCommitRef();
Autoformatter8c463622025-05-16 21:54:17 +0000314
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700315 // Load commit history
316 this.commits = await this.gitService.getCommitHistory(baseCommitRef);
Autoformatter8c463622025-05-16 21:54:17 +0000317
David Crawshaw938d2dc2025-06-14 22:17:33 +0000318 // Check if we should initialize from URL parameters first
319 const initializedFromUrl = this.initializeFromUrlParams();
Autoformatter9abf8032025-06-14 23:24:08 +0000320
David Crawshaw938d2dc2025-06-14 22:17:33 +0000321 // Set default selections only if not initialized from URL
322 if (this.commits.length > 0 && !initializedFromUrl) {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700323 // For range, default is base to HEAD
324 // TODO: is sketch-base right in the unsafe context, where it's sketch-base-...
325 // should this be startswith?
Autoformatter8c463622025-05-16 21:54:17 +0000326 const baseCommit = this.commits.find(
327 (c) => c.refs && c.refs.some((ref) => ref.includes("sketch-base")),
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700328 );
Autoformatter8c463622025-05-16 21:54:17 +0000329
330 this.fromCommit = baseCommit
331 ? baseCommit.hash
332 : this.commits[this.commits.length - 1].hash;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700333 // Default to Uncommitted Changes by setting toCommit to empty string
Autoformatter8c463622025-05-16 21:54:17 +0000334 this.toCommit = ""; // Empty string represents uncommitted changes
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700335 }
Autoformatter9abf8032025-06-14 23:24:08 +0000336
David Crawshaw938d2dc2025-06-14 22:17:33 +0000337 // Always dispatch range event to ensure diff view is updated
338 this.dispatchRangeEvent();
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700339 } catch (error) {
Autoformatter8c463622025-05-16 21:54:17 +0000340 console.error("Error loading commits:", error);
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700341 this.error = `Error loading commits: ${error.message}`;
342 } finally {
343 this.loading = false;
344 }
345 }
346
Autoformatter9abf8032025-06-14 23:24:08 +0000347
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700348
349 /**
350 * Handle From commit change
351 */
352 handleFromChange(event: Event) {
353 const select = event.target as HTMLSelectElement;
354 this.fromCommit = select.value;
355 this.dispatchRangeEvent();
356 }
357
358 /**
359 * Handle To commit change
360 */
361 handleToChange(event: Event) {
362 const select = event.target as HTMLSelectElement;
363 this.toCommit = select.value;
364 this.dispatchRangeEvent();
365 }
366
367 /**
David Crawshaw216d2fc2025-06-15 18:45:53 +0000368 * Toggle the expansion of commit selectors
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700369 */
David Crawshaw216d2fc2025-06-15 18:45:53 +0000370 toggleCommitsExpansion() {
371 this.commitsExpanded = !this.commitsExpanded;
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700372 }
373
374 /**
David Crawshaw216d2fc2025-06-15 18:45:53 +0000375 * Get a summary of the current commit range for display
Philip Zeyligere89b3082025-05-29 03:16:06 +0000376 */
David Crawshaw216d2fc2025-06-15 18:45:53 +0000377 getCommitSummary(): string {
378 if (!this.fromCommit && !this.toCommit) {
379 return 'No commits selected';
380 }
381
382 const fromShort = this.fromCommit ? this.fromCommit.substring(0, 7) : '';
383 const toShort = this.toCommit ? this.toCommit.substring(0, 7) : 'Uncommitted';
384
385 return `${fromShort}..${toShort}`;
Philip Zeyligere89b3082025-05-29 03:16:06 +0000386 }
387
David Crawshaw216d2fc2025-06-15 18:45:53 +0000388
389
390
391
Philip Zeyligere89b3082025-05-29 03:16:06 +0000392 /**
David Crawshaw938d2dc2025-06-14 22:17:33 +0000393 * Validate that a commit hash exists in the loaded commits
394 */
395 private isValidCommitHash(hash: string): boolean {
Autoformatter9abf8032025-06-14 23:24:08 +0000396 if (!hash || hash.trim() === "") return true; // Empty is valid (uncommitted changes)
397 return this.commits.some(
398 (commit) => commit.hash.startsWith(hash) || commit.hash === hash,
399 );
David Crawshaw938d2dc2025-06-14 22:17:33 +0000400 }
401
402 /**
403 * Dispatch range change event and update URL parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700404 */
405 dispatchRangeEvent() {
David Crawshaw216d2fc2025-06-15 18:45:53 +0000406 const range: DiffRange = { type: "range", from: this.fromCommit, to: this.toCommit };
Autoformatter8c463622025-05-16 21:54:17 +0000407
David Crawshaw938d2dc2025-06-14 22:17:33 +0000408 // Update URL parameters
409 this.updateUrlParams(range);
410
Autoformatter8c463622025-05-16 21:54:17 +0000411 const event = new CustomEvent("range-change", {
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700412 detail: { range },
413 bubbles: true,
Autoformatter8c463622025-05-16 21:54:17 +0000414 composed: true,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700415 });
Autoformatter8c463622025-05-16 21:54:17 +0000416
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700417 this.dispatchEvent(event);
418 }
David Crawshaw938d2dc2025-06-14 22:17:33 +0000419
420 /**
421 * Update URL parameters for from and to commits
422 */
423 private updateUrlParams(range: DiffRange) {
424 const url = new URL(window.location.href);
Autoformatter9abf8032025-06-14 23:24:08 +0000425
David Crawshaw938d2dc2025-06-14 22:17:33 +0000426 // Remove existing range parameters
Autoformatter9abf8032025-06-14 23:24:08 +0000427 url.searchParams.delete("from");
428 url.searchParams.delete("to");
429 url.searchParams.delete("commit");
430
David Crawshaw216d2fc2025-06-15 18:45:53 +0000431 // Add from parameter if not empty
432 if (range.from && range.from.trim() !== "") {
433 url.searchParams.set("from", range.from);
434 }
435 // Add to parameter if not empty (empty string means uncommitted changes)
436 if (range.to && range.to.trim() !== "") {
437 url.searchParams.set("to", range.to);
David Crawshaw938d2dc2025-06-14 22:17:33 +0000438 }
Autoformatter9abf8032025-06-14 23:24:08 +0000439
David Crawshaw938d2dc2025-06-14 22:17:33 +0000440 // Update the browser history without reloading the page
Autoformatter9abf8032025-06-14 23:24:08 +0000441 window.history.replaceState(window.history.state, "", url.toString());
David Crawshaw938d2dc2025-06-14 22:17:33 +0000442 }
443
444 /**
445 * Initialize from URL parameters if available
446 */
447 private initializeFromUrlParams() {
448 const url = new URL(window.location.href);
Autoformatter9abf8032025-06-14 23:24:08 +0000449 const fromParam = url.searchParams.get("from");
450 const toParam = url.searchParams.get("to");
Autoformatter9abf8032025-06-14 23:24:08 +0000451
David Crawshaw216d2fc2025-06-15 18:45:53 +0000452 // If from or to parameters are present, use them
David Crawshaw938d2dc2025-06-14 22:17:33 +0000453 if (fromParam || toParam) {
David Crawshaw938d2dc2025-06-14 22:17:33 +0000454 if (fromParam) {
455 this.fromCommit = fromParam;
456 }
457 if (toParam) {
458 this.toCommit = toParam;
459 } else {
460 // If no 'to' param, default to uncommitted changes (empty string)
Autoformatter9abf8032025-06-14 23:24:08 +0000461 this.toCommit = "";
David Crawshaw938d2dc2025-06-14 22:17:33 +0000462 }
463 return true; // Indicate that we initialized from URL
464 }
Autoformatter9abf8032025-06-14 23:24:08 +0000465
David Crawshaw938d2dc2025-06-14 22:17:33 +0000466 return false; // No URL params found
467 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700468}
469
470declare global {
471 interface HTMLElementTagNameMap {
472 "sketch-diff-range-picker": SketchDiffRangePicker;
473 }
474}