Open History to see the last commit
1import type { EnvironmentId } from "@t3tools/contracts";
2import type { SourceControlClientDefinition } from "@t3tools/client-runtime/source-control-clients";
3import { useState } from "react";
4
5import { useEnvironmentSettings } from "../../hooks/useSettings";
6import { serverEnvironment } from "../../state/server";
7import { useAtomCommand } from "../../state/use-atom-command";
8import { Button } from "../ui/button";
9import { ProviderSettingsForm } from "./ProviderSettingsForm";
10
11export function SourceControlHostSettings({
12 environmentId,
13 definition,
14 onSaved,
15}: {
16 readonly environmentId: EnvironmentId;
17 readonly definition: SourceControlClientDefinition & {
18 readonly settings: NonNullable<SourceControlClientDefinition["settings"]>;
19 };
20 readonly onSaved: () => void;
21}) {
22 const saved = useEnvironmentSettings(
23 environmentId,
24 (settings) => settings.sourceControlHosts[definition.kind],
25 );
26 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
27 label: `save ${definition.label} settings`,
28 });
29 const [saving, setSaving] = useState(false);
30 const formDefinition = { settingsSchema: definition.settings };
31 const hasSaved = Object.values(saved ?? {}).some((value) => value !== "");
32
33 const save = async (fields: Record<string, unknown>) => {
34 setSaving(true);
35 const result = await updateSettings({
36 environmentId,
37 input: { patch: { sourceControlHosts: { [definition.kind]: fields } } },
38 });
39 setSaving(false);
40 if (result._tag === "Success") onSaved();
41 };
42
43 return (
44 // Locked while saving, so an edit made mid-request is not overwritten by the saved value.
45 <fieldset disabled={saving} className="contents">
46 <ProviderSettingsForm
47 definition={formDefinition}
48 value={saved ?? {}}
49 idPrefix={`source-control-${definition.kind}-${environmentId}`}
50 variant="settings"
51 onChange={(next) => {
52 const fields = next ?? {};
53 const changed = Object.fromEntries(
54 Object.entries(fields).filter(([key, value]) => saved?.[key] !== value),
55 );
56 const cleared = Object.keys(saved ?? {}).filter((key) => !(key in fields));
57 void save({ ...changed, ...Object.fromEntries(cleared.map((key) => [key, ""])) });
58 }}
59 />
60 {hasSaved ? (
61 <div className="flex justify-end pt-2">
62 <Button
63 size="xs"
64 variant="outline"
65 onClick={() =>
66 void save(Object.fromEntries(Object.keys(saved ?? {}).map((key) => [key, ""])))
67 }
68 >
69 Remove
70 </Button>
71 </div>
72 ) : null}
73 </fieldset>
74 );
75}