Open History to see the last commit
1import { useForm } from "@tanstack/react-form";
2import type { ReactNode } from "react";
3
4import { Button } from "@/components/ui/button";
5import { Input } from "@/components/ui/input";
6import {
7 Select,
8 SelectContent,
9 SelectItem,
10 SelectTrigger,
11 SelectValue,
12} from "@/components/ui/select";
13import { Switch } from "@/components/ui/switch";
14import { updateAccount } from "@/db/mutations";
15import type { AccountSettings } from "@/db/mutations";
16import { useAccount, useFolders } from "@/db/queries";
17import { accountSchema, newNoteStyleSchema, sortNotesBySchema } from "@/db/schema";
18import type { Account, NewNoteStyle, SortNotesBy } from "@/db/schema";
19import { cn } from "@/lib/utils";
20
21import { AccountAvatar } from "./icons";
22
23const accountSettingsSchema = accountSchema.pick({
24 name: true,
25 email: true,
26 defaultFolderId: true,
27 sortNotesBy: true,
28 newNotesStartWith: true,
29 groupNotesByDate: true,
30});
31
32const SORT_LABELS: Record<SortNotesBy, string> = {
33 dateEdited: "Date Edited",
34 dateCreated: "Date Created",
35 title: "Title",
36};
37
38const NEW_NOTE_LABELS: Record<NewNoteStyle, string> = {
39 title: "Title",
40 heading: "Heading",
41 body: "Body",
42};
43
44interface SettingsFormProps {
45 /** Cards sit on the macOS content background or the iOS grouped background. */
46 variant: "mac" | "ios";
47}
48
49export function SettingsForm({ variant }: SettingsFormProps) {
50 const account = useAccount();
51 if (!account) return null;
52 return <AccountSettingsForm account={account} variant={variant} />;
53}
54
55/**
56 * The form edits a copy of the account; Save writes it to `accountCollection`
57 * as one optimistic update. The sidebar's account block changes right away,
58 * and the button waits for the server before the form counts as saved.
59 */
60function AccountSettingsForm({ account, variant }: SettingsFormProps & { account: Account }) {
61 const folders = useFolders();
62
63 const defaultValues: AccountSettings = {
64 name: account.name,
65 email: account.email,
66 defaultFolderId: account.defaultFolderId,
67 sortNotesBy: account.sortNotesBy,
68 newNotesStartWith: account.newNotesStartWith,
69 groupNotesByDate: account.groupNotesByDate,
70 };
71
72 const form = useForm({
73 defaultValues,
74 validators: { onChange: accountSettingsSchema },
75 onSubmit: async ({ value, formApi }) => {
76 try {
77 await updateAccount(account.id, value).when("settled");
78 formApi.reset(value);
79 } catch {
80 // Rolled back: the error toast says why, and the form keeps the edits to retry.
81 }
82 },
83 });
84
85 const card =
86 variant === "ios"
87 ? "rounded-[26px] bg-ios-card"
88 : "rounded-xl border border-mac-separator bg-black/[0.025] dark:bg-white/[0.04]";
89 const usedPercent = Math.round((account.storageUsedGb / account.storageTotalGb) * 100);
90
91 return (
92 <form
93 className={cn("space-y-6", variant === "ios" ? "text-[17px]" : "text-[13px]")}
94 onSubmit={(event) => {
95 event.preventDefault();
96 void form.handleSubmit();
97 }}
98 >
99 <div className={cn(card, "flex items-center gap-4 p-4")}>
100 <AccountAvatar name={account.name} className="size-14 text-lg" />
101 <div className="min-w-0 flex-1">
102 <p className="truncate text-[1.15em] font-semibold">{account.name}</p>
103 <p className="truncate text-[0.95em] opacity-60">{account.email}</p>
104 <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-black/10 dark:bg-white/10">
105 <div
106 className="h-full rounded-full bg-notes-accent"
107 style={{ width: `${usedPercent}%` }}
108 />
109 </div>
110 <p className="mt-1 text-[0.85em] opacity-60">
111 {account.plan} · {account.storageUsedGb} GB of {account.storageTotalGb} GB used
112 </p>
113 </div>
114 </div>
115
116 <SettingsGroup title="Account" className={card}>
117 <form.Field name="name">
118 {(field) => (
119 <SettingsRow
120 label="Name"
121 htmlFor={field.name}
122 error={firstError(field.state.meta.errors)}
123 >
124 <Input
125 id={field.name}
126 value={field.state.value}
127 onChange={(event) => field.handleChange(event.target.value)}
128 onBlur={field.handleBlur}
129 aria-invalid={!field.state.meta.isValid}
130 className="w-full max-w-64 text-right"
131 />
132 </SettingsRow>
133 )}
134 </form.Field>
135 <form.Field name="email">
136 {(field) => (
137 <SettingsRow
138 label="Email"
139 htmlFor={field.name}
140 error={firstError(field.state.meta.errors)}
141 >
142 <Input
143 id={field.name}
144 type="email"
145 value={field.state.value}
146 onChange={(event) => field.handleChange(event.target.value)}
147 onBlur={field.handleBlur}
148 aria-invalid={!field.state.meta.isValid}
149 className="w-full max-w-64 text-right"
150 />
151 </SettingsRow>
152 )}
153 </form.Field>
154 </SettingsGroup>
155
156 <SettingsGroup title="Notes" className={card}>
157 <form.Field name="defaultFolderId">
158 {(field) => (
159 <SettingsRow label="Default folder" htmlFor={field.name}>
160 <Select value={field.state.value} onValueChange={field.handleChange}>
161 <SelectTrigger id={field.name} size="sm" className="min-w-36">
162 <SelectValue />
163 </SelectTrigger>
164 <SelectContent align="end">
165 {folders.map((folder) => (
166 <SelectItem key={folder.id} value={folder.id}>
167 {folder.name}
168 </SelectItem>
169 ))}
170 </SelectContent>
171 </Select>
172 </SettingsRow>
173 )}
174 </form.Field>
175 <form.Field name="sortNotesBy">
176 {(field) => (
177 <SettingsRow label="Sort notes by" htmlFor={field.name}>
178 <Select
179 value={field.state.value}
180 onValueChange={(value) => field.handleChange(sortNotesBySchema.parse(value))}
181 >
182 <SelectTrigger id={field.name} size="sm" className="min-w-36">
183 <SelectValue />
184 </SelectTrigger>
185 <SelectContent align="end">
186 {sortNotesBySchema.options.map((option) => (
187 <SelectItem key={option} value={option}>
188 {SORT_LABELS[option]}
189 </SelectItem>
190 ))}
191 </SelectContent>
192 </Select>
193 </SettingsRow>
194 )}
195 </form.Field>
196 <form.Field name="newNotesStartWith">
197 {(field) => (
198 <SettingsRow label="New notes start with" htmlFor={field.name}>
199 <Select
200 value={field.state.value}
201 onValueChange={(value) => field.handleChange(newNoteStyleSchema.parse(value))}
202 >
203 <SelectTrigger id={field.name} size="sm" className="min-w-36">
204 <SelectValue />
205 </SelectTrigger>
206 <SelectContent align="end">
207 {newNoteStyleSchema.options.map((option) => (
208 <SelectItem key={option} value={option}>
209 {NEW_NOTE_LABELS[option]}
210 </SelectItem>
211 ))}
212 </SelectContent>
213 </Select>
214 </SettingsRow>
215 )}
216 </form.Field>
217 <form.Field name="groupNotesByDate">
218 {(field) => (
219 <SettingsRow label="Group notes by date" htmlFor={field.name}>
220 <Switch
221 id={field.name}
222 checked={field.state.value}
223 onCheckedChange={field.handleChange}
224 className="data-checked:bg-[#34c759] dark:[&>span]:bg-white"
225 />
226 </SettingsRow>
227 )}
228 </form.Field>
229 </SettingsGroup>
230
231 <form.Subscribe
232 selector={(state) => [state.isDirty, state.canSubmit, state.isSubmitting] as const}
233 >
234 {([isDirty, canSubmit, isSubmitting]) => (
235 <div className="flex justify-end gap-2">
236 <Button type="button" variant="ghost" disabled={!isDirty} onClick={() => form.reset()}>
237 Revert
238 </Button>
239 <Button type="submit" disabled={!isDirty || !canSubmit || isSubmitting}>
240 {isSubmitting ? "Saving…" : "Save"}
241 </Button>
242 </div>
243 )}
244 </form.Subscribe>
245 </form>
246 );
247}
248
249function firstError(errors: unknown[]): string | undefined {
250 const [error] = errors;
251 if (!error) return undefined;
252 if (typeof error === "string") return error;
253 return (error as { message?: string }).message;
254}
255
256function SettingsGroup({
257 title,
258 className,
259 children,
260}: {
261 title: string;
262 className: string;
263 children: ReactNode;
264}) {
265 return (
266 <section>
267 <h2 className="mb-1.5 px-4 text-[0.85em] font-semibold tracking-wide uppercase opacity-55">
268 {title}
269 </h2>
270 <div className={cn(className, "divide-y divide-mac-separator dark:divide-white/10")}>
271 {children}
272 </div>
273 </section>
274 );
275}
276
277function SettingsRow({
278 label,
279 htmlFor,
280 error,
281 children,
282}: {
283 label: string;
284 htmlFor: string;
285 error?: string;
286 children: ReactNode;
287}) {
288 return (
289 <div className="px-4 py-2.5">
290 <div className="flex min-h-8 items-center justify-between gap-4">
291 <label htmlFor={htmlFor} className="shrink-0">
292 {label}
293 </label>
294 <div className="flex min-w-0 flex-1 justify-end">{children}</div>
295 </div>
296 {error && <p className="mt-1 text-right text-[0.85em] text-destructive">{error}</p>}
297 </div>
298 );
299}