Add Monaco diff-view, the saga ...
I set out to use Monaco to support the diff view. diff2html is lovely,
but there were a ton of usability improvements I wanted to make (line
numbers not making things double spaced, choosing which diff, editing
the right-hand side), and it seemed a dead end. Furthermore, Phabricator
and Gerrit's experience is that diffs should be shown file by file,
because you'll inevitably see a diff with a file that's too large, and
the GitHub PR view often breaks on big changes... so I wanted to show
files diff-by-diff, with "infinite" context when unchanged sections are
expanded. So...
Ultimately, all of this was sketch-coded over maybe 30 Sketch sessions.
I threw away a lot of branches. My git reflog is a superfund site.
Prompting whole-hog didn't work. Or, rather, it made significant
progress, but something very serious wouldn't work, and I couldn't
figure out what, and nor could Sketch.
Instead, I started by adding a new webcomponent that was just a
placeholder. Then, using https://rodydavis.com/posts/lit-monaco-editor,
I nudged Sketch into adding Monaco to it. Sketch pulled out:
You're right, I should properly read the blog post before implementing the
solution. Let me check the referenced blog post.
I worked heavily in the demo environment at first, but here I ran into
the issue that we have two different esbuild systems: one is vite and
one is esbuild.go, and they're configured differently enough.
Monaco is unusable and confusingly so when its CSS isn't loaded. The right
way to load it, I've found, is via
@import url('./static/monaco/min/vs/editor/editor.main.css');
I spent more time than I care to admit noticing that originally
this wasn't relative, and when we use a skaband setting, the
paths need to be relative-aware.
The paths to the various workers need to be similarly correctly placed.
Getting Sketch to build demo data but not put testing code into production
code was tricky. (I threw away a lot of efforts and factories and singletons...)
When I set out to do the git commit selection, I wanted to do a bunch of
backend /git/* handlers. These were easy enough to code in sketch. I had
to convince Sketch to put them in git_tools.go and not in the agent.
It doesn't really matter: these functions to parse git are pretty stateless,
but it's less work to have them separate. Sketch was mediocre at writing
tests for them. Did you know that our container has an older version
of git that doesn't have the same options to decorate ref names? Yeah, nor did
I.
Handling unstaged changes was fun. git diff --raw shows unstaged files
as having identity 0000. Ideally we'd be using jj and there'd be
a synthetic commit, but instead uncommitted-possible files are read
by content.
A real big challenge was getting the Monaco view to use the right vertical and
horizontal space. I did this many, many times. I don't claim to understand flex
and the virtual dom, and :host, and all the interactions. It would fix one
thing and break another. The chat window would shrink. The terminal would
shrink.
Screenshot support was excellent. I eventually added paste support just so
that I could expedite my workflow, and Sketch coded that easily on the first
pass with minor feedback.
I learned the hard way that Safari's support for WebComponents/shadow
dom in its web inspector is rough. See https://fediverse.zachleat.com/@zachleat/114518629612122858
I also learned the hard way that Chrome doesn't use fonts loaded in CSS
in a shadow dom. That's why the codicon font had to be in the global
style sheet.
Kudos to John Reese who kindly allowed me, a long time ago, to adapt a
shell script he had at work to look over diffs into https://github.com/philz/git-vimdiff.
That's the inspiration for having the "new code" be editable when you're
reviewing it; why shouldn't it be!?!
There are a handful of follow up tasks:
* We lose state when we switch to the Chat view and back.
* Need URL-based support for where we are.
* Maybe need shortcut keys to move between diffs and changes.
* Maybe need caching or look-ahead for downloading the next or previous
file.
* We spend too much vertical real estate on all the diff selections;
could we scroll it out of the way, collapse it, tighten it, etc.
* The workers sometimes throw errors into the console. I think they're
harmless and merely need to be caught and suppressed.
* Needing to commit changes when things are saved is weird. Should we
commit automatically? Amend the previous commit? Have a button for
that? Show the git dirty state?
* Our JS bundle is big. We could maybe delay loading the monaco bundle
to help.
Thanks for coming to my TED talk.
diff --git a/webui/src/web-components/git-data-service.ts b/webui/src/web-components/git-data-service.ts
new file mode 100644
index 0000000..c22b851
--- /dev/null
+++ b/webui/src/web-components/git-data-service.ts
@@ -0,0 +1,220 @@
+// git-data-service.ts
+// Interface and implementation for fetching Git data
+
+import { DiffFile, GitLogEntry } from '../types';
+
+// Re-export DiffFile as GitDiffFile
+export type GitDiffFile = DiffFile;
+
+/**
+ * Interface for Git data services
+ */
+export interface GitDataService {
+ /**
+ * Fetches recent commit history
+ * @param initialCommit The initial commit hash to start from
+ * @returns List of commits
+ */
+ getCommitHistory(initialCommit?: string): Promise<GitLogEntry[]>;
+
+ /**
+ * Fetches diff between two commits
+ * @param from Starting commit hash
+ * @param to Ending commit hash (can be empty string for unstaged changes)
+ * @returns List of changed files
+ */
+ getDiff(from: string, to: string): Promise<GitDiffFile[]>;
+
+ /**
+ * Fetches diff for a single commit
+ * @param commit Commit hash
+ * @returns List of changed files
+ */
+ getCommitDiff(commit: string): Promise<GitDiffFile[]>;
+
+ /**
+ * Fetches file content from git using a file hash
+ * @param fileHash Git blob hash of the file to fetch
+ * @returns File content as string
+ */
+ getFileContent(fileHash: string): Promise<string>;
+
+ /**
+ * Gets file content from the current working directory
+ * @param filePath Path to the file within the repository
+ * @returns File content as string
+ */
+ getWorkingCopyContent(filePath: string): Promise<string>;
+
+ /**
+ * Saves file content to the working directory
+ * @param filePath Path to the file within the repository
+ * @param content New content to save to the file
+ */
+ saveFileContent(filePath: string, content: string): Promise<void>;
+
+ /**
+ * Gets the base commit reference (often "sketch-base")
+ * @returns Base commit reference
+ */
+ getBaseCommitRef(): Promise<string>;
+
+ /**
+ * Fetches unstaged changes (diff between a commit and working directory)
+ * @param from Starting commit hash (defaults to HEAD if not specified)
+ * @returns List of changed files
+ */
+ getUnstagedChanges(from?: string): Promise<GitDiffFile[]>;
+}
+
+/**
+ * Default implementation of GitDataService for the real application
+ */
+export class DefaultGitDataService implements GitDataService {
+ private baseCommitRef: string | null = null;
+
+ async getCommitHistory(initialCommit?: string): Promise<GitLogEntry[]> {
+ try {
+ const url = initialCommit
+ ? `git/recentlog?initialCommit=${encodeURIComponent(initialCommit)}`
+ : 'git/recentlog';
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch commit history: ${response.statusText}`);
+ }
+
+ return await response.json();
+ } catch (error) {
+ console.error('Error fetching commit history:', error);
+ throw error;
+ }
+ }
+
+ async getDiff(from: string, to: string): Promise<GitDiffFile[]> {
+ try {
+ const url = `git/rawdiff?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch diff: ${response.statusText}`);
+ }
+
+ return await response.json();
+ } catch (error) {
+ console.error('Error fetching diff:', error);
+ throw error;
+ }
+ }
+
+ async getCommitDiff(commit: string): Promise<GitDiffFile[]> {
+ try {
+ const url = `git/rawdiff?commit=${encodeURIComponent(commit)}`;
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch commit diff: ${response.statusText}`);
+ }
+
+ return await response.json();
+ } catch (error) {
+ console.error('Error fetching commit diff:', error);
+ throw error;
+ }
+ }
+
+ async getFileContent(fileHash: string): Promise<string> {
+ try {
+ // If the hash is marked as a working copy (special value '000000' or empty)
+ if (fileHash === '0000000000000000000000000000000000000000' || !fileHash) {
+ // This shouldn't happen, but if it does, return empty string
+ // Working copy content should be fetched through getWorkingCopyContent
+ console.warn('Invalid file hash for getFileContent, returning empty string');
+ return '';
+ }
+
+ const url = `git/show?hash=${encodeURIComponent(fileHash)}`;
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch file content: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ return data.output || '';
+ } catch (error) {
+ console.error('Error fetching file content:', error);
+ throw error;
+ }
+ }
+
+ async getWorkingCopyContent(filePath: string): Promise<string> {
+ try {
+ const url = `git/cat?path=${encodeURIComponent(filePath)}`;
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch working copy content: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ return data.output || '';
+ } catch (error) {
+ console.error('Error fetching working copy content:', error);
+ throw error;
+ }
+ }
+
+ async saveFileContent(filePath: string, content: string): Promise<void> {
+ try {
+ const url = `git/save`;
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ path: filePath,
+ content: content
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Failed to save file content: ${response.statusText} - ${errorText}`);
+ }
+
+ // Don't need to return the response, just ensure it was successful
+ } catch (error) {
+ console.error('Error saving file content:', error);
+ throw error;
+ }
+ }
+
+ async getUnstagedChanges(from: string = 'HEAD'): Promise<GitDiffFile[]> {
+ try {
+ // To get unstaged changes, we diff the specified commit (or HEAD) with an empty 'to'
+ return await this.getDiff(from, '');
+ } catch (error) {
+ console.error('Error fetching unstaged changes:', error);
+ throw error;
+ }
+ }
+
+ async getBaseCommitRef(): Promise<string> {
+ // Cache the base commit reference to avoid multiple requests
+ if (this.baseCommitRef) {
+ return this.baseCommitRef;
+ }
+
+ try {
+ // This could be replaced with a specific endpoint call if available
+ // For now, we'll use a fixed value or try to get it from the server
+ this.baseCommitRef = 'sketch-base';
+ return this.baseCommitRef;
+ } catch (error) {
+ console.error('Error fetching base commit reference:', error);
+ throw error;
+ }
+ }
+}
\ No newline at end of file