forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

note-document.tsx179 lines, 7.3 KiBHistoryRawDownload
1import { Link, useBlocker, useNavigate } from "@tanstack/solid-router";
2import { Show, createSignal, onCleanup, onMount } from "solid-js";
3import { formatApiError, type Note } from "@/api/client";
4import { deleteNoteById, patchNoteById, postNote } from "@/api/notes";
5import { NoteFilesPanel } from "@/components/notes/note-files-panel";
6import { NoteRichEditor } from "@/components/notes/note-rich-editor";
7import { Alert } from "@/components/ui/alert";
8import { Button } from "@/components/ui/button";
9import { ConfirmDialog } from "@/components/ui/confirm-dialog";
10import { IconAlert, IconChevronLeft, IconTrash } from "@/components/ui/icons";
11import { cn } from "@/lib/cn";
12import { personalNoteFiles } from "@/lib/note-source";
13import { useT } from "@/stores/preferences-context";
14
15const MAX_TITLE = 200;
16const MAX_CONTENT = 10_000;
17
18/**
19 * A personal note as a full-page document: title, editor, attachments. A new
20 * note (no `note`) becomes a real one on first save and moves to its own URL,
21 * where attachments open up. Leaving with unsaved edits asks first.
22 */
23export function NoteDocument(props: { note?: Note }) {
24 const t = useT();
25 const navigate = useNavigate();
26 const [title, setTitle] = createSignal(props.note?.title ?? "");
27 const [content, setContent] = createSignal(props.note?.content ?? "");
28 const [baseline, setBaseline] = createSignal(JSON.stringify([props.note?.title ?? "", props.note?.content ?? ""]));
29 const [saving, setSaving] = createSignal(false);
30 const [error, setError] = createSignal("");
31 const [deleteOpen, setDeleteOpen] = createSignal(false);
32 const dirty = () => JSON.stringify([title(), content()]) !== baseline();
33 const isNew = () => !props.note;
34
35 let leaving = false;
36 const blocker = useBlocker({ shouldBlockFn: () => dirty(), enableBeforeUnload: () => dirty(), withResolver: true });
37
38 const save = async () => {
39 if (saving()) return;
40 const trimmed = title().trim();
41 if (!trimmed) return setError(t("form.titleRequired"));
42 if (trimmed.length > MAX_TITLE) return setError(t("form.titleMax"));
43 if (content().length > MAX_CONTENT) return setError(t("form.contentMax"));
44 setError("");
45 setSaving(true);
46 // What is being saved, captured now: typing that lands while the request
47 // is out must still count as unsaved afterwards.
48 const body = content();
49 try {
50 if (props.note) {
51 await patchNoteById(props.note.id, { title: trimmed, content: body });
52 if (title().trim() === trimmed) setTitle(trimmed);
53 setBaseline(JSON.stringify([trimmed, body]));
54 } else {
55 const created = await postNote({ title: trimmed, content: body || undefined });
56 // Settle the baseline first so the move to the note's URL is not blocked.
57 setBaseline(JSON.stringify([title(), content()]));
58 await navigate({ to: "/notes/$id", params: { id: created.id }, replace: true });
59 }
60 } catch (err) {
61 setError(formatApiError(err));
62 } finally {
63 setSaving(false);
64 }
65 };
66
67 onMount(() => {
68 const onKey = (event: KeyboardEvent) => {
69 if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== "s") return;
70 event.preventDefault();
71 void save();
72 };
73 window.addEventListener("keydown", onKey);
74 onCleanup(() => window.removeEventListener("keydown", onKey));
75 });
76
77 const status = () => (saving() ? t("notes.saving") : dirty() ? t("notes.unsaved") : isNew() ? "" : t("notes.allSaved"));
78
79 return (
80 <div class="space-y-4">
81 <div class="flex items-center gap-3">
82 <Link to="/notes" class="inline-flex h-8 items-center gap-1 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
83 <IconChevronLeft class="h-4 w-4" />
84 {t("notes.backToNotebook")}
85 </Link>
86 <span class={cn("ml-auto text-xs", dirty() ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground")} aria-live="polite">
87 {status()}
88 </span>
89 <Show when={props.note}>
90 <Button type="button" variant="outline" size="sm" class="rounded-lg text-destructive-text hover:text-destructive-text" onClick={() => setDeleteOpen(true)}>
91 <IconTrash class="h-4 w-4" />
92 {t("common.delete")}
93 </Button>
94 </Show>
95 </div>
96
97 <Show when={error()}>
98 <Alert variant="destructive">{error()}</Alert>
99 </Show>
100
101 {/* Title above both columns, so the editor and the attachments start on one line. */}
102 <input
103 class="w-full bg-transparent px-1 text-3xl font-semibold tracking-tight text-text-strong outline-hidden placeholder:text-muted-foreground/50"
104 placeholder={t("notes.titlePlaceholder")}
105 aria-label={t("form.title")}
106 value={title()}
107 maxlength={MAX_TITLE}
108 onInput={(event) => setTitle(event.currentTarget.value)}
109 onKeyDown={(event) => {
110 if (event.key === "Enter") event.preventDefault();
111 }}
112 />
113
114 <div class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_340px]">
115 <div class="min-w-0">
116 <NoteRichEditor
117 value={content()}
118 onChange={setContent}
119 placeholder={t("notes.bodyPlaceholder")}
120 toolbarClass="top-[45px]"
121 actions={
122 <>
123 <Button type="button" size="sm" class="min-w-[6.5rem] rounded-lg" disabled={saving() || (!dirty() && !isNew())} onClick={() => void save()}>
124 {saving() ? t("notes.saving") : t("common.save")}
125 </Button>
126 </>
127 }
128 />
129 </div>
130
131 <aside class="min-w-0 space-y-4 xl:sticky xl:top-[61px] xl:self-start">
132 <Show
133 when={props.note}
134 fallback={
135 <section class="rounded-xl border border-dashed border-border bg-card/60 p-4">
136 <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
137 <p class="mt-1 text-sm text-muted-foreground">{t("notes.filesAfterSave")}</p>
138 </section>
139 }
140 >
141 {(note) => <NoteFilesPanel noteId={note().id} source={personalNoteFiles} active />}
142 </Show>
143 </aside>
144 </div>
145
146 <ConfirmDialog
147 open={deleteOpen()}
148 onOpenChange={setDeleteOpen}
149 title={t("confirm.deleteTitle")}
150 variant="destructive"
151 summary={t("confirm.deleteNote", { title: props.note?.title ?? "" })}
152 onConfirm={async () => {
153 if (!props.note) return;
154 await deleteNoteById(props.note.id);
155 setBaseline(JSON.stringify([title(), content()]));
156 await navigate({ to: "/notes" });
157 }}
158 />
159
160 <ConfirmDialog
161 open={blocker().status === "blocked"}
162 onOpenChange={(open) => {
163 // The dialog also closes itself after "Leave"; only a dismissal resets.
164 if (!open && !leaving && blocker().status === "blocked") blocker().reset?.();
165 }}
166 title={t("notes.leaveTitle")}
167 description={t("notes.leaveHint")}
168 summary={title().trim() || t("notes.titlePlaceholder")}
169 variant="destructive"
170 icon={<IconAlert class="h-4 w-4" />}
171 confirmLabel={t("notes.leaveConfirm")}
172 onConfirm={() => {
173 leaving = true;
174 blocker().proceed?.();
175 }}
176 />
177 </div>
178 );
179}