📎 client-side upload limits and shared error handling
Browse files at this commitfed2a93290d8e5073e72eae7c4d6c7e962b935ebParent: b92c765- feat
- 📎 client-side upload limits and shared error handling
9 changed files +225 -45
- src/api/__tests__/client/client.test.ts +2 -2
- src/api/client/client.ts +101 -16
- src/components/exams/exam-room-ws.tsx +15 -1
- src/components/exams/question-form.tsx +36 -4
- src/components/notes/note-files-panel.tsx +2 -7
- src/components/notes/note-form.tsx +2 -7
- src/lib/upload-limits.ts +13 -0
- src/pages/question-detail-page.tsx +27 -4
- src/pages/questions-page.tsx +27 -4
src/api/__tests__/client/client.test.tsmodified+2 -2
| @@ -126,7 +126,7 @@ describe("client", () => { | ||
| 126 | 126 | |
| 127 | 127 | it("handles unknown messages with sentence case", () => { |
| 128 | 128 | expect(formatApiErrorMessage("custom error occurred", "en")).toBe("Custom error occurred"); |
| 129 | - expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı. Lütfen tekrar dene."); | |
| 129 | + expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı: Custom error occurred"); | |
| 130 | 130 | }); |
| 131 | 131 | }); |
| 132 | 132 | |
| @@ -150,7 +150,7 @@ describe("client", () => { | ||
| 150 | 150 | |
| 151 | 151 | it("formats generic Error", () => { |
| 152 | 152 | expect(formatApiError(new Error("generic"), "en")).toBe("Generic"); |
| 153 | - expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı. Lütfen tekrar dene."); | |
| 153 | + expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı: Generic"); | |
| 154 | 154 | }); |
| 155 | 155 | }); |
| 156 | 156 | }); |
src/api/client/client.tsmodified+101 -16
| @@ -46,6 +46,38 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | ||
| 46 | 46 | en: "This username is already in use.", |
| 47 | 47 | tr: "Bu kullanıcı adı zaten kullanılıyor.", |
| 48 | 48 | }, |
| 49 | + "file too large": { | |
| 50 | + en: "This file is larger than the allowed upload limit.", | |
| 51 | + tr: "Bu dosya izin verilen yükleme sınırından büyük.", | |
| 52 | + }, | |
| 53 | + "payload too large": { | |
| 54 | + en: "This upload is too large. Choose a smaller file and try again.", | |
| 55 | + tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", | |
| 56 | + }, | |
| 57 | + "request entity too large": { | |
| 58 | + en: "This upload is too large. Choose a smaller file and try again.", | |
| 59 | + tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", | |
| 60 | + }, | |
| 61 | + "unsupported file type": { | |
| 62 | + en: "This file type is not supported.", | |
| 63 | + tr: "Bu dosya türü desteklenmiyor.", | |
| 64 | + }, | |
| 65 | + "unsupported image type": { | |
| 66 | + en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.", | |
| 67 | + tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.", | |
| 68 | + }, | |
| 69 | + "invalid image": { | |
| 70 | + en: "The image could not be read. Choose another image and try again.", | |
| 71 | + tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.", | |
| 72 | + }, | |
| 73 | + "too many files": { | |
| 74 | + en: "This note already has the maximum number of files.", | |
| 75 | + tr: "Bu notta en fazla dosya sayısına ulaşılmış.", | |
| 76 | + }, | |
| 77 | + "note file limit reached": { | |
| 78 | + en: "This note already has the maximum number of files.", | |
| 79 | + tr: "Bu notta en fazla dosya sayısına ulaşılmış.", | |
| 80 | + }, | |
| 49 | 81 | "course not found": { |
| 50 | 82 | en: "Course not found.", |
| 51 | 83 | tr: "Ders bulunamadı.", |
| @@ -74,6 +106,22 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | ||
| 74 | 106 | en: "This attempt is closed. Answers are read-only.", |
| 75 | 107 | tr: "Bu oturum kapalı. Cevaplar salt okunur.", |
| 76 | 108 | }, |
| 109 | + "exam has not started": { | |
| 110 | + en: "This exam has not started yet.", | |
| 111 | + tr: "Bu sınav henüz başlamadı.", | |
| 112 | + }, | |
| 113 | + "exam has ended": { | |
| 114 | + en: "This exam has ended.", | |
| 115 | + tr: "Bu sınav sona erdi.", | |
| 116 | + }, | |
| 117 | + "no attempts left": { | |
| 118 | + en: "No attempts left for this exam.", | |
| 119 | + tr: "Bu sınav için deneme hakkı kalmadı.", | |
| 120 | + }, | |
| 121 | + "answer is required": { | |
| 122 | + en: "Enter an answer before saving.", | |
| 123 | + tr: "Kaydetmeden önce cevap gir.", | |
| 124 | + }, | |
| 77 | 125 | "only students can sit exams": { |
| 78 | 126 | en: "Only students can take exams.", |
| 79 | 127 | tr: "Sınava yalnızca öğrenciler girebilir.", |
| @@ -90,6 +138,30 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | ||
| 90 | 138 | en: "Only students can be marked on a lesson roll call.", |
| 91 | 139 | tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.", |
| 92 | 140 | }, |
| 141 | + "event is full": { | |
| 142 | + en: "This event is full.", | |
| 143 | + tr: "Bu etkinlik dolu.", | |
| 144 | + }, | |
| 145 | + "registration is closed": { | |
| 146 | + en: "Registration is closed for this event.", | |
| 147 | + tr: "Bu etkinlik için kayıt kapalı.", | |
| 148 | + }, | |
| 149 | + "already registered": { | |
| 150 | + en: "This student is already registered.", | |
| 151 | + tr: "Bu öğrenci zaten kayıtlı.", | |
| 152 | + }, | |
| 153 | + "already enrolled": { | |
| 154 | + en: "This student is already enrolled.", | |
| 155 | + tr: "Bu öğrenci zaten kayıtlı.", | |
| 156 | + }, | |
| 157 | + "active pomodoro session already exists": { | |
| 158 | + en: "You already have a focus session running.", | |
| 159 | + tr: "Zaten devam eden bir odak oturumun var.", | |
| 160 | + }, | |
| 161 | + "no active pomodoro session": { | |
| 162 | + en: "There is no active focus session to finish.", | |
| 163 | + tr: "Bitirilecek aktif odak oturumu yok.", | |
| 164 | + }, | |
| 93 | 165 | }; |
| 94 | 166 | |
| 95 | 167 | function currentLocale(): Locale { |
| @@ -118,6 +190,28 @@ function sentenceCase(message: string): string { | ||
| 118 | 190 | return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); |
| 119 | 191 | } |
| 120 | 192 | |
| 193 | +function errorMessageFromPayload(data: unknown, fallback: string): string { | |
| 194 | + if (!data || typeof data !== "object") return fallback; | |
| 195 | + const record = data as Record<string, unknown>; | |
| 196 | + if (typeof record.error === "string") return record.error; | |
| 197 | + if (typeof record.message === "string") return record.message; | |
| 198 | + const detail = record.detail; | |
| 199 | + if (typeof detail === "string") return detail; | |
| 200 | + if (Array.isArray(detail)) { | |
| 201 | + return detail | |
| 202 | + .map((item) => { | |
| 203 | + if (!item || typeof item !== "object") return ""; | |
| 204 | + const row = item as Record<string, unknown>; | |
| 205 | + const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : ""; | |
| 206 | + const msg = typeof row.msg === "string" ? row.msg : ""; | |
| 207 | + return loc && msg ? `${loc}: ${msg}` : msg; | |
| 208 | + }) | |
| 209 | + .filter(Boolean) | |
| 210 | + .join("; ") || fallback; | |
| 211 | + } | |
| 212 | + return fallback; | |
| 213 | +} | |
| 214 | + | |
| 121 | 215 | export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> { |
| 122 | 216 | const headers: Record<string, string> = {}; |
| 123 | 217 | let body: string | undefined; |
| @@ -151,12 +245,7 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro | ||
| 151 | 245 | } |
| 152 | 246 | |
| 153 | 247 | if (!res.ok) { |
| 154 | - const message = | |
| 155 | - data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" | |
| 156 | - ? (data as { error: string }).error | |
| 157 | - : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" | |
| 158 | - ? (data as { message: string }).message | |
| 159 | - : res.statusText || "Request failed"; | |
| 248 | + const message = errorMessageFromPayload(data, res.statusText || "Request failed"); | |
| 160 | 249 | |
| 161 | 250 | let retryAfter: number | null = null; |
| 162 | 251 | if (res.status === 429) { |
| @@ -192,12 +281,7 @@ export async function formClient<T>(path: string, body: FormData, signal?: Abort | ||
| 192 | 281 | } |
| 193 | 282 | |
| 194 | 283 | if (!res.ok) { |
| 195 | - const message = | |
| 196 | - data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" | |
| 197 | - ? (data as { error: string }).error | |
| 198 | - : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" | |
| 199 | - ? (data as { message: string }).message | |
| 200 | - : res.statusText || "Request failed"; | |
| 284 | + const message = errorMessageFromPayload(data, res.statusText || "Request failed"); | |
| 201 | 285 | throw new ApiError(res.status, message); |
| 202 | 286 | } |
| 203 | 287 | |
| @@ -215,9 +299,7 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise<Bl | ||
| 215 | 299 | let message = res.statusText || "Request failed"; |
| 216 | 300 | if (text) { |
| 217 | 301 | try { |
| 218 | - const data = JSON.parse(text) as { error?: unknown; message?: unknown }; | |
| 219 | - if (typeof data.error === "string") message = data.error; | |
| 220 | - else if (typeof data.message === "string") message = data.message; | |
| 302 | + message = errorMessageFromPayload(JSON.parse(text), message); | |
| 221 | 303 | } catch { |
| 222 | 304 | message = text; |
| 223 | 305 | } |
| @@ -232,7 +314,7 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL | ||
| 232 | 314 | const normalized = normalizeApiMessage(message); |
| 233 | 315 | const known = API_ERROR_MESSAGES[normalized]?.[locale]; |
| 234 | 316 | if (known) return known; |
| 235 | - if (locale === "tr") return "İşlem tamamlanamadı. Lütfen tekrar dene."; | |
| 317 | + if (locale === "tr") return `İşlem tamamlanamadı: ${sentenceCase(message)}`; | |
| 236 | 318 | return sentenceCase(message); |
| 237 | 319 | } |
| 238 | 320 | |
| @@ -244,6 +326,9 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()): | ||
| 244 | 326 | if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; |
| 245 | 327 | if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale]; |
| 246 | 328 | if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale]; |
| 329 | + if (err.status === 409) return formatApiErrorMessage(err.message, locale); | |
| 330 | + if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale]; | |
| 331 | + if (err.status === 422) return formatApiErrorMessage(err.message, locale); | |
| 247 | 332 | if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; |
| 248 | 333 | return formatApiErrorMessage(err.message, locale); |
| 249 | 334 | } |
src/components/exams/exam-room-ws.tsxmodified+15 -1
| @@ -1,6 +1,7 @@ | ||
| 1 | -import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createSignal, lazy, onCleanup } from "solid-js"; | |
| 1 | +import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createResource, createSignal, lazy, onCleanup } from "solid-js"; | |
| 2 | 2 | import { getExamAttempt } from "@/api/exams"; |
| 3 | 3 | import { getExamAttemptQuestions } from "@/api/exams"; |
| 4 | +import { getSettings } from "@/api/settings"; | |
| 4 | 5 | import { postExamAttempt } from "@/api/exams"; |
| 5 | 6 | import { postExamAttemptAnswer } from "@/api/exams"; |
| 6 | 7 | import { postExamAttemptFinish } from "@/api/exams"; |
| @@ -20,6 +21,7 @@ import { Textarea } from "@/components/ui/textarea"; | ||
| 20 | 21 | import { cn } from "@/lib/cn"; |
| 21 | 22 | import { createNow } from "@/lib/create-now"; |
| 22 | 23 | import { formatDateTime } from "@/lib/format"; |
| 24 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 23 | 25 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 24 | 26 | |
| 25 | 27 | // Lazy so the drawing pad rides its own chunk, off the exam room's initial load. |
| @@ -56,7 +58,15 @@ export function ExamRoomWS(props: { exam: Exam }) { | ||
| 56 | 58 | const [activeQuestionIndex, setActiveQuestionIndex] = createSignal(0); |
| 57 | 59 | const [remainingMs, setRemainingMs] = createSignal<number | null>(0); |
| 58 | 60 | const [wsState, setWsState] = createSignal<WsState>("disconnected"); |
| 61 | + const [settings] = createResource(async () => { | |
| 62 | + try { | |
| 63 | + return await getSettings(); | |
| 64 | + } catch { | |
| 65 | + return null; | |
| 66 | + } | |
| 67 | + }); | |
| 59 | 68 | const now = createNow(); |
| 69 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 60 | 70 | const scheduled = createMemo(() => props.exam.mode === "sync" || props.exam.mode === "async" || props.exam.mode === "open"); |
| 61 | 71 | const attemptStatus = createMemo(() => { |
| 62 | 72 | const current = attempt(); |
| @@ -238,6 +248,10 @@ export function ExamRoomWS(props: { exam: Exam }) { | ||
| 238 | 248 | |
| 239 | 249 | const saveAnswerImage = async (question: AttemptQuestion, file: File) => { |
| 240 | 250 | setError(""); |
| 251 | + if (file.size > maxFileBytes()) { | |
| 252 | + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); | |
| 253 | + return; | |
| 254 | + } | |
| 241 | 255 | setPending(true); |
| 242 | 256 | try { |
| 243 | 257 | await postExamAttemptAnswerImage(props.exam.id, question.id, file); |
src/components/exams/question-form.tsxmodified+36 -4
| @@ -1,8 +1,9 @@ | ||
| 1 | -import { For, Index, Show, Suspense, createEffect, createSignal, lazy } from "solid-js"; | |
| 1 | +import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy } from "solid-js"; | |
| 2 | 2 | import { formatApiError } from "@/api/client"; |
| 3 | 3 | import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; |
| 4 | 4 | import { QUESTION_KINDS } from "@/api/client"; |
| 5 | 5 | import { getExamQuestionImageBlob } from "@/api/exams"; |
| 6 | +import { getSettings } from "@/api/settings"; | |
| 6 | 7 | import type { DrawScene } from "@/lib/draw-stroke"; |
| 7 | 8 | import { Button } from "@/components/ui/button"; |
| 8 | 9 | import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons"; |
| @@ -11,6 +12,7 @@ import { Label } from "@/components/ui/label"; | ||
| 11 | 12 | import { Select } from "@/components/ui/select"; |
| 12 | 13 | import { Textarea } from "@/components/ui/textarea"; |
| 13 | 14 | import { cn } from "@/lib/cn"; |
| 15 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 14 | 16 | import { useT } from "@/stores/preferences-context"; |
| 15 | 17 | |
| 16 | 18 | // Lazy so the drawing pad rides its own chunk, off the exam editor's initial load. |
| @@ -47,6 +49,14 @@ export function QuestionForm(props: { | ||
| 47 | 49 | const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); |
| 48 | 50 | const [error, setError] = createSignal(""); |
| 49 | 51 | const [pending, setPending] = createSignal(false); |
| 52 | + const [settings] = createResource(async () => { | |
| 53 | + try { | |
| 54 | + return await getSettings(); | |
| 55 | + } catch { | |
| 56 | + return null; | |
| 57 | + } | |
| 58 | + }); | |
| 59 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 50 | 60 | |
| 51 | 61 | createEffect(() => { |
| 52 | 62 | const initial = props.initial; |
| @@ -99,7 +109,27 @@ export function QuestionForm(props: { | ||
| 99 | 109 | setChoices((current) => current.map((choice, i) => (i === index ? value : choice))); |
| 100 | 110 | }; |
| 101 | 111 | |
| 112 | + const validImage = (file: File | null): file is File => { | |
| 113 | + if (!file) return false; | |
| 114 | + if (file.size <= maxFileBytes()) return true; | |
| 115 | + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); | |
| 116 | + return false; | |
| 117 | + }; | |
| 118 | + | |
| 119 | + const setQuestionImage = (file: File | null) => { | |
| 120 | + if (!file) { | |
| 121 | + setImage(null); | |
| 122 | + return; | |
| 123 | + } | |
| 124 | + setError(""); | |
| 125 | + if (validImage(file)) setImage(file); | |
| 126 | + }; | |
| 127 | + | |
| 102 | 128 | const setChoiceImage = (index: number, file: File | null) => { |
| 129 | + if (file) { | |
| 130 | + setError(""); | |
| 131 | + if (!validImage(file)) return; | |
| 132 | + } | |
| 103 | 133 | setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null))); |
| 104 | 134 | }; |
| 105 | 135 | |
| @@ -190,7 +220,7 @@ export function QuestionForm(props: { | ||
| 190 | 220 | type="file" |
| 191 | 221 | accept="image/png,image/jpeg,image/webp,image/gif" |
| 192 | 222 | class="sr-only" |
| 193 | - onChange={(event) => setImage(event.currentTarget.files?.[0] ?? null)} | |
| 223 | + onChange={(event) => setQuestionImage(event.currentTarget.files?.[0] ?? null)} | |
| 194 | 224 | /> |
| 195 | 225 | <label for="question-image" class="flex cursor-pointer items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"> |
| 196 | 226 | <IconFileImage class="h-3.5 w-3.5" /> |
| @@ -225,8 +255,10 @@ export function QuestionForm(props: { | ||
| 225 | 255 | fileName="question.png" |
| 226 | 256 | initialScene={editScene()} |
| 227 | 257 | onSave={(file) => { |
| 228 | - setImage(file); | |
| 229 | - setDrawing(false); | |
| 258 | + if (validImage(file)) { | |
| 259 | + setImage(file); | |
| 260 | + setDrawing(false); | |
| 261 | + } | |
| 230 | 262 | }} |
| 231 | 263 | /> |
| 232 | 264 | </Suspense> |
src/components/notes/note-files-panel.tsxmodified+2 -7
| @@ -31,6 +31,7 @@ import { PageSpinner } from "@/components/ui/page-spinner"; | ||
| 31 | 31 | import { PaginationControls } from "@/components/ui/pagination-controls"; |
| 32 | 32 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 33 | 33 | import { cn } from "@/lib/cn"; |
| 34 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 34 | 35 | import { useT } from "@/stores/preferences-context"; |
| 35 | 36 | |
| 36 | 37 | // Lazy so the drawing pad rides its own chunk, off the notes page's initial load. |
| @@ -43,12 +44,6 @@ const FILE_PAGE_SIZE = 4; | ||
| 43 | 44 | const DRAWING_SUFFIX = ".hzdraw.png"; |
| 44 | 45 | const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX); |
| 45 | 46 | |
| 46 | -function formatBytes(bytes: number): string { | |
| 47 | - if (bytes < 1024) return `${bytes} B`; | |
| 48 | - if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; | |
| 49 | - return `${(bytes / 1024 / 1024).toFixed(1)} MB`; | |
| 50 | -} | |
| 51 | - | |
| 52 | 47 | function extension(name: string): string { |
| 53 | 48 | const ext = name.split(".").pop()?.toLowerCase(); |
| 54 | 49 | return ext && ext !== name.toLowerCase() ? ext : "file"; |
| @@ -92,7 +87,7 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | ||
| 92 | 87 | return null; |
| 93 | 88 | } |
| 94 | 89 | }); |
| 95 | - const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024; | |
| 90 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 96 | 91 | const atLimit = () => (files() ?? []).length >= MAX_NOTE_FILES; |
| 97 | 92 | const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE))); |
| 98 | 93 | const pageFiles = createMemo(() => { |
src/components/notes/note-form.tsxmodified+2 -7
| @@ -8,6 +8,7 @@ import { IconPlus, IconTrash } from "@/components/ui/icons"; | ||
| 8 | 8 | import { Input } from "@/components/ui/input"; |
| 9 | 9 | import { Label } from "@/components/ui/label"; |
| 10 | 10 | import { Textarea } from "@/components/ui/textarea"; |
| 11 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 11 | 12 | import { useT } from "@/stores/preferences-context"; |
| 12 | 13 | |
| 13 | 14 | export type NoteFormValues = { |
| @@ -18,12 +19,6 @@ export type NoteFormValues = { | ||
| 18 | 19 | |
| 19 | 20 | const MAX_NOTE_FILES = 10; |
| 20 | 21 | |
| 21 | -function formatBytes(bytes: number): string { | |
| 22 | - if (bytes < 1024) return `${bytes} B`; | |
| 23 | - if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; | |
| 24 | - return `${(bytes / 1024 / 1024).toFixed(1)} MB`; | |
| 25 | -} | |
| 26 | - | |
| 27 | 22 | export function NoteForm(props: { |
| 28 | 23 | initial?: Partial<Note>; |
| 29 | 24 | submitLabel?: string; |
| @@ -49,7 +44,7 @@ export function NoteForm(props: { | ||
| 49 | 44 | return null; |
| 50 | 45 | } |
| 51 | 46 | }); |
| 52 | - const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024; | |
| 47 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 53 | 48 | const showFiles = () => !!props.enableFiles && !isUpdate(); |
| 54 | 49 | |
| 55 | 50 | const validate = (): string | null => { |
src/lib/upload-limits.tsadded+13 -0
| @@ -0,0 +1,13 @@ | ||
| 1 | +import type { SchoolSettings } from "@/api/client"; | |
| 2 | + | |
| 3 | +export const DEFAULT_MAX_FILE_BYTES = 5 * 1024 * 1024; | |
| 4 | + | |
| 5 | +export function maxUploadBytes(settings: SchoolSettings | null | undefined): number { | |
| 6 | + return settings?.max_file_bytes ?? DEFAULT_MAX_FILE_BYTES; | |
| 7 | +} | |
| 8 | + | |
| 9 | +export function formatBytes(bytes: number): string { | |
| 10 | + if (bytes < 1024) return `${bytes} B`; | |
| 11 | + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; | |
| 12 | + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; | |
| 13 | +} |
src/pages/question-detail-page.tsxmodified+27 -4
| @@ -2,6 +2,7 @@ import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-j | ||
| 2 | 2 | import { useParams, useRouter } from "@tanstack/solid-router"; |
| 3 | 3 | import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared"; |
| 4 | 4 | import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared"; |
| 5 | +import { getSettings } from "@/api/settings"; | |
| 5 | 6 | import type { SolutionResponse } from "@/api/shared"; |
| 6 | 7 | import { formatApiError } from "@/api/client"; |
| 7 | 8 | import { RouteGuard } from "@/components/layout/route-guard"; |
| @@ -20,6 +21,7 @@ import { showToast } from "@/components/ui/toast"; | ||
| 20 | 21 | import { useT } from "@/stores/preferences-context"; |
| 21 | 22 | import { useAuth } from "@/stores/auth-context"; |
| 22 | 23 | import { hasMinRole } from "@/lib/roles"; |
| 24 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 23 | 25 | |
| 24 | 26 | // Lazy so the drawing pad rides its own chunk, off the question detail's initial load. |
| 25 | 27 | const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); |
| @@ -251,6 +253,27 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR | ||
| 251 | 253 | const [body, setBody] = createSignal(props.initialData?.body || ""); |
| 252 | 254 | const [file, setFile] = createSignal<File | null>(null); |
| 253 | 255 | const [drawing, setDrawing] = createSignal(false); |
| 256 | + const [settings] = createResource(async () => { | |
| 257 | + try { | |
| 258 | + return await getSettings(); | |
| 259 | + } catch { | |
| 260 | + return null; | |
| 261 | + } | |
| 262 | + }); | |
| 263 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 264 | + | |
| 265 | + const setImageFile = (next: File | null) => { | |
| 266 | + if (!next) { | |
| 267 | + setFile(null); | |
| 268 | + return; | |
| 269 | + } | |
| 270 | + setError(""); | |
| 271 | + if (next.size > maxFileBytes()) { | |
| 272 | + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); | |
| 273 | + return; | |
| 274 | + } | |
| 275 | + setFile(next); | |
| 276 | + }; | |
| 254 | 277 | |
| 255 | 278 | const handleSubmit = async (e: Event) => { |
| 256 | 279 | e.preventDefault(); |
| @@ -311,14 +334,14 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR | ||
| 311 | 334 | </div> |
| 312 | 335 | <div class="mt-4 text-center"> |
| 313 | 336 | <p class="text-sm font-medium text-foreground">{t("pool.image")}</p> |
| 314 | - <p class="mt-1 text-xs text-muted-foreground">PNG, JPG, GIF</p> | |
| 337 | + <p class="mt-1 text-xs text-muted-foreground">PNG, JPG, GIF · {formatBytes(maxFileBytes())}</p> | |
| 315 | 338 | </div> |
| 316 | 339 | </Show> |
| 317 | 340 | <input |
| 318 | 341 | type="file" |
| 319 | 342 | accept="image/*" |
| 320 | 343 | class="absolute inset-0 z-0 h-full w-full cursor-pointer opacity-0" |
| 321 | - onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} | |
| 344 | + onChange={(e) => setImageFile(e.currentTarget.files?.[0] || null)} | |
| 322 | 345 | /> |
| 323 | 346 | </div> |
| 324 | 347 | {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */} |
| @@ -331,8 +354,8 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR | ||
| 331 | 354 | <DrawCanvas |
| 332 | 355 | fileName="solution.png" |
| 333 | 356 | onSave={(drawn) => { |
| 334 | - setFile(drawn); | |
| 335 | - setDrawing(false); | |
| 357 | + setImageFile(drawn); | |
| 358 | + if (drawn.size <= maxFileBytes()) setDrawing(false); | |
| 336 | 359 | }} |
| 337 | 360 | /> |
| 338 | 361 | </Suspense> |
src/pages/questions-page.tsxmodified+27 -4
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js"; |
| 2 | 2 | import { Link, useSearch, useNavigate } from "@tanstack/solid-router"; |
| 3 | 3 | import { getQuestions, postQuestion } from "@/api/shared"; |
| 4 | +import { getSettings } from "@/api/settings"; | |
| 4 | 5 | import { formatApiError } from "@/api/client"; |
| 5 | 6 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 6 | 7 | import { PageHeader } from "@/components/layout/page-header"; |
| @@ -19,6 +20,7 @@ import { showToast } from "@/components/ui/toast"; | ||
| 19 | 20 | import { useT } from "@/stores/preferences-context"; |
| 20 | 21 | import { useAuth } from "@/stores/auth-context"; |
| 21 | 22 | import { cn } from "@/lib/cn"; |
| 23 | +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; | |
| 22 | 24 | |
| 23 | 25 | // Lazy so the drawing pad rides its own chunk, off the question list's initial load. |
| 24 | 26 | const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); |
| @@ -141,6 +143,27 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } | ||
| 141 | 143 | const [body, setBody] = createSignal(""); |
| 142 | 144 | const [file, setFile] = createSignal<File | null>(null); |
| 143 | 145 | const [drawing, setDrawing] = createSignal(false); |
| 146 | + const [settings] = createResource(async () => { | |
| 147 | + try { | |
| 148 | + return await getSettings(); | |
| 149 | + } catch { | |
| 150 | + return null; | |
| 151 | + } | |
| 152 | + }); | |
| 153 | + const maxFileBytes = () => maxUploadBytes(settings()); | |
| 154 | + | |
| 155 | + const setImageFile = (next: File | null) => { | |
| 156 | + if (!next) { | |
| 157 | + setFile(null); | |
| 158 | + return; | |
| 159 | + } | |
| 160 | + setError(""); | |
| 161 | + if (next.size > maxFileBytes()) { | |
| 162 | + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); | |
| 163 | + return; | |
| 164 | + } | |
| 165 | + setFile(next); | |
| 166 | + }; | |
| 144 | 167 | |
| 145 | 168 | const handleSubmit = async (e: Event) => { |
| 146 | 169 | e.preventDefault(); |
| @@ -200,14 +223,14 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } | ||
| 200 | 223 | </div> |
| 201 | 224 | <div class="mt-4 text-center"> |
| 202 | 225 | <p class="text-sm font-medium text-foreground">{t("pool.image")}</p> |
| 203 | - <p class="mt-1 text-xs text-muted-foreground">PNG, JPG, GIF</p> | |
| 226 | + <p class="mt-1 text-xs text-muted-foreground">PNG, JPG, GIF · {formatBytes(maxFileBytes())}</p> | |
| 204 | 227 | </div> |
| 205 | 228 | </Show> |
| 206 | 229 | <input |
| 207 | 230 | type="file" |
| 208 | 231 | accept="image/*" |
| 209 | 232 | class="absolute inset-0 z-0 h-full w-full cursor-pointer opacity-0" |
| 210 | - onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} | |
| 233 | + onChange={(e) => setImageFile(e.currentTarget.files?.[0] || null)} | |
| 211 | 234 | /> |
| 212 | 235 | </div> |
| 213 | 236 | {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */} |
| @@ -220,8 +243,8 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } | ||
| 220 | 243 | <DrawCanvas |
| 221 | 244 | fileName="question.png" |
| 222 | 245 | onSave={(drawn) => { |
| 223 | - setFile(drawn); | |
| 224 | - setDrawing(false); | |
| 246 | + setImageFile(drawn); | |
| 247 | + if (drawn.size <= maxFileBytes()) setDrawing(false); | |
| 225 | 248 | }} |
| 226 | 249 | /> |
| 227 | 250 | </Suspense> |