forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

note-form.tsx257 lines, 8.9 KiBHistoryRawDownload
1import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
2import { formatApiError } from "@/api/client";
3import { getSettings } from "@/api/settings";
4import type { Note } from "@/api/client";
5import { Button } from "@/components/ui/button";
6import { ConfirmDialog } from "@/components/ui/confirm-dialog";
7import { FormDialog } from "@/components/ui/form-dialog";
8import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
9import { Input } from "@/components/ui/input";
10import { Label } from "@/components/ui/label";
11import { PageSpinner } from "@/components/ui/page-spinner";
12import { Textarea } from "@/components/ui/textarea";
13import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
14import { useT } from "@/stores/preferences-context";
15
16const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
17
18export type NoteFormValues = {
19 title: string;
20 content: string;
21 files: File[];
22};
23
24const MAX_NOTE_FILES = 10;
25
26export function NoteForm(props: {
27 initial?: Partial<Note>;
28 submitLabel?: string;
29 /** Stage files on create (uploaded by parent after note exists). */
30 enableFiles?: boolean;
31 onSubmit: (values: NoteFormValues) => Promise<void>;
32 onCancel?: () => void;
33}) {
34 const t = useT();
35 let fileInput: HTMLInputElement | undefined;
36 const isUpdate = () => !!props.initial?.id;
37 const [title, setTitle] = createSignal(props.initial?.title ?? "");
38 const [content, setContent] = createSignal(props.initial?.content ?? "");
39 const [files, setFiles] = createSignal<File[]>([]);
40 const [error, setError] = createSignal("");
41 const [pending, setPending] = createSignal(false);
42 const [confirmOpen, setConfirmOpen] = createSignal(false);
43 const [drawOpen, setDrawOpen] = createSignal(false);
44 const [pendingValues, setPendingValues] = createSignal<NoteFormValues | null>(null);
45 const [settings] = createResource(async () => {
46 try {
47 return await getSettings();
48 } catch {
49 return null;
50 }
51 });
52 const maxFileBytes = () => maxUploadBytes(settings());
53 const showFiles = () => !!props.enableFiles && !isUpdate();
54
55 const validate = (): string | null => {
56 const value = title().trim();
57 if (!value) return t("form.titleRequired");
58 if (value.length > 200) return t("form.titleMax");
59 if (content().length > 10_000) return t("form.contentMax");
60 return null;
61 };
62
63 const addFile = (file: File | undefined) => {
64 if (!file) return;
65 setError("");
66 if (file.size > maxFileBytes()) {
67 setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
68 return;
69 }
70 if (files().length >= MAX_NOTE_FILES) {
71 setError(t("notes.fileLimit"));
72 return;
73 }
74 setFiles((prev) => [...prev, file]);
75 if (fileInput) fileInput.value = "";
76 };
77
78 const save = async (values: NoteFormValues) => {
79 setError("");
80 setPending(true);
81 try {
82 await props.onSubmit(values);
83 if (!isUpdate()) {
84 setTitle("");
85 setContent("");
86 setFiles([]);
87 }
88 } catch (err) {
89 setError(formatApiError(err));
90 } finally {
91 setPending(false);
92 }
93 };
94
95 const handleSubmit = async (e: SubmitEvent) => {
96 e.preventDefault();
97 const v = validate();
98 if (v) {
99 setError(v);
100 return;
101 }
102 const values: NoteFormValues = { title: title().trim(), content: content(), files: files() };
103 if (isUpdate()) {
104 setPendingValues(values);
105 setConfirmOpen(true);
106 return;
107 }
108 await save(values);
109 };
110
111 return (
112 <>
113 <form class="space-y-5" onSubmit={handleSubmit}>
114 <div class="space-y-1.5 rounded-xl border border-border/80 bg-card p-4 shadow-xs">
115 <Label for="note-title">{t("form.title")}</Label>
116 <Input
117 id="note-title"
118 class="h-10 rounded-lg bg-background/80"
119 value={title()}
120 maxlength={200}
121 required
122 onInput={(e) => setTitle(e.currentTarget.value)}
123 />
124 </div>
125 <div class="space-y-1.5 rounded-xl border border-border/80 bg-card p-4 shadow-xs">
126 <Label for="note-content">{t("form.content")}</Label>
127 <Textarea
128 id="note-content"
129 class="min-h-32 rounded-lg bg-background/80"
130 value={content()}
131 maxlength={10000}
132 rows={4}
133 onInput={(e) => setContent(e.currentTarget.value)}
134 />
135 </div>
136
137 <Show when={showFiles()}>
138 <section class="space-y-3 rounded-xl border border-border/80 bg-card p-4 shadow-xs">
139 <div class="flex flex-wrap items-center justify-between gap-3">
140 <div>
141 <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
142 <p class="mt-1 text-xs text-muted-foreground">
143 {t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}
144 </p>
145 </div>
146 <input
147 ref={(el) => {
148 fileInput = el;
149 }}
150 type="file"
151 class="hidden"
152 disabled={pending() || files().length >= MAX_NOTE_FILES}
153 onChange={(event) => addFile(event.currentTarget.files?.[0])}
154 />
155 <div class="flex flex-wrap items-center gap-2">
156 <Button
157 type="button"
158 variant="outline"
159 size="sm"
160 class="rounded-md"
161 disabled={pending() || files().length >= MAX_NOTE_FILES}
162 onClick={() => setDrawOpen(true)}
163 >
164 <IconEdit class="h-4 w-4" />
165 {t("notes.draw")}
166 </Button>
167 <Button
168 type="button"
169 size="sm"
170 class="rounded-md"
171 disabled={pending() || files().length >= MAX_NOTE_FILES}
172 onClick={() => fileInput?.click()}
173 >
174 <IconPlus class="h-4 w-4" />
175 {t("notes.addFile")}
176 </Button>
177 </div>
178 </div>
179 <Show
180 when={files().length > 0}
181 fallback={
182 <p class="rounded-md border border-dashed border-border/80 bg-muted/20 px-3 py-4 text-center text-sm text-muted-foreground">
183 {t("notes.noFiles")}
184 </p>
185 }
186 >
187 <ul class="divide-y divide-border/70 rounded-md border border-border/70">
188 <For each={files()}>
189 {(file, index) => (
190 <li class="flex items-center justify-between gap-3 px-3 py-2 text-sm">
191 <span class="min-w-0 flex-1 truncate font-medium">{file.name}</span>
192 <span class="shrink-0 text-xs text-muted-foreground">{formatBytes(file.size)}</span>
193 <Button
194 type="button"
195 variant="ghost"
196 size="icon"
197 class="h-8 w-8 rounded-md text-destructive hover:text-destructive"
198 onClick={() => setFiles((prev) => prev.filter((_, i) => i !== index()))}
199 >
200 <IconTrash class="h-4 w-4" />
201 </Button>
202 </li>
203 )}
204 </For>
205 </ul>
206 </Show>
207 </section>
208 </Show>
209
210 {error() && (
211 <p class="rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive">
212 {error()}
213 </p>
214 )}
215 <div class="flex flex-wrap items-center justify-end gap-2 border-t border-border/80 pt-4">
216 {props.onCancel && (
217 <Button type="button" variant="outline" class="h-10 rounded-lg" onClick={props.onCancel}>
218 {t("common.cancel")}
219 </Button>
220 )}
221 <Button type="submit" class="h-10 rounded-lg" disabled={pending()}>
222 {props.submitLabel ?? t("common.save")}
223 </Button>
224 </div>
225 </form>
226
227 <FormDialog
228 open={drawOpen()}
229 onOpenChange={setDrawOpen}
230 title={t("notes.draw")}
231 description={t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}
232 class="max-w-4xl"
233 >
234 <Suspense fallback={<PageSpinner />}>
235 <DrawCanvas
236 onSave={(file) => {
237 addFile(file);
238 setDrawOpen(false);
239 }}
240 />
241 </Suspense>
242 </FormDialog>
243
244 <ConfirmDialog
245 open={confirmOpen()}
246 onOpenChange={setConfirmOpen}
247 title={t("confirm.updateTitle")}
248 summary={t("confirm.updateNote", { title: pendingValues()?.title ?? "" })}
249 onConfirm={async () => {
250 const values = pendingValues();
251 if (!values) return;
252 await save(values);
253 }}
254 />
255 </>
256 );
257}