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 try {
36 const result = await updateSettings({
37 environmentId,
38 input: { patch: { sourceControlHosts: { [definition.kind]: fields } } },
39 });
40 if (result._tag === "Success") onSaved();
41 } finally {
42 setSaving(false);
43 }
44 };
45
46 return (
47 // Locked while saving, so an edit made mid-request is not overwritten by the saved value.
48 <fieldset disabled={saving} className="contents">
49 <ProviderSettingsForm
50 definition={formDefinition}
51 value={saved ?? {}}
52 idPrefix={`source-control-${definition.kind}-${environmentId}`}
53 variant="settings"
54 onChange={(next) => {
55 const fields = next ?? {};
56 const changed = Object.fromEntries(
57 Object.entries(fields).filter(([key, value]) => saved?.[key] !== value),
58 );
59 const cleared = Object.keys(saved ?? {}).filter((key) => !(key in fields));
60 void save({ ...changed, ...Object.fromEntries(cleared.map((key) => [key, ""])) });
61 }}
62 />
63 {hasSaved ? (
64 <div className="flex justify-end pt-2">
65 <Button
66 size="xs"
67 variant="outline"
68 onClick={() =>
69 void save(Object.fromEntries(Object.keys(saved ?? {}).map((key) => [key, ""])))
70 }
71 >
72 Remove
73 </Button>
74 </div>
75 ) : null}
76 </fieldset>
77 );
78}