Repository navigation
Expand file tree
/
Copy pathAddProjectToMachineDialog.tsx
More file actions
447 lines (425 loc) · 17.7 KB
/
Copy pathAddProjectToMachineDialog.tsx
File metadata and controls
447 lines (425 loc) · 17.7 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import { useParams } from "@tanstack/react-router";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import {
getAddProjectInitialQuery,
getCloneDestinationPath,
getCloneDirectoryPath,
} from "@t3tools/client-runtime/operations/projects";
import { resolvePastedPath } from "@t3tools/shared/path";
import {
type EnvironmentId,
type ProjectIgnoredFile,
type ScopedProjectRef,
resolveEnvironmentMachineKind,
} from "@t3tools/contracts";
import {
type CloneProtocol,
cloneUrlForProtocol,
cloneUrlProtocol,
} from "@t3tools/shared/cloneUrl";
import { ArrowRightIcon } from "lucide-react";
import { useId, useState } from "react";
import { create } from "zustand";
import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
import {
COPYABLE_FILE_MAX_BYTES,
addProjectToMachine,
isDefaultCopiedFile,
} from "../lib/addProjectToMachine";
import { formatBytes } from "../lib/formatBytes";
import { newProjectId } from "../lib/utils";
import { readProject, subscribeProject, useProject } from "../state/entities";
import { useEnvironments } from "../state/environments";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { Button } from "./ui/button";
import { Checkbox } from "./ui/checkbox";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { MiddleTruncate } from "./ui/middle-truncate";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import { Toggle, ToggleGroup } from "./ui/toggle-group";
interface AddProjectToMachineRequest {
readonly projectRef: ScopedProjectRef;
readonly targetEnvironmentId: EnvironmentId | null;
}
const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
request: null,
session: 0,
}));
let endRequestWithProject: (() => void) | null = null;
/** Opens the dialog that clones a project onto another connected machine. */
export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
if (readProject(request.projectRef) === null) return;
endRequestWithProject?.();
// The request ends when its project goes away, so a project that comes back
// later cannot reopen a dialog nobody asked for.
endRequestWithProject = subscribeProject(request.projectRef, (project) => {
if (project === null) close();
});
useRequest.setState((state) => ({ request, session: state.session + 1 }));
}
function close() {
endRequestWithProject?.();
endRequestWithProject = null;
useRequest.setState({ request: null });
}
export function AddProjectToMachineDialogHost() {
const request = useRequest((state) => state.request);
const session = useRequest((state) => state.session);
return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
}
function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
const id = useId();
const project = useProject(request.projectRef);
const handleNewThread = useNewThreadHandler();
const { draftId: routeDraftId } = useParams({ strict: false });
const { environments } = useEnvironments();
const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
const [targetId, setTargetId] = useState(request.targetEnvironmentId);
const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
const sourceUrl =
project?.repositoryIdentity?.origin?.remoteUrl ??
project?.repositoryIdentity?.locator.remoteUrl ??
"";
const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
const remoteUrl =
(protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
const defaultPath = getCloneDestinationPath(
getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
getCloneDirectoryPath(
sourceUrl,
targetEnvironment?.serverConfig?.settings.ghqCloneLayout === true,
),
);
const [pathOverride, setPathOverride] = useState<string | null>(null);
const destinationPath = pathOverride ?? defaultPath;
const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
const ignoredFiles = useEnvironmentQuery(
project && canListFiles
? projectEnvironment.listIgnoredFiles({
environmentId: project.environmentId,
input: { cwd: project.workspaceRoot },
})
: null,
);
const files = ignoredFiles.data?.files ?? [];
const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
const selectedFiles = selected ?? defaultSelection(files);
const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
const selectedBytes = files
.filter((file) => selectedFiles.has(file.path))
.reduce((total, file) => total + file.byteLength, 0);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// The project or every target can vanish while the dialog is open. Submitting
// before the file list loads would silently skip the default .env copies.
const unavailable =
project === null ||
target === null ||
(canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
const toggleFile = (path: string, checked: boolean) => {
const next = new Set(selectedFiles);
if (checked) next.add(path);
else next.delete(path);
setSelected(next);
};
// Lands the user on the new machine right away; its composer shows the clone
// and holds sends until it finishes. A draft open on the source project moves
// over with whatever was typed in it.
const openClonedProject = (targetRef: ScopedProjectRef) => {
const drafts = useComposerDraftStore.getState();
const draftId = routeDraftId as DraftId | undefined;
const draft = draftId ? drafts.getDraftSession(draftId) : null;
if (
draftId &&
draft &&
!draft.promotedTo &&
draft.environmentId === request.projectRef.environmentId &&
draft.projectId === request.projectRef.projectId
) {
drafts.setDraftThreadContext(draftId, {
projectRef: targetRef,
environmentSelection: "manual",
loadBalancedEnvironmentId: null,
});
return;
}
void handleNewThread(targetRef);
};
const submit = async () => {
if (!project || !target || submitting) return;
if (destinationPath.trim().length === 0) {
setError("Choose a folder on the other machine.");
return;
}
setSubmitting(true);
setError(null);
try {
const projectId = await addProjectToMachine({
source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
subdirectory: projectSubdirectory(
project.repositoryIdentity?.rootPath,
project.workspaceRoot,
),
target: { environmentId: target.environmentId, label: target.label },
projectId: newProjectId(),
title: project.title,
remoteUrl,
destinationPath: destinationPath.trim(),
files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
});
close();
openClonedProject(scopeProjectRef(target.environmentId, projectId));
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not start the clone.");
setSubmitting(false);
}
};
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) close();
}}
>
<DialogPopup className="sm:max-w-xl">
<form
className="flex min-h-0 flex-col"
onSubmit={(event) => {
event.preventDefault();
void submit();
}}
>
<DialogHeader>
<DialogTitle>Add to another machine</DialogTitle>
<DialogDescription>
Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
files git does not track.
</DialogDescription>
</DialogHeader>
<DialogPanel>
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
<div className="flex min-w-0 flex-col gap-1">
<span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
<EnvironmentMachineIcon
kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
className="size-3.5 shrink-0"
/>
<span className="truncate">{source?.label ?? "This machine"}</span>
</span>
<span className="flex min-w-0 font-mono text-muted-foreground text-xs">
<MiddleTruncate value={project?.workspaceRoot ?? ""} />
</span>
</div>
<div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
<span>git clone</span>
<span className="flex w-full items-center">
<span className="h-px flex-1 bg-border" />
<ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
</span>
<span>
{selectedFiles.size === 0
? "no files"
: `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
</span>
</div>
<div className="flex min-w-0 flex-col gap-1">
{targets.length > 1 ? (
<Select
value={target?.environmentId ?? null}
onValueChange={(value) => {
if (value) setTargetId(value);
}}
items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
>
<SelectTrigger size="sm" aria-label="Machine to add the project to">
{target ? (
<EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
) : null}
<SelectValue />
</SelectTrigger>
<SelectPopup>
{targets.map((t) => (
<SelectItem key={t.environmentId} value={t.environmentId}>
<span className="inline-flex items-center gap-1.5">
<EnvironmentMachineIcon kind={t.machine} className="size-3" />
{t.label}
</span>
</SelectItem>
))}
</SelectPopup>
</Select>
) : (
<span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
{target ? (
<EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
) : null}
<span className="truncate">{target?.label ?? "No machine available"}</span>
</span>
)}
<span className="flex min-w-0 font-mono text-muted-foreground text-xs">
<MiddleTruncate value={destinationPath} />
</span>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Clone over</Label>
{sshUrl && httpsUrl ? (
<ToggleGroup
aria-label="Clone protocol"
value={protocol ? [protocol] : []}
onValueChange={(next) => {
const value = next[0];
if (value === "ssh" || value === "https") setProtocol(value);
}}
>
<Toggle value="ssh">SSH</Toggle>
<Toggle value="https">HTTPS</Toggle>
</ToggleGroup>
) : null}
<span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
<Input
id={`${id}-path`}
value={destinationPath}
onChange={(event) =>
setPathOverride(resolvePastedPath(destinationPath, event.target.value))
}
spellCheck={false}
autoComplete="off"
/>
</div>
{canListFiles ? (
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-2">
<Label className="flex-1">Copy ignored files</Label>
{copyable.length > 0 ? (
<>
<span className="text-muted-foreground text-xs">
{selectedFiles.size} of {files.length}
{selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
</span>
<Button
type="button"
variant="ghost"
size="xs"
onClick={() =>
setSelected(
selectedFiles.size === copyable.length
? new Set()
: new Set(copyable.map((file) => file.path)),
)
}
>
{selectedFiles.size === copyable.length ? "None" : "All"}
</Button>
</>
) : null}
</div>
{ignoredFiles.error ? (
<p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
) : files.length === 0 ? (
<p className="text-muted-foreground text-xs">
{ignoredFiles.isSuccess
? "No ignored files to copy."
: "Finding ignored files…"}
</p>
) : (
<div className="max-h-52 overflow-y-auto rounded-md border">
{files.map((file) => (
<IgnoredFileRow
key={file.path}
file={file}
checked={selectedFiles.has(file.path)}
onCheckedChange={(checked) => toggleFile(file.path, checked)}
/>
))}
</div>
)}
{ignoredFiles.data?.truncated ? (
<p className="text-muted-foreground text-xs">
Showing the first {files.length} files.
</p>
) : null}
<p className="text-muted-foreground text-xs">
Files are copied after the clone finishes. Folders git ignores whole, like
node_modules, are left out.
</p>
</div>
) : null}
{error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
</DialogPanel>
<DialogFooter>
<Button type="button" variant="outline" onClick={close}>
Cancel
</Button>
<Button type="submit" disabled={unavailable || submitting}>
{submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
</Button>
</DialogFooter>
</form>
</DialogPopup>
</Dialog>
);
}
/**
* A project can be rooted below its repository's top folder. The clone lands
* at the top, so copied files keep the same path below it.
*/
function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
if (!repositoryRoot) return "";
const prefix = repositoryRoot.replace(/[\\/]+$/, "");
const rest = workspaceRoot.slice(prefix.length);
return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
? rest.slice(1).replaceAll("\\", "/")
: "";
}
function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
return new Set(
files
.filter(
(file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
)
.map((file) => file.path),
);
}
function IgnoredFileRow({
file,
checked,
onCheckedChange,
}: {
file: ProjectIgnoredFile;
checked: boolean;
onCheckedChange: (checked: boolean) => void;
}) {
const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
return (
<label className="flex cursor-pointer items-center gap-2 px-2.5 py-1.5 text-sm not-last:border-b has-disabled:cursor-not-allowed has-disabled:opacity-64">
<Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
<span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
<span className="shrink-0 text-muted-foreground text-xs tabular-nums">
{tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
</span>
</label>
);
}