hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { For, Show, Suspense, createEffect, createMemo, createSignal, lazy } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { getSettings } from "@/api/settings"; |
| 4 | import { formatApiError } from "@/api/client"; |
| 5 | import type { NoteFile } from "@/api/client"; |
| 6 | import type { DrawScene } from "@/lib/draw-stroke"; |
| 7 | import type { NoteFileSource } from "@/lib/note-source"; |
| 8 | import { NoteFilePreview } from "@/components/notes/note-file-preview"; |
| 9 | import { Alert } from "@/components/ui/alert"; |
| 10 | import { Button } from "@/components/ui/button"; |
| 11 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 12 | import { FormDialog } from "@/components/ui/form-dialog"; |
| 13 | import { createFlash } from "@/lib/flash"; |
| 14 | import { IconDownload, IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons"; |
| 15 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 16 | import { TablePagination } from "@/components/ui/table-pagination"; |
| 17 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 18 | import { cn } from "@/lib/cn"; |
| 19 | import { fileTypeMeta } from "@/lib/file-type"; |
| 20 | import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; |
| 21 | import { useT } from "@/stores/preferences-context"; |
| 22 | |
| 23 | // Lazy so the drawing pad rides its own chunk, off the notes page's initial load. |
| 24 | const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); |
| 25 | |
| 26 | const FILE_PAGE_SIZE = 4; |
| 27 | |
| 28 | /** Drawings are saved with this suffix so the grid can offer "Edit" without fetching every blob. */ |
| 29 | const DRAWING_SUFFIX = ".hzdraw.png"; |
| 30 | const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX); |
| 31 | |
| 32 | export function NoteFilesPanel(props: { |
| 33 | noteId: string; |
| 34 | active: boolean; |
| 35 | /** Which note family the files hang off — personal notes or a course's. */ |
| 36 | source: NoteFileSource; |
| 37 | /** Read-only when false: no upload, drawing, or delete. Defaults to true. */ |
| 38 | canManage?: boolean; |
| 39 | }) { |
| 40 | let input: HTMLInputElement | undefined; |
| 41 | const t = useT(); |
| 42 | const [error, setError] = createSignal(""); |
| 43 | const [flash, setFlash] = createFlash(); |
| 44 | const [pending, setPending] = createSignal(false); |
| 45 | const [filePage, setFilePage] = createSignal(0); |
| 46 | const [drawOpen, setDrawOpen] = createSignal(false); |
| 47 | const [editScene, setEditScene] = createSignal<DrawScene | null>(null); |
| 48 | const [editTarget, setEditTarget] = createSignal<NoteFile | null>(null); |
| 49 | const [previewFile, setPreviewFile] = createSignal<NoteFile | null>(null); |
| 50 | const [deleteTarget, setDeleteTarget] = createSignal<NoteFile | null>(null); |
| 51 | const canManage = () => props.canManage !== false; |
| 52 | const [files, { refetch }] = createResource( |
| 53 | () => (props.active ? props.noteId : null), |
| 54 | async (noteId) => { |
| 55 | if (!noteId) return [] as NoteFile[]; |
| 56 | return (await props.source.listFiles(noteId, { limit: props.source.maxFiles })).items; |
| 57 | }, |
| 58 | ); |
| 59 | const [settings] = createResource(async () => { |
| 60 | try { |
| 61 | return await getSettings(); |
| 62 | } catch { |
| 63 | return null; |
| 64 | } |
| 65 | }); |
| 66 | const maxFileBytes = () => maxUploadBytes(settings()); |
| 67 | const atLimit = () => (files() ?? []).length >= props.source.maxFiles; |
| 68 | const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE))); |
| 69 | const pageFiles = createMemo(() => { |
| 70 | const start = filePage() * FILE_PAGE_SIZE; |
| 71 | return (files() ?? []).slice(start, start + FILE_PAGE_SIZE); |
| 72 | }); |
| 73 | |
| 74 | createEffect(() => { |
| 75 | if (filePage() >= totalPages()) setFilePage(totalPages() - 1); |
| 76 | }); |
| 77 | |
| 78 | const upload = async (file: File | undefined): Promise<boolean> => { |
| 79 | if (!file) return false; |
| 80 | setError(""); |
| 81 | if (file.size > maxFileBytes()) { |
| 82 | setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); |
| 83 | return false; |
| 84 | } |
| 85 | setPending(true); |
| 86 | try { |
| 87 | await props.source.uploadFile(props.noteId, file); |
| 88 | await refetch(); |
| 89 | if (input) input.value = ""; |
| 90 | setFlash(t("common.created")); |
| 91 | return true; |
| 92 | } catch (err) { |
| 93 | setError(formatApiError(err)); |
| 94 | return false; |
| 95 | } finally { |
| 96 | setPending(false); |
| 97 | } |
| 98 | }; |
| 99 | |
| 100 | const download = (file: NoteFile) => { |
| 101 | const link = document.createElement("a"); |
| 102 | link.href = props.source.fileUrl(props.noteId, file.id); |
| 103 | link.download = file.name; |
| 104 | link.click(); |
| 105 | }; |
| 106 | |
| 107 | const openNewDrawing = () => { |
| 108 | setEditScene(null); |
| 109 | setEditTarget(null); |
| 110 | setDrawOpen(true); |
| 111 | }; |
| 112 | |
| 113 | const openEditDrawing = async (file: NoteFile) => { |
| 114 | setError(""); |
| 115 | try { |
| 116 | const blob = await props.source.fileBlob(props.noteId, file.id); |
| 117 | const { pngBytesToScene } = await import("@/lib/drawing-file"); |
| 118 | setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); |
| 119 | setEditTarget(file); |
| 120 | setDrawOpen(true); |
| 121 | } catch (err) { |
| 122 | setError(formatApiError(err)); |
| 123 | } |
| 124 | }; |
| 125 | |
| 126 | // Create-new-then-delete-old: the replacement must be safely stored before the |
| 127 | // original is removed, so a failed upload never loses the existing drawing. |
| 128 | const saveDrawing = async (file: File) => { |
| 129 | const target = editTarget(); |
| 130 | if (!(await upload(file))) return; |
| 131 | if (target) { |
| 132 | try { |
| 133 | await props.source.deleteFile(props.noteId, target.id); |
| 134 | await refetch(); |
| 135 | } catch { |
| 136 | // New drawing is saved; deleting the old copy failed — a stale duplicate |
| 137 | // remains, but nothing is lost. Leave it rather than risk the new one. |
| 138 | } |
| 139 | } |
| 140 | setEditScene(null); |
| 141 | setEditTarget(null); |
| 142 | setDrawOpen(false); |
| 143 | }; |
| 144 | |
| 145 | return ( |
| 146 | <section class="space-y-3 rounded-xl border border-border-line bg-card p-4 shadow-xs"> |
| 147 | <Show when={flash()}> |
| 148 | <Alert variant="success">{flash()}</Alert> |
| 149 | </Show> |
| 150 | <div class="space-y-3"> |
| 151 | <div> |
| 152 | <h3 class="text-sm font-semibold">{t("notes.files")}</h3> |
| 153 | <Show when={canManage()}> |
| 154 | <p class="mt-1 text-xs text-muted-foreground">{t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}</p> |
| 155 | </Show> |
| 156 | </div> |
| 157 | <input |
| 158 | ref={(el) => { |
| 159 | input = el; |
| 160 | }} |
| 161 | type="file" |
| 162 | class="hidden" |
| 163 | disabled={pending() || atLimit()} |
| 164 | onChange={(event) => void upload(event.currentTarget.files?.[0])} |
| 165 | /> |
| 166 | <Show when={canManage()}> |
| 167 | {/* Two equal halves spanning the panel, the same width as the drop |
| 168 | area and file list under them. */} |
| 169 | <div class="grid w-full grid-cols-2 gap-2"> |
| 170 | <Button type="button" variant="outline" size="sm" class="h-10 w-full rounded-full text-[13px] sm:h-8 touch:h-10" disabled={pending() || atLimit()} onClick={openNewDrawing}> |
| 171 | <IconEdit class="h-4 w-4 shrink-0" /> |
| 172 | <span class="truncate">{t("notes.draw")}</span> |
| 173 | </Button> |
| 174 | <Button type="button" size="sm" class="h-10 w-full rounded-full text-[13px] sm:h-8 touch:h-10" disabled={pending() || atLimit()} onClick={() => input?.click()}> |
| 175 | <IconPlus class="h-4 w-4 shrink-0" /> |
| 176 | <span class="truncate">{t("notes.addFile")}</span> |
| 177 | </Button> |
| 178 | </div> |
| 179 | </Show> |
| 180 | </div> |
| 181 | |
| 182 | {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{error()}</p>} |
| 183 | <Show when={canManage() && atLimit()}> |
| 184 | <p class="text-xs text-muted-foreground">{t("notes.fileLimit")}</p> |
| 185 | </Show> |
| 186 | |
| 187 | <Show when={files.error}> |
| 188 | <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{formatApiError(files.error)}</p> |
| 189 | </Show> |
| 190 | |
| 191 | <Suspense fallback={<PageSpinner />}> |
| 192 | <Show |
| 193 | when={(files() ?? []).length > 0} |
| 194 | fallback={!files.error && <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>} |
| 195 | > |
| 196 | <ul class="grid grid-cols-1 gap-3 rounded-md border border-border/70 bg-background/70 p-2 sm:grid-cols-2"> |
| 197 | <For each={pageFiles()}> |
| 198 | {(file) => { |
| 199 | const meta = fileTypeMeta(file, "h-8 w-8"); |
| 200 | return ( |
| 201 | <li class="group overflow-hidden rounded-xl border border-border/70 bg-card text-sm shadow-xs transition-colors hover:border-primary/40"> |
| 202 | <div class="relative h-28 bg-muted/25"> |
| 203 | <button type="button" class="flex h-full w-full items-center justify-center rounded-t-xl transition-colors hover:bg-muted/40" aria-label={`${t("common.view")}: ${file.name}`} onClick={() => setPreviewFile(file)}> |
| 204 | <span class={cn("flex h-16 w-16 items-center justify-center rounded-lg border", meta.class)}> |
| 205 | {meta.icon} |
| 206 | </span> |
| 207 | </button> |
| 208 | <span class={cn("absolute left-2 top-2 rounded px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide", meta.class)}> |
| 209 | {meta.label} |
| 210 | </span> |
| 211 | <div class="absolute right-2 top-2 z-10 rounded-xl border border-border/80 bg-card/90 shadow-md dark:border-white/15 dark:bg-card/95"> |
| 212 | <TableRowActions |
| 213 | label={t("common.actions")} |
| 214 | actions={[ |
| 215 | { |
| 216 | label: t("common.view"), |
| 217 | icon: <IconEye class="h-4 w-4" />, |
| 218 | onSelect: () => setPreviewFile(file), |
| 219 | }, |
| 220 | ...(canManage() && isDrawing(file) |
| 221 | ? [ |
| 222 | { |
| 223 | label: t("common.edit"), |
| 224 | icon: <IconEdit class="h-4 w-4" />, |
| 225 | onSelect: () => void openEditDrawing(file), |
| 226 | }, |
| 227 | ] |
| 228 | : []), |
| 229 | { |
| 230 | label: t("notes.downloadFile"), |
| 231 | icon: <IconDownload class="h-4 w-4" />, |
| 232 | onSelect: () => download(file), |
| 233 | }, |
| 234 | ...(canManage() |
| 235 | ? [ |
| 236 | { |
| 237 | label: t("common.delete"), |
| 238 | icon: <IconTrash class="h-4 w-4" />, |
| 239 | destructive: true, |
| 240 | onSelect: () => setDeleteTarget(file), |
| 241 | }, |
| 242 | ] |
| 243 | : []), |
| 244 | ]} |
| 245 | /> |
| 246 | </div> |
| 247 | </div> |
| 248 | <button type="button" class="w-full px-3 py-2 text-left hover:bg-muted/30" onClick={() => setPreviewFile(file)}> |
| 249 | <span class="block truncate font-medium">{file.name}</span> |
| 250 | <span class="mt-1 block text-xs text-muted-foreground">{formatBytes(file.size)}</span> |
| 251 | </button> |
| 252 | </li> |
| 253 | ); |
| 254 | }} |
| 255 | </For> |
| 256 | </ul> |
| 257 | <Show when={(files() ?? []).length > FILE_PAGE_SIZE}> |
| 258 | <TablePagination pageIndex={filePage()} pageCount={totalPages()} onPageChange={setFilePage} /> |
| 259 | </Show> |
| 260 | <NoteFilePreview noteId={props.noteId} source={props.source} file={previewFile()} onClose={() => setPreviewFile(null)} /> |
| 261 | </Show> |
| 262 | </Suspense> |
| 263 | |
| 264 | <FormDialog |
| 265 | open={drawOpen()} |
| 266 | onOpenChange={(open) => { |
| 267 | setDrawOpen(open); |
| 268 | if (!open) { |
| 269 | setEditScene(null); |
| 270 | setEditTarget(null); |
| 271 | } |
| 272 | }} |
| 273 | title={t("notes.drawTitle")} |
| 274 | class="sm:max-w-3xl" |
| 275 | > |
| 276 | <Show when={error()}> |
| 277 | <p class="mb-3 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{error()}</p> |
| 278 | </Show> |
| 279 | <Suspense fallback={<PageSpinner />}> |
| 280 | <DrawCanvas |
| 281 | pending={pending()} |
| 282 | initialScene={editScene()} |
| 283 | fileName={editTarget()?.name ?? `drawing-${(files() ?? []).length + 1}${DRAWING_SUFFIX}`} |
| 284 | onSave={(file) => void saveDrawing(file)} |
| 285 | /> |
| 286 | </Suspense> |
| 287 | </FormDialog> |
| 288 | |
| 289 | <ConfirmDialog |
| 290 | open={deleteTarget() != null} |
| 291 | onOpenChange={(open) => !open && setDeleteTarget(null)} |
| 292 | title={t("confirm.deleteTitle")} |
| 293 | variant="destructive" |
| 294 | summary={t("confirm.deleteNoteFile", { title: deleteTarget()?.name ?? "" })} |
| 295 | onConfirm={async () => { |
| 296 | const target = deleteTarget(); |
| 297 | if (!target) return; |
| 298 | await props.source.deleteFile(props.noteId, target.id); |
| 299 | if (previewFile()?.id === target.id) setPreviewFile(null); |
| 300 | setDeleteTarget(null); |
| 301 | await refetch(); |
| 302 | setFlash(t("common.deleted")); |
| 303 | }} |
| 304 | /> |
| 305 | </section> |
| 306 | ); |
| 307 | } |