import { For, Show, Suspense, createEffect, createMemo, createSignal, lazy } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { getSettings } from "@/api/settings"; import { formatApiError } from "@/api/client"; import type { NoteFile } from "@/api/client"; import type { DrawScene } from "@/lib/draw-stroke"; import type { NoteFileSource } from "@/lib/note-source"; import { NoteFilePreview } from "@/components/notes/note-file-preview"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { FormDialog } from "@/components/ui/form-dialog"; import { createFlash } from "@/lib/flash"; import { IconDownload, IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import { TablePagination } from "@/components/ui/table-pagination"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { cn } from "@/lib/cn"; import { fileTypeMeta } from "@/lib/file-type"; import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { useT } from "@/stores/preferences-context"; // Lazy so the drawing pad rides its own chunk, off the notes page's initial load. const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); const FILE_PAGE_SIZE = 4; /** Drawings are saved with this suffix so the grid can offer "Edit" without fetching every blob. */ const DRAWING_SUFFIX = ".hzdraw.png"; const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX); export function NoteFilesPanel(props: { noteId: string; active: boolean; /** Which note family the files hang off — personal notes or a course's. */ source: NoteFileSource; /** Read-only when false: no upload, drawing, or delete. Defaults to true. */ canManage?: boolean; }) { let input: HTMLInputElement | undefined; const t = useT(); const [error, setError] = createSignal(""); const [flash, setFlash] = createFlash(); const [pending, setPending] = createSignal(false); const [filePage, setFilePage] = createSignal(0); const [drawOpen, setDrawOpen] = createSignal(false); const [editScene, setEditScene] = createSignal(null); const [editTarget, setEditTarget] = createSignal(null); const [previewFile, setPreviewFile] = createSignal(null); const [deleteTarget, setDeleteTarget] = createSignal(null); const canManage = () => props.canManage !== false; const [files, { refetch }] = createResource( () => (props.active ? props.noteId : null), async (noteId) => { if (!noteId) return [] as NoteFile[]; return (await props.source.listFiles(noteId, { limit: props.source.maxFiles })).items; }, ); const [settings] = createResource(async () => { try { return await getSettings(); } catch { return null; } }); const maxFileBytes = () => maxUploadBytes(settings()); const atLimit = () => (files() ?? []).length >= props.source.maxFiles; const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE))); const pageFiles = createMemo(() => { const start = filePage() * FILE_PAGE_SIZE; return (files() ?? []).slice(start, start + FILE_PAGE_SIZE); }); createEffect(() => { if (filePage() >= totalPages()) setFilePage(totalPages() - 1); }); const upload = async (file: File | undefined): Promise => { if (!file) return false; setError(""); if (file.size > maxFileBytes()) { setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); return false; } setPending(true); try { await props.source.uploadFile(props.noteId, file); await refetch(); if (input) input.value = ""; setFlash(t("common.created")); return true; } catch (err) { setError(formatApiError(err)); return false; } finally { setPending(false); } }; const download = (file: NoteFile) => { const link = document.createElement("a"); link.href = props.source.fileUrl(props.noteId, file.id); link.download = file.name; link.click(); }; const openNewDrawing = () => { setEditScene(null); setEditTarget(null); setDrawOpen(true); }; const openEditDrawing = async (file: NoteFile) => { setError(""); try { const blob = await props.source.fileBlob(props.noteId, file.id); const { pngBytesToScene } = await import("@/lib/drawing-file"); setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); setEditTarget(file); setDrawOpen(true); } catch (err) { setError(formatApiError(err)); } }; // Create-new-then-delete-old: the replacement must be safely stored before the // original is removed, so a failed upload never loses the existing drawing. const saveDrawing = async (file: File) => { const target = editTarget(); if (!(await upload(file))) return; if (target) { try { await props.source.deleteFile(props.noteId, target.id); await refetch(); } catch { // New drawing is saved; deleting the old copy failed — a stale duplicate // remains, but nothing is lost. Leave it rather than risk the new one. } } setEditScene(null); setEditTarget(null); setDrawOpen(false); }; return (
{flash()}

{t("notes.files")}

{t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}

{ input = el; }} type="file" class="hidden" disabled={pending() || atLimit()} onChange={(event) => void upload(event.currentTarget.files?.[0])} /> {/* Two equal halves spanning the panel, the same width as the drop area and file list under them. */}
{error() &&

{error()}

}

{t("notes.fileLimit")}

{formatApiError(files.error)}

}> 0} fallback={!files.error &&

{t("notes.noFiles")}

} >
    {(file) => { const meta = fileTypeMeta(file, "h-8 w-8"); return (
  • {meta.label}
    , onSelect: () => setPreviewFile(file), }, ...(canManage() && isDrawing(file) ? [ { label: t("common.edit"), icon: , onSelect: () => void openEditDrawing(file), }, ] : []), { label: t("notes.downloadFile"), icon: , onSelect: () => download(file), }, ...(canManage() ? [ { label: t("common.delete"), icon: , destructive: true, onSelect: () => setDeleteTarget(file), }, ] : []), ]} />
  • ); }}
FILE_PAGE_SIZE}> setPreviewFile(null)} />
{ setDrawOpen(open); if (!open) { setEditScene(null); setEditTarget(null); } }} title={t("notes.drawTitle")} class="sm:max-w-3xl" >

{error()}

}> void saveDrawing(file)} />
!open && setDeleteTarget(null)} title={t("confirm.deleteTitle")} variant="destructive" summary={t("confirm.deleteNoteFile", { title: deleteTarget()?.name ?? "" })} onConfirm={async () => { const target = deleteTarget(); if (!target) return; await props.source.deleteFile(props.noteId, target.id); if (previewFile()?.id === target.id) setPreviewFile(null); setDeleteTarget(null); await refetch(); setFlash(t("common.deleted")); }} />
); }