-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathuseCodeMirror.ts
More file actions
244 lines (213 loc) · 6.93 KB
/
useCodeMirror.ts
File metadata and controls
244 lines (213 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import {
diff as defaultDiff,
MergeView,
unifiedMergeView,
} from "@codemirror/merge";
import { EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { workspaceApi } from "@features/workspace/hooks/useWorkspace";
import { trpcClient } from "@renderer/trpc/client";
import { handleExternalAppAction } from "@utils/handleExternalAppAction";
import { useEffect, useRef } from "react";
import { gradualCollapseUnchanged } from "./collapseUnchangedExtension";
type EditorInstance = EditorView | MergeView;
interface UseCodeMirrorOptions {
extensions: Extension[];
filePath?: string;
}
interface SingleDocOptions extends UseCodeMirrorOptions {
doc: string;
}
interface DiffOptions extends UseCodeMirrorOptions {
original: string;
modified: string;
mode: "split" | "unified";
loadFullFiles?: boolean;
wordDiffs?: boolean;
hideWhitespaceChanges?: boolean;
onContentChange?: (content: string) => void;
}
const createMergeControls = (onReject?: () => void) => {
return (type: "accept" | "reject", action: (e: MouseEvent) => void) => {
if (type === "accept") {
return document.createElement("span");
}
const button = document.createElement("button");
button.textContent = "\u21a9 Revert";
button.name = "reject";
button.style.background = "var(--red-9)";
button.style.color = "white";
button.style.border = "none";
button.style.padding = "4px 10px";
button.style.borderRadius = "4px";
button.style.cursor = "pointer";
button.style.fontSize = "11px";
button.style.fontWeight = "500";
button.style.lineHeight = "1";
button.onmouseenter = () => {
button.style.background = "var(--red-10)";
};
button.onmouseleave = () => {
button.style.background = "var(--red-9)";
};
button.onmousedown = (e) => {
action(e);
onReject?.();
};
return button;
};
};
const whitespaceIgnoringDiff = (a: string, b: string) => {
const changes = defaultDiff(a, b);
return changes.filter((change) => {
const textA = a.slice(change.fromA, change.toA);
const textB = b.slice(change.fromB, change.toB);
return textA.replace(/\s/g, "") !== textB.replace(/\s/g, "");
});
};
const collapseExtension = (loadFullFiles?: boolean): Extension =>
loadFullFiles ? [] : gradualCollapseUnchanged({ margin: 3, minSize: 4 });
const getBaseDiffConfig = (
hideWhitespaceChanges?: boolean,
onReject?: () => void,
): Partial<Parameters<typeof unifiedMergeView>[0]> => ({
highlightChanges: false,
gutter: true,
mergeControls: createMergeControls(onReject),
diffConfig: hideWhitespaceChanges
? { override: whitespaceIgnoringDiff }
: undefined,
});
export function useCodeMirror(options: SingleDocOptions | DiffOptions) {
const containerRef = useRef<HTMLDivElement>(null);
const instanceRef = useRef<EditorInstance | null>(null);
useEffect(() => {
if (!containerRef.current) return;
instanceRef.current?.destroy();
instanceRef.current = null;
if ("doc" in options) {
instanceRef.current = new EditorView({
state: EditorState.create({
doc: options.doc,
extensions: options.extensions,
}),
parent: containerRef.current,
});
} else if (options.mode === "split") {
const diffConfig = getBaseDiffConfig(
options.hideWhitespaceChanges,
options.onContentChange
? () => {
if (instanceRef.current instanceof MergeView) {
const content = instanceRef.current.b.state.doc.toString();
options.onContentChange?.(content);
}
}
: undefined,
);
const updateListener = options.onContentChange
? EditorView.updateListener.of((update) => {
if (
update.docChanged &&
update.transactions.some((tr) => tr.isUserEvent("revert"))
) {
const content = update.state.doc.toString();
options.onContentChange?.(content);
}
})
: [];
const collapse = collapseExtension(options.loadFullFiles);
instanceRef.current = new MergeView({
a: {
doc: options.original,
extensions: [
...options.extensions,
EditorView.editable.of(false),
EditorState.readOnly.of(true),
collapse,
],
},
b: {
doc: options.modified,
extensions: [
...options.extensions,
...(Array.isArray(updateListener)
? updateListener
: [updateListener]),
collapse,
],
},
...diffConfig,
parent: containerRef.current,
revertControls: "a-to-b",
});
} else {
const diffConfig = getBaseDiffConfig(
options.hideWhitespaceChanges,
options.onContentChange
? () => {
if (instanceRef.current instanceof EditorView) {
const content = instanceRef.current.state.doc.toString();
options.onContentChange?.(content);
}
}
: undefined,
);
instanceRef.current = new EditorView({
doc: options.modified,
extensions: [
...options.extensions,
unifiedMergeView({
original: options.original,
...diffConfig,
}),
collapseExtension(options.loadFullFiles),
],
parent: containerRef.current,
});
}
return () => {
instanceRef.current?.destroy();
instanceRef.current = null;
};
}, [options]);
useEffect(() => {
if (!instanceRef.current || !options.filePath) return;
const filePath = options.filePath;
const domElement =
instanceRef.current instanceof EditorView
? instanceRef.current.dom
: instanceRef.current.a.dom;
const handleContextMenu = async (e: MouseEvent) => {
e.preventDefault();
const result = await trpcClient.contextMenu.showFileContextMenu.mutate({
filePath,
});
if (!result.action) return;
if (result.action.type === "external-app") {
const fileName = filePath.split("/").pop() || "file";
const workspaces = await workspaceApi.getAll();
const workspace =
Object.values(workspaces).find(
(ws) =>
(ws?.worktreePath && filePath.startsWith(ws.worktreePath)) ||
(ws?.folderPath && filePath.startsWith(ws.folderPath)),
) ?? null;
await handleExternalAppAction(
result.action.action,
filePath,
fileName,
{
workspace,
mainRepoPath: workspace?.folderPath,
},
);
}
};
domElement.addEventListener("contextmenu", handleContextMenu);
return () => {
domElement.removeEventListener("contextmenu", handleContextMenu);
};
}, [options.filePath]);
return { containerRef, instanceRef };
}