forge
Explore
Log in

Don't you dare go Hollow

✨ complete frontend workflow polish

Browse files at this commit

4e99344d39e6d181b2480b4095ba7de058280755Burak BoduroğluParent: e78105f
  • feat
    • ✨ complete frontend workflow polish
Show full message
feat: ✨ complete frontend workflow polish

- align row actions, edit panels, tables, and user labels across detail and list views
- keep homework grading panels open and remove raw ids from exam review
- add full screen drawing and whiteboard controls with mobile fallback
- support note attachments, podcast transcripts, and localized API refusals
- cover panel focus, empty answer sheets, and updated UI flows with tests

76 changed files +3173 -1168

docs/backend/podcast-transcript-request.mdmodified+24 -33
@@ -1,36 +1,27 @@
11 # Feature request: timed transcript for podcast episodes
22
3-Status: requested by frontend · Date: 2026-09-23
4-Contract checked: live OpenAPI at `https://hezarfen-backend.dizey.sh/api-docs/openapi.json`
5-(fetched 2026-09-23) — no transcript field or route under `/podcast/*`.
6-
7-## What the frontend already does
8-
9-The podcast player (`src/components/notes/podcast-player.tsx`) renders a
10-timed transcript under the audio when one is present: the line being spoken
11-is highlighted and kept in view, and clicking a line plays from its start
12-(`src/components/notes/podcast-transcript.tsx`). Until the backend sends a
13-transcript, the player shows no transcript control at all.
14-
15-It reads the transcript from `GET /podcast/jobs/{id}/result`, as an optional
16-field of `PodcastJobArtifacts` (`src/api/client/types.ts`):
17-
18-```jsonc
19-{
20- "job_id": "…",
21- "audio_id": "…",
22- "duration_secs": 754,
23- "format": "ogrenci_hoca",
24- "transcript": [
25- { "start_secs": 0.0, "end_secs": 4.2, "text": "Bugün hücreyi konuşalım.", "speaker": "Öğretmen" },
26- { "start_secs": 4.2, "end_secs": 7.9, "text": "Hücre neden bu kadar önemli?", "speaker": "Öğrenci" }
27- ]
28-}
29-```
30-
31-## Requested shape
32-
33-- `transcript`: array, ordered by `start_secs`, or `null`/absent when the
3+Status: partly shipped · Updated: 2026-09-23
4+Contract checked: live OpenAPI at `https://hezarfen-backend.dizey.sh/api-docs/openapi.json`.
5+
6+## What the backend ships now
7+
8+`GET /podcast/jobs/{id}/result` carries `transcript: string | null` on
9+`JobArtifacts` — the episode's narration as plain text, chapters joined by
10+blank lines, with no timings. `null` for jobs that finished before the column
11+existed.
12+
13+## What the frontend does with it
14+
15+The podcast player (`src/components/notes/podcast-player.tsx`) reads the
16+result of whichever episode is selected and, when the transcript is present,
17+offers a "Transkript" toggle that shows it one paragraph per chapter
18+(`src/components/notes/podcast-transcript.tsx`). With no transcript there is
19+no toggle. Without timings the text cannot follow playback or seek, so the
20+request below still stands.
21+
22+## Still requested: timings
23+
24+- `transcript_segments` (new field beside the plain `transcript`): array, ordered by `start_secs`, or `null`/absent when the
3425 service produced none. Only on a `done` job.
3526 - `start_secs` / `end_secs`: offsets into the produced audio, in seconds
3627 (fractions allowed). The pipeline already knows these when it stitches the
@@ -42,8 +33,8 @@ field of `PodcastJobArtifacts` (`src/api/client/types.ts`):
4233 If the backend prefers a separate door (for example
4334 `GET /podcast/jobs/{id}/transcript`, which would also let the history list and
4435 the studio inspector load it lazily), or different field names, the frontend
45-changes in one place: the type above and the `transcript` prop passed to
46-`PodcastPlayer`.
36+changes in one place: `PodcastJobArtifacts` in `src/api/client/types.ts` and
37+the fetch in `PodcastPlayer`.
4738
4839 ## Related: the audio door cannot be seeked
4940
src/api/__tests__/client/client.test.tsmodified+56 -0
@@ -377,6 +377,62 @@ describe("client", () => {
377377 );
378378 });
379379
380+ it("localizes still-linked and archived conflicts instead of quoting them", () => {
381+ const yearLinked = new ApiError(409, "classes and terms are still linked to this academic year — unlink them first");
382+ expect(formatApiError(yearLinked, "tr")).toBe(
383+ "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.",
384+ );
385+ expect(formatApiError(yearLinked, "en")).toBe(
386+ "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.",
387+ );
388+ // a reworded tail or a curly apostrophe still lands on the same wording
389+ expect(formatApiError(new ApiError(409, "Terms are still linked to this year."), "tr")).toMatch(/^Bu eğitim yılına bağlı/);
390+
391+ const cases: Array<[string, RegExp]> = [
392+ ["this class’s academic year is archived — past years are read-only", /^Bu eğitim yılı arşivlendi\./],
393+ ["students or instances are still on this class", /^Bu şubede hâlâ öğrenci veya ders var\./],
394+ ["a class still teaches this course", /^Bu ders hâlâ bir şubede okutuluyor/],
395+ ["exams or frozen karnes still belong to this term", /^Bu döneme bağlı sınavlar/],
396+ ["exam questions or homework still reference this subject", /^Sınav soruları veya ödevler/],
397+ ["the menu still has live bookings", /^Bu menüde hâlâ rezervasyonlar var\./],
398+ ["the slot has a pending or approved booking", /^Bu saatte bekleyen veya onaylanmış/],
399+ ["the plan is already assigned to a student", /^Bu ödeme planı bir öğrenciye atanmış/],
400+ ["that account is the school's last admin", /^Bu hesap okulun son yöneticisi\./],
401+ ["a blueprint already exists for that grade", /^Bu seviye için zaten bir şablon var\./],
402+ ["the year changed under concurrent edits (re-read and retry)", /^Bu kayıt sen düzenlerken değişti\./],
403+ ];
404+ for (const [backend, turkish] of cases) {
405+ expect(formatApiError(new ApiError(409, backend), "tr")).toMatch(turkish);
406+ expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/Server said/);
407+ }
408+ // the exact table still wins over a looser pattern
409+ expect(formatApiError(new ApiError(409, "bank questions still reference this subject — re-tag or delete them first"), "en")).toBe(
410+ "Question bank templates still use this subject. Re-tag or delete them first.",
411+ );
412+ });
413+
414+ it("prefers the machine code over the prose when the backend sends one", () => {
415+ expect(formatApiError(new ApiError(409, "class is at its course ceiling (12)", null, null, "class_at_course_ceiling"), "tr")).toBe(
416+ "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.",
417+ );
418+ expect(formatApiError(new ApiError(409, "some reworded text", null, null, "student_number_taken"), "en")).toBe(
419+ "Another student already has this student number. Enter a different number.",
420+ );
421+ expect(formatApiError(new ApiError(409, "whatever", null, null, "academic_year_archived"), "tr")).toMatch(/^Bu eğitim yılı arşivlendi\./);
422+ // an unknown code falls through to the prose and then the quoted fallback
423+ expect(formatApiError(new ApiError(409, "slot taken by a later edit", null, null, "brand_new_code"), "tr")).toBe(
424+ "İşlem kaydın şu anki durumuyla çakışıyor. Sunucu yanıtı: “slot taken by a later edit”.",
425+ );
426+ });
427+
428+ it("carries the payload code onto the ApiError", async () => {
429+ mockFetchError(409, { error: "already attached", code: "class_at_course_ceiling" });
430+ const err = await client("/classes/1/instances", { method: "POST", body: {} }).catch((e: unknown) => e);
431+ expect(err).toBeInstanceOf(ApiError);
432+ expect((err as ApiError).code).toBe("class_at_course_ceiling");
433+ expect(formatApiError(err, "en")).toMatch(/^This class already has the maximum number of courses\./);
434+ });
435+
380436 it("formats 500+", () => {
381437 expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again.");
382438 expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene.");
src/api/client/client.tsmodified+270 -9
@@ -5,13 +5,22 @@ export class ApiError extends Error {
55 readonly retryAfter: number | null;
66 /** Set when the school has this route's module switched off (`403 {error, module}`). */
77 readonly module: string | null;
8-
9- constructor(status: number, message: string, retryAfter: number | null = null, module: string | null = null) {
8+ /** Machine refusal code (`{error, code}`), sent only where a route documents one. */
9+ readonly code: string | null;
10+
11+ constructor(
12+ status: number,
13+ message: string,
14+ retryAfter: number | null = null,
15+ module: string | null = null,
16+ code: string | null = null,
17+ ) {
1018 super(message);
1119 this.name = "ApiError";
1220 this.status = status;
1321 this.retryAfter = retryAfter;
1422 this.module = module;
23+ this.code = code;
1524 }
1625 }
1726
@@ -300,6 +309,252 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
300309 },
301310 };
302311
312+type LocalizedMessage = Record<Locale, string>;
313+
314+const ARCHIVED_YEAR: LocalizedMessage = {
315+ en: "This academic year is archived. Past years are read-only, so records in it can no longer change.",
316+ tr: "Bu eğitim yılı arşivlendi. Geçmiş yıllar salt okunur, bu yüzden içindeki kayıtlar artık değiştirilemez.",
317+};
318+
319+const STUDENT_NUMBER_TAKEN: LocalizedMessage = {
320+ en: "Another student already has this student number. Enter a different number.",
321+ tr: "Bu öğrenci numarası başka bir öğrencide kayıtlı. Farklı bir numara gir.",
322+};
323+
324+const STALE_RECORD: LocalizedMessage = {
325+ en: "This record changed while you were editing it. Reload the page and try again.",
326+ tr: "Bu kayıt sen düzenlerken değişti. Sayfayı yenileyip tekrar dene.",
327+};
328+
329+/**
330+ * Machine refusal codes (`{error, code}`). The backend sends one only where a
331+ * route documents its vocabulary (class attach/add-member, podcast, insight
332+ * report, student numbers), so these win over the prose whenever present.
333+ * `duplicate` is left out on purpose: it means a course on one route and a
334+ * student on another, so the prose patterns below tell them apart.
335+ */
336+const API_ERROR_CODE_MESSAGES: Record<string, LocalizedMessage> = {
337+ academic_year_archived: ARCHIVED_YEAR,
338+ class_at_course_ceiling: {
339+ en: "This class already has the maximum number of courses. Remove a course from it before adding another.",
340+ tr: "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.",
341+ },
342+ class_roster_too_large: {
343+ en: "This class has too many students to enroll in a course in one step. Contact your system administrator.",
344+ tr: "Bu şubede bir derse tek seferde kaydedilemeyecek kadar çok öğrenci var. Sistem yöneticine başvur.",
345+ },
346+ class_at_roster_ceiling: {
347+ en: "This class is full. Remove a student from it before adding another.",
348+ tr: "Bu şube dolu. Yeni öğrenci eklemeden önce şubeden bir öğrenci çıkar.",
349+ },
350+ class_course_list_too_large: {
351+ en: "This class has too many courses to enroll a student in one step. Contact your system administrator.",
352+ tr: "Bu şubede bir öğrenciyi tek seferde kaydetmek için çok fazla ders var. Sistem yöneticine başvur.",
353+ },
354+ linked_course_missing: {
355+ en: "One of this class's courses was removed while the student was being added. Reload the page and try again.",
356+ tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.",
357+ },
358+ student_number_taken: STUDENT_NUMBER_TAKEN,
359+ not_ready: {
360+ en: "This audio is not ready yet. Wait for it to finish and try again.",
361+ tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.",
362+ },
363+ audio_missing: {
364+ en: "This audio file could not be found on the server. Generate the episode again.",
365+ tr: "Bu ses dosyası sunucuda bulunamadı. Bölümü yeniden oluştur.",
366+ },
367+ source_missing: {
368+ en: "This note has no PDF to narrate. Attach a PDF to the note and try again.",
369+ tr: "Bu notta seslendirilecek bir PDF yok. Nota bir PDF ekleyip tekrar dene.",
370+ },
371+ report_missing: {
372+ en: "No report has been generated for this day yet.",
373+ tr: "Bu gün için henüz rapor oluşturulmadı.",
374+ },
375+ report_empty: {
376+ en: "There is no data for this day to build a report from.",
377+ tr: "Bu gün için rapor oluşturacak veri yok.",
378+ },
379+ report_refused: {
380+ en: "The AI service declined to write this report. Try again later.",
381+ tr: "Yapay zekâ servisi bu raporu hazırlamayı reddetti. Daha sonra tekrar dene.",
382+ },
383+};
384+
385+/**
386+ * Backend refusals that carry no code, matched on the stable part of their
387+ * prose (the nouns and the "still linked / in use / already" verb) rather than
388+ * byte-exact, so a reworded tail or a different em dash still lands. Checked
389+ * in order after the exact table; keep each pattern specific enough that it
390+ * cannot swallow an unrelated reason.
391+ */
392+const API_ERROR_PATTERNS: ReadonlyArray<readonly [RegExp, LocalizedMessage]> = [
393+ [
394+ /\b(classes|terms)\b.*\bstill linked to this (academic )?year\b/,
395+ {
396+ en: "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.",
397+ tr: "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.",
398+ },
399+ ],
400+ [/\bacademic year is archived\b|\bin an archived academic year\b/, ARCHIVED_YEAR],
401+ [
402+ /\btarget year already (holds|has) classes\b/,
403+ {
404+ en: "The target year already has classes. Choose an empty year to carry the classes into.",
405+ tr: "Hedef eğitim yılında zaten şubeler var. Şubeleri aktarmak için boş bir yıl seç.",
406+ },
407+ ],
408+ [
409+ /\b(academic )?year (with|named) (that|this) name already exists\b|\bacademic year .*already exists\b/,
410+ {
411+ en: "An academic year with this name already exists. Choose a different name.",
412+ tr: "Bu adla bir eğitim yılı zaten var. Farklı bir ad seç.",
413+ },
414+ ],
415+ [
416+ /\b(students|instances|courses)\b.*\bstill (on|in|attached to) this class\b/,
417+ {
418+ en: "This class still has students or courses. Remove its students and detach its courses before deleting it.",
419+ tr: "Bu şubede hâlâ öğrenci veya ders var. Silmeden önce öğrencileri şubeden çıkar ve dersleri şubeden kaldır.",
420+ },
421+ ],
422+ [
423+ /\bclass(es)? still teach(es)? this course\b|\bstudents still hold an individual membership\b/,
424+ {
425+ en: "A class still teaches this course, or students are still enrolled in it directly. Detach it from its classes and remove those students before deleting it.",
426+ tr: "Bu ders hâlâ bir şubede okutuluyor ya da derse doğrudan kayıtlı öğrenciler var. Silmeden önce dersi şubelerden çıkar ve bu öğrencileri dersten kaldır.",
427+ },
428+ ],
429+ [
430+ /\b(exams|karnes?)\b.*\bstill belong to this term\b/,
431+ {
432+ en: "Exams or finalized report cards still belong to this term, so it cannot be deleted. Archive it instead.",
433+ tr: "Bu döneme bağlı sınavlar veya kesinleşmiş karneler var, bu yüzden dönem silinemez. Bunun yerine dönemi arşivle.",
434+ },
435+ ],
436+ [
437+ /\b(exam questions|questions|homework)\b.*\bstill reference this subject\b/,
438+ {
439+ en: "Exam questions or homework still use this subject. Move them to another subject or delete them first.",
440+ tr: "Sınav soruları veya ödevler hâlâ bu konuyu kullanıyor. Önce onları başka bir konuya taşı veya sil.",
441+ },
442+ ],
443+ [
444+ /\bmenu still has (live |active )?bookings\b/,
445+ {
446+ en: "This menu still has bookings. Cancel them before deleting the menu.",
447+ tr: "Bu menüde hâlâ rezervasyonlar var. Menüyü silmeden önce rezervasyonları iptal et.",
448+ },
449+ ],
450+ [
451+ /\b(slot|occurrence) has an? (pending or approved )?(booking|appointment)\b/,
452+ {
453+ en: "This time already has a pending or approved appointment. Cancel or decline it before removing the time.",
454+ tr: "Bu saatte bekleyen veya onaylanmış bir randevu var. Saati kaldırmadan önce randevuyu iptal et ya da reddet.",
455+ },
456+ ],
457+ [
458+ /\bplan is already assigned\b/,
459+ {
460+ en: "This payment plan is already assigned to a student, so it can no longer be changed or deleted.",
461+ tr: "Bu ödeme planı bir öğrenciye atanmış, bu yüzden artık değiştirilemez veya silinemez.",
462+ },
463+ ],
464+ [
465+ /\bschool's last admin\b|\blast admin (of|in) (this|the) school\b/,
466+ {
467+ en: "This account is the school's last admin. Make someone else an admin before changing its role.",
468+ tr: "Bu hesap okulun son yöneticisi. Rolünü değiştirmeden önce başka birini yönetici yap.",
469+ },
470+ ],
471+ [
472+ /\bblueprint already exists\b/,
473+ {
474+ en: "A template already exists for this grade. Edit the existing template instead.",
475+ tr: "Bu seviye için zaten bir şablon var. Bunun yerine mevcut şablonu düzenle.",
476+ },
477+ ],
478+ [
479+ /\bmenu already exists\b/,
480+ {
481+ en: "A menu already exists for this date and meal. Edit the existing menu instead.",
482+ tr: "Bu tarih ve öğün için zaten bir menü var. Bunun yerine mevcut menüyü düzenle.",
483+ },
484+ ],
485+ [/\bstudent number is already taken\b|\bstudent number already (exists|taken|in use)\b/, STUDENT_NUMBER_TAKEN],
486+ [
487+ /\balready attached\b/,
488+ {
489+ en: "This course is already attached to this class.",
490+ tr: "Bu ders bu şubeye zaten eklenmiş.",
491+ },
492+ ],
493+ [
494+ /\balready in this class\b/,
495+ {
496+ en: "This student is already in this class.",
497+ tr: "Bu öğrenci zaten bu şubede.",
498+ },
499+ ],
500+ [
501+ /\bhomework (has been|is) graded\b/,
502+ {
503+ en: "This homework has been graded, so the submission is locked until the grade is removed.",
504+ tr: "Bu ödev notlandırıldı. Not kaldırılana kadar teslim değiştirilemez.",
505+ },
506+ ],
507+ [
508+ /\bquestion is approved\b/,
509+ {
510+ en: "This question is approved, so its content can no longer change.",
511+ tr: "Bu soru onaylandığı için içeriği artık değiştirilemez.",
512+ },
513+ ],
514+ [
515+ /\battempts have started\b/,
516+ {
517+ en: "Students have already started this exam, so its questions can no longer change.",
518+ tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.",
519+ },
520+ ],
521+ [
522+ /\bremoved exam kind still has\b/,
523+ {
524+ en: "An exam kind you removed still has graded exams. Keep it in the list, or move those exams to another kind first.",
525+ tr: "Kaldırdığın sınav türüne ait notlandırılmış sınavlar var. Türü listede bırak ya da önce bu sınavları başka bir türe taşı.",
526+ },
527+ ],
528+ [
529+ /\bremoved meal slot still has\b/,
530+ {
531+ en: "A meal you removed still has published menus. Keep it in the list, or delete those menus first.",
532+ tr: "Kaldırdığın öğüne ait yayınlanmış menüler var. Öğünü listede bırak ya da önce bu menüleri sil.",
533+ },
534+ ],
535+ [
536+ /\bmaximum number of boards\b/,
537+ {
538+ en: "You already have the maximum number of boards. Delete one before creating another.",
539+ tr: "En fazla tahta sayısına ulaştın. Yenisini oluşturmadan önce birini sil.",
540+ },
541+ ],
542+ [/\bre-read (it )?and retry\b|\bunder concurrent edits\b|\bkept changing\b/, STALE_RECORD],
543+];
544+
545+/** A specific wording for this backend refusal, or null when only the generic fallback fits. */
546+function knownApiErrorMessage(message: string, code: string | null, locale: Locale): string | null {
547+ const normalized = normalizeApiMessage(message);
548+ const exact = API_ERROR_MESSAGES[normalized]?.[locale];
549+ if (exact) return exact;
550+ const byCode = code ? API_ERROR_CODE_MESSAGES[code]?.[locale] : undefined;
551+ if (byCode) return byCode;
552+ for (const [pattern, messages] of API_ERROR_PATTERNS) {
553+ if (pattern.test(normalized)) return messages[locale];
554+ }
555+ return null;
556+}
557+
303558 const FIELD_LABELS: Record<string, Record<Locale, string>> = {
304559 content: { en: "Content", tr: "İçerik" },
305560 description: { en: "Description", tr: "Açıklama" },
@@ -375,6 +630,12 @@ function formatValidationMessage(message: string, locale: Locale): string | null
375630 return `${label} must be at most ${max} characters. Currently ${got} characters.`;
376631 }
377632
633+function errorCodeFromPayload(data: unknown): string | null {
634+ if (!data || typeof data !== "object") return null;
635+ const code = (data as { code?: unknown }).code;
636+ return typeof code === "string" && code ? code : null;
637+}
638+
378639 function errorMessageFromPayload(data: unknown, fallback: string): string {
379640 if (!data || typeof data !== "object") return fallback;
380641 const record = data as Record<string, unknown>;
@@ -465,7 +726,7 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
465726 }
466727 }
467728
468- throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data));
729+ throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data), errorCodeFromPayload(data));
469730 }
470731
471732 return data as T;
@@ -509,7 +770,7 @@ export async function formClient<T>(path: string, body: FormData, signal?: Abort
509770
510771 if (!res.ok) {
511772 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
512- throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data));
773+ throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data), errorCodeFromPayload(data));
513774 }
514775
515776 return data as T;
@@ -533,7 +794,7 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise<Bl
533794 message = text;
534795 }
535796 }
536- throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload));
797+ throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload), errorCodeFromPayload(payload));
537798 }
538799
539800 return res.blob();
@@ -595,8 +856,7 @@ function formatFallbackMessage(message: string, status: number | null, locale: L
595856 }
596857
597858 export function formatApiErrorMessage(message: string, locale: Locale = currentLocale(), status: number | null = null): string {
598- const normalized = normalizeApiMessage(message);
599- const known = API_ERROR_MESSAGES[normalized]?.[locale];
859+ const known = knownApiErrorMessage(message, null, locale);
600860 if (known) return known;
601861 const runtime = formatRuntimeErrorMessage(message, locale);
602862 if (runtime) return runtime;
@@ -606,7 +866,8 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL
606866 if (decode) return decode;
607867 // Unmapped backend text: name the kind of failure and quote the server's
608868 // reason instead of a bare "something went wrong" that hides it. Add a
609- // mapping in API_ERROR_MESSAGES when a message deserves its own wording.
869+ // mapping in API_ERROR_MESSAGES (exact), API_ERROR_CODE_MESSAGES or
870+ // API_ERROR_PATTERNS when a message deserves its own wording.
610871 return formatFallbackMessage(message, status, locale);
611872 }
612873
@@ -622,7 +883,7 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()):
622883 if (err.module != null && err.status === 403) {
623884 return locale === "tr" ? "Bu özellik okulunuzda şu an kapalı." : "This feature is currently switched off for your school.";
624885 }
625- const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
886+ const known = knownApiErrorMessage(err.message, err.code, locale);
626887 if (known) return known;
627888 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
628889 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
src/api/client/types.tsmodified+4 -15
@@ -1458,22 +1458,11 @@ export type PodcastJobArtifacts = {
14581458 /** The resolved narration format. */
14591459 format?: PodcastFormat | null;
14601460 /**
1461- * Not in the live contract yet (checked 2026-09-23) — the shape proposed in
1462- * docs/backend/podcast-transcript-request.md. Absent or empty until the
1463- * backend ships it, and the player shows no transcript control until then.
1461+ * The episode's narration as plain text, chapters joined by blank lines —
1462+ * no timings. `null` when the service did not report one (every job that
1463+ * finished before the backend stored it).
14641464 */
1465- transcript?: PodcastTranscriptSegment[] | null;
1466-};
1467-
1468-/** One timed line of an episode's narration. */
1469-export type PodcastTranscriptSegment = {
1470- /** Offset into the audio where the line starts, in seconds. */
1471- start_secs: number;
1472- /** Where it ends, in seconds. */
1473- end_secs: number;
1474- text: string;
1475- /** Who speaks it — set on the two-voice `ogrenci_hoca` format, else null. */
1476- speaker?: string | null;
1465+ transcript?: string | null;
14771466 };
14781467
14791468 /** The verdict on a cancel. `false` is not an error — see `postPodcastJobCancel`. */
src/components/ai/note-studio-panel.tsxmodified+9 -0
@@ -210,6 +210,7 @@ export function NoteStudioDetail(props: { noteId: string; episode?: string }) {
210210 aria-valuemax={RAIL_MAX}
211211 aria-valuenow={railWidth()}
212212 tabIndex={0}
213+ title={t("aiStudio.resizeHint")}
213214 class="group absolute inset-y-0 left-0 z-10 hidden w-2 cursor-col-resize touch-none outline-hidden lg:block"
214215 onPointerDown={startResize}
215216 onDblClick={() => setRailWidth(RAIL_DEFAULT)}
@@ -221,6 +222,14 @@ export function NoteStudioDetail(props: { noteId: string; episode?: string }) {
221222 }}
222223 >
223224 <span class="block h-full w-px bg-transparent transition-colors group-hover:bg-primary/60 group-focus-visible:bg-primary group-active:bg-primary" />
225+ {/* A grip on the border, always visible, so the rail reads as
226+ draggable before anyone hovers the hairline. */}
227+ <span
228+ aria-hidden="true"
229+ class="absolute left-0 top-[45vh] flex h-9 w-3.5 -translate-x-1/2 items-center justify-center gap-[3px] rounded-full border border-border-line bg-surface-base text-text-subtle shadow-xs transition-colors group-hover:border-primary/60 group-hover:text-primary-text group-focus-visible:border-primary group-active:border-primary"
230+ >
231+ <span class="flex flex-col gap-[3px]"><span class="h-[3px] w-[3px] rounded-full bg-current" /><span class="h-[3px] w-[3px] rounded-full bg-current" /><span class="h-[3px] w-[3px] rounded-full bg-current" /></span>
232+ </span>
224233 </div>
225234 <PodcastPanel noteId={current().id} noteTitle={current().title} episode={props.episode} active flat />
226235 </aside>
src/components/builder/school-edit-panel.tsxadded+85 -0
@@ -0,0 +1,85 @@
1+import { Show, createEffect, createSignal } from "solid-js";
2+import { patchSchool } from "@/api/schools";
3+import { formatApiError, type School, type SchoolStatus } from "@/api/client";
4+import { Alert } from "@/components/ui/alert";
5+import { Button } from "@/components/ui/button";
6+import { Input } from "@/components/ui/input";
7+import { Label } from "@/components/ui/label";
8+import { Select } from "@/components/ui/select";
9+import { SidePanel } from "@/components/ui/side-panel";
10+import { useT } from "@/stores/preferences-context";
11+
12+/**
13+ * A tenant school's edit form (name, status). One component for the builder
14+ * school detail header and the builder schools list's row menu, so both send
15+ * the same PATCH. The panel closes itself on success; the caller refetches
16+ * and shows its own flash in `onSaved`.
17+ */
18+export function SchoolEditPanel(props: {
19+ school: School | null;
20+ open: boolean;
21+ onOpenChange: (open: boolean) => void;
22+ onSaved: () => void | Promise<void>;
23+}) {
24+ const t = useT();
25+ const [name, setName] = createSignal("");
26+ const [status, setStatus] = createSignal<SchoolStatus>("active");
27+ const [error, setError] = createSignal("");
28+ const [pending, setPending] = createSignal(false);
29+
30+ // Seed the form each time it opens, from the school it opens for.
31+ createEffect(() => {
32+ const current = props.school;
33+ if (!props.open || !current) return;
34+ setName(current.name);
35+ setStatus(current.status);
36+ setError("");
37+ });
38+
39+ const submit = async (event: SubmitEvent) => {
40+ event.preventDefault();
41+ const current = props.school;
42+ if (!current || pending()) return;
43+ setError("");
44+ setPending(true);
45+ try {
46+ await patchSchool(current.id, { name: name().trim(), status: status() });
47+ props.onOpenChange(false);
48+ await props.onSaved();
49+ } catch (err) {
50+ setError(formatApiError(err));
51+ } finally {
52+ setPending(false);
53+ }
54+ };
55+
56+ return (
57+ <SidePanel guardUnsaved open={props.open && !!props.school} onOpenChange={props.onOpenChange} title={t("builder.editSchool")} description={t("builder.editSchoolHint")}>
58+ <form class="space-y-4" onSubmit={submit}>
59+ <Show when={error()}>
60+ <Alert variant="destructive">{error()}</Alert>
61+ </Show>
62+ <div class="space-y-1.5">
63+ <Label for="school-edit-name">{t("builder.schoolName")}</Label>
64+ <Input id="school-edit-name" class="rounded-lg" required maxlength={120} value={name()} onInput={(e) => setName(e.currentTarget.value)} />
65+ </div>
66+ <div class="space-y-1.5">
67+ <Label for="school-edit-status">{t("builder.status")}</Label>
68+ <Select id="school-edit-status" value={status()} onChange={(e) => setStatus(e.currentTarget.value as SchoolStatus)}>
69+ <option value="active">{t("builder.statusActive")}</option>
70+ <option value="suspended">{t("builder.statusSuspended")}</option>
71+ </Select>
72+ <p class="text-xs text-text-subtle">{t("builder.suspendHint")}</p>
73+ </div>
74+ <div class="flex flex-wrap items-center gap-2">
75+ <Button type="button" variant="outline" class="h-10 rounded-lg" onClick={() => props.onOpenChange(false)}>
76+ {t("common.cancel")}
77+ </Button>
78+ <Button type="submit" class="h-10 rounded-lg" disabled={pending()}>
79+ {t("common.save")}
80+ </Button>
81+ </div>
82+ </form>
83+ </SidePanel>
84+ );
85+}
src/components/classes/class-edit-panel.tsxadded+78 -0
@@ -0,0 +1,78 @@
1+import { For, Show, createEffect, createSignal } from "solid-js";
2+import { patchClassById } from "@/api/classes";
3+import { formatApiError, type AcademicYear, type ClassGroup } from "@/api/client";
4+import { Alert } from "@/components/ui/alert";
5+import { Button } from "@/components/ui/button";
6+import { Input } from "@/components/ui/input";
7+import { Label } from "@/components/ui/label";
8+import { Select } from "@/components/ui/select";
9+import { SidePanel } from "@/components/ui/side-panel";
10+import { UserSearchSelect } from "@/components/users/user-search-select";
11+import { useT } from "@/stores/preferences-context";
12+
13+/**
14+ * A şube's edit form (name, grade, academic year, homeroom teacher). One
15+ * component for the class detail page header and the classes list's row menu,
16+ * so both send the same PATCH. The panel closes itself on success and hands
17+ * the saved row back; the caller refetches and shows its own flash.
18+ */
19+export function ClassEditPanel(props: {
20+ cls: ClassGroup | null;
21+ open: boolean;
22+ onOpenChange: (open: boolean) => void;
23+ onSaved: (cls: ClassGroup) => void | Promise<void>;
24+ years: AcademicYear[];
25+ maxNameLen?: number;
26+ maxGradeLen?: number;
27+}) {
28+ const t = useT();
29+ const [name, setName] = createSignal("");
30+ const [grade, setGrade] = createSignal("");
31+ const [yearId, setYearId] = createSignal("");
32+ const [teacherId, setTeacherId] = createSignal("");
33+ const [error, setError] = createSignal("");
34+ const [pending, setPending] = createSignal(false);
35+
36+ // Seed the form each time it opens, from the row it opens for.
37+ createEffect(() => {
38+ const c = props.cls;
39+ if (!props.open || !c) return;
40+ setName(c.name);
41+ setGrade(c.grade ?? "");
42+ setYearId(c.year ?? "");
43+ setTeacherId(c.teacher?.id ?? "");
44+ setError("");
45+ });
46+
47+ const submit = async (event: SubmitEvent) => {
48+ event.preventDefault();
49+ const c = props.cls;
50+ if (!c || pending()) return;
51+ setError("");
52+ setPending(true);
53+ try {
54+ const saved = await patchClassById(c.id, { name: name().trim(), grade: grade().trim() || null, year: yearId() || null, teacher_id: teacherId() || null });
55+ props.onOpenChange(false);
56+ await props.onSaved(saved);
57+ } catch (err) {
58+ setError(formatApiError(err));
59+ } finally {
60+ setPending(false);
61+ }
62+ };
63+
64+ return (
65+ <SidePanel guardUnsaved open={props.open && !!props.cls} onOpenChange={props.onOpenChange} title={t("common.edit")} description={props.cls?.name}>
66+ <form class="space-y-4" onSubmit={submit}>
67+ <div class="space-y-3">
68+ <div class="space-y-1.5"><Label for="edit-class-name">{t("classGroups.className")}</Label><Input id="edit-class-name" maxlength={props.maxNameLen} value={name()} onInput={(e) => setName(e.currentTarget.value)} /></div>
69+ <div class="space-y-1.5"><Label for="edit-class-grade">{t("classGroups.grade")}</Label><Input id="edit-class-grade" maxlength={props.maxGradeLen} value={grade()} onInput={(e) => setGrade(e.currentTarget.value)} /></div>
70+ <div class="space-y-1.5"><Label for="edit-class-year">{t("academicYears.year")}</Label><Select id="edit-class-year" value={yearId()} onChange={(e) => setYearId(e.currentTarget.value)}><option value="">{t("academicYears.unassigned")}</option><For each={props.years}>{(year) => <option value={year.id}>{year.name}</option>}</For></Select></div>
71+ <UserSearchSelect id="edit-class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} initialUser={props.cls?.teacher} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" />
72+ </div>
73+ <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
74+ <div class="flex gap-2 border-t pt-4"><Button type="submit" disabled={pending()}>{t("common.save")}</Button><Button type="button" variant="outline" onClick={() => props.onOpenChange(false)}>{t("common.cancel")}</Button></div>
75+ </form>
76+ </SidePanel>
77+ );
78+}
src/components/courses/course-card.tsxdeleted+0 -60
@@ -1,60 +0,0 @@
1-import { Show } from "solid-js";
2-import { Link } from "@tanstack/solid-router";
3-import type { Course } from "@/api/client";
4-import { Badge } from "@/components/ui/badge";
5-import { IconChevronRight, IconUsers } from "@/components/ui/icons";
6-import { personLabel } from "@/lib/person";
7-
8-const courseInitials = (title: string) =>
9- title.trim().slice(0, 2).toLocaleUpperCase("tr-TR") || "—";
10-
11-export function CourseCard(props: {
12- course: Course;
13- /** The şubeler line under the title: "3 sections", or a dash. */
14- sections: string;
15- enrolled?: boolean;
16- labels: {
17- kind: string;
18- enrolled: string;
19- };
20-}) {
21- // Teaching staff is per instance now, so a catalog card can only name the
22- // course's owner — the şube pages name who actually teaches it.
23- const teachers = () => [props.course.creator];
24-
25- return (
26- <Link
27- to="/courses/$id"
28- params={{ id: props.course.id }}
29- class="group flex h-full min-h-40 flex-col gap-3 rounded-xl border border-border-line bg-surface-base p-4 outline-hidden transition-colors hover:border-primary/35 hover:bg-surface-tint focus-visible:ring-2 focus-visible:ring-ring"
30- >
31- <div class="flex items-start gap-3">
32- <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-xs font-semibold text-primary-text">
33- {courseInitials(props.course.title)}
34- </span>
35- <div class="min-w-0 flex-1">
36- <div class="flex flex-wrap items-center gap-1.5">
37- <h2 class="truncate text-base font-semibold tracking-tight">{props.course.title}</h2>
38- </div>
39- <div class="mt-1 flex flex-wrap items-center gap-1.5">
40- <Badge variant="outline" class="rounded-md text-[11px] font-medium">{props.labels.kind}</Badge>
41- <Show when={props.enrolled}><Badge variant="secondary" class="rounded-md text-[11px]">{props.labels.enrolled}</Badge></Show>
42- </div>
43- </div>
44- <IconChevronRight class="mt-1 h-4 w-4 shrink-0 text-text-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-text-default" />
45- </div>
46-
47- <Show when={props.course.description}>
48- <p class="line-clamp-2 text-sm leading-5 text-text-subtle">{props.course.description}</p>
49- </Show>
50-
51- <div class="mt-auto flex items-center justify-between gap-3 border-t border-border-hairline pt-3 text-xs text-text-subtle">
52- <span class="min-w-0 flex-1 truncate">{props.sections}</span>
53- <span class="flex min-w-0 items-center gap-1.5">
54- <IconUsers class="h-3.5 w-3.5 shrink-0" />
55- <span class="max-w-32 truncate">{teachers().map(personLabel).join(", ")}</span>
56- </span>
57- </div>
58- </Link>
59- );
60-}
src/components/courses/course-edit-panel.tsxadded+95 -0
@@ -0,0 +1,95 @@
1+import { For, Show, createEffect, createSignal } from "solid-js";
2+import { patchCourseById } from "@/api/courses";
3+import { formatApiError, type Course, type CourseKind } from "@/api/client";
4+import { Alert } from "@/components/ui/alert";
5+import { Button } from "@/components/ui/button";
6+import { Input } from "@/components/ui/input";
7+import { Label } from "@/components/ui/label";
8+import { Select } from "@/components/ui/select";
9+import { SidePanel } from "@/components/ui/side-panel";
10+import { Textarea } from "@/components/ui/textarea";
11+import { useT } from "@/stores/preferences-context";
12+
13+const COURSE_KINDS: CourseKind[] = ["course", "study", "club"];
14+
15+/**
16+ * The catalog row's edit form (title, description, kind). One component for
17+ * the course detail page header and the courses list's row menu, so both
18+ * write the same PATCH. The panel closes itself on success and hands the
19+ * saved row back; the caller refetches and shows its own flash.
20+ */
21+export function CourseEditPanel(props: {
22+ course: Course | null;
23+ open: boolean;
24+ onOpenChange: (open: boolean) => void;
25+ onSaved: (course: Course) => void | Promise<void>;
26+}) {
27+ const t = useT();
28+ const [title, setTitle] = createSignal("");
29+ const [description, setDescription] = createSignal("");
30+ const [kind, setKind] = createSignal<CourseKind>("course");
31+ const [error, setError] = createSignal("");
32+ const [pending, setPending] = createSignal(false);
33+
34+ // Seed the form each time it opens, from the row it opens for.
35+ createEffect(() => {
36+ const c = props.course;
37+ if (!props.open || !c) return;
38+ setTitle(c.title);
39+ setDescription(c.description);
40+ setKind(c.kind ?? "course");
41+ setError("");
42+ });
43+
44+ const kindLabel = (value: CourseKind) =>
45+ value === "study" ? t("courses.kind.study") : value === "club" ? t("courses.kind.club") : t("courses.kind.course");
46+
47+ const submit = async (event: SubmitEvent) => {
48+ event.preventDefault();
49+ const c = props.course;
50+ if (!c || pending()) return;
51+ setError("");
52+ setPending(true);
53+ try {
54+ const saved = await patchCourseById(c.id, { title: title().trim(), description: description(), kind: kind() });
55+ props.onOpenChange(false);
56+ await props.onSaved(saved);
57+ } catch (err) {
58+ setError(formatApiError(err));
59+ } finally {
60+ setPending(false);
61+ }
62+ };
63+
64+ return (
65+ <SidePanel guardUnsaved open={props.open && !!props.course} onOpenChange={props.onOpenChange} title={t("common.edit")} description={props.course?.title}>
66+ <form class="space-y-4" onSubmit={submit}>
67+ <div class="space-y-3 rounded-xl border border-border-line bg-surface-tint p-4">
68+ <div class="space-y-1.5">
69+ <Label for="edit-course-title">{t("form.title")}</Label>
70+ <Input id="edit-course-title" value={title()} required maxlength={200} onInput={(e) => setTitle(e.currentTarget.value)} />
71+ </div>
72+ <div class="space-y-1.5">
73+ <Label for="edit-course-desc">{t("form.description")}</Label>
74+ <Textarea id="edit-course-desc" value={description()} rows={3} maxlength={2000} onInput={(e) => setDescription(e.currentTarget.value)} />
75+ </div>
76+ <div class="space-y-1.5">
77+ <Label for="edit-course-kind">{t("courses.kind")}</Label>
78+ <Select id="edit-course-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as CourseKind)}>
79+ <For each={COURSE_KINDS}>{(item) => <option value={item}>{kindLabel(item)}</option>}</For>
80+ </Select>
81+ </div>
82+ </div>
83+ <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
84+ <div class="sticky bottom-0 -mx-5 flex flex-wrap gap-2 border-t border-border-line bg-surface-base px-5 pb-6 pt-4 sm:-mx-6 sm:px-6 sm:pb-6">
85+ <Button type="submit" class="flex-1 rounded-xl sm:flex-none" disabled={pending()}>
86+ {t("common.update")}
87+ </Button>
88+ <Button type="button" variant="outline" class="flex-1 rounded-xl sm:flex-none" onClick={() => props.onOpenChange(false)}>
89+ {t("common.cancel")}
90+ </Button>
91+ </div>
92+ </form>
93+ </SidePanel>
94+ );
95+}
src/components/courses/course-notes-panel.tsxmodified+1 -1
@@ -83,7 +83,7 @@ export function CourseNotesPanel(props: {
8383 <Alert variant="destructive">{error()}</Alert>
8484 </Show>
8585
86- <div class="space-y-3 rounded-lg border border-border-line bg-surface-base p-3">
86+ <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
8787 <DataToolbar
8888 inline
8989 searchValue={search()}
src/components/courses/course-subjects-panel.tsxmodified+17 -22
@@ -11,8 +11,6 @@ import { Alert } from "@/components/ui/alert";
1111 import { Button } from "@/components/ui/button";
1212 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1313 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
14-import { DataToolbar } from "@/components/ui/data-toolbar";
15-import { EmptyState } from "@/components/ui/empty-state";
1614 import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
1715 import { Input } from "@/components/ui/input";
1816 import { Label } from "@/components/ui/label";
@@ -165,29 +163,26 @@ export function CourseSubjectsPanel(props: { courseId: string; canManage: boolea
165163
166164 {error() && <p class="rounded-xl bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{error()}</p>}
167165
168- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
169- <DataToolbar
170- inline
166+ {/* The table draws its toolbar (search, add, columns) and grid as two
167+ sibling cards, like the list pages; no frame around them. */}
168+ <Suspense fallback={<DataTableSkeleton />}>
169+ <DataTable
170+ columns={columns()}
171+ data={visibleSubjects()}
171172 searchValue={search()}
172- searchPlaceholder={t("common.searchPlaceholder")}
173173 onSearchInput={setSearch}
174- actions={
175- <Show when={props.canManage}>
176- <Button type="button" size="sm" class="rounded-lg" onClick={() => props.onCreateOpenChange(true)}>
177- <IconPlus class="h-4 w-4" />{t("subjects.add")}
178- </Button>
179- </Show>
180- }
174+ filterPlaceholder={t("common.searchPlaceholder")}
175+ enablePagination
176+ pageSize={10}
177+ empty={t("subjects.empty")}
178+ emptyIllustration="courses"
179+ actions={props.canManage ? (
180+ <Button type="button" size="sm" class="rounded-lg" onClick={() => props.onCreateOpenChange(true)}>
181+ <IconPlus class="h-4 w-4" />{t("subjects.add")}
182+ </Button>
183+ ) : undefined}
181184 />
182- </div>
183-
184- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs sm:p-4">
185- <Suspense fallback={<DataTableSkeleton />}>
186- <Show when={visibleSubjects().length > 0} fallback={<EmptyState kind="courses" title={t("subjects.empty")} />}>
187- <DataTable columns={columns()} data={visibleSubjects()} enablePagination pageSize={10} />
188- </Show>
189- </Suspense>
190- </div>
185+ </Suspense>
191186 </div>
192187 );
193188 }
src/components/courses/course-teachers-panel.tsxmodified+15 -13
@@ -7,8 +7,7 @@ import { Alert } from "@/components/ui/alert";
77 import { Button } from "@/components/ui/button";
88 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
99 import { DataTable } from "@/components/ui/data-table";
10-import { EmptyState } from "@/components/ui/empty-state";
11-import { IconTrash } from "@/components/ui/icons";
10+import { IconPlus, IconTrash } from "@/components/ui/icons";
1211 import { SidePanel } from "@/components/ui/side-panel";
1312 import { TableRowActions } from "@/components/ui/table-row-actions";
1413 import { UserSearchSelect } from "@/components/users/user-search-select";
@@ -113,17 +112,20 @@ export function CourseTeachersPanel(props: {
113112 <Alert variant="destructive">{error()}</Alert>
114113 </Show>
115114
116- <Show
117- when={props.teachers.length > 0}
118- fallback={
119- <EmptyState
120- kind="people"
121- title={t("courses.noTeachers")}
122- />
123- }
124- >
125- <DataTable columns={columns()} data={props.teachers} storageKey="course-teachers" />
126- </Show>
115+ {/* The assign button rides in the table's toolbar card, so it stays
116+ reachable while the list is empty. */}
117+ <DataTable
118+ columns={columns()}
119+ data={props.teachers}
120+ storageKey="course-teachers"
121+ empty={t("courses.noTeachers")}
122+ emptyIllustration="people"
123+ actions={props.canStaff ? (
124+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => props.onAssignOpenChange(true)}>
125+ <IconPlus class="h-4 w-4" />{t("courses.assignTeacher")}
126+ </Button>
127+ ) : undefined}
128+ />
127129
128130 <SidePanel
129131 open={props.assignOpen}
src/components/events/event-edit-panel.tsxadded+47 -0
@@ -0,0 +1,47 @@
1+import { Show } from "solid-js";
2+import { patchEventById } from "@/api/events";
3+import type { Event } from "@/api/client";
4+import { EventForm } from "@/components/events/event-form";
5+import { SidePanel } from "@/components/ui/side-panel";
6+import { useT } from "@/stores/preferences-context";
7+
8+/**
9+ * An event's edit panel. One component for the event detail page header and
10+ * the events list's row menu, so both send the same PATCH. EventForm reads its
11+ * initial values once, so the form is keyed on the event: a different row gets
12+ * a fresh form. The panel closes itself on success; the caller refetches and
13+ * shows its own flash in `onSaved`. EventForm reports a failed save itself.
14+ */
15+export function EventEditPanel(props: {
16+ event: Event | null;
17+ open: boolean;
18+ onOpenChange: (open: boolean) => void;
19+ onSaved: () => void | Promise<void>;
20+}) {
21+ const t = useT();
22+ return (
23+ <SidePanel guardUnsaved open={props.open && !!props.event} onOpenChange={props.onOpenChange} title={t("common.edit")} description={props.event?.title}>
24+ <Show when={props.event} keyed>
25+ {(ev) => (
26+ <EventForm
27+ initial={ev}
28+ submitLabel={t("common.update")}
29+ onCancel={() => props.onOpenChange(false)}
30+ onSubmit={async (values) => {
31+ const body: Record<string, unknown> = {
32+ title: values.title,
33+ description: values.description,
34+ audience: values.audience,
35+ };
36+ if (values.starts_at !== undefined) body.starts_at = values.starts_at;
37+ if (values.ends_at !== undefined) body.ends_at = values.ends_at;
38+ await patchEventById(ev.id, body);
39+ props.onOpenChange(false);
40+ await props.onSaved();
41+ }}
42+ />
43+ )}
44+ </Show>
45+ </SidePanel>
46+ );
47+}
src/components/exams/answer-sheet-view.test.tsxadded+40 -0
@@ -0,0 +1,40 @@
1+import { cleanup, render, screen, waitFor } from "@solidjs/testing-library";
2+import { afterEach, expect, test, vi } from "vitest";
3+import { ApiError } from "@/api/client";
4+import { AnswerSheetView } from "@/components/exams/answer-sheet-view";
5+import { PreferencesProvider } from "@/stores/preferences-context";
6+
7+const { getExamQuestions, getStudentAttempts, getStudentAnswers } = vi.hoisted(() => ({
8+ getExamQuestions: vi.fn(),
9+ getStudentAttempts: vi.fn(),
10+ getStudentAnswers: vi.fn(),
11+}));
12+
13+vi.mock("@/api/exams", () => ({
14+ getExamQuestions,
15+ getStudentAttempts,
16+ getStudentAnswers,
17+}));
18+
19+afterEach(() => {
20+ cleanup();
21+ vi.clearAllMocks();
22+});
23+
24+test("an answer sheet without an attempt never displays the student UUID", async () => {
25+ const userId = "123e4567-e89b-42d3-a456-426614174000";
26+ getExamQuestions.mockResolvedValue({ items: [] });
27+ getStudentAttempts.mockResolvedValue([]);
28+ getStudentAnswers.mockRejectedValue(new ApiError(404, "not found"));
29+
30+ render(() => (
31+ <PreferencesProvider>
32+ <AnswerSheetView examId="exam-1" userId={userId} />
33+ </PreferencesProvider>
34+ ));
35+
36+ await waitFor(() => expect(getStudentAnswers).toHaveBeenCalledWith("exam-1", userId));
37+ await screen.findByText(/Not started|Başlamadı/);
38+ expect(screen.getByText("—")).toBeTruthy();
39+ expect(document.body.textContent).not.toContain(userId);
40+});
src/components/exams/answer-sheet-view.tsxmodified+6 -4
@@ -14,7 +14,7 @@ import { ReplayableImage } from "@/components/ui/replayable-image";
1414 import { DropdownSelect } from "@/components/ui/select";
1515 import { cn } from "@/lib/cn";
1616 import { joinAnswerSheet } from "@/lib/answer-sheet";
17-import { personLabelWithId } from "@/lib/person";
17+import { personLabel } from "@/lib/person";
1818 import { useT } from "@/stores/preferences-context";
1919
2020 export function AnswerSheetView(props: { examId: string; userId: string; mode?: "grader" | "self" }) {
@@ -95,6 +95,7 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
9595 async ([examId, userId, seq, latest]) => {
9696 const questions = mode() === "self" ? await getExamReviewQuestions(examId) : await getExamQuestions(examId);
9797 let sheet: StudentAnswerSheet;
98+ let hasSheet = true;
9899 try {
99100 if (mode() === "self") {
100101 if (seq == null) throw new ApiError(404, "no attempts");
@@ -107,9 +108,10 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
107108 } catch (err) {
108109 if (err instanceof ApiError && (err.status === 404 || (mode() === "self" && err.status === 409))) {
109110 if (mode() === "self" && err instanceof ApiError && err.status === 409) setReviewInProgress(true);
111+ hasSheet = false;
110112 sheet = {
111113 exam: examId,
112- user: { id: userId, username: userId, display_name: null },
114+ user: { id: userId, username: "", display_name: null },
113115 answers: [],
114116 auto_score: { earned: 0, possible: 0 },
115117 };
@@ -117,7 +119,7 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
117119 throw err;
118120 }
119121 }
120- return { sheet, rows: joinAnswerSheet(questions.items, sheet.answers) };
122+ return { sheet, hasSheet, rows: joinAnswerSheet(questions.items, sheet.answers) };
121123 },
122124 );
123125
@@ -170,7 +172,7 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
170172 <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-xs text-muted-foreground">{t("exams.pastAttemptReadOnly")}</p>
171173 </Show>
172174 <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-4 py-3">
173- <p class="text-sm font-medium">{personLabelWithId(d().sheet.user)}</p>
175+ <p class="text-sm font-medium">{d().hasSheet ? personLabel(d().sheet.user) : "—"}</p>
174176 <Show when={d().sheet.answers.length > 0} fallback={<Badge variant="outline">{t("exams.notStarted")}</Badge>}>
175177 <div class="flex flex-wrap items-center gap-1.5">
176178 <Badge variant="outline" class="border-success/50 bg-success/10 text-success-text">
src/components/homework/course-homework-panel.tsxmodified+18 -5
@@ -14,8 +14,7 @@ import { Button } from "@/components/ui/button";
1414 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1515 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1616 import { DatePicker } from "@/components/ui/date-picker";
17-import { EmptyState } from "@/components/ui/empty-state";
18-import { IconEdit, IconEye, IconTrash } from "@/components/ui/icons";
17+import { IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons";
1918 import { Input } from "@/components/ui/input";
2019 import { Label } from "@/components/ui/label";
2120 import { Select } from "@/components/ui/select";
@@ -213,9 +212,23 @@ export function CourseHomeworkPanel(props: {
213212 </Show>
214213
215214 <Suspense fallback={<DataTableSkeleton />}>
216- <Show when={(homework() ?? []).length > 0} fallback={<EmptyState kind="homework" title={t("homework.empty")} />}>
217- <DataTable columns={columns()} data={homework() ?? []} filterColumn="title" enablePagination pageSize={10} empty={t("homework.empty")} onRowClick={(item) => void navigate({ to: "/homework/$id", params: { id: item.id } })} />
218- </Show>
215+ {/* The add button rides in the table's toolbar card, so it stays
216+ reachable on an empty list too. */}
217+ <DataTable
218+ columns={columns()}
219+ data={homework() ?? []}
220+ filterColumn="title"
221+ enablePagination
222+ pageSize={10}
223+ empty={t("homework.empty")}
224+ emptyIllustration="homework"
225+ onRowClick={(item) => void navigate({ to: "/homework/$id", params: { id: item.id } })}
226+ actions={props.canManage ? (
227+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => props.onCreateOpenChange(true)}>
228+ <IconPlus class="h-4 w-4" />{t("homework.add")}
229+ </Button>
230+ ) : undefined}
231+ />
219232 </Suspense>
220233
221234 <SidePanel guardUnsaved open={props.createOpen} onOpenChange={setPanelOpen} title={editing() ? t("homework.edit") : t("homework.add")} description={t("homework.help")}>
src/components/homework/homework-submissions-panel.tsxmodified+2 -2
@@ -46,7 +46,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId
4646 const enrollmentUsers = createMemo(() => new Map((enrollments() ?? []).map((row) => [row.user.id, row.user])));
4747 const studentLabel = (userId: string) => {
4848 const user = enrollmentUsers().get(userId);
49- return user?.display_name?.trim() || user?.username || userId;
49+ return user?.display_name?.trim() || user?.username || "—";
5050 };
5151
5252 const openGrade = (row: HomeworkRosterEntry) => {
@@ -153,7 +153,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId
153153 });
154154
155155 return (
156- <section class="data-shell space-y-4 p-5">
156+ <section class="space-y-3">
157157 <div>
158158 <h2 class="text-lg font-semibold">{t("homework.submissions")}</h2>
159159 <p class="mt-1 text-sm text-text-subtle">{t("homework.submissionsHelp")}</p>
src/components/notes/note-document.test.tsxadded+124 -0
@@ -0,0 +1,124 @@
1+import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
2+import type { JSX } from "solid-js";
3+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+import { NoteDocument, stageFiles, uploadStagedFiles } from "@/components/notes/note-document";
5+import { PreferencesProvider } from "@/stores/preferences-context";
6+
7+const { getSettings, navigate, postNote, postNoteFile, showToast } = vi.hoisted(() => ({
8+ getSettings: vi.fn(),
9+ navigate: vi.fn(),
10+ postNote: vi.fn(),
11+ postNoteFile: vi.fn(),
12+ showToast: vi.fn(),
13+}));
14+
15+vi.mock("@tanstack/solid-router", () => ({
16+ Link: (props: { to: string; children: JSX.Element }) => <a href={props.to}>{props.children}</a>,
17+ useBlocker: () => () => ({ status: "unblocked" }),
18+ useNavigate: () => navigate,
19+}));
20+vi.mock("@/api/settings", () => ({ getSettings }));
21+vi.mock("@/api/notes", () => ({
22+ deleteNoteById: vi.fn(),
23+ deleteNoteFileById: vi.fn(),
24+ getNoteFileBlob: vi.fn(),
25+ getNoteFileUrl: vi.fn(),
26+ getNoteFiles: vi.fn(),
27+ patchNoteById: vi.fn(),
28+ postNote,
29+ postNoteFile,
30+}));
31+vi.mock("@/components/notes/note-files-panel", () => ({ NoteFilesPanel: () => null }));
32+vi.mock("@/components/notes/note-rich-editor", () => ({
33+ NoteRichEditor: (props: { actions?: JSX.Element; onChange: (value: string) => void }) => (
34+ <div>
35+ {props.actions}
36+ <textarea aria-label="note body" onInput={(event) => props.onChange(event.currentTarget.value)} />
37+ </div>
38+ ),
39+}));
40+vi.mock("@/components/ui/confirm-dialog", () => ({ ConfirmDialog: () => null }));
41+vi.mock("@/components/ui/toast", () => ({ showToast }));
42+
43+const file = (name: string, size: number) => new File([new Uint8Array(size)], name, { type: "text/plain" });
44+
45+describe("NoteDocument staged attachments", () => {
46+ beforeEach(() => {
47+ getSettings.mockResolvedValue({ max_file_bytes: 10 });
48+ navigate.mockResolvedValue(undefined);
49+ postNote.mockResolvedValue({ id: "note-1", title: "Study", content: "" });
50+ postNoteFile.mockResolvedValue({ id: "file-1" });
51+ });
52+
53+ afterEach(() => {
54+ cleanup();
55+ vi.clearAllMocks();
56+ });
57+
58+ it("keeps valid files, rejects oversized files, and stops at the count limit", () => {
59+ const result = stageFiles([file("existing.txt", 1)], [file("ok.txt", 2), file("large.txt", 11), file("extra.txt", 2)], 2, 10);
60+
61+ expect(result.files.map((item) => item.name)).toEqual(["existing.txt", "ok.txt"]);
62+ expect(result.tooLarge).toBe(true);
63+ expect(result.atLimit).toBe(true);
64+ });
65+
66+ it("shows staged files and lets the user remove one before saving", async () => {
67+ const { container } = render(() => (
68+ <PreferencesProvider>
69+ <NoteDocument />
70+ </PreferencesProvider>
71+ ));
72+ const input = container.querySelector('input[type="file"]') as HTMLInputElement;
73+ fireEvent.change(input, { target: { files: [file("study.txt", 3), file("plan.txt", 4)] } });
74+
75+ expect(screen.getByText("study.txt")).toBeTruthy();
76+ expect(screen.getByText("3 B")).toBeTruthy();
77+ expect(screen.getByText(/staged files will upload|dosyalar notu kaydettiğinde/)).toBeTruthy();
78+
79+ fireEvent.click(screen.getByRole("button", { name: /Remove file: study.txt|Dosyayı kaldır: study.txt/ }));
80+ expect(screen.queryByText("study.txt")).toBeNull();
81+ expect(screen.getByText("plan.txt")).toBeTruthy();
82+ });
83+
84+ it("creates the note before uploading staged files, sequentially", async () => {
85+ const calls: string[] = [];
86+ postNote.mockImplementation(async () => {
87+ calls.push("create");
88+ return { id: "note-1", title: "Study", content: "" };
89+ });
90+ postNoteFile.mockImplementation(async (_noteId: string, item: File) => {
91+ calls.push(item.name);
92+ if (item.name === "failed.txt") throw new Error("upload failed");
93+ return { id: item.name };
94+ });
95+
96+ const { container } = render(() => (
97+ <PreferencesProvider>
98+ <NoteDocument />
99+ </PreferencesProvider>
100+ ));
101+ fireEvent.input(screen.getByLabelText(/Title|Başlık/), { target: { value: "Study" } });
102+ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, {
103+ target: { files: [file("first.txt", 2), file("failed.txt", 2), file("last.txt", 2)] },
104+ });
105+ fireEvent.click(screen.getByRole("button", { name: /Save|Kaydet/ }));
106+
107+ await waitFor(() => expect(navigate).toHaveBeenCalled());
108+ expect(calls).toEqual(["create", "first.txt", "failed.txt", "last.txt"]);
109+ expect(navigate).toHaveBeenCalledWith({ to: "/notes/$id", params: { id: "note-1" }, replace: true });
110+ expect(showToast).toHaveBeenCalledWith({ title: expect.stringContaining("failed.txt") });
111+ });
112+
113+ it("reports upload failures by name while continuing in order", async () => {
114+ const calls: string[] = [];
115+ const failed = await uploadStagedFiles("note-1", [file("one.txt", 1), file("two.txt", 1)], async (_id, item) => {
116+ calls.push(item.name);
117+ if (item.name === "one.txt") throw new Error("failed");
118+ return { id: "file-2" };
119+ });
120+
121+ expect(calls).toEqual(["one.txt", "two.txt"]);
122+ expect(failed).toEqual(["one.txt"]);
123+ });
124+});
src/components/notes/note-document.tsxmodified+119 -11
@@ -1,20 +1,57 @@
11 import { Link, useBlocker, useNavigate } from "@tanstack/solid-router";
2-import { Show, createSignal, onCleanup, onMount } from "solid-js";
2+import { For, Show, createSignal, onCleanup, onMount } from "solid-js";
3+import { getSettings } from "@/api/settings";
34 import { formatApiError, type Note } from "@/api/client";
4-import { deleteNoteById, patchNoteById, postNote } from "@/api/notes";
5+import { deleteNoteById, patchNoteById, postNote, postNoteFile } from "@/api/notes";
56 import { NoteFilesPanel } from "@/components/notes/note-files-panel";
67 import { NoteRichEditor } from "@/components/notes/note-rich-editor";
78 import { Alert } from "@/components/ui/alert";
89 import { Button } from "@/components/ui/button";
910 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
10-import { IconAlert, IconChevronLeft, IconTrash } from "@/components/ui/icons";
11+import { IconAlert, IconChevronLeft, IconPlus, IconTrash } from "@/components/ui/icons";
1112 import { cn } from "@/lib/cn";
13+import { createResource } from "@/lib/create-resource";
1214 import { personalNoteFiles } from "@/lib/note-source";
15+import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
16+import { showToast } from "@/components/ui/toast";
1317 import { useT } from "@/stores/preferences-context";
1418
1519 const MAX_TITLE = 200;
1620 const MAX_CONTENT = 10_000;
1721
22+export function stageFiles(current: File[], selected: File[], maxFiles: number, maxBytes: number) {
23+ const files = [...current];
24+ let tooLarge = false;
25+ let atLimit = false;
26+ for (const file of selected) {
27+ if (file.size > maxBytes) {
28+ tooLarge = true;
29+ continue;
30+ }
31+ if (files.length >= maxFiles) {
32+ atLimit = true;
33+ continue;
34+ }
35+ files.push(file);
36+ }
37+ return { files, tooLarge, atLimit };
38+}
39+
40+export async function uploadStagedFiles(noteId: string, files: File[], uploadFile = postNoteFile) {
41+ const failed: string[] = [];
42+ for (const file of files) {
43+ try {
44+ await uploadFile(noteId, file);
45+ } catch {
46+ failed.push(file.name);
47+ }
48+ }
49+ return failed;
50+}
51+
52+const fileSnapshot = (files: File[]) => files.map((file) => [file.name, file.size, file.lastModified]);
53+const documentSnapshot = (title: string, content: string, files: File[]) => JSON.stringify([title, content, fileSnapshot(files)]);
54+
1855 /**
1956 * A personal note as a full-page document: title, editor, attachments. A new
2057 * note (no `note`) becomes a real one on first save and moves to its own URL,
@@ -25,16 +62,37 @@ export function NoteDocument(props: { note?: Note }) {
2562 const navigate = useNavigate();
2663 const [title, setTitle] = createSignal(props.note?.title ?? "");
2764 const [content, setContent] = createSignal(props.note?.content ?? "");
28- const [baseline, setBaseline] = createSignal(JSON.stringify([props.note?.title ?? "", props.note?.content ?? ""]));
65+ const [stagedFiles, setStagedFiles] = createSignal<File[]>([]);
66+ const [baseline, setBaseline] = createSignal(documentSnapshot(props.note?.title ?? "", props.note?.content ?? "", []));
2967 const [saving, setSaving] = createSignal(false);
3068 const [error, setError] = createSignal("");
3169 const [deleteOpen, setDeleteOpen] = createSignal(false);
32- const dirty = () => JSON.stringify([title(), content()]) !== baseline();
70+ const [settings] = createResource(async () => {
71+ try {
72+ return await getSettings();
73+ } catch {
74+ return null;
75+ }
76+ });
77+ const maxFileBytes = () => maxUploadBytes(settings());
78+ const atFileLimit = () => stagedFiles().length >= personalNoteFiles.maxFiles;
79+ const dirty = () => documentSnapshot(title(), content(), stagedFiles()) !== baseline();
3380 const isNew = () => !props.note;
81+ let fileInput: HTMLInputElement | undefined;
3482
3583 let leaving = false;
3684 const blocker = useBlocker({ shouldBlockFn: () => dirty(), enableBeforeUnload: () => dirty(), withResolver: true });
3785
86+ const addFiles = (selected: FileList | null) => {
87+ if (!selected) return;
88+ const result = stageFiles(stagedFiles(), Array.from(selected), personalNoteFiles.maxFiles, maxFileBytes());
89+ setStagedFiles(result.files);
90+ if (result.tooLarge) setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
91+ else if (result.atLimit) setError(t("notes.fileLimit"));
92+ else setError("");
93+ if (fileInput) fileInput.value = "";
94+ };
95+
3896 const save = async () => {
3997 if (saving()) return;
4098 const trimmed = title().trim();
@@ -50,12 +108,15 @@ export function NoteDocument(props: { note?: Note }) {
50108 if (props.note) {
51109 await patchNoteById(props.note.id, { title: trimmed, content: body });
52110 if (title().trim() === trimmed) setTitle(trimmed);
53- setBaseline(JSON.stringify([trimmed, body]));
111+ setBaseline(documentSnapshot(trimmed, body, []));
54112 } else {
55113 const created = await postNote({ title: trimmed, content: body || undefined });
114+ const failedFiles = await uploadStagedFiles(created.id, stagedFiles());
115+ setStagedFiles([]);
56116 // Settle the baseline first so the move to the note's URL is not blocked.
57- setBaseline(JSON.stringify([title(), content()]));
117+ setBaseline(documentSnapshot(title(), content(), []));
58118 await navigate({ to: "/notes/$id", params: { id: created.id }, replace: true });
119+ if (failedFiles.length > 0) showToast({ title: t("notes.fileUploadFailed", { files: failedFiles.join(", ") }) });
59120 }
60121 } catch (err) {
61122 setError(formatApiError(err));
@@ -132,9 +193,56 @@ export function NoteDocument(props: { note?: Note }) {
132193 <Show
133194 when={props.note}
134195 fallback={
135- <section class="rounded-xl border border-dashed border-border bg-card/60 p-4">
136- <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
137- <p class="mt-1 text-sm text-muted-foreground">{t("notes.filesAfterSave")}</p>
196+ <section class="space-y-3 rounded-lg border border-border/80 bg-card p-4 shadow-xs dark:border-white/8">
197+ <div>
198+ <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
199+ <p class="mt-1 text-xs text-muted-foreground">{t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}</p>
200+ </div>
201+ <input
202+ ref={(element) => {
203+ fileInput = element;
204+ }}
205+ type="file"
206+ multiple
207+ class="hidden"
208+ disabled={saving() || atFileLimit()}
209+ onChange={(event) => addFiles(event.currentTarget.files)}
210+ />
211+ <div class="grid w-full grid-cols-2 gap-2">
212+ <Button type="button" size="sm" class="col-span-2 w-full rounded-lg" disabled={saving() || atFileLimit()} onClick={() => fileInput?.click()}>
213+ <IconPlus class="h-4 w-4 shrink-0" />
214+ <span class="truncate">{t("notes.addFile")}</span>
215+ </Button>
216+ </div>
217+ <p class="text-xs text-muted-foreground">{t("notes.filesUploadOnSave")}</p>
218+ <Show when={atFileLimit()}>
219+ <p class="text-xs text-muted-foreground">{t("notes.fileLimit")}</p>
220+ </Show>
221+ <Show
222+ when={stagedFiles().length > 0}
223+ fallback={<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>}
224+ >
225+ <ul class="space-y-2 rounded-md border border-border/70 bg-background/70 p-2">
226+ <For each={stagedFiles()}>
227+ {(file, index) => (
228+ <li class="flex min-w-0 items-center gap-2 rounded-md border border-border/70 bg-card px-2.5 py-2 text-sm">
229+ <span class="min-w-0 flex-1 truncate" title={file.name}>{file.name}</span>
230+ <span class="shrink-0 text-xs text-muted-foreground">{formatBytes(file.size)}</span>
231+ <Button
232+ type="button"
233+ variant="ghost"
234+ size="icon"
235+ class="h-7 w-7 shrink-0 rounded-md text-muted-foreground hover:text-destructive-text"
236+ aria-label={`${t("notes.removeFile")}: ${file.name}`}
237+ onClick={() => setStagedFiles((files) => files.filter((_, fileIndex) => fileIndex !== index()))}
238+ >
239+ <IconTrash class="h-4 w-4" />
240+ </Button>
241+ </li>
242+ )}
243+ </For>
244+ </ul>
245+ </Show>
138246 </section>
139247 }
140248 >
@@ -152,7 +260,7 @@ export function NoteDocument(props: { note?: Note }) {
152260 onConfirm={async () => {
153261 if (!props.note) return;
154262 await deleteNoteById(props.note.id);
155- setBaseline(JSON.stringify([title(), content()]));
263+ setBaseline(documentSnapshot(title(), content(), []));
156264 await navigate({ to: "/notes" });
157265 }}
158266 />
src/components/notes/note-files-panel.tsxmodified+6 -4
@@ -147,7 +147,7 @@ export function NoteFilesPanel(props: {
147147 <Show when={flash()}>
148148 <Alert variant="success">{flash()}</Alert>
149149 </Show>
150- <div class="flex flex-wrap items-center justify-between gap-3">
150+ <div class="space-y-3">
151151 <div>
152152 <h3 class="text-sm font-semibold">{t("notes.files")}</h3>
153153 <Show when={canManage()}>
@@ -164,12 +164,14 @@ export function NoteFilesPanel(props: {
164164 onChange={(event) => void upload(event.currentTarget.files?.[0])}
165165 />
166166 <Show when={canManage()}>
167- <div class="grid grid-cols-2 gap-2 sm:flex sm:items-center">
168- <Button type="button" variant="outline" size="sm" class="w-full sm:w-32 rounded-lg" disabled={pending() || atLimit()} onClick={openNewDrawing}>
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="w-full rounded-lg" disabled={pending() || atLimit()} onClick={openNewDrawing}>
169171 <IconEdit class="h-4 w-4 shrink-0" />
170172 <span class="truncate">{t("notes.draw")}</span>
171173 </Button>
172- <Button type="button" size="sm" class="w-full sm:w-32 rounded-lg" disabled={pending() || atLimit()} onClick={() => input?.click()}>
174+ <Button type="button" size="sm" class="w-full rounded-lg" disabled={pending() || atLimit()} onClick={() => input?.click()}>
173175 <IconPlus class="h-4 w-4 shrink-0" />
174176 <span class="truncate">{t("notes.addFile")}</span>
175177 </Button>
src/components/notes/podcast-history.test.tsxmodified+1 -0
@@ -9,6 +9,7 @@ const podcastApi = vi.hoisted(() => ({
99 listPodcastJobs: vi.fn(),
1010 podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`),
1111 getPodcastJobAudioBlob: vi.fn(),
12+ getPodcastJobResultById: vi.fn(() => Promise.resolve({ job_id: "", audio_id: "", transcript: null })),
1213 }));
1314
1415 vi.mock("@/api/podcast", () => podcastApi);
src/components/notes/podcast-history.tsxmodified+1 -4
@@ -1,7 +1,7 @@
11 import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
22 import { createResponsivePageSize } from "@/lib/create-page-size";
33 import { createResource } from "@/lib/create-resource";
4-import { formatApiError, type PodcastJobSummary, type PodcastTranscriptSegment } from "@/api/client";
4+import { formatApiError, type PodcastJobSummary } from "@/api/client";
55 import type { MessageKey } from "@/i18n/messages";
66 import { listPodcastJobs, podcastAudioUrl } from "@/api/podcast";
77 import { Alert } from "@/components/ui/alert";
@@ -42,8 +42,6 @@ export function PodcastHistory(props: {
4242 refetchKey?: string | number;
4343 /** An episode to open with, e.g. one picked in the studio library. */
4444 episode?: string;
45- /** The transcript of the episode the panel just produced, if the service sent one. */
46- transcript?: { jobId: string; segments: PodcastTranscriptSegment[] } | null;
4745 }) {
4846 const t = useT();
4947 const downloadT = usePodcastDownloadT();
@@ -158,7 +156,6 @@ export function PodcastHistory(props: {
158156 subtitle={formatDateTime(current()?.created_at, locale())}
159157 downloadName={current() ? noteName(current()!) : undefined}
160158 durationSecs={current()?.duration_secs}
161- transcript={props.transcript?.jobId === jobId ? props.transcript.segments : null}
162159 autoplay={autoplay()}
163160 />
164161 )}
src/components/notes/podcast-panel.tsxmodified+3 -13
@@ -1,8 +1,8 @@
11 import { For, Show, Suspense, createEffect, createSignal, onCleanup } from "solid-js";
22 import { createResource } from "@/lib/create-resource";
33 import { getAiCapabilities } from "@/api/ai";
4-import { getPodcastJobById, getPodcastJobResultById, postPodcastJob, postPodcastJobCancel } from "@/api/podcast";
5-import { formatApiError, type PodcastFormat, type PodcastJobArtifacts, type PodcastJobStatus } from "@/api/client";
4+import { getPodcastJobById, postPodcastJob, postPodcastJobCancel } from "@/api/podcast";
5+import { formatApiError, type PodcastFormat, type PodcastJobStatus } from "@/api/client";
66 import { Alert } from "@/components/ui/alert";
77 import { Button } from "@/components/ui/button";
88 import { IconWaveform, IconX } from "@/components/ui/icons";
@@ -27,7 +27,6 @@ export function PodcastPanel(props: {
2727 const [format, setFormat] = createSignal<PodcastFormat>("duz_okuma");
2828 const [jobId, setJobId] = createSignal("");
2929 const [status, setStatus] = createSignal<PodcastJobStatus | null>(null);
30- const [artifacts, setArtifacts] = createSignal<PodcastJobArtifacts | null>(null);
3130 const [error, setError] = createSignal("");
3231 const [submitting, setSubmitting] = createSignal(false);
3332 const [cancelling, setCancelling] = createSignal(false);
@@ -62,11 +61,7 @@ export function PodcastPanel(props: {
6261 if (token !== generation || !active()) return;
6362 setStatus(next);
6463 recordStage(next.stage);
65- if (next.state === "done") {
66- const result = await getPodcastJobResultById(id);
67- if (token === generation) setArtifacts(result);
68- return;
69- }
64+ if (next.state === "done") return;
7065 if (next.state === "failed") {
7166 setError(t("podcast.failed"));
7267 }
@@ -82,7 +77,6 @@ export function PodcastPanel(props: {
8277 const token = generation;
8378 setJobId("");
8479 setStatus(null);
85- setArtifacts(null);
8680 setEtaSecs(null);
8781 setStages([]);
8882 setError("");
@@ -104,7 +98,6 @@ export function PodcastPanel(props: {
10498 const token = generation;
10599 setSubmitting(true);
106100 setError("");
107- setArtifacts(null);
108101 try {
109102 const receipt = await postPodcastJob({ source_id: props.noteId, format: format() });
110103 if (token !== generation) return;
@@ -250,9 +243,6 @@ export function PodcastPanel(props: {
250243 active={active()}
251244 episode={props.episode}
252245 refetchKey={status()?.state === "done" ? jobId() : ""}
253- transcript={
254- artifacts()?.transcript?.length ? { jobId: artifacts()!.job_id, segments: artifacts()!.transcript! } : null
255- }
256246 />
257247 </section>
258248 </Suspense>
src/components/notes/podcast-player.test.tsxmodified+35 -31
@@ -1,27 +1,28 @@
11 import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library";
22 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3-import type { PodcastTranscriptSegment } from "@/api/client";
43 import { PodcastPlayer } from "@/components/notes/podcast-player";
5-import { activeSegmentIndex } from "@/components/notes/podcast-transcript";
4+import { transcriptChapters } from "@/components/notes/podcast-transcript";
65 import { PreferencesProvider } from "@/stores/preferences-context";
76
8-const segments: PodcastTranscriptSegment[] = [
9- { start_secs: 0, end_secs: 4, text: "Hücre canlının en küçük birimidir.", speaker: null },
10- { start_secs: 4, end_secs: 9, text: "Zarı seçici geçirgendir.", speaker: null },
11- { start_secs: 9, end_secs: 15, text: "Çekirdek genetik bilgiyi taşır.", speaker: null },
12-];
13-
14-describe("activeSegmentIndex", () => {
15- it("finds the line being spoken", () => {
16- expect(activeSegmentIndex(segments, 0)).toBe(0);
17- expect(activeSegmentIndex(segments, 5.2)).toBe(1);
18- expect(activeSegmentIndex(segments, 9)).toBe(2);
19- expect(activeSegmentIndex(segments, 99)).toBe(2);
7+const getPodcastJobResultById = vi.hoisted(() => vi.fn());
8+vi.mock("@/api/podcast", async (importOriginal) => ({
9+ ...(await importOriginal<typeof import("@/api/podcast")>()),
10+ getPodcastJobResultById,
11+}));
12+
13+describe("transcriptChapters", () => {
14+ it("splits the backend's text on blank lines", () => {
15+ expect(transcriptChapters("Hücre canlının en küçük birimidir.\n\n Zarı seçici geçirgendir.\r\n\r\nÇekirdek\nbilgiyi taşır.")).toEqual([
16+ "Hücre canlının en küçük birimidir.",
17+ "Zarı seçici geçirgendir.",
18+ "Çekirdek\nbilgiyi taşır.",
19+ ]);
2020 });
2121
22- it("is -1 before the first line and on an empty transcript", () => {
23- expect(activeSegmentIndex([{ ...segments[0], start_secs: 2 }], 1)).toBe(-1);
24- expect(activeSegmentIndex([], 3)).toBe(-1);
22+ it("is empty for a missing or blank transcript", () => {
23+ expect(transcriptChapters(null)).toEqual([]);
24+ expect(transcriptChapters(undefined)).toEqual([]);
25+ expect(transcriptChapters(" \n\n ")).toEqual([]);
2526 });
2627 });
2728
@@ -31,8 +32,7 @@ describe("PodcastPlayer", () => {
3132 // jsdom has no media pipeline; the player only needs these to not throw.
3233 vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue(undefined);
3334 vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
34- // Nor element scrolling, which the transcript's follow uses.
35- Element.prototype.scrollTo ??= () => {};
35+ getPodcastJobResultById.mockResolvedValue({ job_id: "job 1", audio_id: "a.mp3", transcript: null });
3636 // Audio already buffered this far, so the seek needs no local copy.
3737 vi.spyOn(HTMLMediaElement.prototype, "buffered", "get").mockReturnValue({
3838 length: 1,
@@ -47,10 +47,10 @@ describe("PodcastPlayer", () => {
4747 vi.restoreAllMocks();
4848 });
4949
50- const renderPlayer = (transcript?: PodcastTranscriptSegment[] | null) =>
50+ const renderPlayer = () =>
5151 render(() => (
5252 <PreferencesProvider>
53- <PodcastPlayer jobId="job 1" title="Hücre" durationSecs={754} transcript={transcript} />
53+ <PodcastPlayer jobId="job 1" title="Hücre" durationSecs={754} />
5454 </PreferencesProvider>
5555 ));
5656
@@ -75,21 +75,25 @@ describe("PodcastPlayer", () => {
7575 expect(localStorage.getItem("hezarfen.audio.rate")).toBe("1.25");
7676 });
7777
78- it("offers no transcript control while the backend sends none", () => {
79- renderPlayer(null);
78+ it("offers no transcript control while the result carries none", async () => {
79+ renderPlayer();
8080
81+ await vi.waitFor(() => expect(getPodcastJobResultById).toHaveBeenCalledWith("job 1", expect.any(AbortSignal)));
8182 expect(screen.queryByRole("button", { name: "Transkripti göster" })).toBeNull();
8283 });
8384
84- it("opens the transcript and plays from a clicked line", async () => {
85- const { container } = renderPlayer(segments);
86-
87- await fireEvent.click(screen.getByRole("button", { name: "Transkripti göster" }));
88- expect(screen.getByText("Zarı seçici geçirgendir.")).toBeTruthy();
85+ it("opens the job's transcript, one paragraph per chapter", async () => {
86+ getPodcastJobResultById.mockResolvedValue({
87+ job_id: "job 1",
88+ audio_id: "a.mp3",
89+ transcript: "Hücre canlının en küçük birimidir.\n\nZarı seçici geçirgendir.",
90+ });
91+ renderPlayer();
8992
90- await fireEvent.click(screen.getByRole("button", { name: "00:04 konumundan dinle" }));
93+ await fireEvent.click(await screen.findByRole("button", { name: "Transkripti göster" }));
9194
92- expect(container.querySelector("audio")!.currentTime).toBe(4);
93- expect(HTMLMediaElement.prototype.play).toHaveBeenCalled();
95+ const region = screen.getByRole("region", { name: "Transkript" });
96+ expect(region.querySelectorAll("p")).toHaveLength(2);
97+ expect(screen.getByText("Zarı seçici geçirgendir.")).toBeTruthy();
9498 });
9599 });
src/components/notes/podcast-player.tsxmodified+23 -23
@@ -1,24 +1,22 @@
1-import { Show, createSignal } from "solid-js";
2-import { getPodcastJobAudioBlob, podcastAudioUrl } from "@/api/podcast";
3-import type { PodcastTranscriptSegment } from "@/api/client";
4-import { AudioPlayer, type AudioPlayerController } from "@/components/ui/audio-player";
1+import { Show, createEffect, createSignal, onCleanup } from "solid-js";
2+import { getPodcastJobAudioBlob, getPodcastJobResultById, podcastAudioUrl } from "@/api/podcast";
3+import { AudioPlayer } from "@/components/ui/audio-player";
54 import { IconDownload, IconTranscript } from "@/components/ui/icons";
65 import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download";
7-import { PodcastTranscript } from "@/components/notes/podcast-transcript";
6+import { PodcastTranscript, transcriptChapters } from "@/components/notes/podcast-transcript";
87 import { cn } from "@/lib/cn";
98 import { useT } from "@/stores/preferences-context";
109
1110 /**
1211 * One produced episode: the app's audio player on the job's stream, its
13- * download, and — once the backend sends one — the timed transcript under
14- * it. With no transcript there is no toggle at all rather than an empty one.
12+ * download, and the transcript under it when the job's result carries one.
13+ * With no transcript there is no toggle at all rather than an empty one.
1514 */
1615 export function PodcastPlayer(props: {
1716 jobId: string;
1817 title?: string;
1918 subtitle?: string;
2019 durationSecs?: number | null;
21- transcript?: PodcastTranscriptSegment[] | null;
2220 autoplay?: boolean;
2321 /** Off where the surrounding row already offers the download. */
2422 download?: boolean;
@@ -28,10 +26,21 @@ export function PodcastPlayer(props: {
2826 }) {
2927 const t = useT();
3028 const downloadT = usePodcastDownloadT();
31- const [currentSecs, setCurrentSecs] = createSignal(0);
3229 const [transcriptOpen, setTranscriptOpen] = createSignal(false);
33- let controller: AudioPlayerController | undefined;
34- const segments = () => props.transcript ?? [];
30+ const [chapters, setChapters] = createSignal<string[]>([]);
31+ // Read from the job's result rather than a resource: the player sits inside
32+ // the history's <Suspense>, and a missing transcript must not hold the audio
33+ // back. A failed read only means no transcript control.
34+ createEffect(() => {
35+ const jobId = props.jobId;
36+ const controller = new AbortController();
37+ setChapters([]);
38+ setTranscriptOpen(false);
39+ getPodcastJobResultById(jobId, controller.signal)
40+ .then((result) => setChapters(transcriptChapters(result.transcript)))
41+ .catch(() => {});
42+ onCleanup(() => controller.abort());
43+ });
3544
3645 return (
3746 <div class={cn("space-y-2", props.class)}>
@@ -42,8 +51,6 @@ export function PodcastPlayer(props: {
4251 durationHint={props.durationSecs}
4352 loadBlob={(signal) => getPodcastJobAudioBlob(props.jobId, signal)}
4453 autoplay={props.autoplay}
45- onTimeUpdate={setCurrentSecs}
46- controller={(value) => (controller = value)}
4754 actions={
4855 <Show when={props.download !== false}>
4956 <a
@@ -58,7 +65,7 @@ export function PodcastPlayer(props: {
5865 </Show>
5966 }
6067 extra={
61- <Show when={segments().length > 0}>
68+ <Show when={chapters().length > 0}>
6269 <button
6370 type="button"
6471 class={cn(
@@ -75,15 +82,8 @@ export function PodcastPlayer(props: {
7582 </Show>
7683 }
7784 />
78- <Show when={transcriptOpen() && segments().length > 0}>
79- <PodcastTranscript
80- segments={segments()}
81- currentSecs={currentSecs()}
82- onSeek={(secs) => {
83- controller?.seek(secs);
84- controller?.play();
85- }}
86- />
85+ <Show when={transcriptOpen() && chapters().length > 0}>
86+ <PodcastTranscript chapters={chapters()} />
8787 </Show>
8888 </div>
8989 );
src/components/notes/podcast-transcript.tsxmodified+17 -99
@@ -1,110 +1,28 @@
1-import { For, Show, createEffect, createMemo, createSignal } from "solid-js";
2-import type { PodcastTranscriptSegment } from "@/api/client";
3-import { cn } from "@/lib/cn";
4-import { formatDurationClock } from "@/lib/format";
1+import { For } from "solid-js";
52 import { useT } from "@/stores/preferences-context";
63
7-/** Index of the segment playing at `secs`, or -1 before the first one starts. */
8-export function activeSegmentIndex(segments: PodcastTranscriptSegment[], secs: number): number {
9- let low = 0;
10- let high = segments.length - 1;
11- let found = -1;
12- while (low <= high) {
13- const mid = (low + high) >> 1;
14- if (segments[mid].start_secs <= secs) {
15- found = mid;
16- low = mid + 1;
17- } else {
18- high = mid - 1;
19- }
20- }
21- return found;
4+/** The transcript's chapters: the backend joins them with blank lines. */
5+export function transcriptChapters(text: string | null | undefined): string[] {
6+ return (text ?? "")
7+ .split(/\r?\n\s*\r?\n/)
8+ .map((chapter) => chapter.trim())
9+ .filter(Boolean);
2210 }
2311
2412 /**
25- * The episode's timed transcript, following playback: the line being spoken
26- * is highlighted and kept in view, and clicking any line plays from there.
27- * Scrolling the list by hand stops the follow until the reader asks for it
28- * back, so reading ahead is never yanked away.
13+ * The episode's transcript, one paragraph per chapter. The backend sends it
14+ * without timings, so it reads alongside playback rather than following it.
2915 */
30-export function PodcastTranscript(props: {
31- segments: PodcastTranscriptSegment[];
32- currentSecs: number;
33- onSeek: (secs: number) => void;
34-}) {
16+export function PodcastTranscript(props: { chapters: string[] }) {
3517 const t = useT();
36- let list!: HTMLOListElement;
37- const [following, setFollowing] = createSignal(true);
38- // Set around our own scrolls so the scroll handler can tell them apart from
39- // the reader's.
40- let autoScrolling = false;
41- const active = createMemo(() => activeSegmentIndex(props.segments, props.currentSecs));
42-
43- const scrollToActive = (behavior: ScrollBehavior) => {
44- const row = list?.children[active()] as HTMLElement | undefined;
45- if (!row) return;
46- autoScrolling = true;
47- list.scrollTo({ top: row.offsetTop - list.clientHeight / 3, behavior });
48- window.setTimeout(() => (autoScrolling = false), behavior === "smooth" ? 400 : 0);
49- };
50-
51- createEffect(() => {
52- active();
53- if (following()) scrollToActive("smooth");
54- });
55-
5618 return (
57- <div class="relative">
58- <ol
59- ref={list}
60- class="relative max-h-72 space-y-0.5 overflow-y-auto rounded-lg border border-border-hairline bg-surface-base p-1.5"
61- aria-label={t("podcast.transcript.title")}
62- onScroll={() => {
63- if (!autoScrolling) setFollowing(false);
64- }}
65- >
66- <For each={props.segments}>
67- {(segment, index) => (
68- <li>
69- <button
70- type="button"
71- class={cn(
72- "flex w-full gap-3 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-muted focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
73- index() === active() ? "bg-primary/10 text-foreground" : "text-muted-foreground",
74- )}
75- aria-current={index() === active() ? "true" : undefined}
76- aria-label={t("podcast.transcript.seek", { time: formatDurationClock(segment.start_secs * 1000) })}
77- onClick={() => {
78- setFollowing(true);
79- props.onSeek(segment.start_secs);
80- }}
81- >
82- <span class="mt-px shrink-0 text-[11px] tabular-nums text-text-subtle">
83- {formatDurationClock(segment.start_secs * 1000)}
84- </span>
85- <span class="min-w-0 flex-1 leading-relaxed">
86- <Show when={segment.speaker}>
87- {(speaker) => <span class="mr-1.5 font-semibold text-foreground">{speaker()}:</span>}
88- </Show>
89- {segment.text}
90- </span>
91- </button>
92- </li>
93- )}
94- </For>
95- </ol>
96- <Show when={!following() && active() >= 0}>
97- <button
98- type="button"
99- class="absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full border border-border-line bg-background px-3 py-1 text-xs font-medium shadow-sm transition-colors hover:bg-muted"
100- onClick={() => {
101- setFollowing(true);
102- scrollToActive("smooth");
103- }}
104- >
105- {t("podcast.transcript.follow")}
106- </button>
107- </Show>
19+ <div
20+ class="max-h-72 space-y-3 overflow-y-auto rounded-lg border border-border-hairline bg-surface-base px-3 py-2.5 text-sm leading-relaxed text-muted-foreground"
21+ role="region"
22+ aria-label={t("podcast.transcript.title")}
23+ tabindex="0"
24+ >
25+ <For each={props.chapters}>{(chapter) => <p class="whitespace-pre-line">{chapter}</p>}</For>
10826 </div>
10927 );
11028 }
src/components/sessions/course-sessions-panel.tsxmodified+7 -1
@@ -16,7 +16,7 @@ import { DatePicker } from "@/components/ui/date-picker";
1616 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1717 import { DetailField } from "@/components/ui/detail-field";
1818 import { ErrorAlert } from "@/components/ui/error-alert";
19-import { IconClipboardCheck, IconEdit, IconEye, IconTrash } from "@/components/ui/icons";
19+import { IconClipboardCheck, IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons";
2020 import { Input } from "@/components/ui/input";
2121 import { Label } from "@/components/ui/label";
2222 import { Select } from "@/components/ui/select";
@@ -275,6 +275,11 @@ export function CourseSessionsPanel(props: {
275275 pageSize={10}
276276 empty={t("sessions.empty")}
277277 onRowClick={setDetailSession}
278+ actions={props.canManage ? (
279+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => props.onCreateOpenChange(true)}>
280+ <IconPlus class="h-4 w-4" />{t("sessions.add")}
281+ </Button>
282+ ) : undefined}
278283 />
279284 </Suspense>
280285
@@ -416,6 +421,7 @@ export function CourseSessionsPanel(props: {
416421 try {
417422 await deleteSessionById(session.id);
418423 if (selectedSession()?.id === session.id) setSelectedSession(null);
424+ if (detailSession()?.id === session.id) setDetailSession(null);
419425 await refetch();
420426 setFlash(t("common.deleted"));
421427 } catch (err) {
src/components/ui/confirm-dialog.test.tsxadded+73 -0
@@ -0,0 +1,73 @@
1+import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
2+import { createSignal } from "solid-js";
3+import { afterEach, beforeEach, expect, test, vi } from "vitest";
4+import { ConfirmDialog, type ConfirmDialogProps } from "@/components/ui/confirm-dialog";
5+import { PreferencesProvider } from "@/stores/preferences-context";
6+
7+beforeEach(() => vi.spyOn(window, "scrollTo").mockImplementation(() => {}));
8+afterEach(() => {
9+ cleanup();
10+ vi.restoreAllMocks();
11+});
12+
13+function mount(overrides: Partial<ConfirmDialogProps> = {}) {
14+ const [open, setOpen] = createSignal(true);
15+ render(() => (
16+ <PreferencesProvider>
17+ <span data-testid="state">{open() ? "open" : "closed"}</span>
18+ <ConfirmDialog
19+ open={open()}
20+ onOpenChange={setOpen}
21+ title="Delete note"
22+ variant="destructive"
23+ summary="Quarterly plan"
24+ onConfirm={() => {}}
25+ {...overrides}
26+ />
27+ </PreferencesProvider>
28+ ));
29+}
30+
31+const cancelButton = () => screen.getByRole("button", { name: /^(Cancel|İptal|Vazgeç)$/ });
32+const confirmButton = () => screen.getByRole("button", { name: /^(Yes, delete|Evet, sil)$/ });
33+
34+test("destructive dialog shows title, target and the irreversible note, focused on Cancel", async () => {
35+ mount();
36+ expect(await screen.findByText("Delete note")).toBeTruthy();
37+ const summary = screen.getByText("Quarterly plan");
38+ expect(summary.closest("[data-slot=confirm-summary]")?.getAttribute("title")).toBe("Quarterly plan");
39+ expect(screen.getByText(/This can't be undone\.|Bu işlem geri alınamaz\./)).toBeTruthy();
40+ await waitFor(() => expect(document.activeElement).toBe(cancelButton()));
41+});
42+
43+test("an explicit description replaces the default sentence", async () => {
44+ mount({ description: "Students lose access." });
45+ expect(await screen.findByText("Students lose access.")).toBeTruthy();
46+ expect(screen.queryByText(/This can't be undone\.|Bu işlem geri alınamaz\./)).toBeNull();
47+});
48+
49+test("confirm shows a spinner and stays disabled until onConfirm settles, then closes", async () => {
50+ let resolve!: () => void;
51+ const onConfirm = vi.fn(() => new Promise<void>((r) => (resolve = r)));
52+ mount({ onConfirm });
53+ await screen.findByText("Delete note");
54+
55+ fireEvent.click(confirmButton());
56+ fireEvent.click(confirmButton());
57+ expect(onConfirm).toHaveBeenCalledTimes(1);
58+ await waitFor(() => expect((confirmButton() as HTMLButtonElement).disabled).toBe(true));
59+ expect(document.querySelector("[data-slot=confirm-spinner]")).toBeTruthy();
60+ expect(screen.getByTestId("state").textContent).toBe("open");
61+
62+ resolve();
63+ await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed"));
64+});
65+
66+test("cancel closes without confirming", async () => {
67+ const onConfirm = vi.fn();
68+ mount({ onConfirm });
69+ await screen.findByText("Delete note");
70+ fireEvent.click(cancelButton());
71+ await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed"));
72+ expect(onConfirm).not.toHaveBeenCalled();
73+});
src/components/ui/confirm-dialog.tsxmodified+119 -66
@@ -1,12 +1,9 @@
11 import { type JSX, createEffect, createSignal, Show } from "solid-js";
22 import {
33 AlertDialog,
4- AlertDialogBody,
54 AlertDialogCancel,
65 AlertDialogContent,
76 AlertDialogDescription,
8- AlertDialogFooter,
9- AlertDialogHeader,
107 AlertDialogTitle,
118 } from "@/components/ui/alert-dialog";
129 import { Button } from "@/components/ui/button";
@@ -20,8 +17,14 @@ import { cn } from "@/lib/cn";
2017 export type ConfirmDialogProps = {
2118 open: boolean;
2219 onOpenChange: (open: boolean) => void;
20+ /** Short question or action name, shown bold at the top. */
2321 title: string;
22+ /**
23+ * One plain sentence about what happens. Defaults to "this cannot be undone"
24+ * for the destructive variant and to nothing for the default variant.
25+ */
2426 description?: string;
27+ /** The target (item name, or a one-line recap), shown in a box under the title. */
2528 summary: JSX.Element | string;
2629 confirmLabel?: string;
2730 cancelLabel?: string;
@@ -40,12 +43,25 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
4043 const [pending, setPending] = createSignal(false);
4144 const [promptValue, setPromptValue] = createSignal("");
4245 const destructive = () => props.variant === "destructive";
46+ let cancelRef: HTMLButtonElement | undefined;
4347
4448 // Reset the field each time the dialog opens so a prior entry never leaks over.
4549 createEffect(() => {
4650 if (props.open) setPromptValue(props.prompt?.initialValue ?? "");
4751 });
4852
53+ const description = () => props.description ?? (destructive() ? t("confirm.irreversible") : undefined);
54+ const summaryText = () => (typeof props.summary === "string" ? props.summary : undefined);
55+ const hasSummary = () => (typeof props.summary === "string" ? props.summary.trim() !== "" : props.summary != null);
56+ const cancelLabel = () => props.cancelLabel ?? t("common.cancel");
57+
58+ // While onConfirm runs the dialog stays put: Escape/outside clicks are ignored
59+ // so a half-finished request never loses its only visible state.
60+ const requestOpenChange = (open: boolean) => {
61+ if (!open && pending()) return;
62+ props.onOpenChange(open);
63+ };
64+
4965 const run = async () => {
5066 if (pending()) return;
5167 setPending(true);
@@ -58,100 +74,137 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
5874 };
5975
6076 return (
61- <AlertDialog open={props.open} onOpenChange={props.onOpenChange}>
62- <AlertDialogContent>
63- <AlertDialogHeader>
77+ <AlertDialog open={props.open} onOpenChange={requestOpenChange}>
78+ <AlertDialogContent
79+ class="max-w-[440px] rounded-xl border-border-line bg-surface-base"
80+ onOpenAutoFocus={(e: Event) => {
81+ // Destructive confirmations land on Cancel so a stray Enter never
82+ // deletes; a prompt keeps the default (its field comes first).
83+ if (destructive() && !props.prompt && cancelRef) {
84+ e.preventDefault();
85+ cancelRef.focus();
86+ }
87+ }}
88+ >
89+ <div class="flex items-start gap-4 px-5 pb-5 pt-5 sm:px-6">
6490 <span
91+ aria-hidden="true"
6592 class={cn(
66- "mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border",
67- props.iconClass ?? (destructive() ? "border-destructive/20 bg-destructive/10 text-destructive-text" : "border-primary/20 bg-primary/10 text-primary-text"),
93+ "flex h-10 w-10 shrink-0 items-center justify-center rounded-full border [&_svg]:h-5 [&_svg]:w-5",
94+ props.iconClass ??
95+ (destructive()
96+ ? "border-destructive/20 bg-destructive/10 text-destructive-text"
97+ : "border-primary/20 bg-primary/10 text-primary-text"),
6898 )}
6999 >
70- <Show when={props.icon} fallback={
71- <Show when={destructive()} fallback={<IconAlert class="h-4 w-4" />}>
72- <IconTrash class="h-4 w-4" />
73- </Show>
74- }>
100+ <Show
101+ when={props.icon}
102+ fallback={
103+ <Show when={destructive()} fallback={<IconAlert />}>
104+ <IconTrash />
105+ </Show>
106+ }
107+ >
75108 {props.icon}
76109 </Show>
77110 </span>
78- <div class="min-w-0 space-y-1">
79- <AlertDialogTitle>{props.title}</AlertDialogTitle>
80- <AlertDialogDescription>{props.description ?? t("confirm.review")}</AlertDialogDescription>
81- </div>
82- </AlertDialogHeader>
83111
84- <AlertDialogBody>
85- <p class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
86- {t("confirm.summary")}
87- </p>
88- <div class="rounded-md border border-border bg-muted/40 px-3 py-3 text-sm leading-relaxed">
89- {props.summary}
90- </div>
91- <Show when={props.prompt}>
92- {(prompt) => (
93- <div class="mt-3 space-y-1.5">
94- <Label for="confirm-prompt">{prompt().label}</Label>
95- <Show
96- when={prompt().singleLine}
97- fallback={
98- <Textarea
112+ <div class="min-w-0 flex-1 space-y-3 pt-0.5">
113+ <AlertDialogTitle class="text-base font-semibold leading-snug">{props.title}</AlertDialogTitle>
114+
115+ <Show when={hasSummary()}>
116+ <div
117+ data-slot="confirm-summary"
118+ class="rounded-lg border border-border-line bg-muted/40 px-3 py-2 text-sm font-medium leading-relaxed text-foreground"
119+ title={summaryText()}
120+ >
121+ <Show when={summaryText() !== undefined} fallback={props.summary}>
122+ <span class="line-clamp-3 break-words">{summaryText()}</span>
123+ </Show>
124+ </div>
125+ </Show>
126+
127+ <Show when={description()}>
128+ {(text) => (
129+ <AlertDialogDescription class="text-[13px] leading-relaxed text-muted-foreground">
130+ {text()}
131+ </AlertDialogDescription>
132+ )}
133+ </Show>
134+
135+ <Show when={props.prompt}>
136+ {(prompt) => (
137+ <div class="space-y-1.5 pt-1">
138+ <Label for="confirm-prompt">{prompt().label}</Label>
139+ <Show
140+ when={prompt().singleLine}
141+ fallback={
142+ <Textarea
143+ id="confirm-prompt"
144+ class="min-h-20"
145+ rows={2}
146+ maxlength={prompt().maxLength}
147+ placeholder={prompt().placeholder}
148+ value={promptValue()}
149+ disabled={pending()}
150+ onInput={(e) => setPromptValue(e.currentTarget.value)}
151+ />
152+ }
153+ >
154+ <Input
99155 id="confirm-prompt"
100- class="min-h-20"
101- rows={2}
102156 maxlength={prompt().maxLength}
103157 placeholder={prompt().placeholder}
104158 value={promptValue()}
105159 disabled={pending()}
106160 onInput={(e) => setPromptValue(e.currentTarget.value)}
161+ onKeyDown={(e) => {
162+ if (e.key === "Enter") {
163+ e.preventDefault();
164+ void run();
165+ }
166+ }}
107167 />
108- }
109- >
110- <Input
111- id="confirm-prompt"
112- maxlength={prompt().maxLength}
113- placeholder={prompt().placeholder}
114- value={promptValue()}
115- disabled={pending()}
116- onInput={(e) => setPromptValue(e.currentTarget.value)}
117- onKeyDown={(e) => {
118- if (e.key === "Enter") {
119- e.preventDefault();
120- void run();
121- }
122- }}
123- />
124- </Show>
125- </div>
126- )}
127- </Show>
128- </AlertDialogBody>
168+ </Show>
169+ </div>
170+ )}
171+ </Show>
172+ </div>
173+ </div>
129174
130- <AlertDialogFooter>
175+ <div class="flex flex-col-reverse gap-2 border-t border-border-line bg-muted/30 px-5 py-3 sm:flex-row sm:justify-end sm:px-6">
131176 <AlertDialogCancel
177+ ref={cancelRef}
132178 class={cn(
133- "inline-flex h-8 items-center justify-center rounded-md border border-input bg-background px-3 text-xs font-semibold shadow-sm",
134- "hover:bg-accent hover:text-accent-foreground disabled:opacity-50",
179+ "inline-flex h-9 w-full cursor-pointer items-center justify-center rounded-lg border border-border/70 bg-background px-4 text-sm font-medium transition-colors sm:w-auto",
180+ "hover:border-border hover:bg-muted/60 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
181+ "disabled:pointer-events-none disabled:opacity-50",
135182 )}
136183 disabled={pending()}
137184 // Kobalte's close button defaults its accessible name to an English
138185 // "Dismiss", which overrides the visible text.
139- aria-label={props.cancelLabel ?? t("common.cancel")}
186+ aria-label={cancelLabel()}
140187 >
141- {props.cancelLabel ?? t("common.cancel")}
188+ {cancelLabel()}
142189 </AlertDialogCancel>
143190 <Button
144191 type="button"
145- size="sm"
146- class="h-8 rounded-md px-3 text-xs font-semibold"
192+ class="h-9 w-full rounded-lg px-4 font-semibold sm:w-auto sm:min-w-[7.5rem]"
147193 variant={destructive() ? "destructive" : "default"}
148194 disabled={pending()}
195+ aria-busy={pending()}
149196 onClick={() => void run()}
150197 >
151- {props.confirmLabel ??
152- (destructive() ? t("confirm.confirmDelete") : t("confirm.confirmUpdate"))}
198+ <Show when={pending()}>
199+ <span
200+ aria-hidden="true"
201+ data-slot="confirm-spinner"
202+ class="h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent"
203+ />
204+ </Show>
205+ {props.confirmLabel ?? (destructive() ? t("confirm.confirmDelete") : t("confirm.confirmUpdate"))}
153206 </Button>
154- </AlertDialogFooter>
207+ </div>
155208 </AlertDialogContent>
156209 </AlertDialog>
157210 );
src/components/ui/data-table.test.tsxmodified+27 -0
@@ -1,4 +1,5 @@
11 import { createSignal } from "solid-js";
2+import { Portal } from "solid-js/web";
23 import { fireEvent, render, screen, within } from "@solidjs/testing-library";
34 import type { ColumnDef } from "@tanstack/solid-table";
45 import { DataTable } from "@/components/ui/data-table";
@@ -251,6 +252,32 @@ test("on a phone-width screen rows render as labelled cards instead of a sideway
251252 vi.unstubAllGlobals();
252253 });
253254
255+test("a pick in a row's portalled menu does not also open the row", () => {
256+ const portalColumns: ColumnDef<Row>[] = [
257+ { accessorKey: "name", header: "Name" },
258+ {
259+ id: "actions",
260+ header: "Actions",
261+ cell: () => (
262+ <Portal>
263+ <div role="menuitem">Edit</div>
264+ </Portal>
265+ ),
266+ },
267+ ];
268+ const onRowClick = vi.fn();
269+ render(() => (
270+ <PreferencesProvider>
271+ <DataTable columns={portalColumns} data={[{ name: "Ada" }]} enableColumnVisibility={false} onRowClick={onRowClick} />
272+ </PreferencesProvider>
273+ ));
274+
275+ fireEvent.click(screen.getAllByRole("menuitem", { name: "Edit" })[0]!);
276+ expect(onRowClick).not.toHaveBeenCalled();
277+ fireEvent.click(screen.getAllByText("Ada")[0]!);
278+ expect(onRowClick).toHaveBeenCalledOnce();
279+});
280+
254281 test("sortable headers expose their order through aria-sort", () => {
255282 const sortable: ColumnDef<Row>[] = [
256283 { accessorKey: "name", header: "Name" },
src/components/ui/data-table.tsxmodified+4 -0
@@ -329,6 +329,10 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
329329 };
330330 const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => {
331331 if (!(target instanceof Element)) return false;
332+ // Solid bubbles a portalled element's events through its owner, so a pick
333+ // in a row's action menu (rendered in a portal) reaches the row too; it is
334+ // not a click on the row.
335+ if (row instanceof Node && !row.contains(target)) return true;
332336 const interactive = target.closest("button,a,input,select,textarea,[role='button']");
333337 return interactive != null && interactive !== row;
334338 };
src/components/ui/draw-canvas.tsxmodified+14 -3
@@ -1,9 +1,11 @@
11 import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
22 import { Button } from "@/components/ui/button";
3+import { FullscreenToggle } from "@/components/ui/fullscreen-toggle";
34 import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons";
45 import { cn } from "@/lib/cn";
56 import { PAPER_CELL, PAPER_LINE, canvasPx, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke";
67 import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file";
8+import { FULLSCREEN_ROOT_CLASS, createFullscreen } from "@/lib/fullscreen";
79 import { useT } from "@/stores/preferences-context";
810
911 const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"];
@@ -52,7 +54,11 @@ export function DrawCanvas(props: {
5254 const t = useT();
5355 let canvas: HTMLCanvasElement | undefined;
5456 let wrap: HTMLDivElement | undefined;
57+ let root: HTMLDivElement | undefined;
5558 let current: Stroke | undefined;
59+ // Full screen covers the pad, its islands and the save row; the ResizeObserver
60+ // on `wrap` re-sizes the backing store and redraw() repaints every stroke.
61+ const fullscreen = createFullscreen(() => root);
5662 // Live pan drag: pointer origin + pan value at grab, so the pad follows the finger.
5763 let panStart: { x: number; y: number; px: number; py: number } | undefined;
5864
@@ -394,8 +400,12 @@ export function DrawCanvas(props: {
394400 );
395401
396402 return (
397- <div class={cn("space-y-3", props.class)}>
398- <div ref={wrap} class="relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-120" style={paperStyle()}>
403+ <div ref={root} class={cn("space-y-3", props.class, fullscreen.active() && FULLSCREEN_ROOT_CLASS)}>
404+ <div
405+ ref={wrap}
406+ class={cn("relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-120", fullscreen.active() && "min-h-0 flex-1 sm:h-auto h-auto")}
407+ style={paperStyle()}
408+ >
399409 <canvas
400410 ref={canvas}
401411 class="h-full w-full touch-none"
@@ -622,6 +632,7 @@ export function DrawCanvas(props: {
622632 </div>
623633
624634 <div class="absolute bottom-2 right-2 z-10 flex flex-col divide-y divide-border overflow-hidden rounded-lg border bg-card/90 shadow-xs backdrop-blur-xs">
635+ <FullscreenToggle active={fullscreen.active()} onToggle={fullscreen.toggle} />
625636 <button
626637 type="button"
627638 class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
@@ -651,7 +662,7 @@ export function DrawCanvas(props: {
651662 </div>
652663 </div>
653664
654- <div class="flex flex-wrap items-center gap-2">
665+ <div class="flex shrink-0 flex-wrap items-center gap-2">
655666 <Button type="button" class="h-10 px-5" disabled={props.pending || !canSave()} onClick={() => void save()}>
656667 {t("draw.save")}
657668 </Button>
src/components/ui/fullscreen-toggle.tsxadded+30 -0
@@ -0,0 +1,30 @@
1+import { Show } from "solid-js";
2+import { IconMaximize, IconMinimize } from "@/components/ui/icons";
3+import { cn } from "@/lib/cn";
4+import { useT } from "@/stores/preferences-context";
5+
6+/**
7+ * Icon button that enters/leaves full screen for a drawing surface. State lives
8+ * in the host's `createFullscreen()` (src/lib/fullscreen.ts); this only renders.
9+ */
10+export function FullscreenToggle(props: { active: boolean; onToggle: () => void; class?: string }) {
11+ const t = useT();
12+ const label = () => (props.active ? t("draw.exitFullscreen") : t("draw.fullscreen"));
13+ return (
14+ <button
15+ type="button"
16+ class={cn(
17+ "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
18+ props.class,
19+ )}
20+ title={label()}
21+ aria-label={label()}
22+ aria-pressed={props.active}
23+ onClick={() => props.onToggle()}
24+ >
25+ <Show when={props.active} fallback={<IconMaximize class="h-5 w-5" />}>
26+ <IconMinimize class="h-5 w-5" />
27+ </Show>
28+ </button>
29+ );
30+}
src/components/ui/icons.tsxmodified+24 -0
@@ -315,6 +315,30 @@ export function IconZoomIn(props: IconProps) {
315315 );
316316 }
317317
318+/** lucide "maximize" — four outward corners. */
319+export function IconMaximize(props: IconProps) {
320+ return (
321+ <Svg {...props}>
322+ <path d="M8 3H5a2 2 0 0 0-2 2v3" />
323+ <path d="M21 8V5a2 2 0 0 0-2-2h-3" />
324+ <path d="M3 16v3a2 2 0 0 0 2 2h3" />
325+ <path d="M16 21h3a2 2 0 0 0 2-2v-3" />
326+ </Svg>
327+ );
328+}
329+
330+/** lucide "minimize" — four inward corners. */
331+export function IconMinimize(props: IconProps) {
332+ return (
333+ <Svg {...props}>
334+ <path d="M8 3v3a2 2 0 0 1-2 2H3" />
335+ <path d="M21 8h-3a2 2 0 0 1-2-2V3" />
336+ <path d="M3 16h3a2 2 0 0 1 2 2v3" />
337+ <path d="M16 21v-3a2 2 0 0 1 2-2h3" />
338+ </Svg>
339+ );
340+}
341+
318342 export function IconZoomOut(props: IconProps) {
319343 return (
320344 <Svg {...props}>
src/components/ui/illustration.tsxmodified+18 -4
@@ -1,18 +1,32 @@
1-import { createResource } from "@/lib/create-resource";
1+import { createEffect, createSignal, onCleanup } from "solid-js";
22 import { cn } from "@/lib/cn";
33 import { loadIllustration, type IllustrationName } from "@/lib/illustrations";
44
55 /** Decorative, theme-tinted unDraw scene. Loaded on demand so empty states
6- * don't pull every SVG into the main bundle. */
6+ * don't pull every SVG into the main bundle.
7+ *
8+ * A plain signal, not a resource: a resource read suspends the nearest
9+ * <Suspense> until the SVG lands, and a table's "no results" state then
10+ * remounted the whole table — the search box lost focus mid-typing. */
711 export function Illustration(props: { name: IllustrationName; class?: string }) {
8- const [svg] = createResource(() => props.name, loadIllustration);
12+ const [svg, setSvg] = createSignal("");
13+ createEffect(() => {
14+ const name = props.name;
15+ let current = true;
16+ void loadIllustration(name).then((markup) => {
17+ if (current) setSvg(markup);
18+ }, () => {});
19+ onCleanup(() => {
20+ current = false;
21+ });
22+ });
923
1024 return (
1125 <span
1226 class={cn("illustration pointer-events-none block select-none [&>svg]:h-full [&>svg]:w-full", props.class)}
1327 aria-hidden="true"
1428 // Local, build-time assets only — never user content.
15- innerHTML={svg.latest ?? ""}
29+ innerHTML={svg()}
1630 />
1731 );
1832 }
src/components/ui/side-panel.test.tsxmodified+26 -0
@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-li
22 import { createSignal } from "solid-js";
33 import { afterEach, beforeEach, expect, test, vi } from "vitest";
44 import { SidePanel } from "@/components/ui/side-panel";
5+import { TableRowActions } from "@/components/ui/table-row-actions";
56 import { PreferencesProvider } from "@/stores/preferences-context";
67
78 beforeEach(() => vi.spyOn(window, "scrollTo").mockImplementation(() => {}));
@@ -69,3 +70,28 @@ test("guardUnsaved asks only once something was typed", async () => {
6970 expect(await screen.findByText(confirmTitle)).toBeTruthy();
7071 expect(screen.getByTestId("state").textContent).toBe("open");
7172 });
73+
74+test.each(["Grade", "View"])("a row action keeps the %s panel open after menu focus returns", async (action) => {
75+ const [selected, setSelected] = createSignal("");
76+ render(() => (
77+ <PreferencesProvider>
78+ <div id="root">
79+ <TableRowActions
80+ label="Actions"
81+ actions={[
82+ { label: "Grade", icon: <span />, onSelect: () => setSelected("Grade") },
83+ { label: "View", icon: <span />, onSelect: () => setSelected("View") },
84+ ]}
85+ />
86+ </div>
87+ <SidePanel open={selected() !== ""} onOpenChange={(open) => { if (!open) setSelected(""); }} title={selected()}>
88+ <p>Panel content</p>
89+ </SidePanel>
90+ </PreferencesProvider>
91+ ));
92+
93+ fireEvent.pointerDown(screen.getByRole("button", { name: "Actions" }), { button: 0, pointerType: "mouse" });
94+ fireEvent.keyDown(await screen.findByRole("menuitem", { name: action }), { key: "Enter" });
95+ await waitFor(() => expect(screen.getByRole("dialog", { name: action })).toBeTruthy());
96+ expect(screen.getByText("Panel content")).toBeTruthy();
97+});
src/components/ui/side-panel.tsxmodified+11 -0
@@ -81,6 +81,17 @@ export function SidePanel(
8181 // Explicit: with any AlertDialog in the tree (the discard confirm
8282 // below), Kobalte hands plain dialogs its "alertdialog" role too.
8383 role="dialog"
84+ // A row-actions menu that opened this panel is still animating out
85+ // when the panel mounts, and focus passing through it (or back to
86+ // its trigger in the inert app) read as leaving the panel, which
87+ // closed it at once — "Notlandır"/"Görüntüle" seemed to do nothing.
88+ // Focus moving to another dialog still closes the panel, which the
89+ // edit/delete flows opened from inside a panel rely on.
90+ onFocusOutside={(event) => {
91+ const target = (event as CustomEvent<{ originalEvent?: FocusEvent }>).detail?.originalEvent?.target;
92+ if (!(target instanceof Element)) return;
93+ if (target.closest('[role="menu"]') || document.getElementById("root")?.contains(target)) event.preventDefault();
94+ }}
8495 class={cn(
8596 "fixed inset-y-0 right-0 z-[70] flex h-full w-full flex-col border-l border-border-line bg-surface-base text-foreground shadow-[0_16px_40px_rgba(0,0,0,0.16)] outline-hidden",
8697 // The panel spans the whole display, so it has to keep its own
src/components/users/admin-user-edit-panel.tsxadded+57 -0
@@ -0,0 +1,57 @@
1+import { Show } from "solid-js";
2+import { createResource } from "@/lib/create-resource";
3+import { getLimits } from "@/api/limits";
4+import { getSettings } from "@/api/settings";
5+import { getUserProfile, patchUserProfile } from "@/api/users";
6+import type { User } from "@/api/client";
7+import { ProfileForm } from "@/components/users/profile-form";
8+import { PageSpinner } from "@/components/ui/page-spinner";
9+import { SidePanel } from "@/components/ui/side-panel";
10+import { useT } from "@/stores/preferences-context";
11+
12+/**
13+ * The admin's edit form for one account (name, contact, branş, student
14+ * number, display name/bio). One component for the admin user detail header
15+ * and the users list's row menu, so both send the same PATCH. It reads the
16+ * profile (display name, bio, branş live only there), the branş vocabulary and
17+ * the field limits only while open, and mounts the form once they are in:
18+ * ProfileForm reads its initial values once. The caller closes it and
19+ * refetches in `onSaved`.
20+ */
21+export function AdminUserEditPanel(props: {
22+ user: User | null;
23+ open: boolean;
24+ onOpenChange: (open: boolean) => void;
25+ onSaved: () => void | Promise<void>;
26+}) {
27+ const t = useT();
28+ const openId = () => (props.open && props.user ? props.user.id : null);
29+ const [profile] = createResource(openId, (userId) => getUserProfile(userId).catch(() => null));
30+ const [settings] = createResource(() => (props.open ? true : null), () => getSettings().catch(() => null));
31+ const [limits] = createResource(() => (props.open ? true : null), () => getLimits().catch(() => null));
32+
33+ // `.latest` suspends until a first value, which would blank the page's own
34+ // Suspense boundary; the form waits for all three reads instead.
35+ const settled = (res: { state: string }) => res.state === "ready" || res.state === "errored";
36+ const ready = () => settled(profile) && settled(settings) && settled(limits);
37+
38+ return (
39+ <SidePanel guardUnsaved open={props.open && !!props.user} onOpenChange={props.onOpenChange} title={t("profile.edit")} description={props.user?.username}>
40+ <Show when={props.user} keyed>
41+ {(user) => (
42+ <Show when={ready()} fallback={<PageSpinner />}>
43+ <ProfileForm
44+ user={user}
45+ profile={profile.latest ? { display_name: profile.latest.display_name, bio: profile.latest.bio, branch: profile.latest.branch } : undefined}
46+ branches={settings.latest?.branches}
47+ editStudentNumber
48+ maxStudentNumberLen={limits.latest?.user.max_student_number_len}
49+ onSave={(body) => patchUserProfile(user.id, body)}
50+ onSaved={() => void props.onSaved()}
51+ />
52+ </Show>
53+ )}
54+ </Show>
55+ </SidePanel>
56+ );
57+}
src/components/users/student-info-panel.tsxadded+176 -0
@@ -0,0 +1,176 @@
1+import { For, Show, Suspense } from "solid-js";
2+import { createResource } from "@/lib/create-resource";
3+import { ApiError, formatApiError, type PersonRef, type User } from "@/api/client";
4+import { getMyStudents } from "@/api/parents";
5+import { getUserById, getUserSearch } from "@/api/users";
6+import { DetailField } from "@/components/ui/detail-field";
7+import { EmptyInline } from "@/components/ui/empty-inline";
8+import { ErrorAlert } from "@/components/ui/error-alert";
9+import { PageSpinner } from "@/components/ui/page-spinner";
10+import { SidePanel } from "@/components/ui/side-panel";
11+import type { StudentInfoSource } from "@/lib/student-info-access";
12+import { useAuth } from "@/stores/auth-context";
13+import { usePreferences, useT } from "@/stores/preferences-context";
14+
15+type Field = { label: string; value: string };
16+type Section = { title: string; hint?: string; fields: Field[] };
17+
18+/** What each source can actually read; fields no endpoint fills stay out. */
19+type Loaded = {
20+ student: Partial<Pick<User, "name" | "surname" | "email" | "phone" | "birth_date" | "student_number">> | null;
21+ guardian: User | null;
22+};
23+
24+const forbidden = (err: unknown) => err instanceof ApiError && err.status === 403;
25+
26+/**
27+ * Record details about a student — and, for a linked parent, about the parent —
28+ * that the public profile never carries (legal name, student number, contact,
29+ * birth date). Each viewer only reads what the backend already grants them; see
30+ * `studentInfoSource`.
31+ */
32+export function StudentInfoPanel(props: {
33+ open: boolean;
34+ onOpenChange: (open: boolean) => void;
35+ source: StudentInfoSource;
36+ /** `name` is what the profile heading already shows; a legal name equal to
37+ * it is not repeated here. */
38+ student: { id: string; username: string; name: string };
39+}) {
40+ const t = useT();
41+ const prefs = usePreferences();
42+ const auth = useAuth();
43+
44+ const [data, { refetch }] = createResource(
45+ () => (props.open ? props.source : null),
46+ async (source): Promise<Loaded> => {
47+ const me = auth.user() ?? null;
48+ switch (source) {
49+ case "self":
50+ return { student: me, guardian: null };
51+ case "admin":
52+ try {
53+ return { student: await getUserById(props.student.id), guardian: null };
54+ } catch (err) {
55+ if (forbidden(err)) return { student: null, guardian: null };
56+ throw err;
57+ }
58+ case "staff": {
59+ // /users/{id} is admin-only; the search ref is the one place a
60+ // teacher or manager reads a student's number.
61+ try {
62+ const page = await getUserSearch(props.student.username, undefined, "student", { limit: 20 });
63+ const ref = page.items.find((p) => p.id === props.student.id);
64+ return { student: ref ? { student_number: ref.student_number } : null, guardian: null };
65+ } catch (err) {
66+ if (forbidden(err)) return { student: null, guardian: null };
67+ throw err;
68+ }
69+ }
70+ case "parent": {
71+ let ref: PersonRef | undefined;
72+ try {
73+ ref = (await getMyStudents({ limit: 100 })).items.find((p) => p.id === props.student.id);
74+ } catch (err) {
75+ if (!forbidden(err)) throw err;
76+ }
77+ return { student: ref ? { student_number: ref.student_number } : null, guardian: me };
78+ }
79+ }
80+ },
81+ );
82+
83+ const fullName = (u: { name?: string | null; surname?: string | null } | null) =>
84+ [u?.name, u?.surname].map((s) => s?.trim()).filter(Boolean).join(" ");
85+
86+ // birth_date is a calendar date ("1990-01-02"); read it as local midnight so
87+ // no time zone shifts it a day.
88+ const birthDate = (raw: string) => {
89+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
90+ if (!m) return raw;
91+ return new Intl.DateTimeFormat(prefs.locale() === "tr" ? "tr-TR" : "en-US", { dateStyle: "long" }).format(
92+ new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])),
93+ );
94+ };
95+
96+ const present = (fields: { label: string; value: string | null | undefined }[]): Field[] =>
97+ fields
98+ .map((f) => ({ label: f.label, value: f.value?.trim() ?? "" }))
99+ .filter((f) => f.value !== "");
100+
101+ const sections = (d: Loaded): Section[] => {
102+ const out: Section[] = [];
103+ const s = d.student;
104+ if (s) {
105+ const fields = present([
106+ { label: t("profile.fullName"), value: fullName(s) === props.student.name ? null : fullName(s) },
107+ { label: t("roster.studentNumber"), value: s.student_number },
108+ { label: t("profile.birthDate"), value: s.birth_date ? birthDate(s.birth_date) : null },
109+ { label: t("profile.email"), value: s.email },
110+ { label: t("profile.phone"), value: s.phone },
111+ ]);
112+ if (fields.length) out.push({ title: t("profile.studentInfoStudent"), fields });
113+ }
114+ const g = d.guardian;
115+ if (g) {
116+ const fields = present([
117+ { label: t("profile.fullName"), value: fullName(g) || g.display_name },
118+ { label: t("profile.email"), value: g.email },
119+ { label: t("profile.phone"), value: g.phone },
120+ ]);
121+ if (fields.length) {
122+ out.push({ title: t("profile.studentInfoGuardian"), hint: t("profile.studentInfoGuardianHint"), fields });
123+ }
124+ }
125+ return out;
126+ };
127+
128+ return (
129+ <SidePanel
130+ open={props.open}
131+ onOpenChange={props.onOpenChange}
132+ title={t("profile.studentInfo")}
133+ description={t("profile.studentInfoHint")}
134+ >
135+ <Show when={data.error}>
136+ <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} />
137+ </Show>
138+ <Suspense fallback={<PageSpinner />}>
139+ <Show when={!data.error && data()}>
140+ {(d) => (
141+ <Show
142+ when={sections(d()).length > 0}
143+ fallback={
144+ <EmptyInline
145+ size="md"
146+ title={t("profile.studentInfoEmpty")}
147+ hint={t("profile.studentInfoEmptyHint")}
148+ />
149+ }
150+ >
151+ <div class="space-y-6">
152+ <For each={sections(d())}>
153+ {(section) => (
154+ <section class="space-y-3">
155+ <div>
156+ <h3 class="text-sm font-semibold">{section.title}</h3>
157+ <Show when={section.hint}>
158+ <p class="text-xs text-muted-foreground">{section.hint}</p>
159+ </Show>
160+ </div>
161+ <div class="grid gap-4 rounded-lg border p-4 sm:grid-cols-2">
162+ <For each={section.fields}>
163+ {(f) => <DetailField label={f.label} value={f.value} />}
164+ </For>
165+ </div>
166+ </section>
167+ )}
168+ </For>
169+ </div>
170+ </Show>
171+ )}
172+ </Show>
173+ </Suspense>
174+ </SidePanel>
175+ );
176+}
src/components/users/user-search-select.tsxmodified+37 -13
@@ -133,12 +133,8 @@ export function UserSearchSelect(props: {
133133 setOpen(false);
134134 return;
135135 }
136- if (q.length === 0) {
137- setUsers([]);
138- setLoading(false);
139- setOpen(false);
140- return;
141- }
136+ // An empty query is a request for suggestions: `/users/search?q=` lists
137+ // the role's people, so the field works as a dropdown before any typing.
142138 // Mark pending now, not after the debounce fires — otherwise the empty
143139 // "no students" message flashes during the wait before the request starts.
144140 setLoading(true);
@@ -153,7 +149,14 @@ export function UserSearchSelect(props: {
153149 .finally(() => {
154150 if (!ctrl.signal.aborted) setLoading(false);
155151 });
156- }, 300);
152+ }, q.length === 0 ? 0 : 300);
153+ };
154+ // Opening the list (focus, the chevron) with nothing typed yet loads the
155+ // suggestions once; typing narrows them through the search.
156+ const openSuggestions = () => {
157+ if (!canSearch() || props.disabled) return;
158+ setOpen(true);
159+ if (query().trim() === "" && users().length === 0 && !loading()) runSearch("");
157160 };
158161 onCleanup(() => {
159162 controller?.abort();
@@ -161,7 +164,7 @@ export function UserSearchSelect(props: {
161164 });
162165
163166 const emptyText = createMemo(() => {
164- if (query().trim().length === 0 || loading() || options().length > 0) return "";
167+ if (loading() || options().length > 0 || (query().trim() === "" && selected())) return "";
165168 return props.emptyMessage ?? (props.role === "teacher" ? t("form.noTeachers") : t("form.noStudents"));
166169 });
167170
@@ -172,14 +175,18 @@ export function UserSearchSelect(props: {
172175 // Kobalte writes the picked person's name into the input only when
173176 // that person is among the options, so a preset one rides along
174177 // while nothing is being searched.
175- options={query().trim() === "" && selected() ? [selected()!] : options()}
178+ options={
179+ query().trim() === "" && selected() && !options().some((user) => user.id === selected()!.id)
180+ ? [selected()!, ...options()]
181+ : options()
182+ }
176183 // Results arrive async, so options is empty at input time. Kobalte
177184 // refuses to open an empty collection by default (and would close on
178185 // input) — allow it, and control open so the panel stays up while
179186 // loading, then results pop in.
180187 allowsEmptyCollection
181- open={open() && query().trim().length > 0}
182- onOpenChange={(nextOpen) => setOpen(nextOpen && query().trim().length > 0)}
188+ open={open()}
189+ onOpenChange={(nextOpen) => (nextOpen ? openSuggestions() : setOpen(false))}
183190 value={selected()}
184191 onChange={(user) => {
185192 setSelected(user);
@@ -197,8 +204,15 @@ export function UserSearchSelect(props: {
197204 return;
198205 }
199206 setQuery(value);
207+ // Erasing the field clears the pick — the only way to leave an
208+ // optional person (a class's homeroom teacher) unassigned again.
209+ if (value.trim() === "" && current) {
210+ setSelected(null);
211+ props.onChange("");
212+ props.onSelect?.(null);
213+ }
200214 runSearch(value);
201- if (value.trim().length > 0) setOpen(true);
215+ setOpen(true);
202216 }}
203217 optionValue="id"
204218 optionLabel={(user) => pickedLabel(user)}
@@ -216,7 +230,17 @@ export function UserSearchSelect(props: {
216230 )}
217231 >
218232 <ComboboxControl>
219- <ComboboxInput id={props.id} autocomplete="off" />
233+ <ComboboxInput
234+ id={props.id}
235+ autocomplete="off"
236+ // Typing into a field that already names someone used to append
237+ // to the name ("Ayşe Yılmaz (ayse.yilmaz)Mehmet") and find no one,
238+ // so a class's teacher could not be changed. Select it instead.
239+ onFocus={(event: FocusEvent) => {
240+ (event.currentTarget as HTMLInputElement).select();
241+ openSuggestions();
242+ }}
243+ />
220244 <ComboboxTrigger />
221245 </ComboboxControl>
222246 <ComboboxContent>
src/components/users/user-table.tsxmodified+6 -1
@@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
88 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
99 import { DataTable } from "@/components/ui/data-table";
1010 import { TableRowActions } from "@/components/ui/table-row-actions";
11-import { IconCheck, IconExternalLink, IconEye, IconUsers } from "@/components/ui/icons";
11+import { IconCheck, IconEdit, IconExternalLink, IconEye, IconUsers } from "@/components/ui/icons";
1212 import { ROLES } from "@/lib/roles";
1313 import { matchesSearch } from "@/lib/search-text";
1414 import { useT } from "@/stores/preferences-context";
@@ -75,6 +75,8 @@ export function UserTable(props: {
7575 onRoleChange: (userId: string, role: Role) => Promise<void>;
7676 onUserClick?: (user: User) => void;
7777 onParentClick?: (user: User) => void;
78+ /** The detail page's "Düzenle" (profile edit), offered in the row menu when given. */
79+ onEditClick?: (user: User) => void;
7880 title?: string;
7981 description?: string;
8082 actions?: JSX.Element;
@@ -139,6 +141,9 @@ export function UserTable(props: {
139141 icon: <IconEye class="h-4 w-4" />,
140142 onSelect: () => props.onUserClick?.(cell.row.original),
141143 },
144+ ...(props.onEditClick
145+ ? [{ label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => props.onEditClick?.(cell.row.original) }]
146+ : []),
142147 {
143148 label: t("profile.viewProfile"),
144149 icon: <IconExternalLink class="h-4 w-4" />,
src/components/whiteboard/whiteboard-canvas.tsxmodified+12 -2
@@ -1,6 +1,8 @@
11 import { For, Show, createSignal, onCleanup, onMount } from "solid-js";
2+import { FullscreenToggle } from "@/components/ui/fullscreen-toggle";
23 import { IconEdit, IconEraser, IconMove, IconZoomIn, IconZoomOut } from "@/components/ui/icons";
34 import { cn } from "@/lib/cn";
5+import { FULLSCREEN_ROOT_CLASS, createFullscreen } from "@/lib/fullscreen";
46 import {
57 PAPER_CELL,
68 PAPER_LINE,
@@ -55,7 +57,11 @@ export function WhiteboardCanvas(props: {
5557 const t = useT();
5658 let canvas: HTMLCanvasElement | undefined;
5759 let wrap: HTMLDivElement | undefined;
60+ let root: HTMLDivElement | undefined;
5861 let current: Stroke | undefined;
62+ // The ResizeObserver on `wrap` re-sizes the backing store on enter/exit and
63+ // redraw() repaints `committed`, so no stroke is lost.
64+ const fullscreen = createFullscreen(() => root);
5965 let panStart: { x: number; y: number; px: number; py: number } | undefined;
6066 // Every committed mark (local + remote), in draw order. Plain array, not a
6167 // signal: it can grow into the thousands and only pan/zoom/resize repaints it.
@@ -338,10 +344,13 @@ export function WhiteboardCanvas(props: {
338344 };
339345
340346 return (
341- <div class={cn("space-y-3", props.class)}>
347+ <div ref={root} class={cn("space-y-3", props.class, fullscreen.active() && FULLSCREEN_ROOT_CLASS)}>
342348 <div
343349 ref={wrap}
344- class="relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-[70vh]"
350+ class={cn(
351+ "relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-[70vh]",
352+ fullscreen.active() && "h-auto min-h-0 flex-1 sm:h-auto",
353+ )}
345354 style={paperStyle()}
346355 >
347356 <canvas
@@ -403,6 +412,7 @@ export function WhiteboardCanvas(props: {
403412
404413 {/* Bottom-right zoom */}
405414 <div class="absolute bottom-2 right-2 z-10 flex flex-col divide-y divide-border overflow-hidden rounded-lg border bg-card/90 shadow-xs backdrop-blur-xs">
415+ <FullscreenToggle active={fullscreen.active()} onToggle={fullscreen.toggle} />
406416 <button
407417 type="button"
408418 class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
src/i18n/locales/en.tsmodified+18 -7
@@ -204,6 +204,9 @@ export const en: Dict = {
204204 "notes.leaveHint": "Your unsaved changes to this note will be lost.",
205205 "notes.leaveConfirm": "Leave",
206206 "notes.filesAfterSave": "Save the note first, then attach files and drawings here.",
207+ "notes.filesUploadOnSave": "Your staged files will upload when you save the note.",
208+ "notes.removeFile": "Remove file",
209+ "notes.fileUploadFailed": "Note saved, but these files could not be uploaded: {files}",
207210 "notes.open": "Open",
208211 "messages.refreshList": "Refresh messages",
209212 "messages.deleteDraft": "Delete draft",
@@ -639,6 +642,7 @@ export const en: Dict = {
639642 "common.gotIt": "Got it",
640643 "confirm.review": "Check the summary below before you confirm.",
641644 "confirm.summary": "Summary",
645+ "confirm.irreversible": "This can't be undone.",
642646 "confirm.confirmDelete": "Yes, delete",
643647 "confirm.confirmUpdate": "Yes, update",
644648 "confirm.deleteTitle": "Confirm delete",
@@ -711,6 +715,7 @@ export const en: Dict = {
711715 "aiStudio.outputs.description": "Select a lesson note and keep its summary and podcast together for quick access.",
712716 "aiStudio.library.title": "Your generated library",
713717 "aiStudio.resizeRail": "Audio workshop panel width",
718+ "aiStudio.resizeHint": "Drag to resize · double-click to reset",
714719 "aiStudio.backToLibrary": "Back to library",
715720 "aiStudio.library.description": "Every summary and podcast you produced, newest first.",
716721 "aiStudio.library.count": "{count} outputs",
@@ -1098,8 +1103,6 @@ export const en: Dict = {
10981103 "podcast.transcript.title": "Transcript",
10991104 "podcast.transcript.show": "Show transcript",
11001105 "podcast.transcript.hide": "Hide transcript",
1101- "podcast.transcript.follow": "Back to playback",
1102- "podcast.transcript.seek": "Play from {time}",
11031106 "insights.title": "Hezarfen Intelligence",
11041107 "insights.subtitle": "Review student signals, recommendations, and nightly analysis runs.",
11051108 "insights.student": "Student",
@@ -1205,6 +1208,8 @@ export const en: Dict = {
12051208 "draw.zoomIn": "Zoom in",
12061209 "draw.zoomOut": "Zoom out",
12071210 "draw.resetZoom": "Reset zoom",
1211+ "draw.fullscreen": "Full screen",
1212+ "draw.exitFullscreen": "Exit full screen",
12081213 "draw.color": "Colour",
12091214 "draw.width": "Line thickness",
12101215 "draw.paper": "Paper",
@@ -1353,6 +1358,8 @@ export const en: Dict = {
13531358 "appointments.slotTaken": "This time was just taken by someone else. Please pick another.",
13541359 "appointments.noSlots": "No available times right now.",
13551360 "appointments.series": "Series",
1361+ "appointments.series.weekly": "Weekly",
1362+ "appointments.series.once": "One-off",
13561363 "appointments.time": "Time",
13571364 "appointments.status": "Status",
13581365 "appointments.publishSubtitle": "Offer a time window students can book. Repeat it weekly if you like.",
@@ -1407,7 +1414,6 @@ export const en: Dict = {
14071414 "exams.schedule": "Schedule",
14081415 "exams.examStatistics": "Exam statistics",
14091416 "exams.examQuestions": "Exam questions",
1410- "exams.studentResults": "Student grades",
14111417 "exams.window": "Window",
14121418 "exams.unscheduled": "Unscheduled",
14131419 "exams.mode": "Mode",
@@ -1484,7 +1490,6 @@ export const en: Dict = {
14841490 "questions.correctRequired": "Mark one choice as the correct answer before saving.",
14851491 "questions.correctRange": "Correct index must point to one of the choices",
14861492 "bank.title": "Question bank",
1487- "bank.subtitle": "Shared, reusable question templates that any teacher can add to an exam.",
14881493 "bank.empty": "No templates yet.",
14891494 "bank.create": "New template",
14901495 "bank.edit": "Edit template",
@@ -1791,7 +1796,6 @@ export const en: Dict = {
17911796 "courses.rosterItem": "Student",
17921797 "courses.enroll": "Enroll student",
17931798 "courses.exams": "Course exams",
1794- "courses.examItem": "Exam",
17951799 "courses.addExam": "Add exam",
17961800 "courses.weight": "Weight",
17971801 "courses.delete": "Delete course",
@@ -1826,7 +1830,6 @@ export const en: Dict = {
18261830 "courses.takeAttendance": "Take roll call",
18271831 "courses.analysis": "Analysis",
18281832 "homework.title": "Homework",
1829- "homework.item": "Homework",
18301833 "homework.add": "Add homework",
18311834 "homework.edit": "Edit homework",
18321835 "homework.empty": "No homework yet.",
@@ -1950,6 +1953,14 @@ export const en: Dict = {
19501953 "profile.email": "Email",
19511954 "profile.phone": "Phone",
19521955 "profile.birthDate": "Birth date",
1956+ "profile.fullName": "Full name",
1957+ "profile.studentInfo": "Student info",
1958+ "profile.studentInfoHint": "Record details the profile does not show.",
1959+ "profile.studentInfoStudent": "Student",
1960+ "profile.studentInfoGuardian": "Parent",
1961+ "profile.studentInfoGuardianHint": "Your details as the school has them.",
1962+ "profile.studentInfoEmpty": "No further details to show",
1963+ "profile.studentInfoEmptyHint": "The school may not have filled these in yet.",
19531964 "profile.edit": "Edit profile",
19541965 "profile.saved": "Profile saved",
19551966 "profile.emailInvalid": "Enter a valid email address (e.g. name@example.com)",
@@ -2215,7 +2226,6 @@ export const en: Dict = {
22152226 "terms.unarchive": "Reopen term",
22162227 "terms.archived": "Archived",
22172228 "sessions.title": "Lesson sessions",
2218- "sessions.item": "Session",
22192229 "sessions.subtitle": "Schedule lesson sessions and record roll call for each class.",
22202230 "sessions.topic": "Topic",
22212231 "sessions.add": "Add session",
@@ -2283,6 +2293,7 @@ export const en: Dict = {
22832293 "search.hint.courses": "Matches course title, description, creator, teacher and term.",
22842294 "search.hint.courseNotes": "Matches note title and content.",
22852295 "search.hint.classes": "Matches class name, grade and homeroom teacher.",
2296+ "search.hint.classMembers": "Matches student name, username and student number.",
22862297 "search.hint.bank": "Matches a phrase inside the question text.",
22872298 "search.hint.whiteboards": "Matches board titles on the page you are viewing.",
22882299 "search.hint.chat": "Matches the text of the messages in this chat.",
src/i18n/locales/tr.tsmodified+18 -7
@@ -200,6 +200,9 @@ export const tr: Dict = {
200200 "notes.leaveHint": "Bu nottaki kaydedilmemiş değişiklikler kaybolacak.",
201201 "notes.leaveConfirm": "Çık",
202202 "notes.filesAfterSave": "Önce notu kaydet, sonra buraya dosya ve çizim ekleyebilirsin.",
203+ "notes.filesUploadOnSave": "Eklediğin dosyalar notu kaydettiğinde yüklenir.",
204+ "notes.removeFile": "Dosyayı kaldır",
205+ "notes.fileUploadFailed": "Not kaydedildi, ancak şu dosyalar yüklenemedi: {files}",
203206 "notes.open": "Aç",
204207 "messages.refreshList": "Mesajları yenile",
205208 "messages.deleteDraft": "Taslağı sil",
@@ -635,6 +638,7 @@ export const tr: Dict = {
635638 "common.gotIt": "Anladım",
636639 "confirm.review": "Onaylamadan önce aşağıdaki özeti kontrol et.",
637640 "confirm.summary": "İşlem özeti",
641+ "confirm.irreversible": "Bu işlem geri alınamaz.",
638642 "confirm.confirmDelete": "Evet, sil",
639643 "confirm.confirmUpdate": "Evet, güncelle",
640644 "confirm.deleteTitle": "Silmeyi onayla",
@@ -707,6 +711,7 @@ export const tr: Dict = {
707711 "aiStudio.outputs.description": "Bir ders notu seçin; özetini ve podcast'ini hızlı erişim için aynı alanda üretin.",
708712 "aiStudio.library.title": "Üretim kitaplığın",
709713 "aiStudio.resizeRail": "Ses Atölyesi panelinin genişliği",
714+ "aiStudio.resizeHint": "Sürükleyerek genişlet · çift tıkla sıfırla",
710715 "aiStudio.backToLibrary": "Kitaplığa dön",
711716 "aiStudio.library.description": "Ürettiğin her özet ve podcast, en yenisi üstte.",
712717 "aiStudio.library.count": "{count} çıktı",
@@ -1094,8 +1099,6 @@ export const tr: Dict = {
10941099 "podcast.transcript.title": "Transkript",
10951100 "podcast.transcript.show": "Transkripti göster",
10961101 "podcast.transcript.hide": "Transkripti gizle",
1097- "podcast.transcript.follow": "Oynatılan yere dön",
1098- "podcast.transcript.seek": "{time} konumundan dinle",
10991102 "insights.title": "Hezarfen Zeka",
11001103 "insights.subtitle": "Öğrenci sinyallerini, önerileri ve gece analizlerini inceleyin.",
11011104 "insights.student": "Öğrenci",
@@ -1201,6 +1204,8 @@ export const tr: Dict = {
12011204 "draw.zoomIn": "Yakınlaştır",
12021205 "draw.zoomOut": "Uzaklaştır",
12031206 "draw.resetZoom": "Sıfırla",
1207+ "draw.fullscreen": "Tam ekran",
1208+ "draw.exitFullscreen": "Tam ekrandan çık",
12041209 "draw.color": "Renk",
12051210 "draw.width": "Çizgi kalınlığı",
12061211 "draw.paper": "Kağıt",
@@ -1349,6 +1354,8 @@ export const tr: Dict = {
13491354 "appointments.slotTaken": "Bu saat az önce başka biri tarafından alındı. Lütfen başka bir saat seçin.",
13501355 "appointments.noSlots": "Şu anda uygun saat yok.",
13511356 "appointments.series": "Seri",
1357+ "appointments.series.weekly": "Haftalık",
1358+ "appointments.series.once": "Tek seferlik",
13521359 "appointments.time": "Saat",
13531360 "appointments.status": "Durum",
13541361 "appointments.publishSubtitle": "Öğrencilerin alabileceği bir saat aralığı sunun. İsterseniz haftalık tekrarlayın.",
@@ -1403,7 +1410,6 @@ export const tr: Dict = {
14031410 "exams.schedule": "Zamanlama",
14041411 "exams.examStatistics": "Sınav istatistikleri",
14051412 "exams.examQuestions": "Sınav soruları",
1406- "exams.studentResults": "Öğrenci notları",
14071413 "exams.window": "Aralık",
14081414 "exams.unscheduled": "Zamansız",
14091415 "exams.mode": "Mod",
@@ -1480,7 +1486,6 @@ export const tr: Dict = {
14801486 "questions.correctRequired": "Kaydetmeden önce bir seçeneği doğru cevap olarak işaretle.",
14811487 "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",
14821488 "bank.title": "Soru bankası",
1483- "bank.subtitle": "Her öğretmenin sınavlarında kullanabileceği, paylaşımlı ve yeniden kullanılabilir soru şablonları.",
14841489 "bank.empty": "Henüz şablon yok.",
14851490 "bank.create": "Yeni şablon",
14861491 "bank.edit": "Şablonu düzenle",
@@ -1787,7 +1792,6 @@ export const tr: Dict = {
17871792 "courses.rosterItem": "Öğrenci",
17881793 "courses.enroll": "Öğrenci kaydet",
17891794 "courses.exams": "Ders sınavları",
1790- "courses.examItem": "Sınav",
17911795 "courses.addExam": "Sınav ekle",
17921796 "courses.weight": "Ağırlık",
17931797 "courses.delete": "Dersi sil",
@@ -1822,7 +1826,6 @@ export const tr: Dict = {
18221826 "courses.takeAttendance": "Yoklama al",
18231827 "courses.analysis": "Analiz",
18241828 "homework.title": "Ödevler",
1825- "homework.item": "Ödev",
18261829 "homework.add": "Ödev ekle",
18271830 "homework.edit": "Ödevi düzenle",
18281831 "homework.empty": "Henüz ödev yok.",
@@ -1946,6 +1949,14 @@ export const tr: Dict = {
19461949 "profile.email": "E-posta",
19471950 "profile.phone": "Telefon",
19481951 "profile.birthDate": "Doğum tarihi",
1952+ "profile.fullName": "Ad soyad",
1953+ "profile.studentInfo": "Öğrenci bilgileri",
1954+ "profile.studentInfoHint": "Profilde yer almayan kayıt bilgileri.",
1955+ "profile.studentInfoStudent": "Öğrenci",
1956+ "profile.studentInfoGuardian": "Veli",
1957+ "profile.studentInfoGuardianHint": "Okulun kayıtlarındaki sizin bilgileriniz.",
1958+ "profile.studentInfoEmpty": "Gösterilecek ek bilgi yok",
1959+ "profile.studentInfoEmptyHint": "Okul bu bilgileri henüz girmemiş olabilir.",
19491960 "profile.edit": "Profili düzenle",
19501961 "profile.saved": "Profil kaydedildi",
19511962 "profile.emailInvalid": "Geçerli bir e-posta adresi girin (örn. ad@ornek.com)",
@@ -2211,7 +2222,6 @@ export const tr: Dict = {
22112222 "terms.unarchive": "Dönemi yeniden aç",
22122223 "terms.archived": "Arşivli",
22132224 "sessions.title": "Ders oturumları",
2214- "sessions.item": "Oturum",
22152225 "sessions.subtitle": "Ders oturumlarını planlayın ve her ders için yoklama alın.",
22162226 "sessions.topic": "Konu",
22172227 "sessions.add": "Oturum ekle",
@@ -2279,6 +2289,7 @@ export const tr: Dict = {
22792289 "search.hint.courses": "Ders ad\u0131, a\u00e7\u0131klama, olu\u015fturan, \u00f6\u011fretmen ve d\u00f6nemde arar.",
22802290 "search.hint.courseNotes": "Not ba\u015fl\u0131\u011f\u0131 ve i\u00e7eri\u011finde arar.",
22812291 "search.hint.classes": "\u015eube ad\u0131, s\u0131n\u0131f d\u00fczeyi ve dan\u0131\u015fman \u00f6\u011fretmende arar.",
2292+ "search.hint.classMembers": "Öğrenci adı, kullanıcı adı ve öğrenci numarasında arar.",
22822293 "search.hint.bank": "Soru metninde ge\u00e7en bir ifadeyi arar.",
22832294 "search.hint.whiteboards": "A\u00e7\u0131k olan sayfadaki tahta ba\u015fl\u0131klar\u0131nda arar.",
22842295 "search.hint.chat": "Bu sohbetteki mesajlar\u0131n metninde arar.",
src/i18n/messages.tsmodified+18 -7
@@ -190,6 +190,9 @@ export type MessageKey =
190190 | "notes.leaveHint"
191191 | "notes.leaveConfirm"
192192 | "notes.filesAfterSave"
193+ | "notes.filesUploadOnSave"
194+ | "notes.removeFile"
195+ | "notes.fileUploadFailed"
193196 | "notes.open"
194197 | "messages.refreshList"
195198 | "messages.deleteDraft"
@@ -623,6 +626,7 @@ export type MessageKey =
623626 | "common.gotIt"
624627 | "confirm.review"
625628 | "confirm.summary"
629+ | "confirm.irreversible"
626630 | "confirm.confirmDelete"
627631 | "confirm.confirmUpdate"
628632 | "confirm.deleteTitle"
@@ -695,6 +699,7 @@ export type MessageKey =
695699 | "aiStudio.outputs.description"
696700 | "aiStudio.library.title"
697701 | "aiStudio.resizeRail"
702+ | "aiStudio.resizeHint"
698703 | "aiStudio.backToLibrary"
699704 | "aiStudio.library.description"
700705 | "aiStudio.library.count"
@@ -1085,8 +1090,6 @@ export type MessageKey =
10851090 | "podcast.transcript.title"
10861091 | "podcast.transcript.show"
10871092 | "podcast.transcript.hide"
1088- | "podcast.transcript.follow"
1089- | "podcast.transcript.seek"
10901093 | "insights.title"
10911094 | "insights.subtitle"
10921095 | "insights.student"
@@ -1192,6 +1195,8 @@ export type MessageKey =
11921195 | "draw.zoomIn"
11931196 | "draw.zoomOut"
11941197 | "draw.resetZoom"
1198+ | "draw.fullscreen"
1199+ | "draw.exitFullscreen"
11951200 | "draw.color"
11961201 | "draw.width"
11971202 | "draw.paper"
@@ -1306,7 +1311,6 @@ export type MessageKey =
13061311 | "exams.schedule"
13071312 | "exams.examStatistics"
13081313 | "exams.examQuestions"
1309- | "exams.studentResults"
13101314 | "exams.window"
13111315 | "exams.unscheduled"
13121316 | "exams.mode"
@@ -1383,7 +1387,6 @@ export type MessageKey =
13831387 | "questions.correctRequired"
13841388 | "questions.correctRange"
13851389 | "bank.title"
1386- | "bank.subtitle"
13871390 | "bank.empty"
13881391 | "bank.create"
13891392 | "bank.edit"
@@ -1685,7 +1688,6 @@ export type MessageKey =
16851688 | "courses.rosterItem"
16861689 | "courses.enroll"
16871690 | "courses.exams"
1688- | "courses.examItem"
16891691 | "courses.addExam"
16901692 | "courses.weight"
16911693 | "courses.delete"
@@ -1720,7 +1722,6 @@ export type MessageKey =
17201722 | "courses.takeAttendance"
17211723 | "courses.analysis"
17221724 | "homework.title"
1723- | "homework.item"
17241725 | "homework.add"
17251726 | "homework.edit"
17261727 | "homework.empty"
@@ -1844,6 +1845,14 @@ export type MessageKey =
18441845 | "profile.email"
18451846 | "profile.phone"
18461847 | "profile.birthDate"
1848+ | "profile.fullName"
1849+ | "profile.studentInfo"
1850+ | "profile.studentInfoHint"
1851+ | "profile.studentInfoStudent"
1852+ | "profile.studentInfoGuardian"
1853+ | "profile.studentInfoGuardianHint"
1854+ | "profile.studentInfoEmpty"
1855+ | "profile.studentInfoEmptyHint"
18471856 | "profile.edit"
18481857 | "profile.saved"
18491858 | "profile.emailInvalid"
@@ -2109,7 +2118,6 @@ export type MessageKey =
21092118 | "terms.unarchive"
21102119 | "terms.archived"
21112120 | "sessions.title"
2112- | "sessions.item"
21132121 | "sessions.subtitle"
21142122 | "sessions.topic"
21152123 | "sessions.add"
@@ -2184,6 +2192,7 @@ export type MessageKey =
21842192 | "search.hint.courses"
21852193 | "search.hint.courseNotes"
21862194 | "search.hint.classes"
2195+ | "search.hint.classMembers"
21872196 | "search.hint.bank"
21882197 | "search.hint.whiteboards"
21892198 | "search.hint.chat"
@@ -2285,6 +2294,8 @@ export type MessageKey =
22852294 | "appointments.slotTaken"
22862295 | "appointments.noSlots"
22872296 | "appointments.series"
2297+ | "appointments.series.weekly"
2298+ | "appointments.series.once"
22882299 | "appointments.time"
22892300 | "appointments.status"
22902301 | "appointments.publishSubtitle"
src/index.cssmodified+25 -2
@@ -353,12 +353,35 @@
353353 @apply h-9 rounded-md;
354354 }
355355
356+ /* The action bar sits flush on the panel's bottom edge: the body and the
357+ form drop their bottom padding, which otherwise left an empty strip under
358+ Kaydet / Vazgeç on every panel. */
359+ &:has(form > .flex:last-child) {
360+ @apply pb-0;
361+ }
362+
363+ & form:has(> .flex:last-child) {
364+ @apply pb-0;
365+ }
366+
367+ /* A form wrapped in a div (a help line above it) still fills the panel, so
368+ its bar lands on the bottom edge instead of just above it. */
369+ & > div:has(> form:last-child > .flex:last-child) {
370+ @apply flex min-h-full flex-col;
371+ }
372+
373+ & > div > form:last-child:has(> .flex:last-child) {
374+ @apply flex-1;
375+ }
376+
377+ /* mb-0 overrides a bar's own -mb-5, which (with bottom-0 here) pulled it
378+ over the last field. */
356379 & form > .flex:last-child {
357- @apply sticky bottom-0 -mx-5 justify-end border-t border-border bg-background px-5 py-3;
380+ @apply sticky bottom-0 -mx-5 mb-0 justify-end border-t border-border bg-background px-5 py-3;
358381 }
359382
360383 & form > .flex.flex-wrap:last-child {
361- @apply sticky bottom-0 -mx-5 justify-end border-t border-border bg-background px-5 py-3;
384+ @apply sticky bottom-0 -mx-5 mb-0 justify-end border-t border-border bg-background px-5 py-3;
362385 }
363386
364387 & form > .flex:last-child button {
src/lib/fullscreen.tsadded+134 -0
@@ -0,0 +1,134 @@
1+import { createSignal, onCleanup } from "solid-js";
2+
3+type FsElement = HTMLElement & { webkitRequestFullscreen?: () => Promise<void> | void };
4+type FsDocument = Document & {
5+ webkitFullscreenElement?: Element | null;
6+ webkitExitFullscreen?: () => Promise<void> | void;
7+};
8+
9+// Ancestor styles that turn an ancestor into the containing block of a
10+// `position: fixed` child (a SidePanel's slide-in `translate`, for one) and
11+// would trap the CSS fallback overlay inside it. Neutralised while it is up.
12+const TRAPPING_STYLES = ["transform", "translate", "scale", "rotate", "filter", "backdrop-filter", "perspective", "contain", "will-change"] as const;
13+
14+const fullscreenElement = () => {
15+ const d = document as FsDocument;
16+ return d.fullscreenElement ?? d.webkitFullscreenElement ?? null;
17+};
18+
19+/**
20+ * Full-screen state for one element. Uses the Fullscreen API (with the webkit
21+ * prefix for Safari) where the browser offers it on arbitrary elements; iPhone
22+ * Safari does not, so there `active()` still flips and the host renders itself
23+ * as a fixed, inset-0 overlay instead (`native()` tells the two apart). Either
24+ * way the host styles itself off `active()`.
25+ *
26+ * Escape and the host's toggle exit. While active, an Escape keydown is
27+ * swallowed in the capture phase so it doesn't also reach a surrounding
28+ * Kobalte dialog (a SidePanel would otherwise close with the drawing in it).
29+ */
30+export function createFullscreen(target: () => HTMLElement | undefined) {
31+ const [active, setActive] = createSignal(false);
32+ const [native, setNative] = createSignal(false);
33+ let restore: (() => void) | undefined;
34+
35+ const pinOverlay = (el: HTMLElement) => {
36+ const saved: Array<[HTMLElement, string, string, string]> = [];
37+ for (let node = el.parentElement; node && node !== document.body; node = node.parentElement) {
38+ // A dialog's entry animation (fill-mode both) keeps a transform "in effect"
39+ // after it finishes, and Chromium still treats that as a containing block
40+ // even under an !important override. Its end state is the resting layout,
41+ // so cancelling it changes nothing visible.
42+ for (const anim of node.getAnimations?.() ?? []) anim.cancel();
43+ for (const prop of TRAPPING_STYLES) {
44+ saved.push([node, prop, node.style.getPropertyValue(prop), node.style.getPropertyPriority(prop)]);
45+ node.style.setProperty(prop, prop === "will-change" ? "auto" : "none", "important");
46+ }
47+ }
48+ const root = document.documentElement;
49+ const overflow = root.style.overflow;
50+ root.style.overflow = "hidden";
51+ return () => {
52+ for (const [node, prop, value, priority] of saved) node.style.setProperty(prop, value, priority);
53+ root.style.overflow = overflow;
54+ };
55+ };
56+
57+ const enter = async () => {
58+ const el = target() as FsElement | undefined;
59+ if (!el || active()) return;
60+ const request = el.requestFullscreen ?? el.webkitRequestFullscreen;
61+ if (request && (document.fullscreenEnabled ?? true)) {
62+ try {
63+ await request.call(el);
64+ setNative(true);
65+ setActive(true);
66+ return;
67+ } catch {
68+ // Refused (no gesture, iframe policy…) — fall through to the overlay.
69+ }
70+ }
71+ restore = pinOverlay(el);
72+ setNative(false);
73+ setActive(true);
74+ };
75+
76+ const exit = async () => {
77+ if (!active()) return;
78+ if (native()) {
79+ const d = document as FsDocument;
80+ if (fullscreenElement()) {
81+ const leave = d.exitFullscreen ?? d.webkitExitFullscreen;
82+ try {
83+ await leave?.call(d);
84+ } catch {
85+ // Already left; the change listener below settles the state.
86+ }
87+ }
88+ } else {
89+ restore?.();
90+ restore = undefined;
91+ }
92+ setNative(false);
93+ setActive(false);
94+ };
95+
96+ const toggle = () => void (active() ? exit() : enter());
97+
98+ // When the browser itself leaves native full screen on Escape, Chromium can
99+ // still hand that same keydown to the page *after* fullscreenchange — by then
100+ // active() is false and the Escape would close the dialog around the canvas.
101+ let leftNativeAt = -Infinity;
102+ const ESC_GRACE_MS = 500;
103+
104+ // The browser leaves native full screen on its own (Escape, a system gesture).
105+ const onChange = () => {
106+ if (native() && fullscreenElement() !== target()) {
107+ leftNativeAt = performance.now();
108+ setNative(false);
109+ setActive(false);
110+ }
111+ };
112+ const onKey = (e: KeyboardEvent) => {
113+ if (e.key !== "Escape") return;
114+ if (!active() && performance.now() - leftNativeAt > ESC_GRACE_MS) return;
115+ e.preventDefault();
116+ e.stopPropagation();
117+ void exit();
118+ };
119+ document.addEventListener("fullscreenchange", onChange);
120+ document.addEventListener("webkitfullscreenchange", onChange);
121+ window.addEventListener("keydown", onKey, true);
122+ onCleanup(() => {
123+ document.removeEventListener("fullscreenchange", onChange);
124+ document.removeEventListener("webkitfullscreenchange", onChange);
125+ window.removeEventListener("keydown", onKey, true);
126+ void exit();
127+ });
128+
129+ return { active, native, enter, exit, toggle };
130+}
131+
132+/** Classes a host adds to its root while `active()` — covers the viewport in both modes. */
133+export const FULLSCREEN_ROOT_CLASS =
134+ "fixed inset-0 z-[100] m-0 flex flex-col gap-2 space-y-0 bg-background p-2 pt-[max(0.5rem,env(safe-area-inset-top))] pr-[max(0.5rem,env(safe-area-inset-right))] pb-[max(0.5rem,env(safe-area-inset-bottom))] pl-[max(0.5rem,env(safe-area-inset-left))]";
src/lib/instance-options.tsmodified+25 -8
@@ -3,6 +3,7 @@ import { getCourseById } from "@/api/courses";
33 import { getMyInstances } from "@/api/instances";
44 import type { ClassGroup, Role } from "@/api/client";
55 import { hasMinRole } from "@/lib/roles";
6+import { compareClasses } from "@/lib/student-directory";
67
78 /** One pickable section: "<ders> — <şube>", plus the ids behind the label. */
89 export type InstanceOption = {
@@ -25,13 +26,13 @@ export async function loadInstanceOptions(role: Role | undefined): Promise<Insta
2526 const office = hasMinRole(role, "manager");
2627
2728 const rows: { id: string; course: string; class: string }[] = [];
28- const classNames = new Map<string, string>();
29+ const classesById = new Map<string, ClassGroup>();
2930
3031 if (office) {
3132 const classes = (await getClasses({ limit: 200 })).items;
3233 const perClass = await Promise.all(
3334 classes.map(async (klass) => {
34- classNames.set(klass.id, klass.name);
35+ classesById.set(klass.id, klass);
3536 try {
3637 return (await getClassInstances(klass.id, { limit: 200 })).items;
3738 } catch {
@@ -50,7 +51,7 @@ export async function loadInstanceOptions(role: Role | undefined): Promise<Insta
5051 () => ({ items: [] as ClassGroup[] }),
5152 ),
5253 ]);
53- for (const klass of classes.items) classNames.set(klass.id, klass.name);
54+ for (const klass of classes.items) classesById.set(klass.id, klass);
5455 for (const instance of mine.items) {
5556 rows.push({ id: instance.id, course: instance.course, class: instance.class });
5657 }
@@ -62,13 +63,29 @@ export async function loadInstanceOptions(role: Role | undefined): Promise<Insta
6263 try {
6364 titles.set(courseId, (await getCourseById(courseId)).title);
6465 } catch {
65- // Falls back to the id in the label below.
66+ // Shows as a dash in the label below, never the raw id.
6667 }
6768 }),
6869 );
6970
70- return rows.map((row) => ({
71- ...row,
72- label: `${titles.get(row.course) ?? row.course} — ${classNames.get(row.class) ?? "—"}`,
73- }));
71+ // Class by class (9-A, 9-B, 10-A…), then by ders inside a class, the order a
72+ // school reads its timetable in; a şube this caller cannot name goes last.
73+ const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" });
74+ const courseTitle = (row: { course: string }) => titles.get(row.course) ?? "—";
75+ return rows
76+ .sort((a, b) => {
77+ const classA = classesById.get(a.class);
78+ const classB = classesById.get(b.class);
79+ if (classA && !classB) return -1;
80+ if (!classA && classB) return 1;
81+ if (classA && classB) {
82+ const byClass = compareClasses(classA, classB);
83+ if (byClass !== 0) return byClass;
84+ }
85+ return collator.compare(courseTitle(a), courseTitle(b));
86+ })
87+ .map((row) => ({
88+ ...row,
89+ label: `${courseTitle(row)} — ${classesById.get(row.class)?.name ?? "—"}`,
90+ }));
7491 }
src/lib/person.tsmodified+6 -2
@@ -27,8 +27,12 @@ export function appointmentCounterpart(a: Appointment, viewerId: string | undefi
2727 return personLabel(a.requester.id === viewerId ? a.teacher ?? a.requester : a.requester);
2828 }
2929
30-export function personLabelWithId(person: PersonLike): string {
30+// Two students can share a name, so a picker adds the student number, else
31+// the username — never the raw id, which means nothing to a person reading it.
32+export function personPickerLabel(person: PersonLike): string {
3133 if (!person) return "—";
3234 if (typeof person === "string") return person;
33- return `${personLabel(person)} - ${person.id}`;
35+ const label = personLabel(person);
36+ const handle = person.student_number?.trim() || person.username;
37+ return handle && handle !== label ? `${label} (${handle})` : label;
3438 }
src/lib/student-info-access.test.tsadded+30 -0
@@ -0,0 +1,30 @@
1+import { describe, expect, it } from "vitest";
2+import { studentInfoSource } from "./student-info-access";
3+
4+const student = { id: "s1", role: "student" as const };
5+
6+describe("studentInfoSource", () => {
7+ it("lets the student see their own info", () => {
8+ expect(studentInfoSource({ id: "s1", role: "student" }, student)).toBe("self");
9+ });
10+
11+ it("hides it from another student", () => {
12+ expect(studentInfoSource({ id: "s2", role: "student" }, student)).toBeNull();
13+ });
14+
15+ it("opens it to staff, admin reading the full record", () => {
16+ expect(studentInfoSource({ id: "a", role: "admin" }, student)).toBe("admin");
17+ expect(studentInfoSource({ id: "m", role: "manager" }, student)).toBe("staff");
18+ expect(studentInfoSource({ id: "t", role: "teacher" }, student)).toBe("staff");
19+ });
20+
21+ it("opens it to a parent (the profile is already a 403 for unlinked ones)", () => {
22+ expect(studentInfoSource({ id: "p", role: "parent" }, student)).toBe("parent");
23+ });
24+
25+ it("never shows on a non-student profile or without a session", () => {
26+ expect(studentInfoSource({ id: "a", role: "admin" }, { id: "t", role: "teacher" })).toBeNull();
27+ expect(studentInfoSource({ id: "t", role: "teacher" }, { id: "t", role: "teacher" })).toBeNull();
28+ expect(studentInfoSource(null, student)).toBeNull();
29+ });
30+});
src/lib/student-info-access.tsadded+35 -0
@@ -0,0 +1,35 @@
1+import type { Role } from "@/api/client";
2+
3+/**
4+ * Where the "student info" panel on a student's profile reads from, per viewer:
5+ *
6+ * - `self` — the student themself: their own `GET /auth/me` row.
7+ * - `admin` — `GET /users/{id}` (admin only): the full personal record.
8+ * - `staff` — teacher / manager: `GET /users/{id}` is a 403 for them, so only
9+ * the student number that `GET /users/search` carries.
10+ * - `parent` — a parent linked to this student (the profile itself is a 403 for
11+ * any other parent): the student's ref from `GET /users/me/students`
12+ * plus the parent's own `GET /auth/me` row.
13+ *
14+ * `null` hides the button: another student, or a non-student profile.
15+ */
16+export type StudentInfoSource = "self" | "admin" | "staff" | "parent";
17+
18+export function studentInfoSource(
19+ viewer: { id: string; role: Role } | null | undefined,
20+ owner: { id: string; role: Role },
21+): StudentInfoSource | null {
22+ if (!viewer || owner.role !== "student") return null;
23+ if (viewer.id === owner.id) return "self";
24+ switch (viewer.role) {
25+ case "admin":
26+ return "admin";
27+ case "manager":
28+ case "teacher":
29+ return "staff";
30+ case "parent":
31+ return "parent";
32+ default:
33+ return null;
34+ }
35+}
src/pages/academic-years-page.tsxmodified+44 -4
@@ -17,9 +17,10 @@ import { Badge } from "@/components/ui/badge";
1717 import { Button } from "@/components/ui/button";
1818 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1919 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
20+import { DetailField } from "@/components/ui/detail-field";
2021 import { DatePicker } from "@/components/ui/date-picker";
2122 import { ErrorAlert } from "@/components/ui/error-alert";
22-import { IconArchive, IconEdit, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons";
23+import { IconArchive, IconEdit, IconEye, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons";
2324 import { Input } from "@/components/ui/input";
2425 import { Label } from "@/components/ui/label";
2526 import { PageHeader } from "@/components/layout/page-header";
@@ -72,6 +73,7 @@ function AcademicYearsContent() {
7273 const [promotions, setPromotions] = createSignal<GradePromotion[]>([]);
7374 const [editing, setEditing] = createSignal<AcademicYear | null>(null);
7475 const [deleteTarget, setDeleteTarget] = createSignal<AcademicYear | null>(null);
76+ const [detail, setDetail] = createSignal<AcademicYear | null>(null);
7577 const [archiveTarget, setArchiveTarget] = createSignal<AcademicYear | null>(null);
7678 const [rolloverTarget, setRolloverTarget] = createSignal<AcademicYear | null>(null);
7779 const [rolloverFrom, setRolloverFrom] = createSignal("");
@@ -148,10 +150,12 @@ function AcademicYearsContent() {
148150 header: t("settings.name"),
149151 size: 190,
150152 minSize: 170,
151- meta: { cellClass: "min-w-0" },
153+ // One line: a long name ends in "…" beside its badge rather than
154+ // wrapping; the full name is on hover and in the detail panel.
155+ meta: { cellClass: "max-w-0" },
152156 cell: (cell) => (
153- <span class="flex min-w-0 flex-wrap items-center justify-center gap-2 font-medium">
154- <span class="min-w-0 truncate">{cell.row.original.name}</span>
157+ <span class="flex min-w-0 items-center justify-center gap-2 font-medium">
158+ <span class="min-w-0 truncate" title={cell.row.original.name}>{cell.row.original.name}</span>
155159 <Show when={cell.row.original.archived_at != null}>
156160 <Badge variant="secondary" class="shrink-0 whitespace-nowrap rounded-full">{t("academicYears.archived")}</Badge>
157161 </Show>
@@ -201,6 +205,7 @@ function AcademicYearsContent() {
201205 <TableRowActions
202206 label={t("common.actions")}
203207 actions={[
208+ { label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => setDetail(year) },
204209 ...(archived
205210 ? []
206211 : [
@@ -265,10 +270,45 @@ function AcademicYearsContent() {
265270 enablePagination
266271 pageSize={YEAR_PAGE_SIZE}
267272 empty={t("academicYears.empty")}
273+ onRowClick={(year) => setDetail(year)}
268274 />
269275 </Suspense>
270276 </section>
271277
278+ <SidePanel open={detail() != null} onOpenChange={(open) => !open && setDetail(null)} title={detail()?.name ?? ""} description={t("academicYears.year")}>
279+ <Show when={detail()} keyed>
280+ {(year) => (
281+ <div class="space-y-5">
282+ <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-3">
283+ <p class="text-xs font-medium text-muted-foreground">{t("settings.name")}</p>
284+ <p class="mt-1 break-words text-sm font-medium">{year.name}</p>
285+ </div>
286+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
287+ <DetailField label={t("events.starts")} value={formatDate(year.starts_at, locale())} />
288+ <DetailField label={t("events.ends")} value={formatDate(year.ends_at, locale())} />
289+ <DetailField label={t("academicYears.classCount")} value={String(year.class_count)} />
290+ <DetailField label={t("academicYears.termCount")} value={String(year.term_count)} />
291+ <DetailField label={t("academicYears.archived")} value={year.archived_at != null ? formatDate(year.archived_at, locale()) : "—"} />
292+ </div>
293+ <Show when={year.archived_at == null}>
294+ <Button
295+ type="button"
296+ variant="outline"
297+ class="rounded-lg"
298+ onClick={() => {
299+ setDetail(null);
300+ startEdit(year);
301+ }}
302+ >
303+ <IconEdit class="h-4 w-4" />
304+ {t("common.edit")}
305+ </Button>
306+ </Show>
307+ </div>
308+ )}
309+ </Show>
310+ </SidePanel>
311+
272312 <SidePanel guardUnsaved
273313 open={panelOpen()}
274314 onOpenChange={(open) => {
src/pages/admin-user-detail-page.tsxmodified+10 -25
@@ -1,16 +1,14 @@
11 import { Link, useLocation, useParams } from "@tanstack/solid-router";
22 import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
33 import { createResource } from "@/lib/create-resource";
4-import { getLimits } from "@/api/limits";
5-import { getSettings } from "@/api/settings";
6-import { getUserById, getUserProfile, patchUserProfile, patchUserRole } from "@/api/users";
4+import { getUserById, getUserProfile, patchUserRole } from "@/api/users";
75 import { formatApiError, type Role } from "@/api/client";
86 import type { MessageKey } from "@/i18n/messages";
97 import { PageHeader } from "@/components/layout/page-header";
108 import { Breadcrumbs } from "@/components/layout/breadcrumbs";
119 import { RouteGuard } from "@/components/layout/route-guard";
1210 import { ParentStudentsPanel } from "@/components/users/parent-students-panel";
13-import { ProfileForm } from "@/components/users/profile-form";
11+import { AdminUserEditPanel } from "@/components/users/admin-user-edit-panel";
1412 import { Alert } from "@/components/ui/alert";
1513 import { Button } from "@/components/ui/button";
1614 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
@@ -18,7 +16,6 @@ import { DetailField } from "@/components/ui/detail-field";
1816 import { IconEdit, IconExternalLink, IconUsers } from "@/components/ui/icons";
1917 import { PageSpinner } from "@/components/ui/page-spinner";
2018 import { Select } from "@/components/ui/select";
21-import { SidePanel } from "@/components/ui/side-panel";
2219 import { ROLES, hasMinRole } from "@/lib/roles";
2320 import { useAuth } from "@/stores/auth-context";
2421 import { useT } from "@/stores/preferences-context";
@@ -43,8 +40,6 @@ function AdminUserDetailContent() {
4340 const [user, { refetch }] = createResource(id, (userId) => getUserById(userId));
4441 // Branş (and display name/bio) live only on the profile read, not on User.
4542 const [profile, { refetch: refetchProfile }] = createResource(id, (userId) => getUserProfile(userId).catch(() => null));
46- const [settings] = createResource(() => getSettings().catch(() => null));
47- const [limits] = createResource(() => getLimits().catch(() => null));
4843 const [editing, setEditing] = createSignal(false);
4944 const [studentsOpen, setStudentsOpen] = createSignal(false);
5045 const [pendingRole, setPendingRole] = createSignal<Role>("student");
@@ -138,26 +133,16 @@ function AdminUserDetailContent() {
138133 </div>
139134 </section>
140135
141- <SidePanel guardUnsaved
136+ <AdminUserEditPanel
137+ user={current()}
142138 open={editing()}
143139 onOpenChange={setEditing}
144- title={t("profile.edit")}
145- description={current().username}
146- >
147- <ProfileForm
148- user={current()}
149- profile={profile.latest ? { display_name: profile.latest.display_name, bio: profile.latest.bio, branch: profile.latest.branch } : undefined}
150- branches={settings.latest?.branches}
151- editStudentNumber
152- maxStudentNumberLen={limits.latest?.user.max_student_number_len}
153- onSave={(body) => patchUserProfile(current().id, body)}
154- onSaved={async () => {
155- setEditing(false);
156- void refetchProfile();
157- await refetch();
158- }}
159- />
160- </SidePanel>
140+ onSaved={async () => {
141+ setEditing(false);
142+ void refetchProfile();
143+ await refetch();
144+ }}
145+ />
161146
162147 <ParentStudentsPanel
163148 parent={{
src/pages/admin-users-page.tsxmodified+13 -0
@@ -9,6 +9,7 @@ import { RouteGuard } from "@/components/layout/route-guard";
99 import { UserTable } from "@/components/users/user-table";
1010 import { CreateUserPanel } from "@/components/users/create-user-panel";
1111 import { ParentStudentsPanel } from "@/components/users/parent-students-panel";
12+import { AdminUserEditPanel } from "@/components/users/admin-user-edit-panel";
1213 import { Alert } from "@/components/ui/alert";
1314 import { Button } from "@/components/ui/button";
1415 import { DataTableSkeleton } from "@/components/ui/data-table";
@@ -41,6 +42,7 @@ function AdminUsersContent() {
4142 const [selectedParent, setSelectedParent] = createSignal<User | null>(null);
4243 const [roleTab, setRoleTab] = createSignal<RoleTab>("all");
4344 const [creating, setCreating] = createSignal(false);
45+ const [editTarget, setEditTarget] = createSignal<User | null>(null);
4446
4547 const [loadAll, setLoadAll] = createSignal(false);
4648 const [list, { refetch }] = createResource(
@@ -108,10 +110,21 @@ function AdminUsersContent() {
108110 onRoleChange={onRoleChange}
109111 onUserClick={(user) => navigate({ to: "/admin/users/$id", params: { id: user.id } })}
110112 onParentClick={setSelectedParent}
113+ onEditClick={setEditTarget}
111114 />
112115 </Show>
113116 </Suspense>
114117 </section>
118+ <AdminUserEditPanel
119+ user={editTarget()}
120+ open={editTarget() !== null}
121+ onOpenChange={(open) => { if (!open) setEditTarget(null); }}
122+ onSaved={async () => {
123+ // ProfileForm shows its own "saved" toast.
124+ setEditTarget(null);
125+ try { await refetch(); } catch { /* stale rows until the next load */ }
126+ }}
127+ />
115128 <CreateUserPanel
116129 open={creating()}
117130 onOpenChange={setCreating}
src/pages/appointments-page.tsxmodified+1 -2
@@ -610,8 +610,7 @@ function AppointmentsContent() {
610610 <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
611611 <DetailField label={t("appointments.teacher")} value={personLabel(slot.teacher)} />
612612 <DetailField label={t("appointments.time")} value={timeWindow(slot.starts_at, slot.ends_at)} />
613- <DetailField label={t("appointments.series")} value={slot.series || "—"} mono />
614- <DetailField label={t("admin.id")} value={slot.id} mono />
613+ <DetailField label={t("appointments.series")} value={slot.series ? t("appointments.series.weekly") : t("appointments.series.once")} />
615614 </div>
616615 <div class="space-y-1">
617616 <p class="text-xs font-medium text-muted-foreground">{t("appointments.note")}</p>
src/pages/bank-question-detail-page.tsxmodified+9 -3
@@ -8,6 +8,7 @@ import {
88 getBankQuestionById,
99 } from "@/api/bank-questions";
1010 import { getCourses } from "@/api/courses";
11+import { getExamById } from "@/api/exams";
1112 import { formatApiError } from "@/api/client";
1213 import { BankQuestionForm } from "@/components/exams/bank-question-form";
1314 import { PageHeader } from "@/components/layout/page-header";
@@ -48,6 +49,12 @@ function BankQuestionDetailContent() {
4849 });
4950 const [question, { refetch }] = createResource(id, (questionId) => getBankQuestionById(questionId));
5051 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);
52+ // The exam a question was lifted from is named by its title; an exam the
53+ // viewer cannot read (or one since deleted) shows as a dash, not its id.
54+ const [sourceExam] = createResource(
55+ () => question()?.source_exam || null,
56+ (examId) => getExamById(examId).then((exam) => exam.title).catch(() => null),
57+ );
5158 const manageableCourses = createMemo(() =>
5259 (courses() ?? []).filter((course) => {
5360 const current = auth.user();
@@ -98,7 +105,7 @@ function BankQuestionDetailContent() {
98105 <Breadcrumbs items={[{ label: t("bank.title"), to: "/question-bank" }, { label: current().text }]} />
99106 <PageHeader
100107 title={current().text}
101- description={current().subject_name || t("bank.subtitle")}
108+ description={current().subject_name || undefined}
102109 actions={
103110 <>
104111 <Show when={canEdit()}>
@@ -129,8 +136,7 @@ function BankQuestionDetailContent() {
129136 <DetailField label={t("bank.created")} value={formatDate(current().created_at, locale())} />
130137 <DetailField label={t("subjects.subject")} value={current().subject_name || "—"} />
131138 <DetailField label={t("bank.whoCanSee")} value={current().visibility === "school" ? t("bank.sharedWithSchool") : t("bank.onlyMe")} />
132- <DetailField label={t("exams.title")} value={current().source_exam || "—"} mono />
133- <DetailField label={t("admin.id")} value={current().id} mono />
139+ <DetailField label={t("exams.title")} value={(current().source_exam && sourceExam()) || "—"} />
134140 </div>
135141
136142 <Show when={current().image}>
src/pages/builder-school-detail-page.tsxmodified+12 -55
@@ -7,15 +7,15 @@ import {
77 deleteSchoolModule,
88 getSchool,
99 getSchoolModules,
10- patchSchool,
1110 patchSchoolModules,
1211 postSchoolModule,
1312 } from "@/api/schools";
14-import { formatApiError, type SchoolStatus } from "@/api/client";
13+import { formatApiError } from "@/api/client";
1514 import { PageHeader } from "@/components/layout/page-header";
1615 import { BuilderGuard } from "@/components/builder/builder-guard";
1716 import { BuilderHeader } from "@/components/builder/builder-header";
1817 import { SchoolAdminAccessPanel, type AdminAccessMode } from "@/components/builder/school-admin-access-panel";
18+import { SchoolEditPanel } from "@/components/builder/school-edit-panel";
1919 import { SchoolStatusBadge } from "@/components/builder/school-status-badge";
2020 import { ModuleCatalogGrid } from "@/components/modules/module-catalog-grid";
2121 import { formatModuleError } from "@/lib/module-labels";
@@ -24,11 +24,7 @@ import { Button } from "@/components/ui/button";
2424 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
2525 import { ErrorAlert } from "@/components/ui/error-alert";
2626 import { IconEdit, IconExternalLink, IconLock, IconTrash } from "@/components/ui/icons";
27-import { Input } from "@/components/ui/input";
28-import { Label } from "@/components/ui/label";
2927 import { PageSpinner } from "@/components/ui/page-spinner";
30-import { Select } from "@/components/ui/select";
31-import { SidePanel } from "@/components/ui/side-panel";
3228 import { createFlash } from "@/lib/flash";
3329 import { formatDateTime } from "@/lib/format";
3430 import { useAuth } from "@/stores/auth-context";
@@ -69,9 +65,6 @@ function BuilderSchoolDetailContent() {
6965 const [modulesError, setModulesError] = createSignal("");
7066
7167 const [editOpen, setEditOpen] = createSignal(false);
72- const [name, setName] = createSignal("");
73- const [status, setStatus] = createSignal<SchoolStatus>("active");
74- const [editError, setEditError] = createSignal("");
7568 const [accessMode, setAccessMode] = createSignal<AdminAccessMode | null>(null);
7669 const [deleteOpen, setDeleteOpen] = createSignal(false);
7770 const [error, setError] = createSignal("");
@@ -93,25 +86,7 @@ function BuilderSchoolDetailContent() {
9386 };
9487
9588 const openEdit = () => {
96- const current = school();
97- if (!current) return;
98- setName(current.name);
99- setStatus(current.status);
100- setEditError("");
101- setEditOpen(true);
102- };
103-
104- const saveEdit = async (event: SubmitEvent) => {
105- event.preventDefault();
106- setEditError("");
107- try {
108- await patchSchool(id(), { name: name().trim(), status: status() });
109- setEditOpen(false);
110- await refetchSchool();
111- setFlash(t("common.saved"));
112- } catch (err) {
113- setEditError(formatApiError(err));
114- }
89+ if (school()) setEditOpen(true);
11590 };
11691
11792 return (
@@ -194,33 +169,15 @@ function BuilderSchoolDetailContent() {
194169 </Show>
195170 </Suspense>
196171
197- <SidePanel guardUnsaved open={editOpen()} onOpenChange={setEditOpen} title={t("builder.editSchool")} description={t("builder.editSchoolHint")}>
198- <form class="space-y-4" onSubmit={saveEdit}>
199- <Show when={editError()}>
200- <Alert variant="destructive">{editError()}</Alert>
201- </Show>
202- <div class="space-y-1.5">
203- <Label for="school-edit-name">{t("builder.schoolName")}</Label>
204- <Input id="school-edit-name" class="rounded-lg" required maxlength={120} value={name()} onInput={(e) => setName(e.currentTarget.value)} />
205- </div>
206- <div class="space-y-1.5">
207- <Label for="school-edit-status">{t("builder.status")}</Label>
208- <Select id="school-edit-status" value={status()} onChange={(e) => setStatus(e.currentTarget.value as SchoolStatus)}>
209- <option value="active">{t("builder.statusActive")}</option>
210- <option value="suspended">{t("builder.statusSuspended")}</option>
211- </Select>
212- <p class="text-xs text-text-subtle">{t("builder.suspendHint")}</p>
213- </div>
214- <div class="flex flex-wrap items-center gap-2">
215- <Button type="button" variant="outline" class="h-10 rounded-lg" onClick={() => setEditOpen(false)}>
216- {t("common.cancel")}
217- </Button>
218- <Button type="submit" class="h-10 rounded-lg">
219- {t("common.save")}
220- </Button>
221- </div>
222- </form>
223- </SidePanel>
172+ <SchoolEditPanel
173+ school={school() ?? null}
174+ open={editOpen()}
175+ onOpenChange={setEditOpen}
176+ onSaved={async () => {
177+ await refetchSchool();
178+ setFlash(t("common.saved"));
179+ }}
180+ />
224181
225182 <SchoolAdminAccessPanel
226183 id={id()}
src/pages/builder-schools-page.tsxmodified+46 -1
@@ -7,16 +7,19 @@ import { formatApiError, type School } from "@/api/client";
77 import { BuilderGuard } from "@/components/builder/builder-guard";
88 import { BuilderHeader } from "@/components/builder/builder-header";
99 import { CreateSchoolPanel } from "@/components/builder/create-school-panel";
10+import { SchoolAdminAccessPanel, type AdminAccessMode } from "@/components/builder/school-admin-access-panel";
11+import { SchoolEditPanel } from "@/components/builder/school-edit-panel";
1012 import { SchoolStatusBadge } from "@/components/builder/school-status-badge";
1113 import { Alert } from "@/components/ui/alert";
1214 import { Button } from "@/components/ui/button";
1315 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1416 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1517 import { ErrorAlert } from "@/components/ui/error-alert";
16-import { IconEye, IconLock, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons";
18+import { IconEdit, IconExternalLink, IconEye, IconLock, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons";
1719 import { TableRowActions } from "@/components/ui/table-row-actions";
1820 import { createFlash } from "@/lib/flash";
1921 import { formatDateTime } from "@/lib/format";
22+import { useAuth } from "@/stores/auth-context";
2023 import { BuilderProvider } from "@/stores/builder-context";
2124 import { usePreferences, useT } from "@/stores/preferences-context";
2225
@@ -39,6 +42,10 @@ function BuilderSchoolsContent() {
3942 const [list, { refetch }] = createResource(async () => (await getSchools()).items);
4043 const [createOpen, setCreateOpen] = createSignal(false);
4144 const [deleteTarget, setDeleteTarget] = createSignal<School | null>(null);
45+ const [editTarget, setEditTarget] = createSignal<School | null>(null);
46+ // The detail header's admin access (reset password / enter the school).
47+ const [access, setAccess] = createSignal<{ id: string; mode: AdminAccessMode } | null>(null);
48+ const auth = useAuth();
4249 const [error, setError] = createSignal("");
4350 const [flash, setFlash] = createFlash();
4451
@@ -93,6 +100,14 @@ function BuilderSchoolsContent() {
93100 label={t("common.actions")}
94101 actions={[
95102 { label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => open(cell.row.original) },
103+ { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => setEditTarget(cell.row.original) },
104+ { label: t("builder.resetAdminPassword"), icon: <IconLock class="h-4 w-4" />, onSelect: () => setAccess({ id: cell.row.original.id, mode: "password" }) },
105+ {
106+ label: t("builder.enterSchool"),
107+ icon: <IconExternalLink class="h-4 w-4" />,
108+ disabled: cell.row.original.status === "suspended",
109+ onSelect: () => setAccess({ id: cell.row.original.id, mode: "enter" }),
110+ },
96111 cell.row.original.status === "active"
97112 ? { label: t("builder.suspend"), icon: <IconLock class="h-4 w-4" />, onSelect: () => void setStatus(cell.row.original, "suspended") }
98113 : { label: t("builder.activate"), icon: <IconRotateCcw class="h-4 w-4" />, onSelect: () => void setStatus(cell.row.original, "active") },
@@ -153,6 +168,36 @@ function BuilderSchoolsContent() {
153168 }}
154169 />
155170
171+ <SchoolEditPanel
172+ school={editTarget()}
173+ open={editTarget() !== null}
174+ onOpenChange={(value) => { if (!value) setEditTarget(null); }}
175+ onSaved={async () => {
176+ try { await refetch(); } catch { /* stale rows until the next load */ }
177+ setFlash(t("common.saved"));
178+ }}
179+ />
180+
181+ <Show when={access()} keyed>
182+ {(target) => (
183+ <SchoolAdminAccessPanel
184+ id={target.id}
185+ mode={target.mode}
186+ onClose={() => setAccess(null)}
187+ onPasswordReset={() => {
188+ setAccess(null);
189+ setFlash(t("builder.passwordResetDone"));
190+ }}
191+ onEntered={async () => {
192+ setAccess(null);
193+ // The builder cookie is gone; this browser is now that admin.
194+ await auth.refresh();
195+ void navigate({ to: "/" });
196+ }}
197+ />
198+ )}
199+ </Show>
200+
156201 <ConfirmDialog
157202 open={deleteTarget() != null}
158203 onOpenChange={(value) => !value && setDeleteTarget(null)}
src/pages/class-detail-page.tsxmodified+216 -122
@@ -1,11 +1,11 @@
1-import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
1+import { For, Show, createEffect, createMemo, createSignal } from "solid-js";
22 import { createResource } from "@/lib/create-resource";
33 import { useLocation, useNavigate, useParams } from "@tanstack/solid-router";
44 import { Breadcrumbs } from "@/components/layout/breadcrumbs";
5+import { PageHeader } from "@/components/layout/page-header";
56 import type { ColumnDef } from "@tanstack/solid-table";
67 import {
78 getClassById,
8- patchClassById,
99 deleteClassById,
1010 getClassMembers,
1111 postClassMember,
@@ -15,19 +15,18 @@ import {
1515 deleteClassInstance,
1616 postClassBlueprintApply,
1717 } from "@/api/classes";
18-import { getCourses } from "@/api/courses";
18+import { getCourseById, getCourses } from "@/api/courses";
1919 import { getAcademicYears } from "@/api/academic-years";
2020 import { getLimits } from "@/api/limits";
21-import { ApiError, formatApiError, type BlueprintSkip, type ClassCourse, type ClassGroup, type ClassMember } from "@/api/client";
21+import { ApiError, formatApiError, type BlueprintSkip, type ClassCourse, type ClassGroup, type ClassMember, type PersonRef } from "@/api/client";
2222 import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report";
23+import { ClassEditPanel } from "@/components/classes/class-edit-panel";
2324 import { RouteGuard } from "@/components/layout/route-guard";
2425 import { Alert } from "@/components/ui/alert";
25-import { Badge } from "@/components/ui/badge";
2626 import { Button } from "@/components/ui/button";
2727 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
2828 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
29-import { IconExternalLink, IconPlus, IconTrash } from "@/components/ui/icons";
30-import { Input } from "@/components/ui/input";
29+import { IconBook, IconEdit, IconExternalLink, IconListChecks, IconPlus, IconTrash, IconUsers } from "@/components/ui/icons";
3130 import { Label } from "@/components/ui/label";
3231 import { PageSpinner } from "@/components/ui/page-spinner";
3332 import { Select } from "@/components/ui/select";
@@ -35,9 +34,12 @@ import { SidePanel } from "@/components/ui/side-panel";
3534 import { TableRowActions } from "@/components/ui/table-row-actions";
3635 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
3736 import { UserSearchSelect } from "@/components/users/user-search-select";
37+import { COMPACT_SCREEN_QUERY } from "@/lib/create-page-size";
38+import { createMediaQuery } from "@/lib/create-media-query";
3839 import { createFlash } from "@/lib/flash";
39-import { personLabel } from "@/lib/person";
40+import { cn } from "@/lib/cn";
4041 import { hasMinRole } from "@/lib/roles";
42+import { matchesSearch } from "@/lib/search-text";
4143 import { createUrlString } from "@/lib/url-state";
4244 import { useAuth } from "@/stores/auth-context";
4345 import { useT } from "@/stores/preferences-context";
@@ -48,6 +50,20 @@ export default function ClassDetailPage() {
4850 return <RouteGuard minRole="teacher"><ClassDetailContent /></RouteGuard>;
4951 }
5052
53+// A person's name for this page. personLabel falls back to the account id, and
54+// a raw uuid means nothing to the reader — an unnamed ref reads "—" instead.
55+const personName = (person: PersonRef | null | undefined) => person?.display_name || person?.username || "—";
56+
57+// One info tile of the header card, the same surface homework and event
58+// detail pages use for their facts.
59+const TILE = "min-w-0 rounded-xl border border-border-hairline bg-surface-tint px-4 py-4";
60+const TILE_LABEL = "text-xs font-medium uppercase tracking-[0.08em] text-text-subtle";
61+const TILE_VALUE = "mt-1 break-words font-medium text-text-default";
62+
63+// Header and section buttons share the row-actions trigger's box (h-8,
64+// rounded-lg) so a button and the ⋮ menu beside it line up.
65+const ACTION_BUTTON = "h-8 min-w-[7.5rem] rounded-lg! px-3 text-[13px]";
66+
5167 function ClassDetailContent() {
5268 const auth = useAuth();
5369 const t = useT();
@@ -63,10 +79,6 @@ function ClassDetailContent() {
6379 const [pending, setPending] = createSignal(false);
6480
6581 const [editing, setEditing] = createSignal(false);
66- const [name, setName] = createSignal("");
67- const [grade, setGrade] = createSignal("");
68- const [yearId, setYearId] = createSignal("");
69- const [teacherId, setTeacherId] = createSignal("");
7082 const [deleteOpen, setDeleteOpen] = createSignal(false);
7183 const [showAddMember, setShowAddMember] = createSignal(false);
7284 const [addUserId, setAddUserId] = createSignal("");
@@ -80,9 +92,24 @@ function ClassDetailContent() {
8092 const [cls, { refetch: refetchClass }] = createResource(id, (classId) => getClassById(classId));
8193 const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items);
8294 const [limits] = createResource(() => canManage() ? getLimits() : null);
83- const [courses] = createResource(() => canManage() ? getCourses().then((page) => page.items) : null);
84- const [members, { refetch: refetchMembers }] = createResource(id, async (classId) => (await getClassMembers(classId, { limit: 200 })).items);
85- const [classCourses, { refetch: refetchCourses }] = createResource(id, async (classId) => (await getClassInstances(classId, { limit: 50 })).items);
95+ // Every viewer needs the catalog: the courses table names each attached ders
96+ // by title, and without it a teacher saw the raw course id.
97+ const [courses] = createResource(() => getCourses({ limit: 100 }).then((page) => page.items));
98+ const [membersPage, { refetch: refetchMembers }] = createResource(id, (classId) => getClassMembers(classId, { limit: 200 }));
99+ const [coursesPage, { refetch: refetchCourses }] = createResource(id, (classId) => getClassInstances(classId, { limit: 50 }));
100+ const members = () => membersPage.latest?.items;
101+ const classCourses = () => coursesPage.latest?.items;
102+ // A course attached here but past the first catalog page: read it by id.
103+ const missingCourseIds = createMemo(() => {
104+ const list = courses.latest;
105+ if (!list) return null;
106+ const missing = (classCourses() ?? []).map((row) => row.course).filter((cid) => !list.some((course) => course.id === cid));
107+ return missing.length > 0 ? missing.join(",") : null;
108+ });
109+ const [extraCourses] = createResource(missingCourseIds, async (ids) => {
110+ const found = await Promise.all(ids.split(",").map((cid) => getCourseById(cid).catch(() => null)));
111+ return found.filter((course) => course !== null);
112+ });
86113
87114 // The last class the page actually loaded. A refetch that fails leaves the
88115 // resource in an error state, and reading it there throws; holding the last
@@ -93,10 +120,13 @@ function ClassDetailContent() {
93120 if (cls.state === "ready") setLoadedClass(cls());
94121 });
95122
96- const yearName = (yid: string | null) => years.latest?.find((year) => year.id === yid)?.name ?? (yid || t("academicYears.unassigned"));
97- const courseTitle = (courseId: string) => courses.latest?.find((course) => course.id === courseId)?.title ?? courseId;
98- const memberUserIds = () => (members.latest ?? []).map((row) => row.user.id);
99- const attachedCourseIds = () => (classCourses.latest ?? []).map((row) => row.course);
123+ const yearName = (yid: string | null) => yid ? years.latest?.find((year) => year.id === yid)?.name ?? "—" : t("academicYears.unassigned");
124+ const courseTitle = (courseId: string) =>
125+ courses.latest?.find((course) => course.id === courseId)?.title
126+ ?? extraCourses.latest?.find((course) => course.id === courseId)?.title
127+ ?? "—";
128+ const memberUserIds = () => (members() ?? []).map((row) => row.user.id);
129+ const attachedCourseIds = () => (classCourses() ?? []).map((row) => row.course);
100130
101131 // Refreshing the tables after a successful write is not part of the write:
102132 // a failed refetch used to be reported as if the save itself had failed, so
@@ -146,40 +176,53 @@ function ClassDetailContent() {
146176 }
147177 };
148178
149- const memberColumns = createMemo<ColumnDef<ClassMember>[]>(() => [
150- {
179+ // The table leads with the student number. On a phone DataTable renders
180+ // rows as cards titled by the first column, so there the name leads and the
181+ // number becomes a label/value line under it.
182+ const compactScreen = createMediaQuery(COMPACT_SCREEN_QUERY);
183+ const memberColumns = createMemo<ColumnDef<ClassMember>[]>(() => {
184+ const numberColumn: ColumnDef<ClassMember> = {
185+ id: "studentNumber",
186+ accessorFn: (row) => row.user.student_number?.trim() || "—",
187+ header: t("roster.studentNumber"),
188+ meta: { cellClass: "whitespace-nowrap tabular-nums text-muted-foreground" },
189+ };
190+ const studentColumn: ColumnDef<ClassMember> = {
151191 id: "student",
152- accessorFn: (row) => personLabel(row.user),
192+ accessorFn: (row) => personName(row.user),
153193 header: t("classGroups.student"),
154194 meta: { cellClass: "font-medium" },
155- },
156- {
157- id: "addedBy",
158- accessorFn: (row) => personLabel(row.added_by),
159- header: t("classGroups.addedBy"),
160- meta: { cellClass: "text-muted-foreground" },
161- },
162- {
163- id: "actions",
164- header: t("common.actions"),
165- meta: { headerClass: "w-14 text-center", cellClass: "px-1 text-center" },
166- cell: (cell) => (
167- <Show when={canManage()}>
168- <TableRowActions
169- label={t("common.actions")}
170- actions={[
171- {
172- label: t("profile.viewProfile"),
173- icon: <IconExternalLink class="h-4 w-4" />,
174- onSelect: () => void navigate({ to: "/profile/$userId", params: { userId: cell.row.original.user.id } }),
175- },
176- { label: t("classGroups.removeStudent"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setRemoveMember(cell.row.original) },
177- ]}
178- />
179- </Show>
180- ),
181- },
182- ]);
195+ };
196+ return [
197+ ...(compactScreen() ? [studentColumn, numberColumn] : [numberColumn, studentColumn]),
198+ {
199+ id: "addedBy",
200+ accessorFn: (row) => personName(row.added_by),
201+ header: t("classGroups.addedBy"),
202+ meta: { cellClass: "text-muted-foreground" },
203+ },
204+ {
205+ id: "actions",
206+ header: t("common.actions"),
207+ meta: { headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap", cellClass: "w-[110px] min-w-[110px] max-w-[110px] px-1 text-center" },
208+ cell: (cell) => (
209+ <Show when={canManage()}>
210+ <TableRowActions
211+ label={t("common.actions")}
212+ actions={[
213+ {
214+ label: t("profile.viewProfile"),
215+ icon: <IconExternalLink class="h-4 w-4" />,
216+ onSelect: () => void navigate({ to: "/profile/$userId", params: { userId: cell.row.original.user.id } }),
217+ },
218+ { label: t("classGroups.removeStudent"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setRemoveMember(cell.row.original) },
219+ ]}
220+ />
221+ </Show>
222+ ),
223+ },
224+ ];
225+ });
183226
184227 const courseColumns = createMemo<ColumnDef<ClassCourse>[]>(() => [
185228 {
@@ -202,14 +245,14 @@ function ClassDetailContent() {
202245 },
203246 {
204247 id: "attachedBy",
205- accessorFn: (row) => personLabel(row.attached_by),
248+ accessorFn: (row) => personName(row.attached_by),
206249 header: t("classGroups.attachedBy"),
207250 meta: { cellClass: "text-muted-foreground" },
208251 },
209252 {
210253 id: "actions",
211254 header: t("common.actions"),
212- meta: { headerClass: "w-14 text-center", cellClass: "px-1 text-center" },
255+ meta: { headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap", cellClass: "w-[110px] min-w-[110px] max-w-[110px] px-1 text-center" },
213256 cell: (cell) => (
214257 <Show when={canManage()}>
215258 <TableRowActions
@@ -239,45 +282,76 @@ function ClassDetailContent() {
239282 }
240283 >
241284 {(c) => (
242- <div class="space-y-5">
243- <Breadcrumbs items={[{ label: t("classGroups.title"), to: "/management/classes" }, { label: c().name }]} />
244-
245- <header class="flex flex-wrap items-end justify-between gap-4 border-b border-border pb-5">
246- <div class="space-y-1">
247- <h1 class="text-2xl font-semibold tracking-tight">{c().name}</h1>
248- <div class="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
249- <Show when={c().grade}><Badge variant="secondary" class="rounded-full">{c().grade}</Badge></Show>
250- <span>{yearName(c().year)}</span>
251- <span>·</span>
252- <span>{t("classGroups.homeroomTeacher")}: {c().teacher ? personLabel(c().teacher!) : t("classGroups.noTeacher")}</span>
285+ <div class="mx-auto w-full max-w-[1440px] space-y-4">
286+ <section class="rounded-xl border border-border-line bg-surface-base px-4 py-3 shadow-xs sm:px-5">
287+ <Breadcrumbs items={[{ label: t("classGroups.title"), to: "/management/classes" }, { label: c().name }]} />
288+ <PageHeader
289+ title={c().name}
290+ actions={
291+ canManage() ? (
292+ <div class="flex w-full items-center gap-2 sm:w-auto">
293+ {/* A grid gives both buttons the width of the wider one. */}
294+ <div class="grid flex-1 grid-cols-2 gap-2 sm:flex-none">
295+ <Button
296+ type="button"
297+ size="sm"
298+ variant="outline"
299+ class={cn(ACTION_BUTTON, "w-full")}
300+ disabled={pending() || !c().grade}
301+ title={c().grade ? t("classBlueprints.applyHint") : t("classBlueprints.applyNoGrade")}
302+ onClick={() => void applyBlueprint(c().grade ?? "")}
303+ >
304+ <IconListChecks class="h-4 w-4" />
305+ {t("classBlueprints.apply")}
306+ </Button>
307+ <Button
308+ type="button"
309+ size="sm"
310+ variant="outline"
311+ class={cn(ACTION_BUTTON, "w-full")}
312+ onClick={() => setEditing(true)}
313+ >
314+ <IconEdit class="h-4 w-4" />
315+ {t("common.edit")}
316+ </Button>
317+ </div>
318+ <TableRowActions
319+ label={t("common.actions")}
320+ actions={[{
321+ label: t("classGroups.deleteClass"),
322+ icon: <IconTrash class="h-4 w-4" />,
323+ destructive: true,
324+ disabled: pending(),
325+ onSelect: () => setDeleteOpen(true),
326+ }]}
327+ />
328+ </div>
329+ ) : undefined
330+ }
331+ />
332+ <div class="grid gap-3 border-t border-border-hairline pt-3 pb-1 text-sm grid-cols-2 lg:grid-cols-5">
333+ <div class={TILE}>
334+ <p class={TILE_LABEL}>{t("classGroups.grade")}</p>
335+ <p class={TILE_VALUE}>{c().grade || "—"}</p>
253336 </div>
254- </div>
255- <Show when={canManage()}>
256- <div class="flex flex-wrap gap-2">
257- <Button
258- size="sm"
259- variant="outline"
260- class="rounded-lg"
261- disabled={pending() || !c().grade}
262- title={c().grade ? t("classBlueprints.applyHint") : t("classBlueprints.applyNoGrade")}
263- onClick={() => void applyBlueprint(c().grade ?? "")}
264- >
265- {t("classBlueprints.apply")}
266- </Button>
267- <Button size="sm" variant="outline" class="rounded-lg" onClick={() => { setName(c().name); setGrade(c().grade ?? ""); setYearId(c().year ?? ""); setTeacherId(c().teacher?.id ?? ""); setEditing(true); }}>{t("common.edit")}</Button>
268- <TableRowActions
269- label={t("common.actions")}
270- actions={[{
271- label: t("classGroups.deleteClass"),
272- icon: <IconTrash class="h-4 w-4" />,
273- destructive: true,
274- disabled: pending(),
275- onSelect: () => setDeleteOpen(true),
276- }]}
277- />
337+ <div class={TILE}>
338+ <p class={TILE_LABEL}>{t("academicYears.year")}</p>
339+ <p class={TILE_VALUE}>{yearName(c().year)}</p>
340+ </div>
341+ <div class={cn(TILE, "col-span-2 lg:col-span-1")}>
342+ <p class={TILE_LABEL}>{t("classGroups.homeroomTeacher")}</p>
343+ <p class={TILE_VALUE}>{c().teacher ? personName(c().teacher) : t("classGroups.noTeacher")}</p>
344+ </div>
345+ <div class={TILE}>
346+ <p class={TILE_LABEL}>{t("classGroups.membersTab")}</p>
347+ <p class={cn(TILE_VALUE, "tabular-nums")}>{membersPage.latest?.total ?? "—"}</p>
278348 </div>
279- </Show>
280- </header>
349+ <div class={TILE}>
350+ <p class={TILE_LABEL}>{t("classGroups.coursesTab")}</p>
351+ <p class={cn(TILE_VALUE, "tabular-nums")}>{coursesPage.latest?.total ?? "—"}</p>
352+ </div>
353+ </div>
354+ </section>
281355
282356 <Show when={flash()}><Alert variant="success">{flash()}</Alert></Show>
283357 <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
@@ -297,46 +371,66 @@ function ClassDetailContent() {
297371 />
298372
299373 <Tabs value={tab()} onChange={setTab} class="space-y-3">
300- <TabsList>
301- <TabsTrigger value="members">{t("classGroups.membersTab")}</TabsTrigger>
302- <TabsTrigger value="courses">{t("classGroups.coursesTab")}</TabsTrigger>
374+ <TabsList class="grid w-full grid-cols-2 gap-0 rounded-lg border-border-line bg-surface-base p-0 shadow-none sm:w-auto sm:min-w-[22rem]">
375+ <TabsTrigger value="members" class="min-w-0 rounded-none border-r border-border-line last:border-r-0 data-selected:border-b-2 data-selected:border-b-primary data-selected:bg-surface-base data-selected:shadow-none"><IconUsers class="h-4 w-4" />{t("classGroups.membersTab")}</TabsTrigger>
376+ <TabsTrigger value="courses" class="min-w-0 rounded-none border-r border-border-line last:border-r-0 data-selected:border-b-2 data-selected:border-b-primary data-selected:bg-surface-base data-selected:shadow-none"><IconBook class="h-4 w-4" />{t("classGroups.coursesTab")}</TabsTrigger>
303377 </TabsList>
304378
305- <TabsContent value="members" class="space-y-3">
306- <Show when={canManage()}>
307- <div class="flex justify-end">
308- <Button size="sm" variant="outline" class="rounded-lg" onClick={() => setShowAddMember(true)}><IconPlus class="h-4 w-4" />{t("classGroups.addStudent")}</Button>
309- </div>
310- </Show>
311- <Suspense fallback={<DataTableSkeleton />}>
312- <DataTable columns={memberColumns()} data={members.latest ?? []} filterColumn="student" enablePagination pageSize={10} empty={t("classGroups.noMembers")} />
313- </Suspense>
379+ <TabsContent value="members">
380+ <section>
381+ <Show when={membersPage.latest} fallback={<Show when={membersPage.error} fallback={<DataTableSkeleton />}><Alert variant="destructive">{formatApiError(membersPage.error)}</Alert></Show>}>
382+ <DataTable
383+ title={t("classGroups.membersTab")}
384+ actions={canManage() ? (
385+ <Button type="button" size="sm" variant="outline" class={ACTION_BUTTON} onClick={() => setShowAddMember(true)}>
386+ <IconPlus class="h-4 w-4" />{t("classGroups.addStudent")}
387+ </Button>
388+ ) : undefined}
389+ columns={memberColumns()}
390+ data={members() ?? []}
391+ searchPredicate={(row, query) => matchesSearch(query, row.user.display_name, row.user.username, row.user.student_number)}
392+ filterPlaceholder={t("roster.searchStudents")}
393+ filterHint={t("search.hint.classMembers")}
394+ enablePagination
395+ pageSize={10}
396+ empty={t("classGroups.noMembers")}
397+ />
398+ </Show>
399+ </section>
314400 </TabsContent>
315401
316- <TabsContent value="courses" class="space-y-3">
317- <Show when={canManage()}>
318- <div class="flex justify-end">
319- <Button size="sm" variant="outline" class="rounded-lg" onClick={() => setShowAttachCourse(true)}><IconPlus class="h-4 w-4" />{t("classGroups.attachCourse")}</Button>
320- </div>
321- </Show>
322- <Suspense fallback={<DataTableSkeleton />}>
323- <DataTable columns={courseColumns()} data={classCourses.latest ?? []} filterColumn="course" enablePagination pageSize={10} empty={t("classGroups.noCourses")} />
324- </Suspense>
402+ <TabsContent value="courses">
403+ <section>
404+ <Show when={coursesPage.latest} fallback={<Show when={coursesPage.error} fallback={<DataTableSkeleton />}><Alert variant="destructive">{formatApiError(coursesPage.error)}</Alert></Show>}>
405+ <DataTable
406+ title={t("classGroups.coursesTab")}
407+ actions={canManage() ? (
408+ <Button type="button" size="sm" variant="outline" class={ACTION_BUTTON} onClick={() => setShowAttachCourse(true)}>
409+ <IconPlus class="h-4 w-4" />{t("classGroups.attachCourse")}
410+ </Button>
411+ ) : undefined}
412+ columns={courseColumns()}
413+ data={classCourses() ?? []}
414+ filterColumn="course"
415+ enablePagination
416+ pageSize={10}
417+ empty={t("classGroups.noCourses")}
418+ />
419+ </Show>
420+ </section>
325421 </TabsContent>
326422 </Tabs>
327423
328424 {/* Edit class */}
329- <SidePanel guardUnsaved open={editing()} onOpenChange={setEditing} title={t("common.edit")} description={c().name}>
330- <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void wrap(async () => { await patchClassById(id(), { name: name().trim(), grade: grade().trim() || null, year: yearId() || null, teacher_id: teacherId() || null }); setEditing(false); await refresh(refetchClass); }, "common.saved"); }}>
331- <div class="space-y-3">
332- <div class="space-y-1.5"><Label for="edit-class-name">{t("classGroups.className")}</Label><Input id="edit-class-name" maxlength={limits.latest?.course.max_class_name_len} value={name()} onInput={(e) => setName(e.currentTarget.value)} /></div>
333- <div class="space-y-1.5"><Label for="edit-class-grade">{t("classGroups.grade")}</Label><Input id="edit-class-grade" maxlength={limits.latest?.course.max_class_grade_len} value={grade()} onInput={(e) => setGrade(e.currentTarget.value)} /></div>
334- <div class="space-y-1.5"><Label for="edit-class-year">{t("academicYears.year")}</Label><Select id="edit-class-year" value={yearId()} onChange={(e) => setYearId(e.currentTarget.value)}><option value="">{t("academicYears.unassigned")}</option><For each={years.latest ?? []}>{(year) => <option value={year.id}>{year.name}</option>}</For></Select></div>
335- <UserSearchSelect id="edit-class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} initialUser={c().teacher} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" />
336- </div>
337- <div class="flex gap-2 border-t pt-4"><Button type="submit" disabled={pending()}>{t("common.save")}</Button><Button type="button" variant="outline" onClick={() => setEditing(false)}>{t("common.cancel")}</Button></div>
338- </form>
339- </SidePanel>
425+ <ClassEditPanel
426+ cls={c()}
427+ open={editing()}
428+ onOpenChange={setEditing}
429+ years={years.latest ?? []}
430+ maxNameLen={limits.latest?.course.max_class_name_len}
431+ maxGradeLen={limits.latest?.course.max_class_grade_len}
432+ onSaved={async () => { setFlash(t("common.saved")); await refresh(refetchClass); }}
433+ />
340434
341435 {/* Add student */}
342436 <SidePanel open={showAddMember()} onOpenChange={setShowAddMember} title={t("classGroups.addStudent")} description={t("classGroups.addStudentHelp")}>
@@ -376,7 +470,7 @@ function ClassDetailContent() {
376470 onOpenChange={() => setRemoveMember(null)}
377471 title={t("classGroups.removeStudent")}
378472 variant="destructive"
379- summary={t("classGroups.removeStudentConfirm", { name: removeMember() ? personLabel(removeMember()!.user) : "" })}
473+ summary={t("classGroups.removeStudentConfirm", { name: removeMember() ? personName(removeMember()!.user) : "" })}
380474 onConfirm={async () => { const target = removeMember(); if (!target) return; await wrap(async () => { await deleteClassMember(id(), target.user.id); await refresh(refetchMembers); setRemoveMember(null); }, "common.deleted"); }}
381475 />
382476
src/pages/classes-page.test.tsxmodified+1 -0
@@ -16,6 +16,7 @@ vi.mock("@tanstack/solid-router", () => ({
1616 Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>,
1717 Navigate: () => null,
1818 useNavigate: () => navigate,
19+ useLocation: () => () => ({ pathname: "/management/classes", search: {}, searchStr: "", hash: "" }),
1920 }));
2021 vi.mock("@/stores/auth-context", () => ({
2122 useAuth: () => ({
src/pages/classes-page.tsxmodified+193 -81
@@ -1,25 +1,26 @@
11 import { For, Show, Suspense, createMemo, createSignal } from "solid-js";
2+import type { ColumnDef } from "@tanstack/solid-table";
23 import { createResource } from "@/lib/create-resource";
34 import { useNavigate } from "@tanstack/solid-router";
4-import { getClasses, getClassMembers, postClass } from "@/api/classes";
5+import { deleteClassById, getClasses, getClassMembers, postClass, postClassBlueprintApply } from "@/api/classes";
56 import { getAcademicYears } from "@/api/academic-years";
67 import { getCourses } from "@/api/courses";
78 import { getLimits } from "@/api/limits";
8-import { formatApiError, type BlueprintSkip, type ClassGroup } from "@/api/client";
9+import { ApiError, formatApiError, type BlueprintSkip, type ClassGroup } from "@/api/client";
910 import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report";
11+import { ClassEditPanel } from "@/components/classes/class-edit-panel";
12+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1013 import { RouteGuard } from "@/components/layout/route-guard";
11-import { DataToolbar } from "@/components/ui/data-toolbar";
1214 import { DropdownSelect, Select } from "@/components/ui/select";
1315 import { Alert } from "@/components/ui/alert";
1416 import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
15-import { Badge } from "@/components/ui/badge";
1617 import { Button } from "@/components/ui/button";
17-import { DataTableSkeleton } from "@/components/ui/data-table";
18-import { EmptyState } from "@/components/ui/empty-state";
19-import { IconChevronRight, IconPlus } from "@/components/ui/icons";
18+import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
19+import { IconEdit, IconEye, IconListChecks, IconPlus, IconTrash } from "@/components/ui/icons";
2020 import { Input } from "@/components/ui/input";
2121 import { Label } from "@/components/ui/label";
2222 import { SidePanel } from "@/components/ui/side-panel";
23+import { TableRowActions } from "@/components/ui/table-row-actions";
2324 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
2425 import { BlueprintsTab } from "@/components/classes/blueprints-tab";
2526 import { UserSearchSelect } from "@/components/users/user-search-select";
@@ -27,6 +28,8 @@ import { createFlash } from "@/lib/flash";
2728 import { matchesSearch } from "@/lib/search-text";
2829 import { personLabel } from "@/lib/person";
2930 import { hasMinRole } from "@/lib/roles";
31+import { compareClasses } from "@/lib/student-directory";
32+import { createUrlString } from "@/lib/url-state";
3033 import { useAuth } from "@/stores/auth-context";
3134 import { useT } from "@/stores/preferences-context";
3235
@@ -48,8 +51,7 @@ function ClassesContent() {
4851 const canManage = () => hasMinRole(auth.user()?.role, "manager");
4952
5053 const [tab, setTab] = createSignal("classes");
51- const [gradeFilter, setGradeFilter] = createSignal("all");
52- const [query, setQuery] = createSignal("");
54+ const [gradeFilter, setGradeFilter] = createUrlString("grade", "all");
5355 const [showForm, setShowForm] = createSignal(false);
5456 const [name, setName] = createSignal("");
5557 const [grade, setGrade] = createSignal("");
@@ -69,9 +71,9 @@ function ClassesContent() {
6971 const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items);
7072 const [limits] = createResource(() => canManage() ? getLimits() : null);
7173 const [list, { refetch }] = createResource(async () => (await getClasses()).items);
72- const courseTitle = (id: string) => skippedCourseTitles()[id] ?? id;
74+ const courseTitle = (id: string) => skippedCourseTitles()[id] ?? "—";
7375 const listData = () => list.latest ?? list() ?? [];
74- const yearName = (id: string | null) => years.latest?.find((year) => year.id === id)?.name ?? (id || t("academicYears.unassigned"));
76+ const yearName = (id: string | null) => (id ? years.latest?.find((year) => year.id === id)?.name ?? "—" : t("academicYears.unassigned"));
7577
7678 // Grade tabs mirror Figma's Tümü/Lise/Ortaokul row structurally, but the
7779 // labels are read from whatever `grade` values this school actually uses
@@ -83,19 +85,6 @@ function ClassesContent() {
8385 return [...seen].sort((a, b) => a.localeCompare(b, "tr"));
8486 });
8587
86- const gradeFiltered = createMemo(() => {
87- const g = gradeFilter();
88- return g === "all" ? listData() : listData().filter((cls) => cls.grade === g);
89- });
90-
91- const searched = createMemo(() => {
92- const needle = query().trim();
93- if (!needle) return gradeFiltered();
94- return gradeFiltered().filter((cls) =>
95- matchesSearch(needle, cls.name, cls.grade, cls.teacher ? personLabel(cls.teacher) : null),
96- );
97- });
98-
9988 const memberCountIds = createMemo(() => {
10089 const ids = listData().map((cls) => cls.id);
10190 return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null;
@@ -112,6 +101,131 @@ function ClassesContent() {
112101 });
113102 const memberCountsCapped = () => listData().length > MEMBER_COUNT_FETCH_CAP;
114103
104+ // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it.
105+ const gradeFiltered = createMemo(() => {
106+ const g = gradeFilter();
107+ return (g === "all" ? listData() : listData().filter((cls) => cls.grade === g)).slice().sort(compareClasses);
108+ });
109+ // A fresh array once the member counts land: the table redraws a row only
110+ // when its data changes, so the counts would otherwise stay "—".
111+ const rows = createMemo(() => {
112+ memberCounts();
113+ return gradeFiltered().slice();
114+ });
115+ const openClass = (cls: ClassGroup) => void navigate({ to: "/management/classes/$id", params: { id: cls.id } });
116+
117+ // The detail page's header actions, from the row menu: edit, apply the
118+ // grade's blueprint and delete — all manager+, as there.
119+ const [editTarget, setEditTarget] = createSignal<ClassGroup | null>(null);
120+ const [deleteTarget, setDeleteTarget] = createSignal<ClassGroup | null>(null);
121+ const [rowError, setRowError] = createSignal("");
122+ const refreshList = async () => {
123+ try { await refetch(); } catch { /* stale rows until the next load */ }
124+ };
125+ // Applying is best-effort: the request succeeds and reports the pairs it
126+ // could not attach, so a shortfall opens the same report the create uses.
127+ const applyBlueprint = async (cls: ClassGroup) => {
128+ if (pending()) return;
129+ setRowError("");
130+ setPending(true);
131+ try {
132+ const result = await postClassBlueprintApply(cls.id);
133+ if (result.skipped.length === 0) {
134+ setFlash(t("classBlueprints.applied"));
135+ return;
136+ }
137+ try {
138+ const courses = (await getCourses({ limit: 200 })).items;
139+ setSkippedCourseTitles(Object.fromEntries(courses.map((course) => [course.id, course.title])));
140+ } catch {
141+ // The report still opens; the rows fall back to "—".
142+ }
143+ setSkipped(result.skipped);
144+ setReportOpen(true);
145+ } catch (err) {
146+ // A 404 here means no blueprint covers this grade, not a missing class.
147+ setRowError(err instanceof ApiError && err.status === 404
148+ ? t("classBlueprints.noBlueprintForGrade", { grade: cls.grade ?? "" })
149+ : formatApiError(err));
150+ } finally {
151+ setPending(false);
152+ }
153+ };
154+ const columns = createMemo<ColumnDef<ClassGroup>[]>(() => [
155+ {
156+ accessorKey: "name",
157+ header: t("classGroups.className"),
158+ size: 150,
159+ minSize: 120,
160+ meta: { cellClass: "max-w-0" },
161+ cell: (cell) => <span class="block truncate font-medium" title={cell.row.original.name}>{cell.row.original.name}</span>,
162+ },
163+ {
164+ id: "grade",
165+ accessorFn: (row) => row.grade ?? "",
166+ header: t("classGroups.grade"),
167+ size: 90,
168+ minSize: 80,
169+ meta: { cellClass: "whitespace-nowrap text-center", align: "center" },
170+ cell: (cell) => cell.row.original.grade || "—",
171+ },
172+ {
173+ id: "year",
174+ accessorFn: (row) => yearName(row.year),
175+ header: t("academicYears.year"),
176+ size: 190,
177+ minSize: 150,
178+ meta: { cellClass: "max-w-0 truncate text-text-subtle" },
179+ },
180+ {
181+ id: "teacher",
182+ accessorFn: (row) => (row.teacher ? personLabel(row.teacher) : t("classGroups.noTeacher")),
183+ header: t("classGroups.homeroomTeacher"),
184+ size: 180,
185+ minSize: 140,
186+ meta: { cellClass: "max-w-0 truncate" },
187+ cell: (cell) => cell.row.original.teacher ? personLabel(cell.row.original.teacher) : <span class="text-text-subtle">{t("classGroups.noTeacher")}</span>,
188+ },
189+ {
190+ id: "students",
191+ accessorFn: (row) => memberCounts()?.get(row.id) ?? -1,
192+ header: t("nav.studentsRoster"),
193+ size: 110,
194+ minSize: 90,
195+ meta: { cellClass: "whitespace-nowrap text-center", align: "center" },
196+ cell: (cell) => {
197+ const count = memberCounts()?.get(cell.row.original.id);
198+ return count == null ? <span class="text-text-subtle">—</span> : t("classGroups.studentsCount", { count: String(count) });
199+ },
200+ },
201+ {
202+ id: "actions",
203+ header: t("common.actions"),
204+ meta: { headerClass: "w-28 min-w-28 text-center whitespace-nowrap", cellClass: "px-1 text-center" },
205+ cell: (cell) => (
206+ <TableRowActions
207+ label={t("common.actions")}
208+ actions={[
209+ { label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => openClass(cell.row.original) },
210+ ...(canManage()
211+ ? [
212+ { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => setEditTarget(cell.row.original) },
213+ {
214+ label: t("classBlueprints.apply"),
215+ icon: <IconListChecks class="h-4 w-4" />,
216+ disabled: pending() || !cell.row.original.grade,
217+ onSelect: () => void applyBlueprint(cell.row.original),
218+ },
219+ { label: t("classGroups.deleteClass"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setDeleteTarget(cell.row.original) },
220+ ]
221+ : []),
222+ ]}
223+ />
224+ ),
225+ },
226+ ]);
227+
228+
115229 const createClass = async (event: SubmitEvent) => {
116230 event.preventDefault();
117231 setError("");
@@ -192,7 +306,41 @@ function ClassesContent() {
192306 </form>
193307 </SidePanel>
194308
309+ <ClassEditPanel
310+ cls={editTarget()}
311+ open={editTarget() !== null}
312+ onOpenChange={(open) => { if (!open) setEditTarget(null); }}
313+ years={years.latest ?? []}
314+ maxNameLen={limits.latest?.course.max_class_name_len}
315+ maxGradeLen={limits.latest?.course.max_class_grade_len}
316+ onSaved={async () => { setFlash(t("common.saved")); await refreshList(); }}
317+ />
318+
319+ <ConfirmDialog
320+ open={deleteTarget() !== null}
321+ onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
322+ title={t("classGroups.deleteClass")}
323+ variant="destructive"
324+ description={t("classGroups.deleteConfirm")}
325+ summary={deleteTarget()?.name ?? ""}
326+ onConfirm={async () => {
327+ const target = deleteTarget();
328+ if (!target) return;
329+ setRowError("");
330+ try {
331+ await deleteClassById(target.id);
332+ setDeleteTarget(null);
333+ setFlash(t("common.deleted"));
334+ await refreshList();
335+ } catch (err) {
336+ setDeleteTarget(null);
337+ setRowError(formatApiError(err));
338+ }
339+ }}
340+ />
341+
195342 <Show when={flash()}><Alert variant="success">{flash()}</Alert></Show>
343+ <Show when={rowError()}><Alert variant="destructive">{rowError()}</Alert></Show>
196344
197345 <Show when={skipped().length > 0}>
198346 <Alert class="flex flex-wrap items-center justify-between gap-3 border-amber-500/40 bg-amber-500/10 text-amber-900 dark:text-amber-200">
@@ -222,12 +370,27 @@ function ClassesContent() {
222370
223371 <TabsContent value="classes">
224372 <div class="space-y-4">
225- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
226- <DataToolbar
227- searchValue={query()}
228- searchPlaceholder={t("classGroups.searchPlaceholder")}
229- searchHint={t("search.hint.classes")}
230- onSearchInput={setQuery}
373+ <Show when={memberCountsCapped()}>
374+ <Alert role="status">{t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })}</Alert>
375+ </Show>
376+
377+ <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>
378+ <DataTable
379+ urlState
380+ columns={columns()}
381+ data={rows()}
382+ tableClass="table-fixed min-w-[48rem]"
383+ searchPredicate={(cls, needle) => matchesSearch(needle, cls.name, cls.grade, cls.teacher ? personLabel(cls.teacher) : null)}
384+ filterPlaceholder={t("classGroups.searchPlaceholder")}
385+ filterHint={t("search.hint.classes")}
386+ enablePagination
387+ pageSize={20}
388+ storageKey="classes"
389+ pageResetKey={gradeFilter()}
390+ filtersActive={gradeFilter() !== "all"}
391+ onClearFilters={() => setGradeFilter("all")}
392+ empty={t("classGroups.empty")}
393+ onRowClick={openClass}
231394 filters={
232395 <Show when={grades().length > 0}>
233396 <DropdownSelect
@@ -247,27 +410,6 @@ function ClassesContent() {
247410 </Show>
248411 }
249412 />
250- </div>
251-
252- <Show when={memberCountsCapped()}>
253- <Alert role="status">{t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })}</Alert>
254- </Show>
255-
256- <Suspense fallback={<DataTableSkeleton />}>
257- <Show when={searched().length > 0} fallback={<EmptyState kind="people" title={t("classGroups.empty")} />}>
258- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
259- <For each={searched()}>
260- {(cls) => (
261- <ClassCard
262- cls={cls}
263- yearName={yearName(cls.year)}
264- memberCount={memberCounts()?.get(cls.id) ?? null}
265- onClick={() => void navigate({ to: "/management/classes/$id", params: { id: cls.id } })}
266- />
267- )}
268- </For>
269- </div>
270- </Show>
271413 </Suspense>
272414 </div>
273415 </TabsContent>
@@ -279,33 +421,3 @@ function ClassesContent() {
279421 </div>
280422 );
281423 }
282-
283-function ClassCard(props: { cls: ClassGroup; yearName: string; memberCount: number | null; onClick: () => void }) {
284- const t = useT();
285- return (
286- <button
287- type="button"
288- onClick={props.onClick}
289- class="group flex flex-col gap-4 rounded-2xl border border-border-line/80 bg-surface-base p-4 text-left shadow-xs transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
290- >
291- <div class="flex items-start gap-3">
292- <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-sm font-semibold text-primary-text">
293- {props.cls.grade || "—"}
294- </span>
295- <div class="min-w-0 flex-1">
296- <p class="truncate text-base font-semibold text-text-strong">{props.cls.name}</p>
297- <p class="mt-1 truncate text-xs text-text-subtle">{props.cls.teacher ? personLabel(props.cls.teacher) : t("classGroups.noTeacher")}</p>
298- </div>
299- <IconChevronRight class="h-4 w-4 shrink-0 text-text-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-primary-text" />
300- </div>
301- <div class="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 text-xs text-text-subtle">
302- <Badge variant="outline" class="min-w-0 max-w-full justify-start rounded-full bg-transparent" title={props.yearName}>
303- <span class="min-w-0 truncate">{props.yearName}</span>
304- </Badge>
305- <Show when={props.memberCount != null} fallback={<span class="shrink-0 text-xs text-text-subtle">—</span>}>
306- <span class="shrink-0">{t("classGroups.studentsCount", { count: String(props.memberCount) })}</span>
307- </Show>
308- </div>
309- </button>
310- );
311-}
src/pages/course-detail-page.tsxmodified+49 -113
@@ -1,4 +1,4 @@
1-import { For, Show, Suspense, createMemo, createSignal } from "solid-js";
1+import { Show, Suspense, createMemo, createSignal } from "solid-js";
22 import { createResource } from "@/lib/create-resource";
33 import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router";
44 import type { ColumnDef } from "@tanstack/solid-table";
@@ -10,9 +10,9 @@ import { postCourseMember } from "@/api/courses";
1010 import { getClasses, getClassInstances, getMyClasses } from "@/api/classes";
1111 import { getMyInstances } from "@/api/instances";
1212 import { getMyCourses } from "@/api/reports";
13-import { patchCourseById } from "@/api/courses";
1413 import { formatApiError } from "@/api/client";
1514 import type { ClassCourse, ClassGroup, CourseKind, CourseMembership, Instance } from "@/api/client";
15+import { CourseEditPanel } from "@/components/courses/course-edit-panel";
1616 import { CourseNotesPanel } from "@/components/courses/course-notes-panel";
1717 import { CourseSubjectsPanel } from "@/components/courses/course-subjects-panel";
1818 import { RouteGuard } from "@/components/layout/route-guard";
@@ -23,18 +23,13 @@ import { Badge } from "@/components/ui/badge";
2323 import { Button } from "@/components/ui/button";
2424 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
2525 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
26-import { DataToolbar } from "@/components/ui/data-toolbar";
2726 import { EmptyState } from "@/components/ui/empty-state";
2827 import { IconBook, IconEdit, IconNote, IconPlus, IconSchool, IconTrash, IconUsers } from "@/components/ui/icons";
2928 import { createFlash } from "@/lib/flash";
30-import { Input } from "@/components/ui/input";
31-import { Label } from "@/components/ui/label";
3229 import { PageSpinner } from "@/components/ui/page-spinner";
33-import { Select } from "@/components/ui/select";
3430 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
3531 import { SidePanel } from "@/components/ui/side-panel";
3632 import { TableRowActions } from "@/components/ui/table-row-actions";
37-import { Textarea } from "@/components/ui/textarea";
3833 import { UserSearchSelect } from "@/components/users/user-search-select";
3934 import { useAuth } from "@/stores/auth-context";
4035 import { useModules } from "@/stores/modules-context";
@@ -44,8 +39,6 @@ import { createUrlString } from "@/lib/url-state";
4439 import { cn } from "@/lib/cn";
4540 import { matchesSearch } from "@/lib/search-text";
4641
47-const COURSE_KINDS: CourseKind[] = ["course", "study", "club"];
48-
4942 /** One row of the "taught in" list: an instance plus the şube's name. */
5043 type SectionRow = { instance: Instance | ClassCourse; className: string };
5144
@@ -151,9 +144,6 @@ function CourseDetailContent() {
151144 );
152145
153146 const [editing, setEditing] = createSignal(false);
154- const [title, setTitle] = createSignal("");
155- const [description, setDescription] = createSignal("");
156- const [kind, setKind] = createSignal<CourseKind>("course");
157147 const [showSubjectForm, setShowSubjectForm] = createSignal(false);
158148 const [showNoteForm, setShowNoteForm] = createSignal(false);
159149 const [showMemberForm, setShowMemberForm] = createSignal(false);
@@ -181,7 +171,6 @@ function CourseDetailContent() {
181171 const query = sectionSearch().trim();
182172 return query ? (sections() ?? []).filter((section) => matchesSearch(query, section.className)) : sections() ?? [];
183173 });
184- const memberCount = createMemo(() => members()?.length ?? 0);
185174 const memberUserIds = () => (members() ?? []).map((row) => row.user.id);
186175
187176 const sectionColumns = createMemo<ColumnDef<SectionRow>[]>(() => [
@@ -270,12 +259,7 @@ function CourseDetailContent() {
270259 };
271260
272261 const startEdit = () => {
273- const c = course();
274- if (!c) return;
275- setTitle(c.title);
276- setDescription(c.description);
277- setKind(c.kind ?? "course");
278- setEditing(true);
262+ if (course()) setEditing(true);
279263 };
280264
281265 return (
@@ -358,60 +342,15 @@ function CourseDetailContent() {
358342 }}
359343 />
360344
361- <SidePanel guardUnsaved open={editing()} onOpenChange={setEditing} title={t("common.edit")} description={c().title}>
362- <form
363- class="space-y-4"
364- onSubmit={(e) => {
365- e.preventDefault();
366- void wrap(async () => {
367- await patchCourseById(id(), {
368- title: title().trim(),
369- description: description(),
370- kind: kind(),
371- });
372- setEditing(false);
373- await refetchCourse();
374- }, t("common.saved"));
375- }}
376- >
377- <div class="space-y-3 rounded-xl border border-border-line bg-surface-tint p-4">
378- <div class="space-y-1.5">
379- <Label for="edit-course-title">{t("form.title")}</Label>
380- <Input
381- id="edit-course-title"
382- value={title()}
383- required
384- maxlength={200}
385- onInput={(e) => setTitle(e.currentTarget.value)}
386- />
387- </div>
388- <div class="space-y-1.5">
389- <Label for="edit-course-desc">{t("form.description")}</Label>
390- <Textarea
391- id="edit-course-desc"
392- value={description()}
393- rows={3}
394- maxlength={2000}
395- onInput={(e) => setDescription(e.currentTarget.value)}
396- />
397- </div>
398- <div class="space-y-1.5">
399- <Label for="edit-course-kind">{t("courses.kind")}</Label>
400- <Select id="edit-course-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as CourseKind)}>
401- <For each={COURSE_KINDS}>{(item) => <option value={item}>{courseKindLabel(item)}</option>}</For>
402- </Select>
403- </div>
404- </div>
405- <div class="sticky bottom-0 -mx-5 flex flex-wrap gap-2 border-t border-border-line bg-surface-base px-5 pb-6 pt-4 sm:-mx-6 sm:px-6 sm:pb-6">
406- <Button type="submit" class="flex-1 rounded-xl sm:flex-none" disabled={pending()}>
407- {t("common.update")}
408- </Button>
409- <Button type="button" variant="outline" class="flex-1 rounded-xl sm:flex-none" onClick={() => setEditing(false)}>
410- {t("common.cancel")}
411- </Button>
412- </div>
413- </form>
414- </SidePanel>
345+ <CourseEditPanel
346+ course={c()}
347+ open={editing()}
348+ onOpenChange={setEditing}
349+ onSaved={async () => {
350+ setFlash(t("common.saved"));
351+ try { await refetchCourse(); } catch { /* the next load picks the change up */ }
352+ }}
353+ />
415354
416355 <SidePanel open={showMemberForm()} onOpenChange={setShowMemberForm} title={t("courses.addMember")} description={c().title}>
417356 <form
@@ -484,31 +423,26 @@ function CourseDetailContent() {
484423
485424 <Show when={tabOn.sections()}>
486425 <TabsContent value="sections" forceMount class="space-y-3">
487- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
488- <DataToolbar
489- inline
490- searchValue={sectionSearch()}
491- searchPlaceholder={t("common.searchPlaceholder")}
492- onSearchInput={setSectionSearch}
493- />
494- </div>
495- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs sm:p-4">
496- <Suspense fallback={<DataTableSkeleton />}>
497- <Show
498- when={sectionCount() > 0}
499- fallback={<EmptyState kind="people" title={t("instances.empty")} description={t("instances.emptyHelp")} />}
500- >
501- <DataTable
502- columns={sectionColumns()}
503- data={visibleSections()}
504- enablePagination
505- pageSize={10}
506- empty={t("common.noMatches")}
507- onRowClick={(row) => void navigate({ to: "/instances/$id", params: { id: row.instance.id } })}
508- />
509- </Show>
510- </Suspense>
511- </div>
426+ {/* The table draws its toolbar (search + columns) and grid
427+ as two sibling cards, like the list pages. */}
428+ <Suspense fallback={<DataTableSkeleton />}>
429+ <Show
430+ when={sectionCount() > 0}
431+ fallback={<EmptyState kind="people" title={t("instances.empty")} description={t("instances.emptyHelp")} />}
432+ >
433+ <DataTable
434+ columns={sectionColumns()}
435+ data={visibleSections()}
436+ searchValue={sectionSearch()}
437+ onSearchInput={setSectionSearch}
438+ filterPlaceholder={t("common.searchPlaceholder")}
439+ enablePagination
440+ pageSize={10}
441+ empty={t("common.noMatches")}
442+ onRowClick={(row) => void navigate({ to: "/instances/$id", params: { id: row.instance.id } })}
443+ />
444+ </Show>
445+ </Suspense>
512446 </TabsContent>
513447 </Show>
514448
@@ -518,22 +452,24 @@ function CourseDetailContent() {
518452
519453 <Show when={hasMembers()}>
520454 <TabsContent value="members" forceMount class="space-y-3">
521- <Show when={canManageCatalog()}>
522- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
523- <Button type="button" size="sm" class="rounded-lg" onClick={() => setShowMemberForm(true)}>
524- <IconPlus class="h-4 w-4" />{t("courses.addMember")}
525- </Button>
526- </div>
455+ <Show when={canManageCatalog()} fallback={<EmptyState kind="people" title={t("common.accessDenied")} />}>
456+ <Suspense fallback={<DataTableSkeleton />}>
457+ <DataTable
458+ columns={memberColumns()}
459+ data={members() ?? []}
460+ filterColumn="username"
461+ enablePagination
462+ pageSize={10}
463+ empty={t("exams.emptyRoster")}
464+ emptyIllustration="people"
465+ actions={
466+ <Button type="button" size="sm" class="rounded-lg" onClick={() => setShowMemberForm(true)}>
467+ <IconPlus class="h-4 w-4" />{t("courses.addMember")}
468+ </Button>
469+ }
470+ />
471+ </Suspense>
527472 </Show>
528- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs sm:p-4">
529- <Show when={canManageCatalog()} fallback={<EmptyState kind="people" title={t("common.accessDenied")} />}>
530- <Suspense fallback={<DataTableSkeleton />}>
531- <Show when={memberCount() > 0} fallback={<EmptyState kind="people" title={t("exams.emptyRoster")} />}>
532- <DataTable columns={memberColumns()} data={members() ?? []} filterColumn="username" enablePagination pageSize={10} />
533- </Show>
534- </Suspense>
535- </Show>
536- </div>
537473 </TabsContent>
538474 </Show>
539475 </Tabs>
src/pages/courses-page.test.tsxmodified+12 -12
@@ -73,33 +73,33 @@ test("student class directory uses only enrolled-course data", async () => {
7373
7474 render(() => <PreferencesProvider><CoursesPage /></PreferencesProvider>);
7575
76- expect(await screen.findByRole("link", { name: /Algebra/ })).toBeTruthy();
76+ expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy();
7777 expect(screen.getAllByText("Enrolled")).toHaveLength(3);
7878 expect(getMyCourses).toHaveBeenCalledWith();
7979 expect(getCourses).not.toHaveBeenCalled();
8080
8181 fireEvent.click(screen.getByRole("tab", { name: "Study" }));
82- expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy();
83- expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull();
82+ expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy();
83+ expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull();
8484 expect(getMyCourses).toHaveBeenCalledTimes(1);
8585 const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record<string, unknown>) => Record<string, unknown> };
8686 expect(tabNavigation.to).toBe("/courses");
8787 expect(tabNavigation.replace).toBe(true);
8888 // The kind tab keeps the search text and restarts paging.
89- expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, action: undefined, kind: "study", page: undefined });
89+ expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, sort: undefined, action: undefined, kind: "study", page: undefined });
9090
9191 fireEvent.click(screen.getByRole("tab", { name: "Club" }));
92- expect(await screen.findByRole("link", { name: /Robotics/ })).toBeTruthy();
93- expect(screen.queryByRole("link", { name: /Study Lab/ })).toBeNull();
92+ expect(await screen.findByRole("button", { name: /^Robotics/ })).toBeTruthy();
93+ expect(screen.queryByRole("button", { name: /^Study Lab/ })).toBeNull();
9494
9595 fireEvent.click(screen.getByRole("tab", { name: "Classes" }));
96- expect(await screen.findByRole("link", { name: /Algebra/ })).toBeTruthy();
97- expect(screen.queryByRole("link", { name: /Robotics/ })).toBeNull();
96+ expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy();
97+ expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull();
9898
9999 fireEvent.click(screen.getByRole("tab", { name: "All" }));
100100 fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "robot" } });
101- await waitFor(() => expect(screen.getByRole("link", { name: /Robotics/ })).toBeTruthy());
102- expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull();
101+ await waitFor(() => expect(screen.getByRole("button", { name: /^Robotics/ })).toBeTruthy());
102+ expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull();
103103
104104 fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } });
105105 fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" });
@@ -107,6 +107,6 @@ test("student class directory uses only enrolled-course data", async () => {
107107 fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" });
108108 fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" });
109109 fireEvent.click(untaught);
110- expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy();
111- expect(screen.queryByRole("link", { name: /Robotics/ })).toBeNull();
110+ expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy();
111+ expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull();
112112 });
src/pages/courses-page.tsxmodified+151 -90
@@ -1,33 +1,33 @@
1-import { For, Show, Suspense, createEffect, createMemo, createSignal, on } from "solid-js";
2-import { createResponsivePageSize } from "@/lib/create-page-size";
1+import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
32 import { createResource } from "@/lib/create-resource";
43 import { useNavigate, useSearch } from "@tanstack/solid-router";
5-import { getCourses, postCourse } from "@/api/courses";
4+import type { ColumnDef } from "@tanstack/solid-table";
5+import { deleteCourseById, getCourses, postCourse } from "@/api/courses";
66 import { getMyCourses } from "@/api/reports";
77 import { getLimits } from "@/api/limits";
8-import { formatApiError, type CourseKind } from "@/api/client";
9-import { CourseCard } from "@/components/courses/course-card";
8+import { formatApiError, type Course, type CourseKind } from "@/api/client";
9+import { CourseEditPanel } from "@/components/courses/course-edit-panel";
1010 import { RouteGuard } from "@/components/layout/route-guard";
1111 import { Alert } from "@/components/ui/alert";
12+import { Badge } from "@/components/ui/badge";
1213 import { Button } from "@/components/ui/button";
13-import { DataToolbar } from "@/components/ui/data-toolbar";
14-import { EmptyState } from "@/components/ui/empty-state";
14+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
15+import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1516 import { ErrorAlert } from "@/components/ui/error-alert";
16-import { IconPlus } from "@/components/ui/icons";
17+import { IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons";
1718 import { Input } from "@/components/ui/input";
1819 import { Label } from "@/components/ui/label";
19-import { PageSpinner } from "@/components/ui/page-spinner";
20-import { TablePagination } from "@/components/ui/table-pagination";
2120 import { DropdownSelect } from "@/components/ui/select";
2221 import { courseKindLabel } from "@/lib/course-kind";
2322 import { SidePanel } from "@/components/ui/side-panel";
23+import { TableRowActions } from "@/components/ui/table-row-actions";
2424 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
2525 import { Textarea } from "@/components/ui/textarea";
2626 import { createFlash } from "@/lib/flash";
2727 import { matchesSearch } from "@/lib/search-text";
2828 import { personLabel } from "@/lib/person";
2929 import { hasMinRole } from "@/lib/roles";
30-import { createUrlEnum, createUrlPageIndex, createUrlString } from "@/lib/url-state";
30+import { createUrlEnum } from "@/lib/url-state";
3131 import { useAuth } from "@/stores/auth-context";
3232 import { usePreferences, useT } from "@/stores/preferences-context";
3333
@@ -55,18 +55,9 @@ function CoursesContent() {
5555 const [description, setDescription] = createSignal("");
5656 // Catalog rows carry no term, capacity or staff any more — a şube decides
5757 // all three when it attaches the course. `taughtFilter` narrows by whether
58- // any şube has.
59- // Search, filter and page ride in the URL so Back from a course and a
60- // reload land where the list was left.
58+ // any şube has. It rides in the URL beside the table's own search, sort and
59+ // page, so Back from a course and a reload land where the list was left.
6160 const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all");
62- const [page, setPage] = createUrlPageIndex();
63- const pageSize = createResponsivePageSize(PAGE_SIZE);
64- const [search, setSearch] = createUrlString("q");
65- const narrowed = () => search().trim() !== "" || taughtFilter() !== "all";
66- const clearNarrowing = () => {
67- setSearch("");
68- setTaughtFilter("all");
69- };
7061 const [error, setError] = createSignal("");
7162 const [pending, setPending] = createSignal(false);
7263 const [flash, setFlash] = createFlash();
@@ -77,8 +68,6 @@ function CoursesContent() {
7768 createEffect(() => {
7869 setPageKind(routeSearch().kind);
7970 });
80- // Deferred: the page restored from the URL must survive the first run.
81- createEffect(on(() => [pageKind(), taughtFilter(), search(), pageSize()], () => setPage(0), { defer: true }));
8271
8372 const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null);
8473 const [list, { refetch }] = createResource(
@@ -86,22 +75,96 @@ function CoursesContent() {
8675 async (role) => role === "student" ? getMyCourses() : getCourses(),
8776 );
8877 const listData = () => list.latest ?? list();
89- const filteredCourses = createMemo(() => {
90- const query = search().trim();
91- return (listData()?.items ?? []).filter((course) => {
78+ // A memo: the table must see one array per change, not a fresh one per read.
79+ const filteredCourses = createMemo(() =>
80+ (listData()?.items ?? []).filter((course) => {
9281 if (pageKind() && course.kind !== pageKind()) return false;
9382 if (taughtFilter() === "untaught" && course.class_course_count > 0) return false;
9483 if (taughtFilter() === "taught" && course.class_course_count === 0) return false;
95- if (!query) return true;
96- return matchesSearch(query, course.title, course.description, personLabel(course.creator));
97- });
98- });
99- const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredCourses().length / pageSize())));
100- // A stale `?page=` past the end slides back to the last page.
101- createEffect(() => {
102- if (filteredCourses().length > 0 && page() > totalPages() - 1) setPage(totalPages() - 1);
103- });
104- const visibleCourses = createMemo(() => filteredCourses().slice(page() * pageSize(), (page() + 1) * pageSize()));
84+ return true;
85+ }),
86+ );
87+ const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } });
88+ // Catalog rights, as on the detail page: the creator or a manager+.
89+ const canManageCatalog = (course: Course) => {
90+ const u = auth.user();
91+ return !!u && (course.creator?.id === u.id || hasMinRole(u.role, "manager"));
92+ };
93+ const [editTarget, setEditTarget] = createSignal<Course | null>(null);
94+ const [deleteTarget, setDeleteTarget] = createSignal<Course | null>(null);
95+ const [rowError, setRowError] = createSignal("");
96+ const refreshList = async () => {
97+ try { await refetch(); } catch { /* stale rows until the next load */ }
98+ };
99+ const columns = createMemo<ColumnDef<Course>[]>(() => [
100+ {
101+ accessorKey: "title",
102+ header: t("form.title"),
103+ size: 280,
104+ minSize: 200,
105+ meta: { cellClass: "max-w-0" },
106+ cell: (cell) => (
107+ // Always two lines, description or not, so every row is the same height.
108+ <div class="min-w-0">
109+ <p class="truncate font-medium" title={cell.row.original.title}>{cell.row.original.title}</p>
110+ <p class="truncate text-xs text-text-subtle" title={cell.row.original.description || undefined}>
111+ {cell.row.original.description || "—"}
112+ </p>
113+ </div>
114+ ),
115+ },
116+ {
117+ id: "kind",
118+ accessorFn: (row) => courseKindLabel(row.kind, t),
119+ header: t("exams.kind"),
120+ size: 120,
121+ minSize: 100,
122+ meta: { cellClass: "whitespace-nowrap" },
123+ cell: (cell) => (
124+ <div class="flex w-full items-center justify-center gap-1.5">
125+ <Badge variant="outline" class="rounded-md text-[11px] font-medium">{courseKindLabel(cell.row.original.kind, t)}</Badge>
126+ <Show when={auth.user()?.role === "student"}>
127+ <Badge variant="secondary" class="rounded-md text-[11px]">{t("courses.enrolled")}</Badge>
128+ </Show>
129+ </div>
130+ ),
131+ },
132+ {
133+ id: "sections",
134+ accessorFn: (row) => row.class_course_count,
135+ header: t("courses.sectionsFilter"),
136+ size: 90,
137+ minSize: 80,
138+ meta: { cellClass: "text-center", align: "center" },
139+ },
140+ {
141+ id: "creator",
142+ accessorFn: (row) => personLabel(row.creator),
143+ header: t("common.creator"),
144+ size: 170,
145+ minSize: 130,
146+ meta: { cellClass: "max-w-0 truncate text-text-subtle" },
147+ },
148+ {
149+ id: "actions",
150+ header: t("common.actions"),
151+ meta: { headerClass: "w-28 min-w-28 text-center whitespace-nowrap", cellClass: "px-1 text-center" },
152+ cell: (cell) => (
153+ <TableRowActions
154+ label={t("common.actions")}
155+ actions={[
156+ { label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => openCourse(cell.row.original) },
157+ ...(canManageCatalog(cell.row.original)
158+ ? [
159+ { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => setEditTarget(cell.row.original) },
160+ { label: t("courses.delete"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setDeleteTarget(cell.row.original) },
161+ ]
162+ : []),
163+ ]}
164+ />
165+ ),
166+ },
167+ ]);
105168
106169 const createCourse = async (event: SubmitEvent) => {
107170 event.preventDefault();
@@ -142,7 +205,37 @@ function CoursesContent() {
142205 </form>
143206 </SidePanel>
144207
208+ <CourseEditPanel
209+ course={editTarget()}
210+ open={editTarget() !== null}
211+ onOpenChange={(open) => { if (!open) setEditTarget(null); }}
212+ onSaved={async () => { setFlash(t("common.saved")); await refreshList(); }}
213+ />
214+
215+ <ConfirmDialog
216+ open={deleteTarget() !== null}
217+ onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
218+ title={t("confirm.deleteTitle")}
219+ variant="destructive"
220+ summary={t("courses.delete") + `: “${deleteTarget()?.title ?? ""}”`}
221+ onConfirm={async () => {
222+ const target = deleteTarget();
223+ if (!target) return;
224+ setRowError("");
225+ try {
226+ await deleteCourseById(target.id);
227+ setDeleteTarget(null);
228+ setFlash(t("common.deleted"));
229+ await refreshList();
230+ } catch (err) {
231+ setDeleteTarget(null);
232+ setRowError(formatApiError(err));
233+ }
234+ }}
235+ />
236+
145237 <Show when={flash()}><Alert variant="success">{flash()}</Alert></Show>
238+ <Show when={rowError()}><Alert variant="destructive">{rowError()}</Alert></Show>
146239
147240 <Tabs
148241 value={pageKind() ?? "all"}
@@ -151,7 +244,7 @@ function CoursesContent() {
151244 setPageKind(kind);
152245 void navigate({
153246 to: "/courses",
154- search: (prev) => ({ q: prev.q, taught: prev.taught, action: undefined, kind, page: undefined }),
247+ search: (prev) => ({ q: prev.q, taught: prev.taught, sort: prev.sort, action: undefined, kind, page: undefined }),
155248 replace: true,
156249 });
157250 }}
@@ -164,13 +257,26 @@ function CoursesContent() {
164257 </TabsList>
165258
166259 <TabsContent value={pageKind() ?? "all"} class="mt-4 space-y-4 border-0 bg-transparent p-0 shadow-none">
167- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs" aria-label={t("common.search")}>
168- <DataToolbar
169- inline
170- searchValue={search()}
171- searchPlaceholder={t("common.searchPlaceholder")}
172- searchHint={t("search.hint.courses")}
173- onSearchInput={setSearch}
260+ <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}>
261+ <Show when={list.error}>
262+ <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} />
263+ </Show>
264+ <DataTable
265+ urlState
266+ columns={columns()}
267+ data={filteredCourses()}
268+ tableClass="table-fixed min-w-[44rem]"
269+ searchPredicate={(course, query) => matchesSearch(query, course.title, course.description, personLabel(course.creator))}
270+ filterPlaceholder={t("common.searchPlaceholder")}
271+ filterHint={t("search.hint.courses")}
272+ enablePagination
273+ pageSize={PAGE_SIZE}
274+ storageKey="courses"
275+ pageResetKey={`${pageKind() ?? "all"}|${taughtFilter()}`}
276+ filtersActive={taughtFilter() !== "all"}
277+ onClearFilters={() => setTaughtFilter("all")}
278+ empty={t("courses.empty", { item: kindInSentence() })}
279+ onRowClick={openCourse}
174280 filters={
175281 <DropdownSelect
176282 labelPrefix={t("courses.sectionsFilter")}
@@ -192,52 +298,7 @@ function CoursesContent() {
192298 </Show>
193299 }
194300 />
195- </div>
196-
197- <Suspense fallback={<PageSpinner />}>
198- <Show
199- when={!list.error}
200- fallback={<ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} />}
201- >
202- <Show
203- when={filteredCourses().length > 0}
204- fallback={
205- <Show
206- when={narrowed()}
207- fallback={<EmptyState kind="courses" title={t("courses.empty", { item: kindInSentence() })} />}
208- >
209- <EmptyState
210- kind="search"
211- title={search().trim() ? t("common.noMatchesFor", { query: search().trim() }) : t("common.noFilterMatches")}
212- action={
213- <Button type="button" size="sm" variant="outline" class="rounded-lg" onClick={clearNarrowing}>
214- {taughtFilter() !== "all" ? t("common.clearFilters") : t("common.clearSearch")}
215- </Button>
216- }
217- />
218- </Show>
219- }
220- >
221- <div class={list.loading ? "grid grid-cols-1 gap-3 opacity-60 transition-opacity sm:grid-cols-2 xl:grid-cols-3" : "grid grid-cols-1 gap-3 transition-opacity sm:grid-cols-2 xl:grid-cols-3"}>
222- <For each={visibleCourses()}>
223- {(course) => (
224- <CourseCard
225- course={course}
226- sections={t("common.countItem", { count: course.class_course_count, item: t("instances.item") })}
227- enrolled={auth.user()?.role === "student"}
228- labels={{
229- kind: courseKindLabel(course.kind, t),
230- enrolled: t("courses.enrolled"),
231- }}
232- />
233- )}
234- </For>
235- </div>
236- <TablePagination pageIndex={page()} pageCount={totalPages()} onPageChange={setPage} />
237- </Show>
238- </Show>
239301 </Suspense>
240-
241302 </TabsContent>
242303 </Tabs>
243304 </div>
src/pages/event-detail-page.tsxmodified+18 -32
@@ -8,13 +8,12 @@ import { deleteEventById } from "@/api/events";
88 import { getEventAttendance } from "@/api/events";
99 import { getEventById } from "@/api/events";
1010 import { getEventRoster } from "@/api/events";
11-import { patchEventById } from "@/api/events";
1211 import { postEventRegister } from "@/api/events";
1312 import { formatApiError } from "@/api/client";
1413 import type { EventAudience, EventRosterEntry } from "@/api/client";
1514 import type { MessageKey } from "@/i18n/messages";
1615 import { AttendanceTable } from "@/components/events/attendance-table";
17-import { EventForm } from "@/components/events/event-form";
16+import { EventEditPanel } from "@/components/events/event-edit-panel";
1817 import { EventRollCall } from "@/components/events/event-roll-call";
1918 import { RouteGuard } from "@/components/layout/route-guard";
2019 import { PageHeader } from "@/components/layout/page-header";
@@ -24,11 +23,9 @@ import { Badge } from "@/components/ui/badge";
2423 import { Button } from "@/components/ui/button";
2524 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
2625 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
27-import { DataToolbar } from "@/components/ui/data-toolbar";
2826 import { EmptyState } from "@/components/ui/empty-state";
2927 import { IconEdit, IconTrash } from "@/components/ui/icons";
3028 import { PageSpinner } from "@/components/ui/page-spinner";
31-import { SidePanel } from "@/components/ui/side-panel";
3229 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
3330 import { TableRowActions } from "@/components/ui/table-row-actions";
3431 import { UserSearchSelect } from "@/components/users/user-search-select";
@@ -237,31 +234,15 @@ function EventDetailContent() {
237234 }}
238235 />
239236
240- <SidePanel guardUnsaved
237+ <EventEditPanel
238+ event={ev()}
241239 open={editing()}
242240 onOpenChange={setEditing}
243- title={t("common.edit")}
244- description={ev().title}
245- >
246- <EventForm
247- initial={ev()}
248- submitLabel={t("common.update")}
249- onCancel={() => setEditing(false)}
250- onSubmit={async (values) => {
251- const body: Record<string, unknown> = {
252- title: values.title,
253- description: values.description,
254- audience: values.audience,
255- };
256- if (values.starts_at !== undefined) body.starts_at = values.starts_at;
257- if (values.ends_at !== undefined) body.ends_at = values.ends_at;
258- await patchEventById(id(), body);
259- setEditing(false);
260- await refetchEvent();
261- setFlash(t("common.saved"));
262- }}
263- />
264- </SidePanel>
241+ onSaved={async () => {
242+ await refetchEvent();
243+ setFlash(t("common.saved"));
244+ }}
245+ />
265246
266247 <ConfirmDialog
267248 open={registrationTarget() != null}
@@ -319,13 +300,18 @@ function EventDetailContent() {
319300 </Button>
320301 </div>
321302 </div>
322- <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs">
323- <DataToolbar searchValue={rosterSearch()} searchPlaceholder={t("common.searchPlaceholder")} onSearchInput={setRosterSearch} />
324- </div>
325303 <Suspense fallback={<DataTableSkeleton columns={4} />}>
326304 <Show when={roster()}>
327- <Show when={visibleRoster().length > 0} fallback={<EmptyState kind="events" title={t("events.noRoster")} />}>
328- <DataTable columns={rosterColumns()} data={visibleRoster()} enablePagination pageSize={10} />
305+ <Show when={(roster() ?? []).length > 0} fallback={<EmptyState kind="events" title={t("events.noRoster")} />}>
306+ <DataTable
307+ columns={rosterColumns()}
308+ data={visibleRoster()}
309+ searchValue={rosterSearch()}
310+ onSearchInput={setRosterSearch}
311+ filterPlaceholder={t("common.searchPlaceholder")}
312+ enablePagination
313+ pageSize={10}
314+ />
329315 </Show>
330316 </Show>
331317 </Suspense>
src/pages/events-page.tsxmodified+58 -7
@@ -2,17 +2,19 @@ import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js
22 import { createResource } from "@/lib/create-resource";
33 import { Link, useLocation, useNavigate } from "@tanstack/solid-router";
44 import type { ColumnDef } from "@tanstack/solid-table";
5-import { getEvents } from "@/api/events";
5+import { deleteEventById, getEvents } from "@/api/events";
66 import { postEvent } from "@/api/events";
77 import { formatApiError } from "@/api/client";
88 import type { Event, EventAudience } from "@/api/client";
99 import { Alert } from "@/components/ui/alert";
1010 import { Badge } from "@/components/ui/badge";
1111 import { Button } from "@/components/ui/button";
12+import { EventEditPanel } from "@/components/events/event-edit-panel";
1213 import { EventForm } from "@/components/events/event-form";
14+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1315 import { RouteGuard } from "@/components/layout/route-guard";
1416 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
15-import { IconEye, IconPlus } from "@/components/ui/icons";
17+import { IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons";
1618 import { DropdownSelect } from "@/components/ui/select";
1719 import { SidePanel } from "@/components/ui/side-panel";
1820 import { TableRowActions } from "@/components/ui/table-row-actions";
@@ -89,6 +91,18 @@ function EventsContent() {
8991 (scope) => loadCappedList(getEvents, LIST_CAP, scope === "all"),
9092 );
9193 const rows = createMemo(() => filterEvents(list()?.items ?? []));
94+
95+ // The detail page's header actions, from the row menu. Same rights as there:
96+ // the event's creator or a manager+.
97+ const canManage = (event: Event) => {
98+ const u = auth.user();
99+ return !!u && (event.creator === u.id || hasMinRole(u.role, "manager"));
100+ };
101+ const [editTarget, setEditTarget] = createSignal<Event | null>(null);
102+ const [deleteTarget, setDeleteTarget] = createSignal<Event | null>(null);
103+ const refreshList = async () => {
104+ try { await refetch(); } catch { /* stale rows until the next load */ }
105+ };
92106 const eventStatus = (event: Event) => {
93107 const nowMs = now();
94108 if (event.ends_at != null && event.ends_at < nowMs) return "past";
@@ -170,11 +184,19 @@ function EventsContent() {
170184 cell: (cell) => (
171185 <TableRowActions
172186 label={t("common.actions")}
173- actions={[{
174- label: t("common.view"),
175- icon: <IconEye class="h-4 w-4" />,
176- onSelect: () => void navigate({ to: "/events/$id", params: { id: cell.row.original.id } }),
177- }]}
187+ actions={[
188+ {
189+ label: t("common.view"),
190+ icon: <IconEye class="h-4 w-4" />,
191+ onSelect: () => void navigate({ to: "/events/$id", params: { id: cell.row.original.id } }),
192+ },
193+ ...(canManage(cell.row.original)
194+ ? [
195+ { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => setEditTarget(cell.row.original) },
196+ { label: t("common.delete"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setDeleteTarget(cell.row.original) },
197+ ]
198+ : []),
199+ ]}
178200 />
179201 ),
180202 },
@@ -212,6 +234,35 @@ function EventsContent() {
212234 />
213235 </SidePanel>
214236
237+ <EventEditPanel
238+ event={editTarget()}
239+ open={editTarget() !== null}
240+ onOpenChange={(open) => { if (!open) setEditTarget(null); }}
241+ onSaved={async () => { await refreshList(); setFlash(t("common.saved")); }}
242+ />
243+
244+ <ConfirmDialog
245+ open={deleteTarget() !== null}
246+ onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
247+ title={t("confirm.deleteTitle")}
248+ variant="destructive"
249+ summary={t("confirm.deleteEvent", { title: deleteTarget()?.title ?? "" })}
250+ onConfirm={async () => {
251+ const target = deleteTarget();
252+ if (!target) return;
253+ setError("");
254+ try {
255+ await deleteEventById(target.id);
256+ setDeleteTarget(null);
257+ setFlash(t("common.deleted"));
258+ await refreshList();
259+ } catch (err) {
260+ setDeleteTarget(null);
261+ setError(formatApiError(err));
262+ }
263+ }}
264+ />
265+
215266 <Show when={flash()}>
216267 <Alert variant="success">{flash()}</Alert>
217268 </Show>
src/pages/exam-detail-page.tsxmodified+54 -56
@@ -31,7 +31,6 @@ import { Badge } from "@/components/ui/badge";
3131 import { Button } from "@/components/ui/button";
3232 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
3333 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
34-import { EmptyState } from "@/components/ui/empty-state";
3534 import { IconCalendarDays, IconChart, IconChevronDown, IconClipboardCheck, IconClock, IconEdit, IconExam, IconEye, IconRefresh, IconSchool, IconTrash } from "@/components/ui/icons";
3635 import { Input } from "@/components/ui/input";
3736 import { PageSpinner } from "@/components/ui/page-spinner";
@@ -44,7 +43,7 @@ import { createNow } from "@/lib/create-now";
4443 import { examKindLabel } from "@/lib/exam-labels";
4544 import { examDisplayStatus, examStatusMessageKey, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status";
4645 import { examDurationMs, formatDateTime, formatDurationMinutes } from "@/lib/format";
47-import { personId, personLabel, personLabelWithId } from "@/lib/person";
46+import { personId, personLabel, personPickerLabel } from "@/lib/person";
4847 import { cn } from "@/lib/cn";
4948 import { createFlash } from "@/lib/flash";
5049 import { scheduleStatusClass } from "@/lib/schedule-status";
@@ -305,14 +304,14 @@ function ExamDetailContent() {
305304 .filter((row) => (row.status === "submitted" || row.status === "expired") && !graded.has(personId(row.user)))
306305 .map((row) => ({
307306 id: personId(row.user),
308- label: personLabelWithId(row.user),
307+ label: personPickerLabel(row.user),
309308 }));
310309 }
311310 return (roster() ?? [])
312311 .filter((row) => !graded.has(row.user.id))
313312 .map((row) => ({
314313 id: row.user.id,
315- label: personLabelWithId(row.user),
314+ label: personPickerLabel(row.user),
316315 }));
317316 };
318317 const resultColumns = createMemo<ColumnDef<ExamResult>[]>(() => [
@@ -703,62 +702,61 @@ function ExamDetailContent() {
703702 <ExamQuestionsPanel examId={id()} courseId={instance()?.course ?? null} readOnly={isFinished()} embedded />
704703 </TabsContent>
705704
706- <TabsContent value="results" forceMount class="data-shell space-y-4 p-4">
707- <div class="flex flex-wrap items-center justify-between gap-3">
708- <Badge variant="secondary">{`${resultTotal()} ${t("exams.studentResults")}`}</Badge>
709- <div class="flex flex-wrap items-center gap-2">
710- <Show when={isFinished()}>
711- <label
712- class={cn(
713- "inline-flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-xs transition-colors hover:bg-muted/50",
714- reviewOn() && "text-primary-text",
715- )}
716- title={t("exams.allowReviewHelp")}
717- >
718- <span class="font-medium">{t("exams.allowReview")}</span>
719- <span class="relative shrink-0">
720- <input
721- type="checkbox"
722- class="peer sr-only"
723- checked={reviewOn()}
724- disabled={reviewSaving()}
725- onChange={(event) => toggleReview(event.currentTarget.checked)}
726- />
727- <span class="block h-6 w-10 rounded-full bg-input ring-1 ring-inset ring-black/5 transition-colors peer-checked:bg-primary peer-disabled:opacity-60 peer-focus-visible:ring-2 peer-focus-visible:ring-ring dark:ring-white/10" />
728- <span class="pointer-events-none absolute left-1 top-1 h-4 w-4 rounded-full bg-white shadow-sm transition-transform peer-checked:translate-x-4" />
729- </span>
730- </label>
731- </Show>
732- <Button type="button" variant="outline" size="sm" class="rounded-lg" disabled={isDraft()} onClick={() => setGradeOpen(true)}>
733- <IconEdit class="h-4 w-4" />
734- {t("exams.gradeStudent")}
735- </Button>
736- </div>
737- </div>
705+ {/* No frame around the tab: the table draws its toolbar (search,
706+ review switch, grade button, columns) and grid as two sibling
707+ cards, like the list pages. The pager shows the count. */}
708+ <TabsContent value="results" forceMount class="space-y-3">
738709 <Suspense fallback={<DataTableSkeleton />}>
739- <Show
740- when={(results()?.items ?? []).length > 0}
741- fallback={<EmptyState kind="exams" title={t("exams.noResults")} />}
742- >
743- {/* Server-paged: the table's own pager drives the fetch, so a
744- phone's smaller page never shows up as a second pager
745- slicing the fetched page again. */}
746- <DataTable
747- columns={resultColumns()}
748- data={results()?.items ?? []}
749- filterColumn="user"
750- manualPagination={{
751- pageIndex: Math.min(resultPage(), resultTotalPages() - 1),
752- pageSize: resultPageSize(),
753- total: resultTotal(),
754- onPageChange: setResultPage,
755- }}
756- />
757- </Show>
710+ {/* Server-paged: the table's own pager drives the fetch, so a
711+ phone's smaller page never shows up as a second pager
712+ slicing the fetched page again. */}
713+ <DataTable
714+ columns={resultColumns()}
715+ data={results()?.items ?? []}
716+ filterColumn="user"
717+ empty={t("exams.noResults")}
718+ emptyIllustration="exams"
719+ manualPagination={{
720+ pageIndex: Math.min(resultPage(), resultTotalPages() - 1),
721+ pageSize: resultPageSize(),
722+ total: resultTotal(),
723+ onPageChange: setResultPage,
724+ }}
725+ actions={
726+ <>
727+ <Show when={isFinished()}>
728+ <label
729+ class={cn(
730+ "inline-flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-xs transition-colors hover:bg-muted/50",
731+ reviewOn() && "text-primary-text",
732+ )}
733+ title={t("exams.allowReviewHelp")}
734+ >
735+ <span class="font-medium">{t("exams.allowReview")}</span>
736+ <span class="relative shrink-0">
737+ <input
738+ type="checkbox"
739+ class="peer sr-only"
740+ checked={reviewOn()}
741+ disabled={reviewSaving()}
742+ onChange={(event) => toggleReview(event.currentTarget.checked)}
743+ />
744+ <span class="block h-6 w-10 rounded-full bg-input ring-1 ring-inset ring-black/5 transition-colors peer-checked:bg-primary peer-disabled:opacity-60 peer-focus-visible:ring-2 peer-focus-visible:ring-ring dark:ring-white/10" />
745+ <span class="pointer-events-none absolute left-1 top-1 h-4 w-4 rounded-full bg-white shadow-sm transition-transform peer-checked:translate-x-4" />
746+ </span>
747+ </label>
748+ </Show>
749+ <Button type="button" variant="outline" size="sm" class="rounded-lg" disabled={isDraft()} onClick={() => setGradeOpen(true)}>
750+ <IconEdit class="h-4 w-4" />
751+ {t("exams.gradeStudent")}
752+ </Button>
753+ </>
754+ }
755+ />
758756 </Suspense>
759757 </TabsContent>
760758
761- <TabsContent value="audience" class="data-shell p-4">
759+ <TabsContent value="audience" class="space-y-3">
762760 <ExamAudiencePanel
763761 examId={id()}
764762 ownerInstanceId={ex().class_course}
src/pages/exams-page.tsxmodified+45 -7
@@ -3,7 +3,7 @@ import { createResource } from "@/lib/create-resource";
33 import type { ColumnDef } from "@tanstack/solid-table";
44 import { useLocation, useNavigate } from "@tanstack/solid-router";
55 import { getCourseById } from "@/api/courses";
6-import { getExams } from "@/api/exams";
6+import { deleteExamById, getExams } from "@/api/exams";
77 import { patchExamById } from "@/api/exams";
88 import { getInstanceById, postInstanceExam } from "@/api/instances";
99 import { loadInstanceOptions } from "@/lib/instance-options";
@@ -17,7 +17,7 @@ import { Badge } from "@/components/ui/badge";
1717 import { Button } from "@/components/ui/button";
1818 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1919 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
20-import { IconCheck, IconEdit, IconEye, IconPlus, IconRotateCcw } from "@/components/ui/icons";
20+import { IconChart, IconCheck, IconEdit, IconEye, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons";
2121 import { DropdownSelect } from "@/components/ui/select";
2222 import { SearchableSelect } from "@/components/ui/searchable-select";
2323 import { SidePanel } from "@/components/ui/side-panel";
@@ -27,7 +27,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
2727 import { createNow } from "@/lib/create-now";
2828 import { EXAM_KINDS } from "@/api/client";
2929 import { examKindLabel } from "@/lib/exam-labels";
30-import { examDisplayStatus, examStatusMessageKey, examStatusTone, type ExamDisplayStatus } from "@/lib/exam-status";
30+import { examDisplayStatus, examStatusMessageKey, examStatusTone, isSittableExam, type ExamDisplayStatus } from "@/lib/exam-status";
3131 import { LIST_CAP, loadCappedList } from "@/lib/capped-list";
3232 import { createFlash } from "@/lib/flash";
3333 import { countExamQuestions } from "@/lib/exam-publish";
@@ -100,6 +100,7 @@ function ExamsContent() {
100100 const [createStep, setCreateStep] = createSignal<"details" | "questions">("details");
101101 const [createdExam, setCreatedExam] = createSignal<Exam | null>(null);
102102 const [editTab, setEditTab] = createSignal<"details" | "questions">("details");
103+ const [deleteTarget, setDeleteTarget] = createSignal<Exam | null>(null);
103104
104105 // An exam is set inside an instance (şube × ders), so everything on this page
105106 // — the filter, the picker, the section column — keys on the instance and
@@ -122,7 +123,7 @@ function ExamsContent() {
122123 const courseTitle = (instanceId: string) => {
123124 const cached = visibleCourses().find((row) => row.id === instanceId);
124125 if (cached) return cached.label;
125- return courseMap()[instanceId] ?? instanceId;
126+ return courseMap()[instanceId] ?? "—";
126127 };
127128
128129 const examStatus = (exam: Exam) => examDisplayStatus(exam, now());
@@ -168,7 +169,7 @@ function ExamsContent() {
168169 const instance = await getInstanceById(instanceId);
169170 known.set(instanceId, (await getCourseById(instance.course)).title);
170171 } catch {
171- // The id stays as the label.
172+ // Left unnamed; the row shows a dash, not the id.
172173 }
173174 }),
174175 );
@@ -266,6 +267,19 @@ function ExamsContent() {
266267 { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => { setEditingExam(cell.row.original); setEditTab("details"); } },
267268 ]
268269 : []),
270+ // The detail header's live monitor link: a published, sittable exam
271+ // that has opened, for the exam's creator or a manager+.
272+ ...(canEditExam(cell.row.original) && !cell.row.original.draft && isSittableExam(cell.row.original) && !(cell.row.original.starts_at != null && cell.row.original.starts_at > now())
273+ ? [{
274+ label: cell.row.original.ends_at != null && cell.row.original.ends_at < now() ? t("exams.finalState") : t("exams.liveMonitor"),
275+ icon: <IconChart class="h-4 w-4" />,
276+ onSelect: () => void navigate({ to: "/exams/$id/live", params: { id: cell.row.original.id } }),
277+ }]
278+ : []),
279+ // Delete, as in the detail header: not once the exam has finished.
280+ ...(canEditExam(cell.row.original) && !(cell.row.original.ends_at != null && cell.row.original.ends_at < now())
281+ ? [{ label: t("common.delete"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setDeleteTarget(cell.row.original) }]
282+ : []),
269283 ]}
270284 />
271285 ),
@@ -300,8 +314,11 @@ function ExamsContent() {
300314 const exam = editingExam();
301315 if (!exam) return;
302316 const { term: _term, ...patch } = values;
303- const updated = await patchExamById(exam.id, patch);
304- setEditingExam(updated);
317+ await patchExamById(exam.id, patch);
318+ // A saved edit closes the panel, like every other edit form; the
319+ // questions tab saves as you go and is closed by hand.
320+ setEditingExam(null);
321+ setEditTab("details");
305322 await refetchExams();
306323 setFlash(t("common.saved"));
307324 };
@@ -327,6 +344,27 @@ function ExamsContent() {
327344
328345 return (
329346 <div class="space-y-6">
347+ <ConfirmDialog
348+ open={deleteTarget() !== null}
349+ onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
350+ title={t("confirm.deleteTitle")}
351+ variant="destructive"
352+ summary={t("confirm.deleteExam", { title: deleteTarget()?.title ?? "" })}
353+ onConfirm={async () => {
354+ const target = deleteTarget();
355+ if (!target) return;
356+ setError("");
357+ try {
358+ await deleteExamById(target.id);
359+ setDeleteTarget(null);
360+ setFlash(t("common.deleted"));
361+ try { await refetchExams(); } catch { /* stale rows until the next load */ }
362+ } catch (err) {
363+ setDeleteTarget(null);
364+ setError(formatApiError(err));
365+ }
366+ }}
367+ />
330368 <Show when={flash()}>
331369 <Alert variant="success">{flash()}</Alert>
332370 </Show>
src/pages/homework-page.tsxmodified+46 -5
@@ -15,16 +15,18 @@ import { Alert } from "@/components/ui/alert";
1515 import { Button } from "@/components/ui/button";
1616 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1717 import { DatePicker } from "@/components/ui/date-picker";
18-import { IconEye, IconPlus } from "@/components/ui/icons";
18+import { IconEye, IconPlus, IconRotateCcw } from "@/components/ui/icons";
1919 import { Input } from "@/components/ui/input";
2020 import { Label } from "@/components/ui/label";
2121 import { SearchableSelect } from "@/components/ui/searchable-select";
22+import { DropdownSelect } from "@/components/ui/select";
2223 import { SidePanel } from "@/components/ui/side-panel";
2324 import { TableRowActions } from "@/components/ui/table-row-actions";
2425 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
2526 import { Textarea } from "@/components/ui/textarea";
2627 import { formatDateTime } from "@/lib/format";
2728 import { hasMinRole } from "@/lib/roles";
29+import { createUrlString } from "@/lib/url-state";
2830 import { useAuth } from "@/stores/auth-context";
2931 import { usePreferences, useT } from "@/stores/preferences-context";
3032
@@ -82,12 +84,26 @@ function HomeworkContent() {
8284 setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label])));
8385 return items;
8486 });
85- // The sections a teacher may assign work in, labelled "<ders> — <şube>".
87+ // The caller's sections, labelled "<ders> — <şube>" and ordered class by
88+ // class: the şube filter lists them all, the create form only for teachers.
8689 const [instances] = createResource(
87- () => (hasMinRole(auth.user()?.role, "teacher") ? auth.user()?.role : null),
90+ () => auth.user()?.role ?? null,
8891 (role) => loadInstanceOptions(role ?? undefined),
8992 );
90- const manageableCourses = createMemo(() => instances() ?? []);
93+ const manageableCourses = createMemo(() => (hasMinRole(auth.user()?.role, "teacher") ? instances() ?? [] : []));
94+ // The şube filter, as on /exams; it lives in the URL beside the table's own
95+ // search and page.
96+ const [courseFilter, setCourseFilter] = createUrlString("course", "all");
97+ const courseFilterOptions = createMemo(() => {
98+ const known = instances() ?? [];
99+ const knownIds = new Set(known.map((row) => row.id));
100+ // Homework in a şube the picker does not list (e.g. one the caller only
101+ // sees through an assignment) still gets its own entry, after the rest.
102+ const extra = [...new Set((list() ?? []).map((item) => item.class_course))]
103+ .filter((id) => !knownIds.has(id) && courseNames()[id])
104+ .map((id) => ({ value: id, label: courseNames()[id] }));
105+ return [{ value: "all", label: t("common.all") }, ...known.map((row) => ({ value: row.id, label: row.label })), ...extra];
106+ });
91107 const selectedCourse = createMemo(() => manageableCourses().find((row) => row.id === selectedCourseId())?.course ?? null);
92108 const [subjects] = createResource(
93109 () => selectedCourse(),
@@ -101,7 +117,7 @@ function HomeworkContent() {
101117 const [dueTab, setDueTab] = createSignal<DueTab>("all");
102118 const dueFilteredList = createMemo(() => {
103119 const now = serverTime()?.now ?? Date.now();
104- const items = list() ?? [];
120+ const items = (list() ?? []).filter((item) => courseFilter() === "all" || item.class_course === courseFilter());
105121 if (dueTab() === "open") return items.filter((item) => item.due_at >= now);
106122 if (dueTab() === "past") return items.filter((item) => item.due_at < now);
107123 return items;
@@ -267,6 +283,31 @@ function HomeworkContent() {
267283 pageSize={10}
268284 empty={t("homework.empty")}
269285 storageKey="homework"
286+ pageResetKey={`${dueTab()}|${courseFilter()}`}
287+ filtersActive={courseFilter() !== "all"}
288+ onClearFilters={() => setCourseFilter("all")}
289+ filters={
290+ <div class="flex flex-wrap items-center gap-2.5">
291+ <DropdownSelect
292+ labelPrefix={t("nav.courses")}
293+ value={courseFilter()}
294+ onChange={(val) => setCourseFilter(val)}
295+ options={courseFilterOptions()}
296+ />
297+ <Show when={courseFilter() !== "all"}>
298+ <Button
299+ type="button"
300+ variant="ghost"
301+ size="sm"
302+ class="h-8 rounded-lg px-3 text-[13px] font-medium text-muted-foreground hover:text-foreground"
303+ onClick={() => setCourseFilter("all")}
304+ >
305+ <IconRotateCcw class="mr-1 h-3.5 w-3.5" />
306+ {t("common.resetFilters")}
307+ </Button>
308+ </Show>
309+ </div>
310+ }
270311 actions={
271312 <Show when={canCreate()}>
272313 <Button type="button" size="sm" class="rounded-lg" onClick={() => setCreateOpen(true)}>
src/pages/instance-detail-page.tsxmodified+22 -43
@@ -31,7 +31,6 @@ import { Badge } from "@/components/ui/badge";
3131 import { Button } from "@/components/ui/button";
3232 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
3333 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
34-import { EmptyState } from "@/components/ui/empty-state";
3534 import { IconAlert, IconCalendarDays, IconExam, IconHomework, IconPlus, IconSchool, IconTrash, IconUsers } from "@/components/ui/icons";
3635 import { Input } from "@/components/ui/input";
3736 import { PageSpinner } from "@/components/ui/page-spinner";
@@ -208,7 +207,6 @@ function InstanceDetailContent() {
208207 if (mode === "open") return t("exams.mode.open");
209208 return t("exams.unscheduled");
210209 };
211- const countDescription = (count: number, item: string) => t("common.countItem", { count, item });
212210 const examCount = createMemo(() => exams()?.length ?? 0);
213211 const rosterCount = createMemo(() => roster()?.length ?? 0);
214212 const enrolledUserIds = () => (roster() ?? []).map((row) => row.user.id);
@@ -629,14 +627,9 @@ function InstanceDetailContent() {
629627
630628 <Show when={tabOn.exams()}>
631629 <TabsContent value="exams" class="space-y-3">
632- <div class="flex flex-wrap items-center gap-2">
633- <Badge variant="secondary" class="rounded-full">{countDescription(examCount(), t("courses.examItem"))}</Badge>
634- <Show when={canManage()}>
635- <Button type="button" variant="outline" size="sm" class="ml-auto rounded-lg" onClick={() => setShowExamForm(true)}>
636- <IconPlus class="h-4 w-4" />{t("courses.addExam")}
637- </Button>
638- </Show>
639- </div>
630+ {/* Each tab's add button rides in its table's toolbar card
631+ (search, add, columns), like the list pages; the tab label
632+ and the pager already carry the count. */}
640633 <Suspense fallback={<DataTableSkeleton />}>
641634 <DataTable
642635 columns={examColumns()}
@@ -645,6 +638,11 @@ function InstanceDetailContent() {
645638 enablePagination
646639 pageSize={10}
647640 empty={t("exams.empty")}
641+ actions={canManage() ? (
642+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => setShowExamForm(true)}>
643+ <IconPlus class="h-4 w-4" />{t("courses.addExam")}
644+ </Button>
645+ ) : undefined}
648646 onRowClick={(exam) => void navigate({ to: "/exams/$id", params: { id: exam.id } })}
649647 />
650648 </Suspense>
@@ -653,14 +651,6 @@ function InstanceDetailContent() {
653651
654652 <Show when={tabOn.homework()}>
655653 <TabsContent value="homework" class="space-y-3">
656- <div class="flex flex-wrap items-center gap-2">
657- <Badge variant="secondary" class="rounded-full">{countDescription(homeworkCount(), t("homework.item"))}</Badge>
658- <Show when={canManage()}>
659- <Button type="button" variant="outline" size="sm" class="ml-auto rounded-lg" onClick={() => setShowHomeworkForm(true)}>
660- <IconPlus class="h-4 w-4" />{t("homework.add")}
661- </Button>
662- </Show>
663- </div>
664654 <CourseHomeworkPanel
665655 instanceId={id()}
666656 courseId={inst().course}
@@ -675,14 +665,6 @@ function InstanceDetailContent() {
675665
676666 <Show when={tabOn.sessions()}>
677667 <TabsContent value="sessions" class="space-y-3">
678- <div class="flex flex-wrap items-center gap-2">
679- <Badge variant="secondary" class="rounded-full">{countDescription(sessionCount(), t("sessions.item"))}</Badge>
680- <Show when={canManage()}>
681- <Button type="button" variant="outline" size="sm" class="ml-auto rounded-lg" onClick={() => setShowSessionForm(true)}>
682- <IconPlus class="h-4 w-4" />{t("sessions.add")}
683- </Button>
684- </Show>
685- </div>
686668 <CourseSessionsPanel
687669 instanceId={id()}
688670 roster={roster() ?? []}
@@ -699,14 +681,6 @@ function InstanceDetailContent() {
699681 </Show>
700682
701683 <TabsContent value="teachers" class="space-y-3">
702- <div class="flex flex-wrap items-center gap-2 text-sm">
703- <Badge variant="secondary" class="rounded-full">{countDescription(inst().teachers.length, t("courses.teachers"))}</Badge>
704- <Show when={canStaff()}>
705- <Button type="button" variant="outline" size="sm" class="ml-auto rounded-lg" onClick={() => setShowTeacherForm(true)}>
706- <IconPlus class="h-4 w-4" />{t("courses.assignTeacher")}
707- </Button>
708- </Show>
709- </div>
710684 <CourseTeachersPanel
711685 instanceId={id()}
712686 teachers={inst().teachers}
@@ -719,16 +693,21 @@ function InstanceDetailContent() {
719693
720694 <Show when={canManage()}>
721695 <TabsContent value="students" class="space-y-3">
722- <div class="flex flex-wrap items-center gap-2">
723- <Badge variant="secondary" class="rounded-full">{countDescription(rosterCount(), t("courses.rosterItem"))}</Badge>
724- <Button type="button" variant="outline" size="sm" class="ml-auto rounded-lg" onClick={() => setShowEnrollPanel(true)}>
725- <IconPlus class="h-4 w-4" />{t("courses.enroll")}
726- </Button>
727- </div>
728696 <Suspense fallback={<DataTableSkeleton />}>
729- <Show when={(roster() ?? []).length > 0} fallback={<EmptyState kind="people" title={t("exams.emptyRoster")} />}>
730- <DataTable columns={rosterColumns()} data={roster() ?? []} filterColumn="student" enablePagination pageSize={10} />
731- </Show>
697+ <DataTable
698+ columns={rosterColumns()}
699+ data={roster() ?? []}
700+ filterColumn="student"
701+ enablePagination
702+ pageSize={10}
703+ empty={t("exams.emptyRoster")}
704+ emptyIllustration="people"
705+ actions={
706+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => setShowEnrollPanel(true)}>
707+ <IconPlus class="h-4 w-4" />{t("courses.enroll")}
708+ </Button>
709+ }
710+ />
732711 </Suspense>
733712 </TabsContent>
734713 </Show>
src/pages/profile-page.tsxmodified+31 -7
@@ -11,7 +11,7 @@ import { RoleBadge } from "@/components/layout/role-badge";
1111 import { Badge } from "@/components/ui/badge";
1212 import { Button } from "@/components/ui/button";
1313 import { ErrorAlert } from "@/components/ui/error-alert";
14-import { IconEdit, IconSchool } from "@/components/ui/icons";
14+import { IconEdit, IconSchool, IconUserCircle } from "@/components/ui/icons";
1515 import { PageSpinner } from "@/components/ui/page-spinner";
1616 import { PixelIcon, type PixelIconName } from "@/components/ui/pixel-icon";
1717 import { SidePanel } from "@/components/ui/side-panel";
@@ -19,8 +19,10 @@ import { AvatarUpload } from "@/components/users/avatar-upload";
1919 import { BadgeGrid } from "@/components/users/badge-grid";
2020 import { ProfileForm } from "@/components/users/profile-form";
2121 import { ProfileMemberships } from "@/components/users/profile-memberships";
22+import { StudentInfoPanel } from "@/components/users/student-info-panel";
2223 import { UserAvatar } from "@/components/users/user-avatar";
2324 import { personLabel } from "@/lib/person";
25+import { studentInfoSource } from "@/lib/student-info-access";
2426 import { useAuth } from "@/stores/auth-context";
2527 import { useT } from "@/stores/preferences-context";
2628
@@ -53,6 +55,7 @@ function ProfileContent() {
5355 const [limits] = createResource(() => getLimits());
5456 const [settings] = createResource(() => getSettings().catch(() => null));
5557 const [editing, setEditing] = createSignal(false);
58+ const [infoOpen, setInfoOpen] = createSignal(false);
5659
5760 // The five counters that fit the profile owner's role: a student's own
5861 // work, or a teacher's / manager's teaching work.
@@ -80,6 +83,8 @@ function ProfileContent() {
8083 ];
8184
8285 const isSelf = (p: Profile) => target() === "me" || p.id === auth.user()?.id;
86+ // Staff, the student themself or their parent; never another student.
87+ const infoSource = (p: Profile) => studentInfoSource(auth.user(), p);
8388 const name = (p: Profile) => p.display_name || p.username;
8489
8590 // The profile payload's class refs carry no homeroom teacher, so read the
@@ -196,12 +201,20 @@ function ProfileContent() {
196201 </Show>
197202 </div>
198203 </div>
199- <Show when={isSelf(p()) && auth.user()}>
200- <Button type="button" size="sm" variant="outline" class="mt-3 rounded-lg" onClick={() => setEditing(true)}>
201- <IconEdit class="mr-1.5 h-4 w-4" />
202- {t("profile.edit")}
203- </Button>
204- </Show>
204+ <div class="mt-3 flex flex-wrap gap-2">
205+ <Show when={infoSource(p())}>
206+ <Button type="button" size="sm" variant="outline" class="rounded-lg" onClick={() => setInfoOpen(true)}>
207+ <IconUserCircle class="mr-1.5 h-4 w-4" />
208+ {t("profile.studentInfo")}
209+ </Button>
210+ </Show>
211+ <Show when={isSelf(p()) && auth.user()}>
212+ <Button type="button" size="sm" variant="outline" class="rounded-lg" onClick={() => setEditing(true)}>
213+ <IconEdit class="mr-1.5 h-4 w-4" />
214+ {t("profile.edit")}
215+ </Button>
216+ </Show>
217+ </div>
205218 </div>
206219 </section>
207220
@@ -226,6 +239,17 @@ function ProfileContent() {
226239 courseTotal={p().stats.courses}
227240 />
228241
242+ <Show when={infoSource(p())}>
243+ {(source) => (
244+ <StudentInfoPanel
245+ open={infoOpen()}
246+ onOpenChange={setInfoOpen}
247+ source={source()}
248+ student={{ id: p().id, username: p().username, name: name(p()) }}
249+ />
250+ )}
251+ </Show>
252+
229253 <SidePanel guardUnsaved open={editing()} onOpenChange={setEditing} title={t("profile.edit")}>
230254 <Show when={auth.user()}>
231255 {(u) => (
src/pages/question-bank-page.tsxmodified+1 -21
@@ -15,7 +15,6 @@ import { Button } from "@/components/ui/button";
1515 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1616 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1717 import { IconEdit, IconEye, IconEyeOff, IconPlus, IconTrash, IconUsers } from "@/components/ui/icons";
18-import { PixelIcon } from "@/components/ui/pixel-icon";
1918 import { DropdownSelect } from "@/components/ui/select";
2019 import { SidePanel } from "@/components/ui/side-panel";
2120 import { TableRowActions } from "@/components/ui/table-row-actions";
@@ -212,25 +211,6 @@ function QuestionBankContent() {
212211 <Alert variant="destructive">{error()}</Alert>
213212 </Show>
214213
215- <section class="data-shell relative overflow-hidden p-4 sm:p-5">
216- <div class="pointer-events-none absolute -right-3 -top-5 flex rotate-6 items-center gap-3 text-primary/15" aria-hidden="true">
217- <PixelIcon name="book-open" class="h-16 w-16" />
218- <PixelIcon name="sparkles" class="h-10 w-10" />
219- </div>
220- <div class="relative flex items-start gap-3">
221- <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary-text">
222- <PixelIcon name="users" class="h-5 w-5" />
223- </span>
224- <div class="min-w-0">
225- <div class="flex flex-wrap items-center gap-2">
226- <h1 class="text-lg font-semibold tracking-tight">{t("bank.title")}</h1>
227- <PixelIcon name="sparkles" class="h-4 w-4 text-amber-500" />
228- </div>
229- <p class="mt-1 max-w-2xl text-sm text-muted-foreground">{t("bank.subtitle")}</p>
230- </div>
231- </div>
232- </section>
233-
234214 <Tabs
235215 value={bankTab()}
236216 onChange={(value) => {
@@ -252,7 +232,7 @@ function QuestionBankContent() {
252232 </Show>
253233 <DataTable
254234 title={t("bank.title")}
255- description={`${t("bank.subtitle")} ${t("bank.countTotal", { total: total() })}`}
235+ description={t("bank.countTotal", { total: total() })}
256236 actions={
257237 <Show when={manageableCourses().length > 0}>
258238 <Button type="button" size="sm" class="rounded-lg" onClick={() => setCreateOpen(true)}>
src/pages/staff-work-page.tsxmodified+10 -2
@@ -223,13 +223,21 @@ function StaffWorkContent() {
223223 label: t("common.edit"),
224224 icon: <IconEdit class="h-4 w-4" />,
225225 disabled: cell.row.original.check_out == null,
226- onSelect: () => startEdit(cell.row.original),
226+ // The entries panel hands off to the edit form / delete
227+ // confirm: it closes first rather than staying behind them.
228+ onSelect: () => {
229+ setViewUser(null);
230+ startEdit(cell.row.original);
231+ },
227232 },
228233 {
229234 label: t("common.delete"),
230235 icon: <IconTrash class="h-4 w-4" />,
231236 destructive: true,
232- onSelect: () => setDeleteTarget(cell.row.original),
237+ onSelect: () => {
238+ setViewUser(null);
239+ setDeleteTarget(cell.row.original);
240+ },
233241 },
234242 ]}
235243 />
src/pages/students-roster-page.tsxmodified+37 -4
@@ -11,15 +11,17 @@ import { formatApiError, type ClassGroup, type PersonRef } from "@/api/client";
1111 import { RouteGuard } from "@/components/layout/route-guard";
1212 import { CreateUserPanel } from "@/components/users/create-user-panel";
1313 import { RosterPersonCell } from "@/components/users/roster-person-cell";
14+import { StudentInfoPanel } from "@/components/users/student-info-panel";
1415 import { Button } from "@/components/ui/button";
1516 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1617 import { ErrorAlert } from "@/components/ui/error-alert";
17-import { IconEye, IconPlus } from "@/components/ui/icons";
18+import { IconEye, IconPlus, IconUserCircle } from "@/components/ui/icons";
1819 import { DropdownSelect } from "@/components/ui/select";
1920 import { TableRowActions } from "@/components/ui/table-row-actions";
2021 import { useT } from "@/stores/preferences-context";
2122 import { useAuth } from "@/stores/auth-context";
2223 import { sortByClass } from "@/lib/student-directory";
24+import { studentInfoSource } from "@/lib/student-info-access";
2325
2426 const ROSTER_PAGE_SIZE = 10;
2527
@@ -44,6 +46,10 @@ function StudentsRosterContent() {
4446 const [classFilter, setClassFilter] = createUrlString("class");
4547 const [yearFilter, setYearFilter] = createUrlString("year");
4648 const [creating, setCreating] = createSignal(false);
49+ // The profile header's "Öğrenci bilgileri", from the row menu. The same
50+ // access rule the profile uses decides whether it is offered.
51+ const [infoTarget, setInfoTarget] = createSignal<PersonRef | null>(null);
52+ const infoSource = (person: PersonRef) => studentInfoSource(auth.user(), { id: person.id, role: "student" });
4753
4854 const [data, { refetch }] = createResource(async () => {
4955 const [students, classes, years] = await Promise.all([
@@ -75,6 +81,14 @@ function StudentsRosterContent() {
7581 const open = (row: StudentRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } });
7682
7783 const columns = createMemo<ColumnDef<StudentRow>[]>(() => [
84+ {
85+ id: "student_number",
86+ accessorFn: (row) => row.person.student_number ?? "",
87+ size: 110,
88+ header: t("roster.studentNumber"),
89+ meta: { cellClass: "whitespace-nowrap" },
90+ cell: (cell) => <span class="mono text-sm">{cell.row.original.person.student_number?.trim() || "—"}</span>,
91+ },
7892 {
7993 id: "student", size: 220,
8094 header: t("roster.student"),
@@ -95,7 +109,12 @@ function StudentsRosterContent() {
95109 cell: (cell) => (
96110 <TableRowActions
97111 label={t("common.actions")}
98- actions={[{ label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => open(cell.row.original) }]}
112+ actions={[
113+ { label: t("common.view"), icon: <IconEye class="h-4 w-4" />, onSelect: () => open(cell.row.original) },
114+ ...(infoSource(cell.row.original.person)
115+ ? [{ label: t("profile.studentInfo"), icon: <IconUserCircle class="h-4 w-4" />, onSelect: () => setInfoTarget(cell.row.original.person) }]
116+ : []),
117+ ]}
99118 />
100119 ),
101120 },
@@ -104,7 +123,7 @@ function StudentsRosterContent() {
104123 return (
105124 <div class="space-y-5">
106125 <section class="space-y-4 p-0">
107- <Suspense fallback={<DataTableSkeleton columns={3} rows={8} />}>
126+ <Suspense fallback={<DataTableSkeleton columns={4} rows={8} />}>
108127 <Show when={data.error}>
109128 <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} />
110129 </Show>
@@ -134,7 +153,7 @@ function StudentsRosterContent() {
134153 filterPlaceholder={t("roster.searchStudents")}
135154 filterHint={t("search.hint.students")}
136155 searchPredicate={(row, query) =>
137- matchesSearch(query, row.person.username, row.person.display_name)
156+ matchesSearch(query, row.person.username, row.person.display_name, row.person.student_number)
138157 }
139158 filters={
140159 <>
@@ -161,6 +180,20 @@ function StudentsRosterContent() {
161180 </Show>
162181 </Suspense>
163182 </section>
183+ <Show when={infoTarget()} keyed>
184+ {(person) => (
185+ <Show when={infoSource(person)}>
186+ {(source) => (
187+ <StudentInfoPanel
188+ open
189+ onOpenChange={(open) => { if (!open) setInfoTarget(null); }}
190+ source={source()}
191+ student={{ id: person.id, username: person.username, name: person.display_name || person.username }}
192+ />
193+ )}
194+ </Show>
195+ )}
196+ </Show>
164197 <CreateUserPanel
165198 open={creating()}
166199 onOpenChange={setCreating}
src/pages/terms-page.tsxmodified+47 -4
@@ -17,8 +17,9 @@ import { Button } from "@/components/ui/button";
1717 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1818 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
1919 import { DatePicker } from "@/components/ui/date-picker";
20+import { DetailField } from "@/components/ui/detail-field";
2021 import { ErrorAlert } from "@/components/ui/error-alert";
21-import { IconArchive, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
22+import { IconArchive, IconEdit, IconEye, IconPlus, IconTrash } from "@/components/ui/icons";
2223 import { Input } from "@/components/ui/input";
2324 import { Label } from "@/components/ui/label";
2425 import { Select } from "@/components/ui/select";
@@ -64,7 +65,7 @@ function TermsContent() {
6465 // ones — so the create form cannot be filled without this list.
6566 const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items);
6667 const openYears = createMemo(() => (years.latest ?? []).filter((year) => year.archived_at == null));
67- const yearName = (id: string) => years.latest?.find((year) => year.id === id)?.name ?? id;
68+ const yearName = (id: string) => years.latest?.find((year) => year.id === id)?.name ?? "—";
6869 const terms = () => list() ?? [];
6970 const [panelOpen, setPanelOpen] = createSignal(false);
7071 const [name, setName] = createSignal("");
@@ -73,6 +74,7 @@ function TermsContent() {
7374 const [ends, setEnds] = createSignal("");
7475 const [editing, setEditing] = createSignal<Term | null>(null);
7576 const [deleteTarget, setDeleteTarget] = createSignal<Term | null>(null);
77+ const [detail, setDetail] = createSignal<Term | null>(null);
7678 const [error, setError] = createSignal("");
7779 const [flash, setFlash] = createFlash();
7880 const [pending, setPending] = createSignal(false);
@@ -82,8 +84,10 @@ function TermsContent() {
8284 header: t("settings.name"),
8385 size: 170,
8486 minSize: 150,
85- meta: { cellClass: "min-w-0" },
86- cell: (cell) => <span class="font-medium">{cell.row.original.name}</span>,
87+ // One line: a long name ends in "…" (full name on hover and in the
88+ // detail panel) instead of wrapping the row onto two.
89+ meta: { cellClass: "max-w-0" },
90+ cell: (cell) => <span class="block truncate font-medium" title={cell.row.original.name}>{cell.row.original.name}</span>,
8791 },
8892 {
8993 id: "year",
@@ -130,6 +134,11 @@ function TermsContent() {
130134 <TableRowActions
131135 label={t("common.actions")}
132136 actions={[
137+ {
138+ label: t("common.view"),
139+ icon: <IconEye class="h-4 w-4" />,
140+ onSelect: () => setDetail(cell.row.original),
141+ },
133142 {
134143 label: t("common.edit"),
135144 icon: <IconEdit class="h-4 w-4" />,
@@ -263,6 +272,7 @@ function TermsContent() {
263272 enablePagination
264273 pageSize={TERM_PAGE_SIZE}
265274 empty={t("terms.empty")}
275+ onRowClick={(term) => setDetail(term)}
266276 />
267277 </Suspense>
268278 </section>
@@ -312,6 +322,39 @@ function TermsContent() {
312322 </form>
313323 </SidePanel>
314324
325+ <SidePanel open={detail() != null} onOpenChange={(open) => !open && setDetail(null)} title={detail()?.name ?? ""} description={t("terms.term")}>
326+ <Show when={detail()} keyed>
327+ {(term) => (
328+ <div class="space-y-5">
329+ <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-3">
330+ <p class="text-xs font-medium text-muted-foreground">{t("settings.name")}</p>
331+ <p class="mt-1 break-words text-sm font-medium">{term.name}</p>
332+ </div>
333+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
334+ <DetailField label={t("academicYears.year")} value={yearName(term.year)} />
335+ <DetailField label={t("terms.archived")} value={term.archived_at != null ? formatDate(term.archived_at, locale()) : "—"} />
336+ <DetailField label={t("events.starts")} value={formatDate(term.starts_at, locale())} />
337+ <DetailField label={t("events.ends")} value={formatDate(term.ends_at, locale())} />
338+ </div>
339+ <div class="flex flex-wrap gap-2">
340+ <Button
341+ type="button"
342+ variant="outline"
343+ class="rounded-lg"
344+ onClick={() => {
345+ setDetail(null);
346+ startEdit(term);
347+ }}
348+ >
349+ <IconEdit class="h-4 w-4" />
350+ {t("common.edit")}
351+ </Button>
352+ </div>
353+ </div>
354+ )}
355+ </Show>
356+ </SidePanel>
357+
315358 <ConfirmDialog
316359 open={deleteTarget() != null}
317360 onOpenChange={(open) => !open && setDeleteTarget(null)}
src/routes/router.tsxmodified+1 -0
@@ -207,6 +207,7 @@ const coursesRoute = createRoute({
207207 // List state (see src/lib/url-state.ts); declared so validation keeps it.
208208 q: typeof search.q === "string" || typeof search.q === "number" ? String(search.q) : undefined,
209209 page: typeof search.page === "number" && search.page > 1 ? search.page : undefined,
210+ sort: typeof search.sort === "string" ? search.sort : undefined,
210211 taught: search.taught === "taught" || search.taught === "untaught" ? search.taught : undefined,
211212 }),
212213 component: CoursesPage,