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", () => {
126126
127127 it("handles unknown messages with sentence case", () => {
128128 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");
130130 });
131131 });
132132
@@ -150,7 +150,7 @@ describe("client", () => {
150150
151151 it("formats generic Error", () => {
152152 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");
154154 });
155155 });
156156 });
src/api/client/client.tsmodified+101 -16
@@ -46,6 +46,38 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
4646 en: "This username is already in use.",
4747 tr: "Bu kullanıcı adı zaten kullanılıyor.",
4848 },
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+ },
4981 "course not found": {
5082 en: "Course not found.",
5183 tr: "Ders bulunamadı.",
@@ -74,6 +106,22 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
74106 en: "This attempt is closed. Answers are read-only.",
75107 tr: "Bu oturum kapalı. Cevaplar salt okunur.",
76108 },
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+ },
77125 "only students can sit exams": {
78126 en: "Only students can take exams.",
79127 tr: "Sınava yalnızca öğrenciler girebilir.",
@@ -90,6 +138,30 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
90138 en: "Only students can be marked on a lesson roll call.",
91139 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",
92140 },
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+ },
93165 };
94166
95167 function currentLocale(): Locale {
@@ -118,6 +190,28 @@ function sentenceCase(message: string): string {
118190 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
119191 }
120192
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+
121215 export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
122216 const headers: Record<string, string> = {};
123217 let body: string | undefined;
@@ -151,12 +245,7 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro
151245 }
152246
153247 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");
160249
161250 let retryAfter: number | null = null;
162251 if (res.status === 429) {
@@ -192,12 +281,7 @@ export async function formClient<T>(path: string, body: FormData, signal?: Abort
192281 }
193282
194283 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");
201285 throw new ApiError(res.status, message);
202286 }
203287
@@ -215,9 +299,7 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise<Bl
215299 let message = res.statusText || "Request failed";
216300 if (text) {
217301 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);
221303 } catch {
222304 message = text;
223305 }
@@ -232,7 +314,7 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL
232314 const normalized = normalizeApiMessage(message);
233315 const known = API_ERROR_MESSAGES[normalized]?.[locale];
234316 if (known) return known;
235- if (locale === "tr") return "İşlem tamamlanamadı. Lütfen tekrar dene.";
317+ if (locale === "tr") return `İşlem tamamlanamadı: ${sentenceCase(message)}`;
236318 return sentenceCase(message);
237319 }
238320
@@ -244,6 +326,9 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()):
244326 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
245327 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
246328 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);
247332 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
248333 return formatApiErrorMessage(err.message, locale);
249334 }
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";
22 import { getExamAttempt } from "@/api/exams";
33 import { getExamAttemptQuestions } from "@/api/exams";
4+import { getSettings } from "@/api/settings";
45 import { postExamAttempt } from "@/api/exams";
56 import { postExamAttemptAnswer } from "@/api/exams";
67 import { postExamAttemptFinish } from "@/api/exams";
@@ -20,6 +21,7 @@ import { Textarea } from "@/components/ui/textarea";
2021 import { cn } from "@/lib/cn";
2122 import { createNow } from "@/lib/create-now";
2223 import { formatDateTime } from "@/lib/format";
24+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
2325 import { usePreferences, useT } from "@/stores/preferences-context";
2426
2527 // 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 }) {
5658 const [activeQuestionIndex, setActiveQuestionIndex] = createSignal(0);
5759 const [remainingMs, setRemainingMs] = createSignal<number | null>(0);
5860 const [wsState, setWsState] = createSignal<WsState>("disconnected");
61+ const [settings] = createResource(async () => {
62+ try {
63+ return await getSettings();
64+ } catch {
65+ return null;
66+ }
67+ });
5968 const now = createNow();
69+ const maxFileBytes = () => maxUploadBytes(settings());
6070 const scheduled = createMemo(() => props.exam.mode === "sync" || props.exam.mode === "async" || props.exam.mode === "open");
6171 const attemptStatus = createMemo(() => {
6272 const current = attempt();
@@ -238,6 +248,10 @@ export function ExamRoomWS(props: { exam: Exam }) {
238248
239249 const saveAnswerImage = async (question: AttemptQuestion, file: File) => {
240250 setError("");
251+ if (file.size > maxFileBytes()) {
252+ setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
253+ return;
254+ }
241255 setPending(true);
242256 try {
243257 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";
22 import { formatApiError } from "@/api/client";
33 import type { ExamQuestion, QuestionKind, Subject } from "@/api/client";
44 import { QUESTION_KINDS } from "@/api/client";
55 import { getExamQuestionImageBlob } from "@/api/exams";
6+import { getSettings } from "@/api/settings";
67 import type { DrawScene } from "@/lib/draw-stroke";
78 import { Button } from "@/components/ui/button";
89 import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons";
@@ -11,6 +12,7 @@ import { Label } from "@/components/ui/label";
1112 import { Select } from "@/components/ui/select";
1213 import { Textarea } from "@/components/ui/textarea";
1314 import { cn } from "@/lib/cn";
15+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
1416 import { useT } from "@/stores/preferences-context";
1517
1618 // Lazy so the drawing pad rides its own chunk, off the exam editor's initial load.
@@ -47,6 +49,14 @@ export function QuestionForm(props: {
4749 const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null));
4850 const [error, setError] = createSignal("");
4951 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());
5060
5161 createEffect(() => {
5262 const initial = props.initial;
@@ -99,7 +109,27 @@ export function QuestionForm(props: {
99109 setChoices((current) => current.map((choice, i) => (i === index ? value : choice)));
100110 };
101111
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+
102128 const setChoiceImage = (index: number, file: File | null) => {
129+ if (file) {
130+ setError("");
131+ if (!validImage(file)) return;
132+ }
103133 setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null)));
104134 };
105135
@@ -190,7 +220,7 @@ export function QuestionForm(props: {
190220 type="file"
191221 accept="image/png,image/jpeg,image/webp,image/gif"
192222 class="sr-only"
193- onChange={(event) => setImage(event.currentTarget.files?.[0] ?? null)}
223+ onChange={(event) => setQuestionImage(event.currentTarget.files?.[0] ?? null)}
194224 />
195225 <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">
196226 <IconFileImage class="h-3.5 w-3.5" />
@@ -225,8 +255,10 @@ export function QuestionForm(props: {
225255 fileName="question.png"
226256 initialScene={editScene()}
227257 onSave={(file) => {
228- setImage(file);
229- setDrawing(false);
258+ if (validImage(file)) {
259+ setImage(file);
260+ setDrawing(false);
261+ }
230262 }}
231263 />
232264 </Suspense>
src/components/notes/note-files-panel.tsxmodified+2 -7
@@ -31,6 +31,7 @@ import { PageSpinner } from "@/components/ui/page-spinner";
3131 import { PaginationControls } from "@/components/ui/pagination-controls";
3232 import { TableRowActions } from "@/components/ui/table-row-actions";
3333 import { cn } from "@/lib/cn";
34+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
3435 import { useT } from "@/stores/preferences-context";
3536
3637 // 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;
4344 const DRAWING_SUFFIX = ".hzdraw.png";
4445 const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX);
4546
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-
5247 function extension(name: string): string {
5348 const ext = name.split(".").pop()?.toLowerCase();
5449 return ext && ext !== name.toLowerCase() ? ext : "file";
@@ -92,7 +87,7 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) {
9287 return null;
9388 }
9489 });
95- const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024;
90+ const maxFileBytes = () => maxUploadBytes(settings());
9691 const atLimit = () => (files() ?? []).length >= MAX_NOTE_FILES;
9792 const totalPages = createMemo(() => Math.max(1, Math.ceil((files() ?? []).length / FILE_PAGE_SIZE)));
9893 const pageFiles = createMemo(() => {
src/components/notes/note-form.tsxmodified+2 -7
@@ -8,6 +8,7 @@ import { IconPlus, IconTrash } from "@/components/ui/icons";
88 import { Input } from "@/components/ui/input";
99 import { Label } from "@/components/ui/label";
1010 import { Textarea } from "@/components/ui/textarea";
11+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
1112 import { useT } from "@/stores/preferences-context";
1213
1314 export type NoteFormValues = {
@@ -18,12 +19,6 @@ export type NoteFormValues = {
1819
1920 const MAX_NOTE_FILES = 10;
2021
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-
2722 export function NoteForm(props: {
2823 initial?: Partial<Note>;
2924 submitLabel?: string;
@@ -49,7 +44,7 @@ export function NoteForm(props: {
4944 return null;
5045 }
5146 });
52- const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024;
47+ const maxFileBytes = () => maxUploadBytes(settings());
5348 const showFiles = () => !!props.enableFiles && !isUpdate();
5449
5550 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
22 import { useParams, useRouter } from "@tanstack/solid-router";
33 import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared";
44 import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared";
5+import { getSettings } from "@/api/settings";
56 import type { SolutionResponse } from "@/api/shared";
67 import { formatApiError } from "@/api/client";
78 import { RouteGuard } from "@/components/layout/route-guard";
@@ -20,6 +21,7 @@ import { showToast } from "@/components/ui/toast";
2021 import { useT } from "@/stores/preferences-context";
2122 import { useAuth } from "@/stores/auth-context";
2223 import { hasMinRole } from "@/lib/roles";
24+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
2325
2426 // Lazy so the drawing pad rides its own chunk, off the question detail's initial load.
2527 const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
@@ -251,6 +253,27 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
251253 const [body, setBody] = createSignal(props.initialData?.body || "");
252254 const [file, setFile] = createSignal<File | null>(null);
253255 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+ };
254277
255278 const handleSubmit = async (e: Event) => {
256279 e.preventDefault();
@@ -311,14 +334,14 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
311334 </div>
312335 <div class="mt-4 text-center">
313336 <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>
315338 </div>
316339 </Show>
317340 <input
318341 type="file"
319342 accept="image/*"
320343 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)}
322345 />
323346 </div>
324347 {/* 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
331354 <DrawCanvas
332355 fileName="solution.png"
333356 onSave={(drawn) => {
334- setFile(drawn);
335- setDrawing(false);
357+ setImageFile(drawn);
358+ if (drawn.size <= maxFileBytes()) setDrawing(false);
336359 }}
337360 />
338361 </Suspense>
src/pages/questions-page.tsxmodified+27 -4
@@ -1,6 +1,7 @@
11 import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
22 import { Link, useSearch, useNavigate } from "@tanstack/solid-router";
33 import { getQuestions, postQuestion } from "@/api/shared";
4+import { getSettings } from "@/api/settings";
45 import { formatApiError } from "@/api/client";
56 import { RouteGuard } from "@/components/layout/route-guard";
67 import { PageHeader } from "@/components/layout/page-header";
@@ -19,6 +20,7 @@ import { showToast } from "@/components/ui/toast";
1920 import { useT } from "@/stores/preferences-context";
2021 import { useAuth } from "@/stores/auth-context";
2122 import { cn } from "@/lib/cn";
23+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
2224
2325 // Lazy so the drawing pad rides its own chunk, off the question list's initial load.
2426 const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
@@ -141,6 +143,27 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void }
141143 const [body, setBody] = createSignal("");
142144 const [file, setFile] = createSignal<File | null>(null);
143145 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+ };
144167
145168 const handleSubmit = async (e: Event) => {
146169 e.preventDefault();
@@ -200,14 +223,14 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void }
200223 </div>
201224 <div class="mt-4 text-center">
202225 <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>
204227 </div>
205228 </Show>
206229 <input
207230 type="file"
208231 accept="image/*"
209232 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)}
211234 />
212235 </div>
213236 {/* 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 }
220243 <DrawCanvas
221244 fileName="question.png"
222245 onSave={(drawn) => {
223- setFile(drawn);
224- setDrawing(false);
246+ setImageFile(drawn);
247+ if (drawn.size <= maxFileBytes()) setDrawing(false);
225248 }}
226249 />
227250 </Suspense>