forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

note-document.tsx287 lines, 12.2 KiBHistoryRawDownload
1import { Link, useBlocker, useNavigate } from "@tanstack/solid-router";
2import { For, Show, createSignal, onCleanup, onMount } from "solid-js";
3import { getSettings } from "@/api/settings";
4import { formatApiError, type Note } from "@/api/client";
5import { deleteNoteById, patchNoteById, postNote, postNoteFile } from "@/api/notes";
6import { NoteFilesPanel } from "@/components/notes/note-files-panel";
7import { NoteRichEditor } from "@/components/notes/note-rich-editor";
8import { Alert } from "@/components/ui/alert";
9import { Button } from "@/components/ui/button";
10import { TOOLBAR_SLOT } from "@/components/ui/data-toolbar";
11import { ConfirmDialog } from "@/components/ui/confirm-dialog";
12import { IconAlert, IconChevronLeft, IconPlus, IconTrash } from "@/components/ui/icons";
13import { cn } from "@/lib/cn";
14import { createResource } from "@/lib/create-resource";
15import { personalNoteFiles } from "@/lib/note-source";
16import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
17import { showToast } from "@/components/ui/toast";
18import { useT } from "@/stores/preferences-context";
19
20const MAX_TITLE = 200;
21const MAX_CONTENT = 10_000;
22
23export function stageFiles(current: File[], selected: File[], maxFiles: number, maxBytes: number) {
24 const files = [...current];
25 let tooLarge = false;
26 let atLimit = false;
27 for (const file of selected) {
28 if (file.size > maxBytes) {
29 tooLarge = true;
30 continue;
31 }
32 if (files.length >= maxFiles) {
33 atLimit = true;
34 continue;
35 }
36 files.push(file);
37 }
38 return { files, tooLarge, atLimit };
39}
40
41export async function uploadStagedFiles(noteId: string, files: File[], uploadFile = postNoteFile) {
42 const failed: string[] = [];
43 for (const file of files) {
44 try {
45 await uploadFile(noteId, file);
46 } catch {
47 failed.push(file.name);
48 }
49 }
50 return failed;
51}
52
53const fileSnapshot = (files: File[]) => files.map((file) => [file.name, file.size, file.lastModified]);
54const documentSnapshot = (title: string, content: string, files: File[]) => JSON.stringify([title, content, fileSnapshot(files)]);
55
56/**
57 * A personal note as a full-page document: title, editor, attachments. A new
58 * note (no `note`) becomes a real one on first save and moves to its own URL,
59 * where attachments open up. Leaving with unsaved edits asks first.
60 */
61export function NoteDocument(props: { note?: Note }) {
62 const t = useT();
63 const navigate = useNavigate();
64 const [title, setTitle] = createSignal(props.note?.title ?? "");
65 const [content, setContent] = createSignal(props.note?.content ?? "");
66 const [stagedFiles, setStagedFiles] = createSignal<File[]>([]);
67 const [baseline, setBaseline] = createSignal(documentSnapshot(props.note?.title ?? "", props.note?.content ?? "", []));
68 const [saving, setSaving] = createSignal(false);
69 const [error, setError] = createSignal("");
70 const [deleteOpen, setDeleteOpen] = createSignal(false);
71 const [settings] = createResource(async () => {
72 try {
73 return await getSettings();
74 } catch {
75 return null;
76 }
77 });
78 const maxFileBytes = () => maxUploadBytes(settings());
79 const atFileLimit = () => stagedFiles().length >= personalNoteFiles.maxFiles;
80 const dirty = () => documentSnapshot(title(), content(), stagedFiles()) !== baseline();
81 const isNew = () => !props.note;
82 let fileInput: HTMLInputElement | undefined;
83
84 let leaving = false;
85 const blocker = useBlocker({ shouldBlockFn: () => dirty(), enableBeforeUnload: () => dirty(), withResolver: true });
86
87 const addFiles = (selected: FileList | null) => {
88 if (!selected) return;
89 const result = stageFiles(stagedFiles(), Array.from(selected), personalNoteFiles.maxFiles, maxFileBytes());
90 setStagedFiles(result.files);
91 if (result.tooLarge) setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
92 else if (result.atLimit) setError(t("notes.fileLimit"));
93 else setError("");
94 if (fileInput) fileInput.value = "";
95 };
96
97 const save = async () => {
98 if (saving()) return;
99 const trimmed = title().trim();
100 if (!trimmed) return setError(t("form.titleRequired"));
101 if (trimmed.length > MAX_TITLE) return setError(t("form.titleMax"));
102 if (content().length > MAX_CONTENT) return setError(t("form.contentMax"));
103 setError("");
104 setSaving(true);
105 // What is being saved, captured now: typing that lands while the request
106 // is out must still count as unsaved afterwards.
107 const body = content();
108 try {
109 if (props.note) {
110 await patchNoteById(props.note.id, { title: trimmed, content: body });
111 if (title().trim() === trimmed) setTitle(trimmed);
112 setBaseline(documentSnapshot(trimmed, body, []));
113 } else {
114 const created = await postNote({ title: trimmed, content: body || undefined });
115 const failedFiles = await uploadStagedFiles(created.id, stagedFiles());
116 setStagedFiles([]);
117 // Settle the baseline first so the move to the note's URL is not blocked.
118 setBaseline(documentSnapshot(title(), content(), []));
119 await navigate({ to: "/notes/$id", params: { id: created.id }, replace: true });
120 if (failedFiles.length > 0) showToast({ title: t("notes.fileUploadFailed", { files: failedFiles.join(", ") }) });
121 }
122 } catch (err) {
123 setError(formatApiError(err));
124 } finally {
125 setSaving(false);
126 }
127 };
128
129 onMount(() => {
130 const onKey = (event: KeyboardEvent) => {
131 if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== "s") return;
132 event.preventDefault();
133 void save();
134 };
135 window.addEventListener("keydown", onKey);
136 onCleanup(() => window.removeEventListener("keydown", onKey));
137 });
138
139 const status = () => (saving() ? t("notes.saving") : dirty() ? t("notes.unsaved") : isNew() ? "" : t("notes.allSaved"));
140
141 return (
142 <div class="space-y-4">
143 {/* Header row controls are toolbar pills, the back link included. */}
144 <div class={cn("flex items-center gap-3", TOOLBAR_SLOT)}>
145 <Link to="/notes" class="inline-flex items-center gap-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
146 <IconChevronLeft class="h-4 w-4" />
147 {t("notes.backToNotebook")}
148 </Link>
149 <span class={cn("ml-auto text-xs", dirty() ? "text-warning-text" : "text-muted-foreground")} aria-live="polite">
150 {status()}
151 </span>
152 <Show when={props.note}>
153 <Button type="button" variant="outline" size="sm" class="text-destructive-text hover:text-destructive-text" onClick={() => setDeleteOpen(true)}>
154 <IconTrash class="h-4 w-4" />
155 {t("common.delete")}
156 </Button>
157 </Show>
158 </div>
159
160 <Show when={error()}>
161 <Alert variant="destructive">{error()}</Alert>
162 </Show>
163
164 {/* Title above both columns, so the editor and the attachments start on one line. */}
165 <input
166 class="w-full bg-transparent px-1 text-3xl font-semibold tracking-tight text-text-strong outline-hidden placeholder:text-muted-foreground/50"
167 placeholder={t("notes.titlePlaceholder")}
168 aria-label={t("form.title")}
169 value={title()}
170 maxlength={MAX_TITLE}
171 onInput={(event) => setTitle(event.currentTarget.value)}
172 onKeyDown={(event) => {
173 if (event.key === "Enter") event.preventDefault();
174 }}
175 />
176
177 <div class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_340px]">
178 <div class="min-w-0">
179 <NoteRichEditor
180 value={content()}
181 onChange={setContent}
182 placeholder={t("notes.bodyPlaceholder")}
183 toolbarClass="top-[calc(49px+env(safe-area-inset-top))]"
184 actions={
185 <>
186 <Button type="button" size="sm" class="h-8 min-w-[6.5rem] rounded-full px-3.5 text-[13px]" disabled={saving() || (!dirty() && !isNew())} onClick={() => void save()}>
187 {saving() ? t("notes.saving") : t("common.save")}
188 </Button>
189 </>
190 }
191 />
192 </div>
193
194 <aside class="min-w-0 space-y-4 xl:sticky xl:top-[calc(61px+env(safe-area-inset-top))] xl:self-start">
195 <Show
196 when={props.note}
197 fallback={
198 <section class="space-y-3 rounded-xl border border-border-line bg-card p-4 shadow-xs">
199 <div>
200 <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
201 <p class="mt-1 text-xs text-muted-foreground">{t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}</p>
202 </div>
203 <input
204 ref={(element) => {
205 fileInput = element;
206 }}
207 type="file"
208 multiple
209 class="hidden"
210 disabled={saving() || atFileLimit()}
211 onChange={(event) => addFiles(event.currentTarget.files)}
212 />
213 <Button type="button" size="sm" class="h-10 w-full rounded-full text-[13px] sm:h-8 touch:h-10" disabled={saving() || atFileLimit()} onClick={() => fileInput?.click()}>
214 <IconPlus class="h-4 w-4 shrink-0" />
215 <span class="truncate">{t("notes.addFile")}</span>
216 </Button>
217 <p class="text-xs text-muted-foreground">{t("notes.filesUploadOnSave")}</p>
218 <Show when={atFileLimit()}>
219 <p class="text-xs text-muted-foreground">{t("notes.fileLimit")}</p>
220 </Show>
221 <Show
222 when={stagedFiles().length > 0}
223 fallback={<p class="rounded-md border border-dashed border-border/80 bg-muted/20 px-3 py-6 text-center text-sm text-muted-foreground">{t("notes.noFiles")}</p>}
224 >
225 <ul class="space-y-2 rounded-md border border-border/70 bg-background/70 p-2">
226 <For each={stagedFiles()}>
227 {(file, index) => (
228 <li class="flex min-w-0 items-center gap-2 rounded-md border border-border/70 bg-card px-2.5 py-2 text-sm">
229 <span class="min-w-0 flex-1 truncate" title={file.name}>{file.name}</span>
230 <span class="shrink-0 text-xs text-muted-foreground">{formatBytes(file.size)}</span>
231 <Button
232 type="button"
233 variant="ghost"
234 size="icon"
235 class="h-7 w-7 shrink-0 rounded-md text-muted-foreground hover:text-destructive-text"
236 aria-label={`${t("notes.removeFile")}: ${file.name}`}
237 onClick={() => setStagedFiles((files) => files.filter((_, fileIndex) => fileIndex !== index()))}
238 >
239 <IconTrash class="h-4 w-4" />
240 </Button>
241 </li>
242 )}
243 </For>
244 </ul>
245 </Show>
246 </section>
247 }
248 >
249 {(note) => <NoteFilesPanel noteId={note().id} source={personalNoteFiles} active />}
250 </Show>
251 </aside>
252 </div>
253
254 <ConfirmDialog
255 open={deleteOpen()}
256 onOpenChange={setDeleteOpen}
257 title={t("confirm.deleteTitle")}
258 variant="destructive"
259 summary={t("confirm.deleteNote", { title: props.note?.title ?? "" })}
260 onConfirm={async () => {
261 if (!props.note) return;
262 await deleteNoteById(props.note.id);
263 setBaseline(documentSnapshot(title(), content(), []));
264 await navigate({ to: "/notes" });
265 }}
266 />
267
268 <ConfirmDialog
269 open={blocker().status === "blocked"}
270 onOpenChange={(open) => {
271 // The dialog also closes itself after "Leave"; only a dismissal resets.
272 if (!open && !leaving && blocker().status === "blocked") blocker().reset?.();
273 }}
274 title={t("notes.leaveTitle")}
275 description={t("notes.leaveHint")}
276 summary={title().trim() || t("notes.titlePlaceholder")}
277 variant="destructive"
278 icon={<IconAlert class="h-4 w-4" />}
279 confirmLabel={t("notes.leaveConfirm")}
280 onConfirm={() => {
281 leaving = true;
282 blocker().proceed?.();
283 }}
284 />
285 </div>
286 );
287}