import { Link, useBlocker, useNavigate } from "@tanstack/solid-router"; import { For, Show, createSignal, onCleanup, onMount } from "solid-js"; import { getSettings } from "@/api/settings"; import { formatApiError, type Note } from "@/api/client"; import { deleteNoteById, patchNoteById, postNote, postNoteFile } from "@/api/notes"; import { NoteFilesPanel } from "@/components/notes/note-files-panel"; import { NoteRichEditor } from "@/components/notes/note-rich-editor"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { TOOLBAR_SLOT } from "@/components/ui/data-toolbar"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { IconAlert, IconChevronLeft, IconPlus, IconTrash } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { createResource } from "@/lib/create-resource"; import { personalNoteFiles } from "@/lib/note-source"; import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { showToast } from "@/components/ui/toast"; import { useT } from "@/stores/preferences-context"; const MAX_TITLE = 200; const MAX_CONTENT = 10_000; export function stageFiles(current: File[], selected: File[], maxFiles: number, maxBytes: number) { const files = [...current]; let tooLarge = false; let atLimit = false; for (const file of selected) { if (file.size > maxBytes) { tooLarge = true; continue; } if (files.length >= maxFiles) { atLimit = true; continue; } files.push(file); } return { files, tooLarge, atLimit }; } export async function uploadStagedFiles(noteId: string, files: File[], uploadFile = postNoteFile) { const failed: string[] = []; for (const file of files) { try { await uploadFile(noteId, file); } catch { failed.push(file.name); } } return failed; } const fileSnapshot = (files: File[]) => files.map((file) => [file.name, file.size, file.lastModified]); const documentSnapshot = (title: string, content: string, files: File[]) => JSON.stringify([title, content, fileSnapshot(files)]); /** * A personal note as a full-page document: title, editor, attachments. A new * note (no `note`) becomes a real one on first save and moves to its own URL, * where attachments open up. Leaving with unsaved edits asks first. */ export function NoteDocument(props: { note?: Note }) { const t = useT(); const navigate = useNavigate(); const [title, setTitle] = createSignal(props.note?.title ?? ""); const [content, setContent] = createSignal(props.note?.content ?? ""); const [stagedFiles, setStagedFiles] = createSignal([]); const [baseline, setBaseline] = createSignal(documentSnapshot(props.note?.title ?? "", props.note?.content ?? "", [])); const [saving, setSaving] = createSignal(false); const [error, setError] = createSignal(""); const [deleteOpen, setDeleteOpen] = createSignal(false); const [settings] = createResource(async () => { try { return await getSettings(); } catch { return null; } }); const maxFileBytes = () => maxUploadBytes(settings()); const atFileLimit = () => stagedFiles().length >= personalNoteFiles.maxFiles; const dirty = () => documentSnapshot(title(), content(), stagedFiles()) !== baseline(); const isNew = () => !props.note; let fileInput: HTMLInputElement | undefined; let leaving = false; const blocker = useBlocker({ shouldBlockFn: () => dirty(), enableBeforeUnload: () => dirty(), withResolver: true }); const addFiles = (selected: FileList | null) => { if (!selected) return; const result = stageFiles(stagedFiles(), Array.from(selected), personalNoteFiles.maxFiles, maxFileBytes()); setStagedFiles(result.files); if (result.tooLarge) setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); else if (result.atLimit) setError(t("notes.fileLimit")); else setError(""); if (fileInput) fileInput.value = ""; }; const save = async () => { if (saving()) return; const trimmed = title().trim(); if (!trimmed) return setError(t("form.titleRequired")); if (trimmed.length > MAX_TITLE) return setError(t("form.titleMax")); if (content().length > MAX_CONTENT) return setError(t("form.contentMax")); setError(""); setSaving(true); // What is being saved, captured now: typing that lands while the request // is out must still count as unsaved afterwards. const body = content(); try { if (props.note) { await patchNoteById(props.note.id, { title: trimmed, content: body }); if (title().trim() === trimmed) setTitle(trimmed); setBaseline(documentSnapshot(trimmed, body, [])); } else { const created = await postNote({ title: trimmed, content: body || undefined }); const failedFiles = await uploadStagedFiles(created.id, stagedFiles()); setStagedFiles([]); // Settle the baseline first so the move to the note's URL is not blocked. setBaseline(documentSnapshot(title(), content(), [])); await navigate({ to: "/notes/$id", params: { id: created.id }, replace: true }); if (failedFiles.length > 0) showToast({ title: t("notes.fileUploadFailed", { files: failedFiles.join(", ") }) }); } } catch (err) { setError(formatApiError(err)); } finally { setSaving(false); } }; onMount(() => { const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== "s") return; event.preventDefault(); void save(); }; window.addEventListener("keydown", onKey); onCleanup(() => window.removeEventListener("keydown", onKey)); }); const status = () => (saving() ? t("notes.saving") : dirty() ? t("notes.unsaved") : isNew() ? "" : t("notes.allSaved")); return (
{/* Header row controls are toolbar pills, the back link included. */}
{t("notes.backToNotebook")} {status()}
{error()} {/* Title above both columns, so the editor and the attachments start on one line. */} setTitle(event.currentTarget.value)} onKeyDown={(event) => { if (event.key === "Enter") event.preventDefault(); }} />
} />
{ if (!props.note) return; await deleteNoteById(props.note.id); setBaseline(documentSnapshot(title(), content(), [])); await navigate({ to: "/notes" }); }} /> { // The dialog also closes itself after "Leave"; only a dismissal resets. if (!open && !leaving && blocker().status === "blocked") blocker().reset?.(); }} title={t("notes.leaveTitle")} description={t("notes.leaveHint")} summary={title().trim() || t("notes.titlePlaceholder")} variant="destructive" icon={} confirmLabel={t("notes.leaveConfirm")} onConfirm={() => { leaving = true; blocker().proceed?.(); }} />
); }