forge
Explore
Log in

Don't you dare go Hollow

📎 client-side upload limits and shared error handling

Browse files at this commit

fed2a93290d8e5073e72eae7c4d6c7e962b935ebBurak BoduroğluParent: b92c765
  • feat
    • 📎 client-side upload limits and shared error handling
Show full message
feat: 📎 client-side upload limits and shared error handling
- extract formatBytes/maxUploadBytes into shared src/lib/upload-limits.ts
- add client-side file size validation in exam room, question form, solution
  form, and ask-question dialog
- add known API error messages for file upload, exam, event, and pomodoro
  errors
- extract errorMessageFromPayload helper for client/form/blob endpoints
  with Pydantic validation detail support
- add status-code handling for 409, 413, 422
- show max file size in question/solution upload UI
src/api/__tests__/client/client.test.tsmodified+2 -2
@@ -126,7 +126,7 @@ describe("client", () => {
126 126
127 it("handles unknown messages with sentence case", () => {127 it("handles unknown messages with sentence case", () => {
128 expect(formatApiErrorMessage("custom error occurred", "en")).toBe("Custom error occurred");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 it("formats generic Error", () => {151 it("formats generic Error", () => {
152 expect(formatApiError(new Error("generic"), "en")).toBe("Generic");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 en: "This username is already in use.",46 en: "This username is already in use.",
47 tr: "Bu kullanıcı adı zaten kullanılıyor.",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 "course not found": {81 "course not found": {
50 en: "Course not found.",82 en: "Course not found.",
51 tr: "Ders bulunamadı.",83 tr: "Ders bulunamadı.",
@@ -74,6 +106,22 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
74 en: "This attempt is closed. Answers are read-only.",106 en: "This attempt is closed. Answers are read-only.",
75 tr: "Bu oturum kapalı. Cevaplar salt okunur.",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 "only students can sit exams": {125 "only students can sit exams": {
78 en: "Only students can take exams.",126 en: "Only students can take exams.",
79 tr: "Sınava yalnızca öğrenciler girebilir.",127 tr: "Sınava yalnızca öğrenciler girebilir.",
@@ -90,6 +138,30 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
90 en: "Only students can be marked on a lesson roll call.",138 en: "Only students can be marked on a lesson roll call.",
91 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",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 function currentLocale(): Locale {167 function currentLocale(): Locale {
@@ -118,6 +190,28 @@ function sentenceCase(message: string): string {
118 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);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 export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> {215 export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
122 const headers: Record<string, string> = {};216 const headers: Record<string, string> = {};
123 let body: string | undefined;217 let body: string | undefined;
@@ -151,12 +245,7 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro
151 }245 }
152 246
153 if (!res.ok) {247 if (!res.ok) {
154- const message =248+ const message = errorMessageFromPayload(data, res.statusText || "Request failed");
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";
160 249
161 let retryAfter: number | null = null;250 let retryAfter: number | null = null;
162 if (res.status === 429) {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 if (!res.ok) {283 if (!res.ok) {
195- const message =284+ const message = errorMessageFromPayload(data, res.statusText || "Request failed");
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";
201 throw new ApiError(res.status, message);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 let message = res.statusText || "Request failed";299 let message = res.statusText || "Request failed";
216 if (text) {300 if (text) {
217 try {301 try {
218- const data = JSON.parse(text) as { error?: unknown; message?: unknown };302+ message = errorMessageFromPayload(JSON.parse(text), message);
219- if (typeof data.error === "string") message = data.error;
220- else if (typeof data.message === "string") message = data.message;
221 } catch {303 } catch {
222 message = text;304 message = text;
223 }305 }
@@ -232,7 +314,7 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL
232 const normalized = normalizeApiMessage(message);314 const normalized = normalizeApiMessage(message);
233 const known = API_ERROR_MESSAGES[normalized]?.[locale];315 const known = API_ERROR_MESSAGES[normalized]?.[locale];
234 if (known) return known;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 return sentenceCase(message);318 return sentenceCase(message);
237 }319 }
238 320
@@ -244,6 +326,9 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()):
244 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];326 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
245 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];327 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
246 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];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 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";332 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
248 return formatApiErrorMessage(err.message, locale);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 import { getExamAttempt } from "@/api/exams";2 import { getExamAttempt } from "@/api/exams";
3 import { getExamAttemptQuestions } from "@/api/exams";3 import { getExamAttemptQuestions } from "@/api/exams";
4+import { getSettings } from "@/api/settings";
4 import { postExamAttempt } from "@/api/exams";5 import { postExamAttempt } from "@/api/exams";
5 import { postExamAttemptAnswer } from "@/api/exams";6 import { postExamAttemptAnswer } from "@/api/exams";
6 import { postExamAttemptFinish } from "@/api/exams";7 import { postExamAttemptFinish } from "@/api/exams";
@@ -20,6 +21,7 @@ import { Textarea } from "@/components/ui/textarea";
20 import { cn } from "@/lib/cn";21 import { cn } from "@/lib/cn";
21 import { createNow } from "@/lib/create-now";22 import { createNow } from "@/lib/create-now";
22 import { formatDateTime } from "@/lib/format";23 import { formatDateTime } from "@/lib/format";
24+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
23 import { usePreferences, useT } from "@/stores/preferences-context";25 import { usePreferences, useT } from "@/stores/preferences-context";
24 26
25 // Lazy so the drawing pad rides its own chunk, off the exam room's initial load.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 const [activeQuestionIndex, setActiveQuestionIndex] = createSignal(0);58 const [activeQuestionIndex, setActiveQuestionIndex] = createSignal(0);
57 const [remainingMs, setRemainingMs] = createSignal<number | null>(0);59 const [remainingMs, setRemainingMs] = createSignal<number | null>(0);
58 const [wsState, setWsState] = createSignal<WsState>("disconnected");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 const now = createNow();68 const now = createNow();
69+ const maxFileBytes = () => maxUploadBytes(settings());
60 const scheduled = createMemo(() => props.exam.mode === "sync" || props.exam.mode === "async" || props.exam.mode === "open");70 const scheduled = createMemo(() => props.exam.mode === "sync" || props.exam.mode === "async" || props.exam.mode === "open");
61 const attemptStatus = createMemo(() => {71 const attemptStatus = createMemo(() => {
62 const current = attempt();72 const current = attempt();
@@ -238,6 +248,10 @@ export function ExamRoomWS(props: { exam: Exam }) {
238 248
239 const saveAnswerImage = async (question: AttemptQuestion, file: File) => {249 const saveAnswerImage = async (question: AttemptQuestion, file: File) => {
240 setError("");250 setError("");
251+ if (file.size > maxFileBytes()) {
252+ setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
253+ return;
254+ }
241 setPending(true);255 setPending(true);
242 try {256 try {
243 await postExamAttemptAnswerImage(props.exam.id, question.id, file);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 import { formatApiError } from "@/api/client";2 import { formatApiError } from "@/api/client";
3 import type { ExamQuestion, QuestionKind, Subject } from "@/api/client";3 import type { ExamQuestion, QuestionKind, Subject } from "@/api/client";
4 import { QUESTION_KINDS } from "@/api/client";4 import { QUESTION_KINDS } from "@/api/client";
5 import { getExamQuestionImageBlob } from "@/api/exams";5 import { getExamQuestionImageBlob } from "@/api/exams";
6+import { getSettings } from "@/api/settings";
6 import type { DrawScene } from "@/lib/draw-stroke";7 import type { DrawScene } from "@/lib/draw-stroke";
7 import { Button } from "@/components/ui/button";8 import { Button } from "@/components/ui/button";
8 import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons";9 import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons";
@@ -11,6 +12,7 @@ import { Label } from "@/components/ui/label";
11 import { Select } from "@/components/ui/select";12 import { Select } from "@/components/ui/select";
12 import { Textarea } from "@/components/ui/textarea";13 import { Textarea } from "@/components/ui/textarea";
13 import { cn } from "@/lib/cn";14 import { cn } from "@/lib/cn";
15+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
14 import { useT } from "@/stores/preferences-context";16 import { useT } from "@/stores/preferences-context";
15 17
16 // Lazy so the drawing pad rides its own chunk, off the exam editor's initial load.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 const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null));49 const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null));
48 const [error, setError] = createSignal("");50 const [error, setError] = createSignal("");
49 const [pending, setPending] = createSignal(false);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 createEffect(() => {61 createEffect(() => {
52 const initial = props.initial;62 const initial = props.initial;
@@ -99,7 +109,27 @@ export function QuestionForm(props: {
99 setChoices((current) => current.map((choice, i) => (i === index ? value : choice)));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 const setChoiceImage = (index: number, file: File | null) => {128 const setChoiceImage = (index: number, file: File | null) => {
129+ if (file) {
130+ setError("");
131+ if (!validImage(file)) return;
132+ }
103 setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null)));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 type="file"220 type="file"
191 accept="image/png,image/jpeg,image/webp,image/gif"221 accept="image/png,image/jpeg,image/webp,image/gif"
192 class="sr-only"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 <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">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 <IconFileImage class="h-3.5 w-3.5" />226 <IconFileImage class="h-3.5 w-3.5" />
@@ -225,8 +255,10 @@ export function QuestionForm(props: {
225 fileName="question.png"255 fileName="question.png"
226 initialScene={editScene()}256 initialScene={editScene()}
227 onSave={(file) => {257 onSave={(file) => {
228- setImage(file);258+ if (validImage(file)) {
229- setDrawing(false);259+ setImage(file);
260+ setDrawing(false);
261+ }
230 }}262 }}
231 />263 />
232 </Suspense>264 </Suspense>
src/components/notes/note-files-panel.tsxmodified+2 -7
@@ -31,6 +31,7 @@ import { PageSpinner } from "@/components/ui/page-spinner";
31 import { PaginationControls } from "@/components/ui/pagination-controls";31 import { PaginationControls } from "@/components/ui/pagination-controls";
32 import { TableRowActions } from "@/components/ui/table-row-actions";32 import { TableRowActions } from "@/components/ui/table-row-actions";
33 import { cn } from "@/lib/cn";33 import { cn } from "@/lib/cn";
34+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
34 import { useT } from "@/stores/preferences-context";35 import { useT } from "@/stores/preferences-context";
35 36
36 // Lazy so the drawing pad rides its own chunk, off the notes page's initial load.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 const DRAWING_SUFFIX = ".hzdraw.png";44 const DRAWING_SUFFIX = ".hzdraw.png";
44 const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX);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 function extension(name: string): string {47 function extension(name: string): string {
53 const ext = name.split(".").pop()?.toLowerCase();48 const ext = name.split(".").pop()?.toLowerCase();
54 return ext && ext !== name.toLowerCase() ? ext : "file";49 return ext && ext !== name.toLowerCase() ? ext : "file";
@@ -92,7 +87,7 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) {
92 return null;87 return null;
93 }88 }
94 });89 });
95- const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024;90+ const maxFileBytes = () => maxUploadBytes(settings());
96 const atLimit = () => (files() ?? []).length >= MAX_NOTE_FILES;91 const atLimit = () => (files() ?? []).length >= MAX_NOTE_FILES;
97 const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE)));92 const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE)));
98 const pageFiles = createMemo(() => {93 const pageFiles = createMemo(() => {
src/components/notes/note-form.tsxmodified+2 -7
@@ -8,6 +8,7 @@ import { IconPlus, IconTrash } from "@/components/ui/icons";
8 import { Input } from "@/components/ui/input";8 import { Input } from "@/components/ui/input";
9 import { Label } from "@/components/ui/label";9 import { Label } from "@/components/ui/label";
10 import { Textarea } from "@/components/ui/textarea";10 import { Textarea } from "@/components/ui/textarea";
11+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
11 import { useT } from "@/stores/preferences-context";12 import { useT } from "@/stores/preferences-context";
12 13
13 export type NoteFormValues = {14 export type NoteFormValues = {
@@ -18,12 +19,6 @@ export type NoteFormValues = {
18 19
19 const MAX_NOTE_FILES = 10;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 export function NoteForm(props: {22 export function NoteForm(props: {
28 initial?: Partial<Note>;23 initial?: Partial<Note>;
29 submitLabel?: string;24 submitLabel?: string;
@@ -49,7 +44,7 @@ export function NoteForm(props: {
49 return null;44 return null;
50 }45 }
51 });46 });
52- const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024;47+ const maxFileBytes = () => maxUploadBytes(settings());
53 const showFiles = () => !!props.enableFiles && !isUpdate();48 const showFiles = () => !!props.enableFiles && !isUpdate();
54 49
55 const validate = (): string | null => {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 import { useParams, useRouter } from "@tanstack/solid-router";2 import { useParams, useRouter } from "@tanstack/solid-router";
3 import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared";3 import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared";
4 import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared";4 import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared";
5+import { getSettings } from "@/api/settings";
5 import type { SolutionResponse } from "@/api/shared";6 import type { SolutionResponse } from "@/api/shared";
6 import { formatApiError } from "@/api/client";7 import { formatApiError } from "@/api/client";
7 import { RouteGuard } from "@/components/layout/route-guard";8 import { RouteGuard } from "@/components/layout/route-guard";
@@ -20,6 +21,7 @@ import { showToast } from "@/components/ui/toast";
20 import { useT } from "@/stores/preferences-context";21 import { useT } from "@/stores/preferences-context";
21 import { useAuth } from "@/stores/auth-context";22 import { useAuth } from "@/stores/auth-context";
22 import { hasMinRole } from "@/lib/roles";23 import { hasMinRole } from "@/lib/roles";
24+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
23 25
24 // Lazy so the drawing pad rides its own chunk, off the question detail's initial load.26 // Lazy so the drawing pad rides its own chunk, off the question detail's initial load.
25 const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));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 const [body, setBody] = createSignal(props.initialData?.body || "");253 const [body, setBody] = createSignal(props.initialData?.body || "");
252 const [file, setFile] = createSignal<File | null>(null);254 const [file, setFile] = createSignal<File | null>(null);
253 const [drawing, setDrawing] = createSignal(false);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 const handleSubmit = async (e: Event) => {278 const handleSubmit = async (e: Event) => {
256 e.preventDefault();279 e.preventDefault();
@@ -311,14 +334,14 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
311 </div>334 </div>
312 <div class="mt-4 text-center">335 <div class="mt-4 text-center">
313 <p class="text-sm font-medium text-foreground">{t("pool.image")}</p>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 </div>338 </div>
316 </Show>339 </Show>
317 <input340 <input
318 type="file"341 type="file"
319 accept="image/*"342 accept="image/*"
320 class="absolute inset-0 z-0 h-full w-full cursor-pointer opacity-0"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 </div>346 </div>
324 {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */}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 <DrawCanvas354 <DrawCanvas
332 fileName="solution.png"355 fileName="solution.png"
333 onSave={(drawn) => {356 onSave={(drawn) => {
334- setFile(drawn);357+ setImageFile(drawn);
335- setDrawing(false);358+ if (drawn.size <= maxFileBytes()) setDrawing(false);
336 }}359 }}
337 />360 />
338 </Suspense>361 </Suspense>
src/pages/questions-page.tsxmodified+27 -4
@@ -1,6 +1,7 @@
1 import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";1 import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
2 import { Link, useSearch, useNavigate } from "@tanstack/solid-router";2 import { Link, useSearch, useNavigate } from "@tanstack/solid-router";
3 import { getQuestions, postQuestion } from "@/api/shared";3 import { getQuestions, postQuestion } from "@/api/shared";
4+import { getSettings } from "@/api/settings";
4 import { formatApiError } from "@/api/client";5 import { formatApiError } from "@/api/client";
5 import { RouteGuard } from "@/components/layout/route-guard";6 import { RouteGuard } from "@/components/layout/route-guard";
6 import { PageHeader } from "@/components/layout/page-header";7 import { PageHeader } from "@/components/layout/page-header";
@@ -19,6 +20,7 @@ import { showToast } from "@/components/ui/toast";
19 import { useT } from "@/stores/preferences-context";20 import { useT } from "@/stores/preferences-context";
20 import { useAuth } from "@/stores/auth-context";21 import { useAuth } from "@/stores/auth-context";
21 import { cn } from "@/lib/cn";22 import { cn } from "@/lib/cn";
23+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
22 24
23 // Lazy so the drawing pad rides its own chunk, off the question list's initial load.25 // Lazy so the drawing pad rides its own chunk, off the question list's initial load.
24 const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));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 const [body, setBody] = createSignal("");143 const [body, setBody] = createSignal("");
142 const [file, setFile] = createSignal<File | null>(null);144 const [file, setFile] = createSignal<File | null>(null);
143 const [drawing, setDrawing] = createSignal(false);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 const handleSubmit = async (e: Event) => {168 const handleSubmit = async (e: Event) => {
146 e.preventDefault();169 e.preventDefault();
@@ -200,14 +223,14 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void }
200 </div>223 </div>
201 <div class="mt-4 text-center">224 <div class="mt-4 text-center">
202 <p class="text-sm font-medium text-foreground">{t("pool.image")}</p>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 </div>227 </div>
205 </Show>228 </Show>
206 <input229 <input
207 type="file"230 type="file"
208 accept="image/*"231 accept="image/*"
209 class="absolute inset-0 z-0 h-full w-full cursor-pointer opacity-0"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 </div>235 </div>
213 {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */}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 <DrawCanvas243 <DrawCanvas
221 fileName="question.png"244 fileName="question.png"
222 onSave={(drawn) => {245 onSave={(drawn) => {
223- setFile(drawn);246+ setImageFile(drawn);
224- setDrawing(false);247+ if (drawn.size <= maxFileBytes()) setDrawing(false);
225 }}248 }}
226 />249 />
227 </Suspense>250 </Suspense>