🐛 UX pass from desktop and phone QA
Browse files at this commit37148ac2533c545e62fa5bb35bbcf8a9578061f0Parent: bd48f3f- fix
- 🐛 UX pass from desktop and phone QA
97 changed files +2457 -493
- src/components/ai/note-studio-panel.tsx +1 -1
- src/components/exams/exam-form.tsx +4 -3
- src/components/homework/homework-submissions-panel.tsx +7 -1
- src/components/insights/insight-students-table.tsx +3 -8
- src/components/layout/app-shell.tsx +58 -8
- src/components/layout/celebi-composer.tsx +2 -1
- src/components/layout/command-palette.tsx +2 -2
- src/components/layout/floating-action-button.tsx +1 -1
- src/components/layout/notification-center.tsx +15 -1
- src/components/layout/notification-feed.ts +33 -14
- src/components/layout/notification-list.tsx +20 -3
- src/components/layout/record-not-found.tsx +37 -0
- src/components/layout/route-error.test.tsx +24 -0
- src/components/layout/route-error.tsx +4 -0
- src/components/layout/route-guard.tsx +69 -15
- src/components/layout/shell-unread-badge.test.tsx +8 -4
- src/components/layout/theme-mode-control.tsx +4 -2
- src/components/marks/marks-report-view.tsx +11 -7
- src/components/meals/meal-menu-card.tsx +5 -3
- src/components/messages/gmail-compose-box.tsx +40 -4
- src/components/notes/rag-outputs-panel.tsx +1 -1
- src/components/rag/rag-study-panel.tsx +4 -0
- src/components/system/not-found-page.tsx +1 -1
- src/components/ui/badge.tsx +1 -1
- src/components/ui/chart-heatmap.tsx +40 -6
- src/components/ui/combobox.tsx +9 -2
- src/components/ui/data-table-search.tsx +3 -3
- src/components/ui/data-table-view-menu.tsx +1 -1
- src/components/ui/data-table.test.tsx +59 -1
- src/components/ui/data-table.tsx +129 -30
- src/components/ui/data-toolbar.tsx +1 -1
- src/components/ui/empty-state.tsx +4 -0
- src/components/ui/rich-text-editor.tsx +7 -0
- src/components/ui/side-panel.test.tsx +1 -1
- src/components/ui/side-panel.tsx +3 -1
- src/components/ui/table-pagination.tsx +3 -3
- src/components/users/user-search-select.tsx +51 -2
- src/components/users/user-table.tsx +6 -1
- src/i18n/locales/en.ts +60 -7
- src/i18n/locales/tr.ts +61 -8
- src/i18n/messages.ts +54 -1
- src/index.css +27 -1
- src/lib/exam-labels.test.ts +13 -0
- src/lib/exam-labels.ts +16 -2
- src/lib/format.ts +12 -0
- src/lib/homework-grade.test.ts +22 -0
- src/lib/homework-grade.ts +13 -0
- src/lib/instance-labels.test.ts +62 -0
- src/lib/instance-labels.ts +153 -0
- src/lib/meals.test.ts +10 -1
- src/lib/meals.ts +32 -0
- src/lib/record-list-path.test.ts +24 -0
- src/lib/record-list-path.ts +24 -0
- src/lib/terms.test.ts +38 -0
- src/lib/terms.ts +17 -0
- src/lib/url-state.test.tsx +108 -0
- src/lib/url-state.ts +157 -0
- src/lib/uuid-time.test.ts +16 -0
- src/lib/uuid-time.ts +13 -0
- src/pages/academic-years-page.tsx +4 -3
- src/pages/admin-user-detail-page.tsx +3 -0
- src/pages/ai-insight-student-page.tsx +3 -8
- src/pages/builder-schools-page.tsx +1 -0
- src/pages/calendar-page.test.tsx +1 -0
- src/pages/calendar-page.tsx +70 -23
- src/pages/class-detail-page.tsx +8 -3
- src/pages/course-detail-page.tsx +10 -6
- src/pages/courses-page.test.tsx +11 -6
- src/pages/courses-page.tsx +46 -15
- src/pages/dashboard-page.test.tsx +16 -1
- src/pages/dashboard-page.tsx +122 -55
- src/pages/event-detail-page.tsx +2 -1
- src/pages/events-page.tsx +29 -8
- src/pages/exam-detail-page.tsx +11 -8
- src/pages/exams-page.tsx +35 -16
- src/pages/homework-detail-page.tsx +21 -6
- src/pages/homework-page.tsx +10 -17
- src/pages/instance-detail-page.tsx +98 -26
- src/pages/license-modules-page.tsx +7 -13
- src/pages/meal-detail-page.tsx +9 -9
- src/pages/meals-page.tsx +3 -2
- src/pages/note-editor-page.tsx +13 -1
- src/pages/payment-statement-page.tsx +1 -0
- src/pages/payments-page.tsx +12 -13
- src/pages/pomodoro-page.tsx +1 -1
- src/pages/profile-page.tsx +7 -1
- src/pages/question-bank-page.tsx +3 -1
- src/pages/settings-page.tsx +106 -44
- src/pages/student-attendance-page.tsx +26 -1
- src/pages/student-marks-page.tsx +29 -13
- src/pages/student-pomodoro-page.tsx +26 -1
- src/pages/students-roster-page.tsx +17 -12
- src/pages/teachers-roster-page.tsx +63 -23
- src/pages/terms-page.tsx +4 -3
- src/pages/work-log-page.tsx +1 -0
- src/routes/router.tsx +4 -0
- src/stores/quick-actions.ts +20 -0
src/components/ai/note-studio-panel.tsxmodified+1 -1
| @@ -126,7 +126,7 @@ export function NoteStudioPanel() { | |||
| 126 | <p class="truncate text-xs text-muted-foreground">{note().courseTitle}</p> | 126 | <p class="truncate text-xs text-muted-foreground">{note().courseTitle}</p> |
| 127 | </div> | 127 | </div> |
| 128 | </div> | 128 | </div> |
| 129 | - <div class="grid gap-4 xl:grid-cols-2"> | 129 | + <div class="grid grid-cols-1 gap-4 xl:grid-cols-2"> |
| 130 | <RagOutputsPanel | 130 | <RagOutputsPanel |
| 131 | noteId={note().id} | 131 | noteId={note().id} |
| 132 | source={courseNoteFiles} | 132 | source={courseNoteFiles} |
src/components/exams/exam-form.tsxmodified+4 -3
| @@ -15,6 +15,7 @@ import { Label } from "@/components/ui/label"; | |||
| 15 | import { Select } from "@/components/ui/select"; | 15 | import { Select } from "@/components/ui/select"; |
| 16 | import { Textarea } from "@/components/ui/textarea"; | 16 | import { Textarea } from "@/components/ui/textarea"; |
| 17 | import { examKindLabel } from "@/lib/exam-labels"; | 17 | import { examKindLabel } from "@/lib/exam-labels"; |
| 18 | +import { pickCurrentTerm } from "@/lib/terms"; | ||
| 18 | import { useT } from "@/stores/preferences-context"; | 19 | import { useT } from "@/stores/preferences-context"; |
| 19 | 20 | ||
| 20 | function dateInputFromMs(ms: number | null | undefined): string { | 21 | function dateInputFromMs(ms: number | null | undefined): string { |
| @@ -112,8 +113,8 @@ export function ExamForm(props: { | |||
| 112 | createEffect(() => { | 113 | createEffect(() => { |
| 113 | const list = terms(); | 114 | const list = terms(); |
| 114 | if (!list || list.length === 0 || term()) return; | 115 | if (!list || list.length === 0 || term()) return; |
| 115 | - // Newest first from the backend — the open dönem is what a teacher means. | 116 | + // The dönem running today is what a teacher means; list order is newest first. |
| 116 | - setTerm((list.find((item) => item.archived_at == null) ?? list[0]).id); | 117 | + setTerm(pickCurrentTerm(list, Date.now())?.id ?? list[0].id); |
| 117 | }); | 118 | }); |
| 118 | const examKinds = createMemo(() => { | 119 | const examKinds = createMemo(() => { |
| 119 | const names = settings()?.exam_kinds.map((item) => item.name) ?? EXAM_KINDS; | 120 | const names = settings()?.exam_kinds.map((item) => item.name) ?? EXAM_KINDS; |
| @@ -225,7 +226,7 @@ export function ExamForm(props: { | |||
| 225 | <div class="space-y-3 rounded-xl border border-border-line bg-surface-overlay p-4"> | 226 | <div class="space-y-3 rounded-xl border border-border-line bg-surface-overlay p-4"> |
| 226 | <h3 class="text-xs font-semibold text-text-subtle">{t("exams.sectionBasic")}</h3> | 227 | <h3 class="text-xs font-semibold text-text-subtle">{t("exams.sectionBasic")}</h3> |
| 227 | <div class="space-y-1.5"> | 228 | <div class="space-y-1.5"> |
| 228 | - <Label for="exam-title">{t("form.title")}</Label> | 229 | + <Label for="exam-title">{t("form.title")}<span class="ml-0.5 text-destructive-text">*</span></Label> |
| 229 | <Input | 230 | <Input |
| 230 | id="exam-title" | 231 | id="exam-title" |
| 231 | value={title()} | 232 | value={title()} |
src/components/homework/homework-submissions-panel.tsxmodified+7 -1
| @@ -22,6 +22,7 @@ import { formatDateTime } from "@/lib/format"; | |||
| 22 | import { formatBytes } from "@/lib/upload-limits"; | 22 | import { formatBytes } from "@/lib/upload-limits"; |
| 23 | import { usePreferences, useT } from "@/stores/preferences-context"; | 23 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 24 | import { sanitizeRichText } from "@/lib/rich-text"; | 24 | import { sanitizeRichText } from "@/lib/rich-text"; |
| 25 | +import { defaultGradeStatus } from "@/lib/homework-grade"; | ||
| 25 | 26 | ||
| 26 | export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId: string }) { | 27 | export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId: string }) { |
| 27 | const t = useT(); | 28 | const t = useT(); |
| @@ -50,7 +51,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId | |||
| 50 | 51 | ||
| 51 | const openGrade = (row: HomeworkRosterEntry) => { | 52 | const openGrade = (row: HomeworkRosterEntry) => { |
| 52 | setGradeTarget(row); | 53 | setGradeTarget(row); |
| 53 | - setStatus(row.result?.status ?? (row.missing ? "missing" : "done")); | 54 | + setStatus(defaultGradeStatus(row)); |
| 54 | setMark(row.result?.mark == null ? "" : String(row.result.mark)); | 55 | setMark(row.result?.mark == null ? "" : String(row.result.mark)); |
| 55 | setError(""); | 56 | setError(""); |
| 56 | }; | 57 | }; |
| @@ -68,6 +69,10 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId | |||
| 68 | event.preventDefault(); | 69 | event.preventDefault(); |
| 69 | const target = gradeTarget(); | 70 | const target = gradeTarget(); |
| 70 | if (!target) return; | 71 | if (!target) return; |
| 72 | + if (!status()) { | ||
| 73 | + setError(t("homework.gradeStatusRequired")); | ||
| 74 | + return; | ||
| 75 | + } | ||
| 71 | const numericMark = mark().trim() === "" ? null : Number(mark()); | 76 | const numericMark = mark().trim() === "" ? null : Number(mark()); |
| 72 | if (numericMark != null && (!Number.isFinite(numericMark) || numericMark < 0 || numericMark > 100)) { | 77 | if (numericMark != null && (!Number.isFinite(numericMark) || numericMark < 0 || numericMark > 100)) { |
| 73 | setError(t("form.markRange")); | 78 | setError(t("form.markRange")); |
| @@ -165,6 +170,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId | |||
| 165 | <div class="space-y-1.5"> | 170 | <div class="space-y-1.5"> |
| 166 | <Label for="homework-grade-status">{t("events.status")}</Label> | 171 | <Label for="homework-grade-status">{t("events.status")}</Label> |
| 167 | <Select id="homework-grade-status" value={status()} onChange={(event) => setStatus(event.currentTarget.value)}> | 172 | <Select id="homework-grade-status" value={status()} onChange={(event) => setStatus(event.currentTarget.value)}> |
| 173 | + <option value="" disabled>{t("homework.gradeStatusPlaceholder")}</option> | ||
| 168 | <option value="done">{t("homework.status.done")}</option> | 174 | <option value="done">{t("homework.status.done")}</option> |
| 169 | <option value="incomplete">{t("homework.status.incomplete")}</option> | 175 | <option value="incomplete">{t("homework.status.incomplete")}</option> |
| 170 | <option value="missing">{t("homework.status.missing")}</option> | 176 | <option value="missing">{t("homework.status.missing")}</option> |
src/components/insights/insight-students-table.tsxmodified+3 -8
| @@ -16,6 +16,7 @@ import { | |||
| 16 | } from "@/lib/insight-run-report"; | 16 | } from "@/lib/insight-run-report"; |
| 17 | import { cn } from "@/lib/cn"; | 17 | import { cn } from "@/lib/cn"; |
| 18 | import { matchesSearch } from "@/lib/search-text"; | 18 | import { matchesSearch } from "@/lib/search-text"; |
| 19 | +import { formatDate } from "@/lib/format"; | ||
| 19 | import { usePreferences } from "@/stores/preferences-context"; | 20 | import { usePreferences } from "@/stores/preferences-context"; |
| 20 | 21 | ||
| 21 | type Filter = "all" | "attention" | "none"; | 22 | type Filter = "all" | "attention" | "none"; |
| @@ -51,14 +52,8 @@ export function InsightStudentsTable(props: { | |||
| 51 | })); | 52 | })); |
| 52 | const loaded = (row: StudentSignal) => row.state === "ok"; | 53 | const loaded = (row: StudentSignal) => row.state === "ok"; |
| 53 | const muted = "text-muted-foreground"; | 54 | const muted = "text-muted-foreground"; |
| 54 | - const calculatedDate = (value: number | null | undefined) => { | 55 | + // The app-wide "18 Eyl 2026" date, not a numeric 18.09.2026. |
| 55 | - if (value == null) return "—"; | 56 | + const calculatedDate = (value: number | null | undefined) => formatDate(value, locale()); |
| 56 | - return new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-US", { | ||
| 57 | - day: "2-digit", | ||
| 58 | - month: "2-digit", | ||
| 59 | - year: "numeric", | ||
| 60 | - }).format(new Date(value)); | ||
| 61 | - }; | ||
| 62 | 57 | ||
| 63 | // Widths sum to ~1095px with the action column, so the grid fits a 1440px | 58 | // Widths sum to ~1095px with the action column, so the grid fits a 1440px |
| 64 | // screen beside the sidebar; at the 120px default every column got, the | 59 | // screen beside the sidebar; at the 120px default every column got, the |
src/components/layout/app-shell.tsxmodified+58 -8
| @@ -1,4 +1,5 @@ | |||
| 1 | -import { Show, createEffect, createMemo, createSignal, type ParentProps } from "solid-js"; | 1 | +import { Show, createEffect, createMemo, createSignal, onCleanup, onMount, type ParentProps } from "solid-js"; |
| 2 | +import { Dynamic } from "solid-js/web"; | ||
| 2 | import { Link, useLocation, useNavigate } from "@tanstack/solid-router"; | 3 | import { Link, useLocation, useNavigate } from "@tanstack/solid-router"; |
| 3 | import { LogoMark } from "@/components/brand/logo-mark"; | 4 | import { LogoMark } from "@/components/brand/logo-mark"; |
| 4 | import { AccountProfileDialog } from "@/components/users/account-profile-dialog"; | 5 | import { AccountProfileDialog } from "@/components/users/account-profile-dialog"; |
| @@ -20,6 +21,7 @@ import { useAuth } from "@/stores/auth-context"; | |||
| 20 | import { useModules } from "@/stores/modules-context"; | 21 | import { useModules } from "@/stores/modules-context"; |
| 21 | import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel"; | 22 | import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel"; |
| 22 | import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette"; | 23 | import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette"; |
| 24 | +import { quickActionsSuppressed } from "@/stores/quick-actions"; | ||
| 23 | import { ShellFeedProvider } from "@/stores/shell-feed-context"; | 25 | import { ShellFeedProvider } from "@/stores/shell-feed-context"; |
| 24 | import { usePreferences, useT } from "@/stores/preferences-context"; | 26 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 25 | import { cn } from "@/lib/cn"; | 27 | import { cn } from "@/lib/cn"; |
| @@ -48,12 +50,34 @@ export function AppShell(props: ParentProps) { | |||
| 48 | const key = routeLabelKey(location().pathname, auth.user()?.role); | 50 | const key = routeLabelKey(location().pathname, auth.user()?.role); |
| 49 | return key ? t(key) : ""; | 51 | return key ? t(key) : ""; |
| 50 | }); | 52 | }); |
| 53 | + // The page's own h1, when it renders one (detail pages, the 404). Watched | ||
| 54 | + // rather than declared per route: the shell names the page with an h1 of its | ||
| 55 | + // own only where the page has none, so no screen ends up with two. | ||
| 56 | + let content: HTMLDivElement | undefined; | ||
| 57 | + const [pageHeading, setPageHeading] = createSignal<string | null>(null); | ||
| 58 | + onMount(() => { | ||
| 59 | + if (!content || typeof MutationObserver === "undefined") return; | ||
| 60 | + const read = () => { | ||
| 61 | + const heading = content?.querySelector("h1:not([data-shell-title])"); | ||
| 62 | + setPageHeading(heading ? (heading.textContent ?? "").trim() : null); | ||
| 63 | + }; | ||
| 64 | + read(); | ||
| 65 | + const observer = new MutationObserver(read); | ||
| 66 | + observer.observe(content, { childList: true, subtree: true, characterData: true }); | ||
| 67 | + onCleanup(() => observer.disconnect()); | ||
| 68 | + }); | ||
| 69 | + // Unlisted routes (an instance, the 404) borrow the page's own heading. | ||
| 70 | + const pageTitle = () => routeLabel() || pageHeading() || ""; | ||
| 51 | // One place names the browser tab for every shell route, from the same | 71 | // One place names the browser tab for every shell route, from the same |
| 52 | // label the header shows. | 72 | // label the header shows. |
| 53 | createEffect(() => { | 73 | createEffect(() => { |
| 54 | - const label = routeLabel(); | 74 | + const label = pageTitle(); |
| 55 | document.title = label ? `${label} · ${t("app.name")}` : t("app.name"); | 75 | document.title = label ? `${label} · ${t("app.name")}` : t("app.name"); |
| 56 | }); | 76 | }); |
| 77 | + const shellChrome = () => Boolean(auth.user()) && !fullScreen(); | ||
| 78 | + // Room below the last row for the quick-action button resting over the tab | ||
| 79 | + // bar, so a pager or a last card's actions can scroll clear of it. | ||
| 80 | + const fabClearance = () => shellChrome() && phone() && !quickActionsSuppressed(); | ||
| 57 | const logout = async () => { | 81 | const logout = async () => { |
| 58 | await auth.logout(); | 82 | await auth.logout(); |
| 59 | void navigate({ to: "/login" }); | 83 | void navigate({ to: "/login" }); |
| @@ -135,11 +159,21 @@ export function AppShell(props: ParentProps) { | |||
| 135 | /> | 159 | /> |
| 136 | </Show> | 160 | </Show> |
| 137 | 161 | ||
| 138 | - <main id="main-content" tabIndex={-1} class="min-w-0 flex-1 outline-hidden"> | 162 | + {/* The menu sheet is modal: what it covers leaves the tab order and |
| 163 | + the accessibility tree while it is up. */} | ||
| 164 | + <main class="min-w-0 flex-1" inert={mobileOpen() || undefined}> | ||
| 139 | <Show when={auth.user() && !fullScreen() && !phone()}> | 165 | <Show when={auth.user() && !fullScreen() && !phone()}> |
| 140 | <header class="sticky top-[env(safe-area-inset-top)] z-30 flex h-[49px] items-center gap-3 border-b border-border/70 bg-background px-4 pt-1.5 sm:px-6 lg:px-4"> | 166 | <header class="sticky top-[env(safe-area-inset-top)] z-30 flex h-[49px] items-center gap-3 border-b border-border/70 bg-background px-4 pt-1.5 sm:px-6 lg:px-4"> |
| 141 | <div class="flex min-w-0 shrink-0 items-center gap-2 sm:w-52 lg:w-[260px]"> | 167 | <div class="flex min-w-0 shrink-0 items-center gap-2 sm:w-52 lg:w-[260px]"> |
| 142 | - <span class="hidden truncate text-sm font-semibold sm:block" title={routeLabel()}>{routeLabel()}</span> | 168 | + {/* The page's h1 unless the page renders its own. */} |
| 169 | + <Dynamic | ||
| 170 | + component={pageHeading() === null ? "h1" : "span"} | ||
| 171 | + data-shell-title="" | ||
| 172 | + class="hidden truncate text-sm font-semibold sm:block" | ||
| 173 | + title={pageTitle()} | ||
| 174 | + > | ||
| 175 | + {pageTitle()} | ||
| 176 | + </Dynamic> | ||
| 143 | </div> | 177 | </div> |
| 144 | 178 | ||
| 145 | <div class="min-w-0 flex-1" /> | 179 | <div class="min-w-0 flex-1" /> |
| @@ -167,14 +201,28 @@ export function AppShell(props: ParentProps) { | |||
| 167 | <Show when={auth.user() && !fullScreen()}> | 201 | <Show when={auth.user() && !fullScreen()}> |
| 168 | <NetworkStatusBanner /> | 202 | <NetworkStatusBanner /> |
| 169 | </Show> | 203 | </Show> |
| 204 | + {/* The skip link's target starts below the header, so it lands on | ||
| 205 | + the page rather than on the header's controls. */} | ||
| 170 | <div | 206 | <div |
| 207 | + id="main-content" | ||
| 208 | + tabIndex={-1} | ||
| 209 | + ref={(el) => { | ||
| 210 | + content = el; | ||
| 211 | + }} | ||
| 171 | class={cn( | 212 | class={cn( |
| 172 | // Every page fills the content column, as Messages always did: a | 213 | // Every page fills the content column, as Messages always did: a |
| 173 | // fixed 1180px cap left wide screens mostly empty margin. | 214 | // fixed 1180px cap left wide screens mostly empty margin. |
| 174 | - "w-full px-4 py-6 sm:px-6 lg:px-10 lg:py-6", | 215 | + "w-full px-4 py-6 outline-hidden sm:px-6 lg:px-10 lg:py-6", |
| 175 | - auth.user() && !fullScreen() && "pb-[calc(3.5rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] lg:pb-6", | 216 | + shellChrome() && "pb-[calc(3.5rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] lg:pb-6", |
| 217 | + fabClearance() && "pb-[calc(9rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))]", | ||
| 176 | )} | 218 | )} |
| 177 | > | 219 | > |
| 220 | + {/* No header below lg, so the page title opens the content. */} | ||
| 221 | + <Show when={shellChrome() && phone() && pageHeading() === null && pageTitle()}> | ||
| 222 | + <h1 data-shell-title="" class="-mt-2 mb-3 truncate text-lg font-semibold tracking-tight text-text-strong"> | ||
| 223 | + {pageTitle()} | ||
| 224 | + </h1> | ||
| 225 | + </Show> | ||
| 178 | <Show when={auth.user()} fallback={props.children}> | 226 | <Show when={auth.user()} fallback={props.children}> |
| 179 | <ModuleGate>{props.children}</ModuleGate> | 227 | <ModuleGate>{props.children}</ModuleGate> |
| 180 | </Show> | 228 | </Show> |
| @@ -184,11 +232,13 @@ export function AppShell(props: ParentProps) { | |||
| 184 | {/* MobileTabBar and the quick actions stay inside the provider — they are | 232 | {/* MobileTabBar and the quick actions stay inside the provider — they are |
| 185 | shell surfaces, so a useShellFeed() badge there must not throw. */} | 233 | shell surfaces, so a useShellFeed() badge there must not throw. */} |
| 186 | <Show when={auth.user() && !fullScreen()}> | 234 | <Show when={auth.user() && !fullScreen()}> |
| 187 | - <MobileTabBar onMenu={() => setMobileOpen(true)} onSearch={openCommandPalette} /> | 235 | + <div inert={mobileOpen() || undefined}> |
| 236 | + <MobileTabBar onMenu={() => setMobileOpen(true)} onSearch={openCommandPalette} /> | ||
| 237 | + </div> | ||
| 188 | </Show> | 238 | </Show> |
| 189 | <Show when={auth.user() && !fullScreen() && phone()}> | 239 | <Show when={auth.user() && !fullScreen() && phone()}> |
| 190 | <MobileQuickActions | 240 | <MobileQuickActions |
| 191 | - hidden={mobileOpen() || celebiPanelOpen() || commandPaletteOpen() || profileOpen()} | 241 | + hidden={mobileOpen() || celebiPanelOpen() || commandPaletteOpen() || profileOpen() || quickActionsSuppressed()} |
| 192 | /> | 242 | /> |
| 193 | </Show> | 243 | </Show> |
| 194 | </ShellFeedProvider> | 244 | </ShellFeedProvider> |
src/components/layout/celebi-composer.tsxmodified+2 -1
| @@ -81,7 +81,8 @@ export function CelebiComposer(props: { | |||
| 81 | <IconSend class="h-4 w-4" /> | 81 | <IconSend class="h-4 w-4" /> |
| 82 | </Button> | 82 | </Button> |
| 83 | </div> | 83 | </div> |
| 84 | - <p class="mt-1.5 px-1 text-[11px] leading-4 text-muted-foreground">{t("ai.hint")}</p> | 84 | + {/* Enter / Shift+Enter means nothing on a touch keyboard. */} |
| 85 | + <p class="mt-1.5 px-1 text-[11px] leading-4 text-muted-foreground [@media(pointer:coarse)]:hidden">{t("ai.hint")}</p> | ||
| 85 | </form> | 86 | </form> |
| 86 | ); | 87 | ); |
| 87 | } | 88 | } |
src/components/layout/command-palette.tsxmodified+2 -2
| @@ -395,7 +395,7 @@ export function CommandPalette(props: CommandPaletteProps) { | |||
| 395 | return ( | 395 | return ( |
| 396 | <Dialog open={props.open} onOpenChange={props.onOpenChange}> | 396 | <Dialog open={props.open} onOpenChange={props.onOpenChange}> |
| 397 | <DialogContent | 397 | <DialogContent |
| 398 | - class="max-h-[min(85vh,38rem)] max-w-2xl overflow-hidden rounded-lg p-0 shadow-2xl border border-black/8 dark:border-white/12 bg-popover/95" | 398 | + class="max-h-[min(85vh,38rem)] max-w-2xl overflow-hidden rounded-lg p-0 shadow-2xl border border-black/8 dark:border-white/12 bg-popover" |
| 399 | // The dialog's focus trap parks focus on the panel itself when it | 399 | // The dialog's focus trap parks focus on the panel itself when it |
| 400 | // opens, which used to swallow a focus() queued from an effect — the | 400 | // opens, which used to swallow a focus() queued from an effect — the |
| 401 | // palette opened with nothing focused and the first keystroke went | 401 | // palette opened with nothing focused and the first keystroke went |
| @@ -416,7 +416,7 @@ export function CommandPalette(props: CommandPaletteProps) { | |||
| 416 | type="text" | 416 | type="text" |
| 417 | value={query()} | 417 | value={query()} |
| 418 | placeholder={t("common.searchPlaceholder")} | 418 | placeholder={t("common.searchPlaceholder")} |
| 419 | - class="flex-1 h-9 w-full bg-transparent px-1 text-sm sm:text-base font-medium text-foreground outline-hidden border-none shadow-none focus:outline-hidden focus:ring-0 placeholder:text-muted-foreground/60" | 419 | + class="flex-1 h-9 w-full bg-transparent px-1 text-base font-medium text-foreground outline-hidden border-none shadow-none focus:outline-hidden focus:ring-0 placeholder:text-muted-foreground/60" |
| 420 | onInput={(event) => setQuery(event.currentTarget.value)} | 420 | onInput={(event) => setQuery(event.currentTarget.value)} |
| 421 | onKeyDown={handleKeyDown} | 421 | onKeyDown={handleKeyDown} |
| 422 | // Combobox pattern: focus stays in the field while arrow keys move | 422 | // Combobox pattern: focus stays in the field while arrow keys move |
src/components/layout/floating-action-button.tsxmodified+1 -1
| @@ -324,7 +324,7 @@ export function FloatingActionButton(props: { | |||
| 324 | aria-label={t("fab.restore")} | 324 | aria-label={t("fab.restore")} |
| 325 | title={t("fab.restore")} | 325 | title={t("fab.restore")} |
| 326 | class={cn( | 326 | class={cn( |
| 327 | - "pointer-events-auto absolute flex h-14 w-8 items-center outline-hidden focus-visible:ring-2 focus-visible:ring-ring", | 327 | + "pointer-events-auto absolute flex h-14 w-11 items-center outline-hidden focus-visible:ring-2 focus-visible:ring-ring", |
| 328 | parkedRight() ? "right-0 justify-end" : "left-0 justify-start", | 328 | parkedRight() ? "right-0 justify-end" : "left-0 justify-start", |
| 329 | )} | 329 | )} |
| 330 | style={{ top: `${restTop()}px` }} | 330 | style={{ top: `${restTop()}px` }} |
src/components/layout/notification-center.tsxmodified+15 -1
| @@ -19,6 +19,7 @@ export function NotificationCenter() { | |||
| 19 | }); | 19 | }); |
| 20 | 20 | ||
| 21 | const unreadCount = feed.unreadCount; | 21 | const unreadCount = feed.unreadCount; |
| 22 | + let panel: HTMLDivElement | undefined; | ||
| 22 | 23 | ||
| 23 | return ( | 24 | return ( |
| 24 | <Popover | 25 | <Popover |
| @@ -43,7 +44,20 @@ export function NotificationCenter() { | |||
| 43 | </Show> | 44 | </Show> |
| 44 | </PopoverTrigger> | 45 | </PopoverTrigger> |
| 45 | 46 | ||
| 46 | - <PopoverContent class="w-80 sm:w-96 rounded-xl border border-border-line bg-surface-base p-0 shadow-2xl overflow-hidden"> | 47 | + {/* Focus lands on the popover itself, not its first control: that is |
| 48 | + "Tümünü sil", and one Enter would clear the whole list. */} | ||
| 49 | + <PopoverContent | ||
| 50 | + class="w-80 sm:w-96 rounded-xl border border-border-line bg-surface-base p-0 shadow-2xl overflow-hidden" | ||
| 51 | + ref={(el: HTMLDivElement) => { | ||
| 52 | + panel = el; | ||
| 53 | + }} | ||
| 54 | + tabIndex={-1} | ||
| 55 | + aria-label={t("notifications.title")} | ||
| 56 | + onOpenAutoFocus={(event: Event) => { | ||
| 57 | + event.preventDefault(); | ||
| 58 | + panel?.focus(); | ||
| 59 | + }} | ||
| 60 | + > | ||
| 47 | <NotificationList | 61 | <NotificationList |
| 48 | feed={feed} | 62 | feed={feed} |
| 49 | onNavigate={(url) => { | 63 | onNavigate={(url) => { |
src/components/layout/notification-feed.tsmodified+33 -14
| @@ -1,5 +1,6 @@ | |||
| 1 | import { createMemo, createSignal } from "solid-js"; | 1 | import { createMemo, createSignal } from "solid-js"; |
| 2 | import { patchMessageById } from "@/api/messages"; | 2 | import { patchMessageById } from "@/api/messages"; |
| 3 | +import { createInstanceLabels } from "@/lib/instance-labels"; | ||
| 3 | import { personLabel } from "@/lib/person"; | 4 | import { personLabel } from "@/lib/person"; |
| 4 | import { | 5 | import { |
| 5 | dismissAllNotificationIds, | 6 | dismissAllNotificationIds, |
| @@ -10,6 +11,7 @@ import { | |||
| 10 | type NotificationItem, | 11 | type NotificationItem, |
| 11 | type NotificationType, | 12 | type NotificationType, |
| 12 | } from "@/lib/notifications"; | 13 | } from "@/lib/notifications"; |
| 14 | +import { useAuth } from "@/stores/auth-context"; | ||
| 13 | import { usePreferences } from "@/stores/preferences-context"; | 15 | import { usePreferences } from "@/stores/preferences-context"; |
| 14 | import { useShellFeed } from "@/stores/shell-feed-context"; | 16 | import { useShellFeed } from "@/stores/shell-feed-context"; |
| 15 | 17 | ||
| @@ -37,6 +39,21 @@ export function createNotificationFeed() { | |||
| 37 | // An item is still notifiable until it has ended (ends_at, else starts_at). | 39 | // An item is still notifiable until it has ended (ends_at, else starts_at). |
| 38 | const notEnded = (starts: number, ends?: number | null) => (ends ?? starts) >= nowMs(); | 40 | const notEnded = (starts: number, ends?: number | null) => (ends ?? starts) >= nowMs(); |
| 39 | 41 | ||
| 42 | + // Exams and homework of one ders taught in two şubeler share titles; the | ||
| 43 | + // row's description names "<ders> — <şube>" so they can be told apart. | ||
| 44 | + const auth = useAuth(); | ||
| 45 | + const sectionLabels = createInstanceLabels( | ||
| 46 | + () => [ | ||
| 47 | + ...feed.exams().items.filter((ex) => ex.starts_at && !ex.draft && notEnded(ex.starts_at, ex.ends_at)).map((ex) => ex.class_course), | ||
| 48 | + ...feed.homework().items.filter((hw) => hw.due_at >= nowMs()).map((hw) => hw.class_course), | ||
| 49 | + ], | ||
| 50 | + () => auth.user()?.role, | ||
| 51 | + ); | ||
| 52 | + const withSection = (instanceId: string, text: string) => { | ||
| 53 | + const label = sectionLabels()[instanceId]?.label; | ||
| 54 | + return label ? (text ? `${label} · ${text}` : label) : text; | ||
| 55 | + }; | ||
| 56 | + | ||
| 40 | // Combine notification items | 57 | // Combine notification items |
| 41 | const allNotifications = createMemo<NotificationItem[]>(() => { | 58 | const allNotifications = createMemo<NotificationItem[]>(() => { |
| 42 | const list: NotificationItem[] = []; | 59 | const list: NotificationItem[] = []; |
| @@ -92,14 +109,15 @@ export function createNotificationFeed() { | |||
| 92 | id: `ex_${ex.id}`, | 109 | id: `ex_${ex.id}`, |
| 93 | type: "exam", | 110 | type: "exam", |
| 94 | title: ex.title, | 111 | title: ex.title, |
| 95 | - description: ex.starts_at | 112 | + description: withSection( |
| 96 | - ? new Date(ex.starts_at).toLocaleString(dateLocale(), { | 113 | + ex.class_course, |
| 97 | - month: "short", | 114 | + new Date(ex.starts_at).toLocaleString(dateLocale(), { |
| 98 | - day: "numeric", | 115 | + month: "short", |
| 99 | - hour: "2-digit", | 116 | + day: "numeric", |
| 100 | - minute: "2-digit", | 117 | + hour: "2-digit", |
| 101 | - }) | 118 | + minute: "2-digit", |
| 102 | - : "", | 119 | + }), |
| 120 | + ), | ||
| 103 | targetUrl: `/exams/${ex.id}`, | 121 | targetUrl: `/exams/${ex.id}`, |
| 104 | timestamp: t, | 122 | timestamp: t, |
| 105 | }); | 123 | }); |
| @@ -115,12 +133,13 @@ export function createNotificationFeed() { | |||
| 115 | id: `hw_${hw.id}`, | 133 | id: `hw_${hw.id}`, |
| 116 | type: "homework", | 134 | type: "homework", |
| 117 | title: hw.title, | 135 | title: hw.title, |
| 118 | - description: hw.due_at | 136 | + description: withSection( |
| 119 | - ? `${t("homework.dueAt")}: ${new Date(hw.due_at).toLocaleDateString(dateLocale(), { | 137 | + hw.class_course, |
| 120 | - month: "short", | 138 | + `${t("homework.dueAt")}: ${new Date(hw.due_at).toLocaleDateString(dateLocale(), { |
| 121 | - day: "numeric", | 139 | + month: "short", |
| 122 | - })}` | 140 | + day: "numeric", |
| 123 | - : "", | 141 | + })}`, |
| 142 | + ), | ||
| 124 | targetUrl: `/homework/${hw.id}`, | 143 | targetUrl: `/homework/${hw.id}`, |
| 125 | timestamp: hw.due_at, | 144 | timestamp: hw.due_at, |
| 126 | }); | 145 | }); |
src/components/layout/notification-list.tsxmodified+20 -3
| @@ -1,6 +1,7 @@ | |||
| 1 | import { For, Show, Suspense, createSignal } from "solid-js"; | 1 | import { For, Show, Suspense, createSignal } from "solid-js"; |
| 2 | import { Button } from "@/components/ui/button"; | 2 | import { Button } from "@/components/ui/button"; |
| 3 | import { ComingSoonPanel } from "@/components/ui/coming-soon"; | 3 | import { ComingSoonPanel } from "@/components/ui/coming-soon"; |
| 4 | +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | ||
| 4 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | 5 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| 5 | import { | 6 | import { |
| 6 | IconBell, | 7 | IconBell, |
| @@ -34,6 +35,9 @@ export function NotificationList(props: { | |||
| 34 | }) { | 35 | }) { |
| 35 | const t = useT(); | 36 | const t = useT(); |
| 36 | const [previewNotification, setPreviewNotification] = createSignal<NotificationItem | null>(null); | 37 | const [previewNotification, setPreviewNotification] = createSignal<NotificationItem | null>(null); |
| 38 | + // Clearing everything cannot be undone, so it asks first. | ||
| 39 | + const [confirmClear, setConfirmClear] = createSignal(false); | ||
| 40 | + const totalCount = () => props.feed.groups().reduce((count, group) => count + group.items.length, 0); | ||
| 37 | 41 | ||
| 38 | const notificationGroupLabel = (type: NotificationType) => { | 42 | const notificationGroupLabel = (type: NotificationType) => { |
| 39 | if (type === "message") return t("nav.messages"); | 43 | if (type === "message") return t("nav.messages"); |
| @@ -94,7 +98,7 @@ export function NotificationList(props: { | |||
| 94 | variant="ghost" | 98 | variant="ghost" |
| 95 | size="sm" | 99 | size="sm" |
| 96 | class="h-7 rounded-lg px-2 text-[11px] font-semibold text-text-subtle hover:bg-destructive/10 hover:text-destructive-text" | 100 | class="h-7 rounded-lg px-2 text-[11px] font-semibold text-text-subtle hover:bg-destructive/10 hover:text-destructive-text" |
| 97 | - onClick={() => props.feed.dismissAll()} | 101 | + onClick={() => setConfirmClear(true)} |
| 98 | title={t("notifications.clearAll")} | 102 | title={t("notifications.clearAll")} |
| 99 | > | 103 | > |
| 100 | <IconTrash class="mr-1 h-3 w-3" /> | 104 | <IconTrash class="mr-1 h-3 w-3" /> |
| @@ -185,7 +189,7 @@ export function NotificationList(props: { | |||
| 185 | </Show> | 189 | </Show> |
| 186 | </div> | 190 | </div> |
| 187 | 191 | ||
| 188 | - <div class="min-w-0 flex-1 space-y-0.5 pr-6"> | 192 | + <div class="min-w-0 flex-1 space-y-0.5 pr-6 touch:pr-10"> |
| 189 | <span class="block truncate font-semibold text-text-strong"> | 193 | <span class="block truncate font-semibold text-text-strong"> |
| 190 | {item.title} | 194 | {item.title} |
| 191 | </span> | 195 | </span> |
| @@ -196,8 +200,11 @@ export function NotificationList(props: { | |||
| 196 | 200 | ||
| 197 | <button | 201 | <button |
| 198 | type="button" | 202 | type="button" |
| 199 | - class="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-md text-text-subtle/70 opacity-80 transition-all hover:bg-destructive/10 hover:text-destructive-text sm:opacity-0 sm:group-hover:opacity-100" | 203 | + // A thumb-sized target on touch screens, where |
| 204 | + // there is no hover to reveal it either. | ||
| 205 | + class="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-md text-text-subtle/70 opacity-80 transition-all hover:bg-destructive/10 hover:text-destructive-text sm:opacity-0 sm:group-hover:opacity-100 touch:right-0 touch:top-0 touch:h-11 touch:w-11 touch:opacity-80" | ||
| 200 | title={t("notifications.dismiss")} | 206 | title={t("notifications.dismiss")} |
| 207 | + aria-label={t("notifications.dismiss")} | ||
| 201 | onClick={(e) => dismissOne(e, item.id)} | 208 | onClick={(e) => dismissOne(e, item.id)} |
| 202 | > | 209 | > |
| 203 | <IconX class="h-3.5 w-3.5" /> | 210 | <IconX class="h-3.5 w-3.5" /> |
| @@ -267,6 +274,16 @@ export function NotificationList(props: { | |||
| 267 | </div> | 274 | </div> |
| 268 | )} | 275 | )} |
| 269 | </Show> | 276 | </Show> |
| 277 | + | ||
| 278 | + <ConfirmDialog | ||
| 279 | + open={confirmClear()} | ||
| 280 | + onOpenChange={setConfirmClear} | ||
| 281 | + title={t("notifications.clearAllConfirmTitle")} | ||
| 282 | + summary={t("notifications.clearAllConfirmSummary", { count: totalCount() })} | ||
| 283 | + confirmLabel={t("notifications.clearAll")} | ||
| 284 | + variant="destructive" | ||
| 285 | + onConfirm={() => props.feed.dismissAll()} | ||
| 286 | + /> | ||
| 270 | </> | 287 | </> |
| 271 | ); | 288 | ); |
| 272 | } | 289 | } |
src/components/layout/record-not-found.tsxadded+37 -0
| @@ -0,0 +1,37 @@ | |||
| 1 | +import { Link, useLocation, useRouter } from "@tanstack/solid-router"; | ||
| 2 | +import { currentLocale } from "@/api/client"; | ||
| 3 | +import { buttonVariants } from "@/components/ui/button"; | ||
| 4 | +import { EmptyState } from "@/components/ui/empty-state"; | ||
| 5 | +import { cn } from "@/lib/cn"; | ||
| 6 | +import { listPathFor } from "@/lib/record-list-path"; | ||
| 7 | + | ||
| 8 | +/** | ||
| 9 | + * What a detail page shows when its record does not exist (a 404 — deleted, | ||
| 10 | + * or a bad link): there is nothing to retry, so it offers the way back to the | ||
| 11 | + * list instead. Also rendered by the router's error fallback, which can sit | ||
| 12 | + * above the i18n provider, hence the client's bilingual-fallback idiom. | ||
| 13 | + */ | ||
| 14 | +export function RecordNotFound(props: { backTo?: string }) { | ||
| 15 | + const router = useRouter(); | ||
| 16 | + const location = useLocation(); | ||
| 17 | + const tr = () => currentLocale() === "tr"; | ||
| 18 | + const backTo = () => | ||
| 19 | + props.backTo ?? listPathFor(location().pathname, (path) => path in router.routesByPath); | ||
| 20 | + return ( | ||
| 21 | + <EmptyState | ||
| 22 | + kind="search" | ||
| 23 | + class="mx-auto w-full max-w-[640px]" | ||
| 24 | + title={tr() ? "Kayıt bulunamadı" : "Record not found"} | ||
| 25 | + description={ | ||
| 26 | + tr() | ||
| 27 | + ? "Bu kayıt silinmiş ya da bağlantı hatalı olabilir." | ||
| 28 | + : "This record may have been deleted, or the link is wrong." | ||
| 29 | + } | ||
| 30 | + action={ | ||
| 31 | + <Link to={backTo()} class={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-9 rounded-lg px-4")}> | ||
| 32 | + {backTo() === "/" ? (tr() ? "Ana sayfaya dön" : "Back to home") : tr() ? "Listeye dön" : "Back to the list"} | ||
| 33 | + </Link> | ||
| 34 | + } | ||
| 35 | + /> | ||
| 36 | + ); | ||
| 37 | +} | ||
src/components/layout/route-error.test.tsxmodified+24 -0
| @@ -49,3 +49,27 @@ test("the app router uses it for every route", async () => { | |||
| 49 | const { router } = await import("@/routes/router"); | 49 | const { router } = await import("@/routes/router"); |
| 50 | expect(router.options.defaultErrorComponent).toBe(RouteErrorFallback); | 50 | expect(router.options.defaultErrorComponent).toBe(RouteErrorFallback); |
| 51 | }); | 51 | }); |
| 52 | + | ||
| 53 | +test("a 404 shows not-found with a way back to the list, not a retry", async () => { | ||
| 54 | + const { ApiError } = await import("@/api/client"); | ||
| 55 | + const root = createRootRoute({ component: () => <Outlet /> }); | ||
| 56 | + const list = createRoute({ getParentRoute: () => root, path: "/courses", component: () => <p>LIST</p> }); | ||
| 57 | + const detail = createRoute({ | ||
| 58 | + getParentRoute: () => root, | ||
| 59 | + path: "/courses/$id", | ||
| 60 | + component: () => { | ||
| 61 | + throw new ApiError(404, "not found"); | ||
| 62 | + }, | ||
| 63 | + }); | ||
| 64 | + const router = createRouter({ | ||
| 65 | + routeTree: root.addChildren([list, detail]), | ||
| 66 | + history: createMemoryHistory({ initialEntries: ["/courses/bad"] }), | ||
| 67 | + defaultErrorComponent: RouteErrorFallback, | ||
| 68 | + }); | ||
| 69 | + | ||
| 70 | + render(() => <RouterProvider router={router} />); | ||
| 71 | + | ||
| 72 | + const back = await screen.findByRole("link", { name: /^(Back to the list|Listeye dön)$/ }); | ||
| 73 | + expect(back.getAttribute("href")).toBe("/courses"); | ||
| 74 | + expect(screen.queryByRole("button")).toBeNull(); | ||
| 75 | +}); | ||
src/components/layout/route-error.tsxmodified+4 -0
| @@ -2,6 +2,8 @@ import type { ErrorComponentProps } from "@tanstack/solid-router"; | |||
| 2 | import { currentLocale, formatApiError } from "@/api/client"; | 2 | import { currentLocale, formatApiError } from "@/api/client"; |
| 3 | import { Button } from "@/components/ui/button"; | 3 | import { Button } from "@/components/ui/button"; |
| 4 | import { IconAlert } from "@/components/ui/icons"; | 4 | import { IconAlert } from "@/components/ui/icons"; |
| 5 | +import { RecordNotFound } from "@/components/layout/record-not-found"; | ||
| 6 | +import { isNotFoundError } from "@/lib/record-list-path"; | ||
| 5 | 7 | ||
| 6 | /** | 8 | /** |
| 7 | * The router's default error component: a page that throws while rendering | 9 | * The router's default error component: a page that throws while rendering |
| @@ -15,6 +17,8 @@ import { IconAlert } from "@/components/ui/icons"; | |||
| 15 | */ | 17 | */ |
| 16 | export function RouteErrorFallback(props: ErrorComponentProps) { | 18 | export function RouteErrorFallback(props: ErrorComponentProps) { |
| 17 | const tr = () => currentLocale() === "tr"; | 19 | const tr = () => currentLocale() === "tr"; |
| 20 | + // A missing record is an answer, not a failure: retrying a 404 changes nothing. | ||
| 21 | + if (isNotFoundError(props.error)) return <RecordNotFound />; | ||
| 18 | console.error("Route render error:", props.error); | 22 | console.error("Route render error:", props.error); |
| 19 | return ( | 23 | return ( |
| 20 | <div role="alert" class="mx-auto flex w-full max-w-[520px] flex-col items-center gap-4 rounded-xl border border-border-line bg-surface-base px-6 py-10 text-center"> | 24 | <div role="alert" class="mx-auto flex w-full max-w-[520px] flex-col items-center gap-4 rounded-xl border border-border-line bg-surface-base px-6 py-10 text-center"> |
src/components/layout/route-guard.tsxmodified+69 -15
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { Link, Navigate } from "@tanstack/solid-router"; | 1 | +import { Link, Navigate, useLocation } from "@tanstack/solid-router"; |
| 2 | import { type ParentProps, Show } from "solid-js"; | 2 | import { type ParentProps, Show } from "solid-js"; |
| 3 | import type { Role } from "@/api/client"; | 3 | import type { Role } from "@/api/client"; |
| 4 | import { formatApiError } from "@/api/client"; | 4 | import { formatApiError } from "@/api/client"; |
| @@ -6,30 +6,84 @@ import { Alert } from "@/components/ui/alert"; | |||
| 6 | import { Button } from "@/components/ui/button"; | 6 | import { Button } from "@/components/ui/button"; |
| 7 | import { IconHome, IconLock } from "@/components/ui/icons"; | 7 | import { IconHome, IconLock } from "@/components/ui/icons"; |
| 8 | import { PageSpinner } from "@/components/ui/page-spinner"; | 8 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 9 | -import { hasExactRole, roleInRange } from "@/lib/roles"; | 9 | +import { hasExactRole, hasMinRole, roleInRange } from "@/lib/roles"; |
| 10 | import { useAuth } from "@/stores/auth-context"; | 10 | import { useAuth } from "@/stores/auth-context"; |
| 11 | import { useT } from "@/stores/preferences-context"; | 11 | import { useT } from "@/stores/preferences-context"; |
| 12 | 12 | ||
| 13 | -function AccessDeniedCard() { | 13 | +// Pages kept for one audience that staff reach by URL or an old link: where |
| 14 | +// the school-wide view of the same data exists, point there instead. | ||
| 15 | +const STAFF_ALTERNATIVES: Record<string, { to: string; minRole: Role }> = { | ||
| 16 | + "/marks": { to: "/management/student-marks", minRole: "teacher" }, | ||
| 17 | + "/pomodoro": { to: "/management/pomodoros", minRole: "teacher" }, | ||
| 18 | + "/students": { to: "/management/students", minRole: "manager" }, | ||
| 19 | + "/students/attendance": { to: "/management/student-attendance", minRole: "teacher" }, | ||
| 20 | + "/students/exams": { to: "/management/student-marks", minRole: "teacher" }, | ||
| 21 | +}; | ||
| 22 | + | ||
| 23 | +function AccessDeniedCard(props: { exactRole?: Role; userRole: Role }) { | ||
| 14 | const t = useT(); | 24 | const t = useT(); |
| 25 | + const location = useLocation(); | ||
| 26 | + // Asking "the administrator" for access reads wrong to staff — often they | ||
| 27 | + // are the administrator. For a page kept for students or parents, say so. | ||
| 28 | + const audience = () => | ||
| 29 | + props.exactRole && props.exactRole !== props.userRole && hasMinRole(props.userRole, "teacher") | ||
| 30 | + ? props.exactRole | ||
| 31 | + : null; | ||
| 32 | + const alternative = () => { | ||
| 33 | + if (!audience()) return null; | ||
| 34 | + const alt = STAFF_ALTERNATIVES[location().pathname.replace(/\/+$/, "")]; | ||
| 35 | + return alt && hasMinRole(props.userRole, alt.minRole) ? alt.to : null; | ||
| 36 | + }; | ||
| 15 | return ( | 37 | return ( |
| 16 | <div class="flex min-h-[50vh] items-center justify-center px-4 py-16"> | 38 | <div class="flex min-h-[50vh] items-center justify-center px-4 py-16"> |
| 17 | <div class="w-full max-w-[420px] space-y-5 rounded-xl border border-border-line bg-surface-base p-8 text-center shadow-[0_10px_24px_-4px_rgba(0,0,0,0.10)]"> | 39 | <div class="w-full max-w-[420px] space-y-5 rounded-xl border border-border-line bg-surface-base p-8 text-center shadow-[0_10px_24px_-4px_rgba(0,0,0,0.10)]"> |
| 18 | <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-warning/10 text-warning-text"> | 40 | <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-warning/10 text-warning-text"> |
| 19 | <IconLock class="h-6 w-6" /> | 41 | <IconLock class="h-6 w-6" /> |
| 20 | </div> | 42 | </div> |
| 21 | - <div class="space-y-2"> | 43 | + <Show |
| 22 | - <p class="text-4xl font-semibold tracking-tight text-text-strong">403</p> | 44 | + when={audience()} |
| 23 | - <p class="text-base font-semibold text-text-strong">{t("common.accessDenied")}</p> | 45 | + fallback={ |
| 24 | - <p class="text-sm leading-[21px] text-text-subtle">{t("errors.accessDeniedDescription")}</p> | 46 | + <div class="space-y-2"> |
| 25 | - </div> | 47 | + <p class="text-4xl font-semibold tracking-tight text-text-strong">403</p> |
| 26 | - <Link | 48 | + <p class="text-base font-semibold text-text-strong">{t("common.accessDenied")}</p> |
| 27 | - to="/" | 49 | + <p class="text-sm leading-[21px] text-text-subtle">{t("errors.accessDeniedDescription")}</p> |
| 28 | - class="inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90" | 50 | + </div> |
| 51 | + } | ||
| 29 | > | 52 | > |
| 30 | - <IconHome class="mr-1 h-4 w-4" /> | 53 | + {(role) => ( |
| 31 | - {t("common.goHome")} | 54 | + <div class="space-y-2"> |
| 32 | - </Link> | 55 | + <p class="text-base font-semibold text-text-strong"> |
| 56 | + {t(role() === "parent" ? "errors.parentOnlyTitle" : "errors.studentOnlyTitle")} | ||
| 57 | + </p> | ||
| 58 | + <p class="text-sm leading-[21px] text-text-subtle"> | ||
| 59 | + {t(alternative() ? "errors.audienceOnlyWithAlternative" : "errors.audienceOnlyDescription")} | ||
| 60 | + </p> | ||
| 61 | + </div> | ||
| 62 | + )} | ||
| 63 | + </Show> | ||
| 64 | + <div class="flex flex-wrap items-center justify-center gap-2"> | ||
| 65 | + <Show when={alternative()}> | ||
| 66 | + {(to) => ( | ||
| 67 | + <Link | ||
| 68 | + to={to()} | ||
| 69 | + class="inline-flex h-9 items-center justify-center whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90" | ||
| 70 | + > | ||
| 71 | + {t("errors.openStaffView")} | ||
| 72 | + </Link> | ||
| 73 | + )} | ||
| 74 | + </Show> | ||
| 75 | + <Link | ||
| 76 | + to="/" | ||
| 77 | + class={ | ||
| 78 | + alternative() | ||
| 79 | + ? "inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent" | ||
| 80 | + : "inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90" | ||
| 81 | + } | ||
| 82 | + > | ||
| 83 | + <IconHome class="mr-1 h-4 w-4" /> | ||
| 84 | + {t("common.goHome")} | ||
| 85 | + </Link> | ||
| 86 | + </div> | ||
| 33 | </div> | 87 | </div> |
| 34 | </div> | 88 | </div> |
| 35 | ); | 89 | ); |
| @@ -67,7 +121,7 @@ export function RouteGuard( | |||
| 67 | }> | 121 | }> |
| 68 | <Show when={auth.user()} fallback={<Navigate to="/login" />}> | 122 | <Show when={auth.user()} fallback={<Navigate to="/login" />}> |
| 69 | {(u) => ( | 123 | {(u) => ( |
| 70 | - <Show when={allowed(u().role)} fallback={<AccessDeniedCard />}> | 124 | + <Show when={allowed(u().role)} fallback={<AccessDeniedCard exactRole={props.exactRole} userRole={u().role} />}> |
| 71 | {props.children} | 125 | {props.children} |
| 72 | </Show> | 126 | </Show> |
| 73 | )} | 127 | )} |
src/components/layout/shell-unread-badge.test.tsxmodified+8 -4
| @@ -1,5 +1,5 @@ | |||
| 1 | import { createSignal } from "solid-js"; | 1 | import { createSignal } from "solid-js"; |
| 2 | -import { fireEvent, render, screen } from "@solidjs/testing-library"; | 2 | +import { fireEvent, render, screen, within } from "@solidjs/testing-library"; |
| 3 | import { NotificationCenter } from "@/components/layout/notification-center"; | 3 | import { NotificationCenter } from "@/components/layout/notification-center"; |
| 4 | import { ShellMessagesButton } from "@/components/layout/shell-messages-button"; | 4 | import { ShellMessagesButton } from "@/components/layout/shell-messages-button"; |
| 5 | import { PreferencesProvider } from "@/stores/preferences-context"; | 5 | import { PreferencesProvider } from "@/stores/preferences-context"; |
| @@ -49,7 +49,7 @@ function mountFeed(inbox: unknown[], unread: { items: unknown[]; total: number } | |||
| 49 | return { setMessages, setUnreadMessages }; | 49 | return { setMessages, setUnreadMessages }; |
| 50 | } | 50 | } |
| 51 | 51 | ||
| 52 | -const badges = () => Array.from(document.querySelectorAll(".bg-destructive")).map((n) => n.textContent); | 52 | +const badges = () => Array.from(document.querySelectorAll("span.bg-destructive")).map((n) => n.textContent); |
| 53 | 53 | ||
| 54 | beforeEach(() => localStorage.clear()); | 54 | beforeEach(() => localStorage.clear()); |
| 55 | afterEach(() => vi.restoreAllMocks()); | 55 | afterEach(() => vi.restoreAllMocks()); |
| @@ -72,7 +72,7 @@ test("both shell badges report the same unread count", () => { | |||
| 72 | 72 | ||
| 73 | // DEFECT 2: unlisted unread ignored dismissal, so dismiss-all left the badge | 73 | // DEFECT 2: unlisted unread ignored dismissal, so dismiss-all left the badge |
| 74 | // stuck at (total - listed) over an empty popover. | 74 | // stuck at (total - listed) over an empty popover. |
| 75 | -test("dismiss all clears the badge, a later message raises it again", () => { | 75 | +test("dismiss all clears the badge, a later message raises it again", async () => { |
| 76 | const listed = Array.from({ length: 10 }, (_, i) => msg(`m${i}`)); | 76 | const listed = Array.from({ length: 10 }, (_, i) => msg(`m${i}`)); |
| 77 | const { setUnreadMessages } = mountFeed([], { items: listed, total: 11 }); | 77 | const { setUnreadMessages } = mountFeed([], { items: listed, total: 11 }); |
| 78 | 78 | ||
| @@ -84,8 +84,12 @@ test("dismiss all clears the badge, a later message raises it again", () => { | |||
| 84 | 84 | ||
| 85 | expect(badges()).toEqual(["9+"]); | 85 | expect(badges()).toEqual(["9+"]); |
| 86 | 86 | ||
| 87 | + // Clearing everything asks first; nothing is cleared until it is confirmed. | ||
| 87 | fireEvent.click(screen.getByTitle("Clear all")); | 88 | fireEvent.click(screen.getByTitle("Clear all")); |
| 88 | - expect(badges()).toEqual([]); | 89 | + expect(badges()).toEqual(["9+"]); |
| 90 | + const dialog = await screen.findByRole("alertdialog"); | ||
| 91 | + fireEvent.click(within(dialog).getByRole("button", { name: "Clear all" })); | ||
| 92 | + await vi.waitFor(() => expect(badges()).toEqual([])); | ||
| 89 | 93 | ||
| 90 | // A genuinely new message pushes the oldest listed one off the page. | 94 | // A genuinely new message pushes the oldest listed one off the page. |
| 91 | setUnreadMessages({ ...emptyPage, items: [msg("new"), ...listed.slice(0, 9)], total: 12 }); | 95 | setUnreadMessages({ ...emptyPage, items: [msg("new"), ...listed.slice(0, 9)], total: 12 }); |
src/components/layout/theme-mode-control.tsxmodified+4 -2
| @@ -29,12 +29,14 @@ export function ThemeModeControl(props: ThemeModeControlProps) { | |||
| 29 | } | 29 | } |
| 30 | 30 | ||
| 31 | if (props.variant === "compact") { | 31 | if (props.variant === "compact") { |
| 32 | + // Icon-only, so each button carries its name; a thumb-sized target on | ||
| 33 | + // touch screens. | ||
| 32 | return ( | 34 | return ( |
| 33 | <div class="flex rounded-lg bg-muted p-0.5 dark:bg-white/8" role="group" aria-label={prefs.t("theme.toggle")}> | 35 | <div class="flex rounded-lg bg-muted p-0.5 dark:bg-white/8" role="group" aria-label={prefs.t("theme.toggle")}> |
| 34 | - <button type="button" class={cn("rounded-md p-1.5 text-muted-foreground transition-colors hover:text-foreground dark:text-white/60 dark:hover:text-white", !isDark() && "bg-background text-foreground shadow-xs dark:bg-white/12 dark:text-white")} onClick={() => selectTheme("light")} aria-pressed={!isDark()} title={lightLabel()}> | 36 | + <button type="button" class={cn("rounded-md p-1.5 text-muted-foreground transition-colors hover:text-foreground touch:p-3.5 dark:text-white/60 dark:hover:text-white", !isDark() && "bg-background text-foreground shadow-xs dark:bg-white/12 dark:text-white")} onClick={() => selectTheme("light")} aria-pressed={!isDark()} aria-label={lightLabel()} title={lightLabel()}> |
| 35 | <IconSun class="h-4 w-4" /> | 37 | <IconSun class="h-4 w-4" /> |
| 36 | </button> | 38 | </button> |
| 37 | - <button type="button" class={cn("rounded-md p-1.5 text-muted-foreground transition-colors hover:text-foreground dark:text-white/60 dark:hover:text-white", isDark() && "bg-background text-foreground shadow-xs dark:bg-white/12 dark:text-white")} onClick={() => selectTheme("dark")} aria-pressed={isDark()} title={darkLabel()}> | 39 | + <button type="button" class={cn("rounded-md p-1.5 text-muted-foreground transition-colors hover:text-foreground touch:p-3.5 dark:text-white/60 dark:hover:text-white", isDark() && "bg-background text-foreground shadow-xs dark:bg-white/12 dark:text-white")} onClick={() => selectTheme("dark")} aria-pressed={isDark()} aria-label={darkLabel()} title={darkLabel()}> |
| 38 | <IconMoon class="h-4 w-4" /> | 40 | <IconMoon class="h-4 w-4" /> |
| 39 | </button> | 41 | </button> |
| 40 | </div> | 42 | </div> |
src/components/marks/marks-report-view.tsxmodified+11 -7
| @@ -15,16 +15,11 @@ import { cn } from "@/lib/cn"; | |||
| 15 | import { examKindLabel } from "@/lib/exam-labels"; | 15 | import { examKindLabel } from "@/lib/exam-labels"; |
| 16 | import { examWeight } from "@/lib/exam-weight"; | 16 | import { examWeight } from "@/lib/exam-weight"; |
| 17 | import { useAuth } from "@/stores/auth-context"; | 17 | import { useAuth } from "@/stores/auth-context"; |
| 18 | -import { useT } from "@/stores/preferences-context"; | 18 | +import { usePreferences, useT } from "@/stores/preferences-context"; |
| 19 | +import { formatDecimal } from "@/lib/format"; | ||
| 19 | 20 | ||
| 20 | -const round = (n: number) => (Math.round(n * 100) / 100).toString(); | ||
| 21 | type MarkRow = MarksReport["courses"][number]["results"][number]; | 21 | type MarkRow = MarksReport["courses"][number]["results"][number]; |
| 22 | 22 | ||
| 23 | -function markWithGrade(mark: number | null, grade?: string | null) { | ||
| 24 | - if (mark == null) return grade ?? "—"; | ||
| 25 | - return grade ? `${round(mark)} / ${grade}` : round(mark); | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | function scoreWidth(mark: number | null): string { | 23 | function scoreWidth(mark: number | null): string { |
| 29 | return `${Math.max(0, Math.min(100, Math.round(mark ?? 0)))}%`; | 24 | return `${Math.max(0, Math.min(100, Math.round(mark ?? 0)))}%`; |
| 30 | } | 25 | } |
| @@ -34,6 +29,15 @@ const MAX_SECTIONS = 3; | |||
| 34 | 29 | ||
| 35 | export function MarksReportView(props: { report: MarksReport; compact?: boolean }) { | 30 | export function MarksReportView(props: { report: MarksReport; compact?: boolean }) { |
| 36 | const t = useT(); | 31 | const t = useT(); |
| 32 | + const { locale } = usePreferences(); | ||
| 33 | + // "68,2 · Bant 3": the grade is the school's band label, and "68,2 / 3" | ||
| 34 | + // read as a score out of 3. | ||
| 35 | + const markWithGrade = (mark: number | null, grade?: string | null) => { | ||
| 36 | + const band = grade ? t("marks.bandLabel", { grade }) : null; | ||
| 37 | + if (mark == null) return band ?? "—"; | ||
| 38 | + const value = formatDecimal(mark, locale()); | ||
| 39 | + return band ? `${value} · ${band}` : value; | ||
| 40 | + }; | ||
| 37 | const auth = useAuth(); | 41 | const auth = useAuth(); |
| 38 | // The report names each block only by its instance id, so the section's own | 42 | // The report names each block only by its instance id, so the section's own |
| 39 | // name has to be read separately: `/classes/me` for the student reading their | 43 | // name has to be read separately: `/classes/me` for the student reading their |
src/components/meals/meal-menu-card.tsxmodified+5 -3
| @@ -4,7 +4,8 @@ import type { MealMenu } from "@/api/client"; | |||
| 4 | import { Badge } from "@/components/ui/badge"; | 4 | import { Badge } from "@/components/ui/badge"; |
| 5 | import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; | 5 | import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; |
| 6 | import { IconAlert, IconUtensils } from "@/components/ui/icons"; | 6 | import { IconAlert, IconUtensils } from "@/components/ui/icons"; |
| 7 | -import { formatTry } from "@/lib/meals"; | 7 | +import { dietaryTagLabel, formatTry, mealSlotLabel } from "@/lib/meals"; |
| 8 | +import { useT } from "@/stores/preferences-context"; | ||
| 8 | 9 | ||
| 9 | export function MealMenuCard(props: { | 10 | export function MealMenuCard(props: { |
| 10 | menu: MealMenu; | 11 | menu: MealMenu; |
| @@ -18,6 +19,7 @@ export function MealMenuCard(props: { | |||
| 18 | */ | 19 | */ |
| 19 | reservationCount?: number; | 20 | reservationCount?: number; |
| 20 | }) { | 21 | }) { |
| 22 | + const t = useT(); | ||
| 21 | const total = () => props.menu.dishes.reduce((sum, dish) => sum + dish.price_minor, 0); | 23 | const total = () => props.menu.dishes.reduce((sum, dish) => sum + dish.price_minor, 0); |
| 22 | const conflicts = () => [...new Set(props.menu.dishes.flatMap((dish) => dish.conflicts))]; | 24 | const conflicts = () => [...new Set(props.menu.dishes.flatMap((dish) => dish.conflicts))]; |
| 23 | const occupancyPct = () => { | 25 | const occupancyPct = () => { |
| @@ -31,7 +33,7 @@ export function MealMenuCard(props: { | |||
| 31 | <div class="flex items-start justify-between gap-3"> | 33 | <div class="flex items-start justify-between gap-3"> |
| 32 | <div class="flex min-w-0 items-center gap-3"> | 34 | <div class="flex min-w-0 items-center gap-3"> |
| 33 | <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border-hairline bg-surface-tint"><IconUtensils class="h-5 w-5" /></span> | 35 | <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border-hairline bg-surface-tint"><IconUtensils class="h-5 w-5" /></span> |
| 34 | - <div class="min-w-0"><h2 class="truncate font-semibold text-text-strong">{props.menu.slot}</h2><time class="text-xs text-text-subtle" datetime={props.menu.date}>{props.menu.date}</time></div> | 36 | + <div class="min-w-0"><h2 class="truncate font-semibold text-text-strong">{mealSlotLabel(props.menu.slot, t)}</h2><time class="text-xs text-text-subtle" datetime={props.menu.date}>{props.menu.date}</time></div> |
| 35 | </div> | 37 | </div> |
| 36 | <span class="shrink-0 font-semibold tabular-nums">{formatTry(total(), props.locale)}</span> | 38 | <span class="shrink-0 font-semibold tabular-nums">{formatTry(total(), props.locale)}</span> |
| 37 | </div> | 39 | </div> |
| @@ -39,7 +41,7 @@ export function MealMenuCard(props: { | |||
| 39 | <div class="mt-4 flex flex-wrap gap-1.5"><For each={props.menu.dishes}>{(dish) => <Badge variant="outline">{dish.name}</Badge>}</For></div> | 41 | <div class="mt-4 flex flex-wrap gap-1.5"><For each={props.menu.dishes}>{(dish) => <Badge variant="outline">{dish.name}</Badge>}</For></div> |
| 40 | <Show when={conflicts().length > 0}> | 42 | <Show when={conflicts().length > 0}> |
| 41 | <div class="mt-3 flex items-start gap-2 rounded-xl border border-warning/50 bg-warning/10 p-2 text-xs text-warning-text"> | 43 | <div class="mt-3 flex items-start gap-2 rounded-xl border border-warning/50 bg-warning/10 p-2 text-xs text-warning-text"> |
| 42 | - <IconAlert class="mt-0.5 h-4 w-4" /><span>{props.labels.conflict}: {conflicts().join(", ")}</span> | 44 | + <IconAlert class="mt-0.5 h-4 w-4" /><span>{props.labels.conflict}: {conflicts().map((tag) => dietaryTagLabel(tag, t)).join(", ")}</span> |
| 43 | </div> | 45 | </div> |
| 44 | </Show> | 46 | </Show> |
| 45 | <Show when={occupancyPct() != null}> | 47 | <Show when={occupancyPct() != null}> |
src/components/messages/gmail-compose-box.tsxmodified+40 -4
| @@ -3,11 +3,13 @@ import { Button } from "@/components/ui/button"; | |||
| 3 | import { Input } from "@/components/ui/input"; | 3 | import { Input } from "@/components/ui/input"; |
| 4 | import { RichTextEditor } from "@/components/ui/rich-text-editor"; | 4 | import { RichTextEditor } from "@/components/ui/rich-text-editor"; |
| 5 | import { UserSearchSelect } from "@/components/users/user-search-select"; | 5 | import { UserSearchSelect } from "@/components/users/user-search-select"; |
| 6 | -import { IconSend, IconTrash, IconX } from "@/components/ui/icons"; | 6 | +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 7 | +import { IconAlert, IconSend, IconTrash, IconX } from "@/components/ui/icons"; | ||
| 7 | import { postMessage } from "@/api/messages"; | 8 | import { postMessage } from "@/api/messages"; |
| 8 | import { formatApiError } from "@/api/client"; | 9 | import { formatApiError } from "@/api/client"; |
| 9 | import { useAuth } from "@/stores/auth-context"; | 10 | import { useAuth } from "@/stores/auth-context"; |
| 10 | import { useT } from "@/stores/preferences-context"; | 11 | import { useT } from "@/stores/preferences-context"; |
| 12 | +import { suppressQuickActions } from "@/stores/quick-actions"; | ||
| 11 | 13 | ||
| 12 | interface GmailComposeBoxProps { | 14 | interface GmailComposeBoxProps { |
| 13 | open: boolean; | 15 | open: boolean; |
| @@ -26,6 +28,12 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { | |||
| 26 | const [pending, setPending] = createSignal(false); | 28 | const [pending, setPending] = createSignal(false); |
| 27 | const [error, setError] = createSignal(""); | 29 | const [error, setError] = createSignal(""); |
| 28 | 30 | ||
| 31 | + // The sheet docks at the bottom of a phone; the quick-action button would | ||
| 32 | + // float over its editor. | ||
| 33 | + createEffect(() => { | ||
| 34 | + if (props.open) suppressQuickActions(); | ||
| 35 | + }); | ||
| 36 | + | ||
| 29 | createEffect(() => { | 37 | createEffect(() => { |
| 30 | if (props.open) { | 38 | if (props.open) { |
| 31 | setRecipient(""); | 39 | setRecipient(""); |
| @@ -50,6 +58,18 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { | |||
| 50 | props.onClose(); | 58 | props.onClose(); |
| 51 | }; | 59 | }; |
| 52 | 60 | ||
| 61 | + // Closing throws the draft away, so anything typed is confirmed first. | ||
| 62 | + const [confirmDiscard, setConfirmDiscard] = createSignal(false); | ||
| 63 | + const hasDraft = () => | ||
| 64 | + !!recipient() || | ||
| 65 | + subject().trim() !== "" || | ||
| 66 | + label().trim() !== "" || | ||
| 67 | + body().replace(/<[^>]*>| /g, "").trim() !== ""; | ||
| 68 | + const requestClose = () => { | ||
| 69 | + if (hasDraft()) setConfirmDiscard(true); | ||
| 70 | + else handleClose(); | ||
| 71 | + }; | ||
| 72 | + | ||
| 53 | const handleSend = async (e: SubmitEvent) => { | 73 | const handleSend = async (e: SubmitEvent) => { |
| 54 | e.preventDefault(); | 74 | e.preventDefault(); |
| 55 | if (!recipient()) { | 75 | if (!recipient()) { |
| @@ -95,14 +115,17 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { | |||
| 95 | class="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground" | 115 | class="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground" |
| 96 | onClick={() => setIsMinimized(!isMinimized())} | 116 | onClick={() => setIsMinimized(!isMinimized())} |
| 97 | title={isMinimized() ? t("messages.expand") : t("messages.minimize")} | 117 | title={isMinimized() ? t("messages.expand") : t("messages.minimize")} |
| 118 | + aria-label={isMinimized() ? t("messages.expand") : t("messages.minimize")} | ||
| 119 | + aria-expanded={!isMinimized()} | ||
| 98 | > | 120 | > |
| 99 | - <span class="text-xs font-bold">{isMinimized() ? "□" : "—"}</span> | 121 | + <span class="text-xs font-bold" aria-hidden="true">{isMinimized() ? "□" : "—"}</span> |
| 100 | </button> | 122 | </button> |
| 101 | <button | 123 | <button |
| 102 | type="button" | 124 | type="button" |
| 103 | class="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text" | 125 | class="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text" |
| 104 | - onClick={handleClose} | 126 | + onClick={requestClose} |
| 105 | title={t("common.cancel")} | 127 | title={t("common.cancel")} |
| 128 | + aria-label={t("common.cancel")} | ||
| 106 | > | 129 | > |
| 107 | <IconX class="h-4 w-4" /> | 130 | <IconX class="h-4 w-4" /> |
| 108 | </button> | 131 | </button> |
| @@ -186,8 +209,9 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { | |||
| 186 | <button | 209 | <button |
| 187 | type="button" | 210 | type="button" |
| 188 | class="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text transition-colors" | 211 | class="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text transition-colors" |
| 189 | - onClick={handleClose} | 212 | + onClick={requestClose} |
| 190 | title={t("messages.deleteDraft")} | 213 | title={t("messages.deleteDraft")} |
| 214 | + aria-label={t("messages.deleteDraft")} | ||
| 191 | > | 215 | > |
| 192 | <IconTrash class="h-4 w-4" /> | 216 | <IconTrash class="h-4 w-4" /> |
| 193 | </button> | 217 | </button> |
| @@ -195,6 +219,18 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { | |||
| 195 | </form> | 219 | </form> |
| 196 | </Show> | 220 | </Show> |
| 197 | </div> | 221 | </div> |
| 222 | + <ConfirmDialog | ||
| 223 | + open={confirmDiscard()} | ||
| 224 | + onOpenChange={setConfirmDiscard} | ||
| 225 | + title={t("messages.discardDraftTitle")} | ||
| 226 | + summary={subject().trim() || t("messages.newMessage")} | ||
| 227 | + description={t("messages.discardDraftHint")} | ||
| 228 | + confirmLabel={t("sidePanel.discard")} | ||
| 229 | + cancelLabel={t("sidePanel.keepEditing")} | ||
| 230 | + variant="destructive" | ||
| 231 | + icon={<IconAlert class="h-4 w-4" />} | ||
| 232 | + onConfirm={handleClose} | ||
| 233 | + /> | ||
| 198 | </Show> | 234 | </Show> |
| 199 | ); | 235 | ); |
| 200 | } | 236 | } |
src/components/notes/rag-outputs-panel.tsxmodified+1 -1
| @@ -199,7 +199,7 @@ export function RagOutputsPanel(props: { | |||
| 199 | }; | 199 | }; |
| 200 | 200 | ||
| 201 | return ( | 201 | return ( |
| 202 | - <section class="space-y-3 rounded-xl border border-border-line bg-surface-base p-3 sm:p-4"> | 202 | + <section class="min-w-0 space-y-3 rounded-xl border border-border-line bg-surface-base p-3 sm:p-4"> |
| 203 | <div class="flex flex-wrap items-start justify-between gap-3"> | 203 | <div class="flex flex-wrap items-start justify-between gap-3"> |
| 204 | <div> | 204 | <div> |
| 205 | <h3 class="text-sm font-semibold">{t("courseNotes.ragTitle")}</h3> | 205 | <h3 class="text-sm font-semibold">{t("courseNotes.ragTitle")}</h3> |
src/components/rag/rag-study-panel.tsxmodified+4 -0
| @@ -23,6 +23,7 @@ import { IconChevronDown, IconMenu, IconPlus, IconX } from "@/components/ui/icon | |||
| 23 | import { cn } from "@/lib/cn"; | 23 | import { cn } from "@/lib/cn"; |
| 24 | import { scopeFromCitations } from "@/lib/rag-study-scope"; | 24 | import { scopeFromCitations } from "@/lib/rag-study-scope"; |
| 25 | import { usePreferences } from "@/stores/preferences-context"; | 25 | import { usePreferences } from "@/stores/preferences-context"; |
| 26 | +import { suppressQuickActions } from "@/stores/quick-actions"; | ||
| 26 | 27 | ||
| 27 | const POLL_INTERVAL_MS = 2000; | 28 | const POLL_INTERVAL_MS = 2000; |
| 28 | 29 | ||
| @@ -33,6 +34,9 @@ const POLL_INTERVAL_MS = 2000; | |||
| 33 | * own general chat on `/chatbot`; this is the grounded one. | 34 | * own general chat on `/chatbot`; this is the grounded one. |
| 34 | */ | 35 | */ |
| 35 | export function RagStudyPanel() { | 36 | export function RagStudyPanel() { |
| 37 | + // The page is a docked composer; the phone quick-action button would sit | ||
| 38 | + // on its send button. | ||
| 39 | + suppressQuickActions(); | ||
| 36 | const { locale } = usePreferences(); | 40 | const { locale } = usePreferences(); |
| 37 | const copy = () => ragCopy(locale()); | 41 | const copy = () => ragCopy(locale()); |
| 38 | const [threadId, setThreadId] = createSignal<string | undefined>(); | 42 | const [threadId, setThreadId] = createSignal<string | undefined>(); |
src/components/system/not-found-page.tsxmodified+1 -1
| @@ -15,7 +15,7 @@ export function NotFoundPage() { | |||
| 15 | </div> | 15 | </div> |
| 16 | <div class="space-y-2"> | 16 | <div class="space-y-2"> |
| 17 | <p class="text-4xl font-semibold tracking-tight text-text-strong">404</p> | 17 | <p class="text-4xl font-semibold tracking-tight text-text-strong">404</p> |
| 18 | - <p class="text-base font-semibold text-text-strong">{t("common.notFound")}</p> | 18 | + <h1 class="text-base font-semibold text-text-strong">{t("common.notFound")}</h1> |
| 19 | <p class="text-sm leading-[21px] text-text-subtle">{t("errors.notFoundDescription")}</p> | 19 | <p class="text-sm leading-[21px] text-text-subtle">{t("errors.notFoundDescription")}</p> |
| 20 | </div> | 20 | </div> |
| 21 | <div class="flex items-center justify-center gap-2 pt-1"> | 21 | <div class="flex items-center justify-center gap-2 pt-1"> |
src/components/ui/badge.tsxmodified+1 -1
| @@ -30,7 +30,7 @@ export type BadgeProps = ParentProps< | |||
| 30 | export function Badge(props: BadgeProps) { | 30 | export function Badge(props: BadgeProps) { |
| 31 | const [local, rest] = splitProps(props, ["class", "variant", "children"]); | 31 | const [local, rest] = splitProps(props, ["class", "variant", "children"]); |
| 32 | return ( | 32 | return ( |
| 33 | - <div class={cn(badgeVariants({ variant: local.variant }), local.class)} {...rest}> | 33 | + <div data-slot="badge" class={cn(badgeVariants({ variant: local.variant }), local.class)} {...rest}> |
| 34 | {local.children} | 34 | {local.children} |
| 35 | </div> | 35 | </div> |
| 36 | ); | 36 | ); |
src/components/ui/chart-heatmap.tsxmodified+40 -6
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { For, Show, createMemo, type Component } from "solid-js"; | 1 | +import { For, Show, createMemo, onCleanup, type Component } from "solid-js"; |
| 2 | import { cn } from "@/lib/cn"; | 2 | import { cn } from "@/lib/cn"; |
| 3 | import { usePreferences, useT } from "@/stores/preferences-context"; | 3 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 4 | import { EmptyInline } from "@/components/ui/empty-inline"; | 4 | import { EmptyInline } from "@/components/ui/empty-inline"; |
| @@ -29,6 +29,8 @@ export type ChartHeatmapProps = { | |||
| 29 | }; | 29 | }; |
| 30 | 30 | ||
| 31 | const DEFAULT_WEEKS = 26; | 31 | const DEFAULT_WEEKS = 26; |
| 32 | +/** Columns a month label needs clear of the next one. */ | ||
| 33 | +const MONTH_LABEL_SPAN = 3; | ||
| 32 | 34 | ||
| 33 | /** Local midnight for the day containing `ms` — DST-safe, unlike `ms - ms % DAY_MS`. */ | 35 | /** Local midnight for the day containing `ms` — DST-safe, unlike `ms - ms % DAY_MS`. */ |
| 34 | function startOfDay(ms: number): number { | 36 | function startOfDay(ms: number): number { |
| @@ -114,16 +116,26 @@ export const ChartHeatmap: Component<ChartHeatmapProps> = (props) => { | |||
| 114 | ); | 116 | ); |
| 115 | 117 | ||
| 116 | // A month label sits above the first column whose Monday opens a new month. | 118 | // A month label sits above the first column whose Monday opens a new month. |
| 117 | - const monthLabels = createMemo(() => | 119 | + // A label runs wider than its column, so one whose next label starts within |
| 118 | - columns().map((week, index) => { | 120 | + // MONTH_LABEL_SPAN columns is dropped — otherwise the range's opening month |
| 121 | + // and the next one print over each other ("MaNis"). | ||
| 122 | + const monthLabels = createMemo(() => { | ||
| 123 | + const labels = columns().map((week, index) => { | ||
| 119 | const monday = new Date(week[0]); | 124 | const monday = new Date(week[0]); |
| 120 | if (index > 0) { | 125 | if (index > 0) { |
| 121 | const previous = new Date(columns()[index - 1][0]); | 126 | const previous = new Date(columns()[index - 1][0]); |
| 122 | if (previous.getMonth() === monday.getMonth()) return ""; | 127 | if (previous.getMonth() === monday.getMonth()) return ""; |
| 123 | } | 128 | } |
| 124 | return monthFormat().format(monday); | 129 | return monthFormat().format(monday); |
| 125 | - }), | 130 | + }); |
| 126 | - ); | 131 | + let next = Number.POSITIVE_INFINITY; |
| 132 | + for (let index = labels.length - 1; index >= 0; index -= 1) { | ||
| 133 | + if (!labels[index]) continue; | ||
| 134 | + if (next - index < MONTH_LABEL_SPAN) labels[index] = ""; | ||
| 135 | + else next = index; | ||
| 136 | + } | ||
| 137 | + return labels; | ||
| 138 | + }); | ||
| 127 | 139 | ||
| 128 | // Monday / Wednesday / Friday only — the full seven would not fit the gutter. | 140 | // Monday / Wednesday / Friday only — the full seven would not fit the gutter. |
| 129 | const weekdayLabels = createMemo(() => { | 141 | const weekdayLabels = createMemo(() => { |
| @@ -156,15 +168,37 @@ export const ChartHeatmap: Component<ChartHeatmapProps> = (props) => { | |||
| 156 | it scrolls instead of shrinking cells past legibility. */} | 168 | it scrolls instead of shrinking cells past legibility. */} |
| 157 | {/* `px-1` keeps today's focus ring off the scroll container's clip | 169 | {/* `px-1` keeps today's focus ring off the scroll container's clip |
| 158 | edge, which otherwise shaves the last column's cells in half. */} | 170 | edge, which otherwise shaves the last column's cells in half. */} |
| 171 | + {/* Where it scrolls (a phone), it opens on the newest weeks — the | ||
| 172 | + right edge — rather than on the oldest. */} | ||
| 159 | <div class="overflow-x-auto px-1 pb-1"> | 173 | <div class="overflow-x-auto px-1 pb-1"> |
| 160 | <div | 174 | <div |
| 175 | + ref={(grid) => { | ||
| 176 | + // Re-pinned on every resize while the page settles (under | ||
| 177 | + // Suspense the node is built detached, and the card widens as | ||
| 178 | + // the layout fills in), until the user scrolls it themselves. | ||
| 179 | + if (typeof ResizeObserver === "undefined") return; | ||
| 180 | + let pinned = true; | ||
| 181 | + const release = () => { | ||
| 182 | + pinned = false; | ||
| 183 | + }; | ||
| 184 | + const observer = new ResizeObserver(() => { | ||
| 185 | + const scroller = grid.parentElement; | ||
| 186 | + if (pinned && scroller) scroller.scrollLeft = scroller.scrollWidth; | ||
| 187 | + }); | ||
| 188 | + observer.observe(grid); | ||
| 189 | + // The grid holds its min-width while the card around it shrinks, | ||
| 190 | + // so the scroller's own size matters as much. | ||
| 191 | + queueMicrotask(() => grid.parentElement && observer.observe(grid.parentElement)); | ||
| 192 | + for (const type of ["pointerdown", "wheel", "keydown"]) grid.addEventListener(type, release, { passive: true }); | ||
| 193 | + onCleanup(() => observer.disconnect()); | ||
| 194 | + }} | ||
| 161 | class="grid min-w-[460px] gap-1" | 195 | class="grid min-w-[460px] gap-1" |
| 162 | style={{ "grid-template-columns": `auto repeat(${weeks()}, minmax(0, 1fr))` }} | 196 | style={{ "grid-template-columns": `auto repeat(${weeks()}, minmax(0, 1fr))` }} |
| 163 | > | 197 | > |
| 164 | <span aria-hidden="true" /> | 198 | <span aria-hidden="true" /> |
| 165 | <For each={monthLabels()}> | 199 | <For each={monthLabels()}> |
| 166 | {(label) => ( | 200 | {(label) => ( |
| 167 | - <span class="text-[11px] leading-none text-muted-foreground">{label}</span> | 201 | + <span class="whitespace-nowrap text-[11px] leading-none text-muted-foreground">{label}</span> |
| 168 | )} | 202 | )} |
| 169 | </For> | 203 | </For> |
| 170 | 204 | ||
src/components/ui/combobox.tsxmodified+9 -2
| @@ -3,6 +3,7 @@ import type { ComponentProps, ValidComponent } from "solid-js"; | |||
| 3 | import { splitProps } from "solid-js"; | 3 | import { splitProps } from "solid-js"; |
| 4 | import { IconCheck, IconChevronDown } from "@/components/ui/icons"; | 4 | import { IconCheck, IconChevronDown } from "@/components/ui/icons"; |
| 5 | import { cn } from "@/lib/cn"; | 5 | import { cn } from "@/lib/cn"; |
| 6 | +import { useT } from "@/stores/preferences-context"; | ||
| 6 | 7 | ||
| 7 | export const Combobox = ComboboxPrimitive; | 8 | export const Combobox = ComboboxPrimitive; |
| 8 | export const ComboboxItemLabel = ComboboxPrimitive.ItemLabel; | 9 | export const ComboboxItemLabel = ComboboxPrimitive.ItemLabel; |
| @@ -42,10 +43,13 @@ export function ComboboxInput<T extends ValidComponent = "input">( | |||
| 42 | export function ComboboxTrigger<T extends ValidComponent = "button">( | 43 | export function ComboboxTrigger<T extends ValidComponent = "button">( |
| 43 | props: ComponentProps<typeof ComboboxPrimitive.Trigger<T>>, | 44 | props: ComponentProps<typeof ComboboxPrimitive.Trigger<T>>, |
| 44 | ) { | 45 | ) { |
| 46 | + const t = useT(); | ||
| 45 | const [local, rest] = splitProps(props as ComponentProps<typeof ComboboxPrimitive.Trigger>, ["class"]); | 47 | const [local, rest] = splitProps(props as ComponentProps<typeof ComboboxPrimitive.Trigger>, ["class"]); |
| 46 | return ( | 48 | return ( |
| 47 | <ComboboxPrimitive.Trigger | 49 | <ComboboxPrimitive.Trigger |
| 48 | class={cn("flex h-full shrink-0 items-center pr-3 pl-1 text-muted-foreground/70 outline-hidden", local.class)} | 50 | class={cn("flex h-full shrink-0 items-center pr-3 pl-1 text-muted-foreground/70 outline-hidden", local.class)} |
| 51 | + // Kobalte's built-in name is an English "Show suggestions". | ||
| 52 | + aria-label={t("combobox.showSuggestions")} | ||
| 49 | {...rest} | 53 | {...rest} |
| 50 | > | 54 | > |
| 51 | <ComboboxPrimitive.Icon> | 55 | <ComboboxPrimitive.Icon> |
| @@ -62,11 +66,14 @@ export function ComboboxContent<T extends ValidComponent = "div">( | |||
| 62 | "class", | 66 | "class", |
| 63 | "children", | 67 | "children", |
| 64 | ]); | 68 | ]); |
| 69 | + // Capped at the viewport: sized by its longest option, the list otherwise | ||
| 70 | + // outgrows a phone screen and drags the whole page sideways. Long options | ||
| 71 | + // wrap instead (ComboboxItem). | ||
| 65 | return ( | 72 | return ( |
| 66 | <ComboboxPrimitive.Portal> | 73 | <ComboboxPrimitive.Portal> |
| 67 | <ComboboxPrimitive.Content | 74 | <ComboboxPrimitive.Content |
| 68 | class={cn( | 75 | class={cn( |
| 69 | - "z-[70] mt-1.5 max-h-72 min-w-(--kb-popper-anchor-width) overflow-hidden rounded-md border border-border/80 bg-popover p-1 text-popover-foreground shadow-xl shadow-black/10 outline-hidden", | 76 | + "z-[70] mt-1.5 max-h-72 min-w-(--kb-popper-anchor-width) max-w-[calc(100vw-1rem)] overflow-hidden rounded-md border border-border/80 bg-popover p-1 text-popover-foreground shadow-xl shadow-black/10 outline-hidden", |
| 70 | "origin-(--kb-combobox-content-transform-origin) animate-in fade-in-0 zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", | 77 | "origin-(--kb-combobox-content-transform-origin) animate-in fade-in-0 zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", |
| 71 | local.class, | 78 | local.class, |
| 72 | )} | 79 | )} |
| @@ -86,7 +93,7 @@ export function ComboboxItem<T extends ValidComponent = "li">( | |||
| 86 | return ( | 93 | return ( |
| 87 | <ComboboxPrimitive.Item | 94 | <ComboboxPrimitive.Item |
| 88 | class={cn( | 95 | class={cn( |
| 89 | - "relative flex cursor-pointer select-none items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors", | 96 | + "relative flex cursor-pointer select-none items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors [&>:first-child]:min-w-0 [&>:first-child]:break-words", |
| 90 | "data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-40", | 97 | "data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-40", |
| 91 | local.class, | 98 | local.class, |
| 92 | )} | 99 | )} |
src/components/ui/data-table-search.tsxmodified+3 -3
| @@ -49,9 +49,9 @@ export function DataTableSearch(props: DataTableSearchProps) { | |||
| 49 | }} | 49 | }} |
| 50 | placeholder={props.placeholder ?? t("common.search")} | 50 | placeholder={props.placeholder ?? t("common.search")} |
| 51 | aria-describedby={props.hint ? hintId : undefined} | 51 | aria-describedby={props.hint ? hintId : undefined} |
| 52 | - // Phones get a touch-sized box at 16px: below that iOS Safari zooms | 52 | + // Touch screens get a touch-sized box at 16px (index.css): below that |
| 53 | - // the page into a focused field. Compact from `sm` up. | 53 | + // iOS Safari zooms the page into a focused field. Compact otherwise. |
| 54 | - class={cn("h-10 rounded-lg bg-muted/40 text-base sm:h-8 sm:text-[13px] md:text-[13px]", props.value ? "pl-9 pr-8" : "pl-9")} | 54 | + class={cn("h-10 rounded-lg bg-muted/40 text-base sm:h-8 sm:text-[13px] md:text-[13px] touch:h-10", props.value ? "pl-9 pr-8" : "pl-9")} |
| 55 | /> | 55 | /> |
| 56 | <Show when={props.value}> | 56 | <Show when={props.value}> |
| 57 | <button | 57 | <button |
src/components/ui/data-table-view-menu.tsxmodified+1 -1
| @@ -26,7 +26,7 @@ export function DataTableViewMenu(props: DataTableViewMenuProps) { | |||
| 26 | 26 | ||
| 27 | return ( | 27 | return ( |
| 28 | <DropdownMenu placement="bottom-end" gutter={6}> | 28 | <DropdownMenu placement="bottom-end" gutter={6}> |
| 29 | - <DropdownMenuTrigger class="ml-auto inline-flex h-8 items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-border/70 bg-muted/40 px-3 text-[13px] font-medium transition-all hover:bg-muted active:scale-[0.98] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"> | 29 | + <DropdownMenuTrigger class="ml-auto inline-flex h-8 touch:h-10 items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-border/70 bg-muted/40 px-3 text-[13px] font-medium transition-all hover:bg-muted active:scale-[0.98] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"> |
| 30 | {t("common.columns")} | 30 | {t("common.columns")} |
| 31 | <IconChevronDown class="h-3.5 w-3.5 opacity-60" /> | 31 | <IconChevronDown class="h-3.5 w-3.5 opacity-60" /> |
| 32 | </DropdownMenuTrigger> | 32 | </DropdownMenuTrigger> |
src/components/ui/data-table.test.tsxmodified+59 -1
| @@ -1,3 +1,4 @@ | |||
| 1 | +import { createSignal } from "solid-js"; | ||
| 1 | import { fireEvent, render, screen, within } from "@solidjs/testing-library"; | 2 | import { fireEvent, render, screen, within } from "@solidjs/testing-library"; |
| 2 | import type { ColumnDef } from "@tanstack/solid-table"; | 3 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 3 | import { DataTable } from "@/components/ui/data-table"; | 4 | import { DataTable } from "@/components/ui/data-table"; |
| @@ -190,7 +191,7 @@ test("a search that matches nothing says so and clears back to the list", () => | |||
| 190 | 191 | ||
| 191 | fireEvent.input(screen.getByRole("textbox"), { target: { value: "zzz" } }); | 192 | fireEvent.input(screen.getByRole("textbox"), { target: { value: "zzz" } }); |
| 192 | expect(screen.queryByText("No people yet.")).toBeNull(); | 193 | expect(screen.queryByText("No people yet.")).toBeNull(); |
| 193 | - expect(screen.getByText(/Nothing matches|eşleşen kayıt yok/)).toBeTruthy(); | 194 | + expect(screen.getByText(/No results for “zzz”|“zzz” için sonuç yok/)).toBeTruthy(); |
| 194 | 195 | ||
| 195 | fireEvent.click(within(screen.getByRole("table")).getByRole("button", { name: /Clear search|Aramayı temizle/ })); | 196 | fireEvent.click(within(screen.getByRole("table")).getByRole("button", { name: /Clear search|Aramayı temizle/ })); |
| 196 | expect(screen.getByText("Ada")).toBeTruthy(); | 197 | expect(screen.getByText("Ada")).toBeTruthy(); |
| @@ -249,3 +250,60 @@ test("on a phone-width screen rows render as labelled cards instead of a sideway | |||
| 249 | expect(onRowClick).toHaveBeenCalledOnce(); | 250 | expect(onRowClick).toHaveBeenCalledOnce(); |
| 250 | vi.unstubAllGlobals(); | 251 | vi.unstubAllGlobals(); |
| 251 | }); | 252 | }); |
| 253 | + | ||
| 254 | +test("sortable headers expose their order through aria-sort", () => { | ||
| 255 | + const sortable: ColumnDef<Row>[] = [ | ||
| 256 | + { accessorKey: "name", header: "Name" }, | ||
| 257 | + { accessorKey: "role", header: "Role", enableSorting: false }, | ||
| 258 | + ]; | ||
| 259 | + render(() => ( | ||
| 260 | + <PreferencesProvider> | ||
| 261 | + <DataTable columns={sortable} data={[{ name: "Ada", role: "a" }, { name: "Bo", role: "b" }]} enableColumnVisibility={false} /> | ||
| 262 | + </PreferencesProvider> | ||
| 263 | + )); | ||
| 264 | + const [nameHeader, roleHeader] = screen.getAllByRole("columnheader"); | ||
| 265 | + expect(nameHeader?.getAttribute("aria-sort")).toBe("none"); | ||
| 266 | + expect(roleHeader?.hasAttribute("aria-sort")).toBe(false); | ||
| 267 | + fireEvent.click(within(nameHeader!).getByRole("button")); | ||
| 268 | + expect(nameHeader?.getAttribute("aria-sort")).toBe("ascending"); | ||
| 269 | + fireEvent.click(within(nameHeader!).getByRole("button")); | ||
| 270 | + expect(nameHeader?.getAttribute("aria-sort")).toBe("descending"); | ||
| 271 | +}); | ||
| 272 | + | ||
| 273 | +test("an empty list narrowed by the caller's filters offers to clear them", () => { | ||
| 274 | + const onClearFilters = vi.fn(); | ||
| 275 | + render(() => ( | ||
| 276 | + <PreferencesProvider> | ||
| 277 | + <DataTable columns={columns} data={[]} empty="No people yet." enableColumnVisibility={false} filtersActive onClearFilters={onClearFilters} /> | ||
| 278 | + </PreferencesProvider> | ||
| 279 | + )); | ||
| 280 | + expect(screen.queryByText("No people yet.")).toBeNull(); | ||
| 281 | + fireEvent.click(screen.getByRole("button", { name: /Clear filters|Filtreleri temizle/ })); | ||
| 282 | + expect(onClearFilters).toHaveBeenCalledOnce(); | ||
| 283 | +}); | ||
| 284 | + | ||
| 285 | +test("the next page holds when the caller hands over a fresh data array", async () => { | ||
| 286 | + const [tick, setTick] = createSignal(0); | ||
| 287 | + const people = Array.from({ length: 12 }, (_, i) => ({ name: `P${String(i).padStart(2, "0")}` })); | ||
| 288 | + render(() => ( | ||
| 289 | + <PreferencesProvider> | ||
| 290 | + {/* A new array on every read, like a page that maps rows inline. */} | ||
| 291 | + <DataTable columns={[{ accessorKey: "name", header: "Name" }]} data={(tick(), people.map((row) => ({ ...row })))} enableColumnVisibility={false} /> | ||
| 292 | + </PreferencesProvider> | ||
| 293 | + )); | ||
| 294 | + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); | ||
| 295 | + expect(screen.getByText("P10")).toBeTruthy(); | ||
| 296 | + setTick(1); | ||
| 297 | + expect(screen.getByText("P10")).toBeTruthy(); | ||
| 298 | + expect(screen.queryByText("P00")).toBeNull(); | ||
| 299 | +}); | ||
| 300 | + | ||
| 301 | +test("a toolbar holding only the column menu is not boxed", () => { | ||
| 302 | + const { container } = render(() => ( | ||
| 303 | + <PreferencesProvider> | ||
| 304 | + <DataTable columns={[{ accessorKey: "name", header: "Name" }, { accessorKey: "role", header: "Role" }]} data={[{ name: "Ada", role: "a" }]} /> | ||
| 305 | + </PreferencesProvider> | ||
| 306 | + )); | ||
| 307 | + const toolbar = container.querySelector(".space-y-3 > div"); | ||
| 308 | + expect(toolbar?.className).not.toContain("rounded-xl"); | ||
| 309 | +}); | ||
src/components/ui/data-table.tsxmodified+129 -30
| @@ -25,6 +25,7 @@ import { cn } from "@/lib/cn"; | |||
| 25 | import { createMediaQuery } from "@/lib/create-media-query"; | 25 | import { createMediaQuery } from "@/lib/create-media-query"; |
| 26 | import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size"; | 26 | import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size"; |
| 27 | import { createTablePreferences } from "@/lib/table-preferences"; | 27 | import { createTablePreferences } from "@/lib/table-preferences"; |
| 28 | +import { createUrlPageIndex, createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state"; | ||
| 28 | import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; | 29 | import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; |
| 29 | import { useT } from "@/stores/preferences-context"; | 30 | import { useT } from "@/stores/preferences-context"; |
| 30 | 31 | ||
| @@ -89,6 +90,22 @@ export type DataTableProps<TData, TValue = unknown> = { | |||
| 89 | storageKey?: string; | 90 | storageKey?: string; |
| 90 | /** Split the title/toolbar and table into the same inner surfaces as detail pages. */ | 91 | /** Split the title/toolbar and table into the same inner surfaces as detail pages. */ |
| 91 | surfaceSections?: boolean; | 92 | surfaceSections?: boolean; |
| 93 | + /** | ||
| 94 | + * Keep search, page and sort in the URL (`?q=`, `?page=`, `?sort=`) so Back | ||
| 95 | + * and a reload restore them. A string prefixes the keys (`?roster.q=`) for | ||
| 96 | + * a page with more than one list. Needs a router; only the search the table | ||
| 97 | + * owns (`searchPredicate` / `filterColumn`) is stored — a caller passing | ||
| 98 | + * `searchValue` / `onSearchInput` keeps its own. | ||
| 99 | + */ | ||
| 100 | + urlState?: boolean | string; | ||
| 101 | + /** Back to page one whenever this changes — pass the caller's own filters. */ | ||
| 102 | + pageResetKey?: unknown; | ||
| 103 | + /** | ||
| 104 | + * The caller's own filters narrow the list. An empty result then offers | ||
| 105 | + * `onClearFilters` instead of the "nothing here yet" message. | ||
| 106 | + */ | ||
| 107 | + filtersActive?: boolean; | ||
| 108 | + onClearFilters?: () => void; | ||
| 92 | }; | 109 | }; |
| 93 | 110 | ||
| 94 | const resolveUpdater = <T,>(updater: Updater<T>, old: T): T => | 111 | const resolveUpdater = <T,>(updater: Updater<T>, old: T): T => |
| @@ -100,16 +117,52 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 100 | const t = useT(); | 117 | const t = useT(); |
| 101 | const paginationEnabled = props.enablePagination ?? true; | 118 | const paginationEnabled = props.enablePagination ?? true; |
| 102 | const prefs = createTablePreferences(props.storageKey); | 119 | const prefs = createTablePreferences(props.storageKey); |
| 103 | - const [sorting, setSorting] = createSignal<SortingState>([]); | 120 | + // Read once: a table either keeps its state in the URL or it does not. |
| 104 | - const [columnFilters, setColumnFilters] = createSignal<ColumnFiltersState>([]); | 121 | + const urlKeys = props.urlState |
| 122 | + ? listParamKeys(typeof props.urlState === "string" ? props.urlState : undefined) | ||
| 123 | + : null; | ||
| 124 | + const [sorting, setSortingState] = urlKeys | ||
| 125 | + ? createUrlParam<SortingState>(urlKeys.sort, { parse: decodeSort, serialize: encodeSort }) | ||
| 126 | + : createSignal<SortingState>([]); | ||
| 127 | + const [otherColumnFilters, setOtherColumnFilters] = createSignal<ColumnFiltersState>([]); | ||
| 105 | const clientPageSize = createResponsivePageSize(props.pageSize ?? 10); | 128 | const clientPageSize = createResponsivePageSize(props.pageSize ?? 10); |
| 106 | - const [clientPageIndex, setClientPageIndex] = createSignal(0); | 129 | + const [clientPageIndex, setClientPageIndex] = urlKeys && !props.manualPagination |
| 130 | + ? createUrlPageIndex(urlKeys.page) | ||
| 131 | + : createSignal(0); | ||
| 107 | const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() }); | 132 | const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() }); |
| 108 | // A page index means nothing once the page size changes under it (a phone | 133 | // A page index means nothing once the page size changes under it (a phone |
| 109 | // rotated, a window narrowed): start over rather than land mid-list. | 134 | // rotated, a window narrowed): start over rather than land mid-list. |
| 110 | createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true })); | 135 | createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true })); |
| 111 | - const [search, setSearch] = createSignal(""); | 136 | + createEffect(on(() => props.pageResetKey, () => setClientPageIndex(0), { defer: true })); |
| 137 | + // The search box's text when the table owns it — the `searchPredicate` | ||
| 138 | + // query, or the `filterColumn` filter value. | ||
| 139 | + const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput | ||
| 140 | + ? createUrlString(urlKeys.q) | ||
| 141 | + : createSignal(""); | ||
| 112 | const searchValue = () => props.searchValue ?? search(); | 142 | const searchValue = () => props.searchValue ?? search(); |
| 143 | + // The filterColumn filter is the search signal; any other column filter | ||
| 144 | + // stays local. | ||
| 145 | + const columnFilters = (): ColumnFiltersState => { | ||
| 146 | + const column = props.filterColumn; | ||
| 147 | + const query = search(); | ||
| 148 | + if (!column || props.searchPredicate || props.onSearchInput || !query) return otherColumnFilters(); | ||
| 149 | + return [...otherColumnFilters().filter((filter) => filter.id !== column), { id: column, value: query }]; | ||
| 150 | + }; | ||
| 151 | + const setColumnFilters = (next: ColumnFiltersState) => { | ||
| 152 | + const column = props.filterColumn; | ||
| 153 | + if (!column || props.searchPredicate || props.onSearchInput) { | ||
| 154 | + setOtherColumnFilters(next); | ||
| 155 | + return; | ||
| 156 | + } | ||
| 157 | + const own = next.find((filter) => filter.id === column); | ||
| 158 | + setSearch(typeof own?.value === "string" ? own.value : ""); | ||
| 159 | + setOtherColumnFilters(next.filter((filter) => filter.id !== column)); | ||
| 160 | + }; | ||
| 161 | + // A sort order reshuffles every page: start from the first one. | ||
| 162 | + const setSorting = (next: SortingState) => { | ||
| 163 | + setSortingState(next); | ||
| 164 | + setClientPageIndex(0); | ||
| 165 | + }; | ||
| 113 | // Sorting is client-side only, and the backend takes no sort parameter: on | 166 | // Sorting is client-side only, and the backend takes no sort parameter: on |
| 114 | // a server-paged table it would reorder the visible page alone while the | 167 | // a server-paged table it would reorder the visible page alone while the |
| 115 | // header claimed the whole list. Off there unless a caller opts in. | 168 | // header claimed the whole list. Off there unless a caller opts in. |
| @@ -136,8 +189,13 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 136 | getSortedRowModel: getSortedRowModel(), | 189 | getSortedRowModel: getSortedRowModel(), |
| 137 | getFilteredRowModel: getFilteredRowModel(), | 190 | getFilteredRowModel: getFilteredRowModel(), |
| 138 | ...(paginationEnabled && !props.manualPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}), | 191 | ...(paginationEnabled && !props.manualPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}), |
| 139 | - onSortingChange: setSorting, | 192 | + // The page index is ours, not the table's: an automatic reset on every |
| 140 | - onColumnFiltersChange: setColumnFilters, | 193 | + // new `data` array sent a page that rebuilds its rows on each read (a |
| 194 | + // clock tick, a fresh map) straight back to page one on "Sonraki", and | ||
| 195 | + // would wipe a page restored from the URL on the first refetch. | ||
| 196 | + autoResetPageIndex: false, | ||
| 197 | + onSortingChange: (updater) => setSorting(resolveUpdater(updater, sorting())), | ||
| 198 | + onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())), | ||
| 141 | onColumnVisibilityChange: (updater) => | 199 | onColumnVisibilityChange: (updater) => |
| 142 | prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), | 200 | prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), |
| 143 | onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex), | 201 | onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex), |
| @@ -198,12 +256,17 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 198 | (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()), | 256 | (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()), |
| 199 | 0, | 257 | 0, |
| 200 | ); | 258 | ); |
| 201 | - const actionColumnsWidth = () => | 259 | + // The table scrolls sideways only once the frame is narrower than every |
| 260 | + // column at its floor: a column that declares `minSize` may shrink to it, | ||
| 261 | + // one that does not keeps its `size`. Sizing the table by `size` alone | ||
| 262 | + // made a tablet scroll a table that fit, and slid the last data column | ||
| 263 | + // under the sticky action column. | ||
| 264 | + const minTableWidth = () => | ||
| 202 | table.getVisibleLeafColumns().reduce( | 265 | table.getVisibleLeafColumns().reduce( |
| 203 | - (total, column) => total + (stickyRightLocked(column.id) ? 110 : 0), | 266 | + (total, column) => |
| 267 | + total + (stickyRightLocked(column.id) ? 110 : Math.min(column.getSize(), column.columnDef.minSize ?? column.getSize())), | ||
| 204 | 0, | 268 | 0, |
| 205 | ); | 269 | ); |
| 206 | - const tableWidth = () => dataColumnsWidth() + actionColumnsWidth(); | ||
| 207 | const columnWidth = (column: Column<TData, unknown>) => { | 270 | const columnWidth = (column: Column<TData, unknown>) => { |
| 208 | if (stickyRightLocked(column.id)) return "110px"; | 271 | if (stickyRightLocked(column.id)) return "110px"; |
| 209 | const total = dataColumnsWidth(); | 272 | const total = dataColumnsWidth(); |
| @@ -223,23 +286,35 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 223 | const sectioned = () => props.surfaceSections !== false; | 286 | const sectioned = () => props.surfaceSections !== false; |
| 224 | const showHeader = () => false; | 287 | const showHeader = () => false; |
| 225 | const showToolbar = () => showSearch() || props.filters != null || showColumnMenu() || props.actions != null; | 288 | const showToolbar = () => showSearch() || props.filters != null || showColumnMenu() || props.actions != null; |
| 289 | + // A lone "Sütunlar" button does not need a card of its own: a full-width | ||
| 290 | + // box with one button at its far end only adds a layer (a third nested box | ||
| 291 | + // inside a detail tab). It sits bare at the right edge instead. | ||
| 292 | + const columnMenuOnly = () => showColumnMenu() && !showSearch() && props.filters == null && props.actions == null; | ||
| 226 | const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); | 293 | const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); |
| 227 | const pageIndex = () => props.manualPagination?.pageIndex ?? table.getState().pagination.pageIndex; | 294 | const pageIndex = () => props.manualPagination?.pageIndex ?? table.getState().pagination.pageIndex; |
| 228 | const pageSize = () => props.manualPagination?.pageSize ?? table.getState().pagination.pageSize; | 295 | const pageSize = () => props.manualPagination?.pageSize ?? table.getState().pagination.pageSize; |
| 229 | const totalRows = () => props.manualPagination?.total ?? table.getFilteredRowModel().rows.length; | 296 | const totalRows = () => props.manualPagination?.total ?? table.getFilteredRowModel().rows.length; |
| 230 | const setPageIndex = (next: number) => { | 297 | const setPageIndex = (next: number) => { |
| 231 | if (props.manualPagination) props.manualPagination.onPageChange(next); | 298 | if (props.manualPagination) props.manualPagination.onPageChange(next); |
| 232 | - else table.setPageIndex(next); | 299 | + else setClientPageIndex(next); |
| 233 | }; | 300 | }; |
| 301 | + // A page past the end — rows deleted, a filter narrowed the list, a stale | ||
| 302 | + // `?page=` — slides back to the last page there is. Only once rows exist: | ||
| 303 | + // before the data arrives every page is "past the end". | ||
| 304 | + createEffect(() => { | ||
| 305 | + if (props.manualPagination || !paginationEnabled) return; | ||
| 306 | + const rows = table.getFilteredRowModel().rows.length; | ||
| 307 | + if (rows === 0) return; | ||
| 308 | + const last = Math.max(0, Math.ceil(rows / clientPageSize()) - 1); | ||
| 309 | + if (clientPageIndex() > last) setClientPageIndex(last); | ||
| 310 | + }); | ||
| 234 | const searchFieldValue = () => { | 311 | const searchFieldValue = () => { |
| 235 | - if (props.onSearchInput || props.searchPredicate) return searchValue(); | 312 | + if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue(); |
| 236 | - if (props.filterColumn) return (table.getColumn(props.filterColumn)?.getFilterValue() as string) ?? ""; | ||
| 237 | return ""; | 313 | return ""; |
| 238 | }; | 314 | }; |
| 239 | const handleSearch = (value: string) => { | 315 | const handleSearch = (value: string) => { |
| 240 | if (props.onSearchInput) props.onSearchInput(value); | 316 | if (props.onSearchInput) props.onSearchInput(value); |
| 241 | - else if (props.searchPredicate) setSearch(value); | 317 | + else setSearch(value); |
| 242 | - else if (props.filterColumn) table.getColumn(props.filterColumn)?.setFilterValue(value); | ||
| 243 | setPageIndex(0); | 318 | setPageIndex(0); |
| 244 | }; | 319 | }; |
| 245 | const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { | 320 | const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { |
| @@ -247,10 +322,17 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 247 | const interactive = target.closest("button,a,input,select,textarea,[role='button']"); | 322 | const interactive = target.closest("button,a,input,select,textarea,[role='button']"); |
| 248 | return interactive != null && interactive !== row; | 323 | return interactive != null && interactive !== row; |
| 249 | }; | 324 | }; |
| 250 | - // A search that matches nothing is not an empty list: say so and offer the way back. | 325 | + // A search or filter that matches nothing is not an empty list: say what |
| 326 | + // was asked for and offer the way back, instead of "nothing here yet". | ||
| 327 | + const activeQuery = () => searchFieldValue().trim(); | ||
| 328 | + const narrowed = () => activeQuery() !== "" || props.filtersActive === true; | ||
| 329 | + const clearNarrowing = () => { | ||
| 330 | + if (activeQuery()) handleSearch(""); | ||
| 331 | + if (props.filtersActive) props.onClearFilters?.(); | ||
| 332 | + }; | ||
| 251 | const emptyContent = () => ( | 333 | const emptyContent = () => ( |
| 252 | <Show | 334 | <Show |
| 253 | - when={searchFieldValue().trim()} | 335 | + when={narrowed()} |
| 254 | fallback={ | 336 | fallback={ |
| 255 | <div class="flex flex-col items-center gap-3"> | 337 | <div class="flex flex-col items-center gap-3"> |
| 256 | <Illustration name={props.emptyIllustration ?? "empty"} class="h-20 w-32" /> | 338 | <Illustration name={props.emptyIllustration ?? "empty"} class="h-20 w-32" /> |
| @@ -260,10 +342,14 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 260 | > | 342 | > |
| 261 | <div class="flex flex-col items-center gap-3"> | 343 | <div class="flex flex-col items-center gap-3"> |
| 262 | <Illustration name="no-results" class="h-20 w-32" /> | 344 | <Illustration name="no-results" class="h-20 w-32" /> |
| 263 | - <span>{t("common.noMatches")}</span> | 345 | + <span class="max-w-full break-words"> |
| 264 | - <Button type="button" size="sm" variant="outline" onClick={() => handleSearch("")}> | 346 | + {activeQuery() ? t("common.noMatchesFor", { query: activeQuery() }) : t("common.noFilterMatches")} |
| 265 | - {t("common.clearSearch")} | 347 | + </span> |
| 266 | - </Button> | 348 | + <Show when={activeQuery() || props.onClearFilters}> |
| 349 | + <Button type="button" size="sm" variant="outline" onClick={clearNarrowing}> | ||
| 350 | + {props.filtersActive && props.onClearFilters ? t("common.clearFilters") : t("common.clearSearch")} | ||
| 351 | + </Button> | ||
| 352 | + </Show> | ||
| 267 | </div> | 353 | </div> |
| 268 | </Show> | 354 | </Show> |
| 269 | ); | 355 | ); |
| @@ -271,6 +357,12 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 271 | const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId); | 357 | const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId); |
| 272 | return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId; | 358 | return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId; |
| 273 | }; | 359 | }; |
| 360 | + // Screen readers hear the order only through aria-sort on the header cell. | ||
| 361 | + const ariaSort = (column: Column<TData, unknown>) => { | ||
| 362 | + if (!sortingEnabled() || !column.getCanSort()) return undefined; | ||
| 363 | + const sorted = column.getIsSorted(); | ||
| 364 | + return sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none"; | ||
| 365 | + }; | ||
| 274 | const renderHeader = (header: ReturnType<typeof table.getHeaderGroups>[number]["headers"][number]) => { | 366 | const renderHeader = (header: ReturnType<typeof table.getHeaderGroups>[number]["headers"][number]) => { |
| 275 | const content = flexRender(header.column.columnDef.header, header.getContext()); | 367 | const content = flexRender(header.column.columnDef.header, header.getContext()); |
| 276 | if (!sortingEnabled() || !header.column.getCanSort()) { | 368 | if (!sortingEnabled() || !header.column.getCanSort()) { |
| @@ -326,7 +418,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 326 | sideways instead of stacking one control per line. From `lg`: | 418 | sideways instead of stacking one control per line. From `lg`: |
| 327 | search, filters, then actions pushed to the right edge. Controls | 419 | search, filters, then actions pushed to the right edge. Controls |
| 328 | are touch-sized (h-10) below `sm` and compact (h-8) above it. */} | 420 | are touch-sized (h-10) below `sm` and compact (h-8) above it. */} |
| 329 | - <div class={cn("flex flex-wrap items-center gap-2", sectioned() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs")}> | 421 | + <div class={cn("flex flex-wrap items-center gap-2", sectioned() && !columnMenuOnly() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs")}> |
| 330 | <Show when={showSearch()}> | 422 | <Show when={showSearch()}> |
| 331 | <DataTableSearch | 423 | <DataTableSearch |
| 332 | class="order-1 w-auto min-w-40 flex-1 grow-[100] sm:max-w-xs" | 424 | class="order-1 w-auto min-w-40 flex-1 grow-[100] sm:max-w-xs" |
| @@ -337,7 +429,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 337 | /> | 429 | /> |
| 338 | </Show> | 430 | </Show> |
| 339 | <Show when={props.filters}> | 431 | <Show when={props.filters}> |
| 340 | - <div class="order-3 -my-1 flex w-full items-center gap-2 overflow-x-auto py-1 [scrollbar-width:none] sm:my-0 sm:py-0 sm:flex-wrap sm:overflow-visible lg:order-2 lg:w-auto [&_button]:h-10 [&_button]:shrink-0 [&_button]:rounded-lg [&_button]:text-[13px] sm:[&_button]:h-8 [&_select]:h-10 [&_select]:rounded-lg [&_select]:text-[13px] sm:[&_select]:h-8 max-sm:[&>*]:flex-nowrap max-sm:[&>*]:shrink-0">{props.filters}</div> | 432 | + <div class="order-3 -my-1 flex w-full items-center gap-2 overflow-x-auto py-1 [scrollbar-width:none] sm:my-0 sm:py-0 sm:flex-wrap sm:overflow-visible lg:order-2 lg:w-auto [&_button]:h-10 [&_button]:shrink-0 [&_button]:rounded-lg [&_button]:text-[13px] sm:[&_button]:h-8 touch:[&_button]:h-10 [&_select]:h-10 [&_select]:rounded-lg [&_select]:text-[13px] sm:[&_select]:h-8 touch:[&_select]:h-10 max-sm:[&>*]:flex-nowrap max-sm:[&>*]:shrink-0">{props.filters}</div> |
| 341 | </Show> | 433 | </Show> |
| 342 | <Show when={props.actions || showColumnMenu()}> | 434 | <Show when={props.actions || showColumnMenu()}> |
| 343 | {/* Beside the search the actions keep their own width (the search | 435 | {/* Beside the search the actions keep their own width (the search |
| @@ -348,7 +440,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 348 | <Show when={props.actions}> | 440 | <Show when={props.actions}> |
| 349 | {/* A "yakında" button does nothing yet; on a phone it only | 441 | {/* A "yakında" button does nothing yet; on a phone it only |
| 350 | pushes the working action off the search row. */} | 442 | pushes the working action off the search row. */} |
| 351 | - <div class="flex min-w-0 flex-wrap items-center gap-2 [&_button]:rounded-md max-sm:flex-1 max-sm:[&_button]:h-10 max-sm:[&_button]:flex-1 max-sm:[&_button:has([data-coming-soon])]:hidden">{props.actions}</div> | 443 | + <div class="flex min-w-0 flex-wrap items-center gap-2 [&_button]:rounded-md max-sm:flex-1 touch:[&_button]:h-10 max-sm:[&_button]:flex-1 max-sm:[&_button:has([data-coming-soon])]:hidden">{props.actions}</div> |
| 352 | </Show> | 444 | </Show> |
| 353 | <Show when={showColumnMenu()}> | 445 | <Show when={showColumnMenu()}> |
| 354 | <DataTableViewMenu columns={viewMenuColumns()} /> | 446 | <DataTableViewMenu columns={viewMenuColumns()} /> |
| @@ -405,13 +497,15 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 405 | {/* Two fields per line, label over value: a label/value | 497 | {/* Two fields per line, label over value: a label/value |
| 406 | row per field made every card as tall as its column | 498 | row per field made every card as tall as its column |
| 407 | count. Cells are written for a centred table column, | 499 | count. Cells are written for a centred table column, |
| 408 | - so the card pulls their content back to the left. */} | 500 | + so the card pulls their content back to the left, and |
| 501 | + a status pill sized for that column's width shrinks | ||
| 502 | + back to its own label. */} | ||
| 409 | <dl class="mt-2 grid grid-cols-2 gap-x-4 gap-y-2"> | 503 | <dl class="mt-2 grid grid-cols-2 gap-x-4 gap-y-2"> |
| 410 | <For each={details()}> | 504 | <For each={details()}> |
| 411 | {(cell) => ( | 505 | {(cell) => ( |
| 412 | <div class="min-w-0"> | 506 | <div class="min-w-0"> |
| 413 | <dt class="truncate text-[11px] leading-4 text-muted-foreground">{headerLabel(cell.column.id)}</dt> | 507 | <dt class="truncate text-[11px] leading-4 text-muted-foreground">{headerLabel(cell.column.id)}</dt> |
| 414 | - <dd class="mt-0.5 min-w-0 break-words text-[13px] leading-5 text-foreground text-left [&_*]:text-left [&_.items-center]:items-start [&_.justify-center]:justify-start [&_.justify-end]:justify-start [&_.mx-auto]:mx-0"> | 508 | + <dd class="mt-0.5 min-w-0 break-words text-[13px] leading-5 text-foreground text-left [&_*]:text-left [&_.items-center]:items-start [&_.justify-center]:justify-start [&_.justify-end]:justify-start [&_.mx-auto]:mx-0 [&_[data-slot=badge]]:w-auto [&_[data-slot=badge]]:min-w-0 [&_[data-slot=badge]]:max-w-full [&_[data-slot=badge]]:items-center!"> |
| 415 | {flexRender(cell.column.columnDef.cell, cell.getContext())} | 509 | {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 416 | </dd> | 510 | </dd> |
| 417 | </div> | 511 | </div> |
| @@ -435,7 +529,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 435 | <DataTableFrame class={sectioned() ? "shadow-xs" : undefined}> | 529 | <DataTableFrame class={sectioned() ? "shadow-xs" : undefined}> |
| 436 | <Table | 530 | <Table |
| 437 | class={cn("data-table table-fixed", props.tableClass)} | 531 | class={cn("data-table table-fixed", props.tableClass)} |
| 438 | - style={{ width: `max(100%, ${tableWidth()}px)` }} | 532 | + style={{ width: `max(100%, ${minTableWidth()}px)` }} |
| 439 | > | 533 | > |
| 440 | <colgroup> | 534 | <colgroup> |
| 441 | <For each={table.getVisibleLeafColumns()}> | 535 | <For each={table.getVisibleLeafColumns()}> |
| @@ -458,6 +552,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 458 | actionColumnClass(header.column.id), | 552 | actionColumnClass(header.column.id), |
| 459 | )} | 553 | )} |
| 460 | style={{ width: columnWidth(header.column) }} | 554 | style={{ width: columnWidth(header.column) }} |
| 555 | + aria-sort={ariaSort(header.column)} | ||
| 461 | > | 556 | > |
| 462 | <Show when={!header.isPlaceholder}>{renderHeader(header)}</Show> | 557 | <Show when={!header.isPlaceholder}>{renderHeader(header)}</Show> |
| 463 | </TableHead> | 558 | </TableHead> |
| @@ -563,13 +658,17 @@ export function DataTableFrame(props: ParentProps<{ class?: string }>) { | |||
| 563 | observer.observe(frame); | 658 | observer.observe(frame); |
| 564 | onCleanup(() => observer.disconnect()); | 659 | onCleanup(() => observer.disconnect()); |
| 565 | }); | 660 | }); |
| 661 | + // The hint sits under the frame, not floated inside it: pinned to the | ||
| 662 | + // frame's bottom edge it covered the last row's action button. | ||
| 566 | return ( | 663 | return ( |
| 567 | - <div ref={frame} class={cn("data-table-wrap relative", props.class)}> | 664 | + <div class="space-y-1"> |
| 568 | - {props.children} | 665 | + <div ref={frame} class={cn("data-table-wrap relative", props.class)}> |
| 666 | + {props.children} | ||
| 667 | + </div> | ||
| 569 | <Show when={scrollable()}> | 668 | <Show when={scrollable()}> |
| 570 | - <span class="pointer-events-none sticky bottom-2 left-[calc(100%-6rem)] z-30 ml-[calc(100%-6.5rem)] inline-flex w-fit items-center gap-1 rounded-full border border-border/70 bg-surface-base/95 px-2 py-1 text-xs font-medium text-muted-foreground shadow-sm backdrop-blur" aria-hidden="true"> | 669 | + <p class="flex justify-end text-[11px] font-medium text-muted-foreground" aria-hidden="true"> |
| 571 | ↔ {t("common.scrollHint")} | 670 | ↔ {t("common.scrollHint")} |
| 572 | - </span> | 671 | + </p> |
| 573 | </Show> | 672 | </Show> |
| 574 | </div> | 673 | </div> |
| 575 | ); | 674 | ); |
src/components/ui/data-toolbar.tsxmodified+1 -1
| @@ -36,7 +36,7 @@ export function DataToolbar(props: { | |||
| 36 | <div class="order-3 flex w-full flex-wrap items-center gap-2 sm:order-2 sm:w-auto">{props.filters}</div> | 36 | <div class="order-3 flex w-full flex-wrap items-center gap-2 sm:order-2 sm:w-auto">{props.filters}</div> |
| 37 | </Show> | 37 | </Show> |
| 38 | <Show when={props.actions}> | 38 | <Show when={props.actions}> |
| 39 | - <div class="order-2 ml-auto flex shrink-0 grow items-center justify-end gap-2 sm:order-3 sm:grow-0 max-sm:[&_button]:h-10 max-sm:[&_button]:flex-1 max-sm:[&_button:has([data-coming-soon])]:hidden">{props.actions}</div> | 39 | + <div class="order-2 ml-auto flex shrink-0 grow items-center justify-end gap-2 sm:order-3 sm:grow-0 touch:[&_button]:h-10 max-sm:[&_button]:flex-1 max-sm:[&_button:has([data-coming-soon])]:hidden">{props.actions}</div> |
| 40 | </Show> | 40 | </Show> |
| 41 | </div> | 41 | </div> |
| 42 | ); | 42 | ); |
src/components/ui/empty-state.tsxmodified+4 -0
| @@ -1,4 +1,5 @@ | |||
| 1 | import { Show } from "solid-js"; | 1 | import { Show } from "solid-js"; |
| 2 | +import type { JSX } from "solid-js"; | ||
| 2 | import { Illustration } from "@/components/ui/illustration"; | 3 | import { Illustration } from "@/components/ui/illustration"; |
| 3 | import { cn } from "@/lib/cn"; | 4 | import { cn } from "@/lib/cn"; |
| 4 | import type { IllustrationName } from "@/lib/illustrations"; | 5 | import type { IllustrationName } from "@/lib/illustrations"; |
| @@ -43,6 +44,8 @@ export function EmptyState(props: { | |||
| 43 | title: string; | 44 | title: string; |
| 44 | description?: string; | 45 | description?: string; |
| 45 | kind?: EmptyStateKind; | 46 | kind?: EmptyStateKind; |
| 47 | + /** A way out, e.g. "clear search" under a no-results panel. */ | ||
| 48 | + action?: JSX.Element; | ||
| 46 | class?: string; | 49 | class?: string; |
| 47 | }) { | 50 | }) { |
| 48 | const kind = () => props.kind ?? "default"; | 51 | const kind = () => props.kind ?? "default"; |
| @@ -62,6 +65,7 @@ export function EmptyState(props: { | |||
| 62 | <p class="mx-auto max-w-[420px] text-sm leading-[21px] text-text-subtle">{props.description}</p> | 65 | <p class="mx-auto max-w-[420px] text-sm leading-[21px] text-text-subtle">{props.description}</p> |
| 63 | </Show> | 66 | </Show> |
| 64 | </div> | 67 | </div> |
| 68 | + <Show when={props.action}>{props.action}</Show> | ||
| 65 | </div> | 69 | </div> |
| 66 | ); | 70 | ); |
| 67 | } | 71 | } |
src/components/ui/rich-text-editor.tsxmodified+7 -0
| @@ -64,6 +64,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 64 | class="flex h-7 w-7 items-center justify-center rounded font-bold text-xs hover:bg-muted text-foreground" | 64 | class="flex h-7 w-7 items-center justify-center rounded font-bold text-xs hover:bg-muted text-foreground" |
| 65 | onClick={() => execCommand("bold")} | 65 | onClick={() => execCommand("bold")} |
| 66 | title={t("editor.bold")} | 66 | title={t("editor.bold")} |
| 67 | + aria-label={t("editor.bold")} | ||
| 67 | > | 68 | > |
| 68 | B | 69 | B |
| 69 | </button> | 70 | </button> |
| @@ -72,6 +73,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 72 | class="flex h-7 w-7 items-center justify-center rounded italic text-xs hover:bg-muted text-foreground" | 73 | class="flex h-7 w-7 items-center justify-center rounded italic text-xs hover:bg-muted text-foreground" |
| 73 | onClick={() => execCommand("italic")} | 74 | onClick={() => execCommand("italic")} |
| 74 | title={t("editor.italic")} | 75 | title={t("editor.italic")} |
| 76 | + aria-label={t("editor.italic")} | ||
| 75 | > | 77 | > |
| 76 | I | 78 | I |
| 77 | </button> | 79 | </button> |
| @@ -80,6 +82,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 80 | class="flex h-7 w-7 items-center justify-center rounded underline text-xs hover:bg-muted text-foreground" | 82 | class="flex h-7 w-7 items-center justify-center rounded underline text-xs hover:bg-muted text-foreground" |
| 81 | onClick={() => execCommand("underline")} | 83 | onClick={() => execCommand("underline")} |
| 82 | title={t("editor.underline")} | 84 | title={t("editor.underline")} |
| 85 | + aria-label={t("editor.underline")} | ||
| 83 | > | 86 | > |
| 84 | U | 87 | U |
| 85 | </button> | 88 | </button> |
| @@ -88,6 +91,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 88 | class="flex h-7 w-7 items-center justify-center rounded line-through text-xs hover:bg-muted text-foreground" | 91 | class="flex h-7 w-7 items-center justify-center rounded line-through text-xs hover:bg-muted text-foreground" |
| 89 | onClick={() => execCommand("strikeThrough")} | 92 | onClick={() => execCommand("strikeThrough")} |
| 90 | title={t("editor.strike")} | 93 | title={t("editor.strike")} |
| 94 | + aria-label={t("editor.strike")} | ||
| 91 | > | 95 | > |
| 92 | S | 96 | S |
| 93 | </button> | 97 | </button> |
| @@ -99,6 +103,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 99 | class="flex h-7 px-2 items-center justify-center rounded text-xs font-mono hover:bg-muted text-foreground" | 103 | class="flex h-7 px-2 items-center justify-center rounded text-xs font-mono hover:bg-muted text-foreground" |
| 100 | onClick={() => execCommand("insertUnorderedList")} | 104 | onClick={() => execCommand("insertUnorderedList")} |
| 101 | title={t("editor.bulletList")} | 105 | title={t("editor.bulletList")} |
| 106 | + aria-label={t("editor.bulletList")} | ||
| 102 | > | 107 | > |
| 103 | • {t("editor.bulletListLabel")} | 108 | • {t("editor.bulletListLabel")} |
| 104 | </button> | 109 | </button> |
| @@ -107,6 +112,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 107 | class="flex h-7 px-2 items-center justify-center rounded text-xs font-mono hover:bg-muted text-foreground" | 112 | class="flex h-7 px-2 items-center justify-center rounded text-xs font-mono hover:bg-muted text-foreground" |
| 108 | onClick={() => execCommand("insertOrderedList")} | 113 | onClick={() => execCommand("insertOrderedList")} |
| 109 | title={t("editor.numberedList")} | 114 | title={t("editor.numberedList")} |
| 115 | + aria-label={t("editor.numberedList")} | ||
| 110 | > | 116 | > |
| 111 | {t("editor.numberedListLabel")} | 117 | {t("editor.numberedListLabel")} |
| 112 | </button> | 118 | </button> |
| @@ -118,6 +124,7 @@ export function RichTextEditor(props: RichTextEditorProps) { | |||
| 118 | class="flex h-7 px-2 items-center justify-center rounded text-xs hover:bg-muted text-muted-foreground" | 124 | class="flex h-7 px-2 items-center justify-center rounded text-xs hover:bg-muted text-muted-foreground" |
| 119 | onClick={() => execCommand("removeFormat")} | 125 | onClick={() => execCommand("removeFormat")} |
| 120 | title={t("editor.clearFormatting")} | 126 | title={t("editor.clearFormatting")} |
| 127 | + aria-label={t("editor.clearFormatting")} | ||
| 121 | > | 128 | > |
| 122 | {t("editor.clearFormattingLabel")} | 129 | {t("editor.clearFormattingLabel")} |
| 123 | </button> | 130 | </button> |
src/components/ui/side-panel.test.tsxmodified+1 -1
| @@ -43,7 +43,7 @@ test("a dirty panel asks before discarding, and stays open on Keep editing", asy | |||
| 43 | expect(screen.getByTestId("state").textContent).toBe("open"); | 43 | expect(screen.getByTestId("state").textContent).toBe("open"); |
| 44 | 44 | ||
| 45 | fireEvent.click(closeButton()); | 45 | fireEvent.click(closeButton()); |
| 46 | - fireEvent.click(await screen.findByRole("button", { name: /^(Discard|Sil ve kapat)$/ })); | 46 | + fireEvent.click(await screen.findByRole("button", { name: /^(Discard changes|Değişiklikleri at)$/ })); |
| 47 | await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed")); | 47 | await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed")); |
| 48 | }); | 48 | }); |
| 49 | 49 | ||
src/components/ui/side-panel.tsxmodified+3 -1
| @@ -1,7 +1,7 @@ | |||
| 1 | import { Dialog as DialogPrimitive } from "@kobalte/core/dialog"; | 1 | import { Dialog as DialogPrimitive } from "@kobalte/core/dialog"; |
| 2 | import { createEffect, createSignal, onCleanup, type ParentProps } from "solid-js"; | 2 | import { createEffect, createSignal, onCleanup, type ParentProps } from "solid-js"; |
| 3 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 3 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 4 | -import { IconX } from "@/components/ui/icons"; | 4 | +import { IconAlert, IconX } from "@/components/ui/icons"; |
| 5 | import { cn } from "@/lib/cn"; | 5 | import { cn } from "@/lib/cn"; |
| 6 | import { useT } from "@/stores/preferences-context"; | 6 | import { useT } from "@/stores/preferences-context"; |
| 7 | 7 | ||
| @@ -135,6 +135,8 @@ export function SidePanel( | |||
| 135 | confirmLabel={t("sidePanel.discard")} | 135 | confirmLabel={t("sidePanel.discard")} |
| 136 | cancelLabel={t("sidePanel.keepEditing")} | 136 | cancelLabel={t("sidePanel.keepEditing")} |
| 137 | variant="destructive" | 137 | variant="destructive" |
| 138 | + // Discarding a draft is not deleting a record: no trash can. | ||
| 139 | + icon={<IconAlert class="h-4 w-4" />} | ||
| 138 | onConfirm={() => props.onOpenChange(false)} | 140 | onConfirm={() => props.onOpenChange(false)} |
| 139 | /> | 141 | /> |
| 140 | </> | 142 | </> |
src/components/ui/table-pagination.tsxmodified+3 -3
| @@ -18,8 +18,8 @@ export type TablePaginationProps = { | |||
| 18 | 18 | ||
| 19 | /** | 19 | /** |
| 20 | * Footer: "a-b / total" + prev / "page / count" / next, on one row at every | 20 | * Footer: "a-b / total" + prev / "page / count" / next, on one row at every |
| 21 | - * width. The buttons are full touch targets on phones and compact from `sm` | 21 | + * width. The buttons are full touch targets on phones and touch screens, |
| 22 | - * up. A single page keeps the row count but drops the buttons — two disabled | 22 | + * compact otherwise. A single page keeps the row count but drops the buttons — two disabled |
| 23 | * arrows around "1 / 1" only take room. | 23 | * arrows around "1 / 1" only take room. |
| 24 | */ | 24 | */ |
| 25 | export function TablePagination(props: TablePaginationProps) { | 25 | export function TablePagination(props: TablePaginationProps) { |
| @@ -27,7 +27,7 @@ export function TablePagination(props: TablePaginationProps) { | |||
| 27 | const hasRange = () => props.total != null && props.pageSize != null; | 27 | const hasRange = () => props.total != null && props.pageSize != null; |
| 28 | const start = () => (!props.total || !props.pageSize ? 0 : props.pageIndex * props.pageSize + 1); | 28 | const start = () => (!props.total || !props.pageSize ? 0 : props.pageIndex * props.pageSize + 1); |
| 29 | const end = () => Math.min((props.pageIndex + 1) * (props.pageSize ?? 0), props.total ?? 0); | 29 | const end = () => Math.min((props.pageIndex + 1) * (props.pageSize ?? 0), props.total ?? 0); |
| 30 | - const navButton = "h-10 w-10 gap-1 px-0 text-xs sm:h-7 sm:w-auto sm:px-1.5 sm:text-[11px]"; | 30 | + const navButton = "h-10 w-10 gap-1 px-0 text-xs sm:h-7 sm:w-auto sm:px-1.5 sm:text-[11px] touch:h-10 touch:min-w-10"; |
| 31 | 31 | ||
| 32 | return ( | 32 | return ( |
| 33 | // Nothing to count and nowhere to go: an empty frame would only take room. | 33 | // Nothing to count and nowhere to go: an empty frame would only take room. |
src/components/users/user-search-select.tsxmodified+51 -2
| @@ -1,5 +1,5 @@ | |||
| 1 | import { Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js"; | 1 | import { Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js"; |
| 2 | -import { getUserSearch } from "@/api/users"; | 2 | +import { getUserById, getUserSearch } from "@/api/users"; |
| 3 | import type { PersonRef, Role } from "@/api/client"; | 3 | import type { PersonRef, Role } from "@/api/client"; |
| 4 | import type { PersonLike } from "@/lib/person"; | 4 | import type { PersonLike } from "@/lib/person"; |
| 5 | import { | 5 | import { |
| @@ -38,6 +38,12 @@ export function UserSearchSelect(props: { | |||
| 38 | /** Overrides the default "what can I type here" line under the field. */ | 38 | /** Overrides the default "what can I type here" line under the field. */ |
| 39 | hint?: string; | 39 | hint?: string; |
| 40 | role?: Role; | 40 | role?: Role; |
| 41 | + /** | ||
| 42 | + * The person behind a preset `value` (e.g. the class's current teacher), so | ||
| 43 | + * the field names them instead of showing the placeholder. Without it a | ||
| 44 | + * preset id is resolved with one `/users/{id}` read. | ||
| 45 | + */ | ||
| 46 | + initialUser?: PersonRef | null; | ||
| 41 | }) { | 47 | }) { |
| 42 | const t = useT(); | 48 | const t = useT(); |
| 43 | const auth = useAuth(); | 49 | const auth = useAuth(); |
| @@ -81,6 +87,37 @@ export function UserSearchSelect(props: { | |||
| 81 | if (!props.value && selected()) setSelected(null); | 87 | if (!props.value && selected()) setSelected(null); |
| 82 | }); | 88 | }); |
| 83 | 89 | ||
| 90 | + // A value set by the parent (an edit form opening on a saved record) has no | ||
| 91 | + // picked option behind it, so the input would read as empty. Show the | ||
| 92 | + // person it points at: from `initialUser` when given, else one lookup. | ||
| 93 | + let resolving: string | null = null; | ||
| 94 | + createEffect(() => { | ||
| 95 | + const id = props.value; | ||
| 96 | + if (!id || selected()?.id === id) return; | ||
| 97 | + const preset = props.initialUser; | ||
| 98 | + if (preset && preset.id === id) { | ||
| 99 | + setSelected(preset); | ||
| 100 | + return; | ||
| 101 | + } | ||
| 102 | + if (!canSearch() || resolving === id) return; | ||
| 103 | + resolving = id; | ||
| 104 | + void getUserById(id) | ||
| 105 | + .then((user) => { | ||
| 106 | + if (props.value !== id) return; | ||
| 107 | + setSelected({ | ||
| 108 | + id: user.id, | ||
| 109 | + username: user.username, | ||
| 110 | + display_name: user.display_name || [user.name, user.surname].filter(Boolean).join(" ") || null, | ||
| 111 | + }); | ||
| 112 | + }) | ||
| 113 | + .catch(() => { | ||
| 114 | + // Unreadable account: leave the field empty rather than show the uuid. | ||
| 115 | + }) | ||
| 116 | + .finally(() => { | ||
| 117 | + if (resolving === id) resolving = null; | ||
| 118 | + }); | ||
| 119 | + }); | ||
| 120 | + | ||
| 84 | let controller: AbortController | null = null; | 121 | let controller: AbortController | null = null; |
| 85 | let timer: ReturnType<typeof setTimeout> | undefined; | 122 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 86 | // Debounce keystrokes so a typed name is one request, not one per letter. | 123 | // Debounce keystrokes so a typed name is one request, not one per letter. |
| @@ -132,7 +169,10 @@ export function UserSearchSelect(props: { | |||
| 132 | <div class="space-y-2"> | 169 | <div class="space-y-2"> |
| 133 | <Show when={props.label}>{(label) => <Label for={props.id}>{label()}</Label>}</Show> | 170 | <Show when={props.label}>{(label) => <Label for={props.id}>{label()}</Label>}</Show> |
| 134 | <Combobox<PersonRef> | 171 | <Combobox<PersonRef> |
| 135 | - options={options()} | 172 | + // Kobalte writes the picked person's name into the input only when |
| 173 | + // that person is among the options, so a preset one rides along | ||
| 174 | + // while nothing is being searched. | ||
| 175 | + options={query().trim() === "" && selected() ? [selected()!] : options()} | ||
| 136 | // Results arrive async, so options is empty at input time. Kobalte | 176 | // Results arrive async, so options is empty at input time. Kobalte |
| 137 | // refuses to open an empty collection by default (and would close on | 177 | // refuses to open an empty collection by default (and would close on |
| 138 | // input) — allow it, and control open so the panel stays up while | 178 | // input) — allow it, and control open so the panel stays up while |
| @@ -147,6 +187,15 @@ export function UserSearchSelect(props: { | |||
| 147 | props.onSelect?.(user ?? null); | 187 | props.onSelect?.(user ?? null); |
| 148 | }} | 188 | }} |
| 149 | onInputChange={(value) => { | 189 | onInputChange={(value) => { |
| 190 | + // Kobalte echoes the picked person's label into the input; that is | ||
| 191 | + // not a search, and treating it as one drops the preset person from | ||
| 192 | + // the options, which makes Kobalte clear the field again. | ||
| 193 | + const current = selected(); | ||
| 194 | + if (current && value === pickedLabel(current)) { | ||
| 195 | + setQuery(""); | ||
| 196 | + setOpen(false); | ||
| 197 | + return; | ||
| 198 | + } | ||
| 150 | setQuery(value); | 199 | setQuery(value); |
| 151 | runSearch(value); | 200 | runSearch(value); |
| 152 | if (value.trim().length > 0) setOpen(true); | 201 | if (value.trim().length > 0) setOpen(true); |
src/components/users/user-table.tsxmodified+6 -1
| @@ -28,6 +28,7 @@ function UserRoleActions(props: { | |||
| 28 | const [pendingRole, setPendingRole] = createSignal<Role>(props.user.role); | 28 | const [pendingRole, setPendingRole] = createSignal<Role>(props.user.role); |
| 29 | const [confirmOpen, setConfirmOpen] = createSignal(false); | 29 | const [confirmOpen, setConfirmOpen] = createSignal(false); |
| 30 | const dirty = () => pendingRole() !== props.user.role; | 30 | const dirty = () => pendingRole() !== props.user.role; |
| 31 | + const demotesAdmin = () => props.user.role === "admin" && pendingRole() !== "admin"; | ||
| 31 | 32 | ||
| 32 | return ( | 33 | return ( |
| 33 | <> | 34 | <> |
| @@ -52,6 +53,9 @@ function UserRoleActions(props: { | |||
| 52 | open={confirmOpen()} | 53 | open={confirmOpen()} |
| 53 | onOpenChange={setConfirmOpen} | 54 | onOpenChange={setConfirmOpen} |
| 54 | title={t("confirm.updateTitle")} | 55 | title={t("confirm.updateTitle")} |
| 56 | + description={demotesAdmin() ? t("admin.demoteAdminWarning") : undefined} | ||
| 57 | + variant={demotesAdmin() ? "destructive" : "default"} | ||
| 58 | + confirmLabel={t("confirm.confirmUpdate")} | ||
| 55 | summary={t("confirm.updateRole", { | 59 | summary={t("confirm.updateRole", { |
| 56 | user: props.user.username, | 60 | user: props.user.username, |
| 57 | from: t(`role.${props.user.role}` as MessageKey), | 61 | from: t(`role.${props.user.role}` as MessageKey), |
| @@ -168,7 +172,8 @@ export function UserTable(props: { | |||
| 168 | filterHint={t("search.hint.users")} | 172 | filterHint={t("search.hint.users")} |
| 169 | surfaceSections | 173 | surfaceSections |
| 170 | enablePagination | 174 | enablePagination |
| 171 | - pageSize={20} | 175 | + // The shared default (10, halved on phones), like every other list. |
| 176 | + urlState | ||
| 172 | onRowClick={props.onUserClick} | 177 | onRowClick={props.onUserClick} |
| 173 | /> | 178 | /> |
| 174 | ); | 179 | ); |
src/i18n/locales/en.tsmodified+60 -7
| @@ -163,6 +163,7 @@ export const en: Dict = { | |||
| 163 | "profile.noCourses": "No courses to show.", | 163 | "profile.noCourses": "No courses to show.", |
| 164 | "profile.stats": "Stats", | 164 | "profile.stats": "Stats", |
| 165 | "profile.statFocusHours": "Hours focused", | 165 | "profile.statFocusHours": "Hours focused", |
| 166 | + "profile.statFocusMinutes": "Minutes focused", | ||
| 166 | "profile.statSessions": "Focus sessions", | 167 | "profile.statSessions": "Focus sessions", |
| 167 | "profile.statHomework": "Homework submitted", | 168 | "profile.statHomework": "Homework submitted", |
| 168 | "profile.statOnTime": "Submitted on time", | 169 | "profile.statOnTime": "Submitted on time", |
| @@ -371,6 +372,8 @@ export const en: Dict = { | |||
| 371 | "notifications.title": "Notifications", | 372 | "notifications.title": "Notifications", |
| 372 | "notifications.clearAll": "Clear all", | 373 | "notifications.clearAll": "Clear all", |
| 373 | "notifications.dismiss": "Dismiss", | 374 | "notifications.dismiss": "Dismiss", |
| 375 | + "notifications.clearAllConfirmTitle": "Clear all notifications?", | ||
| 376 | + "notifications.clearAllConfirmSummary": "The {count} notifications in the list will be removed.", | ||
| 374 | "notifications.empty": "No new notifications yet.", | 377 | "notifications.empty": "No new notifications yet.", |
| 375 | "notifications.tabAll": "All", | 378 | "notifications.tabAll": "All", |
| 376 | "notifications.tabSystem": "System", | 379 | "notifications.tabSystem": "System", |
| @@ -505,10 +508,12 @@ export const en: Dict = { | |||
| 505 | "roster.addStudent": "Add student", | 508 | "roster.addStudent": "Add student", |
| 506 | "roster.addTeacher": "Add teacher", | 509 | "roster.addTeacher": "Add teacher", |
| 507 | "roster.studentsSubtitle": "Every student in the school, with their class.", | 510 | "roster.studentsSubtitle": "Every student in the school, with their class.", |
| 508 | - "roster.teachersSubtitle": "Every teacher in the school and the classes they lead.", | 511 | + "roster.teachersSubtitle": "Every teacher in the school, the sections they teach and the classes they lead.", |
| 509 | "roster.searchStudents": "Search student name or username…", | 512 | "roster.searchStudents": "Search student name or username…", |
| 510 | "roster.searchTeachers": "Search teacher name or username…", | 513 | "roster.searchTeachers": "Search teacher name or username…", |
| 511 | "roster.noTeachers": "No teachers yet.", | 514 | "roster.noTeachers": "No teachers yet.", |
| 515 | + "roster.taughtSections": "Sections taught", | ||
| 516 | + "roster.homeroomOf": "Homeroom", | ||
| 512 | "builder.console": "Operator console", | 517 | "builder.console": "Operator console", |
| 513 | "builder.logout": "Sign out", | 518 | "builder.logout": "Sign out", |
| 514 | "builder.loginTitle": "Operator sign-in", | 519 | "builder.loginTitle": "Operator sign-in", |
| @@ -634,7 +639,7 @@ export const en: Dict = { | |||
| 634 | "modules.offDescription": "Your school doesn't have this module turned on right now. Ask your school administrator if you need it.", | 639 | "modules.offDescription": "Your school doesn't have this module turned on right now. Ask your school administrator if you need it.", |
| 635 | "common.learnMore": "Learn more", | 640 | "common.learnMore": "Learn more", |
| 636 | "common.gotIt": "Got it", | 641 | "common.gotIt": "Got it", |
| 637 | - "confirm.review": "Please review your changes before saving.", | 642 | + "confirm.review": "Check the summary below before you confirm.", |
| 638 | "confirm.summary": "Summary", | 643 | "confirm.summary": "Summary", |
| 639 | "confirm.confirmDelete": "Yes, delete", | 644 | "confirm.confirmDelete": "Yes, delete", |
| 640 | "confirm.confirmUpdate": "Yes, update", | 645 | "confirm.confirmUpdate": "Yes, update", |
| @@ -660,6 +665,9 @@ export const en: Dict = { | |||
| 660 | "common.noResults": "No results.", | 665 | "common.noResults": "No results.", |
| 661 | "common.scrollHint": "Scroll horizontally", | 666 | "common.scrollHint": "Scroll horizontally", |
| 662 | "common.noMatches": "Nothing matches your search.", | 667 | "common.noMatches": "Nothing matches your search.", |
| 668 | + "common.noMatchesFor": "No results for “{query}”.", | ||
| 669 | + "common.noFilterMatches": "Nothing matches the selected filters.", | ||
| 670 | + "common.clearFilters": "Clear filters", | ||
| 663 | "common.creator": "Created by", | 671 | "common.creator": "Created by", |
| 664 | "common.searchPlaceholder": "Search…", | 672 | "common.searchPlaceholder": "Search…", |
| 665 | "common.all": "All", | 673 | "common.all": "All", |
| @@ -746,7 +754,7 @@ export const en: Dict = { | |||
| 746 | "common.dismiss": "Dismiss", | 754 | "common.dismiss": "Dismiss", |
| 747 | "sidePanel.discardTitle": "Discard your changes?", | 755 | "sidePanel.discardTitle": "Discard your changes?", |
| 748 | "sidePanel.discardSummary": "What you entered in this form has not been saved and will be lost.", | 756 | "sidePanel.discardSummary": "What you entered in this form has not been saved and will be lost.", |
| 749 | - "sidePanel.discard": "Discard", | 757 | + "sidePanel.discard": "Discard changes", |
| 750 | "sidePanel.keepEditing": "Keep editing", | 758 | "sidePanel.keepEditing": "Keep editing", |
| 751 | "dashboard.partialError": "Some panels could not load and show no data.", | 759 | "dashboard.partialError": "Some panels could not load and show no data.", |
| 752 | "common.breadcrumb": "Breadcrumb", | 760 | "common.breadcrumb": "Breadcrumb", |
| @@ -814,7 +822,7 @@ export const en: Dict = { | |||
| 814 | "dashboard.stats.notes": "Notes", | 822 | "dashboard.stats.notes": "Notes", |
| 815 | "dashboard.stats.events": "Events", | 823 | "dashboard.stats.events": "Events", |
| 816 | "dashboard.stats.exams": "Exams", | 824 | "dashboard.stats.exams": "Exams", |
| 817 | - "dashboard.stats.courses": "Education", | 825 | + "dashboard.stats.courses": "Courses", |
| 818 | "dashboard.stats.role": "Your role", | 826 | "dashboard.stats.role": "Your role", |
| 819 | "dashboard.stats.average": "Average", | 827 | "dashboard.stats.average": "Average", |
| 820 | "dashboard.stats.averageHint": "Overall report card", | 828 | "dashboard.stats.averageHint": "Overall report card", |
| @@ -1358,6 +1366,9 @@ export const en: Dict = { | |||
| 1358 | "exams.allowReview": "Let students review their answers", | 1366 | "exams.allowReview": "Let students review their answers", |
| 1359 | "exams.allowReviewHelp": "Students can see their own paper and past attempts once you've marked this exam.", | 1367 | "exams.allowReviewHelp": "Students can see their own paper and past attempts once you've marked this exam.", |
| 1360 | "exams.draft": "Draft", | 1368 | "exams.draft": "Draft", |
| 1369 | + "exams.emptyUpcoming": "No upcoming exams.", | ||
| 1370 | + "exams.emptyCompleted": "No finished exams.", | ||
| 1371 | + "exams.emptyDraft": "No draft exams.", | ||
| 1361 | "exams.draftHelp": "Keep hidden from students until published.", | 1372 | "exams.draftHelp": "Keep hidden from students until published.", |
| 1362 | "exams.publish": "Publish exam", | 1373 | "exams.publish": "Publish exam", |
| 1363 | "exams.published": "Exam published", | 1374 | "exams.published": "Exam published", |
| @@ -1709,6 +1720,9 @@ export const en: Dict = { | |||
| 1709 | "courses.pageSubtitle": "Classes, study groups, and clubs, all in one place.", | 1720 | "courses.pageSubtitle": "Classes, study groups, and clubs, all in one place.", |
| 1710 | "courses.create": "New education item", | 1721 | "courses.create": "New education item", |
| 1711 | "courses.empty": "No {item} yet.", | 1722 | "courses.empty": "No {item} yet.", |
| 1723 | + "courses.sectionsFilter": "Section", | ||
| 1724 | + "courses.withSections": "Has sections", | ||
| 1725 | + "courses.withoutSections": "No sections", | ||
| 1712 | "courses.enrolled": "Enrolled", | 1726 | "courses.enrolled": "Enrolled", |
| 1713 | "courses.roster": "Roster", | 1727 | "courses.roster": "Roster", |
| 1714 | "courses.rosterItem": "Student", | 1728 | "courses.rosterItem": "Student", |
| @@ -1758,7 +1772,7 @@ export const en: Dict = { | |||
| 1758 | "homework.dueAt": "Due date", | 1772 | "homework.dueAt": "Due date", |
| 1759 | "homework.assigned": "Assigned to", | 1773 | "homework.assigned": "Assigned to", |
| 1760 | "homework.wholeCourse": "Whole course", | 1774 | "homework.wholeCourse": "Whole course", |
| 1761 | - "homework.wholeCourseHelp": "This first version assigns homework to the whole course. Use the backend API for student subsets until the multi-select UI exists.", | 1775 | + "homework.wholeCourseHelp": "The homework is assigned to every student enrolled in this course.", |
| 1762 | "homework.dueRequired": "Choose a valid due date and time.", | 1776 | "homework.dueRequired": "Choose a valid due date and time.", |
| 1763 | "homework.mineTitle": "My homework", | 1777 | "homework.mineTitle": "My homework", |
| 1764 | "homework.submit": "Submit homework", | 1778 | "homework.submit": "Submit homework", |
| @@ -1790,6 +1804,9 @@ export const en: Dict = { | |||
| 1790 | "marks.title": "Report card", | 1804 | "marks.title": "Report card", |
| 1791 | "marks.subtitle": "Your weighted grade averages across every course you’re enrolled in.", | 1805 | "marks.subtitle": "Your weighted grade averages across every course you’re enrolled in.", |
| 1792 | "marks.overall": "Overall average", | 1806 | "marks.overall": "Overall average", |
| 1807 | + "marks.band": "Grade band", | ||
| 1808 | + "marks.bandLabel": "Band {grade}", | ||
| 1809 | + "marks.examCount": "Exams", | ||
| 1793 | "marks.averageCapped": "The average column is filled in for schools of up to {cap} students. Open a student to see their report.", | 1810 | "marks.averageCapped": "The average column is filled in for schools of up to {cap} students. Open a student to see their report.", |
| 1794 | "marks.courseAvg": "Course average", | 1811 | "marks.courseAvg": "Course average", |
| 1795 | "marks.empty": "Not enrolled in any course yet.", | 1812 | "marks.empty": "Not enrolled in any course yet.", |
| @@ -1941,7 +1958,7 @@ export const en: Dict = { | |||
| 1941 | "meals.capacity": "Capacity", | 1958 | "meals.capacity": "Capacity", |
| 1942 | "meals.reservations": "Reservations", | 1959 | "meals.reservations": "Reservations", |
| 1943 | "meals.from": "Starting date", | 1960 | "meals.from": "Starting date", |
| 1944 | - "meals.empty": "No menus in this date range.", | 1961 | + "meals.empty": "No menus from this date on.", |
| 1945 | "meals.dishes": "dishes", | 1962 | "meals.dishes": "dishes", |
| 1946 | "meals.conflict": "Dietary warning", | 1963 | "meals.conflict": "Dietary warning", |
| 1947 | "meals.topPick": "Most picked", | 1964 | "meals.topPick": "Most picked", |
| @@ -2050,6 +2067,7 @@ export const en: Dict = { | |||
| 2050 | "payments.assign": "Assign", | 2067 | "payments.assign": "Assign", |
| 2051 | "payments.assignHelp": "Assigning bills every installment as a charge at once. Students already on the plan are not billed again.", | 2068 | "payments.assignHelp": "Assigning bills every installment as a charge at once. Students already on the plan are not billed again.", |
| 2052 | "payments.selectStudent": "Select student", | 2069 | "payments.selectStudent": "Select student", |
| 2070 | + "payments.searchStudents": "Search students…", | ||
| 2053 | "payments.assignments": "Assigned students", | 2071 | "payments.assignments": "Assigned students", |
| 2054 | "payments.noAssignments": "No students assigned yet.", | 2072 | "payments.noAssignments": "No students assigned yet.", |
| 2055 | "payments.outcomeAssigned": "Assigned", | 2073 | "payments.outcomeAssigned": "Assigned", |
| @@ -2205,7 +2223,7 @@ export const en: Dict = { | |||
| 2205 | "search.hint.bank": "Matches a phrase inside the question text.", | 2223 | "search.hint.bank": "Matches a phrase inside the question text.", |
| 2206 | "search.hint.whiteboards": "Matches board titles on the page you are viewing.", | 2224 | "search.hint.whiteboards": "Matches board titles on the page you are viewing.", |
| 2207 | "search.hint.chat": "Matches the text of the messages in this chat.", | 2225 | "search.hint.chat": "Matches the text of the messages in this chat.", |
| 2208 | - "search.hint.deadlines": "Matches the title of the upcoming items.", | 2226 | + "search.hint.deadlines": "Matches the title and the course — class of the upcoming items.", |
| 2209 | "search.hint.homework": "Matches homework title, description and course.", | 2227 | "search.hint.homework": "Matches homework title, description and course.", |
| 2210 | "search.hint.paymentsStudents": "Matches a student's name, surname or username.", | 2228 | "search.hint.paymentsStudents": "Matches a student's name, surname or username.", |
| 2211 | "work.userNotFound": "No work log found for this user.", | 2229 | "work.userNotFound": "No work log found for this user.", |
| @@ -2311,4 +2329,39 @@ export const en: Dict = { | |||
| 2311 | "attendance.overLimit": "Over the limit", | 2329 | "attendance.overLimit": "Over the limit", |
| 2312 | "common.yes": "Yes", | 2330 | "common.yes": "Yes", |
| 2313 | "common.no": "No", | 2331 | "common.no": "No", |
| 2332 | + "settings.leaveHint": "Your unsaved changes to the settings will be lost.", | ||
| 2333 | + "exams.kind.yazili": "Written", | ||
| 2334 | + "exams.kind.uygulama": "Practical", | ||
| 2335 | + "exams.kind.performans": "Performance", | ||
| 2336 | + "meals.slotName.breakfast": "Breakfast", | ||
| 2337 | + "meals.slotName.lunch": "Lunch", | ||
| 2338 | + "meals.slotName.dinner": "Dinner", | ||
| 2339 | + "meals.slotName.snack": "Snack", | ||
| 2340 | + "meals.tagName.vegetarian": "Vegetarian", | ||
| 2341 | + "meals.tagName.vegan": "Vegan", | ||
| 2342 | + "meals.tagName.gluten_free": "Gluten-free", | ||
| 2343 | + "meals.tagName.lactose_free": "Lactose-free", | ||
| 2344 | + "meals.tagName.nut_allergy": "Nut allergy", | ||
| 2345 | + "exams.createSubtitle": "Set the course, term and timing first; you add the questions in the next step.", | ||
| 2346 | + "homework.gradeStatusPlaceholder": "Choose a status", | ||
| 2347 | + "homework.gradeStatusRequired": "Choose a status before saving.", | ||
| 2348 | + "combobox.showSuggestions": "Show suggestions", | ||
| 2349 | + "course.removeStudentTitle": "Remove the student from this course?", | ||
| 2350 | + "course.removeStudentHint": "Their enrollment in this class's course is removed; the account itself is not deleted.", | ||
| 2351 | + "course.removeStudentAction": "Remove from course", | ||
| 2352 | + "admin.demoteAdminWarning": "This user will lose their system administrator rights.", | ||
| 2353 | + "instances.policySaved": "Saved", | ||
| 2354 | + "instances.dersSaatiInvalid": "Lesson hours must be a whole number, 0 or more.", | ||
| 2355 | + "instances.karneConfirmTitle": "Change the report card setting?", | ||
| 2356 | + "instances.karneOnHint": "This class's marks in the course will count toward the report card.", | ||
| 2357 | + "instances.karneOffHint": "This class's marks in the course will no longer count toward the report card.", | ||
| 2358 | + "instances.karneTurnOn": "Count toward report card", | ||
| 2359 | + "instances.karneTurnOff": "Stop counting", | ||
| 2360 | + "messages.discardDraftTitle": "Discard this draft?", | ||
| 2361 | + "messages.discardDraftHint": "What you wrote in this message has not been sent and will be lost.", | ||
| 2362 | + "errors.studentOnlyTitle": "This page is for students", | ||
| 2363 | + "errors.parentOnlyTitle": "This page is for parents", | ||
| 2364 | + "errors.audienceOnlyDescription": "This view is shown only to the student or parent signed in to their own account; staff accounts do not open it.", | ||
| 2365 | + "errors.audienceOnlyWithAlternative": "This view is shown only to the student or parent signed in to their own account. The school-wide view of the same data is under management.", | ||
| 2366 | + "errors.openStaffView": "Open the management view", | ||
| 2314 | }; | 2367 | }; |
src/i18n/locales/tr.tsmodified+61 -8
| @@ -159,6 +159,7 @@ export const tr: Dict = { | |||
| 159 | "profile.noCourses": "Gösterilecek ders yok.", | 159 | "profile.noCourses": "Gösterilecek ders yok.", |
| 160 | "profile.stats": "İstatistikler", | 160 | "profile.stats": "İstatistikler", |
| 161 | "profile.statFocusHours": "Odak saati", | 161 | "profile.statFocusHours": "Odak saati", |
| 162 | + "profile.statFocusMinutes": "Odak dakikası", | ||
| 162 | "profile.statSessions": "Odak oturumu", | 163 | "profile.statSessions": "Odak oturumu", |
| 163 | "profile.statHomework": "Teslim edilen ödev", | 164 | "profile.statHomework": "Teslim edilen ödev", |
| 164 | "profile.statOnTime": "Zamanında teslim", | 165 | "profile.statOnTime": "Zamanında teslim", |
| @@ -367,6 +368,8 @@ export const tr: Dict = { | |||
| 367 | "notifications.title": "Bildirimler", | 368 | "notifications.title": "Bildirimler", |
| 368 | "notifications.clearAll": "Tümünü sil", | 369 | "notifications.clearAll": "Tümünü sil", |
| 369 | "notifications.dismiss": "Sil", | 370 | "notifications.dismiss": "Sil", |
| 371 | + "notifications.clearAllConfirmTitle": "Tüm bildirimler silinsin mi?", | ||
| 372 | + "notifications.clearAllConfirmSummary": "Listedeki {count} bildirim kaldırılacak.", | ||
| 370 | "notifications.empty": "Henüz yeni bir bildiriminiz yok.", | 373 | "notifications.empty": "Henüz yeni bir bildiriminiz yok.", |
| 371 | "notifications.tabAll": "Tümü", | 374 | "notifications.tabAll": "Tümü", |
| 372 | "notifications.tabSystem": "Sistem", | 375 | "notifications.tabSystem": "Sistem", |
| @@ -501,10 +504,12 @@ export const tr: Dict = { | |||
| 501 | "roster.addStudent": "Öğrenci ekle", | 504 | "roster.addStudent": "Öğrenci ekle", |
| 502 | "roster.addTeacher": "Öğretmen ekle", | 505 | "roster.addTeacher": "Öğretmen ekle", |
| 503 | "roster.studentsSubtitle": "Kurumdaki tüm öğrenciler, sınıflarıyla birlikte.", | 506 | "roster.studentsSubtitle": "Kurumdaki tüm öğrenciler, sınıflarıyla birlikte.", |
| 504 | - "roster.teachersSubtitle": "Kurumdaki öğretmenler ve sınıf öğretmenliği yaptıkları sınıflar.", | 507 | + "roster.teachersSubtitle": "Kurumdaki öğretmenler, verdikleri dersler ve sınıf öğretmenliği yaptıkları sınıflar.", |
| 505 | "roster.searchStudents": "Öğrenci adı veya kullanıcı adı ara…", | 508 | "roster.searchStudents": "Öğrenci adı veya kullanıcı adı ara…", |
| 506 | "roster.searchTeachers": "Öğretmen adı veya kullanıcı adı ara…", | 509 | "roster.searchTeachers": "Öğretmen adı veya kullanıcı adı ara…", |
| 507 | "roster.noTeachers": "Henüz öğretmen yok.", | 510 | "roster.noTeachers": "Henüz öğretmen yok.", |
| 511 | + "roster.taughtSections": "Verdiği dersler", | ||
| 512 | + "roster.homeroomOf": "Sınıf öğretmenliği", | ||
| 508 | "builder.console": "Operatör konsolu", | 513 | "builder.console": "Operatör konsolu", |
| 509 | "builder.logout": "Çıkış yap", | 514 | "builder.logout": "Çıkış yap", |
| 510 | "builder.loginTitle": "Operatör girişi", | 515 | "builder.loginTitle": "Operatör girişi", |
| @@ -630,7 +635,7 @@ export const tr: Dict = { | |||
| 630 | "modules.offDescription": "Bu modül okulunuzda şu an kullanıma açık değil. İhtiyacınız varsa okul yöneticinizle iletişime geçin.", | 635 | "modules.offDescription": "Bu modül okulunuzda şu an kullanıma açık değil. İhtiyacınız varsa okul yöneticinizle iletişime geçin.", |
| 631 | "common.learnMore": "Daha fazla", | 636 | "common.learnMore": "Daha fazla", |
| 632 | "common.gotIt": "Anladım", | 637 | "common.gotIt": "Anladım", |
| 633 | - "confirm.review": "Lütfen kaydetmeden önce değişiklikleri gözden geçirin.", | 638 | + "confirm.review": "Onaylamadan önce aşağıdaki özeti kontrol et.", |
| 634 | "confirm.summary": "İşlem özeti", | 639 | "confirm.summary": "İşlem özeti", |
| 635 | "confirm.confirmDelete": "Evet, sil", | 640 | "confirm.confirmDelete": "Evet, sil", |
| 636 | "confirm.confirmUpdate": "Evet, güncelle", | 641 | "confirm.confirmUpdate": "Evet, güncelle", |
| @@ -656,6 +661,9 @@ export const tr: Dict = { | |||
| 656 | "common.noResults": "Sonuç yok.", | 661 | "common.noResults": "Sonuç yok.", |
| 657 | "common.scrollHint": "Yatay kaydır", | 662 | "common.scrollHint": "Yatay kaydır", |
| 658 | "common.noMatches": "Aramanızla eşleşen kayıt yok.", | 663 | "common.noMatches": "Aramanızla eşleşen kayıt yok.", |
| 664 | + "common.noMatchesFor": "“{query}” için sonuç yok.", | ||
| 665 | + "common.noFilterMatches": "Seçili filtrelerle eşleşen kayıt yok.", | ||
| 666 | + "common.clearFilters": "Filtreleri temizle", | ||
| 659 | "common.creator": "Oluşturan", | 667 | "common.creator": "Oluşturan", |
| 660 | "common.searchPlaceholder": "Ara…", | 668 | "common.searchPlaceholder": "Ara…", |
| 661 | "common.all": "Tümü", | 669 | "common.all": "Tümü", |
| @@ -740,9 +748,9 @@ export const tr: Dict = { | |||
| 740 | "form.fieldRequired": "Bu alan zorunlu.", | 748 | "form.fieldRequired": "Bu alan zorunlu.", |
| 741 | "common.close": "Kapat", | 749 | "common.close": "Kapat", |
| 742 | "common.dismiss": "Gizle", | 750 | "common.dismiss": "Gizle", |
| 743 | - "sidePanel.discardTitle": "Değişiklikler silinsin mi?", | 751 | + "sidePanel.discardTitle": "Değişiklikler atılsın mı?", |
| 744 | "sidePanel.discardSummary": "Bu forma girdikleriniz kaydedilmedi ve kaybolacak.", | 752 | "sidePanel.discardSummary": "Bu forma girdikleriniz kaydedilmedi ve kaybolacak.", |
| 745 | - "sidePanel.discard": "Sil ve kapat", | 753 | + "sidePanel.discard": "Değişiklikleri at", |
| 746 | "sidePanel.keepEditing": "Düzenlemeye devam et", | 754 | "sidePanel.keepEditing": "Düzenlemeye devam et", |
| 747 | "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.", | 755 | "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.", |
| 748 | "common.breadcrumb": "Sayfa konumu", | 756 | "common.breadcrumb": "Sayfa konumu", |
| @@ -810,7 +818,7 @@ export const tr: Dict = { | |||
| 810 | "dashboard.stats.notes": "Notlar", | 818 | "dashboard.stats.notes": "Notlar", |
| 811 | "dashboard.stats.events": "Etkinlikler", | 819 | "dashboard.stats.events": "Etkinlikler", |
| 812 | "dashboard.stats.exams": "Sınavlar", | 820 | "dashboard.stats.exams": "Sınavlar", |
| 813 | - "dashboard.stats.courses": "Eğitim", | 821 | + "dashboard.stats.courses": "Dersler", |
| 814 | "dashboard.stats.role": "Rolün", | 822 | "dashboard.stats.role": "Rolün", |
| 815 | "dashboard.stats.average": "Ortalama", | 823 | "dashboard.stats.average": "Ortalama", |
| 816 | "dashboard.stats.averageHint": "Genel karne", | 824 | "dashboard.stats.averageHint": "Genel karne", |
| @@ -1354,6 +1362,9 @@ export const tr: Dict = { | |||
| 1354 | "exams.allowReview": "Öğrenciler cevaplarını inceleyebilsin", | 1362 | "exams.allowReview": "Öğrenciler cevaplarını inceleyebilsin", |
| 1355 | "exams.allowReviewHelp": "Bu sınavı notlandırdığınızda öğrenciler kendi kağıtlarını ve geçmiş denemelerini görebilir.", | 1363 | "exams.allowReviewHelp": "Bu sınavı notlandırdığınızda öğrenciler kendi kağıtlarını ve geçmiş denemelerini görebilir.", |
| 1356 | "exams.draft": "Taslak", | 1364 | "exams.draft": "Taslak", |
| 1365 | + "exams.emptyUpcoming": "Yaklaşan sınav yok.", | ||
| 1366 | + "exams.emptyCompleted": "Biten sınav yok.", | ||
| 1367 | + "exams.emptyDraft": "Taslak sınav yok.", | ||
| 1357 | "exams.draftHelp": "Yayınlanana kadar öğrencilerden gizle.", | 1368 | "exams.draftHelp": "Yayınlanana kadar öğrencilerden gizle.", |
| 1358 | "exams.publish": "Sınavı yayınla", | 1369 | "exams.publish": "Sınavı yayınla", |
| 1359 | "exams.published": "Sınav yayınlandı", | 1370 | "exams.published": "Sınav yayınlandı", |
| @@ -1705,6 +1716,9 @@ export const tr: Dict = { | |||
| 1705 | "courses.pageSubtitle": "Dersler, etütler ve kulüplerin tümü tek bir yerde.", | 1716 | "courses.pageSubtitle": "Dersler, etütler ve kulüplerin tümü tek bir yerde.", |
| 1706 | "courses.create": "Yeni eğitim kaydı", | 1717 | "courses.create": "Yeni eğitim kaydı", |
| 1707 | "courses.empty": "Henüz {item} yok.", | 1718 | "courses.empty": "Henüz {item} yok.", |
| 1719 | + "courses.sectionsFilter": "Şube", | ||
| 1720 | + "courses.withSections": "Şubesi olan", | ||
| 1721 | + "courses.withoutSections": "Şubesi olmayan", | ||
| 1708 | "courses.enrolled": "Kayıtlı", | 1722 | "courses.enrolled": "Kayıtlı", |
| 1709 | "courses.roster": "Sınıf listesi", | 1723 | "courses.roster": "Sınıf listesi", |
| 1710 | "courses.rosterItem": "Öğrenci", | 1724 | "courses.rosterItem": "Öğrenci", |
| @@ -1754,7 +1768,7 @@ export const tr: Dict = { | |||
| 1754 | "homework.dueAt": "Son teslim", | 1768 | "homework.dueAt": "Son teslim", |
| 1755 | "homework.assigned": "Atanan", | 1769 | "homework.assigned": "Atanan", |
| 1756 | "homework.wholeCourse": "Tüm ders", | 1770 | "homework.wholeCourse": "Tüm ders", |
| 1757 | - "homework.wholeCourseHelp": "İlk sürüm ödevi tüm derse atar. Öğrenci alt grupları için çoklu seçim arayüzü gelene kadar backend API kullanılabilir.", | 1771 | + "homework.wholeCourseHelp": "Ödev, bu derse kayıtlı tüm öğrencilere atanır.", |
| 1758 | "homework.dueRequired": "Geçerli bir son teslim tarihi ve saati seç.", | 1772 | "homework.dueRequired": "Geçerli bir son teslim tarihi ve saati seç.", |
| 1759 | "homework.mineTitle": "Ödevlerim", | 1773 | "homework.mineTitle": "Ödevlerim", |
| 1760 | "homework.submit": "Ödevi teslim et", | 1774 | "homework.submit": "Ödevi teslim et", |
| @@ -1786,6 +1800,9 @@ export const tr: Dict = { | |||
| 1786 | "marks.title": "Karnem", | 1800 | "marks.title": "Karnem", |
| 1787 | "marks.subtitle": "Kayıtlı olduğunuz tüm derslerdeki ağırlıklı not ortalamalarınız.", | 1801 | "marks.subtitle": "Kayıtlı olduğunuz tüm derslerdeki ağırlıklı not ortalamalarınız.", |
| 1788 | "marks.overall": "Genel ortalama", | 1802 | "marks.overall": "Genel ortalama", |
| 1803 | + "marks.band": "Not bandı", | ||
| 1804 | + "marks.bandLabel": "Bant {grade}", | ||
| 1805 | + "marks.examCount": "Sınav sayısı", | ||
| 1789 | "marks.averageCapped": "Ortalama sütunu en fazla {cap} öğrencili okullarda doldurulur. Raporu görmek için öğrenciyi aç.", | 1806 | "marks.averageCapped": "Ortalama sütunu en fazla {cap} öğrencili okullarda doldurulur. Raporu görmek için öğrenciyi aç.", |
| 1790 | "marks.courseAvg": "Ders ortalaması", | 1807 | "marks.courseAvg": "Ders ortalaması", |
| 1791 | "marks.empty": "Henüz hiçbir derse kayıtlı değilsin.", | 1808 | "marks.empty": "Henüz hiçbir derse kayıtlı değilsin.", |
| @@ -1937,7 +1954,7 @@ export const tr: Dict = { | |||
| 1937 | "meals.capacity": "Kapasite", | 1954 | "meals.capacity": "Kapasite", |
| 1938 | "meals.reservations": "Rezervasyon", | 1955 | "meals.reservations": "Rezervasyon", |
| 1939 | "meals.from": "Başlangıç tarihi", | 1956 | "meals.from": "Başlangıç tarihi", |
| 1940 | - "meals.empty": "Bu tarih aralığında menü yok.", | 1957 | + "meals.empty": "Bu tarihten itibaren menü yok.", |
| 1941 | "meals.dishes": "yemek", | 1958 | "meals.dishes": "yemek", |
| 1942 | "meals.conflict": "Beslenme uyarısı", | 1959 | "meals.conflict": "Beslenme uyarısı", |
| 1943 | "meals.topPick": "En çok tercih", | 1960 | "meals.topPick": "En çok tercih", |
| @@ -2046,6 +2063,7 @@ export const tr: Dict = { | |||
| 2046 | "payments.assign": "Ata", | 2063 | "payments.assign": "Ata", |
| 2047 | "payments.assignHelp": "Atama, tüm taksitleri anında ücret olarak yansıtır. Planda olan öğrenciye tekrar ücret çıkmaz.", | 2064 | "payments.assignHelp": "Atama, tüm taksitleri anında ücret olarak yansıtır. Planda olan öğrenciye tekrar ücret çıkmaz.", |
| 2048 | "payments.selectStudent": "Öğrenci seç", | 2065 | "payments.selectStudent": "Öğrenci seç", |
| 2066 | + "payments.searchStudents": "Öğrenci ara…", | ||
| 2049 | "payments.assignments": "Atanan öğrenciler", | 2067 | "payments.assignments": "Atanan öğrenciler", |
| 2050 | "payments.noAssignments": "Henüz öğrenci atanmadı.", | 2068 | "payments.noAssignments": "Henüz öğrenci atanmadı.", |
| 2051 | "payments.outcomeAssigned": "Atandı", | 2069 | "payments.outcomeAssigned": "Atandı", |
| @@ -2201,7 +2219,7 @@ export const tr: Dict = { | |||
| 2201 | "search.hint.bank": "Soru metninde ge\u00e7en bir ifadeyi arar.", | 2219 | "search.hint.bank": "Soru metninde ge\u00e7en bir ifadeyi arar.", |
| 2202 | "search.hint.whiteboards": "A\u00e7\u0131k olan sayfadaki tahta ba\u015fl\u0131klar\u0131nda arar.", | 2220 | "search.hint.whiteboards": "A\u00e7\u0131k olan sayfadaki tahta ba\u015fl\u0131klar\u0131nda arar.", |
| 2203 | "search.hint.chat": "Bu sohbetteki mesajlar\u0131n metninde arar.", | 2221 | "search.hint.chat": "Bu sohbetteki mesajlar\u0131n metninde arar.", |
| 2204 | - "search.hint.deadlines": "Yakla\u015fan kay\u0131tlar\u0131n ba\u015fl\u0131\u011f\u0131nda arar.", | 2222 | + "search.hint.deadlines": "Yaklaşan kayıtların başlığında ve ders — şube adında arar.", |
| 2205 | "search.hint.homework": "\u00d6dev ad\u0131, a\u00e7\u0131klamas\u0131 ve dersinde arar.", | 2223 | "search.hint.homework": "\u00d6dev ad\u0131, a\u00e7\u0131klamas\u0131 ve dersinde arar.", |
| 2206 | "search.hint.paymentsStudents": "\u00d6\u011frencinin ad\u0131nda, soyad\u0131nda veya kullan\u0131c\u0131 ad\u0131nda arar.", | 2224 | "search.hint.paymentsStudents": "\u00d6\u011frencinin ad\u0131nda, soyad\u0131nda veya kullan\u0131c\u0131 ad\u0131nda arar.", |
| 2207 | "work.userNotFound": "Bu kullanıcı için mesai kaydı bulunamadı.", | 2225 | "work.userNotFound": "Bu kullanıcı için mesai kaydı bulunamadı.", |
| @@ -2307,4 +2325,39 @@ export const tr: Dict = { | |||
| 2307 | "attendance.overLimit": "Sınır aşıldı", | 2325 | "attendance.overLimit": "Sınır aşıldı", |
| 2308 | "common.yes": "Evet", | 2326 | "common.yes": "Evet", |
| 2309 | "common.no": "Hayır", | 2327 | "common.no": "Hayır", |
| 2328 | + "settings.leaveHint": "Ayarlardaki kaydedilmemiş değişiklikler kaybolacak.", | ||
| 2329 | + "exams.kind.yazili": "Yazılı", | ||
| 2330 | + "exams.kind.uygulama": "Uygulama", | ||
| 2331 | + "exams.kind.performans": "Performans", | ||
| 2332 | + "meals.slotName.breakfast": "Kahvaltı", | ||
| 2333 | + "meals.slotName.lunch": "Öğle yemeği", | ||
| 2334 | + "meals.slotName.dinner": "Akşam yemeği", | ||
| 2335 | + "meals.slotName.snack": "Ara öğün", | ||
| 2336 | + "meals.tagName.vegetarian": "Vejetaryen", | ||
| 2337 | + "meals.tagName.vegan": "Vegan", | ||
| 2338 | + "meals.tagName.gluten_free": "Glutensiz", | ||
| 2339 | + "meals.tagName.lactose_free": "Laktozsuz", | ||
| 2340 | + "meals.tagName.nut_allergy": "Kuruyemiş alerjisi", | ||
| 2341 | + "exams.createSubtitle": "Önce ders, dönem ve zamanlamayı belirle; soruları bir sonraki adımda eklersin.", | ||
| 2342 | + "homework.gradeStatusPlaceholder": "Durum seç", | ||
| 2343 | + "homework.gradeStatusRequired": "Kaydetmeden önce bir durum seç.", | ||
| 2344 | + "combobox.showSuggestions": "Önerileri göster", | ||
| 2345 | + "course.removeStudentTitle": "Öğrenci bu dersten çıkarılsın mı?", | ||
| 2346 | + "course.removeStudentHint": "Öğrencinin bu şubedeki ders kaydı kaldırılır; hesabı silinmez.", | ||
| 2347 | + "course.removeStudentAction": "Dersten çıkar", | ||
| 2348 | + "admin.demoteAdminWarning": "Bu kullanıcı sistem yöneticisi yetkilerini kaybedecek.", | ||
| 2349 | + "instances.policySaved": "Kaydedildi", | ||
| 2350 | + "instances.dersSaatiInvalid": "Ders saati 0 veya daha büyük bir tam sayı olmalı.", | ||
| 2351 | + "instances.karneConfirmTitle": "Karne ayarı değiştirilsin mi?", | ||
| 2352 | + "instances.karneOnHint": "Bu şubedeki dersin notları karneye işlenecek.", | ||
| 2353 | + "instances.karneOffHint": "Bu şubedeki dersin notları artık karneye işlenmeyecek.", | ||
| 2354 | + "instances.karneTurnOn": "Karneye işle", | ||
| 2355 | + "instances.karneTurnOff": "Karneye işleme", | ||
| 2356 | + "messages.discardDraftTitle": "Taslak atılsın mı?", | ||
| 2357 | + "messages.discardDraftHint": "Bu mesaja yazdıkların gönderilmedi ve kaybolacak.", | ||
| 2358 | + "errors.studentOnlyTitle": "Bu sayfa öğrenciler için", | ||
| 2359 | + "errors.parentOnlyTitle": "Bu sayfa veliler için", | ||
| 2360 | + "errors.audienceOnlyDescription": "Bu görünüm yalnızca kendi hesabıyla giriş yapan öğrenci ya da veliye gösterilir; personel hesaplarında açılmaz.", | ||
| 2361 | + "errors.audienceOnlyWithAlternative": "Bu görünüm yalnızca kendi hesabıyla giriş yapan öğrenci ya da veliye gösterilir. Aynı bilgilerin okul geneli görünümü yönetim bölümünde.", | ||
| 2362 | + "errors.openStaffView": "Yönetim görünümünü aç", | ||
| 2310 | }; | 2363 | }; |
src/i18n/messages.tsmodified+54 -1
| @@ -149,6 +149,7 @@ export type MessageKey = | |||
| 149 | | "profile.noCourses" | 149 | | "profile.noCourses" |
| 150 | | "profile.stats" | 150 | | "profile.stats" |
| 151 | | "profile.statFocusHours" | 151 | | "profile.statFocusHours" |
| 152 | + | "profile.statFocusMinutes" | ||
| 152 | | "profile.statSessions" | 153 | | "profile.statSessions" |
| 153 | | "profile.statHomework" | 154 | | "profile.statHomework" |
| 154 | | "profile.statOnTime" | 155 | | "profile.statOnTime" |
| @@ -474,6 +475,8 @@ export type MessageKey = | |||
| 474 | | "roster.searchStudents" | 475 | | "roster.searchStudents" |
| 475 | | "roster.searchTeachers" | 476 | | "roster.searchTeachers" |
| 476 | | "roster.noTeachers" | 477 | | "roster.noTeachers" |
| 478 | + | "roster.taughtSections" | ||
| 479 | + | "roster.homeroomOf" | ||
| 477 | | "builder.console" | 480 | | "builder.console" |
| 478 | | "builder.logout" | 481 | | "builder.logout" |
| 479 | | "builder.loginTitle" | 482 | | "builder.loginTitle" |
| @@ -573,6 +576,8 @@ export type MessageKey = | |||
| 573 | | "notifications.title" | 576 | | "notifications.title" |
| 574 | | "notifications.clearAll" | 577 | | "notifications.clearAll" |
| 575 | | "notifications.dismiss" | 578 | | "notifications.dismiss" |
| 579 | + | "notifications.clearAllConfirmTitle" | ||
| 580 | + | "notifications.clearAllConfirmSummary" | ||
| 576 | | "notifications.empty" | 581 | | "notifications.empty" |
| 577 | | "notifications.tabAll" | 582 | | "notifications.tabAll" |
| 578 | | "notifications.tabSystem" | 583 | | "notifications.tabSystem" |
| @@ -644,6 +649,9 @@ export type MessageKey = | |||
| 644 | | "common.noResults" | 649 | | "common.noResults" |
| 645 | | "common.scrollHint" | 650 | | "common.scrollHint" |
| 646 | | "common.noMatches" | 651 | | "common.noMatches" |
| 652 | + | "common.noMatchesFor" | ||
| 653 | + | "common.noFilterMatches" | ||
| 654 | + | "common.clearFilters" | ||
| 647 | | "common.creator" | 655 | | "common.creator" |
| 648 | | "common.searchPlaceholder" | 656 | | "common.searchPlaceholder" |
| 649 | | "common.all" | 657 | | "common.all" |
| @@ -1257,6 +1265,9 @@ export type MessageKey = | |||
| 1257 | | "exams.allowReview" | 1265 | | "exams.allowReview" |
| 1258 | | "exams.allowReviewHelp" | 1266 | | "exams.allowReviewHelp" |
| 1259 | | "exams.draft" | 1267 | | "exams.draft" |
| 1268 | + | "exams.emptyUpcoming" | ||
| 1269 | + | "exams.emptyCompleted" | ||
| 1270 | + | "exams.emptyDraft" | ||
| 1260 | | "exams.draftHelp" | 1271 | | "exams.draftHelp" |
| 1261 | | "exams.publish" | 1272 | | "exams.publish" |
| 1262 | | "exams.published" | 1273 | | "exams.published" |
| @@ -1603,6 +1614,9 @@ export type MessageKey = | |||
| 1603 | | "courses.pageSubtitle" | 1614 | | "courses.pageSubtitle" |
| 1604 | | "courses.create" | 1615 | | "courses.create" |
| 1605 | | "courses.empty" | 1616 | | "courses.empty" |
| 1617 | + | "courses.sectionsFilter" | ||
| 1618 | + | "courses.withSections" | ||
| 1619 | + | "courses.withoutSections" | ||
| 1606 | | "courses.enrolled" | 1620 | | "courses.enrolled" |
| 1607 | | "courses.roster" | 1621 | | "courses.roster" |
| 1608 | | "courses.rosterItem" | 1622 | | "courses.rosterItem" |
| @@ -1684,6 +1698,9 @@ export type MessageKey = | |||
| 1684 | | "marks.title" | 1698 | | "marks.title" |
| 1685 | | "marks.subtitle" | 1699 | | "marks.subtitle" |
| 1686 | | "marks.overall" | 1700 | | "marks.overall" |
| 1701 | + | "marks.band" | ||
| 1702 | + | "marks.bandLabel" | ||
| 1703 | + | "marks.examCount" | ||
| 1687 | | "marks.averageCapped" | 1704 | | "marks.averageCapped" |
| 1688 | | "marks.courseAvg" | 1705 | | "marks.courseAvg" |
| 1689 | | "marks.empty" | 1706 | | "marks.empty" |
| @@ -1944,6 +1961,7 @@ export type MessageKey = | |||
| 1944 | | "payments.assign" | 1961 | | "payments.assign" |
| 1945 | | "payments.assignHelp" | 1962 | | "payments.assignHelp" |
| 1946 | | "payments.selectStudent" | 1963 | | "payments.selectStudent" |
| 1964 | + | "payments.searchStudents" | ||
| 1947 | | "payments.assignments" | 1965 | | "payments.assignments" |
| 1948 | | "payments.noAssignments" | 1966 | | "payments.noAssignments" |
| 1949 | | "payments.outcomeAssigned" | 1967 | | "payments.outcomeAssigned" |
| @@ -2290,7 +2308,42 @@ export type MessageKey = | |||
| 2290 | | "attendance.unexcusedDays" | 2308 | | "attendance.unexcusedDays" |
| 2291 | | "attendance.overLimit" | 2309 | | "attendance.overLimit" |
| 2292 | | "common.yes" | 2310 | | "common.yes" |
| 2293 | - | "common.no"; | 2311 | + | "common.no" |
| 2312 | + | "settings.leaveHint" | ||
| 2313 | + | "exams.kind.yazili" | ||
| 2314 | + | "exams.kind.uygulama" | ||
| 2315 | + | "exams.kind.performans" | ||
| 2316 | + | "meals.slotName.breakfast" | ||
| 2317 | + | "meals.slotName.lunch" | ||
| 2318 | + | "meals.slotName.dinner" | ||
| 2319 | + | "meals.slotName.snack" | ||
| 2320 | + | "meals.tagName.vegetarian" | ||
| 2321 | + | "meals.tagName.vegan" | ||
| 2322 | + | "meals.tagName.gluten_free" | ||
| 2323 | + | "meals.tagName.lactose_free" | ||
| 2324 | + | "meals.tagName.nut_allergy" | ||
| 2325 | + | "exams.createSubtitle" | ||
| 2326 | + | "homework.gradeStatusPlaceholder" | ||
| 2327 | + | "homework.gradeStatusRequired" | ||
| 2328 | + | "combobox.showSuggestions" | ||
| 2329 | + | "course.removeStudentTitle" | ||
| 2330 | + | "course.removeStudentHint" | ||
| 2331 | + | "course.removeStudentAction" | ||
| 2332 | + | "admin.demoteAdminWarning" | ||
| 2333 | + | "instances.policySaved" | ||
| 2334 | + | "instances.dersSaatiInvalid" | ||
| 2335 | + | "instances.karneConfirmTitle" | ||
| 2336 | + | "instances.karneOnHint" | ||
| 2337 | + | "instances.karneOffHint" | ||
| 2338 | + | "instances.karneTurnOn" | ||
| 2339 | + | "instances.karneTurnOff" | ||
| 2340 | + | "messages.discardDraftTitle" | ||
| 2341 | + | "messages.discardDraftHint" | ||
| 2342 | + | "errors.studentOnlyTitle" | ||
| 2343 | + | "errors.parentOnlyTitle" | ||
| 2344 | + | "errors.audienceOnlyDescription" | ||
| 2345 | + | "errors.audienceOnlyWithAlternative" | ||
| 2346 | + | "errors.openStaffView"; | ||
| 2294 | 2347 | ||
| 2295 | export type Dict = Record<MessageKey, string>; | 2348 | export type Dict = Record<MessageKey, string>; |
| 2296 | 2349 | ||
src/index.cssmodified+27 -1
| @@ -4,6 +4,19 @@ | |||
| 4 | 4 | ||
| 5 | @custom-variant dark (&:is([data-kb-theme="dark"] *)); | 5 | @custom-variant dark (&:is([data-kb-theme="dark"] *)); |
| 6 | 6 | ||
| 7 | +/* Touch sizing: a phone-width screen or any coarse pointer. Width alone let a | ||
| 8 | + phone turned to landscape (or a tablet) fall back to desktop density — | ||
| 9 | + 13px fields iOS zooms into and 26px buttons. Put `touch:` after the `sm:` | ||
| 10 | + compact size it overrides; custom variants sort after the breakpoints. */ | ||
| 11 | +@custom-variant touch { | ||
| 12 | + @media (pointer: coarse) { | ||
| 13 | + @slot; | ||
| 14 | + } | ||
| 15 | + @media (width < 40rem) { | ||
| 16 | + @slot; | ||
| 17 | + } | ||
| 18 | +} | ||
| 19 | + | ||
| 7 | @utility container { | 20 | @utility container { |
| 8 | margin-inline: auto; | 21 | margin-inline: auto; |
| 9 | padding-inline: 1.25rem; | 22 | padding-inline: 1.25rem; |
| @@ -157,7 +170,9 @@ | |||
| 157 | } | 170 | } |
| 158 | 171 | ||
| 159 | @utility data-table-wrap { | 172 | @utility data-table-wrap { |
| 160 | - @apply isolate max-h-[65vh] overflow-auto rounded-xl border border-border-line bg-surface-base; | 173 | + /* Scrolls sideways only. A height cap gave the table its own vertical |
| 174 | + * scroller inside the page, clipping the last rows of a page that fit. */ | ||
| 175 | + @apply isolate overflow-x-auto overflow-y-hidden rounded-xl border border-border-line bg-surface-base; | ||
| 161 | } | 176 | } |
| 162 | 177 | ||
| 163 | @utility data-table { | 178 | @utility data-table { |
| @@ -647,3 +662,14 @@ | |||
| 647 | position: absolute; | 662 | position: absolute; |
| 648 | } | 663 | } |
| 649 | } | 664 | } |
| 665 | + | ||
| 666 | +/* iOS Safari zooms the page into any focused field under 16px. Unlayered, so | ||
| 667 | + it outranks every text-* utility on a field, shared or one-off, without | ||
| 668 | + each form having to remember a phone size. */ | ||
| 669 | +@media (pointer: coarse), (width < 40rem) { | ||
| 670 | + input:not([type='checkbox'], [type='radio'], [type='range'], [type='color'], [type='file']), | ||
| 671 | + textarea, | ||
| 672 | + select { | ||
| 673 | + font-size: 16px; | ||
| 674 | + } | ||
| 675 | +} | ||
src/lib/exam-labels.test.tsmodified+13 -0
| @@ -12,3 +12,16 @@ test("unlimited attempts (max 0) falls back to the attempt count", () => { | |||
| 12 | test("no attempt data renders a dash", () => { | 12 | test("no attempt data renders a dash", () => { |
| 13 | expect(attemptLabel({}, 3)).toBe("—"); | 13 | expect(attemptLabel({}, 3)).toBe("—"); |
| 14 | }); | 14 | }); |
| 15 | + | ||
| 16 | +test("exam kind labels: built-in, seeded Turkish keys, and custom fallback", async () => { | ||
| 17 | + const { examKindLabel, isKnownExamKind } = await import("./exam-labels"); | ||
| 18 | + const t = (key: string) => `<${key}>`; | ||
| 19 | + expect(examKindLabel("midterm", t)).toBe("<exams.kind.midterm>"); | ||
| 20 | + expect(examKindLabel("yazili", t)).toBe("<exams.kind.yazili>"); | ||
| 21 | + expect(examKindLabel("sozlu", t)).toBe("<exams.kind.oral>"); | ||
| 22 | + expect(examKindLabel("uygulama", t)).toBe("<exams.kind.uygulama>"); | ||
| 23 | + expect(examKindLabel("deneme", t)).toBe("deneme"); | ||
| 24 | + expect(examKindLabel("toString", t)).toBe("toString"); | ||
| 25 | + // Seeded keys stay renamable in settings. | ||
| 26 | + expect(isKnownExamKind("yazili")).toBe(false); | ||
| 27 | +}); | ||
src/lib/exam-labels.tsmodified+16 -2
| @@ -12,12 +12,26 @@ const EXAM_KIND_LABELS: Record<KnownExamKind, MessageKey> = { | |||
| 12 | oral: "exams.kind.oral", | 12 | oral: "exams.kind.oral", |
| 13 | }; | 13 | }; |
| 14 | 14 | ||
| 15 | +// Kinds a school's settings commonly seed (Turkish ASCII keys). They are | ||
| 16 | +// ordinary school-defined kinds — renamable in settings — but a key like | ||
| 17 | +// "yazili" should still read as "Yazılı" wherever it is shown. | ||
| 18 | +const SEEDED_EXAM_KIND_LABELS: Record<string, MessageKey> = { | ||
| 19 | + yazili: "exams.kind.yazili", | ||
| 20 | + sozlu: "exams.kind.oral", | ||
| 21 | + uygulama: "exams.kind.uygulama", | ||
| 22 | + performans: "exams.kind.performans", | ||
| 23 | + proje: "exams.kind.project", | ||
| 24 | +}; | ||
| 25 | + | ||
| 15 | export function isKnownExamKind(kind: string): kind is KnownExamKind { | 26 | export function isKnownExamKind(kind: string): kind is KnownExamKind { |
| 16 | - return kind in EXAM_KIND_LABELS; | 27 | + return Object.hasOwn(EXAM_KIND_LABELS, kind); |
| 17 | } | 28 | } |
| 18 | 29 | ||
| 30 | +/** Display label for an exam kind key; unknown (custom) kinds show as typed. */ | ||
| 19 | export function examKindLabel(kind: string, t: T): string { | 31 | export function examKindLabel(kind: string, t: T): string { |
| 20 | - return kind in EXAM_KIND_LABELS ? t(EXAM_KIND_LABELS[kind as KnownExamKind]) : kind; | 32 | + if (isKnownExamKind(kind)) return t(EXAM_KIND_LABELS[kind]); |
| 33 | + const seeded = Object.hasOwn(SEEDED_EXAM_KIND_LABELS, kind) ? SEEDED_EXAM_KIND_LABELS[kind] : undefined; | ||
| 34 | + return seeded ? t(seeded) : kind; | ||
| 21 | } | 35 | } |
| 22 | 36 | ||
| 23 | /** Attempts cell for the live monitor. `maxAttempts` comes from the monitored | 37 | /** Attempts cell for the live monitor. `maxAttempts` comes from the monitored |
src/lib/format.tsmodified+12 -0
| @@ -49,3 +49,15 @@ export function examDurationMs(durationMs: number | null | undefined, startsAt: | |||
| 49 | if (startsAt == null || endsAt == null || endsAt <= startsAt) return null; | 49 | if (startsAt == null || endsAt == null || endsAt <= startsAt) return null; |
| 50 | return endsAt - startsAt; | 50 | return endsAt - startsAt; |
| 51 | } | 51 | } |
| 52 | + | ||
| 53 | +/** | ||
| 54 | + * A mark or average with a fixed number of decimals in the reader's locale: | ||
| 55 | + * "68,2" in Turkish, "68.2" in English. | ||
| 56 | + */ | ||
| 57 | +export function formatDecimal(value: number | null | undefined, locale: Locale = "en", digits = 1): string { | ||
| 58 | + if (value == null || !Number.isFinite(value)) return "—"; | ||
| 59 | + return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US", { | ||
| 60 | + minimumFractionDigits: digits, | ||
| 61 | + maximumFractionDigits: digits, | ||
| 62 | + }).format(value); | ||
| 63 | +} | ||
src/lib/homework-grade.test.tsadded+22 -0
| @@ -0,0 +1,22 @@ | |||
| 1 | +import { expect, test } from "vitest"; | ||
| 2 | +import type { HomeworkRosterEntry } from "@/api/client"; | ||
| 3 | +import { defaultGradeStatus } from "./homework-grade"; | ||
| 4 | + | ||
| 5 | +const submission = {} as NonNullable<HomeworkRosterEntry["submission"]>; | ||
| 6 | +const result = (status: string) => ({ status }) as NonNullable<HomeworkRosterEntry["result"]>; | ||
| 7 | + | ||
| 8 | +test("a saved result wins", () => { | ||
| 9 | + expect(defaultGradeStatus({ result: result("incomplete"), missing: true, submission: null })).toBe("incomplete"); | ||
| 10 | +}); | ||
| 11 | + | ||
| 12 | +test("a non-submitter past the deadline defaults to missing", () => { | ||
| 13 | + expect(defaultGradeStatus({ result: null, missing: true, submission: null })).toBe("missing"); | ||
| 14 | +}); | ||
| 15 | + | ||
| 16 | +test("a submitter defaults to done", () => { | ||
| 17 | + expect(defaultGradeStatus({ result: null, missing: false, submission })).toBe("done"); | ||
| 18 | +}); | ||
| 19 | + | ||
| 20 | +test("a non-submitter before the deadline has no default", () => { | ||
| 21 | + expect(defaultGradeStatus({ result: null, missing: false, submission: null })).toBe(""); | ||
| 22 | +}); | ||
src/lib/homework-grade.tsadded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +import type { HomeworkRosterEntry } from "@/api/client"; | ||
| 2 | + | ||
| 3 | +/** | ||
| 4 | + * The status the grading panel opens with: the saved result, else "missing" | ||
| 5 | + * once the deadline passed with nothing handed in, else "done" only for a | ||
| 6 | + * student who did submit. A non-submitter before the deadline gets "" — the | ||
| 7 | + * grader has to choose, so one quick save never marks them as done. | ||
| 8 | + */ | ||
| 9 | +export function defaultGradeStatus(row: Pick<HomeworkRosterEntry, "result" | "missing" | "submission">): string { | ||
| 10 | + if (row.result?.status) return row.result.status; | ||
| 11 | + if (row.missing) return "missing"; | ||
| 12 | + return row.submission ? "done" : ""; | ||
| 13 | +} | ||
src/lib/instance-labels.test.tsadded+62 -0
| @@ -0,0 +1,62 @@ | |||
| 1 | +import { formatInstanceLabel, loadInstanceLabels, resetInstanceLabelCache } from "./instance-labels"; | ||
| 2 | + | ||
| 3 | +const calls: string[] = []; | ||
| 4 | + | ||
| 5 | +vi.mock("@/api/instances", () => ({ | ||
| 6 | + getInstanceById: async (id: string) => { | ||
| 7 | + calls.push(`instance:${id}`); | ||
| 8 | + if (id === "missing") throw new Error("404"); | ||
| 9 | + return { id, course: id === "i2" ? "c-math" : "c-math", class: id === "i2" ? "k-9a" : "k-10b" }; | ||
| 10 | + }, | ||
| 11 | +})); | ||
| 12 | +vi.mock("@/api/courses", () => ({ | ||
| 13 | + getCourseById: async (id: string) => { | ||
| 14 | + calls.push(`course:${id}`); | ||
| 15 | + return { id, title: "Matematik" }; | ||
| 16 | + }, | ||
| 17 | +})); | ||
| 18 | +vi.mock("@/api/classes", () => ({ | ||
| 19 | + getClassById: async (id: string) => { | ||
| 20 | + calls.push(`class:${id}`); | ||
| 21 | + return { id, name: id === "k-9a" ? "9-A" : "10-B" }; | ||
| 22 | + }, | ||
| 23 | + getMyClasses: async () => { | ||
| 24 | + calls.push("classes:me"); | ||
| 25 | + return { items: [{ id: "k-10b", name: "10-B" }], total: 1, limit: null, offset: 0 }; | ||
| 26 | + }, | ||
| 27 | +})); | ||
| 28 | + | ||
| 29 | +describe("instance labels", () => { | ||
| 30 | + beforeEach(() => { | ||
| 31 | + calls.length = 0; | ||
| 32 | + resetInstanceLabelCache(); | ||
| 33 | + }); | ||
| 34 | + | ||
| 35 | + it("names the class next to the course so two sections of one ders differ", async () => { | ||
| 36 | + const labels = await loadInstanceLabels(["i1", "i2", "i1"], "admin"); | ||
| 37 | + expect(labels.get("i1")?.label).toBe("Matematik — 10-B"); | ||
| 38 | + expect(labels.get("i2")?.label).toBe("Matematik — 9-A"); | ||
| 39 | + // The shared course is read once. | ||
| 40 | + expect(calls.filter((call) => call === "course:c-math")).toHaveLength(1); | ||
| 41 | + }); | ||
| 42 | + | ||
| 43 | + it("reads a student's class names from /classes/me, never /classes/{id}", async () => { | ||
| 44 | + const labels = await loadInstanceLabels(["i1", "i2"], "student"); | ||
| 45 | + expect(labels.get("i1")?.label).toBe("Matematik — 10-B"); | ||
| 46 | + // 9-A is not the student's class: the label falls back to the course title. | ||
| 47 | + expect(labels.get("i2")?.label).toBe("Matematik"); | ||
| 48 | + expect(calls.some((call) => call.startsWith("class:"))).toBe(false); | ||
| 49 | + expect(calls.filter((call) => call === "classes:me")).toHaveLength(1); | ||
| 50 | + }); | ||
| 51 | + | ||
| 52 | + it("drops an unreadable instance instead of inventing a label", async () => { | ||
| 53 | + const labels = await loadInstanceLabels(["missing"], "admin"); | ||
| 54 | + expect(labels.has("missing")).toBe(false); | ||
| 55 | + }); | ||
| 56 | + | ||
| 57 | + it("formats partial labels", () => { | ||
| 58 | + expect(formatInstanceLabel("Fizik", null)).toBe("Fizik"); | ||
| 59 | + expect(formatInstanceLabel(null, "9-A")).toBe("9-A"); | ||
| 60 | + expect(formatInstanceLabel(null, null)).toBe(""); | ||
| 61 | + }); | ||
| 62 | +}); | ||
src/lib/instance-labels.tsadded+153 -0
| @@ -0,0 +1,153 @@ | |||
| 1 | +import { createEffect, createSignal, onCleanup } from "solid-js"; | ||
| 2 | +import { getClassById, getMyClasses } from "@/api/classes"; | ||
| 3 | +import { getCourseById } from "@/api/courses"; | ||
| 4 | +import { getInstanceById } from "@/api/instances"; | ||
| 5 | +import type { Role } from "@/api/client"; | ||
| 6 | +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; | ||
| 7 | +import { hasMinRole } from "@/lib/roles"; | ||
| 8 | + | ||
| 9 | +/** | ||
| 10 | + * "<ders> — <şube>" for a şube×ders instance. | ||
| 11 | + * | ||
| 12 | + * Exams and homework name an instance (`class_course`), never a course. The | ||
| 13 | + * same ders taught in two şubeler therefore produces rows with the same title, | ||
| 14 | + * and only the şube tells them apart — so every surface listing them labels a | ||
| 15 | + * row through here instead of showing the catalog title alone. | ||
| 16 | + * | ||
| 17 | + * Reads, all cached for the tab (a section never changes its course or class): | ||
| 18 | + * - `GET /instances/{id}` for the course and class ids, | ||
| 19 | + * - `GET /courses/{id}` for the catalog title, | ||
| 20 | + * - the class name: `GET /classes/{id}` for teacher+ (that route is teacher+ | ||
| 21 | + * only), `GET /classes/me` once for anyone else. | ||
| 22 | + * A read the caller may not make just leaves that part out of the label. | ||
| 23 | + */ | ||
| 24 | +export type InstanceLabel = { | ||
| 25 | + course: string; | ||
| 26 | + class: string; | ||
| 27 | + courseTitle: string | null; | ||
| 28 | + className: string | null; | ||
| 29 | + label: string; | ||
| 30 | +}; | ||
| 31 | + | ||
| 32 | +const instanceCache = new Map<string, Promise<InstanceLabel | null>>(); | ||
| 33 | +const courseCache = new Map<string, Promise<string | null>>(); | ||
| 34 | +const classCache = new Map<string, Promise<string | null>>(); | ||
| 35 | +let myClassesCache: Promise<Map<string, string>> | null = null; | ||
| 36 | + | ||
| 37 | +function courseTitle(id: string): Promise<string | null> { | ||
| 38 | + let hit = courseCache.get(id); | ||
| 39 | + if (!hit) { | ||
| 40 | + hit = getCourseById(id).then( | ||
| 41 | + (course) => course.title, | ||
| 42 | + () => { | ||
| 43 | + courseCache.delete(id); | ||
| 44 | + return null; | ||
| 45 | + }, | ||
| 46 | + ); | ||
| 47 | + courseCache.set(id, hit); | ||
| 48 | + } | ||
| 49 | + return hit; | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +function className(id: string, role: Role | undefined): Promise<string | null> { | ||
| 53 | + if (hasMinRole(role, "teacher")) { | ||
| 54 | + let hit = classCache.get(id); | ||
| 55 | + if (!hit) { | ||
| 56 | + hit = getClassById(id).then( | ||
| 57 | + (klass) => klass.name, | ||
| 58 | + () => { | ||
| 59 | + classCache.delete(id); | ||
| 60 | + return null; | ||
| 61 | + }, | ||
| 62 | + ); | ||
| 63 | + classCache.set(id, hit); | ||
| 64 | + } | ||
| 65 | + return hit; | ||
| 66 | + } | ||
| 67 | + if (!myClassesCache) { | ||
| 68 | + myClassesCache = getMyClasses().then( | ||
| 69 | + (page) => new Map(page.items.map((klass) => [klass.id, klass.name])), | ||
| 70 | + () => new Map<string, string>(), | ||
| 71 | + ); | ||
| 72 | + } | ||
| 73 | + return myClassesCache.then((names) => names.get(id) ?? null); | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/** Joins a course title and a class name; either may be missing. */ | ||
| 77 | +export function formatInstanceLabel(courseTitle: string | null, className: string | null): string { | ||
| 78 | + if (courseTitle && className) return `${courseTitle} — ${className}`; | ||
| 79 | + return courseTitle ?? className ?? ""; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +export function loadInstanceLabel(id: string, role: Role | undefined): Promise<InstanceLabel | null> { | ||
| 83 | + const key = `${role ?? ""}:${id}`; | ||
| 84 | + let hit = instanceCache.get(key); | ||
| 85 | + if (!hit) { | ||
| 86 | + hit = Promise.resolve() | ||
| 87 | + .then(() => getInstanceById(id)) | ||
| 88 | + .then(async (instance) => { | ||
| 89 | + const [title, klass] = await Promise.all([courseTitle(instance.course), className(instance.class, role)]); | ||
| 90 | + // A part that failed to load (a rate limit, a blip) is not kept, so | ||
| 91 | + // the next list asks again instead of showing a half label all session. | ||
| 92 | + if (title == null || klass == null) instanceCache.delete(key); | ||
| 93 | + const label = formatInstanceLabel(title, klass); | ||
| 94 | + return label ? { course: instance.course, class: instance.class, courseTitle: title, className: klass, label } : null; | ||
| 95 | + }) | ||
| 96 | + .catch(() => { | ||
| 97 | + // A failed read is not remembered, so a later list can try again. | ||
| 98 | + instanceCache.delete(key); | ||
| 99 | + return null; | ||
| 100 | + }); | ||
| 101 | + instanceCache.set(key, hit); | ||
| 102 | + } | ||
| 103 | + return hit; | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/** Labels for a bounded set of instance ids, fetched a few at a time. */ | ||
| 107 | +export async function loadInstanceLabels(ids: readonly string[], role: Role | undefined): Promise<Map<string, InstanceLabel>> { | ||
| 108 | + const unique = [...new Set(ids)]; | ||
| 109 | + const labels = await mapConcurrent(unique, FAN_OUT_LIMIT, (id) => loadInstanceLabel(id, role)); | ||
| 110 | + const out = new Map<string, InstanceLabel>(); | ||
| 111 | + unique.forEach((id, index) => { | ||
| 112 | + const label = labels[index]; | ||
| 113 | + if (label) out.set(id, label); | ||
| 114 | + }); | ||
| 115 | + return out; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/** Reactive `instance id -> label` record that fills in as the reads land. */ | ||
| 119 | +export function createInstanceLabels(ids: () => readonly string[], role: () => Role | undefined) { | ||
| 120 | + const [labels, setLabels] = createSignal<Record<string, InstanceLabel>>({}); | ||
| 121 | + createEffect(() => { | ||
| 122 | + const wanted = [...new Set(ids())]; | ||
| 123 | + const currentRole = role(); | ||
| 124 | + let disposed = false; | ||
| 125 | + onCleanup(() => { | ||
| 126 | + disposed = true; | ||
| 127 | + }); | ||
| 128 | + if (!currentRole || wanted.length === 0) return; | ||
| 129 | + void loadInstanceLabels(wanted, currentRole).catch(() => new Map<string, InstanceLabel>()).then((found) => { | ||
| 130 | + if (disposed || found.size === 0) return; | ||
| 131 | + setLabels((prev) => { | ||
| 132 | + let changed = false; | ||
| 133 | + const next = { ...prev }; | ||
| 134 | + for (const [id, entry] of found) { | ||
| 135 | + if (next[id]?.label !== entry.label) { | ||
| 136 | + next[id] = entry; | ||
| 137 | + changed = true; | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + return changed ? next : prev; | ||
| 141 | + }); | ||
| 142 | + }); | ||
| 143 | + }); | ||
| 144 | + return labels; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/** Test hook: forget every cached read. */ | ||
| 148 | +export function resetInstanceLabelCache(): void { | ||
| 149 | + instanceCache.clear(); | ||
| 150 | + courseCache.clear(); | ||
| 151 | + classCache.clear(); | ||
| 152 | + myClassesCache = null; | ||
| 153 | +} | ||
src/lib/meals.test.tsmodified+10 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { describe, expect, it } from "vitest"; | 1 | +import { describe, expect, it, test } from "vitest"; |
| 2 | import type { SchoolSettings } from "@/api/client"; | 2 | import type { SchoolSettings } from "@/api/client"; |
| 3 | import { dirtySettingsPatch, formatTry, mealCutoffAt, minuteToUtcTime, nextCourseWork, utcTimeToMinute } from "./meals"; | 3 | import { dirtySettingsPatch, formatTry, mealCutoffAt, minuteToUtcTime, nextCourseWork, utcTimeToMinute } from "./meals"; |
| 4 | 4 | ||
| @@ -47,3 +47,12 @@ describe("meal helpers", () => { | |||
| 47 | expect(dirtySettingsPatch(before, { ...before, max_chatbot_threads: 2 })).toEqual({ max_chatbot_threads: 2 }); | 47 | expect(dirtySettingsPatch(before, { ...before, max_chatbot_threads: 2 })).toEqual({ max_chatbot_threads: 2 }); |
| 48 | }); | 48 | }); |
| 49 | }); | 49 | }); |
| 50 | + | ||
| 51 | +test("meal slot and dietary tag labels map seeded keys and keep custom ones", async () => { | ||
| 52 | + const { mealSlotLabel, dietaryTagLabel } = await import("./meals"); | ||
| 53 | + const t = (key: string) => `<${key}>`; | ||
| 54 | + expect(mealSlotLabel("breakfast", t)).toBe("<meals.slotName.breakfast>"); | ||
| 55 | + expect(mealSlotLabel("ikindi", t)).toBe("ikindi"); | ||
| 56 | + expect(dietaryTagLabel("gluten_free", t)).toBe("<meals.tagName.gluten_free>"); | ||
| 57 | + expect(dietaryTagLabel("constructor", t)).toBe("constructor"); | ||
| 58 | +}); | ||
src/lib/meals.tsmodified+32 -0
| @@ -1,5 +1,37 @@ | |||
| 1 | import type { Exam, Homework, MealSlot, SchoolSettings } from "@/api/client"; | 1 | import type { Exam, Homework, MealSlot, SchoolSettings } from "@/api/client"; |
| 2 | import type { PatchSettingsBody } from "@/api/settings"; | 2 | import type { PatchSettingsBody } from "@/api/settings"; |
| 3 | +import type { MessageKey } from "@/i18n/messages"; | ||
| 4 | + | ||
| 5 | +type T = (key: MessageKey) => string; | ||
| 6 | + | ||
| 7 | +// Meal slots and dietary tags are school-defined keys; these are the ones a | ||
| 8 | +// school is seeded with. A key outside the map is shown as the school typed it. | ||
| 9 | +const MEAL_SLOT_LABELS: Record<string, MessageKey> = { | ||
| 10 | + breakfast: "meals.slotName.breakfast", | ||
| 11 | + lunch: "meals.slotName.lunch", | ||
| 12 | + dinner: "meals.slotName.dinner", | ||
| 13 | + snack: "meals.slotName.snack", | ||
| 14 | +}; | ||
| 15 | + | ||
| 16 | +const DIETARY_TAG_LABELS: Record<string, MessageKey> = { | ||
| 17 | + vegetarian: "meals.tagName.vegetarian", | ||
| 18 | + vegan: "meals.tagName.vegan", | ||
| 19 | + gluten_free: "meals.tagName.gluten_free", | ||
| 20 | + lactose_free: "meals.tagName.lactose_free", | ||
| 21 | + nut_allergy: "meals.tagName.nut_allergy", | ||
| 22 | +}; | ||
| 23 | + | ||
| 24 | +function lookup(map: Record<string, MessageKey>, key: string, t: T): string { | ||
| 25 | + return Object.hasOwn(map, key) ? t(map[key]) : key; | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +export function mealSlotLabel(slot: string, t: T): string { | ||
| 29 | + return lookup(MEAL_SLOT_LABELS, slot, t); | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +export function dietaryTagLabel(tag: string, t: T): string { | ||
| 33 | + return lookup(DIETARY_TAG_LABELS, tag, t); | ||
| 34 | +} | ||
| 3 | 35 | ||
| 4 | export function formatTry(minor: number, locale: string): string { | 36 | export function formatTry(minor: number, locale: string): string { |
| 5 | return new Intl.NumberFormat(locale, { style: "currency", currency: "TRY" }).format(minor / 100); | 37 | return new Intl.NumberFormat(locale, { style: "currency", currency: "TRY" }).format(minor / 100); |
src/lib/record-list-path.test.tsadded+24 -0
| @@ -0,0 +1,24 @@ | |||
| 1 | +import { expect, test } from "vitest"; | ||
| 2 | +import { ApiError } from "@/api/client"; | ||
| 3 | +import { isNotFoundError, listPathFor } from "./record-list-path"; | ||
| 4 | + | ||
| 5 | +const routes = new Set(["/", "/courses", "/management/classes", "/notes", "/admin/users"]); | ||
| 6 | +const has = (path: string) => routes.has(path); | ||
| 7 | + | ||
| 8 | +test("a detail URL points back at its list", () => { | ||
| 9 | + expect(listPathFor("/management/classes/bad-id", has)).toBe("/management/classes"); | ||
| 10 | + expect(listPathFor("/notes/bad-id/", has)).toBe("/notes"); | ||
| 11 | + expect(listPathFor("/admin/users/x", has)).toBe("/admin/users"); | ||
| 12 | +}); | ||
| 13 | + | ||
| 14 | +test("instances go back to courses, unknown parents go home", () => { | ||
| 15 | + expect(listPathFor("/instances/x", has)).toBe("/courses"); | ||
| 16 | + expect(listPathFor("/nowhere/x", has)).toBe("/"); | ||
| 17 | + expect(listPathFor("/x", has)).toBe("/"); | ||
| 18 | +}); | ||
| 19 | + | ||
| 20 | +test("only an ApiError 404 counts as not found", () => { | ||
| 21 | + expect(isNotFoundError(new ApiError(404, "not found"))).toBe(true); | ||
| 22 | + expect(isNotFoundError(new ApiError(500, "boom"))).toBe(false); | ||
| 23 | + expect(isNotFoundError(new Error("404"))).toBe(false); | ||
| 24 | +}); | ||
src/lib/record-list-path.tsadded+24 -0
| @@ -0,0 +1,24 @@ | |||
| 1 | +import { ApiError } from "@/api/client"; | ||
| 2 | + | ||
| 3 | +/** A read that failed because the record is not there (deleted, or a bad link). */ | ||
| 4 | +export function isNotFoundError(err: unknown): boolean { | ||
| 5 | + return err instanceof ApiError && err.status === 404; | ||
| 6 | +} | ||
| 7 | + | ||
| 8 | +// Detail routes whose parent path is not a list page of their own. | ||
| 9 | +const LIST_OVERRIDES: Record<string, string> = { | ||
| 10 | + "/instances": "/courses", | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +/** | ||
| 14 | + * The list a detail URL belongs to: its path minus the last segment | ||
| 15 | + * (`/management/classes/abc` → `/management/classes`), when that is a route | ||
| 16 | + * the app has; otherwise the home page. | ||
| 17 | + */ | ||
| 18 | +export function listPathFor(pathname: string, hasRoute: (path: string) => boolean): string { | ||
| 19 | + const trimmed = pathname.replace(/\/+$/, ""); | ||
| 20 | + const parent = trimmed.slice(0, trimmed.lastIndexOf("/")); | ||
| 21 | + if (!parent) return "/"; | ||
| 22 | + const target = LIST_OVERRIDES[parent] ?? parent; | ||
| 23 | + return hasRoute(target) ? target : "/"; | ||
| 24 | +} | ||
src/lib/terms.test.tsadded+38 -0
| @@ -0,0 +1,38 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import type { Term } from "@/api/client"; | ||
| 3 | +import { pickCurrentTerm } from "./terms"; | ||
| 4 | + | ||
| 5 | +const day = 86_400_000; | ||
| 6 | +const term = (id: string, starts: number, ends: number, archived = false): Term => ({ | ||
| 7 | + id, | ||
| 8 | + name: id, | ||
| 9 | + year: "y", | ||
| 10 | + starts_at: starts * day, | ||
| 11 | + ends_at: ends * day, | ||
| 12 | + archived_at: archived ? 1 : null, | ||
| 13 | +}); | ||
| 14 | + | ||
| 15 | +describe("pickCurrentTerm", () => { | ||
| 16 | + // Newest first, as the backend lists them. | ||
| 17 | + const list = [term("second", 150, 300), term("first", 0, 140)]; | ||
| 18 | + | ||
| 19 | + it("picks the term whose range contains today", () => { | ||
| 20 | + expect(pickCurrentTerm(list, 20 * day)?.id).toBe("first"); | ||
| 21 | + expect(pickCurrentTerm(list, 200 * day)?.id).toBe("second"); | ||
| 22 | + }); | ||
| 23 | + | ||
| 24 | + it("falls back to the nearest upcoming term between terms", () => { | ||
| 25 | + expect(pickCurrentTerm(list, 145 * day)?.id).toBe("second"); | ||
| 26 | + expect(pickCurrentTerm([term("late", 400, 500), term("soon", 50, 90)], 10 * day)?.id).toBe("soon"); | ||
| 27 | + }); | ||
| 28 | + | ||
| 29 | + it("falls back to the first term when all are past", () => { | ||
| 30 | + expect(pickCurrentTerm(list, 999 * day)?.id).toBe("second"); | ||
| 31 | + }); | ||
| 32 | + | ||
| 33 | + it("skips archived terms unless nothing else is left", () => { | ||
| 34 | + expect(pickCurrentTerm([term("old", 0, 100, true), term("next", 200, 300)], 50 * day)?.id).toBe("next"); | ||
| 35 | + expect(pickCurrentTerm([term("old", 0, 100, true)], 50 * day)?.id).toBe("old"); | ||
| 36 | + expect(pickCurrentTerm([], 0)).toBeUndefined(); | ||
| 37 | + }); | ||
| 38 | +}); | ||
src/lib/terms.tsadded+17 -0
| @@ -0,0 +1,17 @@ | |||
| 1 | +import type { Term } from "@/api/client"; | ||
| 2 | + | ||
| 3 | +/** | ||
| 4 | + * The dönem a new record most likely belongs to: the open term whose date | ||
| 5 | + * range contains `now`, else the nearest one still to come, else the first | ||
| 6 | + * listed. Archived terms are only considered when every term is archived. | ||
| 7 | + */ | ||
| 8 | +export function pickCurrentTerm(terms: readonly Term[], now: number): Term | undefined { | ||
| 9 | + const open = terms.filter((term) => term.archived_at == null); | ||
| 10 | + const pool = open.length > 0 ? open : terms; | ||
| 11 | + const current = pool.find((term) => term.starts_at <= now && now <= term.ends_at); | ||
| 12 | + if (current) return current; | ||
| 13 | + const upcoming = pool | ||
| 14 | + .filter((term) => term.starts_at > now) | ||
| 15 | + .sort((a, b) => a.starts_at - b.starts_at)[0]; | ||
| 16 | + return upcoming ?? pool[0]; | ||
| 17 | +} | ||
src/lib/url-state.test.tsxadded+108 -0
| @@ -0,0 +1,108 @@ | |||
| 1 | +import { createRoot, createSignal } from "solid-js"; | ||
| 2 | +import { | ||
| 3 | + createUrlEnum, | ||
| 4 | + createUrlString, | ||
| 5 | + decodeSort, | ||
| 6 | + encodePageIndex, | ||
| 7 | + encodeSort, | ||
| 8 | + listParamKeys, | ||
| 9 | + patchSearch, | ||
| 10 | + readEnum, | ||
| 11 | + readPageIndex, | ||
| 12 | + readString, | ||
| 13 | +} from "@/lib/url-state"; | ||
| 14 | + | ||
| 15 | +const router = vi.hoisted(() => ({ | ||
| 16 | + navigate: vi.fn(), | ||
| 17 | + location: null as null | (() => { pathname: string; search: Record<string, unknown>; hash: string }), | ||
| 18 | +})); | ||
| 19 | + | ||
| 20 | +vi.mock("@tanstack/solid-router", () => ({ | ||
| 21 | + useNavigate: () => router.navigate, | ||
| 22 | + useLocation: () => router.location, | ||
| 23 | +})); | ||
| 24 | + | ||
| 25 | +afterEach(() => vi.clearAllMocks()); | ||
| 26 | + | ||
| 27 | +test("patchSearch merges and drops blank values", () => { | ||
| 28 | + expect(patchSearch({ kind: "club", q: "alg", page: 2 }, { q: "", page: undefined, sort: "title.asc" })).toEqual({ | ||
| 29 | + kind: "club", | ||
| 30 | + sort: "title.asc", | ||
| 31 | + }); | ||
| 32 | +}); | ||
| 33 | + | ||
| 34 | +test("readString turns router-parsed scalars back into text", () => { | ||
| 35 | + expect(readString("abc")).toBe("abc"); | ||
| 36 | + expect(readString(12)).toBe("12"); | ||
| 37 | + expect(readString(true)).toBe("true"); | ||
| 38 | + expect(readString({ a: 1 })).toBe(""); | ||
| 39 | + expect(readString(undefined)).toBe(""); | ||
| 40 | +}); | ||
| 41 | + | ||
| 42 | +test("pages are one-based in the URL and zero-based in the table", () => { | ||
| 43 | + expect(readPageIndex(3)).toBe(2); | ||
| 44 | + expect(readPageIndex("2")).toBe(1); | ||
| 45 | + expect(readPageIndex(1)).toBe(0); | ||
| 46 | + expect(readPageIndex(0)).toBe(0); | ||
| 47 | + expect(readPageIndex(-4)).toBe(0); | ||
| 48 | + expect(readPageIndex("x")).toBe(0); | ||
| 49 | + expect(readPageIndex(undefined)).toBe(0); | ||
| 50 | + expect(encodePageIndex(0)).toBeUndefined(); | ||
| 51 | + expect(encodePageIndex(2)).toBe(3); | ||
| 52 | +}); | ||
| 53 | + | ||
| 54 | +test("sort round-trips through one param", () => { | ||
| 55 | + expect(decodeSort("starts_at.desc")).toEqual([{ id: "starts_at", desc: true }]); | ||
| 56 | + expect(decodeSort("title.asc")).toEqual([{ id: "title", desc: false }]); | ||
| 57 | + expect(decodeSort("title")).toEqual([{ id: "title", desc: false }]); | ||
| 58 | + expect(decodeSort("a.b.desc")).toEqual([{ id: "a.b", desc: true }]); | ||
| 59 | + expect(decodeSort("")).toEqual([]); | ||
| 60 | + expect(decodeSort(undefined)).toEqual([]); | ||
| 61 | + expect(encodeSort([{ id: "starts_at", desc: true }])).toBe("starts_at.desc"); | ||
| 62 | + expect(encodeSort([])).toBeUndefined(); | ||
| 63 | +}); | ||
| 64 | + | ||
| 65 | +test("readEnum falls back on anything outside the set", () => { | ||
| 66 | + expect(readEnum("week", ["day", "week", "month"] as const, "month")).toBe("week"); | ||
| 67 | + expect(readEnum("year", ["day", "week", "month"] as const, "month")).toBe("month"); | ||
| 68 | +}); | ||
| 69 | + | ||
| 70 | +test("listParamKeys prefixes keys for a second list on the page", () => { | ||
| 71 | + expect(listParamKeys()).toEqual({ q: "q", page: "page", sort: "sort" }); | ||
| 72 | + expect(listParamKeys("roster")).toEqual({ q: "roster.q", page: "roster.page", sort: "roster.sort" }); | ||
| 73 | +}); | ||
| 74 | + | ||
| 75 | +test("a URL param starts from the URL, writes with replace, and follows outside changes", () => { | ||
| 76 | + const [location, setLocation] = createSignal({ pathname: "/exams", search: { tab: "draft", q: "alg" } as Record<string, unknown>, hash: "" }); | ||
| 77 | + router.location = location; | ||
| 78 | + | ||
| 79 | + // Effects start once the root has been built, as they do in a mounted page. | ||
| 80 | + const { tab, setTab, query, setQuery, dispose } = createRoot((dispose) => { | ||
| 81 | + const [tab, setTab] = createUrlEnum("tab", ["all", "draft"] as const, "all"); | ||
| 82 | + const [query, setQuery] = createUrlString("q"); | ||
| 83 | + return { tab, setTab, query, setQuery, dispose }; | ||
| 84 | + }); | ||
| 85 | + expect(tab()).toBe("draft"); | ||
| 86 | + expect(query()).toBe("alg"); | ||
| 87 | + | ||
| 88 | + setQuery("algebra"); | ||
| 89 | + expect(query()).toBe("algebra"); | ||
| 90 | + const call = router.navigate.mock.calls.at(-1)?.[0]; | ||
| 91 | + expect(call).toMatchObject({ to: "/exams", replace: true, resetScroll: false }); | ||
| 92 | + expect(call.search({ tab: "draft", q: "alg" })).toEqual({ tab: "draft", q: "algebra" }); | ||
| 93 | + | ||
| 94 | + // The default value leaves the URL bare. | ||
| 95 | + setTab("all"); | ||
| 96 | + expect(router.navigate.mock.calls.at(-1)?.[0].search({ tab: "draft" })).toEqual({}); | ||
| 97 | + | ||
| 98 | + // The router catches up with our own writes: nothing is pulled back. | ||
| 99 | + setLocation({ pathname: "/exams", search: { tab: "draft", q: "algebra" }, hash: "" }); | ||
| 100 | + expect(query()).toBe("algebra"); | ||
| 101 | + setLocation({ pathname: "/exams", search: { q: "algebra" }, hash: "" }); | ||
| 102 | + expect(tab()).toBe("all"); | ||
| 103 | + | ||
| 104 | + // A change from elsewhere (a nav link to the bare route) flows back in. | ||
| 105 | + setLocation({ pathname: "/exams", search: {}, hash: "" }); | ||
| 106 | + expect(query()).toBe(""); | ||
| 107 | + dispose(); | ||
| 108 | +}); | ||
src/lib/url-state.tsadded+157 -0
| @@ -0,0 +1,157 @@ | |||
| 1 | +import { createEffect, createSignal, on } from "solid-js"; | ||
| 2 | +import { useLocation, useNavigate } from "@tanstack/solid-router"; | ||
| 3 | + | ||
| 4 | +/** | ||
| 5 | + * List and view state that lives in the URL search params, so Back and a | ||
| 6 | + * reload land on the same page, search, sort, tab or calendar view the user | ||
| 7 | + * left. Every write replaces the current history entry: typing into a search | ||
| 8 | + * box must not push one entry per keystroke, and Back should leave the page | ||
| 9 | + * rather than step through its filters. | ||
| 10 | + */ | ||
| 11 | + | ||
| 12 | +export type SearchRecord = Record<string, unknown>; | ||
| 13 | + | ||
| 14 | +/** A value the URL should not carry: the default state is a bare URL. */ | ||
| 15 | +const isBlank = (value: unknown) => value === undefined || value === null || value === ""; | ||
| 16 | + | ||
| 17 | +/** `prev` with `patch` merged in; blank values drop their key. */ | ||
| 18 | +export function patchSearch(prev: SearchRecord, patch: SearchRecord): SearchRecord { | ||
| 19 | + const next: SearchRecord = { ...prev }; | ||
| 20 | + for (const [key, value] of Object.entries(patch)) { | ||
| 21 | + if (isBlank(value)) delete next[key]; | ||
| 22 | + else next[key] = value; | ||
| 23 | + } | ||
| 24 | + return next; | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/** | ||
| 28 | + * A search param as text. The router parses `?q=12` into the number 12 and | ||
| 29 | + * `?q=true` into a boolean, so anything scalar is turned back into a string. | ||
| 30 | + */ | ||
| 31 | +export function readString(value: unknown): string { | ||
| 32 | + if (typeof value === "string") return value; | ||
| 33 | + if (typeof value === "number" || typeof value === "boolean") return String(value); | ||
| 34 | + return ""; | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/** `?page=` is one-based for people; the table's index is zero-based. */ | ||
| 38 | +export function readPageIndex(value: unknown): number { | ||
| 39 | + const page = typeof value === "number" ? value : Number.parseInt(readString(value), 10); | ||
| 40 | + return Number.isInteger(page) && page > 1 ? page - 1 : 0; | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/** The first page is the default, so it leaves the URL bare. */ | ||
| 44 | +export function encodePageIndex(index: number): number | undefined { | ||
| 45 | + return index > 0 ? index + 1 : undefined; | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +export type SortEntry = { id: string; desc: boolean }; | ||
| 49 | + | ||
| 50 | +/** `?sort=starts_at.desc` → one sort entry; anything unreadable → unsorted. */ | ||
| 51 | +export function decodeSort(value: unknown): SortEntry[] { | ||
| 52 | + const raw = readString(value).trim(); | ||
| 53 | + if (!raw) return []; | ||
| 54 | + const dot = raw.lastIndexOf("."); | ||
| 55 | + const direction = dot > 0 ? raw.slice(dot + 1) : ""; | ||
| 56 | + if (direction === "asc" || direction === "desc") return [{ id: raw.slice(0, dot), desc: direction === "desc" }]; | ||
| 57 | + return [{ id: raw, desc: false }]; | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/** The inverse of `decodeSort`; only the leading sort survives a round trip. */ | ||
| 61 | +export function encodeSort(state: readonly SortEntry[]): string | undefined { | ||
| 62 | + const first = state[0]; | ||
| 63 | + return first ? `${first.id}.${first.desc ? "desc" : "asc"}` : undefined; | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/** A param that must be one of `allowed`, else `fallback`. */ | ||
| 67 | +export function readEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T { | ||
| 68 | + const raw = readString(value); | ||
| 69 | + return (allowed as readonly string[]).includes(raw) ? (raw as T) : fallback; | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +export type UrlParamOptions<T> = { | ||
| 73 | + /** Raw router value (string, number, boolean or undefined) → state. */ | ||
| 74 | + parse: (raw: unknown) => T; | ||
| 75 | + /** State → URL value; `undefined` (or "") drops the key, e.g. for the default. */ | ||
| 76 | + serialize: (value: T) => unknown; | ||
| 77 | +}; | ||
| 78 | + | ||
| 79 | +/** Stable key for comparing what was written with what the URL now says. */ | ||
| 80 | +const fingerprint = (value: unknown) => (isBlank(value) ? "" : JSON.stringify(value)); | ||
| 81 | + | ||
| 82 | +/** | ||
| 83 | + * A signal mirrored into one search param. Reads are local and immediate — | ||
| 84 | + * the input never waits for the router — and each write replaces the URL. | ||
| 85 | + * A change that did not come from this signal (a nav link back to the bare | ||
| 86 | + * route, the browser restoring an entry) flows back into it. | ||
| 87 | + */ | ||
| 88 | +export function createUrlParam<T>(key: string, options: UrlParamOptions<T>): [() => T, (value: T) => void] { | ||
| 89 | + const location = useLocation(); | ||
| 90 | + const navigate = useNavigate(); | ||
| 91 | + const urlValue = () => ((location().search ?? {}) as SearchRecord)[key]; | ||
| 92 | + const [value, setValue] = createSignal<T>(options.parse(urlValue())); | ||
| 93 | + // Writes still on their way through the router. Each one arrives in order; | ||
| 94 | + // an arriving value we wrote is not an outside change and must not pull | ||
| 95 | + // the input back to an older keystroke. | ||
| 96 | + let pending: string[] = []; | ||
| 97 | + | ||
| 98 | + createEffect( | ||
| 99 | + on( | ||
| 100 | + () => fingerprint(options.serialize(options.parse(urlValue()))), | ||
| 101 | + (current) => { | ||
| 102 | + const index = pending.indexOf(current); | ||
| 103 | + if (index >= 0) { | ||
| 104 | + pending = pending.slice(index + 1); | ||
| 105 | + return; | ||
| 106 | + } | ||
| 107 | + pending = []; | ||
| 108 | + setValue(() => options.parse(urlValue())); | ||
| 109 | + }, | ||
| 110 | + { defer: true }, | ||
| 111 | + ), | ||
| 112 | + ); | ||
| 113 | + | ||
| 114 | + const write = (next: T) => { | ||
| 115 | + setValue(() => next); | ||
| 116 | + const serialized = options.serialize(next); | ||
| 117 | + const current = fingerprint(options.serialize(options.parse(urlValue()))); | ||
| 118 | + if (fingerprint(serialized) === current && pending.length === 0) return; | ||
| 119 | + pending.push(fingerprint(serialized)); | ||
| 120 | + void navigate({ | ||
| 121 | + to: location().pathname, | ||
| 122 | + search: (prev: SearchRecord) => patchSearch(prev ?? {}, { [key]: serialized }), | ||
| 123 | + hash: location().hash || undefined, | ||
| 124 | + replace: true, | ||
| 125 | + resetScroll: false, | ||
| 126 | + } as never); | ||
| 127 | + }; | ||
| 128 | + | ||
| 129 | + return [value, write]; | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/** A text param (`?q=`, `?tab=`); `fallback` is the bare-URL value. */ | ||
| 133 | +export function createUrlString(key: string, fallback = ""): [() => string, (value: string) => void] { | ||
| 134 | + return createUrlParam(key, { | ||
| 135 | + parse: (raw) => readString(raw) || fallback, | ||
| 136 | + serialize: (value) => (value === fallback ? undefined : value), | ||
| 137 | + }); | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/** One of a fixed set (`?tab=sessions`, `?view=week`); `fallback` stays out of the URL. */ | ||
| 141 | +export function createUrlEnum<T extends string>(key: string, allowed: readonly T[], fallback: T): [() => T, (value: T) => void] { | ||
| 142 | + return createUrlParam(key, { | ||
| 143 | + parse: (raw) => readEnum(raw, allowed, fallback), | ||
| 144 | + serialize: (value) => (value === fallback ? undefined : value), | ||
| 145 | + }); | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/** A zero-based page index kept one-based in `?page=`. */ | ||
| 149 | +export function createUrlPageIndex(key = "page"): [() => number, (value: number) => void] { | ||
| 150 | + return createUrlParam(key, { parse: readPageIndex, serialize: encodePageIndex }); | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/** Search-param names for one list; a prefix keeps two lists on a page apart. */ | ||
| 154 | +export function listParamKeys(prefix?: string) { | ||
| 155 | + const name = (key: string) => (prefix ? `${prefix}.${key}` : key); | ||
| 156 | + return { q: name("q"), page: name("page"), sort: name("sort") }; | ||
| 157 | +} | ||
src/lib/uuid-time.test.tsadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +import { uuidV7Ms } from "./uuid-time"; | ||
| 2 | + | ||
| 3 | +describe("uuidV7Ms", () => { | ||
| 4 | + it("reads the unix-ms prefix of a v7 id", () => { | ||
| 5 | + expect(uuidV7Ms("01a0b1b0-aca9-7025-b739-d3ad153d617b")).toBe(0x01a0b1b0aca9); | ||
| 6 | + }); | ||
| 7 | + | ||
| 8 | + it("orders ids created later after earlier ones", () => { | ||
| 9 | + expect(uuidV7Ms("01a0b1b0-aca9-7025-b739-d3ad153d617b")!).toBeLessThan(uuidV7Ms("01a0b1b1-0000-7000-8000-000000000000")!); | ||
| 10 | + }); | ||
| 11 | + | ||
| 12 | + it("returns null for a non-v7 id", () => { | ||
| 13 | + expect(uuidV7Ms("123e4567-e89b-42d3-a456-426614174000")).toBeNull(); | ||
| 14 | + expect(uuidV7Ms("not-an-id")).toBeNull(); | ||
| 15 | + }); | ||
| 16 | +}); | ||
src/lib/uuid-time.tsadded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +/** | ||
| 2 | + * The creation instant embedded in a UUIDv7 id (its first 48 bits are unix | ||
| 3 | + * milliseconds), or `null` for any other id. | ||
| 4 | + * | ||
| 5 | + * Only for ordering records the backend gives no date for — an exam that was | ||
| 6 | + * never scheduled still sorts by when it was created. Never shown as a date: | ||
| 7 | + * it says when the row was made, not when anything happened. | ||
| 8 | + */ | ||
| 9 | +export function uuidV7Ms(id: string): number | null { | ||
| 10 | + const match = /^([0-9a-f]{8})-([0-9a-f]{4})-7[0-9a-f]{3}-/i.exec(id); | ||
| 11 | + if (!match) return null; | ||
| 12 | + return Number.parseInt(match[1] + match[2], 16); | ||
| 13 | +} | ||
src/pages/academic-years-page.tsxmodified+4 -3
| @@ -27,7 +27,7 @@ import { Select } from "@/components/ui/select"; | |||
| 27 | import { SidePanel } from "@/components/ui/side-panel"; | 27 | import { SidePanel } from "@/components/ui/side-panel"; |
| 28 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 28 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 29 | import { createFlash } from "@/lib/flash"; | 29 | import { createFlash } from "@/lib/flash"; |
| 30 | -import { formatDateTime } from "@/lib/format"; | 30 | +import { formatDate } from "@/lib/format"; |
| 31 | import { usePreferences, useT } from "@/stores/preferences-context"; | 31 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 32 | 32 | ||
| 33 | const YEAR_PAGE_SIZE = 10; | 33 | const YEAR_PAGE_SIZE = 10; |
| @@ -164,7 +164,7 @@ function AcademicYearsContent() { | |||
| 164 | size: 150, | 164 | size: 150, |
| 165 | minSize: 145, | 165 | minSize: 145, |
| 166 | meta: { cellClass: "whitespace-nowrap" }, | 166 | meta: { cellClass: "whitespace-nowrap" }, |
| 167 | - cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDateTime(cell.row.original.starts_at, locale())}</span>, | 167 | + cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDate(cell.row.original.starts_at, locale())}</span>, |
| 168 | }, | 168 | }, |
| 169 | { | 169 | { |
| 170 | accessorKey: "ends_at", | 170 | accessorKey: "ends_at", |
| @@ -172,7 +172,7 @@ function AcademicYearsContent() { | |||
| 172 | size: 150, | 172 | size: 150, |
| 173 | minSize: 145, | 173 | minSize: 145, |
| 174 | meta: { cellClass: "whitespace-nowrap" }, | 174 | meta: { cellClass: "whitespace-nowrap" }, |
| 175 | - cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDateTime(cell.row.original.ends_at, locale())}</span>, | 175 | + cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDate(cell.row.original.ends_at, locale())}</span>, |
| 176 | }, | 176 | }, |
| 177 | { | 177 | { |
| 178 | id: "classes", | 178 | id: "classes", |
| @@ -249,6 +249,7 @@ function AcademicYearsContent() { | |||
| 249 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> | 249 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> |
| 250 | </Show> | 250 | </Show> |
| 251 | <DataTable | 251 | <DataTable |
| 252 | + urlState | ||
| 252 | title={t("academicYears.title")} | 253 | title={t("academicYears.title")} |
| 253 | description={t("academicYears.subtitle")} | 254 | description={t("academicYears.subtitle")} |
| 254 | actions={ | 255 | actions={ |
src/pages/admin-user-detail-page.tsxmodified+3 -0
| @@ -174,6 +174,9 @@ function AdminUserDetailContent() { | |||
| 174 | open={roleConfirmOpen()} | 174 | open={roleConfirmOpen()} |
| 175 | onOpenChange={setRoleConfirmOpen} | 175 | onOpenChange={setRoleConfirmOpen} |
| 176 | title={t("confirm.updateTitle")} | 176 | title={t("confirm.updateTitle")} |
| 177 | + description={current().role === "admin" && pendingRole() !== "admin" ? t("admin.demoteAdminWarning") : undefined} | ||
| 178 | + variant={current().role === "admin" && pendingRole() !== "admin" ? "destructive" : "default"} | ||
| 179 | + confirmLabel={t("confirm.confirmUpdate")} | ||
| 177 | summary={t("confirm.updateRole", { | 180 | summary={t("confirm.updateRole", { |
| 178 | user: current().username, | 181 | user: current().username, |
| 179 | from: t(`role.${current().role}` as MessageKey), | 182 | from: t(`role.${current().role}` as MessageKey), |
src/pages/ai-insight-student-page.tsxmodified+3 -8
| @@ -17,6 +17,7 @@ import { loadInsightStudents } from "@/lib/insight-students"; | |||
| 17 | import { personLabel } from "@/lib/person"; | 17 | import { personLabel } from "@/lib/person"; |
| 18 | import { hasMinRole } from "@/lib/roles"; | 18 | import { hasMinRole } from "@/lib/roles"; |
| 19 | import { useAuth } from "@/stores/auth-context"; | 19 | import { useAuth } from "@/stores/auth-context"; |
| 20 | +import { formatDate } from "@/lib/format"; | ||
| 20 | import { usePreferences } from "@/stores/preferences-context"; | 21 | import { usePreferences } from "@/stores/preferences-context"; |
| 21 | 22 | ||
| 22 | function confidenceVariant(confidence: InsightConfidence) { | 23 | function confidenceVariant(confidence: InsightConfidence) { |
| @@ -66,14 +67,8 @@ function AiInsightStudentContent() { | |||
| 66 | confidence === "none" || confidence === "exploratory" || confidence === "stable" | 67 | confidence === "none" || confidence === "exploratory" || confidence === "stable" |
| 67 | ? t(`insights.confidence.${confidence}`) | 68 | ? t(`insights.confidence.${confidence}`) |
| 68 | : confidence; | 69 | : confidence; |
| 69 | - const numericDate = (value: number | null | undefined) => { | 70 | + // The app-wide "18 Eyl 2026" date, not a numeric 18.09.2026. |
| 70 | - if (value == null) return "—"; | 71 | + const numericDate = (value: number | null | undefined) => formatDate(value, prefs.locale()); |
| 71 | - return new Intl.DateTimeFormat(prefs.locale() === "tr" ? "tr-TR" : "en-US", { | ||
| 72 | - day: "2-digit", | ||
| 73 | - month: "2-digit", | ||
| 74 | - year: "numeric", | ||
| 75 | - }).format(new Date(value)); | ||
| 76 | - }; | ||
| 77 | 72 | ||
| 78 | const recompute = async () => { | 73 | const recompute = async () => { |
| 79 | const current = person(); | 74 | const current = person(); |
src/pages/builder-schools-page.tsxmodified+1 -0
| @@ -118,6 +118,7 @@ function BuilderSchoolsContent() { | |||
| 118 | </Show> | 118 | </Show> |
| 119 | <Show when={!list.error}> | 119 | <Show when={!list.error}> |
| 120 | <DataTable | 120 | <DataTable |
| 121 | + urlState | ||
| 121 | title={t("builder.schools")} | 122 | title={t("builder.schools")} |
| 122 | description={t("builder.schoolsSubtitle")} | 123 | description={t("builder.schoolsSubtitle")} |
| 123 | actions={ | 124 | actions={ |
src/pages/calendar-page.test.tsxmodified+1 -0
| @@ -9,6 +9,7 @@ vi.mock("@tanstack/solid-router", () => ({ | |||
| 9 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, | 9 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, |
| 10 | Navigate: () => null, | 10 | Navigate: () => null, |
| 11 | useNavigate: () => vi.fn(), | 11 | useNavigate: () => vi.fn(), |
| 12 | + useLocation: () => () => ({ pathname: "/calendar", search: {}, searchStr: "", hash: "" }), | ||
| 12 | })); | 13 | })); |
| 13 | vi.mock("@/stores/auth-context", () => ({ | 14 | vi.mock("@/stores/auth-context", () => ({ |
| 14 | useAuth: () => ({ | 15 | useAuth: () => ({ |
src/pages/calendar-page.tsxmodified+70 -23
| @@ -1,6 +1,7 @@ | |||
| 1 | -import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; | 1 | +import { For, Show, Suspense, createMemo } from "solid-js"; |
| 2 | import { createBoardResources } from "@/lib/board-resources"; | 2 | import { createBoardResources } from "@/lib/board-resources"; |
| 3 | import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; | 3 | import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; |
| 4 | +import { createInstanceLabels } from "@/lib/instance-labels"; | ||
| 4 | import { getEvents } from "@/api/events"; | 5 | import { getEvents } from "@/api/events"; |
| 5 | import { getExams } from "@/api/exams"; | 6 | import { getExams } from "@/api/exams"; |
| 6 | import { getHomework } from "@/api/homework"; | 7 | import { getHomework } from "@/api/homework"; |
| @@ -17,6 +18,7 @@ import { PageSpinner } from "@/components/ui/page-spinner"; | |||
| 17 | import { IconCalendarDays, IconChevronLeft, IconChevronRight } from "@/components/ui/icons"; | 18 | import { IconCalendarDays, IconChevronLeft, IconChevronRight } from "@/components/ui/icons"; |
| 18 | import type { MessageKey } from "@/i18n/messages"; | 19 | import type { MessageKey } from "@/i18n/messages"; |
| 19 | import { cn } from "@/lib/cn"; | 20 | import { cn } from "@/lib/cn"; |
| 21 | +import { createUrlEnum, createUrlParam, readString } from "@/lib/url-state"; | ||
| 20 | import { createNow } from "@/lib/create-now"; | 22 | import { createNow } from "@/lib/create-now"; |
| 21 | import { appointmentCounterpart } from "@/lib/person"; | 23 | import { appointmentCounterpart } from "@/lib/person"; |
| 22 | import { useAuth } from "@/stores/auth-context"; | 24 | import { useAuth } from "@/stores/auth-context"; |
| @@ -43,6 +45,8 @@ type CalendarItem = { | |||
| 43 | at: number; | 45 | at: number; |
| 44 | endsAt: number | null; | 46 | endsAt: number | null; |
| 45 | href: string; | 47 | href: string; |
| 48 | + /** The şube×ders an exam or homework belongs to, for its "<ders> — <şube>" line. */ | ||
| 49 | + instance?: string; | ||
| 46 | /** Appointments carry their own badge instead of the plain category one. */ | 50 | /** Appointments carry their own badge instead of the plain category one. */ |
| 47 | status?: AppointmentStatus; | 51 | status?: AppointmentStatus; |
| 48 | }; | 52 | }; |
| @@ -128,6 +132,20 @@ const VIEWS: { id: CalendarView; labelKey: MessageKey }[] = [ | |||
| 128 | { id: "month", labelKey: "calendar.viewMonth" }, | 132 | { id: "month", labelKey: "calendar.viewMonth" }, |
| 129 | ]; | 133 | ]; |
| 130 | 134 | ||
| 135 | +/** `?date=2026-09-24` → a day key; null when the text is not a real date. */ | ||
| 136 | +function isoToDateKey(raw: unknown): string | null { | ||
| 137 | + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(readString(raw)); | ||
| 138 | + if (!match) return null; | ||
| 139 | + const d = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])); | ||
| 140 | + return d.getDate() === Number(match[3]) ? dateKey(d) : null; | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +/** A day key (zero-based month) → `2026-09-24` for the URL. */ | ||
| 144 | +function dateKeyToIso(key: string): string { | ||
| 145 | + const [y, m, d] = key.split("-").map(Number); | ||
| 146 | + return `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`; | ||
| 147 | +} | ||
| 148 | + | ||
| 131 | function dateKey(d: Date) { | 149 | function dateKey(d: Date) { |
| 132 | return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; | 150 | return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; |
| 133 | } | 151 | } |
| @@ -146,10 +164,34 @@ function CalendarContent() { | |||
| 146 | const { locale } = usePreferences(); | 164 | const { locale } = usePreferences(); |
| 147 | const now = createNow(); | 165 | const now = createNow(); |
| 148 | const nowDate = () => new Date(now()); | 166 | const nowDate = () => new Date(now()); |
| 149 | - const [viewYear, setViewYear] = createSignal(nowDate().getFullYear()); | 167 | + // View, selected day and shown month live in the URL (`?view=week&date= |
| 150 | - const [viewMonth, setViewMonth] = createSignal(nowDate().getMonth()); | 168 | + // 2026-09-24&month=2026-10`), so Back from an item returns to the same |
| 151 | - const [selected, setSelected] = createSignal(dateKey(nowDate())); | 169 | + // view and day instead of this month's grid. Today is the bare URL. |
| 152 | - const [view, setView] = createSignal<CalendarView>("month"); | 170 | + const [view, setView] = createUrlEnum<CalendarView>("view", ["day", "week", "month"], "month"); |
| 171 | + const [selected, setSelected] = createUrlParam("date", { | ||
| 172 | + parse: (raw) => isoToDateKey(raw) ?? dateKey(nowDate()), | ||
| 173 | + serialize: (key: string) => (key === dateKey(nowDate()) ? undefined : dateKeyToIso(key)), | ||
| 174 | + }); | ||
| 175 | + // The month grid follows the selected day unless paged away from it. | ||
| 176 | + const selectedMonth = () => { | ||
| 177 | + const [y, m] = selected().split("-").map(Number); | ||
| 178 | + return { year: y, month: m }; | ||
| 179 | + }; | ||
| 180 | + const [shownMonth, setShownMonth] = createUrlParam("month", { | ||
| 181 | + parse: (raw) => { | ||
| 182 | + const match = /^(\d{4})-(\d{2})$/.exec(readString(raw)); | ||
| 183 | + return match ? { year: Number(match[1]), month: Number(match[2]) - 1 } : selectedMonth(); | ||
| 184 | + }, | ||
| 185 | + serialize: (value: { year: number; month: number }) => { | ||
| 186 | + const base = selectedMonth(); | ||
| 187 | + return value.year === base.year && value.month === base.month | ||
| 188 | + ? undefined | ||
| 189 | + : `${value.year}-${String(value.month + 1).padStart(2, "0")}`; | ||
| 190 | + }, | ||
| 191 | + }); | ||
| 192 | + const viewYear = () => shownMonth().year; | ||
| 193 | + const viewMonth = () => shownMonth().month; | ||
| 194 | + const showMonthOf = (d: Date) => setShownMonth({ year: d.getFullYear(), month: d.getMonth() }); | ||
| 153 | 195 | ||
| 154 | // Each feed stands alone: a failed one reads as empty and is named in the | 196 | // Each feed stands alone: a failed one reads as empty and is named in the |
| 155 | // notice above the grid, instead of blanking the whole calendar. | 197 | // notice above the grid, instead of blanking the whole calendar. |
| @@ -224,10 +266,10 @@ function CalendarContent() { | |||
| 224 | } | 266 | } |
| 225 | for (const exam of exams() ?? []) { | 267 | for (const exam of exams() ?? []) { |
| 226 | if (!exam.starts_at || exam.draft) continue; | 268 | if (!exam.starts_at || exam.draft) continue; |
| 227 | - rows.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at, endsAt: exam.ends_at, href: `/exams/${exam.id}` }); | 269 | + rows.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at, endsAt: exam.ends_at, href: `/exams/${exam.id}`, instance: exam.class_course }); |
| 228 | } | 270 | } |
| 229 | for (const hw of homework() ?? []) { | 271 | for (const hw of homework() ?? []) { |
| 230 | - rows.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, endsAt: null, href: `/homework/${hw.id}` }); | 272 | + rows.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, endsAt: null, href: `/homework/${hw.id}`, instance: hw.class_course }); |
| 231 | } | 273 | } |
| 232 | for (const event of events() ?? []) { | 274 | for (const event of events() ?? []) { |
| 233 | if (!event.starts_at) continue; | 275 | if (!event.starts_at) continue; |
| @@ -248,6 +290,18 @@ function CalendarContent() { | |||
| 248 | return rows; | 290 | return rows; |
| 249 | }); | 291 | }); |
| 250 | 292 | ||
| 293 | + // The same ders runs in several şubeler and their exams/homework share | ||
| 294 | + // titles, so a chip leads with the şube and the agenda names "<ders> — <şube>". | ||
| 295 | + const sectionLabels = createInstanceLabels( | ||
| 296 | + () => items().flatMap((item) => (item.instance ? [item.instance] : [])), | ||
| 297 | + () => auth.user()?.role, | ||
| 298 | + ); | ||
| 299 | + const sectionOf = (item: CalendarItem) => (item.instance ? sectionLabels()[item.instance] : undefined); | ||
| 300 | + const chipTitle = (item: CalendarItem) => { | ||
| 301 | + const klass = sectionOf(item)?.className; | ||
| 302 | + return klass ? `${klass} · ${item.title}` : item.title; | ||
| 303 | + }; | ||
| 304 | + | ||
| 251 | const itemsByDay = createMemo(() => { | 305 | const itemsByDay = createMemo(() => { |
| 252 | const map = new Map<string, CalendarItem[]>(); | 306 | const map = new Map<string, CalendarItem[]>(); |
| 253 | for (const item of items()) { | 307 | for (const item of items()) { |
| @@ -305,8 +359,7 @@ function CalendarContent() { | |||
| 305 | const d = selectedDay(); | 359 | const d = selectedDay(); |
| 306 | d.setDate(d.getDate() + days); | 360 | d.setDate(d.getDate() + days); |
| 307 | setSelected(dateKey(d)); | 361 | setSelected(dateKey(d)); |
| 308 | - setViewYear(d.getFullYear()); | 362 | + showMonthOf(d); |
| 309 | - setViewMonth(d.getMonth()); | ||
| 310 | }; | 363 | }; |
| 311 | 364 | ||
| 312 | // Monday-first, like the month grid. | 365 | // Monday-first, like the month grid. |
| @@ -335,20 +388,11 @@ function CalendarContent() { | |||
| 335 | 388 | ||
| 336 | const goToday = () => { | 389 | const goToday = () => { |
| 337 | const n = nowDate(); | 390 | const n = nowDate(); |
| 338 | - setViewYear(n.getFullYear()); | ||
| 339 | - setViewMonth(n.getMonth()); | ||
| 340 | setSelected(dateKey(n)); | 391 | setSelected(dateKey(n)); |
| 392 | + showMonthOf(n); | ||
| 341 | }; | 393 | }; |
| 342 | - const prevMonth = () => { | 394 | + const prevMonth = () => showMonthOf(new Date(viewYear(), viewMonth() - 1, 1)); |
| 343 | - const m = viewMonth(); | 395 | + const nextMonth = () => showMonthOf(new Date(viewYear(), viewMonth() + 1, 1)); |
| 344 | - if (m === 0) { setViewYear((y: number) => y - 1); setViewMonth(11); } | ||
| 345 | - else setViewMonth(m - 1); | ||
| 346 | - }; | ||
| 347 | - const nextMonth = () => { | ||
| 348 | - const m = viewMonth(); | ||
| 349 | - if (m === 11) { setViewYear((y: number) => y + 1); setViewMonth(0); } | ||
| 350 | - else setViewMonth(m + 1); | ||
| 351 | - }; | ||
| 352 | 396 | ||
| 353 | return ( | 397 | return ( |
| 354 | <div class="space-y-4"> | 398 | <div class="space-y-4"> |
| @@ -456,7 +500,7 @@ function CalendarContent() { | |||
| 456 | class={cn("block min-w-0 rounded px-1.5 py-1 text-[11px] leading-tight font-medium", KIND_STYLES[item.kind].chip)} | 500 | class={cn("block min-w-0 rounded px-1.5 py-1 text-[11px] leading-tight font-medium", KIND_STYLES[item.kind].chip)} |
| 457 | > | 501 | > |
| 458 | <span class="block truncate">{clock(item.at)}</span> | 502 | <span class="block truncate">{clock(item.at)}</span> |
| 459 | - <span class="block truncate">{item.title}</span> | 503 | + <span class="block truncate" title={sectionOf(item)?.label}>{chipTitle(item)}</span> |
| 460 | </a> | 504 | </a> |
| 461 | )} | 505 | )} |
| 462 | </For> | 506 | </For> |
| @@ -520,7 +564,7 @@ function CalendarContent() { | |||
| 520 | {(item) => ( | 564 | {(item) => ( |
| 521 | <span class={cn("inline-flex min-w-0 items-center gap-1 rounded px-1 py-0.5 text-[11px] font-medium leading-none", KIND_STYLES[item.kind].chip)}> | 565 | <span class={cn("inline-flex min-w-0 items-center gap-1 rounded px-1 py-0.5 text-[11px] font-medium leading-none", KIND_STYLES[item.kind].chip)}> |
| 522 | <span class={cn("h-1.5 w-1.5 shrink-0 rounded-full", KIND_STYLES[item.kind].dot)} /> | 566 | <span class={cn("h-1.5 w-1.5 shrink-0 rounded-full", KIND_STYLES[item.kind].dot)} /> |
| 523 | - <span class="truncate">{item.title}</span> | 567 | + <span class="truncate" title={sectionOf(item)?.label}>{chipTitle(item)}</span> |
| 524 | </span> | 568 | </span> |
| 525 | )} | 569 | )} |
| 526 | </For> | 570 | </For> |
| @@ -568,6 +612,9 @@ function CalendarContent() { | |||
| 568 | > | 612 | > |
| 569 | <div class="min-w-0"> | 613 | <div class="min-w-0"> |
| 570 | <p class={cn("truncate text-xs font-semibold", KIND_STYLES[item.kind].titleHover)}>{item.title}</p> | 614 | <p class={cn("truncate text-xs font-semibold", KIND_STYLES[item.kind].titleHover)}>{item.title}</p> |
| 615 | + <Show when={sectionOf(item)}> | ||
| 616 | + {(section) => <p class="mt-0.5 truncate text-[11px] text-text-default">{section().label}</p>} | ||
| 617 | + </Show> | ||
| 571 | <p class="mt-0.5 text-[11px] text-muted-foreground">{timeRange(item)}</p> | 618 | <p class="mt-0.5 text-[11px] text-muted-foreground">{timeRange(item)}</p> |
| 572 | </div> | 619 | </div> |
| 573 | <Show | 620 | <Show |
src/pages/class-detail-page.tsxmodified+8 -3
| @@ -38,8 +38,11 @@ import { UserSearchSelect } from "@/components/users/user-search-select"; | |||
| 38 | import { createFlash } from "@/lib/flash"; | 38 | import { createFlash } from "@/lib/flash"; |
| 39 | import { personLabel } from "@/lib/person"; | 39 | import { personLabel } from "@/lib/person"; |
| 40 | import { hasMinRole } from "@/lib/roles"; | 40 | import { hasMinRole } from "@/lib/roles"; |
| 41 | +import { createUrlString } from "@/lib/url-state"; | ||
| 41 | import { useAuth } from "@/stores/auth-context"; | 42 | import { useAuth } from "@/stores/auth-context"; |
| 42 | import { useT } from "@/stores/preferences-context"; | 43 | import { useT } from "@/stores/preferences-context"; |
| 44 | +import { RecordNotFound } from "@/components/layout/record-not-found"; | ||
| 45 | +import { isNotFoundError } from "@/lib/record-list-path"; | ||
| 43 | 46 | ||
| 44 | export default function ClassDetailPage() { | 47 | export default function ClassDetailPage() { |
| 45 | return <RouteGuard minRole="teacher"><ClassDetailContent /></RouteGuard>; | 48 | return <RouteGuard minRole="teacher"><ClassDetailContent /></RouteGuard>; |
| @@ -54,7 +57,7 @@ function ClassDetailContent() { | |||
| 54 | const id = createMemo(() => { location(); return params().id; }); | 57 | const id = createMemo(() => { location(); return params().id; }); |
| 55 | const canManage = () => hasMinRole(auth.user()?.role, "manager"); | 58 | const canManage = () => hasMinRole(auth.user()?.role, "manager"); |
| 56 | 59 | ||
| 57 | - const [tab, setTab] = createSignal("members"); | 60 | + const [tab, setTab] = createUrlString("tab", "members"); |
| 58 | const [error, setError] = createSignal(""); | 61 | const [error, setError] = createSignal(""); |
| 59 | const [flash, setFlash] = createFlash(); | 62 | const [flash, setFlash] = createFlash(); |
| 60 | const [pending, setPending] = createSignal(false); | 63 | const [pending, setPending] = createSignal(false); |
| @@ -229,7 +232,9 @@ function ClassDetailContent() { | |||
| 229 | when={loadedClass()} | 232 | when={loadedClass()} |
| 230 | fallback={ | 233 | fallback={ |
| 231 | <Show when={cls.error} fallback={<PageSpinner />}> | 234 | <Show when={cls.error} fallback={<PageSpinner />}> |
| 232 | - <Alert variant="destructive">{formatApiError(cls.error)}</Alert> | 235 | + <Show when={!isNotFoundError(cls.error)} fallback={<RecordNotFound backTo="/management/classes" />}> |
| 236 | + <Alert variant="destructive">{formatApiError(cls.error)}</Alert> | ||
| 237 | + </Show> | ||
| 233 | </Show> | 238 | </Show> |
| 234 | } | 239 | } |
| 235 | > | 240 | > |
| @@ -318,7 +323,7 @@ function ClassDetailContent() { | |||
| 318 | <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> | 323 | <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> |
| 319 | <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> | 324 | <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> |
| 320 | <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> | 325 | <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> |
| 321 | - <UserSearchSelect id="edit-class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" /> | 326 | + <UserSearchSelect id="edit-class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} initialUser={c().teacher} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" /> |
| 322 | </div> | 327 | </div> |
| 323 | <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> | 328 | <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> |
| 324 | </form> | 329 | </form> |
src/pages/course-detail-page.tsxmodified+10 -6
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; | 1 | +import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; | 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router"; | 3 | import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router"; |
| 4 | import type { ColumnDef } from "@tanstack/solid-table"; | 4 | import type { ColumnDef } from "@tanstack/solid-table"; |
| @@ -40,6 +40,7 @@ import { useAuth } from "@/stores/auth-context"; | |||
| 40 | import { useModules } from "@/stores/modules-context"; | 40 | import { useModules } from "@/stores/modules-context"; |
| 41 | import { useT } from "@/stores/preferences-context"; | 41 | import { useT } from "@/stores/preferences-context"; |
| 42 | import { hasMinRole } from "@/lib/roles"; | 42 | import { hasMinRole } from "@/lib/roles"; |
| 43 | +import { createUrlString } from "@/lib/url-state"; | ||
| 43 | import { cn } from "@/lib/cn"; | 44 | import { cn } from "@/lib/cn"; |
| 44 | import { matchesSearch } from "@/lib/search-text"; | 45 | import { matchesSearch } from "@/lib/search-text"; |
| 45 | 46 | ||
| @@ -79,17 +80,20 @@ function CourseDetailContent() { | |||
| 79 | sections: () => modules.isEnabled("classes"), | 80 | sections: () => modules.isEnabled("classes"), |
| 80 | notes: () => modules.isEnabled("course_notes"), | 81 | notes: () => modules.isEnabled("course_notes"), |
| 81 | }; | 82 | }; |
| 82 | - const [courseTab, setCourseTab] = createSignal("subjects"); | 83 | + // `?tab=` is the open tab, so Back from a şube lands on "Şubeler" again. |
| 84 | + const [requestedTab, setCourseTab] = createUrlString("tab", "subjects"); | ||
| 83 | const availableTabs = () => [ | 85 | const availableTabs = () => [ |
| 84 | ...(tabOn.subjects() ? ["subjects"] : []), | 86 | ...(tabOn.subjects() ? ["subjects"] : []), |
| 85 | ...(tabOn.sections() ? ["sections"] : []), | 87 | ...(tabOn.sections() ? ["sections"] : []), |
| 86 | ...(tabOn.notes() ? ["notes"] : []), | 88 | ...(tabOn.notes() ? ["notes"] : []), |
| 87 | ...(hasMembers() ? ["members"] : []), | 89 | ...(hasMembers() ? ["members"] : []), |
| 88 | ]; | 90 | ]; |
| 89 | - createEffect(() => { | 91 | + // A tab not on offer falls back to the first one that is, without |
| 92 | + // rewriting the URL: "members" only appears once the course has loaded. | ||
| 93 | + const courseTab = () => { | ||
| 90 | const tabs = availableTabs(); | 94 | const tabs = availableTabs(); |
| 91 | - if (tabs.length > 0 && !tabs.includes(courseTab())) setCourseTab(tabs[0]); | 95 | + return tabs.length === 0 || tabs.includes(requestedTab()) ? requestedTab() : tabs[0]; |
| 92 | - }); | 96 | + }; |
| 93 | const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId)); | 97 | const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId)); |
| 94 | const [mine] = createResource( | 98 | const [mine] = createResource( |
| 95 | () => (auth.user()?.role === "student" ? true : null), | 99 | () => (auth.user()?.role === "student" ? true : null), |
| @@ -154,7 +158,7 @@ function CourseDetailContent() { | |||
| 154 | const [showNoteForm, setShowNoteForm] = createSignal(false); | 158 | const [showNoteForm, setShowNoteForm] = createSignal(false); |
| 155 | const [showMemberForm, setShowMemberForm] = createSignal(false); | 159 | const [showMemberForm, setShowMemberForm] = createSignal(false); |
| 156 | const [noteCount, setNoteCount] = createSignal<number | null>(null); | 160 | const [noteCount, setNoteCount] = createSignal<number | null>(null); |
| 157 | - const [sectionSearch, setSectionSearch] = createSignal(""); | 161 | + const [sectionSearch, setSectionSearch] = createUrlString("sections.q"); |
| 158 | const [memberUserId, setMemberUserId] = createSignal(""); | 162 | const [memberUserId, setMemberUserId] = createSignal(""); |
| 159 | const [error, setError] = createSignal(""); | 163 | const [error, setError] = createSignal(""); |
| 160 | const [pending, setPending] = createSignal(false); | 164 | const [pending, setPending] = createSignal(false); |
src/pages/courses-page.test.tsxmodified+11 -6
| @@ -14,6 +14,7 @@ vi.mock("@tanstack/solid-router", () => ({ | |||
| 14 | Navigate: () => null, | 14 | Navigate: () => null, |
| 15 | useNavigate: () => navigate, | 15 | useNavigate: () => navigate, |
| 16 | useSearch: () => () => ({ kind: undefined, action: undefined }), | 16 | useSearch: () => () => ({ kind: undefined, action: undefined }), |
| 17 | + useLocation: () => () => ({ pathname: "/courses", search: {}, searchStr: "", hash: "" }), | ||
| 17 | })); | 18 | })); |
| 18 | vi.mock("@/stores/auth-context", () => ({ | 19 | vi.mock("@/stores/auth-context", () => ({ |
| 19 | useAuth: () => ({ | 20 | useAuth: () => ({ |
| @@ -81,11 +82,11 @@ test("student class directory uses only enrolled-course data", async () => { | |||
| 81 | expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); | 82 | expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); |
| 82 | expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); | 83 | expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); |
| 83 | expect(getMyCourses).toHaveBeenCalledTimes(1); | 84 | expect(getMyCourses).toHaveBeenCalledTimes(1); |
| 84 | - expect(navigate).toHaveBeenCalledWith({ | 85 | + const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record<string, unknown>) => Record<string, unknown> }; |
| 85 | - to: "/courses", | 86 | + expect(tabNavigation.to).toBe("/courses"); |
| 86 | - search: { action: undefined, kind: "study" }, | 87 | + expect(tabNavigation.replace).toBe(true); |
| 87 | - replace: true, | 88 | + // The kind tab keeps the search text and restarts paging. |
| 88 | - }); | 89 | + expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, action: undefined, kind: "study", page: undefined }); |
| 89 | 90 | ||
| 90 | fireEvent.click(screen.getByRole("tab", { name: "Club" })); | 91 | fireEvent.click(screen.getByRole("tab", { name: "Club" })); |
| 91 | expect(await screen.findByRole("link", { name: /Robotics/ })).toBeTruthy(); | 92 | expect(await screen.findByRole("link", { name: /Robotics/ })).toBeTruthy(); |
| @@ -101,7 +102,11 @@ test("student class directory uses only enrolled-course data", async () => { | |||
| 101 | expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); | 102 | expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); |
| 102 | 103 | ||
| 103 | fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } }); | 104 | fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } }); |
| 104 | - fireEvent.change(screen.getByLabelText("Taught in", { selector: "select" }), { target: { value: "untaught" } }); | 105 | + fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" }); |
| 106 | + const untaught = await screen.findByRole("menuitem", { name: "No sections" }); | ||
| 107 | + fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" }); | ||
| 108 | + fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" }); | ||
| 109 | + fireEvent.click(untaught); | ||
| 105 | expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); | 110 | expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); |
| 106 | expect(screen.queryByRole("link", { name: /Robotics/ })).toBeNull(); | 111 | expect(screen.queryByRole("link", { name: /Robotics/ })).toBeNull(); |
| 107 | }); | 112 | }); |
src/pages/courses-page.tsxmodified+46 -15
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; | 1 | +import { For, Show, Suspense, createEffect, createMemo, createSignal, on } from "solid-js"; |
| 2 | import { createResponsivePageSize } from "@/lib/create-page-size"; | 2 | import { createResponsivePageSize } from "@/lib/create-page-size"; |
| 3 | import { createResource } from "@/lib/create-resource"; | 3 | import { createResource } from "@/lib/create-resource"; |
| 4 | import { useNavigate, useSearch } from "@tanstack/solid-router"; | 4 | import { useNavigate, useSearch } from "@tanstack/solid-router"; |
| @@ -18,7 +18,7 @@ import { Input } from "@/components/ui/input"; | |||
| 18 | import { Label } from "@/components/ui/label"; | 18 | import { Label } from "@/components/ui/label"; |
| 19 | import { PageSpinner } from "@/components/ui/page-spinner"; | 19 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 20 | import { TablePagination } from "@/components/ui/table-pagination"; | 20 | import { TablePagination } from "@/components/ui/table-pagination"; |
| 21 | -import { Select } from "@/components/ui/select"; | 21 | +import { DropdownSelect } from "@/components/ui/select"; |
| 22 | import { courseKindLabel } from "@/lib/course-kind"; | 22 | import { courseKindLabel } from "@/lib/course-kind"; |
| 23 | import { SidePanel } from "@/components/ui/side-panel"; | 23 | import { SidePanel } from "@/components/ui/side-panel"; |
| 24 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | 24 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| @@ -27,6 +27,7 @@ import { createFlash } from "@/lib/flash"; | |||
| 27 | import { matchesSearch } from "@/lib/search-text"; | 27 | import { matchesSearch } from "@/lib/search-text"; |
| 28 | import { personLabel } from "@/lib/person"; | 28 | import { personLabel } from "@/lib/person"; |
| 29 | import { hasMinRole } from "@/lib/roles"; | 29 | import { hasMinRole } from "@/lib/roles"; |
| 30 | +import { createUrlEnum, createUrlPageIndex, createUrlString } from "@/lib/url-state"; | ||
| 30 | import { useAuth } from "@/stores/auth-context"; | 31 | import { useAuth } from "@/stores/auth-context"; |
| 31 | import { usePreferences, useT } from "@/stores/preferences-context"; | 32 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 32 | 33 | ||
| @@ -55,10 +56,17 @@ function CoursesContent() { | |||
| 55 | // Catalog rows carry no term, capacity or staff any more — a şube decides | 56 | // Catalog rows carry no term, capacity or staff any more — a şube decides |
| 56 | // all three when it attaches the course. `taughtFilter` narrows by whether | 57 | // all three when it attaches the course. `taughtFilter` narrows by whether |
| 57 | // any şube has. | 58 | // any şube has. |
| 58 | - const [taughtFilter, setTaughtFilter] = createSignal("all"); | 59 | + // Search, filter and page ride in the URL so Back from a course and a |
| 59 | - const [page, setPage] = createSignal(0); | 60 | + // reload land where the list was left. |
| 61 | + const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all"); | ||
| 62 | + const [page, setPage] = createUrlPageIndex(); | ||
| 60 | const pageSize = createResponsivePageSize(PAGE_SIZE); | 63 | const pageSize = createResponsivePageSize(PAGE_SIZE); |
| 61 | - const [search, setSearch] = createSignal(""); | 64 | + const [search, setSearch] = createUrlString("q"); |
| 65 | + const narrowed = () => search().trim() !== "" || taughtFilter() !== "all"; | ||
| 66 | + const clearNarrowing = () => { | ||
| 67 | + setSearch(""); | ||
| 68 | + setTaughtFilter("all"); | ||
| 69 | + }; | ||
| 62 | const [error, setError] = createSignal(""); | 70 | const [error, setError] = createSignal(""); |
| 63 | const [pending, setPending] = createSignal(false); | 71 | const [pending, setPending] = createSignal(false); |
| 64 | const [flash, setFlash] = createFlash(); | 72 | const [flash, setFlash] = createFlash(); |
| @@ -69,9 +77,8 @@ function CoursesContent() { | |||
| 69 | createEffect(() => { | 77 | createEffect(() => { |
| 70 | setPageKind(routeSearch().kind); | 78 | setPageKind(routeSearch().kind); |
| 71 | }); | 79 | }); |
| 72 | - createEffect(() => { | 80 | + // Deferred: the page restored from the URL must survive the first run. |
| 73 | - pageKind(); taughtFilter(); search(); pageSize(); setPage(0); | 81 | + createEffect(on(() => [pageKind(), taughtFilter(), search(), pageSize()], () => setPage(0), { defer: true })); |
| 74 | - }); | ||
| 75 | 82 | ||
| 76 | const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); | 83 | const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); |
| 77 | const [list, { refetch }] = createResource( | 84 | const [list, { refetch }] = createResource( |
| @@ -90,6 +97,10 @@ function CoursesContent() { | |||
| 90 | }); | 97 | }); |
| 91 | }); | 98 | }); |
| 92 | const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredCourses().length / pageSize()))); | 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 | + }); | ||
| 93 | const visibleCourses = createMemo(() => filteredCourses().slice(page() * pageSize(), (page() + 1) * pageSize())); | 104 | const visibleCourses = createMemo(() => filteredCourses().slice(page() * pageSize(), (page() + 1) * pageSize())); |
| 94 | 105 | ||
| 95 | const createCourse = async (event: SubmitEvent) => { | 106 | const createCourse = async (event: SubmitEvent) => { |
| @@ -140,7 +151,7 @@ function CoursesContent() { | |||
| 140 | setPageKind(kind); | 151 | setPageKind(kind); |
| 141 | void navigate({ | 152 | void navigate({ |
| 142 | to: "/courses", | 153 | to: "/courses", |
| 143 | - search: { action: undefined, kind }, | 154 | + search: (prev) => ({ q: prev.q, taught: prev.taught, action: undefined, kind, page: undefined }), |
| 144 | replace: true, | 155 | replace: true, |
| 145 | }); | 156 | }); |
| 146 | }} | 157 | }} |
| @@ -161,11 +172,16 @@ function CoursesContent() { | |||
| 161 | searchHint={t("search.hint.courses")} | 172 | searchHint={t("search.hint.courses")} |
| 162 | onSearchInput={setSearch} | 173 | onSearchInput={setSearch} |
| 163 | filters={ | 174 | filters={ |
| 164 | - <Select wrapperClass="w-40 shrink-0 sm:w-52" class="h-8 rounded-lg" aria-label={t("instances.taughtIn")} value={taughtFilter()} onChange={(e) => setTaughtFilter(e.currentTarget.value)}> | 175 | + <DropdownSelect |
| 165 | - <option value="all">{t("common.all")}</option> | 176 | + labelPrefix={t("courses.sectionsFilter")} |
| 166 | - <option value="taught">{t("instances.taughtIn")}</option> | 177 | + value={taughtFilter()} |
| 167 | - <option value="untaught">{t("instances.empty")}</option> | 178 | + onChange={(value) => setTaughtFilter(value === "taught" || value === "untaught" ? value : "all")} |
| 168 | - </Select> | 179 | + options={[ |
| 180 | + { value: "all", label: t("common.all") }, | ||
| 181 | + { value: "taught", label: t("courses.withSections") }, | ||
| 182 | + { value: "untaught", label: t("courses.withoutSections") }, | ||
| 183 | + ]} | ||
| 184 | + /> | ||
| 169 | } | 185 | } |
| 170 | actions={ | 186 | actions={ |
| 171 | <Show when={canCreate()}> | 187 | <Show when={canCreate()}> |
| @@ -185,7 +201,22 @@ function CoursesContent() { | |||
| 185 | > | 201 | > |
| 186 | <Show | 202 | <Show |
| 187 | when={filteredCourses().length > 0} | 203 | when={filteredCourses().length > 0} |
| 188 | - fallback={<EmptyState kind="courses" title={t("courses.empty", { item: kindInSentence() })} />} | 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 | + } | ||
| 189 | > | 220 | > |
| 190 | <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"}> | 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"}> |
| 191 | <For each={visibleCourses()}> | 222 | <For each={visibleCourses()}> |
src/pages/dashboard-page.test.tsxmodified+16 -1
| @@ -63,9 +63,11 @@ vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], | |||
| 63 | vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); | 63 | vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); |
| 64 | vi.mock("@/api/courses", () => ({ | 64 | vi.mock("@/api/courses", () => ({ |
| 65 | getCourses: async () => page([course]), | 65 | getCourses: async () => page([course]), |
| 66 | + getCourseById: async () => course, | ||
| 66 | })); | 67 | })); |
| 67 | vi.mock("@/api/instances", () => ({ | 68 | vi.mock("@/api/instances", () => ({ |
| 68 | getMyInstances: async () => page([instance]), | 69 | getMyInstances: async () => page([instance]), |
| 70 | + getInstanceById: async () => instance, | ||
| 69 | getInstanceEnrollments: async () => page([]), | 71 | getInstanceEnrollments: async () => page([]), |
| 70 | getInstanceSessions: async () => page([ | 72 | getInstanceSessions: async () => page([ |
| 71 | { id: "session-today", class_course: "instance-1", teacher: { id: "u-1", username: "demo", display_name: null }, topic: "Fractions", starts_at: now, ends_at: now + 40 * 60 * 1000 }, | 73 | { id: "session-today", class_course: "instance-1", teacher: { id: "u-1", username: "demo", display_name: null }, topic: "Fractions", starts_at: now, ends_at: now + 40 * 60 * 1000 }, |
| @@ -130,6 +132,15 @@ vi.mock("@/api/exams", async () => { | |||
| 130 | starts_at: now - 10 * DAY, | 132 | starts_at: now - 10 * DAY, |
| 131 | ends_at: now - 10 * DAY + 3_000, | 133 | ends_at: now - 10 * DAY + 3_000, |
| 132 | }, | 134 | }, |
| 135 | + // Never scheduled, yet graded: it still belongs on the trend. | ||
| 136 | + { | ||
| 137 | + id: "exam-paper", | ||
| 138 | + title: "Paper quiz", | ||
| 139 | + class_course: "instance-1", | ||
| 140 | + draft: false, | ||
| 141 | + starts_at: null, | ||
| 142 | + ends_at: null, | ||
| 143 | + }, | ||
| 133 | ]); | 144 | ]); |
| 134 | }, | 145 | }, |
| 135 | getExamStatistics: async (examId: string) => ({ | 146 | getExamStatistics: async (examId: string) => ({ |
| @@ -204,6 +215,8 @@ vi.mock("@/api/classes", () => ({ | |||
| 204 | getMyClasses: async () => page([{ id: "class-1", name: "9-A" }]), | 215 | getMyClasses: async () => page([{ id: "class-1", name: "9-A" }]), |
| 205 | getClassesByUserId: async () => page([]), | 216 | getClassesByUserId: async () => page([]), |
| 206 | getClasses: async () => page([]), | 217 | getClasses: async () => page([]), |
| 218 | + getClassById: async () => ({ id: "class-1", name: "9-A" }), | ||
| 219 | + getClassMembers: async () => page([]), | ||
| 207 | })); | 220 | })); |
| 208 | vi.mock("@/api/academic-years", () => ({ | 221 | vi.mock("@/api/academic-years", () => ({ |
| 209 | getAcademicYears: async () => page([{ id: "y-1", name: "2026-2027" }]), | 222 | getAcademicYears: async () => page([{ id: "y-1", name: "2026-2027" }]), |
| @@ -284,7 +297,9 @@ test("teacher sees real exam averages instead of capacities and resource links", | |||
| 284 | expect(screen.getByText("Success trend")).toBeTruthy(); | 297 | expect(screen.getByText("Success trend")).toBeTruthy(); |
| 285 | expect(screen.getByText("Average of recent exams, by course.")).toBeTruthy(); | 298 | expect(screen.getByText("Average of recent exams, by course.")).toBeTruthy(); |
| 286 | // The trend point and the per-course bar carry the backend's average. | 299 | // The trend point and the per-course bar carry the backend's average. |
| 287 | - expect(await screen.findByRole("img", { name: /Algebra: Midterm.*74\.5/ })).toBeTruthy(); | 300 | + expect(await screen.findByRole("img", { name: /Algebra — 9-A: Midterm.*74\.5/ })).toBeTruthy(); |
| 301 | + // An unscheduled exam with marks is charted too (it used to empty the panel). | ||
| 302 | + expect(screen.getByRole("img", { name: /Algebra — 9-A: Paper quiz/ })).toBeTruthy(); | ||
| 288 | expect((await screen.findAllByText("74.5")).length).toBeGreaterThanOrEqual(2); | 303 | expect((await screen.findAllByText("74.5")).length).toBeGreaterThanOrEqual(2); |
| 289 | expect(screen.queryByText("Course capacities")).toBeNull(); | 304 | expect(screen.queryByText("Course capacities")).toBeNull(); |
| 290 | expect(screen.queryByText("Workload split")).toBeNull(); | 305 | expect(screen.queryByText("Workload split")).toBeNull(); |
src/pages/dashboard-page.tsxmodified+122 -55
| @@ -5,7 +5,7 @@ import type { ColumnDef } from "@tanstack/solid-table"; | |||
| 5 | import type { Role } from "@/api/client"; | 5 | import type { Role } from "@/api/client"; |
| 6 | import { formatApiError, isModuleDisabledError } from "@/api/client"; | 6 | import { formatApiError, isModuleDisabledError } from "@/api/client"; |
| 7 | import { getAppointments } from "@/api/appointments"; | 7 | import { getAppointments } from "@/api/appointments"; |
| 8 | -import { getClasses, getClassesByUserId, getMyClasses } from "@/api/classes"; | 8 | +import { getClasses, getClassesByUserId, getClassMembers, getMyClasses } from "@/api/classes"; |
| 9 | import { getCourses } from "@/api/courses"; | 9 | import { getCourses } from "@/api/courses"; |
| 10 | import { getInstanceEnrollments, getMyInstances } from "@/api/instances"; | 10 | import { getInstanceEnrollments, getMyInstances } from "@/api/instances"; |
| 11 | import { getEvents } from "@/api/events"; | 11 | import { getEvents } from "@/api/events"; |
| @@ -51,12 +51,15 @@ import { | |||
| 51 | import { PageSpinner } from "@/components/ui/page-spinner"; | 51 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 52 | import type { MessageKey } from "@/i18n/messages"; | 52 | import type { MessageKey } from "@/i18n/messages"; |
| 53 | import { cn } from "@/lib/cn"; | 53 | import { cn } from "@/lib/cn"; |
| 54 | -import { formatDateTime } from "@/lib/format"; | 54 | +import { formatDateTime, formatDecimal } from "@/lib/format"; |
| 55 | +import { createInstanceLabels, loadInstanceLabels } from "@/lib/instance-labels"; | ||
| 56 | +import { uuidV7Ms } from "@/lib/uuid-time"; | ||
| 55 | import { formatTry } from "@/lib/meals"; | 57 | import { formatTry } from "@/lib/meals"; |
| 56 | import { matchesSearch } from "@/lib/search-text"; | 58 | import { matchesSearch } from "@/lib/search-text"; |
| 57 | import { personLabel } from "@/lib/person"; | 59 | import { personLabel } from "@/lib/person"; |
| 58 | import { packageLabel } from "@/lib/module-labels"; | 60 | import { packageLabel } from "@/lib/module-labels"; |
| 59 | import { hasMinRole } from "@/lib/roles"; | 61 | import { hasMinRole } from "@/lib/roles"; |
| 62 | +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; | ||
| 60 | import { getModulesCatalog } from "@/api/modules"; | 63 | import { getModulesCatalog } from "@/api/modules"; |
| 61 | import { useModules } from "@/stores/modules-context"; | 64 | import { useModules } from "@/stores/modules-context"; |
| 62 | import { useAuth } from "@/stores/auth-context"; | 65 | import { useAuth } from "@/stores/auth-context"; |
| @@ -74,6 +77,16 @@ const HEATMAP_WEEKS = 26; | |||
| 74 | const TREND_EXAM_CAP = 20; | 77 | const TREND_EXAM_CAP = 20; |
| 75 | /** Marks plotted in a student's own trend. */ | 78 | /** Marks plotted in a student's own trend. */ |
| 76 | const TREND_MARK_CAP = 20; | 79 | const TREND_MARK_CAP = 20; |
| 80 | +/** Classes whose roster size the admin "Şubeler" quick links read. */ | ||
| 81 | +const CLASS_LINK_CAP = 12; | ||
| 82 | + | ||
| 83 | +/** | ||
| 84 | + * Chronological key for an exam: its schedule when it has one, else when it | ||
| 85 | + * was created (the id is a UUIDv7). Used only to order points, never shown. | ||
| 86 | + */ | ||
| 87 | +function examOrder(exam: { id: string; starts_at: number | null }): number { | ||
| 88 | + return exam.starts_at ?? uuidV7Ms(exam.id) ?? 0; | ||
| 89 | +} | ||
| 77 | 90 | ||
| 78 | type Status = "active" | "today" | "soon"; | 91 | type Status = "active" | "today" | "soon"; |
| 79 | type DeadlineKind = "exam" | "event" | "appointment" | "homework" | "payment"; | 92 | type DeadlineKind = "exam" | "event" | "appointment" | "homework" | "payment"; |
| @@ -84,6 +97,10 @@ type DeadlineRow = { | |||
| 84 | title: string; | 97 | title: string; |
| 85 | at: number; | 98 | at: number; |
| 86 | status: Status; | 99 | status: Status; |
| 100 | + /** The şube×ders an exam or homework belongs to. */ | ||
| 101 | + instance?: string; | ||
| 102 | + /** Its "<ders> — <şube>" label, once read. */ | ||
| 103 | + section?: string; | ||
| 87 | }; | 104 | }; |
| 88 | 105 | ||
| 89 | type StatCardData = { | 106 | type StatCardData = { |
| @@ -230,9 +247,12 @@ function DashboardContent() { | |||
| 230 | const [examStats] = createResource( | 247 | const [examStats] = createResource( |
| 231 | () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null, | 248 | () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null, |
| 232 | async (items) => { | 249 | async (items) => { |
| 250 | + // An exam with no schedule (an untimed, paper or imported one) still | ||
| 251 | + // gets graded — skipping unscheduled exams left the charts empty while | ||
| 252 | + // real marks existed. Only a scheduled exam still in the future is out. | ||
| 233 | const recent = items | 253 | const recent = items |
| 234 | - .filter((exam) => !exam.draft && exam.starts_at != null && exam.starts_at <= now()) | 254 | + .filter((exam) => !exam.draft && (exam.starts_at == null || exam.starts_at <= now())) |
| 235 | - .sort((a, b) => b.starts_at! - a.starts_at!) | 255 | + .sort((a, b) => examOrder(b) - examOrder(a)) |
| 236 | .slice(0, TREND_EXAM_CAP); | 256 | .slice(0, TREND_EXAM_CAP); |
| 237 | const settled = await Promise.all( | 257 | const settled = await Promise.all( |
| 238 | recent.map(async (exam) => { | 258 | recent.map(async (exam) => { |
| @@ -246,9 +266,17 @@ function DashboardContent() { | |||
| 246 | ); | 266 | ); |
| 247 | return settled | 267 | return settled |
| 248 | .filter((row) => row.stats?.average != null) | 268 | .filter((row) => row.stats?.average != null) |
| 249 | - .sort((a, b) => a.exam.starts_at! - b.exam.starts_at!); | 269 | + .sort((a, b) => examOrder(a.exam) - examOrder(b.exam)); |
| 250 | }, | 270 | }, |
| 251 | ); | 271 | ); |
| 272 | + // Exams name an instance (şube × ders). The trend labels "<ders> — <şube>" | ||
| 273 | + // and the course bars group by the catalog course behind it; `/instances/me` | ||
| 274 | + // is empty for the office, so each charted instance is read by id (bounded | ||
| 275 | + // by TREND_EXAM_CAP, cached for the tab). | ||
| 276 | + const [trendSections] = createResource( | ||
| 277 | + () => examStats.latest ?? null, | ||
| 278 | + (rows) => loadInstanceLabels(rows.map((row) => row.exam.class_course), role()), | ||
| 279 | + ); | ||
| 252 | const myClass = () => myClasses.latest?.items[0] ?? null; | 280 | const myClass = () => myClasses.latest?.items[0] ?? null; |
| 253 | 281 | ||
| 254 | // TCH-01 "Öğrencim" stat — Course carries no enrolled-count field, so this | 282 | // TCH-01 "Öğrencim" stat — Course carries no enrolled-count field, so this |
| @@ -341,9 +369,26 @@ function DashboardContent() { | |||
| 341 | () => (isAdminHome() ? true : null), | 369 | () => (isAdminHome() ? true : null), |
| 342 | () => getUsers({ limit: 30 }), | 370 | () => getUsers({ limit: 30 }), |
| 343 | ); | 371 | ); |
| 372 | + // "Şubeler" quick links: the classes with the most students, each labelled | ||
| 373 | + // with its roster size. A class carries no member count, so each one costs | ||
| 374 | + // a `limit=1` roster read for its `total` — capped at CLASS_LINK_CAP classes | ||
| 375 | + // (taken in name order) so a large school does not fan out on the homepage. | ||
| 344 | const [recentClasses] = createResource( | 376 | const [recentClasses] = createResource( |
| 345 | () => (isAdminHome() && on("classes") ? true : null), | 377 | () => (isAdminHome() && on("classes") ? true : null), |
| 346 | - () => quiet(getClasses({ limit: 2 })), | 378 | + async () => { |
| 379 | + const page = await quiet(getClasses({ limit: 200 })); | ||
| 380 | + if (!page) return null; | ||
| 381 | + const candidates = [...page.items] | ||
| 382 | + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) | ||
| 383 | + .slice(0, CLASS_LINK_CAP); | ||
| 384 | + const counted = await mapConcurrent(candidates, FAN_OUT_LIMIT, async (cls) => ({ | ||
| 385 | + cls, | ||
| 386 | + students: await getClassMembers(cls.id, { limit: 1 }).then((members) => members.total, () => null), | ||
| 387 | + })); | ||
| 388 | + return counted | ||
| 389 | + .sort((a, b) => (b.students ?? -1) - (a.students ?? -1) || a.cls.name.localeCompare(b.cls.name, "tr", { numeric: true })) | ||
| 390 | + .slice(0, 2); | ||
| 391 | + }, | ||
| 347 | ); | 392 | ); |
| 348 | const studentQuickLinks = createMemo<QuickLinkRow[]>(() => | 393 | const studentQuickLinks = createMemo<QuickLinkRow[]>(() => |
| 349 | (recentStudents()?.items ?? []) | 394 | (recentStudents()?.items ?? []) |
| @@ -357,10 +402,10 @@ function DashboardContent() { | |||
| 357 | })), | 402 | })), |
| 358 | ); | 403 | ); |
| 359 | const classQuickLinks = createMemo<QuickLinkRow[]>(() => | 404 | const classQuickLinks = createMemo<QuickLinkRow[]>(() => |
| 360 | - (recentClasses()?.items ?? []).slice(0, 2).map((cls) => ({ | 405 | + (recentClasses() ?? []).map((row) => ({ |
| 361 | - id: cls.id, | 406 | + id: row.cls.id, |
| 362 | - primary: cls.name, | 407 | + primary: row.cls.name, |
| 363 | - secondary: cls.grade ?? undefined, | 408 | + secondary: row.students == null ? undefined : t("classGroups.studentsCount", { count: row.students }), |
| 364 | Icon: IconBook, | 409 | Icon: IconBook, |
| 365 | })), | 410 | })), |
| 366 | ); | 411 | ); |
| @@ -433,7 +478,7 @@ function DashboardContent() { | |||
| 433 | return [ | 478 | return [ |
| 434 | { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook }, | 479 | { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook }, |
| 435 | { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam }, | 480 | { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam }, |
| 436 | - { labelKey: "dashboard.stats.average", module: "marks", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, | 481 | + { labelKey: "dashboard.stats.average", module: "marks", value: formatDecimal(marks()?.overall_average, locale()), Icon: IconChart }, |
| 437 | { labelKey: "dashboard.stats.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, | 482 | { labelKey: "dashboard.stats.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, |
| 438 | ]; | 483 | ]; |
| 439 | } | 484 | } |
| @@ -468,68 +513,70 @@ function DashboardContent() { | |||
| 468 | const myMarkTrend = createMemo(() => { | 513 | const myMarkTrend = createMemo(() => { |
| 469 | const report = marks(); | 514 | const report = marks(); |
| 470 | if (!report) return []; | 515 | if (!report) return []; |
| 516 | + // A mark's exam may have no schedule; it still belongs on the line, | ||
| 517 | + // ordered by when the exam was created, just without a date caption. | ||
| 471 | const examDates = new Map((exams()?.items ?? []).map((exam) => [exam.id, exam.starts_at])); | 518 | const examDates = new Map((exams()?.items ?? []).map((exam) => [exam.id, exam.starts_at])); |
| 472 | return report.courses | 519 | return report.courses |
| 473 | .flatMap((course) => | 520 | .flatMap((course) => |
| 474 | - course.results.map((result) => ({ | 521 | + course.results.map((result) => { |
| 475 | - id: `${course.course.id}:${result.exam}`, | 522 | + const at = examDates.get(result.exam) ?? null; |
| 476 | - label: `${course.course.title}: ${result.title}`, | 523 | + return { |
| 477 | - value: result.mark, | 524 | + id: `${course.course.id}:${result.exam}`, |
| 478 | - at: examDates.get(result.exam) ?? null, | 525 | + label: `${course.course.title}: ${result.title}`, |
| 479 | - })), | 526 | + value: result.mark, |
| 527 | + at, | ||
| 528 | + order: examOrder({ id: result.exam, starts_at: at }), | ||
| 529 | + }; | ||
| 530 | + }), | ||
| 480 | ) | 531 | ) |
| 481 | - .filter((row): row is typeof row & { at: number } => row.at != null) | 532 | + .sort((a, b) => a.order - b.order) |
| 482 | - .sort((a, b) => a.at - b.at) | ||
| 483 | .slice(-TREND_MARK_CAP) | 533 | .slice(-TREND_MARK_CAP) |
| 484 | .map((row) => ({ | 534 | .map((row) => ({ |
| 485 | id: row.id, | 535 | id: row.id, |
| 486 | label: row.label, | 536 | label: row.label, |
| 487 | value: row.value, | 537 | value: row.value, |
| 488 | - formattedValue: row.value.toFixed(1), | 538 | + formattedValue: formatDecimal(row.value, locale()), |
| 489 | - caption: formatTrendDate(row.at), | 539 | + caption: row.at == null ? undefined : formatTrendDate(row.at), |
| 490 | })); | 540 | })); |
| 491 | }); | 541 | }); |
| 492 | 542 | ||
| 493 | - // Exams name an instance; the catalog course behind it is what a chart label | 543 | + const sectionOf = (instanceId: string) => trendSections.latest?.get(instanceId) ?? null; |
| 494 | - // should read, and `/instances/me` already covers the teacher's own sections. | ||
| 495 | - const [myInstances] = createResource( | ||
| 496 | - () => (role() && role() !== "parent" ? true : null), | ||
| 497 | - async () => (await getMyInstances({ limit: 200 })).items, | ||
| 498 | - ); | ||
| 499 | - const instanceCourse = (instanceId: string) => | ||
| 500 | - (myInstances.latest ?? []).find((instance) => instance.id === instanceId)?.course ?? null; | ||
| 501 | 544 | ||
| 502 | // Teacher+ trend — the backend's own per-exam average, oldest exam first. | 545 | // Teacher+ trend — the backend's own per-exam average, oldest exam first. |
| 503 | - const examAverageTrend = createMemo(() => { | 546 | + const examAverageTrend = createMemo(() => |
| 504 | - const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title])); | 547 | + (examStats() ?? []).map((row) => { |
| 505 | - return (examStats() ?? []).map((row) => ({ | 548 | + const section = sectionOf(row.exam.class_course); |
| 506 | - id: row.exam.id, | 549 | + return { |
| 507 | - label: `${titles.get(instanceCourse(row.exam.class_course) ?? "") ?? row.exam.class_course}: ${row.exam.title}`, | 550 | + id: row.exam.id, |
| 508 | - value: row.stats!.average!, | 551 | + label: section ? `${section.label}: ${row.exam.title}` : row.exam.title, |
| 509 | - formattedValue: row.stats!.average!.toFixed(1), | 552 | + value: row.stats!.average!, |
| 510 | - caption: formatTrendDate(row.exam.starts_at!), | 553 | + formattedValue: formatDecimal(row.stats!.average!, locale()), |
| 511 | - })); | 554 | + caption: row.exam.starts_at == null ? undefined : formatTrendDate(row.exam.starts_at), |
| 512 | - }); | 555 | + }; |
| 556 | + }), | ||
| 557 | + ); | ||
| 513 | 558 | ||
| 514 | // Teacher+ comparison — the same exam averages grouped by course, so a weak | 559 | // Teacher+ comparison — the same exam averages grouped by course, so a weak |
| 515 | // subject stands out rather than being averaged into one school-wide number. | 560 | // subject stands out rather than being averaged into one school-wide number. |
| 561 | + // An exam whose section could not be read has no course to go under and is | ||
| 562 | + // left out of the bars rather than filed under a raw id. | ||
| 516 | const courseAverageBars = createMemo(() => { | 563 | const courseAverageBars = createMemo(() => { |
| 517 | - const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title])); | 564 | + const buckets = new Map<string, { label: string; averages: number[] }>(); |
| 518 | - const buckets = new Map<string, number[]>(); | ||
| 519 | for (const row of examStats() ?? []) { | 565 | for (const row of examStats() ?? []) { |
| 520 | - const courseId = instanceCourse(row.exam.class_course) ?? row.exam.class_course; | 566 | + const section = sectionOf(row.exam.class_course); |
| 521 | - const list = buckets.get(courseId) ?? []; | 567 | + if (!section?.courseTitle) continue; |
| 522 | - list.push(row.stats!.average!); | 568 | + const bucket = buckets.get(section.course) ?? { label: section.courseTitle, averages: [] }; |
| 523 | - buckets.set(courseId, list); | 569 | + bucket.averages.push(row.stats!.average!); |
| 570 | + buckets.set(section.course, bucket); | ||
| 524 | } | 571 | } |
| 525 | return [...buckets.entries()] | 572 | return [...buckets.entries()] |
| 526 | - .map(([courseId, averages]) => { | 573 | + .map(([courseId, bucket]) => { |
| 527 | - const mean = averages.reduce((sum, value) => sum + value, 0) / averages.length; | 574 | + const mean = bucket.averages.reduce((sum, value) => sum + value, 0) / bucket.averages.length; |
| 528 | return { | 575 | return { |
| 529 | id: courseId, | 576 | id: courseId, |
| 530 | - label: titles.get(courseId) ?? courseId, | 577 | + label: bucket.label, |
| 531 | value: mean, | 578 | value: mean, |
| 532 | - formattedValue: mean.toFixed(1), | 579 | + formattedValue: formatDecimal(mean, locale()), |
| 533 | }; | 580 | }; |
| 534 | }) | 581 | }) |
| 535 | .sort((a, b) => b.value - a.value); | 582 | .sort((a, b) => b.value - a.value); |
| @@ -539,7 +586,7 @@ function DashboardContent() { | |||
| 539 | const courseAverages = createMemo(() => | 586 | const courseAverages = createMemo(() => |
| 540 | (marks()?.courses ?? []) | 587 | (marks()?.courses ?? []) |
| 541 | .filter((c) => c.average != null) | 588 | .filter((c) => c.average != null) |
| 542 | - .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })), | 589 | + .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: formatDecimal(c.average!, locale()) })), |
| 543 | ); | 590 | ); |
| 544 | 591 | ||
| 545 | // Weekly activity split — student attendance breakdown (events + sessions). | 592 | // Weekly activity split — student attendance breakdown (events + sessions). |
| @@ -589,11 +636,11 @@ function DashboardContent() { | |||
| 589 | .reduce((sum, entry) => sum + entry.value, 0); | 636 | .reduce((sum, entry) => sum + entry.value, 0); |
| 590 | }); | 637 | }); |
| 591 | 638 | ||
| 592 | - const deadlines = createMemo<DeadlineRow[]>(() => { | 639 | + const rawDeadlines = createMemo<DeadlineRow[]>(() => { |
| 593 | const items: DeadlineRow[] = []; | 640 | const items: DeadlineRow[] = []; |
| 594 | for (const exam of exams()?.items ?? []) { | 641 | for (const exam of exams()?.items ?? []) { |
| 595 | const status = scheduleStatus(exam.starts_at, exam.ends_at, now()); | 642 | const status = scheduleStatus(exam.starts_at, exam.ends_at, now()); |
| 596 | - if (status) items.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at!, status }); | 643 | + if (status) items.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at!, status, instance: exam.class_course }); |
| 597 | } | 644 | } |
| 598 | for (const event of events()?.items ?? []) { | 645 | for (const event of events()?.items ?? []) { |
| 599 | const status = scheduleStatus(event.starts_at, event.ends_at, now()); | 646 | const status = scheduleStatus(event.starts_at, event.ends_at, now()); |
| @@ -601,7 +648,7 @@ function DashboardContent() { | |||
| 601 | } | 648 | } |
| 602 | for (const hw of homework()?.items ?? []) { | 649 | for (const hw of homework()?.items ?? []) { |
| 603 | const status = scheduleStatus(hw.due_at, hw.due_at, now()); | 650 | const status = scheduleStatus(hw.due_at, hw.due_at, now()); |
| 604 | - if (status) items.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, status }); | 651 | + if (status) items.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, status, instance: hw.class_course }); |
| 605 | } | 652 | } |
| 606 | for (const appointment of appointments()?.items ?? []) { | 653 | for (const appointment of appointments()?.items ?? []) { |
| 607 | if (appointment.starts_at == null || !["pending", "approved"].includes(appointment.status)) continue; | 654 | if (appointment.starts_at == null || !["pending", "approved"].includes(appointment.status)) continue; |
| @@ -622,6 +669,19 @@ function DashboardContent() { | |||
| 622 | } | 669 | } |
| 623 | return items.sort((a, b) => a.at - b.at); | 670 | return items.sort((a, b) => a.at - b.at); |
| 624 | }); | 671 | }); |
| 672 | + // One ders taught in two şubeler gives two rows with the same title, so a | ||
| 673 | + // row names "<ders> — <şube>" under its title. | ||
| 674 | + // The label is folded into the row (a new array) rather than read in the | ||
| 675 | + // cell: the table caches cells by data identity and would not repaint. | ||
| 676 | + const deadlineSections = createInstanceLabels( | ||
| 677 | + () => rawDeadlines().flatMap((row) => (row.instance ? [row.instance] : [])), | ||
| 678 | + role, | ||
| 679 | + ); | ||
| 680 | + const deadlines = createMemo<DeadlineRow[]>(() => { | ||
| 681 | + const labels = deadlineSections(); | ||
| 682 | + return rawDeadlines().map((row) => (row.instance && labels[row.instance] ? { ...row, section: labels[row.instance].label } : row)); | ||
| 683 | + }); | ||
| 684 | + const deadlineSection = (row: DeadlineRow) => row.section; | ||
| 625 | 685 | ||
| 626 | const headerClass = "text-xs font-medium text-muted-foreground"; | 686 | const headerClass = "text-xs font-medium text-muted-foreground"; |
| 627 | const deadlineColumns = createMemo<ColumnDef<DeadlineRow>[]>(() => [ | 687 | const deadlineColumns = createMemo<ColumnDef<DeadlineRow>[]>(() => [ |
| @@ -630,7 +690,14 @@ function DashboardContent() { | |||
| 630 | header: t("dashboard.col.task"), | 690 | header: t("dashboard.col.task"), |
| 631 | enableSorting: false, | 691 | enableSorting: false, |
| 632 | meta: { headerClass }, | 692 | meta: { headerClass }, |
| 633 | - cell: (info) => <span class="block truncate font-medium">{info.row.original.title}</span>, | 693 | + cell: (info) => ( |
| 694 | + <div class="min-w-0"> | ||
| 695 | + <span class="block truncate font-medium">{info.row.original.title}</span> | ||
| 696 | + <Show when={deadlineSection(info.row.original)}> | ||
| 697 | + {(section) => <span class="block truncate text-xs text-text-subtle">{section()}</span>} | ||
| 698 | + </Show> | ||
| 699 | + </div> | ||
| 700 | + ), | ||
| 634 | }, | 701 | }, |
| 635 | { | 702 | { |
| 636 | accessorKey: "kind", | 703 | accessorKey: "kind", |
| @@ -663,7 +730,7 @@ function DashboardContent() { | |||
| 663 | }, | 730 | }, |
| 664 | ]); | 731 | ]); |
| 665 | 732 | ||
| 666 | - const deadlineSearch = (row: DeadlineRow, q: string) => matchesSearch(q, row.title); | 733 | + const deadlineSearch = (row: DeadlineRow, q: string) => matchesSearch(q, row.title, deadlineSection(row)); |
| 667 | const openDeadline = (row: DeadlineRow) => { | 734 | const openDeadline = (row: DeadlineRow) => { |
| 668 | switch (row.kind) { | 735 | switch (row.kind) { |
| 669 | case "exam": | 736 | case "exam": |
src/pages/event-detail-page.tsxmodified+2 -1
| @@ -40,6 +40,7 @@ import { formatDateTime } from "@/lib/format"; | |||
| 40 | import { personId, personLabel } from "@/lib/person"; | 40 | import { personId, personLabel } from "@/lib/person"; |
| 41 | import { matchesSearch } from "@/lib/search-text"; | 41 | import { matchesSearch } from "@/lib/search-text"; |
| 42 | import { hasMinRole } from "@/lib/roles"; | 42 | import { hasMinRole } from "@/lib/roles"; |
| 43 | +import { createUrlString } from "@/lib/url-state"; | ||
| 43 | import { useAuth } from "@/stores/auth-context"; | 44 | import { useAuth } from "@/stores/auth-context"; |
| 44 | import { usePreferences, useT } from "@/stores/preferences-context"; | 45 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 45 | 46 | ||
| @@ -77,7 +78,7 @@ function EventDetailContent() { | |||
| 77 | const [deleteOpen, setDeleteOpen] = createSignal(false); | 78 | const [deleteOpen, setDeleteOpen] = createSignal(false); |
| 78 | const [registrationTarget, setRegistrationTarget] = createSignal<string | null>(null); | 79 | const [registrationTarget, setRegistrationTarget] = createSignal<string | null>(null); |
| 79 | const [rosterSearch, setRosterSearch] = createSignal(""); | 80 | const [rosterSearch, setRosterSearch] = createSignal(""); |
| 80 | - const [eventTab, setEventTab] = createSignal("studentAttendance"); | 81 | + const [eventTab, setEventTab] = createUrlString("tab", "studentAttendance"); |
| 81 | const [error, setError] = createSignal(""); | 82 | const [error, setError] = createSignal(""); |
| 82 | const [pending, setPending] = createSignal(false); | 83 | const [pending, setPending] = createSignal(false); |
| 83 | 84 | ||
src/pages/events-page.tsxmodified+29 -8
| @@ -18,6 +18,7 @@ import { SidePanel } from "@/components/ui/side-panel"; | |||
| 18 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 18 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 19 | import { TruncationNotice } from "@/components/ui/truncation-notice"; | 19 | import { TruncationNotice } from "@/components/ui/truncation-notice"; |
| 20 | import { cn } from "@/lib/cn"; | 20 | import { cn } from "@/lib/cn"; |
| 21 | +import { createUrlEnum } from "@/lib/url-state"; | ||
| 21 | import { createNow } from "@/lib/create-now"; | 22 | import { createNow } from "@/lib/create-now"; |
| 22 | import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; | 23 | import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; |
| 23 | import { createFlash } from "@/lib/flash"; | 24 | import { createFlash } from "@/lib/flash"; |
| @@ -52,18 +53,34 @@ function EventsContent() { | |||
| 52 | setShowForm(true); | 53 | setShowForm(true); |
| 53 | } | 54 | } |
| 54 | }); | 55 | }); |
| 55 | - const [timeFilter, setTimeFilter] = createSignal("all"); | 56 | + const [timeFilter, setTimeFilter] = createUrlEnum("when", ["all", "upcoming", "past"] as const, "all"); |
| 56 | const now = createNow(); | 57 | const now = createNow(); |
| 57 | const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); | 58 | const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); |
| 58 | 59 | ||
| 59 | const filterEvents = (items: Event[]) => { | 60 | const filterEvents = (items: Event[]) => { |
| 60 | const scope = timeFilter(); | 61 | const scope = timeFilter(); |
| 61 | const nowMs = now(); | 62 | const nowMs = now(); |
| 62 | - return items.filter((event) => { | 63 | + const isPast = (event: Event) => event.ends_at != null && event.ends_at < nowMs; |
| 63 | - if (scope === "upcoming" && event.ends_at != null && event.ends_at < nowMs) return false; | 64 | + const at = (event: Event) => event.starts_at ?? event.ends_at ?? null; |
| 64 | - if (scope === "past" && (event.ends_at == null || event.ends_at >= nowMs)) return false; | 65 | + // Default order, before any header sort: what is still ahead comes first, |
| 65 | - return true; | 66 | + // soonest first; what is over follows, most recent first. The API lists |
| 66 | - }); | 67 | + // newest first, which put a far-off event above next week's. |
| 68 | + const byDefault = (a: Event, b: Event) => { | ||
| 69 | + const pastA = isPast(a); | ||
| 70 | + const pastB = isPast(b); | ||
| 71 | + if (pastA !== pastB) return pastA ? 1 : -1; | ||
| 72 | + const atA = at(a); | ||
| 73 | + const atB = at(b); | ||
| 74 | + if (atA == null || atB == null) return atA == null ? (atB == null ? 0 : 1) : -1; | ||
| 75 | + return pastA ? atB - atA : atA - atB; | ||
| 76 | + }; | ||
| 77 | + return items | ||
| 78 | + .filter((event) => { | ||
| 79 | + if (scope === "upcoming" && isPast(event)) return false; | ||
| 80 | + if (scope === "past" && !isPast(event)) return false; | ||
| 81 | + return true; | ||
| 82 | + }) | ||
| 83 | + .sort(byDefault); | ||
| 67 | }; | 84 | }; |
| 68 | 85 | ||
| 69 | const [loadAll, setLoadAll] = createSignal(false); | 86 | const [loadAll, setLoadAll] = createSignal(false); |
| @@ -71,7 +88,7 @@ function EventsContent() { | |||
| 71 | () => (loadAll() ? "all" : "capped"), | 88 | () => (loadAll() ? "all" : "capped"), |
| 72 | (scope) => loadCappedList(getEvents, LIST_CAP, scope === "all"), | 89 | (scope) => loadCappedList(getEvents, LIST_CAP, scope === "all"), |
| 73 | ); | 90 | ); |
| 74 | - const rows = () => filterEvents(list()?.items ?? []); | 91 | + const rows = createMemo(() => filterEvents(list()?.items ?? [])); |
| 75 | const eventStatus = (event: Event) => { | 92 | const eventStatus = (event: Event) => { |
| 76 | const nowMs = now(); | 93 | const nowMs = now(); |
| 77 | if (event.ends_at != null && event.ends_at < nowMs) return "past"; | 94 | if (event.ends_at != null && event.ends_at < nowMs) return "past"; |
| @@ -214,6 +231,7 @@ function EventsContent() { | |||
| 214 | onLoadAll={() => setLoadAll(true)} | 231 | onLoadAll={() => setLoadAll(true)} |
| 215 | /> | 232 | /> |
| 216 | <DataTable | 233 | <DataTable |
| 234 | + urlState | ||
| 217 | title={t("events.title")} | 235 | title={t("events.title")} |
| 218 | description={t("events.subtitle")} | 236 | description={t("events.subtitle")} |
| 219 | actions={ | 237 | actions={ |
| @@ -232,13 +250,16 @@ function EventsContent() { | |||
| 232 | enablePagination | 250 | enablePagination |
| 233 | pageSize={EVENT_PAGE_SIZE} | 251 | pageSize={EVENT_PAGE_SIZE} |
| 234 | empty={t("events.empty")} | 252 | empty={t("events.empty")} |
| 253 | + pageResetKey={timeFilter()} | ||
| 254 | + filtersActive={timeFilter() !== "all"} | ||
| 255 | + onClearFilters={() => setTimeFilter("all")} | ||
| 235 | storageKey="events" | 256 | storageKey="events" |
| 236 | onRowClick={(event) => void navigate({ to: "/events/$id", params: { id: event.id } })} | 257 | onRowClick={(event) => void navigate({ to: "/events/$id", params: { id: event.id } })} |
| 237 | filters={ | 258 | filters={ |
| 238 | <DropdownSelect | 259 | <DropdownSelect |
| 239 | labelPrefix={t("attempt.status")} | 260 | labelPrefix={t("attempt.status")} |
| 240 | value={timeFilter()} | 261 | value={timeFilter()} |
| 241 | - onChange={(val) => setTimeFilter(val)} | 262 | + onChange={(val) => setTimeFilter(val === "upcoming" || val === "past" ? val : "all")} |
| 242 | options={[ | 263 | options={[ |
| 243 | { value: "all", label: t("common.all") }, | 264 | { value: "all", label: t("common.all") }, |
| 244 | { value: "upcoming", label: t("events.upcoming") }, | 265 | { value: "upcoming", label: t("events.upcoming") }, |
src/pages/exam-detail-page.tsxmodified+11 -8
| @@ -39,6 +39,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | |||
| 39 | import { SidePanel } from "@/components/ui/side-panel"; | 39 | import { SidePanel } from "@/components/ui/side-panel"; |
| 40 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 40 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 41 | import { hasMinRole } from "@/lib/roles"; | 41 | import { hasMinRole } from "@/lib/roles"; |
| 42 | +import { createUrlString } from "@/lib/url-state"; | ||
| 42 | import { createNow } from "@/lib/create-now"; | 43 | import { createNow } from "@/lib/create-now"; |
| 43 | import { examKindLabel } from "@/lib/exam-labels"; | 44 | import { examKindLabel } from "@/lib/exam-labels"; |
| 44 | import { examDisplayStatus, examStatusMessageKey, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status"; | 45 | import { examDisplayStatus, examStatusMessageKey, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status"; |
| @@ -123,7 +124,9 @@ function ExamDetailContent() { | |||
| 123 | const [answerMark, setAnswerMark] = createSignal("0"); | 124 | const [answerMark, setAnswerMark] = createSignal("0"); |
| 124 | const [answerError, setAnswerError] = createSignal(""); | 125 | const [answerError, setAnswerError] = createSignal(""); |
| 125 | const [answerPending, setAnswerPending] = createSignal(false); | 126 | const [answerPending, setAnswerPending] = createSignal(false); |
| 126 | - const [examTab, setExamTab] = createSignal("questions"); | 127 | + // `?tab=` when the user picked one, so Back from an answer sheet or a |
| 128 | + // student lands on the same tab; otherwise the exam's own default below. | ||
| 129 | + const [pickedTab, setExamTab] = createUrlString("tab"); | ||
| 127 | const isSittable = () => { | 130 | const isSittable = () => { |
| 128 | const e = exam(); | 131 | const e = exam(); |
| 129 | return e ? isSittableExam(e) : false; | 132 | return e ? isSittableExam(e) : false; |
| @@ -210,13 +213,13 @@ function ExamDetailContent() { | |||
| 210 | }; | 213 | }; |
| 211 | const isFinished = () => examStatus().finished; | 214 | const isFinished = () => examStatus().finished; |
| 212 | const isUpcoming = () => examStatus().upcoming; | 215 | const isUpcoming = () => examStatus().upcoming; |
| 213 | - let defaultTabExamId = ""; | 216 | + // A finished exam opens on its results, any other on its questions. Fixed |
| 214 | - createEffect(() => { | 217 | + // per exam when it loads, so the clock passing ends_at does not switch tabs. |
| 218 | + const defaultTab = createMemo(on(() => exam()?.id, () => { | ||
| 215 | const current = exam(); | 219 | const current = exam(); |
| 216 | - if (!current || current.id === defaultTabExamId) return; | 220 | + return current && current.ends_at != null && current.ends_at < now() ? "results" : "questions"; |
| 217 | - defaultTabExamId = current.id; | 221 | + })); |
| 218 | - setExamTab(current.ends_at != null && current.ends_at < now() ? "results" : "questions"); | 222 | + const examTab = () => pickedTab() || defaultTab(); |
| 219 | - }); | ||
| 220 | const ownAttemptSummary = (): ExamAttemptSummary | null => { | 223 | const ownAttemptSummary = (): ExamAttemptSummary | null => { |
| 221 | const attempt = ownAttempt(); | 224 | const attempt = ownAttempt(); |
| 222 | return attempt ? { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } : null; | 225 | return attempt ? { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } : null; |
| @@ -399,7 +402,7 @@ function ExamDetailContent() { | |||
| 399 | <Breadcrumbs items={[{ label: t("exams.title"), to: "/exams" }, { label: ex().title }]} /> | 402 | <Breadcrumbs items={[{ label: t("exams.title"), to: "/exams" }, { label: ex().title }]} /> |
| 400 | <PageHeader | 403 | <PageHeader |
| 401 | title={ex().title} | 404 | title={ex().title} |
| 402 | - description={ex().description || "—"} | 405 | + description={ex().description || undefined} |
| 403 | actions={ | 406 | actions={ |
| 404 | <div class="flex flex-wrap items-center gap-2"> | 407 | <div class="flex flex-wrap items-center gap-2"> |
| 405 | <Show when={isStudent() && !isDraft() && isSittable()}> | 408 | <Show when={isStudent() && !isDraft() && isSittable()}> |
src/pages/exams-page.tsxmodified+35 -16
| @@ -34,6 +34,7 @@ import { hasMinRole } from "@/lib/roles"; | |||
| 34 | import { matchesSearch } from "@/lib/search-text"; | 34 | import { matchesSearch } from "@/lib/search-text"; |
| 35 | import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status"; | 35 | import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status"; |
| 36 | import { cn } from "@/lib/cn"; | 36 | import { cn } from "@/lib/cn"; |
| 37 | +import { createUrlEnum, createUrlString } from "@/lib/url-state"; | ||
| 37 | import { useAuth } from "@/stores/auth-context"; | 38 | import { useAuth } from "@/stores/auth-context"; |
| 38 | import { usePreferences, useT } from "@/stores/preferences-context"; | 39 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 39 | 40 | ||
| @@ -62,9 +63,24 @@ function ExamsContent() { | |||
| 62 | if (status === "upcoming" || status === "active" || status === "unscheduled") return "upcoming"; | 63 | if (status === "upcoming" || status === "active" || status === "unscheduled") return "upcoming"; |
| 63 | return "completed"; | 64 | return "completed"; |
| 64 | }; | 65 | }; |
| 65 | - const [tab, setTab] = createSignal<ExamTab>("all"); | 66 | + // Tab and filters live in the URL beside the table's own search/page/sort, |
| 66 | - const [courseFilter, setCourseFilter] = createSignal("all"); | 67 | + // so Back from an exam lands on the same slice of the list. |
| 67 | - const [kindFilter, setKindFilter] = createSignal("all"); | 68 | + const [tab, setTab] = createUrlEnum<ExamTab>("tab", ["all", "upcoming", "completed", "draft"], "all"); |
| 69 | + const [courseFilter, setCourseFilter] = createUrlString("course", "all"); | ||
| 70 | + const [kindFilter, setKindFilter] = createUrlString("kind", "all"); | ||
| 71 | + const filtersActive = () => courseFilter() !== "all" || kindFilter() !== "all"; | ||
| 72 | + const clearFilters = () => { | ||
| 73 | + setCourseFilter("all"); | ||
| 74 | + setKindFilter("all"); | ||
| 75 | + }; | ||
| 76 | + const emptyMessage = () => | ||
| 77 | + tab() === "upcoming" | ||
| 78 | + ? t("exams.emptyUpcoming") | ||
| 79 | + : tab() === "completed" | ||
| 80 | + ? t("exams.emptyCompleted") | ||
| 81 | + : tab() === "draft" | ||
| 82 | + ? t("exams.emptyDraft") | ||
| 83 | + : t("exams.empty"); | ||
| 68 | const [createOpen, setCreateOpen] = createSignal(location().searchStr.includes("action=new")); | 84 | const [createOpen, setCreateOpen] = createSignal(location().searchStr.includes("action=new")); |
| 69 | createEffect(() => { | 85 | createEffect(() => { |
| 70 | if (location().searchStr.includes("action=new")) { | 86 | if (location().searchStr.includes("action=new")) { |
| @@ -172,13 +188,15 @@ function ExamsContent() { | |||
| 172 | const statusLabel = (status: ExamDisplayStatus) => { | 188 | const statusLabel = (status: ExamDisplayStatus) => { |
| 173 | return t(examStatusMessageKey(status)); | 189 | return t(examStatusMessageKey(status)); |
| 174 | }; | 190 | }; |
| 175 | - const rows = (): ExamRow[] => filterExams(list()?.items ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) })); | 191 | + // A memo, not a function: the table must see one array per change, not a |
| 192 | + // fresh one on every read. | ||
| 193 | + const rows = createMemo((): ExamRow[] => filterExams(list()?.items ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }))); | ||
| 176 | const columns = createMemo<ColumnDef<ExamRow>[]>(() => [ | 194 | const columns = createMemo<ColumnDef<ExamRow>[]>(() => [ |
| 177 | { | 195 | { |
| 178 | accessorKey: "title", | 196 | accessorKey: "title", |
| 179 | header: t("exams.title"), | 197 | header: t("exams.title"), |
| 180 | size: 220, | 198 | size: 220, |
| 181 | - minSize: 180, | 199 | + minSize: 160, |
| 182 | cell: (cell) => ( | 200 | cell: (cell) => ( |
| 183 | <div class="min-w-0"> | 201 | <div class="min-w-0"> |
| 184 | <p class="truncate font-medium">{cell.row.original.title}</p> | 202 | <p class="truncate font-medium">{cell.row.original.title}</p> |
| @@ -206,13 +224,14 @@ function ExamsContent() { | |||
| 206 | id: "status", | 224 | id: "status", |
| 207 | accessorFn: (exam) => statusLabel(exam.displayStatus), | 225 | accessorFn: (exam) => statusLabel(exam.displayStatus), |
| 208 | header: t("attempt.status"), | 226 | header: t("attempt.status"), |
| 209 | - size: 130, | 227 | + // The pill is min-w-24 plus cell padding: narrower clips it. |
| 210 | - minSize: 110, | 228 | + size: 140, |
| 229 | + minSize: 120, | ||
| 211 | meta: { headerClass: "text-center", cellClass: "text-center" }, | 230 | meta: { headerClass: "text-center", cellClass: "text-center" }, |
| 212 | cell: (cell) => { | 231 | cell: (cell) => { |
| 213 | const status = cell.row.original.displayStatus; | 232 | const status = cell.row.original.displayStatus; |
| 214 | return ( | 233 | return ( |
| 215 | - <Badge variant="outline" class={cn("min-w-28 justify-center whitespace-nowrap", scheduleStatusClass(examStatusTone(status)))}> | 234 | + <Badge variant="outline" class={cn("min-w-24 max-w-full justify-center whitespace-nowrap", scheduleStatusClass(examStatusTone(status)))}> |
| 216 | <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(examStatusTone(status)))} /> | 235 | <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(examStatusTone(status)))} /> |
| 217 | {statusLabel(status)} | 236 | {statusLabel(status)} |
| 218 | </Badge> | 237 | </Badge> |
| @@ -339,13 +358,16 @@ function ExamsContent() { | |||
| 339 | } | 358 | } |
| 340 | columns={columns()} | 359 | columns={columns()} |
| 341 | data={rows()} | 360 | data={rows()} |
| 342 | - tableClass="table-fixed min-w-[46rem]" | ||
| 343 | filterPlaceholder={t("exams.searchPlaceholder")} | 361 | filterPlaceholder={t("exams.searchPlaceholder")} |
| 344 | filterHint={t("search.hint.exams")} | 362 | filterHint={t("search.hint.exams")} |
| 345 | searchPredicate={searchExam} | 363 | searchPredicate={searchExam} |
| 346 | enablePagination | 364 | enablePagination |
| 347 | pageSize={EXAM_PAGE_SIZE} | 365 | pageSize={EXAM_PAGE_SIZE} |
| 348 | - empty={t("exams.empty")} | 366 | + empty={emptyMessage()} |
| 367 | + urlState | ||
| 368 | + pageResetKey={`${tab()}|${courseFilter()}|${kindFilter()}`} | ||
| 369 | + filtersActive={filtersActive()} | ||
| 370 | + onClearFilters={clearFilters} | ||
| 349 | storageKey="exams" | 371 | storageKey="exams" |
| 350 | onRowClick={(exam) => void navigate({ to: "/exams/$id", params: { id: exam.id } })} | 372 | onRowClick={(exam) => void navigate({ to: "/exams/$id", params: { id: exam.id } })} |
| 351 | filters={ | 373 | filters={ |
| @@ -370,16 +392,13 @@ function ExamsContent() { | |||
| 370 | ]} | 392 | ]} |
| 371 | /> | 393 | /> |
| 372 | 394 | ||
| 373 | - <Show when={courseFilter() !== "all" || kindFilter() !== "all"}> | 395 | + <Show when={filtersActive()}> |
| 374 | <Button | 396 | <Button |
| 375 | type="button" | 397 | type="button" |
| 376 | variant="ghost" | 398 | variant="ghost" |
| 377 | size="sm" | 399 | size="sm" |
| 378 | class="h-8 rounded-lg px-3 text-[13px] font-medium text-muted-foreground hover:text-foreground" | 400 | class="h-8 rounded-lg px-3 text-[13px] font-medium text-muted-foreground hover:text-foreground" |
| 379 | - onClick={() => { | 401 | + onClick={clearFilters} |
| 380 | - setCourseFilter("all"); | ||
| 381 | - setKindFilter("all"); | ||
| 382 | - }} | ||
| 383 | > | 402 | > |
| 384 | <IconRotateCcw class="h-3.5 w-3.5 mr-1" /> | 403 | <IconRotateCcw class="h-3.5 w-3.5 mr-1" /> |
| 385 | {t("common.resetFilters")} | 404 | {t("common.resetFilters")} |
| @@ -406,7 +425,7 @@ function ExamsContent() { | |||
| 406 | } | 425 | } |
| 407 | }} | 426 | }} |
| 408 | title={createdExam() ? createdExam()!.title : t("exams.create")} | 427 | title={createdExam() ? createdExam()!.title : t("exams.create")} |
| 409 | - description={createdExam() ? t("exams.step2Questions") : t("exams.subtitle")} | 428 | + description={createdExam() ? t("exams.step2Questions") : t("exams.createSubtitle")} |
| 410 | size={createStep() === "questions" ? "wide" : "default"} | 429 | size={createStep() === "questions" ? "wide" : "default"} |
| 411 | > | 430 | > |
| 412 | <div class="mb-4 flex rounded-md border border-border-line bg-surface-overlay p-1"> | 431 | <div class="mb-4 flex rounded-md border border-border-line bg-surface-overlay p-1"> |
src/pages/homework-detail-page.tsxmodified+21 -6
| @@ -16,6 +16,7 @@ import { Badge } from "@/components/ui/badge"; | |||
| 16 | import { PageSpinner } from "@/components/ui/page-spinner"; | 16 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 17 | import { formatDateTime } from "@/lib/format"; | 17 | import { formatDateTime } from "@/lib/format"; |
| 18 | import { hasMinRole } from "@/lib/roles"; | 18 | import { hasMinRole } from "@/lib/roles"; |
| 19 | +import { loadInstanceLabel } from "@/lib/instance-labels"; | ||
| 19 | import { useAuth } from "@/stores/auth-context"; | 20 | import { useAuth } from "@/stores/auth-context"; |
| 20 | import { usePreferences, useT } from "@/stores/preferences-context"; | 21 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 21 | 22 | ||
| @@ -33,7 +34,19 @@ export default function HomeworkDetailPage() { | |||
| 33 | // further, and it is what names the work on screen. | 34 | // further, and it is what names the work on screen. |
| 34 | const [instance] = createResource(() => homework()?.class_course ?? null, (instanceId) => getInstanceById(instanceId)); | 35 | const [instance] = createResource(() => homework()?.class_course ?? null, (instanceId) => getInstanceById(instanceId)); |
| 35 | const [course] = createResource(() => instance()?.course ?? null, (courseId) => getCourseById(courseId)); | 36 | const [course] = createResource(() => instance()?.course ?? null, (courseId) => getCourseById(courseId)); |
| 37 | + // "<ders> — <şube>": the same ders runs in several şubeler, and their | ||
| 38 | + // homework shares titles, so the header names the şube too. | ||
| 39 | + const [sectionLabel] = createResource( | ||
| 40 | + () => homework()?.class_course ?? null, | ||
| 41 | + async (instanceId) => (await loadInstanceLabel(instanceId, auth.user()?.role))?.label ?? null, | ||
| 42 | + ); | ||
| 36 | const [subject] = createResource(() => homework()?.subject ?? null, async (subjectId) => subjectId ? getSubjectById(subjectId) : null); | 43 | const [subject] = createResource(() => homework()?.subject ?? null, async (subjectId) => subjectId ? getSubjectById(subjectId) : null); |
| 44 | + // A subject named exactly like its course ("Matematik / Matematik") adds | ||
| 45 | + // nothing next to the course tile, so that tile is left out. | ||
| 46 | + const showSubject = () => { | ||
| 47 | + const name = subject()?.name?.trim(); | ||
| 48 | + return !!name && name.toLocaleLowerCase() !== course()?.title?.trim().toLocaleLowerCase(); | ||
| 49 | + }; | ||
| 37 | const canManage = () => { | 50 | const canManage = () => { |
| 38 | const user = auth.user(); | 51 | const user = auth.user(); |
| 39 | const item = homework(); | 52 | const item = homework(); |
| @@ -55,15 +68,17 @@ export default function HomeworkDetailPage() { | |||
| 55 | <Breadcrumbs items={[{ label: t("homework.title"), to: "/homework" }, { label: item().title }]} /> | 68 | <Breadcrumbs items={[{ label: t("homework.title"), to: "/homework" }, { label: item().title }]} /> |
| 56 | <PageHeader title={item().title} description={item().description || undefined} /> | 69 | <PageHeader title={item().title} description={item().description || undefined} /> |
| 57 | </section> | 70 | </section> |
| 58 | - <section class="data-shell grid gap-3 p-4 text-sm sm:grid-cols-2 sm:p-5 lg:grid-cols-4"> | 71 | + <section class={`data-shell grid gap-3 p-4 text-sm sm:grid-cols-2 sm:p-5 ${showSubject() ? "lg:grid-cols-4" : "lg:grid-cols-3"}`}> |
| 59 | <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> | 72 | <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> |
| 60 | <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("nav.courses")}</p> | 73 | <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("nav.courses")}</p> |
| 61 | - <p class="mt-1 font-medium text-text-default">{course()?.title ?? item().class_course}</p> | 74 | + <p class="mt-1 font-medium text-text-default">{sectionLabel.latest ?? course()?.title ?? "—"}</p> |
| 62 | - </div> | ||
| 63 | - <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> | ||
| 64 | - <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("subjects.subject")}</p> | ||
| 65 | - <p class="mt-1 font-medium text-text-default">{subject()?.name ?? item().subject}</p> | ||
| 66 | </div> | 75 | </div> |
| 76 | + <Show when={showSubject()}> | ||
| 77 | + <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> | ||
| 78 | + <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("subjects.subject")}</p> | ||
| 79 | + <p class="mt-1 font-medium text-text-default">{subject()?.name}</p> | ||
| 80 | + </div> | ||
| 81 | + </Show> | ||
| 67 | <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> | 82 | <div class="rounded-xl border border-border-hairline bg-surface-tint px-4 py-4"> |
| 68 | <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("homework.dueAt")}</p> | 83 | <p class="text-xs font-medium uppercase tracking-[0.08em] text-text-subtle">{t("homework.dueAt")}</p> |
| 69 | <p class="mt-1 font-medium text-text-default">{formatDateTime(item().due_at, locale())}</p> | 84 | <p class="mt-1 font-medium text-text-default">{formatDateTime(item().due_at, locale())}</p> |
src/pages/homework-page.tsxmodified+10 -17
| @@ -2,9 +2,10 @@ import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js | |||
| 2 | import { createResource } from "@/lib/create-resource"; | 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { useLocation, useNavigate } from "@tanstack/solid-router"; | 3 | import { useLocation, useNavigate } from "@tanstack/solid-router"; |
| 4 | import type { ColumnDef } from "@tanstack/solid-table"; | 4 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 5 | -import { getCourseById, getCourseSubjects } from "@/api/courses"; | 5 | +import { getCourseSubjects } from "@/api/courses"; |
| 6 | -import { getInstanceById, postInstanceHomework } from "@/api/instances"; | 6 | +import { postInstanceHomework } from "@/api/instances"; |
| 7 | import { loadInstanceOptions } from "@/lib/instance-options"; | 7 | import { loadInstanceOptions } from "@/lib/instance-options"; |
| 8 | +import { loadInstanceLabels } from "@/lib/instance-labels"; | ||
| 8 | import { getHomework } from "@/api/homework"; | 9 | import { getHomework } from "@/api/homework"; |
| 9 | import { getTime } from "@/api/time"; | 10 | import { getTime } from "@/api/time"; |
| 10 | import { formatApiError } from "@/api/client"; | 11 | import { formatApiError } from "@/api/client"; |
| @@ -71,23 +72,14 @@ function HomeworkContent() { | |||
| 71 | const [dueTime, setDueTime] = createSignal(""); | 72 | const [dueTime, setDueTime] = createSignal(""); |
| 72 | const [error, setError] = createSignal(""); | 73 | const [error, setError] = createSignal(""); |
| 73 | const [pending, setPending] = createSignal(false); | 74 | const [pending, setPending] = createSignal(false); |
| 74 | - // Homework is filed against an instance (şube × ders), so a row's label is | 75 | + // Homework is filed against an instance (şube × ders): the same ders taught |
| 75 | - // the catalog course's title, resolved one hop through the instance. | 76 | + // in two şubeler yields rows with the same title, so a row's label names |
| 77 | + // both — "<ders> — <şube>", as the exams list does. | ||
| 76 | const [courseNames, setCourseNames] = createSignal<Record<string, string>>({}); | 78 | const [courseNames, setCourseNames] = createSignal<Record<string, string>>({}); |
| 77 | const [list, { refetch }] = createResource(async () => { | 79 | const [list, { refetch }] = createResource(async () => { |
| 78 | const items = (await getHomework({ limit: 100 })).items; | 80 | const items = (await getHomework({ limit: 100 })).items; |
| 79 | - const instanceIds = [...new Set(items.map((item) => item.class_course))]; | 81 | + const labels = await loadInstanceLabels(items.map((item) => item.class_course), auth.user()?.role); |
| 80 | - await Promise.all( | 82 | + setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label]))); |
| 81 | - instanceIds.map(async (instanceId) => { | ||
| 82 | - try { | ||
| 83 | - const instance = await getInstanceById(instanceId); | ||
| 84 | - const course = await getCourseById(instance.course); | ||
| 85 | - setCourseNames((current) => ({ ...current, [instanceId]: course.title })); | ||
| 86 | - } catch { | ||
| 87 | - // An unreadable section just keeps its id as the label. | ||
| 88 | - } | ||
| 89 | - }), | ||
| 90 | - ); | ||
| 91 | return items; | 83 | return items; |
| 92 | }); | 84 | }); |
| 93 | // The sections a teacher may assign work in, labelled "<ders> — <şube>". | 85 | // The sections a teacher may assign work in, labelled "<ders> — <şube>". |
| @@ -102,7 +94,7 @@ function HomeworkContent() { | |||
| 102 | async (courseId) => (courseId ? (await getCourseSubjects(courseId)).items : []), | 94 | async (courseId) => (courseId ? (await getCourseSubjects(courseId)).items : []), |
| 103 | ); | 95 | ); |
| 104 | const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); | 96 | const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); |
| 105 | - const courseName = (id: string) => courseNames()[id] ?? id; | 97 | + const courseName = (id: string) => courseNames()[id] ?? "—"; |
| 106 | const canCreate = () => manageableCourses().length > 0; | 98 | const canCreate = () => manageableCourses().length > 0; |
| 107 | const pageTitle = () => auth.user()?.role === "student" ? t("homework.mineTitle") : t("homework.title"); | 99 | const pageTitle = () => auth.user()?.role === "student" ? t("homework.mineTitle") : t("homework.title"); |
| 108 | type DueTab = "all" | "open" | "past"; | 100 | type DueTab = "all" | "open" | "past"; |
| @@ -265,6 +257,7 @@ function HomeworkContent() { | |||
| 265 | <Alert variant="destructive">{formatApiError(list.error)}</Alert> | 257 | <Alert variant="destructive">{formatApiError(list.error)}</Alert> |
| 266 | </Show> | 258 | </Show> |
| 267 | <DataTable | 259 | <DataTable |
| 260 | + urlState | ||
| 268 | columns={columns()} | 261 | columns={columns()} |
| 269 | data={dueFilteredList()} | 262 | data={dueFilteredList()} |
| 270 | tableClass="table-fixed min-w-[44rem]" | 263 | tableClass="table-fixed min-w-[44rem]" |
src/pages/instance-detail-page.tsxmodified+98 -26
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; | 1 | +import { Show, Suspense, createEffect, createMemo, createSignal, onCleanup } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; | 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { useLocation, useNavigate, useParams } from "@tanstack/solid-router"; | 3 | import { useLocation, useNavigate, useParams } from "@tanstack/solid-router"; |
| 4 | import type { ColumnDef } from "@tanstack/solid-table"; | 4 | import type { ColumnDef } from "@tanstack/solid-table"; |
| @@ -32,7 +32,7 @@ import { Button } from "@/components/ui/button"; | |||
| 32 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 32 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 33 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 33 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 34 | import { EmptyState } from "@/components/ui/empty-state"; | 34 | import { EmptyState } from "@/components/ui/empty-state"; |
| 35 | -import { IconCalendarDays, IconExam, IconHomework, IconPlus, IconSchool, IconTrash, IconUsers } from "@/components/ui/icons"; | 35 | +import { IconAlert, IconCalendarDays, IconExam, IconHomework, IconPlus, IconSchool, IconTrash, IconUsers } from "@/components/ui/icons"; |
| 36 | import { Input } from "@/components/ui/input"; | 36 | import { Input } from "@/components/ui/input"; |
| 37 | import { PageSpinner } from "@/components/ui/page-spinner"; | 37 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 38 | import { SidePanel } from "@/components/ui/side-panel"; | 38 | import { SidePanel } from "@/components/ui/side-panel"; |
| @@ -44,6 +44,7 @@ import { createFlash } from "@/lib/flash"; | |||
| 44 | import { examKindLabel } from "@/lib/exam-labels"; | 44 | import { examKindLabel } from "@/lib/exam-labels"; |
| 45 | import { examWeight } from "@/lib/exam-weight"; | 45 | import { examWeight } from "@/lib/exam-weight"; |
| 46 | import { hasMinRole } from "@/lib/roles"; | 46 | import { hasMinRole } from "@/lib/roles"; |
| 47 | +import { createUrlString } from "@/lib/url-state"; | ||
| 47 | import { useAuth } from "@/stores/auth-context"; | 48 | import { useAuth } from "@/stores/auth-context"; |
| 48 | import { useModules } from "@/stores/modules-context"; | 49 | import { useModules } from "@/stores/modules-context"; |
| 49 | import { useT } from "@/stores/preferences-context"; | 50 | import { useT } from "@/stores/preferences-context"; |
| @@ -70,9 +71,10 @@ function InstanceDetailContent() { | |||
| 70 | // `?tab=sessions&rollCall=<session id>` opens straight on a lesson's roll | 71 | // `?tab=sessions&rollCall=<session id>` opens straight on a lesson's roll |
| 71 | // call — the dashboard's "today's lessons" panel links here. | 72 | // call — the dashboard's "today's lessons" panel links here. |
| 72 | const linkedSearch = () => location().search as { tab?: unknown; rollCall?: unknown }; | 73 | const linkedSearch = () => location().search as { tab?: unknown; rollCall?: unknown }; |
| 73 | - const linkedTab = () => (typeof linkedSearch().tab === "string" ? (linkedSearch().tab as string) : null); | ||
| 74 | const linkedRollCall = () => (typeof linkedSearch().rollCall === "string" ? (linkedSearch().rollCall as string) : undefined); | 74 | const linkedRollCall = () => (typeof linkedSearch().rollCall === "string" ? (linkedSearch().rollCall as string) : undefined); |
| 75 | - const [tab, setTab] = createSignal(linkedTab() ?? "exams"); | 75 | + // The open tab is `?tab=` itself, so Back from an exam or a homework lands |
| 76 | + // on the tab it was opened from. | ||
| 77 | + const [requestedTab, setTab] = createUrlString("tab", "exams"); | ||
| 76 | // Exams, homework and sessions are separately sold modules; a tab for one the | 78 | // Exams, homework and sessions are separately sold modules; a tab for one the |
| 77 | // school switched off would only ever answer 403, so it is left out and the | 79 | // school switched off would only ever answer 403, so it is left out and the |
| 78 | // page falls back to the first tab still there. | 80 | // page falls back to the first tab still there. |
| @@ -82,7 +84,10 @@ function InstanceDetailContent() { | |||
| 82 | homework: () => modules.isEnabled("homework"), | 84 | homework: () => modules.isEnabled("homework"), |
| 83 | sessions: () => modules.isEnabled("sessions"), | 85 | sessions: () => modules.isEnabled("sessions"), |
| 84 | }; | 86 | }; |
| 85 | - createEffect(() => { | 87 | + // A tab that is not on offer (module off, no rights yet) shows the first |
| 88 | + // one that is, without rewriting the URL: rights settle after the instance | ||
| 89 | + // loads, and the requested tab must still be there when they do. | ||
| 90 | + const tab = () => { | ||
| 86 | const tabs = [ | 91 | const tabs = [ |
| 87 | ...(tabOn.exams() ? ["exams"] : []), | 92 | ...(tabOn.exams() ? ["exams"] : []), |
| 88 | ...(tabOn.homework() ? ["homework"] : []), | 93 | ...(tabOn.homework() ? ["homework"] : []), |
| @@ -90,8 +95,8 @@ function InstanceDetailContent() { | |||
| 90 | "teachers", | 95 | "teachers", |
| 91 | ...(canManage() ? ["students"] : []), | 96 | ...(canManage() ? ["students"] : []), |
| 92 | ]; | 97 | ]; |
| 93 | - if (!tabs.includes(tab())) setTab(tabs[0]); | 98 | + return tabs.includes(requestedTab()) ? requestedTab() : tabs[0]; |
| 94 | - }); | 99 | + }; |
| 95 | const [instance, { refetch: refetchInstance }] = createResource(id, (instanceId) => getInstanceById(instanceId)); | 100 | const [instance, { refetch: refetchInstance }] = createResource(id, (instanceId) => getInstanceById(instanceId)); |
| 96 | const [course] = createResource(() => instance()?.course ?? null, (courseId) => getCourseById(courseId)); | 101 | const [course] = createResource(() => instance()?.course ?? null, (courseId) => getCourseById(courseId)); |
| 97 | const [klass] = createResource(() => instance()?.class ?? null, (classId) => getClassById(classId).catch(() => null)); | 102 | const [klass] = createResource(() => instance()?.class ?? null, (classId) => getClassById(classId).catch(() => null)); |
| @@ -133,16 +138,31 @@ function InstanceDetailContent() { | |||
| 133 | const [flash, setFlash] = createFlash(); | 138 | const [flash, setFlash] = createFlash(); |
| 134 | 139 | ||
| 135 | // Policy edits are two inline writes on a shared resource, so they keep local | 140 | // Policy edits are two inline writes on a shared resource, so they keep local |
| 136 | - // signals and PATCH optimistically instead of refetching the instance. | 141 | + // signals and PATCH optimistically instead of refetching the instance. Both |
| 142 | + // write only on an explicit act — Enter or the save button for ders saati, a | ||
| 143 | + // confirmation for the karne switch — so a stray tap while scrolling on a | ||
| 144 | + // phone never changes the record. | ||
| 137 | const [countsTowardKarne, setCountsTowardKarne] = createSignal(true); | 145 | const [countsTowardKarne, setCountsTowardKarne] = createSignal(true); |
| 138 | const [dersSaati, setDersSaati] = createSignal(""); | 146 | const [dersSaati, setDersSaati] = createSignal(""); |
| 147 | + const [savedDersSaati, setSavedDersSaati] = createSignal<number | null>(null); | ||
| 139 | const [savingPolicy, setSavingPolicy] = createSignal(false); | 148 | const [savingPolicy, setSavingPolicy] = createSignal(false); |
| 149 | + const [karneConfirm, setKarneConfirm] = createSignal<boolean | null>(null); | ||
| 150 | + const [policySaved, setPolicySaved] = createSignal<"dersSaati" | "karne" | null>(null); | ||
| 151 | + let policySavedTimer: number | undefined; | ||
| 152 | + onCleanup(() => window.clearTimeout(policySavedTimer)); | ||
| 153 | + const flashPolicySaved = (which: "dersSaati" | "karne") => { | ||
| 154 | + setPolicySaved(which); | ||
| 155 | + window.clearTimeout(policySavedTimer); | ||
| 156 | + policySavedTimer = window.setTimeout(() => setPolicySaved(null), 2500); | ||
| 157 | + }; | ||
| 140 | createEffect(() => { | 158 | createEffect(() => { |
| 141 | const i = instance(); | 159 | const i = instance(); |
| 142 | if (!i) return; | 160 | if (!i) return; |
| 143 | setCountsTowardKarne(i.counts_toward_karne); | 161 | setCountsTowardKarne(i.counts_toward_karne); |
| 144 | setDersSaati(String(i.ders_saati)); | 162 | setDersSaati(String(i.ders_saati)); |
| 163 | + setSavedDersSaati(i.ders_saati); | ||
| 145 | }); | 164 | }); |
| 165 | + const dersSaatiDirty = () => dersSaati().trim() !== String(savedDersSaati() ?? ""); | ||
| 146 | 166 | ||
| 147 | const toggleKarne = async (next: boolean) => { | 167 | const toggleKarne = async (next: boolean) => { |
| 148 | if (savingPolicy()) return; | 168 | if (savingPolicy()) return; |
| @@ -150,6 +170,7 @@ function InstanceDetailContent() { | |||
| 150 | setSavingPolicy(true); | 170 | setSavingPolicy(true); |
| 151 | try { | 171 | try { |
| 152 | await patchInstanceById(id(), { counts_toward_karne: next }); | 172 | await patchInstanceById(id(), { counts_toward_karne: next }); |
| 173 | + flashPolicySaved("karne"); | ||
| 153 | } catch (err) { | 174 | } catch (err) { |
| 154 | setCountsTowardKarne(!next); | 175 | setCountsTowardKarne(!next); |
| 155 | setError(formatApiError(err)); | 176 | setError(formatApiError(err)); |
| @@ -159,18 +180,22 @@ function InstanceDetailContent() { | |||
| 159 | }; | 180 | }; |
| 160 | 181 | ||
| 161 | const saveDersSaati = async () => { | 182 | const saveDersSaati = async () => { |
| 183 | + if (savingPolicy()) return; | ||
| 162 | const value = Number(dersSaati().trim()); | 184 | const value = Number(dersSaati().trim()); |
| 163 | - const current = instance()?.ders_saati; | 185 | + const current = savedDersSaati(); |
| 164 | - if (!Number.isInteger(value) || value < 0 || value === current) { | 186 | + if (dersSaati().trim() === "" || !Number.isInteger(value) || value < 0) { |
| 165 | - setDersSaati(String(current ?? "")); | 187 | + setError(t("instances.dersSaatiInvalid")); |
| 166 | return; | 188 | return; |
| 167 | } | 189 | } |
| 190 | + if (value === current) return; | ||
| 191 | + setError(""); | ||
| 168 | setSavingPolicy(true); | 192 | setSavingPolicy(true); |
| 169 | try { | 193 | try { |
| 170 | await patchInstanceById(id(), { ders_saati: value }); | 194 | await patchInstanceById(id(), { ders_saati: value }); |
| 171 | - await refetchInstance(); | 195 | + setSavedDersSaati(value); |
| 196 | + setDersSaati(String(value)); | ||
| 197 | + flashPolicySaved("dersSaati"); | ||
| 172 | } catch (err) { | 198 | } catch (err) { |
| 173 | - setDersSaati(String(current ?? "")); | ||
| 174 | setError(formatApiError(err)); | 199 | setError(formatApiError(err)); |
| 175 | } finally { | 200 | } finally { |
| 176 | setSavingPolicy(false); | 201 | setSavingPolicy(false); |
| @@ -316,16 +341,38 @@ function InstanceDetailContent() { | |||
| 316 | when={canManage()} | 341 | when={canManage()} |
| 317 | fallback={<p class="truncate text-sm font-semibold text-text-default">{inst().ders_saati}</p>} | 342 | fallback={<p class="truncate text-sm font-semibold text-text-default">{inst().ders_saati}</p>} |
| 318 | > | 343 | > |
| 319 | - <Input | 344 | + <form |
| 320 | - aria-label={t("instances.dersSaati")} | 345 | + class="flex items-center gap-1.5" |
| 321 | - class="h-7 w-20 px-2 py-0 text-sm" | 346 | + onSubmit={(e) => { |
| 322 | - type="number" | 347 | + e.preventDefault(); |
| 323 | - min={0} | 348 | + void saveDersSaati(); |
| 324 | - value={dersSaati()} | 349 | + }} |
| 325 | - disabled={savingPolicy()} | 350 | + > |
| 326 | - onInput={(e) => setDersSaati(e.currentTarget.value)} | 351 | + <Input |
| 327 | - onBlur={() => void saveDersSaati()} | 352 | + aria-label={t("instances.dersSaati")} |
| 328 | - /> | 353 | + class="h-7 w-20 px-2 py-0 text-base sm:text-sm" |
| 354 | + type="number" | ||
| 355 | + inputMode="numeric" | ||
| 356 | + min={0} | ||
| 357 | + value={dersSaati()} | ||
| 358 | + disabled={savingPolicy()} | ||
| 359 | + onInput={(e) => setDersSaati(e.currentTarget.value)} | ||
| 360 | + onKeyDown={(e) => { | ||
| 361 | + if (e.key === "Escape" && dersSaatiDirty()) { | ||
| 362 | + e.preventDefault(); | ||
| 363 | + setDersSaati(String(savedDersSaati() ?? "")); | ||
| 364 | + } | ||
| 365 | + }} | ||
| 366 | + /> | ||
| 367 | + <Show when={dersSaatiDirty()}> | ||
| 368 | + <Button type="submit" size="sm" class="h-7 rounded-md px-2 text-xs" disabled={savingPolicy()}> | ||
| 369 | + {t("common.save")} | ||
| 370 | + </Button> | ||
| 371 | + </Show> | ||
| 372 | + <Show when={!dersSaatiDirty() && policySaved() === "dersSaati"}> | ||
| 373 | + <span class="text-xs text-success-text" role="status">{t("instances.policySaved")}</span> | ||
| 374 | + </Show> | ||
| 375 | + </form> | ||
| 329 | </Show> | 376 | </Show> |
| 330 | </div> | 377 | </div> |
| 331 | </div> | 378 | </div> |
| @@ -351,11 +398,20 @@ function InstanceDetailContent() { | |||
| 351 | checked={countsTowardKarne()} | 398 | checked={countsTowardKarne()} |
| 352 | disabled={savingPolicy()} | 399 | disabled={savingPolicy()} |
| 353 | aria-label={t("instances.countsTowardKarne")} | 400 | aria-label={t("instances.countsTowardKarne")} |
| 354 | - onChange={(event) => void toggleKarne(event.currentTarget.checked)} | 401 | + onChange={(event) => { |
| 402 | + // Keep the switch where it is until the change is confirmed. | ||
| 403 | + const next = event.currentTarget.checked; | ||
| 404 | + event.currentTarget.checked = !next; | ||
| 405 | + setKarneConfirm(next); | ||
| 406 | + }} | ||
| 355 | /> | 407 | /> |
| 356 | <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" /> | 408 | <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" /> |
| 357 | <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" /> | 409 | <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" /> |
| 358 | </span> | 410 | </span> |
| 411 | + <span class="font-semibold text-text-default">{countsTowardKarne() ? t("common.yes") : t("common.no")}</span> | ||
| 412 | + <Show when={policySaved() === "karne"}> | ||
| 413 | + <span class="text-success-text" role="status">{t("instances.policySaved")}</span> | ||
| 414 | + </Show> | ||
| 359 | </label> | 415 | </label> |
| 360 | </Show> | 416 | </Show> |
| 361 | </div> | 417 | </div> |
| @@ -383,12 +439,28 @@ function InstanceDetailContent() { | |||
| 383 | </div> | 439 | </div> |
| 384 | </div> | 440 | </div> |
| 385 | 441 | ||
| 442 | + <ConfirmDialog | ||
| 443 | + open={karneConfirm() !== null} | ||
| 444 | + onOpenChange={(open) => !open && setKarneConfirm(null)} | ||
| 445 | + title={t("instances.karneConfirmTitle")} | ||
| 446 | + description={karneConfirm() ? t("instances.karneOnHint") : t("instances.karneOffHint")} | ||
| 447 | + summary={`${course.latest?.title ?? ""} — ${klass.latest?.name ?? ""}`.replace(/^ — | — $/, "")} | ||
| 448 | + confirmLabel={karneConfirm() ? t("instances.karneTurnOn") : t("instances.karneTurnOff")} | ||
| 449 | + onConfirm={async () => { | ||
| 450 | + const next = karneConfirm(); | ||
| 451 | + if (next !== null) await toggleKarne(next); | ||
| 452 | + }} | ||
| 453 | + /> | ||
| 454 | + | ||
| 386 | <ConfirmDialog | 455 | <ConfirmDialog |
| 387 | open={removeTarget() !== null} | 456 | open={removeTarget() !== null} |
| 388 | onOpenChange={() => setRemoveTarget(null)} | 457 | onOpenChange={() => setRemoveTarget(null)} |
| 389 | - title={t("course.removeStudent")} | 458 | + title={t("course.removeStudentTitle")} |
| 459 | + description={t("course.removeStudentHint")} | ||
| 390 | variant="destructive" | 460 | variant="destructive" |
| 391 | - summary={`${t("course.removeStudentConfirm")} "${removeTarget()?.userName}"?`} | 461 | + icon={<IconAlert class="h-4 w-4" />} |
| 462 | + confirmLabel={t("course.removeStudentAction")} | ||
| 463 | + summary={removeTarget()?.userName ?? ""} | ||
| 392 | onConfirm={async () => { | 464 | onConfirm={async () => { |
| 393 | const target = removeTarget(); | 465 | const target = removeTarget(); |
| 394 | if (!target) return; | 466 | if (!target) return; |
src/pages/license-modules-page.tsxmodified+7 -13
| @@ -6,7 +6,7 @@ import { formatApiError } from "@/api/client"; | |||
| 6 | import { RouteGuard } from "@/components/layout/route-guard"; | 6 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 7 | import { Badge } from "@/components/ui/badge"; | 7 | import { Badge } from "@/components/ui/badge"; |
| 8 | import { Button } from "@/components/ui/button"; | 8 | import { Button } from "@/components/ui/button"; |
| 9 | -import { ComingSoonBadge, ComingSoonPanel, ComingSoonValue } from "@/components/ui/coming-soon"; | 9 | +import { ComingSoonBadge, ComingSoonPanel } from "@/components/ui/coming-soon"; |
| 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 11 | import { ErrorAlert } from "@/components/ui/error-alert"; | 11 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 12 | import { IconDownload, IconPackage, IconPlus } from "@/components/ui/icons"; | 12 | import { IconDownload, IconPackage, IconPlus } from "@/components/ui/icons"; |
| @@ -79,9 +79,9 @@ function LicenseModulesContent() { | |||
| 79 | </Badge> | 79 | </Badge> |
| 80 | ), | 80 | ), |
| 81 | }, | 81 | }, |
| 82 | - { id: "unitPrice", header: t("modules.unitPrice"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => <ComingSoonValue /> }, | 82 | + // Unit price, seats and annual amount have no licensing/billing endpoint |
| 83 | - { id: "seats", header: t("modules.activeSeats"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => <ComingSoonValue /> }, | 83 | + // behind them, so those design columns are left out rather than filled |
| 84 | - { id: "annual", header: t("modules.annualAmount"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => <ComingSoonValue /> }, | 84 | + // with "yakında". |
| 85 | ]); | 85 | ]); |
| 86 | 86 | ||
| 87 | return ( | 87 | return ( |
| @@ -100,7 +100,7 @@ function LicenseModulesContent() { | |||
| 100 | </TabsList> | 100 | </TabsList> |
| 101 | </Tabs> | 101 | </Tabs> |
| 102 | 102 | ||
| 103 | - <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}> | 103 | + <Suspense fallback={<DataTableSkeleton columns={2} rows={8} />}> |
| 104 | <Show when={data.error}> | 104 | <Show when={data.error}> |
| 105 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> | 105 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> |
| 106 | </Show> | 106 | </Show> |
| @@ -118,24 +118,18 @@ function LicenseModulesContent() { | |||
| 118 | </div> | 118 | </div> |
| 119 | <p class="text-sm text-text-subtle">{enabledPackages().join(" + ") || "—"}</p> | 119 | <p class="text-sm text-text-subtle">{enabledPackages().join(" + ") || "—"}</p> |
| 120 | </div> | 120 | </div> |
| 121 | - <div class="text-right"> | ||
| 122 | - <ComingSoonValue class="justify-end" /> | ||
| 123 | - <p class="mt-1 text-xs text-text-subtle">{t("modules.annualTotal")}</p> | ||
| 124 | - </div> | ||
| 125 | </div> | 121 | </div> |
| 126 | <div class="h-2 overflow-hidden rounded-full bg-surface-tint" role="progressbar" aria-valuemin={0} aria-valuemax={totalCount()} aria-valuenow={enabledCount()}> | 122 | <div class="h-2 overflow-hidden rounded-full bg-surface-tint" role="progressbar" aria-valuemin={0} aria-valuemax={totalCount()} aria-valuenow={enabledCount()}> |
| 127 | <div class="h-full rounded-full bg-primary" style={{ width: `${totalCount() ? (enabledCount() / totalCount()) * 100 : 0}%` }} /> | 123 | <div class="h-full rounded-full bg-primary" style={{ width: `${totalCount() ? (enabledCount() / totalCount()) * 100 : 0}%` }} /> |
| 128 | </div> | 124 | </div> |
| 129 | <div class="flex flex-wrap items-center justify-between gap-2 text-sm"> | 125 | <div class="flex flex-wrap items-center justify-between gap-2 text-sm"> |
| 130 | <span class="text-text-subtle">{t("modules.enabledCount", { on: String(enabledCount()), total: String(totalCount()) })}</span> | 126 | <span class="text-text-subtle">{t("modules.enabledCount", { on: String(enabledCount()), total: String(totalCount()) })}</span> |
| 131 | - <span class="flex items-center gap-2 text-text-default"> | ||
| 132 | - {t("modules.renewal")}: <ComingSoonValue /> | ||
| 133 | - </span> | ||
| 134 | </div> | 127 | </div> |
| 135 | </section> | 128 | </section> |
| 136 | 129 | ||
| 137 | <section class="space-y-4 p-0"> | 130 | <section class="space-y-4 p-0"> |
| 138 | <DataTable | 131 | <DataTable |
| 132 | + urlState | ||
| 139 | title={t("nav.licenseModules")} | 133 | title={t("nav.licenseModules")} |
| 140 | description={t("modules.subtitle")} | 134 | description={t("modules.subtitle")} |
| 141 | actions={<><Button size="sm" variant="outline" class="min-w-[7.5rem] rounded-lg" disabled title={t("comingSoon.title")}> | 135 | actions={<><Button size="sm" variant="outline" class="min-w-[7.5rem] rounded-lg" disabled title={t("comingSoon.title")}> |
| @@ -150,7 +144,7 @@ function LicenseModulesContent() { | |||
| 150 | </Button></>} | 144 | </Button></>} |
| 151 | columns={columns()} | 145 | columns={columns()} |
| 152 | data={value().rows} | 146 | data={value().rows} |
| 153 | - tableClass="min-w-[760px]" | 147 | + tableClass="min-w-md" |
| 154 | enablePagination={false} | 148 | enablePagination={false} |
| 155 | storageKey="license-modules" | 149 | storageKey="license-modules" |
| 156 | /> | 150 | /> |
src/pages/meal-detail-page.tsxmodified+9 -9
| @@ -47,7 +47,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | |||
| 47 | import { Textarea } from "@/components/ui/textarea"; | 47 | import { Textarea } from "@/components/ui/textarea"; |
| 48 | import { UserSearchSelect } from "@/components/users/user-search-select"; | 48 | import { UserSearchSelect } from "@/components/users/user-search-select"; |
| 49 | import { formatDateTime } from "@/lib/format"; | 49 | import { formatDateTime } from "@/lib/format"; |
| 50 | -import { formatTry, mealCutoffAt } from "@/lib/meals"; | 50 | +import { dietaryTagLabel, formatTry, mealCutoffAt, mealSlotLabel } from "@/lib/meals"; |
| 51 | import { personLabel } from "@/lib/person"; | 51 | import { personLabel } from "@/lib/person"; |
| 52 | import { hasMinRole } from "@/lib/roles"; | 52 | import { hasMinRole } from "@/lib/roles"; |
| 53 | import { useAuth } from "@/stores/auth-context"; | 53 | import { useAuth } from "@/stores/auth-context"; |
| @@ -186,7 +186,7 @@ function MealDetailContent() { | |||
| 186 | {(current) => ( | 186 | {(current) => ( |
| 187 | <div class="space-y-5"> | 187 | <div class="space-y-5"> |
| 188 | <div class="space-y-2"> | 188 | <div class="space-y-2"> |
| 189 | - <Breadcrumbs items={[{ label: t("meals.title"), to: "/meals" }, { label: `${current().date} · ${current().slot}` }]} /> | 189 | + <Breadcrumbs items={[{ label: t("meals.title"), to: "/meals" }, { label: `${current().date} · ${mealSlotLabel(current().slot, t)}` }]} /> |
| 190 | <PageHeader | 190 | <PageHeader |
| 191 | title={t("meals.menu")} | 191 | title={t("meals.menu")} |
| 192 | description={t("meals.detailHelp")} | 192 | description={t("meals.detailHelp")} |
| @@ -226,7 +226,7 @@ function MealDetailContent() { | |||
| 226 | <article class="rounded-xl border border-border-line bg-surface-base p-4"> | 226 | <article class="rounded-xl border border-border-line bg-surface-base p-4"> |
| 227 | <div class="flex justify-between gap-3"><h2 class="font-semibold text-text-strong">{dish.name}</h2><span class="font-semibold">{formatTry(dish.price_minor, moneyLocale())}</span></div> | 227 | <div class="flex justify-between gap-3"><h2 class="font-semibold text-text-strong">{dish.name}</h2><span class="font-semibold">{formatTry(dish.price_minor, moneyLocale())}</span></div> |
| 228 | <p class="mt-2 text-sm text-text-subtle">{dish.description || "—"}</p> | 228 | <p class="mt-2 text-sm text-text-subtle">{dish.description || "—"}</p> |
| 229 | - <div class="mt-3 flex flex-wrap gap-1"><For each={dish.tags}>{(tag) => <Badge variant="outline" class={dish.conflicts.includes(tag) ? "border-warning/50 bg-warning/10 text-warning-text" : ""}>{dish.conflicts.includes(tag) ? `⚠ ${tag}` : tag}</Badge>}</For></div> | 229 | + <div class="mt-3 flex flex-wrap gap-1"><For each={dish.tags}>{(tag) => <Badge variant="outline" class={dish.conflicts.includes(tag) ? "border-warning/50 bg-warning/10 text-warning-text" : ""}>{dish.conflicts.includes(tag) ? `⚠ ${dietaryTagLabel(tag, t)}` : dietaryTagLabel(tag, t)}</Badge>}</For></div> |
| 230 | <Show when={canManage()}><div class="mt-3 flex gap-2 border-t border-border-hairline pt-3"><Button variant="outline" size="sm" onClick={() => openDish(dish)}>{t("common.edit")}</Button><Button variant="ghost" size="sm" class="text-destructive-text" onClick={() => setDeleteDish(dish)}>{t("common.delete")}</Button></div></Show> | 230 | <Show when={canManage()}><div class="mt-3 flex gap-2 border-t border-border-hairline pt-3"><Button variant="outline" size="sm" onClick={() => openDish(dish)}>{t("common.edit")}</Button><Button variant="ghost" size="sm" class="text-destructive-text" onClick={() => setDeleteDish(dish)}>{t("common.delete")}</Button></div></Show> |
| 231 | </article> | 231 | </article> |
| 232 | )}</For> | 232 | )}</For> |
| @@ -242,7 +242,7 @@ function MealDetailContent() { | |||
| 242 | 242 | ||
| 243 | <TabsContent value="account" class="space-y-4"> | 243 | <TabsContent value="account" class="space-y-4"> |
| 244 | <div class="grid gap-4 lg:grid-cols-2"> | 244 | <div class="grid gap-4 lg:grid-cols-2"> |
| 245 | - <section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.dietaryProfile")}</h2><div class="mt-3 flex flex-wrap gap-1.5"><For each={profile()?.tags ?? []}>{(tag) => <Badge variant="outline" class="border-warning/50 bg-warning/10 text-warning-text">⚠ {tag}</Badge>}</For></div><p class="mt-3 text-sm text-text-subtle">{profile()?.note || t("meals.noDietaryNotes")}</p></section> | 245 | + <section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.dietaryProfile")}</h2><div class="mt-3 flex flex-wrap gap-1.5"><For each={profile()?.tags ?? []}>{(tag) => <Badge variant="outline" class="border-warning/50 bg-warning/10 text-warning-text">⚠ {dietaryTagLabel(tag, t)}</Badge>}</For></div><p class="mt-3 text-sm text-text-subtle">{profile()?.note || t("meals.noDietaryNotes")}</p></section> |
| 246 | <Show when={canReadMoney()}><section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.balance")}</h2><p class="mt-3 text-2xl font-semibold tabular-nums">{formatTry(balance()?.balance_minor ?? 0, moneyLocale())}</p></section></Show> | 246 | <Show when={canReadMoney()}><section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.balance")}</h2><p class="mt-3 text-2xl font-semibold tabular-nums">{formatTry(balance()?.balance_minor ?? 0, moneyLocale())}</p></section></Show> |
| 247 | </div> | 247 | </div> |
| 248 | <Show when={canReadMoney()}><section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.ledger")}</h2><div class="mt-3 divide-y divide-border-hairline"><For each={ledger()?.items ?? []}>{(line) => <div class="flex justify-between gap-3 py-3 text-sm"><div><p class="font-medium">{t(`meals.ledger.${line.kind}` as never)}</p><p class="text-xs text-text-subtle">{line.note || line.method || "—"} · {formatDateTime(line.created_at, locale())}</p></div><span class="font-semibold tabular-nums">{line.kind === "charge" ? "−" : "+"}{formatTry(line.amount_minor, moneyLocale())}</span></div>}</For></div><Show when={(ledger()?.items.length ?? 0) === 0}><p class="mt-3 text-sm text-text-subtle">{t("meals.noLedger")}</p></Show></section></Show> | 248 | <Show when={canReadMoney()}><section class="data-shell p-4"><h2 class="font-semibold text-text-strong">{t("meals.ledger")}</h2><div class="mt-3 divide-y divide-border-hairline"><For each={ledger()?.items ?? []}>{(line) => <div class="flex justify-between gap-3 py-3 text-sm"><div><p class="font-medium">{t(`meals.ledger.${line.kind}` as never)}</p><p class="text-xs text-text-subtle">{line.note || line.method || "—"} · {formatDateTime(line.created_at, locale())}</p></div><span class="font-semibold tabular-nums">{line.kind === "charge" ? "−" : "+"}{formatTry(line.amount_minor, moneyLocale())}</span></div>}</For></div><Show when={(ledger()?.items.length ?? 0) === 0}><p class="mt-3 text-sm text-text-subtle">{t("meals.noLedger")}</p></Show></section></Show> |
| @@ -267,7 +267,7 @@ function MealDetailContent() { | |||
| 267 | <UserSearchSelect id="meal-record-user" role="student" value={lookupStudent()} onChange={setLookupStudent} label={t("meals.student")} /> | 267 | <UserSearchSelect id="meal-record-user" role="student" value={lookupStudent()} onChange={setLookupStudent} label={t("meals.student")} /> |
| 268 | <Show when={lookupStudent()}> | 268 | <Show when={lookupStudent()}> |
| 269 | <div class="space-y-3"> | 269 | <div class="space-y-3"> |
| 270 | - <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border border-border-line px-3 py-2 text-sm"><input type="checkbox" checked={profileTags().includes(tag)} onChange={() => toggleTag(tag, profileTags(), setProfileTags)} />{tag}</label>}</For></div> | 270 | + <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border border-border-line px-3 py-2 text-sm"><input type="checkbox" checked={profileTags().includes(tag)} onChange={() => toggleTag(tag, profileTags(), setProfileTags)} />{dietaryTagLabel(tag, t)}</label>}</For></div> |
| 271 | <Textarea maxlength={limits()?.meal.max_dietary_note_len} value={profileNote()} placeholder={t("meals.dietaryNote")} onInput={(e) => setProfileNote(e.currentTarget.value)} /> | 271 | <Textarea maxlength={limits()?.meal.max_dietary_note_len} value={profileNote()} placeholder={t("meals.dietaryNote")} onInput={(e) => setProfileNote(e.currentTarget.value)} /> |
| 272 | <Button disabled={pending()} onClick={() => void run(async () => { await patchDietaryProfileByUserId(lookupStudent(), { tags: profileTags(), note: profileNote().trim() || null }); await refetchProfile(); })}>{t("common.save")}</Button> | 272 | <Button disabled={pending()} onClick={() => void run(async () => { await patchDietaryProfileByUserId(lookupStudent(), { tags: profileTags(), note: profileNote().trim() || null }); await refetchProfile(); })}>{t("common.save")}</Button> |
| 273 | </div> | 273 | </div> |
| @@ -282,18 +282,18 @@ function MealDetailContent() { | |||
| 282 | 282 | ||
| 283 | <ConfirmDialog open={cancelOpen()} onOpenChange={setCancelOpen} title={t("meals.cancelBooking")} variant="destructive" summary={t("meals.cancelSummary")} onConfirm={() => run(async () => { const booking = activeBooking(); if (!booking) return; await deleteMealBookingById(booking.id); await Promise.all([refetchBookings(), refetchBalance(), refetchLedger()]); }, t("meals.cancelled"))} /> | 283 | <ConfirmDialog open={cancelOpen()} onOpenChange={setCancelOpen} title={t("meals.cancelBooking")} variant="destructive" summary={t("meals.cancelSummary")} onConfirm={() => run(async () => { const booking = activeBooking(); if (!booking) return; await deleteMealBookingById(booking.id); await Promise.all([refetchBookings(), refetchBalance(), refetchLedger()]); }, t("meals.cancelled"))} /> |
| 284 | <ConfirmDialog open={cancelBooking() !== null} onOpenChange={(open) => !open && setCancelBooking(null)} title={t("meals.cancelBooking")} variant="destructive" summary={cancelBooking() ? `${t("meals.cancelSummary")} · ${personLabel(cancelBooking()!.student)}` : ""} onConfirm={() => run(async () => { const booking = cancelBooking(); if (!booking) return; await deleteMealBookingById(booking.id); setCancelBooking(null); await Promise.all([refetchService(), refetchServiceBookings()]); }, t("meals.cancelled"))} /> | 284 | <ConfirmDialog open={cancelBooking() !== null} onOpenChange={(open) => !open && setCancelBooking(null)} title={t("meals.cancelBooking")} variant="destructive" summary={cancelBooking() ? `${t("meals.cancelSummary")} · ${personLabel(cancelBooking()!.student)}` : ""} onConfirm={() => run(async () => { const booking = cancelBooking(); if (!booking) return; await deleteMealBookingById(booking.id); setCancelBooking(null); await Promise.all([refetchService(), refetchServiceBookings()]); }, t("meals.cancelled"))} /> |
| 285 | - <ConfirmDialog open={deleteMenuOpen()} onOpenChange={setDeleteMenuOpen} title={t("meals.deleteMenu")} variant="destructive" summary={`${current().date} · ${current().slot}`} onConfirm={() => run(async () => { await deleteMealMenuById(id()); void navigate({ to: "/meals" }); }, t("common.deleted"))} /> | 285 | + <ConfirmDialog open={deleteMenuOpen()} onOpenChange={setDeleteMenuOpen} title={t("meals.deleteMenu")} variant="destructive" summary={`${current().date} · ${mealSlotLabel(current().slot, t)}`} onConfirm={() => run(async () => { await deleteMealMenuById(id()); void navigate({ to: "/meals" }); }, t("common.deleted"))} /> |
| 286 | <ConfirmDialog open={deleteDish() !== null} onOpenChange={(open) => !open && setDeleteDish(null)} title={t("meals.deleteDish")} variant="destructive" summary={deleteDish()?.name ?? ""} onConfirm={() => run(async () => { if (!deleteDish()) return; await deleteMealDishById(deleteDish()!.id); setDeleteDish(null); await refetchMenu(); }, t("common.deleted"))} /> | 286 | <ConfirmDialog open={deleteDish() !== null} onOpenChange={(open) => !open && setDeleteDish(null)} title={t("meals.deleteDish")} variant="destructive" summary={deleteDish()?.name ?? ""} onConfirm={() => run(async () => { if (!deleteDish()) return; await deleteMealDishById(deleteDish()!.id); setDeleteDish(null); await refetchMenu(); }, t("common.deleted"))} /> |
| 287 | 287 | ||
| 288 | - <SidePanel guardUnsaved open={showMenuEdit()} onOpenChange={setShowMenuEdit} title={t("meals.editMenu")} description={`${current().date} · ${current().slot}`}> | 288 | + <SidePanel guardUnsaved open={showMenuEdit()} onOpenChange={setShowMenuEdit} title={t("meals.editMenu")} description={`${current().date} · ${mealSlotLabel(current().slot, t)}`}> |
| 289 | <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { await patchMealMenuById(id(), { capacity: capacity() ? Number(capacity()) : null }); setShowMenuEdit(false); await refetchMenu(); }); }}><div class="space-y-1.5"><Label for="menu-capacity">{t("meals.capacity")}</Label><Input id="menu-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div><Button type="submit" disabled={pending()}>{t("common.save")}</Button></form> | 289 | <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { await patchMealMenuById(id(), { capacity: capacity() ? Number(capacity()) : null }); setShowMenuEdit(false); await refetchMenu(); }); }}><div class="space-y-1.5"><Label for="menu-capacity">{t("meals.capacity")}</Label><Input id="menu-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div><Button type="submit" disabled={pending()}>{t("common.save")}</Button></form> |
| 290 | </SidePanel> | 290 | </SidePanel> |
| 291 | - <SidePanel guardUnsaved open={showDishForm()} onOpenChange={setShowDishForm} title={editingDish() ? t("meals.editDish") : t("meals.addDish")} description={`${current().date} · ${current().slot}`}> | 291 | + <SidePanel guardUnsaved open={showDishForm()} onOpenChange={setShowDishForm} title={editingDish() ? t("meals.editDish") : t("meals.addDish")} description={`${current().date} · ${mealSlotLabel(current().slot, t)}`}> |
| 292 | <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { const body = { name: dishName().trim(), description: dishDescription().trim() || null, price_minor: Math.round(Number(dishPrice()) * 100), tags: dishTags() }; if (editingDish()) await patchMealDishById(editingDish()!.id, body); else await postMealDish(id(), body); setShowDishForm(false); await refetchMenu(); }); }}> | 292 | <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { const body = { name: dishName().trim(), description: dishDescription().trim() || null, price_minor: Math.round(Number(dishPrice()) * 100), tags: dishTags() }; if (editingDish()) await patchMealDishById(editingDish()!.id, body); else await postMealDish(id(), body); setShowDishForm(false); await refetchMenu(); }); }}> |
| 293 | <div class="space-y-1.5"><Label for="dish-name">{t("meals.dishName")}</Label><Input id="dish-name" required maxlength={limits()?.meal.max_dish_name_len} value={dishName()} onInput={(e) => setDishName(e.currentTarget.value)} /></div> | 293 | <div class="space-y-1.5"><Label for="dish-name">{t("meals.dishName")}</Label><Input id="dish-name" required maxlength={limits()?.meal.max_dish_name_len} value={dishName()} onInput={(e) => setDishName(e.currentTarget.value)} /></div> |
| 294 | <div class="space-y-1.5"><Label for="dish-description">{t("form.description")}</Label><Textarea id="dish-description" maxlength={limits()?.meal.max_dish_description_len} value={dishDescription()} onInput={(e) => setDishDescription(e.currentTarget.value)} /></div> | 294 | <div class="space-y-1.5"><Label for="dish-description">{t("form.description")}</Label><Textarea id="dish-description" maxlength={limits()?.meal.max_dish_description_len} value={dishDescription()} onInput={(e) => setDishDescription(e.currentTarget.value)} /></div> |
| 295 | <div class="space-y-1.5"><Label for="dish-price">{t("meals.priceTry")}</Label><Input id="dish-price" required type="number" min={0} step={0.01} value={dishPrice()} onInput={(e) => setDishPrice(e.currentTarget.value)} /></div> | 295 | <div class="space-y-1.5"><Label for="dish-price">{t("meals.priceTry")}</Label><Input id="dish-price" required type="number" min={0} step={0.01} value={dishPrice()} onInput={(e) => setDishPrice(e.currentTarget.value)} /></div> |
| 296 | - <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border border-border-line px-3 py-2 text-sm"><input type="checkbox" checked={dishTags().includes(tag)} onChange={() => toggleTag(tag, dishTags(), setDishTags)} />{tag}</label>}</For></div> | 296 | + <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border border-border-line px-3 py-2 text-sm"><input type="checkbox" checked={dishTags().includes(tag)} onChange={() => toggleTag(tag, dishTags(), setDishTags)} />{dietaryTagLabel(tag, t)}</label>}</For></div> |
| 297 | <Button type="submit" disabled={pending()}>{t("common.save")}</Button> | 297 | <Button type="submit" disabled={pending()}>{t("common.save")}</Button> |
| 298 | </form> | 298 | </form> |
| 299 | </SidePanel> | 299 | </SidePanel> |
src/pages/meals-page.tsxmodified+3 -2
| @@ -22,6 +22,7 @@ import { Select } from "@/components/ui/select"; | |||
| 22 | import { SidePanel } from "@/components/ui/side-panel"; | 22 | import { SidePanel } from "@/components/ui/side-panel"; |
| 23 | import { inputDateToIso, isoDateToInput } from "@/lib/datetime-input"; | 23 | import { inputDateToIso, isoDateToInput } from "@/lib/datetime-input"; |
| 24 | import { createFlash } from "@/lib/flash"; | 24 | import { createFlash } from "@/lib/flash"; |
| 25 | +import { mealSlotLabel } from "@/lib/meals"; | ||
| 25 | import { hasMinRole } from "@/lib/roles"; | 26 | import { hasMinRole } from "@/lib/roles"; |
| 26 | import { useAuth } from "@/stores/auth-context"; | 27 | import { useAuth } from "@/stores/auth-context"; |
| 27 | import { usePreferences, useT } from "@/stores/preferences-context"; | 28 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| @@ -98,7 +99,7 @@ function MealsContent() { | |||
| 98 | <form class="space-y-4" onSubmit={publish}> | 99 | <form class="space-y-4" onSubmit={publish}> |
| 99 | <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show> | 100 | <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show> |
| 100 | <div class="space-y-1.5"><Label for="meal-date">{t("meals.date")}</Label><DatePicker id="meal-date" required placeholder={t("form.datePlaceholder")} value={isoDateToInput(date())} onChange={(value) => setDate(inputDateToIso(value))} /></div> | 101 | <div class="space-y-1.5"><Label for="meal-date">{t("meals.date")}</Label><DatePicker id="meal-date" required placeholder={t("form.datePlaceholder")} value={isoDateToInput(date())} onChange={(value) => setDate(inputDateToIso(value))} /></div> |
| 101 | - <div class="space-y-1.5"><Label for="meal-slot">{t("meals.slot")}</Label><Select id="meal-slot" required value={newSlot()} onChange={(e) => setNewSlot(e.currentTarget.value)}><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{item.name}</option>}</For></Select></div> | 102 | + <div class="space-y-1.5"><Label for="meal-slot">{t("meals.slot")}</Label><Select id="meal-slot" required value={newSlot()} onChange={(e) => setNewSlot(e.currentTarget.value)}><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{mealSlotLabel(item.name, t)}</option>}</For></Select></div> |
| 102 | <div class="space-y-1.5"><Label for="meal-capacity">{t("meals.capacity")}</Label><Input id="meal-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div> | 103 | <div class="space-y-1.5"><Label for="meal-capacity">{t("meals.capacity")}</Label><Input id="meal-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div> |
| 103 | <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show> | 104 | <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show> |
| 104 | <div class="flex gap-2 border-t border-border-hairline pt-4"><Button type="submit" disabled={pending()}>{t("common.create")}</Button><Button type="button" variant="outline" onClick={() => setShowCreate(false)}>{t("common.cancel")}</Button></div> | 105 | <div class="flex gap-2 border-t border-border-hairline pt-4"><Button type="submit" disabled={pending()}>{t("common.create")}</Button><Button type="button" variant="outline" onClick={() => setShowCreate(false)}>{t("common.cancel")}</Button></div> |
| @@ -108,7 +109,7 @@ function MealsContent() { | |||
| 108 | <DataSection title={t("meals.title")} description={t("meals.subtitle")} actions={<Show when={canManage()}><Button size="sm" class="min-w-[7.5rem] rounded-lg" onClick={() => { setNewSlot(settings()?.meal_slots[0]?.name ?? ""); setShowCreate(true); }}><IconPlus class="h-4 w-4" />{t("meals.publish")}</Button></Show>}> | 109 | <DataSection title={t("meals.title")} description={t("meals.subtitle")} actions={<Show when={canManage()}><Button size="sm" class="min-w-[7.5rem] rounded-lg" onClick={() => { setNewSlot(settings()?.meal_slots[0]?.name ?? ""); setShowCreate(true); }}><IconPlus class="h-4 w-4" />{t("meals.publish")}</Button></Show>}> |
| 109 | <div class="flex flex-wrap items-center gap-2"> | 110 | <div class="flex flex-wrap items-center gap-2"> |
| 110 | <DatePicker id="menus-from" class="h-8 w-44" placeholder={t("meals.from")} value={isoDateToInput(from())} onChange={(value) => { const iso = inputDateToIso(value); if (iso) { setFrom(iso); setPage(0); } }} /> | 111 | <DatePicker id="menus-from" class="h-8 w-44" placeholder={t("meals.from")} value={isoDateToInput(from())} onChange={(value) => { const iso = inputDateToIso(value); if (iso) { setFrom(iso); setPage(0); } }} /> |
| 111 | - <Select id="menus-slot" aria-label={t("meals.slot")} wrapperClass="w-auto" class="h-8 rounded-lg text-[13px]" value={slot()} onChange={(e) => setSlot(e.currentTarget.value)}><option value="all">{t("meals.slot")}: {t("common.all")}</option><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{item.name}</option>}</For></Select> | 112 | + <Select id="menus-slot" aria-label={t("meals.slot")} wrapperClass="w-auto" class="h-8 rounded-lg text-[13px]" value={slot()} onChange={(e) => setSlot(e.currentTarget.value)}><option value="all">{t("meals.slot")}: {t("common.all")}</option><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{mealSlotLabel(item.name, t)}</option>}</For></Select> |
| 112 | </div> | 113 | </div> |
| 113 | <Suspense fallback={<PageSpinner />}> | 114 | <Suspense fallback={<PageSpinner />}> |
| 114 | <Show when={menus.error}><ErrorAlert message={formatApiError(menus.error)} onRetry={() => void refetch()} /></Show> | 115 | <Show when={menus.error}><ErrorAlert message={formatApiError(menus.error)} onRetry={() => void refetch()} /></Show> |
src/pages/note-editor-page.tsxmodified+13 -1
| @@ -2,11 +2,13 @@ import { useLocation } from "@tanstack/solid-router"; | |||
| 2 | import { Show, Suspense, createMemo } from "solid-js"; | 2 | import { Show, Suspense, createMemo } from "solid-js"; |
| 3 | import { getNoteById } from "@/api/notes"; | 3 | import { getNoteById } from "@/api/notes"; |
| 4 | import { formatApiError } from "@/api/client"; | 4 | import { formatApiError } from "@/api/client"; |
| 5 | +import { RecordNotFound } from "@/components/layout/record-not-found"; | ||
| 5 | import { RouteGuard } from "@/components/layout/route-guard"; | 6 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 6 | import { NoteDocument } from "@/components/notes/note-document"; | 7 | import { NoteDocument } from "@/components/notes/note-document"; |
| 7 | import { ErrorAlert } from "@/components/ui/error-alert"; | 8 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 8 | import { PageSpinner } from "@/components/ui/page-spinner"; | 9 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 9 | import { createResource } from "@/lib/create-resource"; | 10 | import { createResource } from "@/lib/create-resource"; |
| 11 | +import { isNotFoundError } from "@/lib/record-list-path"; | ||
| 10 | 12 | ||
| 11 | /** `/notes/new` and `/notes/$id` — the router remounts this page per note. */ | 13 | /** `/notes/new` and `/notes/$id` — the router remounts this page per note. */ |
| 12 | export default function NoteEditorPage() { | 14 | export default function NoteEditorPage() { |
| @@ -21,7 +23,17 @@ export default function NoteEditorPage() { | |||
| 21 | <RouteGuard> | 23 | <RouteGuard> |
| 22 | <Show when={id()} fallback={<NoteDocument />}> | 24 | <Show when={id()} fallback={<NoteDocument />}> |
| 23 | <Suspense fallback={<PageSpinner />}> | 25 | <Suspense fallback={<PageSpinner />}> |
| 24 | - <Show when={!note.error} fallback={<ErrorAlert message={formatApiError(note.error)} onRetry={() => void refetch()} />}> | 26 | + <Show |
| 27 | + when={!note.error} | ||
| 28 | + fallback={ | ||
| 29 | + <Show | ||
| 30 | + when={!isNotFoundError(note.error)} | ||
| 31 | + fallback={<RecordNotFound backTo="/notes" />} | ||
| 32 | + > | ||
| 33 | + <ErrorAlert message={formatApiError(note.error)} onRetry={() => void refetch()} /> | ||
| 34 | + </Show> | ||
| 35 | + } | ||
| 36 | + > | ||
| 25 | <Show when={note()}>{(loaded) => <NoteDocument note={loaded()} />}</Show> | 37 | <Show when={note()}>{(loaded) => <NoteDocument note={loaded()} />}</Show> |
| 26 | </Show> | 38 | </Show> |
| 27 | </Suspense> | 39 | </Suspense> |
src/pages/payment-statement-page.tsxmodified+1 -0
| @@ -156,6 +156,7 @@ function StatementContent() { | |||
| 156 | <ErrorAlert message={formatApiError(statement.error)} onRetry={() => void refetch()} /> | 156 | <ErrorAlert message={formatApiError(statement.error)} onRetry={() => void refetch()} /> |
| 157 | </Show> | 157 | </Show> |
| 158 | <DataTable | 158 | <DataTable |
| 159 | + urlState | ||
| 159 | title={t("payments.statementTitle")} | 160 | title={t("payments.statementTitle")} |
| 160 | description={t("payments.statementSubtitle")} | 161 | description={t("payments.statementSubtitle")} |
| 161 | empty={t("payments.noStatement")} | 162 | empty={t("payments.noStatement")} |
src/pages/payments-page.tsxmodified+12 -13
| @@ -27,7 +27,7 @@ import { RouteGuard } from "@/components/layout/route-guard"; | |||
| 27 | import { Alert } from "@/components/ui/alert"; | 27 | import { Alert } from "@/components/ui/alert"; |
| 28 | import { Badge } from "@/components/ui/badge"; | 28 | import { Badge } from "@/components/ui/badge"; |
| 29 | import { Button } from "@/components/ui/button"; | 29 | import { Button } from "@/components/ui/button"; |
| 30 | -import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; | 30 | +import { ComingSoonBadge } from "@/components/ui/coming-soon"; |
| 31 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 31 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 32 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 32 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 33 | import { DatePicker } from "@/components/ui/date-picker"; | 33 | import { DatePicker } from "@/components/ui/date-picker"; |
| @@ -44,6 +44,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | |||
| 44 | import { Textarea } from "@/components/ui/textarea"; | 44 | import { Textarea } from "@/components/ui/textarea"; |
| 45 | import { UserSearchSelect } from "@/components/users/user-search-select"; | 45 | import { UserSearchSelect } from "@/components/users/user-search-select"; |
| 46 | import { createFlash } from "@/lib/flash"; | 46 | import { createFlash } from "@/lib/flash"; |
| 47 | +import { createUrlString } from "@/lib/url-state"; | ||
| 47 | import { formatDate, formatDateTime } from "@/lib/format"; | 48 | import { formatDate, formatDateTime } from "@/lib/format"; |
| 48 | import { formatTry } from "@/lib/meals"; | 49 | import { formatTry } from "@/lib/meals"; |
| 49 | import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments"; | 50 | import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments"; |
| @@ -93,7 +94,9 @@ function PaymentsContent() { | |||
| 93 | const t = useT(); | 94 | const t = useT(); |
| 94 | const { locale } = usePreferences(); | 95 | const { locale } = usePreferences(); |
| 95 | const moneyLocale = () => (locale() === "tr" ? "tr-TR" : "en-US"); | 96 | const moneyLocale = () => (locale() === "tr" ? "tr-TR" : "en-US"); |
| 96 | - const [tab, setTab] = createSignal("collect"); | 97 | + // Tab, student search and plan filter ride in the URL: Back from a |
| 98 | + // student's statement lands on the same filtered list. | ||
| 99 | + const [tab, setTab] = createUrlString("tab", "collect"); | ||
| 97 | const [error, setError] = createSignal(""); | 100 | const [error, setError] = createSignal(""); |
| 98 | const [flash, setFlash] = createFlash(); | 101 | const [flash, setFlash] = createFlash(); |
| 99 | const [pending, setPending] = createSignal(false); | 102 | const [pending, setPending] = createSignal(false); |
| @@ -106,10 +109,10 @@ function PaymentsContent() { | |||
| 106 | }); | 109 | }); |
| 107 | const student = () => selectedStudent()?.id ?? ""; | 110 | const student = () => selectedStudent()?.id ?? ""; |
| 108 | 111 | ||
| 109 | - const [planFilter, setPlanFilter] = createSignal(""); | 112 | + const [planFilter, setPlanFilter] = createUrlString("plan"); |
| 110 | - const [studentQuery, setStudentQuery] = createSignal(""); | 113 | + const [studentQuery, setStudentQuery] = createUrlString("q"); |
| 111 | // Debounced so typing doesn't fire a search request per keystroke. | 114 | // Debounced so typing doesn't fire a search request per keystroke. |
| 112 | - const [debouncedQuery, setDebouncedQuery] = createSignal(""); | 115 | + const [debouncedQuery, setDebouncedQuery] = createSignal(studentQuery().trim()); |
| 113 | let queryTimer: ReturnType<typeof setTimeout> | undefined; | 116 | let queryTimer: ReturnType<typeof setTimeout> | undefined; |
| 114 | createEffect(() => { | 117 | createEffect(() => { |
| 115 | const q = studentQuery(); | 118 | const q = studentQuery(); |
| @@ -610,12 +613,8 @@ function PaymentsContent() { | |||
| 610 | when={selectedStudent()} | 613 | when={selectedStudent()} |
| 611 | fallback={ | 614 | fallback={ |
| 612 | <> | 615 | <> |
| 613 | - <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4"> | 616 | + {/* No endpoint totals billed / collected / overdue across the |
| 614 | - <div class="detail-metric-card"><p class="text-xs font-medium text-text-subtle">{t("payments.periodBilled")}</p><ComingSoonValue class="mt-1" /></div> | 617 | + school, so the design's period KPI cards are left out. */} |
| 615 | - <div class="detail-metric-card"><p class="text-xs font-medium text-text-subtle">{t("payments.periodCollected")}</p><ComingSoonValue class="mt-1" /></div> | ||
| 616 | - <div class="detail-metric-card"><p class="text-xs font-medium text-text-subtle">{t("payments.periodOverdue")}</p><ComingSoonValue class="mt-1" /></div> | ||
| 617 | - <div class="detail-metric-card"><p class="text-xs font-medium text-text-subtle">{t("payments.periodExpected")}</p><ComingSoonValue class="mt-1" /></div> | ||
| 618 | - </div> | ||
| 619 | <section class="space-y-4 p-0"> | 618 | <section class="space-y-4 p-0"> |
| 620 | <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}> | 619 | <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}> |
| 621 | <Show when={studentsPage.error}> | 620 | <Show when={studentsPage.error}> |
| @@ -630,11 +629,11 @@ function PaymentsContent() { | |||
| 630 | setStudentQuery(value); | 629 | setStudentQuery(value); |
| 631 | setStudentPage(0); | 630 | setStudentPage(0); |
| 632 | }} | 631 | }} |
| 633 | - filterPlaceholder={t("payments.selectStudent")} | 632 | + filterPlaceholder={t("payments.searchStudents")} |
| 634 | filterHint={t("search.hint.paymentsStudents")} | 633 | filterHint={t("search.hint.paymentsStudents")} |
| 635 | title={t("payments.title")} | 634 | title={t("payments.title")} |
| 636 | description={t("payments.subtitle")} | 635 | description={t("payments.subtitle")} |
| 637 | - empty={t("payments.selectStudent")} | 636 | + empty={t("form.noStudents")} |
| 638 | actions={ | 637 | actions={ |
| 639 | <Button size="sm" variant="outline" class="rounded-lg" disabled title={t("comingSoon.title")}> | 638 | <Button size="sm" variant="outline" class="rounded-lg" disabled title={t("comingSoon.title")}> |
| 640 | {t("payments.exportStatement")} | 639 | {t("payments.exportStatement")} |
src/pages/pomodoro-page.tsxmodified+1 -1
| @@ -336,7 +336,7 @@ function PomodoroContent() { | |||
| 336 | </div> | 336 | </div> |
| 337 | </div> | 337 | </div> |
| 338 | <Suspense fallback={<DataTableSkeleton />}> | 338 | <Suspense fallback={<DataTableSkeleton />}> |
| 339 | - <DataTable columns={columns()} data={log()?.items ?? []} empty={t("pomodoro.empty")} enablePagination pageSize={10} /> | 339 | + <DataTable columns={columns()} data={log()?.items ?? []} empty={t("pomodoro.empty")} enablePagination pageSize={10} urlState /> |
| 340 | </Suspense> | 340 | </Suspense> |
| 341 | </section> | 341 | </section> |
| 342 | </div> | 342 | </div> |
src/pages/profile-page.tsxmodified+7 -1
| @@ -56,10 +56,16 @@ function ProfileContent() { | |||
| 56 | 56 | ||
| 57 | // The five counters that fit the profile owner's role: a student's own | 57 | // The five counters that fit the profile owner's role: a student's own |
| 58 | // work, or a teacher's / manager's teaching work. | 58 | // work, or a teacher's / manager's teaching work. |
| 59 | + // Focus time reads in minutes below an hour: flooring 50 minutes to hours | ||
| 60 | + // showed "0 Odak saati" beside "5 Odak oturumu". | ||
| 61 | + const focusStat = (ms: number): { label: string; value: number } => | ||
| 62 | + ms < 3_600_000 | ||
| 63 | + ? { label: t("profile.statFocusMinutes"), value: Math.floor(ms / 60_000) } | ||
| 64 | + : { label: t("profile.statFocusHours"), value: Math.floor(ms / 3_600_000) }; | ||
| 59 | const profileStats = (p: Profile): { icon: PixelIconName; label: string; value: number }[] => | 65 | const profileStats = (p: Profile): { icon: PixelIconName; label: string; value: number }[] => |
| 60 | p.role === "student" || p.role === "parent" | 66 | p.role === "student" || p.role === "parent" |
| 61 | ? [ | 67 | ? [ |
| 62 | - { icon: "hourglass", label: t("profile.statFocusHours"), value: Math.floor(p.stats.pomodoro_focus_ms_total / 3_600_000) }, | 68 | + { icon: "hourglass", ...focusStat(p.stats.pomodoro_focus_ms_total) }, |
| 63 | { icon: "zap", label: t("profile.statSessions"), value: p.stats.pomodoro_finished_total }, | 69 | { icon: "zap", label: t("profile.statSessions"), value: p.stats.pomodoro_finished_total }, |
| 64 | { icon: "notes", label: t("profile.statHomework"), value: p.stats.homework_submitted_total }, | 70 | { icon: "notes", label: t("profile.statHomework"), value: p.stats.homework_submitted_total }, |
| 65 | { icon: "check-double", label: t("profile.statOnTime"), value: p.stats.homework_on_time_total }, | 71 | { icon: "check-double", label: t("profile.statOnTime"), value: p.stats.homework_on_time_total }, |
src/pages/question-bank-page.tsxmodified+3 -1
| @@ -116,7 +116,9 @@ function QuestionBankContent() { | |||
| 116 | cell: (cell) => ( | 116 | cell: (cell) => ( |
| 117 | <div class="min-w-0"> | 117 | <div class="min-w-0"> |
| 118 | <p class="max-w-[30rem] truncate font-medium">{cell.row.original.text}</p> | 118 | <p class="max-w-[30rem] truncate font-medium">{cell.row.original.text}</p> |
| 119 | - <p class="truncate text-xs text-muted-foreground">{cell.row.original.subject_name || "—"}</p> | 119 | + <Show when={cell.row.original.subject_name}> |
| 120 | + <p class="truncate text-xs text-muted-foreground">{cell.row.original.subject_name}</p> | ||
| 121 | + </Show> | ||
| 120 | </div> | 122 | </div> |
| 121 | ), | 123 | ), |
| 122 | }, | 124 | }, |
src/pages/settings-page.tsxmodified+106 -44
| @@ -1,4 +1,5 @@ | |||
| 1 | import { For, Index, Show, Suspense, createEffect, createSignal } from "solid-js"; | 1 | import { For, Index, Show, Suspense, createEffect, createSignal } from "solid-js"; |
| 2 | +import { useBlocker } from "@tanstack/solid-router"; | ||
| 2 | import { createResource } from "@/lib/create-resource"; | 3 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { getSettings } from "@/api/settings"; | 4 | import { getSettings } from "@/api/settings"; |
| 4 | import { patchSettings } from "@/api/settings"; | 5 | import { patchSettings } from "@/api/settings"; |
| @@ -11,8 +12,9 @@ import { PageHeader } from "@/components/layout/page-header"; | |||
| 11 | import { Alert } from "@/components/ui/alert"; | 12 | import { Alert } from "@/components/ui/alert"; |
| 12 | import { Badge } from "@/components/ui/badge"; | 13 | import { Badge } from "@/components/ui/badge"; |
| 13 | import { Button } from "@/components/ui/button"; | 14 | import { Button } from "@/components/ui/button"; |
| 15 | +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | ||
| 14 | import { ErrorAlert } from "@/components/ui/error-alert"; | 16 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 15 | -import { IconPlus, IconTrash } from "@/components/ui/icons"; | 17 | +import { IconAlert, IconPlus, IconTrash } from "@/components/ui/icons"; |
| 16 | import { Input } from "@/components/ui/input"; | 18 | import { Input } from "@/components/ui/input"; |
| 17 | import { Label } from "@/components/ui/label"; | 19 | import { Label } from "@/components/ui/label"; |
| 18 | import { PageSpinner } from "@/components/ui/page-spinner"; | 20 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| @@ -21,7 +23,7 @@ import { examKindLabel, isKnownExamKind } from "@/lib/exam-labels"; | |||
| 21 | import { moduleLabel, packageLabel } from "@/lib/module-labels"; | 23 | import { moduleLabel, packageLabel } from "@/lib/module-labels"; |
| 22 | import { getAttendanceStatusMeta } from "@/lib/attendance-status"; | 24 | import { getAttendanceStatusMeta } from "@/lib/attendance-status"; |
| 23 | import { cn } from "@/lib/cn"; | 25 | import { cn } from "@/lib/cn"; |
| 24 | -import { dirtySettingsPatch, minuteToUtcTime, utcTimeToMinute } from "@/lib/meals"; | 26 | +import { dietaryTagLabel, dirtySettingsPatch, mealSlotLabel, minuteToUtcTime, utcTimeToMinute } from "@/lib/meals"; |
| 25 | import { useT } from "@/stores/preferences-context"; | 27 | import { useT } from "@/stores/preferences-context"; |
| 26 | 28 | ||
| 27 | const CORE_ATTENDANCE = new Set(["present", "absent", "late", "excused"]); | 29 | const CORE_ATTENDANCE = new Set(["present", "absent", "late", "excused"]); |
| @@ -38,6 +40,10 @@ const BYTES_PER_MIB = 1024 * 1024; | |||
| 38 | // inside already carry their own `data-shell` surfaces. | 40 | // inside already carry their own `data-shell` surfaces. |
| 39 | const TAB_PANEL = "border-0 bg-transparent p-0 shadow-none space-y-4"; | 41 | const TAB_PANEL = "border-0 bg-transparent p-0 shadow-none space-y-4"; |
| 40 | 42 | ||
| 43 | +function mibText(bytes: number): string { | ||
| 44 | + return String(Math.round((bytes / BYTES_PER_MIB) * 10) / 10); | ||
| 45 | +} | ||
| 46 | + | ||
| 41 | function isCoreAttendance(status: string): status is keyof typeof CORE_ATTENDANCE_LABELS { | 47 | function isCoreAttendance(status: string): status is keyof typeof CORE_ATTENDANCE_LABELS { |
| 42 | return status in CORE_ATTENDANCE_LABELS; | 48 | return status in CORE_ATTENDANCE_LABELS; |
| 43 | } | 49 | } |
| @@ -106,7 +112,7 @@ function SettingsContent() { | |||
| 106 | setExamKinds(next.exam_kinds.map((item) => ({ ...item }))); | 112 | setExamKinds(next.exam_kinds.map((item) => ({ ...item }))); |
| 107 | setAttendanceStatuses([...next.attendance_statuses]); | 113 | setAttendanceStatuses([...next.attendance_statuses]); |
| 108 | setGradeBands(next.grade_bands.map((item) => ({ ...item }))); | 114 | setGradeBands(next.grade_bands.map((item) => ({ ...item }))); |
| 109 | - setMaxFileMiB(String(Math.round((fileBytes / BYTES_PER_MIB) * 10) / 10)); | 115 | + setMaxFileMiB(mibText(fileBytes)); |
| 110 | setChatbotHistoryTurns(String(next.chatbot_history_turns)); | 116 | setChatbotHistoryTurns(String(next.chatbot_history_turns)); |
| 111 | setMaxChatbotThreads(String(next.max_chatbot_threads)); | 117 | setMaxChatbotThreads(String(next.max_chatbot_threads)); |
| 112 | setMaxChatbotMessageLen(String(next.max_chatbot_message_len)); | 118 | setMaxChatbotMessageLen(String(next.max_chatbot_message_len)); |
| @@ -121,7 +127,38 @@ function SettingsContent() { | |||
| 121 | setBaseline({ ...next, max_file_bytes: fileBytes }); | 127 | setBaseline({ ...next, max_file_bytes: fileBytes }); |
| 122 | }); | 128 | }); |
| 123 | 129 | ||
| 124 | - const dirty = () => baseline() !== null && JSON.stringify(snapshot()) !== JSON.stringify(baseline()); | 130 | + // The settings exactly as a save would send them: trimmed, numeric, and with |
| 131 | + // the file-size field kept at the saved byte count while its rounded MiB | ||
| 132 | + // text is untouched (5.3 MiB does not round-trip to the stored bytes). | ||
| 133 | + const current = (): SchoolSettings => { | ||
| 134 | + const before = baseline(); | ||
| 135 | + const fileBytes = | ||
| 136 | + before && maxFileMiB() === mibText(before.max_file_bytes) | ||
| 137 | + ? before.max_file_bytes | ||
| 138 | + : Math.round(Number(maxFileMiB()) * BYTES_PER_MIB); | ||
| 139 | + return { | ||
| 140 | + ...snapshot(), | ||
| 141 | + exam_kinds: examKinds().map((item) => ({ name: item.name.trim(), weight: Number(item.weight) })), | ||
| 142 | + attendance_statuses: attendanceStatuses().map((status) => status.trim()), | ||
| 143 | + grade_bands: gradeBands().map((band) => ({ min: Number(band.min), label: band.label.trim() })), | ||
| 144 | + max_file_bytes: fileBytes, | ||
| 145 | + meal_slots: mealSlots().map((slot) => ({ name: slot.name.trim(), serving_minute: slot.serving_minute })), | ||
| 146 | + dietary_tags: dietaryTags().map((tag) => tag.trim()), | ||
| 147 | + excuse_kinds: excuseKinds().map((kind) => kind.trim()).filter(Boolean), | ||
| 148 | + branches: branches().map((branch) => branch.trim()).filter(Boolean), | ||
| 149 | + }; | ||
| 150 | + }; | ||
| 151 | + | ||
| 152 | + // Field by field, the same comparison the PATCH body is built from. A whole- | ||
| 153 | + // object JSON compare flagged a fresh load as dirty: the backend's key order | ||
| 154 | + // differs from this form's. | ||
| 155 | + const dirty = () => { | ||
| 156 | + const before = baseline(); | ||
| 157 | + return before !== null && Object.keys(dirtySettingsPatch(before, current())).length > 0; | ||
| 158 | + }; | ||
| 159 | + | ||
| 160 | + const blocker = useBlocker({ shouldBlockFn: () => dirty(), enableBeforeUnload: () => dirty(), withResolver: true }); | ||
| 161 | + let leaving = false; | ||
| 125 | 162 | ||
| 126 | createEffect(() => { | 163 | createEffect(() => { |
| 127 | if (dirty() && saved()) setSaved(false); | 164 | if (dirty() && saved()) setSaved(false); |
| @@ -130,7 +167,7 @@ function SettingsContent() { | |||
| 130 | const save = async () => { | 167 | const save = async () => { |
| 131 | setError(""); | 168 | setError(""); |
| 132 | setSaved(false); | 169 | setSaved(false); |
| 133 | - const maxFileBytes = Math.round(Number(maxFileMiB()) * BYTES_PER_MIB); | 170 | + const maxFileBytes = current().max_file_bytes; |
| 134 | if (!Number.isFinite(maxFileBytes)) { | 171 | if (!Number.isFinite(maxFileBytes)) { |
| 135 | setError(t("settings.maxFileSizeInvalid")); | 172 | setError(t("settings.maxFileSizeInvalid")); |
| 136 | return; | 173 | return; |
| @@ -151,18 +188,7 @@ function SettingsContent() { | |||
| 151 | try { | 188 | try { |
| 152 | const before = baseline(); | 189 | const before = baseline(); |
| 153 | if (!before) return; | 190 | if (!before) return; |
| 154 | - const current = { | 191 | + const next = await patchSettings(dirtySettingsPatch(before, current())); |
| 155 | - ...snapshot(), | ||
| 156 | - exam_kinds: examKinds().map((item) => ({ name: item.name.trim(), weight: Number(item.weight) })), | ||
| 157 | - attendance_statuses: attendanceStatuses().map((status) => status.trim()), | ||
| 158 | - grade_bands: gradeBands().map((band) => ({ min: Number(band.min), label: band.label.trim() })), | ||
| 159 | - max_file_bytes: maxFileBytes, | ||
| 160 | - meal_slots: mealSlots().map((slot) => ({ ...slot, name: slot.name.trim() })), | ||
| 161 | - dietary_tags: dietaryTags().map((tag) => tag.trim()), | ||
| 162 | - excuse_kinds: excuseKinds().map((kind) => kind.trim()).filter(Boolean), | ||
| 163 | - branches: branches().map((branch) => branch.trim()).filter(Boolean), | ||
| 164 | - }; | ||
| 165 | - const next = await patchSettings(dirtySettingsPatch(before, current)); | ||
| 166 | mutate(next); | 192 | mutate(next); |
| 167 | setBaseline(next); | 193 | setBaseline(next); |
| 168 | setSaved(true); | 194 | setSaved(true); |
| @@ -260,17 +286,20 @@ function SettingsContent() { | |||
| 260 | </span> | 286 | </span> |
| 261 | } | 287 | } |
| 262 | > | 288 | > |
| 263 | - <Input | 289 | + <div class="flex min-w-0 items-center gap-2"> |
| 264 | - aria-label={t("settings.name")} | 290 | + <Input |
| 265 | - class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" | 291 | + aria-label={t("settings.name")} |
| 266 | - value={item().name} | 292 | + class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" |
| 267 | - placeholder={t("settings.name")} | 293 | + value={item().name} |
| 268 | - onInput={(e) => | 294 | + placeholder={t("settings.name")} |
| 269 | - setExamKinds((rows) => | 295 | + onInput={(e) => |
| 270 | - rows.map((row, i) => (i === index ? { ...row, name: e.currentTarget.value } : row)), | 296 | + setExamKinds((rows) => |
| 271 | - ) | 297 | + rows.map((row, i) => (i === index ? { ...row, name: e.currentTarget.value } : row)), |
| 272 | - } | 298 | + ) |
| 273 | - /> | 299 | + } |
| 300 | + /> | ||
| 301 | + <KeyLabelHint value={item().name} label={examKindLabel(item().name.trim(), t)} /> | ||
| 302 | + </div> | ||
| 274 | </Show> | 303 | </Show> |
| 275 | <Input | 304 | <Input |
| 276 | aria-label={t("settings.weight")} | 305 | aria-label={t("settings.weight")} |
| @@ -523,14 +552,17 @@ function SettingsContent() { | |||
| 523 | <Index each={mealSlots()}> | 552 | <Index each={mealSlots()}> |
| 524 | {(slot, index) => ( | 553 | {(slot, index) => ( |
| 525 | <div class="grid grid-cols-[minmax(0,1fr)_7rem_2.25rem] items-center gap-2 rounded-lg border border-border/60 bg-card px-2 py-1.5 shadow-2xs"> | 554 | <div class="grid grid-cols-[minmax(0,1fr)_7rem_2.25rem] items-center gap-2 rounded-lg border border-border/60 bg-card px-2 py-1.5 shadow-2xs"> |
| 526 | - <Input | 555 | + <div class="flex min-w-0 items-center gap-2"> |
| 527 | - aria-label={t("settings.mealSlot")} | 556 | + <Input |
| 528 | - class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" | 557 | + aria-label={t("settings.mealSlot")} |
| 529 | - maxlength={limits()?.settings.max_item_len} | 558 | + class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" |
| 530 | - value={slot().name} | 559 | + maxlength={limits()?.settings.max_item_len} |
| 531 | - placeholder={t("settings.name")} | 560 | + value={slot().name} |
| 532 | - onInput={(e) => setMealSlots((rows) => rows.map((row, i) => i === index ? { ...row, name: e.currentTarget.value } : row))} | 561 | + placeholder={t("settings.name")} |
| 533 | - /> | 562 | + onInput={(e) => setMealSlots((rows) => rows.map((row, i) => i === index ? { ...row, name: e.currentTarget.value } : row))} |
| 563 | + /> | ||
| 564 | + <KeyLabelHint value={slot().name} label={mealSlotLabel(slot().name.trim(), t)} /> | ||
| 565 | + </div> | ||
| 534 | <Input | 566 | <Input |
| 535 | aria-label={t("settings.servingTimeUtc")} | 567 | aria-label={t("settings.servingTimeUtc")} |
| 536 | class="h-9 rounded-md border-0 bg-muted/40 text-center font-mono shadow-none focus-visible:ring-1" | 568 | class="h-9 rounded-md border-0 bg-muted/40 text-center font-mono shadow-none focus-visible:ring-1" |
| @@ -561,14 +593,17 @@ function SettingsContent() { | |||
| 561 | <Index each={dietaryTags()}> | 593 | <Index each={dietaryTags()}> |
| 562 | {(tag, index) => ( | 594 | {(tag, index) => ( |
| 563 | <div class="grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-2 rounded-lg border border-border/60 bg-card px-2 py-1.5 shadow-2xs"> | 595 | <div class="grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-2 rounded-lg border border-border/60 bg-card px-2 py-1.5 shadow-2xs"> |
| 564 | - <Input | 596 | + <div class="flex min-w-0 items-center gap-2"> |
| 565 | - aria-label={t("settings.dietaryTags")} | 597 | + <Input |
| 566 | - class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" | 598 | + aria-label={t("settings.dietaryTags")} |
| 567 | - maxlength={limits()?.settings.max_item_len} | 599 | + class="h-9 rounded-md border-0 bg-transparent shadow-none focus-visible:ring-1" |
| 568 | - value={tag()} | 600 | + maxlength={limits()?.settings.max_item_len} |
| 569 | - placeholder={t("settings.dietaryTags")} | 601 | + value={tag()} |
| 570 | - onInput={(e) => setDietaryTags((rows) => rows.map((row, i) => i === index ? e.currentTarget.value : row))} | 602 | + placeholder={t("settings.dietaryTags")} |
| 571 | - /> | 603 | + onInput={(e) => setDietaryTags((rows) => rows.map((row, i) => i === index ? e.currentTarget.value : row))} |
| 604 | + /> | ||
| 605 | + <KeyLabelHint value={tag()} label={dietaryTagLabel(tag().trim(), t)} /> | ||
| 606 | + </div> | ||
| 572 | <Button type="button" variant="ghost" size="icon" class="h-9 w-9 rounded-md text-muted-foreground hover:text-destructive-text" aria-label={t("common.delete")} onClick={() => setDietaryTags((rows) => rows.filter((_, i) => i !== index))}><IconTrash class="h-4 w-4" /></Button> | 607 | <Button type="button" variant="ghost" size="icon" class="h-9 w-9 rounded-md text-muted-foreground hover:text-destructive-text" aria-label={t("common.delete")} onClick={() => setDietaryTags((rows) => rows.filter((_, i) => i !== index))}><IconTrash class="h-4 w-4" /></Button> |
| 573 | </div> | 608 | </div> |
| 574 | )} | 609 | )} |
| @@ -704,10 +739,37 @@ function SettingsContent() { | |||
| 704 | </TabsContent> | 739 | </TabsContent> |
| 705 | </Suspense> | 740 | </Suspense> |
| 706 | </Tabs> | 741 | </Tabs> |
| 742 | + | ||
| 743 | + <ConfirmDialog | ||
| 744 | + open={blocker().status === "blocked"} | ||
| 745 | + onOpenChange={(open) => { | ||
| 746 | + if (!open && !leaving && blocker().status === "blocked") blocker().reset?.(); | ||
| 747 | + }} | ||
| 748 | + title={t("notes.leaveTitle")} | ||
| 749 | + description={t("settings.leaveHint")} | ||
| 750 | + summary={t("settings.title")} | ||
| 751 | + variant="destructive" | ||
| 752 | + icon={<IconAlert class="h-4 w-4" />} | ||
| 753 | + confirmLabel={t("notes.leaveConfirm")} | ||
| 754 | + onConfirm={() => { | ||
| 755 | + leaving = true; | ||
| 756 | + blocker().proceed?.(); | ||
| 757 | + }} | ||
| 758 | + /> | ||
| 707 | </div> | 759 | </div> |
| 708 | ); | 760 | ); |
| 709 | } | 761 | } |
| 710 | 762 | ||
| 763 | +/** The display name of a seeded key (e.g. "breakfast" → "Kahvaltı"), shown | ||
| 764 | + * beside the editable key; nothing for a key that has no separate label. */ | ||
| 765 | +function KeyLabelHint(props: { value: string; label: string }) { | ||
| 766 | + return ( | ||
| 767 | + <Show when={props.label !== props.value.trim()}> | ||
| 768 | + <span class="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{props.label}</span> | ||
| 769 | + </Show> | ||
| 770 | + ); | ||
| 771 | +} | ||
| 772 | + | ||
| 711 | function EmptyRows(props: { label: string }) { | 773 | function EmptyRows(props: { label: string }) { |
| 712 | return ( | 774 | return ( |
| 713 | <div class="rounded-lg border border-dashed border-border/80 bg-muted/15 px-3 py-8 text-center text-xs text-muted-foreground"> | 775 | <div class="rounded-lg border border-dashed border-border/80 bg-muted/15 px-3 py-8 text-center text-xs text-muted-foreground"> |
src/pages/student-attendance-page.tsxmodified+26 -1
| @@ -9,6 +9,7 @@ import { RouteGuard } from "@/components/layout/route-guard"; | |||
| 9 | import { Alert } from "@/components/ui/alert"; | 9 | import { Alert } from "@/components/ui/alert"; |
| 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 11 | import { ErrorAlert } from "@/components/ui/error-alert"; | 11 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 12 | +import { DropdownSelect } from "@/components/ui/select"; | ||
| 12 | import { IconEye } from "@/components/ui/icons"; | 13 | import { IconEye } from "@/components/ui/icons"; |
| 13 | import { SidePanel } from "@/components/ui/side-panel"; | 14 | import { SidePanel } from "@/components/ui/side-panel"; |
| 14 | import { studentDirectoryColumns } from "@/components/users/student-directory-columns"; | 15 | import { studentDirectoryColumns } from "@/components/users/student-directory-columns"; |
| @@ -60,7 +61,19 @@ function StudentAttendanceContent() { | |||
| 60 | }, | 61 | }, |
| 61 | ); | 62 | ); |
| 62 | 63 | ||
| 63 | - const rows = () => list(); | 64 | + // No endpoint reports attendance or focus time for a list of students — |
| 65 | + // only one student at a time — so the list stays a roster (a column per | ||
| 66 | + // student would be one report read per row). The class filter narrows it | ||
| 67 | + // with the memberships the directory already read. | ||
| 68 | + const [classFilter, setClassFilter] = createSignal(""); | ||
| 69 | + const classOptions = createMemo(() => { | ||
| 70 | + const seen = new Map<string, string>(); | ||
| 71 | + for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); | ||
| 72 | + return [...seen] | ||
| 73 | + .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) | ||
| 74 | + .map(([value, label]) => ({ value, label })); | ||
| 75 | + }); | ||
| 76 | + const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); | ||
| 64 | const listLoading = () => list.loading; | 77 | const listLoading = () => list.loading; |
| 65 | const searchPerson = (row: StudentDirectoryRow, query: string) => | 78 | const searchPerson = (row: StudentDirectoryRow, query: string) => |
| 66 | matchesSearch(query, row.person.display_name, row.person.student_number, ...row.classes.map((cls) => cls.name)); | 79 | matchesSearch(query, row.person.display_name, row.person.student_number, ...row.classes.map((cls) => cls.name)); |
| @@ -100,6 +113,7 @@ function StudentAttendanceContent() { | |||
| 100 | 113 | ||
| 101 | <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}> | 114 | <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}> |
| 102 | <DataTable | 115 | <DataTable |
| 116 | + urlState | ||
| 103 | title={t("nav.studentAttendance")} | 117 | title={t("nav.studentAttendance")} |
| 104 | description={t("attendance.lookup")} | 118 | description={t("attendance.lookup")} |
| 105 | columns={columns()} | 119 | columns={columns()} |
| @@ -107,6 +121,17 @@ function StudentAttendanceContent() { | |||
| 107 | tableClass="min-w-xl" | 121 | tableClass="min-w-xl" |
| 108 | empty={t("form.noStudents")} | 122 | empty={t("form.noStudents")} |
| 109 | searchPredicate={searchPerson} | 123 | searchPredicate={searchPerson} |
| 124 | + filters={ | ||
| 125 | + <DropdownSelect | ||
| 126 | + labelPrefix={t("roster.class")} | ||
| 127 | + value={classFilter()} | ||
| 128 | + onChange={setClassFilter} | ||
| 129 | + options={[{ value: "", label: t("common.all") }, ...classOptions()]} | ||
| 130 | + /> | ||
| 131 | + } | ||
| 132 | + filtersActive={classFilter() !== ""} | ||
| 133 | + pageResetKey={classFilter()} | ||
| 134 | + onClearFilters={() => setClassFilter("")} | ||
| 110 | filterHint={t("search.hint.people")} | 135 | filterHint={t("search.hint.people")} |
| 111 | enablePagination | 136 | enablePagination |
| 112 | pageSize={PAGE_SIZE} | 137 | pageSize={PAGE_SIZE} |
src/pages/student-marks-page.tsxmodified+29 -13
| @@ -18,10 +18,10 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; | |||
| 18 | import { matchesSearch } from "@/lib/search-text"; | 18 | import { matchesSearch } from "@/lib/search-text"; |
| 19 | import { personLabel } from "@/lib/person"; | 19 | import { personLabel } from "@/lib/person"; |
| 20 | import { getStudentDirectory, type StudentDirectoryRow } from "@/lib/student-directory"; | 20 | import { getStudentDirectory, type StudentDirectoryRow } from "@/lib/student-directory"; |
| 21 | -import { useT } from "@/stores/preferences-context"; | 21 | +import { usePreferences, useT } from "@/stores/preferences-context"; |
| 22 | +import { formatDecimal } from "@/lib/format"; | ||
| 22 | 23 | ||
| 23 | const PAGE_SIZE = 10; | 24 | const PAGE_SIZE = 10; |
| 24 | -const round = (n: number) => (Math.round(n * 100) / 100).toString(); | ||
| 25 | // ponytail: display-only color tiers (70/40 on a 0-100 scale), not a pass/fail rule | 25 | // ponytail: display-only color tiers (70/40 on a 0-100 scale), not a pass/fail rule |
| 26 | const avgTone = (v: number) => (v >= 70 ? "text-success-text" : v >= 40 ? "text-warning-text" : "text-destructive-text"); | 26 | const avgTone = (v: number) => (v >= 70 ? "text-success-text" : v >= 40 ? "text-warning-text" : "text-destructive-text"); |
| 27 | 27 | ||
| @@ -37,6 +37,7 @@ const MARKS_FETCH_CAP = 200; | |||
| 37 | 37 | ||
| 38 | function StudentMarksContent() { | 38 | function StudentMarksContent() { |
| 39 | const t = useT(); | 39 | const t = useT(); |
| 40 | + const { locale } = usePreferences(); | ||
| 40 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); | 41 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); |
| 41 | const [error, setError] = createSignal(""); | 42 | const [error, setError] = createSignal(""); |
| 42 | 43 | ||
| @@ -72,6 +73,10 @@ function StudentMarksContent() { | |||
| 72 | ); | 73 | ); |
| 73 | const marksCapped = () => list().length > MARKS_FETCH_CAP; | 74 | const marksCapped = () => list().length > MARKS_FETCH_CAP; |
| 74 | const marksOf = (id: string) => marksMapRes()?.[id]; | 75 | const marksOf = (id: string) => marksMapRes()?.[id]; |
| 76 | + const examCountOf = (id: string) => { | ||
| 77 | + const rep = marksOf(id); | ||
| 78 | + return rep ? rep.courses.reduce((sum, course) => sum + course.results.length, 0) : null; | ||
| 79 | + }; | ||
| 75 | 80 | ||
| 76 | const [report, { refetch: refetchReport }] = createResource( | 81 | const [report, { refetch: refetchReport }] = createResource( |
| 77 | () => viewUser()?.id ?? null, | 82 | () => viewUser()?.id ?? null, |
| @@ -110,18 +115,28 @@ function StudentMarksContent() { | |||
| 110 | accessorFn: (row) => marksOf(row.person.id)?.overall_average ?? -1, | 115 | accessorFn: (row) => marksOf(row.person.id)?.overall_average ?? -1, |
| 111 | meta: { align: "right" }, | 116 | meta: { align: "right" }, |
| 112 | cell: (cell) => { | 117 | cell: (cell) => { |
| 113 | - const rep = marksOf(cell.row.original.person.id); | 118 | + const average = marksOf(cell.row.original.person.id)?.overall_average; |
| 114 | - if (rep == null) return <span class="text-sm text-muted-foreground">—</span>; | 119 | + if (average == null) return <span class="text-sm text-muted-foreground">—</span>; |
| 115 | - if (rep.overall_average == null) | 120 | + return <span class={cn("font-semibold tabular-nums", avgTone(average))}>{formatDecimal(average, locale())}</span>; |
| 116 | - return <span class="text-sm text-muted-foreground">{rep.overall_grade ?? "—"}</span>; | ||
| 117 | - return ( | ||
| 118 | - <span class={cn("font-semibold tabular-nums", avgTone(rep.overall_average))}> | ||
| 119 | - {round(rep.overall_average)} | ||
| 120 | - <Show when={rep.overall_grade}>{(g) => <span class="ml-1 font-medium text-muted-foreground">/ {g()}</span>}</Show> | ||
| 121 | - </span> | ||
| 122 | - ); | ||
| 123 | }, | 121 | }, |
| 124 | }, | 122 | }, |
| 123 | + // The school's grade-band label for that average — its own column, since | ||
| 124 | + // "68,19 / 3" beside the average read as a score out of 3. | ||
| 125 | + { | ||
| 126 | + id: "grade", | ||
| 127 | + header: t("marks.band"), | ||
| 128 | + accessorFn: (row) => marksOf(row.person.id)?.overall_grade ?? "", | ||
| 129 | + meta: { align: "right" }, | ||
| 130 | + cell: (cell) => <span class="tabular-nums text-muted-foreground">{marksOf(cell.row.original.person.id)?.overall_grade ?? "—"}</span>, | ||
| 131 | + }, | ||
| 132 | + // Graded exams behind the average, counted from the same report. | ||
| 133 | + { | ||
| 134 | + id: "exams", | ||
| 135 | + header: t("marks.examCount"), | ||
| 136 | + accessorFn: (row) => examCountOf(row.person.id) ?? -1, | ||
| 137 | + meta: { align: "right" }, | ||
| 138 | + cell: (cell) => <span class="tabular-nums text-muted-foreground">{examCountOf(cell.row.original.person.id) ?? "—"}</span>, | ||
| 139 | + }, | ||
| 125 | { | 140 | { |
| 126 | id: "actions", | 141 | id: "actions", |
| 127 | header: t("common.actions"), | 142 | header: t("common.actions"), |
| @@ -158,8 +173,9 @@ function StudentMarksContent() { | |||
| 158 | <Alert role="status">{t("marks.averageCapped", { cap: MARKS_FETCH_CAP })}</Alert> | 173 | <Alert role="status">{t("marks.averageCapped", { cap: MARKS_FETCH_CAP })}</Alert> |
| 159 | </Show> | 174 | </Show> |
| 160 | 175 | ||
| 161 | - <Show when={!listLoading()} fallback={<DataTableSkeleton columns={5} rows={6} />}> | 176 | + <Show when={!listLoading()} fallback={<DataTableSkeleton columns={7} rows={6} />}> |
| 162 | <DataTable | 177 | <DataTable |
| 178 | + urlState | ||
| 163 | title={t("nav.studentMarks")} | 179 | title={t("nav.studentMarks")} |
| 164 | description={t("marks.lookup")} | 180 | description={t("marks.lookup")} |
| 165 | columns={columns()} | 181 | columns={columns()} |
src/pages/student-pomodoro-page.tsxmodified+26 -1
| @@ -9,6 +9,7 @@ import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; | |||
| 9 | import { Alert } from "@/components/ui/alert"; | 9 | import { Alert } from "@/components/ui/alert"; |
| 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 10 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 11 | import { ErrorAlert } from "@/components/ui/error-alert"; | 11 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 12 | +import { DropdownSelect } from "@/components/ui/select"; | ||
| 12 | import { IconEye } from "@/components/ui/icons"; | 13 | import { IconEye } from "@/components/ui/icons"; |
| 13 | import { SidePanel } from "@/components/ui/side-panel"; | 14 | import { SidePanel } from "@/components/ui/side-panel"; |
| 14 | import { studentDirectoryColumns } from "@/components/users/student-directory-columns"; | 15 | import { studentDirectoryColumns } from "@/components/users/student-directory-columns"; |
| @@ -60,7 +61,19 @@ function StudentPomodoroContent() { | |||
| 60 | }, | 61 | }, |
| 61 | ); | 62 | ); |
| 62 | 63 | ||
| 63 | - const rows = () => list(); | 64 | + // No endpoint reports attendance or focus time for a list of students — |
| 65 | + // only one student at a time — so the list stays a roster (a column per | ||
| 66 | + // student would be one report read per row). The class filter narrows it | ||
| 67 | + // with the memberships the directory already read. | ||
| 68 | + const [classFilter, setClassFilter] = createSignal(""); | ||
| 69 | + const classOptions = createMemo(() => { | ||
| 70 | + const seen = new Map<string, string>(); | ||
| 71 | + for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); | ||
| 72 | + return [...seen] | ||
| 73 | + .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) | ||
| 74 | + .map(([value, label]) => ({ value, label })); | ||
| 75 | + }); | ||
| 76 | + const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); | ||
| 64 | const listLoading = () => list.loading; | 77 | const listLoading = () => list.loading; |
| 65 | const searchPerson = (row: StudentDirectoryRow, query: string) => | 78 | const searchPerson = (row: StudentDirectoryRow, query: string) => |
| 66 | matchesSearch(query, row.person.display_name, row.person.student_number, ...row.classes.map((cls) => cls.name)); | 79 | matchesSearch(query, row.person.display_name, row.person.student_number, ...row.classes.map((cls) => cls.name)); |
| @@ -97,6 +110,7 @@ function StudentPomodoroContent() { | |||
| 97 | 110 | ||
| 98 | <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}> | 111 | <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}> |
| 99 | <DataTable | 112 | <DataTable |
| 113 | + urlState | ||
| 100 | title={t("nav.studentPomodoro")} | 114 | title={t("nav.studentPomodoro")} |
| 101 | description={t("pomodoro.lookup")} | 115 | description={t("pomodoro.lookup")} |
| 102 | columns={studentColumns()} | 116 | columns={studentColumns()} |
| @@ -104,6 +118,17 @@ function StudentPomodoroContent() { | |||
| 104 | tableClass="min-w-xl" | 118 | tableClass="min-w-xl" |
| 105 | empty={t("form.noStudents")} | 119 | empty={t("form.noStudents")} |
| 106 | searchPredicate={searchPerson} | 120 | searchPredicate={searchPerson} |
| 121 | + filters={ | ||
| 122 | + <DropdownSelect | ||
| 123 | + labelPrefix={t("roster.class")} | ||
| 124 | + value={classFilter()} | ||
| 125 | + onChange={setClassFilter} | ||
| 126 | + options={[{ value: "", label: t("common.all") }, ...classOptions()]} | ||
| 127 | + /> | ||
| 128 | + } | ||
| 129 | + filtersActive={classFilter() !== ""} | ||
| 130 | + pageResetKey={classFilter()} | ||
| 131 | + onClearFilters={() => setClassFilter("")} | ||
| 107 | filterHint={t("search.hint.people")} | 132 | filterHint={t("search.hint.people")} |
| 108 | enablePagination | 133 | enablePagination |
| 109 | pageSize={PAGE_SIZE} | 134 | pageSize={PAGE_SIZE} |
src/pages/students-roster-page.tsxmodified+17 -12
| @@ -3,6 +3,7 @@ import type { ColumnDef } from "@tanstack/solid-table"; | |||
| 3 | import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; | 3 | import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; |
| 4 | import { createResource } from "@/lib/create-resource"; | 4 | import { createResource } from "@/lib/create-resource"; |
| 5 | import { matchesSearch } from "@/lib/search-text"; | 5 | import { matchesSearch } from "@/lib/search-text"; |
| 6 | +import { createUrlString } from "@/lib/url-state"; | ||
| 6 | import { getClassMembers, getClasses } from "@/api/classes"; | 7 | import { getClassMembers, getClasses } from "@/api/classes"; |
| 7 | import { getAcademicYears } from "@/api/academic-years"; | 8 | import { getAcademicYears } from "@/api/academic-years"; |
| 8 | import { getUserSearch } from "@/api/users"; | 9 | import { getUserSearch } from "@/api/users"; |
| @@ -11,7 +12,7 @@ import { RouteGuard } from "@/components/layout/route-guard"; | |||
| 11 | import { CreateUserPanel } from "@/components/users/create-user-panel"; | 12 | import { CreateUserPanel } from "@/components/users/create-user-panel"; |
| 12 | import { RosterPersonCell } from "@/components/users/roster-person-cell"; | 13 | import { RosterPersonCell } from "@/components/users/roster-person-cell"; |
| 13 | import { Button } from "@/components/ui/button"; | 14 | import { Button } from "@/components/ui/button"; |
| 14 | -import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; | 15 | +import { ComingSoonBadge } from "@/components/ui/coming-soon"; |
| 15 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 16 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 16 | import { ErrorAlert } from "@/components/ui/error-alert"; | 17 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 17 | import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; | 18 | import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; |
| @@ -33,15 +34,16 @@ export default function StudentsRosterPage() { | |||
| 33 | ); | 34 | ); |
| 34 | } | 35 | } |
| 35 | 36 | ||
| 36 | -// ADM-02. The roster, class and term are real; topic mastery, plan adherence | 37 | +// ADM-02. The roster, class and term are real. Topic mastery, plan adherence |
| 37 | -// and the risk status are AI/analytics fields no endpoint serves, so their | 38 | +// and the risk status are AI/analytics fields no endpoint serves, and a |
| 38 | -// columns keep the design's slot and say "yakında" instead of a number. | 39 | +// per-student attendance rate would cost one report read per row, so those |
| 40 | +// design columns are left out rather than filled with "yakında". | ||
| 39 | function StudentsRosterContent() { | 41 | function StudentsRosterContent() { |
| 40 | const t = useT(); | 42 | const t = useT(); |
| 41 | const auth = useAuth(); | 43 | const auth = useAuth(); |
| 42 | const navigate = useNavigate(); | 44 | const navigate = useNavigate(); |
| 43 | - const [classFilter, setClassFilter] = createSignal(""); | 45 | + const [classFilter, setClassFilter] = createUrlString("class"); |
| 44 | - const [yearFilter, setYearFilter] = createSignal(""); | 46 | + const [yearFilter, setYearFilter] = createUrlString("year"); |
| 45 | const [creating, setCreating] = createSignal(false); | 47 | const [creating, setCreating] = createSignal(false); |
| 46 | 48 | ||
| 47 | const [data, { refetch }] = createResource(async () => { | 49 | const [data, { refetch }] = createResource(async () => { |
| @@ -87,10 +89,6 @@ function StudentsRosterContent() { | |||
| 87 | <span class="truncate text-sm">{cell.row.original.classes.map((cls) => cls.name).join(", ") || "—"}</span> | 89 | <span class="truncate text-sm">{cell.row.original.classes.map((cls) => cls.name).join(", ") || "—"}</span> |
| 88 | ), | 90 | ), |
| 89 | }, | 91 | }, |
| 90 | - { id: "mastery", size: 130, header: t("roster.mastery"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 91 | - { id: "attendance", size: 130, header: t("roster.attendance"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 92 | - { id: "plan", size: 130, header: t("roster.planAdherence"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 93 | - { id: "status", size: 130, header: t("roster.status"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 94 | { | 92 | { |
| 95 | id: "actions", | 93 | id: "actions", |
| 96 | header: t("common.actions"), | 94 | header: t("common.actions"), |
| @@ -122,13 +120,20 @@ function StudentsRosterContent() { | |||
| 122 | 120 | ||
| 123 | 121 | ||
| 124 | <section class="space-y-4 p-0"> | 122 | <section class="space-y-4 p-0"> |
| 125 | - <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}> | 123 | + <Suspense fallback={<DataTableSkeleton columns={3} rows={8} />}> |
| 126 | <Show when={data.error}> | 124 | <Show when={data.error}> |
| 127 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> | 125 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> |
| 128 | </Show> | 126 | </Show> |
| 129 | <Show when={!data.error && data()}> | 127 | <Show when={!data.error && data()}> |
| 130 | {(value) => ( | 128 | {(value) => ( |
| 131 | <DataTable | 129 | <DataTable |
| 130 | + urlState | ||
| 131 | + pageResetKey={`${classFilter()}|${yearFilter()}`} | ||
| 132 | + filtersActive={classFilter() !== "" || yearFilter() !== ""} | ||
| 133 | + onClearFilters={() => { | ||
| 134 | + setClassFilter(""); | ||
| 135 | + setYearFilter(""); | ||
| 136 | + }} | ||
| 132 | surfaceSections | 137 | surfaceSections |
| 133 | title={t("nav.studentsRoster")} | 138 | title={t("nav.studentsRoster")} |
| 134 | description={t("roster.studentsSubtitle")} | 139 | description={t("roster.studentsSubtitle")} |
| @@ -145,7 +150,7 @@ function StudentsRosterContent() { | |||
| 145 | </Show></>} | 150 | </Show></>} |
| 146 | columns={columns()} | 151 | columns={columns()} |
| 147 | data={rows()} | 152 | data={rows()} |
| 148 | - tableClass="min-w-[52rem]" | 153 | + tableClass="min-w-xl" |
| 149 | empty={t("form.noStudents")} | 154 | empty={t("form.noStudents")} |
| 150 | filterPlaceholder={t("roster.searchStudents")} | 155 | filterPlaceholder={t("roster.searchStudents")} |
| 151 | filterHint={t("search.hint.students")} | 156 | filterHint={t("search.hint.students")} |
src/pages/teachers-roster-page.tsxmodified+63 -23
| @@ -3,14 +3,17 @@ import type { ColumnDef } from "@tanstack/solid-table"; | |||
| 3 | import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; | 3 | import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; |
| 4 | import { createResource } from "@/lib/create-resource"; | 4 | import { createResource } from "@/lib/create-resource"; |
| 5 | import { matchesSearch } from "@/lib/search-text"; | 5 | import { matchesSearch } from "@/lib/search-text"; |
| 6 | -import { getClasses } from "@/api/classes"; | 6 | +import { getClassInstances, getClasses } from "@/api/classes"; |
| 7 | +import { getCourses } from "@/api/courses"; | ||
| 7 | import { getUserSearch } from "@/api/users"; | 8 | import { getUserSearch } from "@/api/users"; |
| 8 | -import { formatApiError, type PersonRef } from "@/api/client"; | 9 | +import { formatApiError, type Course, type PersonRef } from "@/api/client"; |
| 10 | +import { formatInstanceLabel } from "@/lib/instance-labels"; | ||
| 11 | +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; | ||
| 9 | import { RouteGuard } from "@/components/layout/route-guard"; | 12 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 10 | import { CreateUserPanel } from "@/components/users/create-user-panel"; | 13 | import { CreateUserPanel } from "@/components/users/create-user-panel"; |
| 11 | import { RosterPersonCell } from "@/components/users/roster-person-cell"; | 14 | import { RosterPersonCell } from "@/components/users/roster-person-cell"; |
| 12 | import { Button } from "@/components/ui/button"; | 15 | import { Button } from "@/components/ui/button"; |
| 13 | -import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; | 16 | +import { ComingSoonBadge } from "@/components/ui/coming-soon"; |
| 14 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | 17 | import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; |
| 15 | import { ErrorAlert } from "@/components/ui/error-alert"; | 18 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| 16 | import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; | 19 | import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; |
| @@ -21,7 +24,13 @@ import { useAuth } from "@/stores/auth-context"; | |||
| 21 | 24 | ||
| 22 | const ROSTER_PAGE_SIZE = 10; | 25 | const ROSTER_PAGE_SIZE = 10; |
| 23 | 26 | ||
| 24 | -type TeacherRow = { person: PersonRef; homeroomClasses: number }; | 27 | +type TeacherRow = { |
| 28 | + person: PersonRef; | ||
| 29 | + /** Classes this teacher is the homeroom teacher (sınıf öğretmeni) of. */ | ||
| 30 | + homeroom: string[]; | ||
| 31 | + /** The sections they teach, as "<ders> — <şube>". */ | ||
| 32 | + sections: string[]; | ||
| 33 | +}; | ||
| 25 | 34 | ||
| 26 | export default function TeachersRosterPage() { | 35 | export default function TeachersRosterPage() { |
| 27 | return ( | 36 | return ( |
| @@ -31,9 +40,11 @@ export default function TeachersRosterPage() { | |||
| 31 | ); | 40 | ); |
| 32 | } | 41 | } |
| 33 | 42 | ||
| 34 | -// ADM-08. "Sınıf" is the number of classes the teacher is homeroom teacher of | 43 | +// ADM-08. Two real columns: the classes a teacher is homeroom teacher of |
| 35 | -// (ClassGroup.teacher); branch, weekly load, AI acceptance and employment | 44 | +// (ClassGroup.teacher) and the sections they teach (Instance.teachers, read |
| 36 | -// status have no field anywhere, so they stay "yakında". | 45 | +// one `/classes/{id}/instances` page per class — bounded by the class count, |
| 46 | +// not the teacher count). Branch, weekly load, AI acceptance and employment | ||
| 47 | +// status have no field anywhere, so those design columns are left out. | ||
| 37 | function TeachersRosterContent() { | 48 | function TeachersRosterContent() { |
| 38 | const t = useT(); | 49 | const t = useT(); |
| 39 | const auth = useAuth(); | 50 | const auth = useAuth(); |
| @@ -41,29 +52,57 @@ function TeachersRosterContent() { | |||
| 41 | const [creating, setCreating] = createSignal(false); | 52 | const [creating, setCreating] = createSignal(false); |
| 42 | 53 | ||
| 43 | const [data, { refetch }] = createResource(async () => { | 54 | const [data, { refetch }] = createResource(async () => { |
| 44 | - const [teachers, classes] = await Promise.all([getUserSearch("", undefined, "teacher"), getClasses()]); | 55 | + const [teachers, classes, courses] = await Promise.all([ |
| 45 | - const homeroom = new Map<string, number>(); | 56 | + getUserSearch("", undefined, "teacher"), |
| 46 | - for (const cls of classes.items) { | 57 | + getClasses(), |
| 47 | - if (cls.teacher) homeroom.set(cls.teacher.id, (homeroom.get(cls.teacher.id) ?? 0) + 1); | 58 | + getCourses().catch(() => ({ items: [] as Course[] })), |
| 59 | + ]); | ||
| 60 | + const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); | ||
| 61 | + const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); | ||
| 62 | + const homeroom = new Map<string, string[]>(); | ||
| 63 | + for (const cls of classes.items) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name); | ||
| 64 | + const titles = new Map(courses.items.map((course) => [course.id, course.title])); | ||
| 65 | + const perClass = await mapConcurrent(classes.items, FAN_OUT_LIMIT, async (cls) => ({ | ||
| 66 | + cls, | ||
| 67 | + // One unreadable class must not empty the whole column. | ||
| 68 | + instances: await getClassInstances(cls.id).then((page) => page.items, () => []), | ||
| 69 | + })); | ||
| 70 | + const sections = new Map<string, string[]>(); | ||
| 71 | + for (const { cls, instances } of perClass) { | ||
| 72 | + for (const instance of instances) { | ||
| 73 | + const label = formatInstanceLabel(titles.get(instance.course) ?? null, cls.name); | ||
| 74 | + for (const teacher of instance.teachers) push(sections, teacher.id, label); | ||
| 75 | + } | ||
| 48 | } | 76 | } |
| 49 | - return teachers.items.map<TeacherRow>((person) => ({ person, homeroomClasses: homeroom.get(person.id) ?? 0 })); | 77 | + return teachers.items.map<TeacherRow>((person) => ({ |
| 78 | + person, | ||
| 79 | + homeroom: (homeroom.get(person.id) ?? []).sort(byName), | ||
| 80 | + sections: [...new Set(sections.get(person.id) ?? [])].sort(byName), | ||
| 81 | + })); | ||
| 50 | }); | 82 | }); |
| 51 | 83 | ||
| 52 | const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); | 84 | const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); |
| 53 | 85 | ||
| 54 | const columns = createMemo<ColumnDef<TeacherRow>[]>(() => [ | 86 | const columns = createMemo<ColumnDef<TeacherRow>[]>(() => [ |
| 55 | { id: "teacher", size: 220, header: t("roster.teacher"), cell: (cell) => <RosterPersonCell person={cell.row.original.person} /> }, | 87 | { id: "teacher", size: 220, header: t("roster.teacher"), cell: (cell) => <RosterPersonCell person={cell.row.original.person} /> }, |
| 56 | - { id: "branch", size: 130, header: t("roster.branch"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 57 | { | 88 | { |
| 58 | - accessorKey: "homeroomClasses", | 89 | + id: "sections", |
| 59 | - size: 90, | 90 | + size: 260, |
| 60 | - header: t("roster.class"), | 91 | + accessorFn: (row) => row.sections.length, |
| 61 | - meta: { cellClass: "tabular-nums" }, | 92 | + header: t("roster.taughtSections"), |
| 62 | - cell: (cell) => (cell.row.original.homeroomClasses > 0 ? cell.row.original.homeroomClasses : "—"), | 93 | + meta: { cellClass: "max-w-0" }, |
| 94 | + cell: (cell) => { | ||
| 95 | + const list = cell.row.original.sections; | ||
| 96 | + return list.length ? <span class="block truncate text-sm" title={list.join("\n")}>{list.join(", ")}</span> : "—"; | ||
| 97 | + }, | ||
| 98 | + }, | ||
| 99 | + { | ||
| 100 | + id: "homeroom", | ||
| 101 | + size: 130, | ||
| 102 | + accessorFn: (row) => row.homeroom.join(", "), | ||
| 103 | + header: t("roster.homeroomOf"), | ||
| 104 | + cell: (cell) => <span class="truncate text-sm">{cell.row.original.homeroom.join(", ") || "—"}</span>, | ||
| 63 | }, | 105 | }, |
| 64 | - { id: "weekly", size: 130, header: t("roster.weeklyLessons"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 65 | - { id: "acceptance", size: 130, header: t("roster.suggestionAcceptance"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 66 | - { id: "status", size: 130, header: t("roster.status"), enableSorting: false, meta: { hideInCards: true }, cell: () => <ComingSoonValue /> }, | ||
| 67 | { | 106 | { |
| 68 | id: "actions", | 107 | id: "actions", |
| 69 | header: t("common.actions"), | 108 | header: t("common.actions"), |
| @@ -95,13 +134,14 @@ function TeachersRosterContent() { | |||
| 95 | 134 | ||
| 96 | 135 | ||
| 97 | <section class="space-y-4 p-0"> | 136 | <section class="space-y-4 p-0"> |
| 98 | - <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}> | 137 | + <Suspense fallback={<DataTableSkeleton columns={4} rows={8} />}> |
| 99 | <Show when={data.error}> | 138 | <Show when={data.error}> |
| 100 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> | 139 | <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} /> |
| 101 | </Show> | 140 | </Show> |
| 102 | <Show when={!data.error && data()}> | 141 | <Show when={!data.error && data()}> |
| 103 | {(rows) => ( | 142 | {(rows) => ( |
| 104 | <DataTable | 143 | <DataTable |
| 144 | + urlState | ||
| 105 | surfaceSections | 145 | surfaceSections |
| 106 | title={t("nav.teachersRoster")} | 146 | title={t("nav.teachersRoster")} |
| 107 | description={t("roster.teachersSubtitle")} | 147 | description={t("roster.teachersSubtitle")} |
| @@ -118,7 +158,7 @@ function TeachersRosterContent() { | |||
| 118 | </Show></>} | 158 | </Show></>} |
| 119 | columns={columns()} | 159 | columns={columns()} |
| 120 | data={rows()} | 160 | data={rows()} |
| 121 | - tableClass="min-w-[52rem]" | 161 | + tableClass="min-w-2xl" |
| 122 | empty={t("roster.noTeachers")} | 162 | empty={t("roster.noTeachers")} |
| 123 | filterPlaceholder={t("roster.searchTeachers")} | 163 | filterPlaceholder={t("roster.searchTeachers")} |
| 124 | filterHint={t("search.hint.teachers")} | 164 | filterHint={t("search.hint.teachers")} |
src/pages/terms-page.tsxmodified+4 -3
| @@ -25,7 +25,7 @@ import { Select } from "@/components/ui/select"; | |||
| 25 | import { SidePanel } from "@/components/ui/side-panel"; | 25 | import { SidePanel } from "@/components/ui/side-panel"; |
| 26 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 26 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 27 | import { createFlash } from "@/lib/flash"; | 27 | import { createFlash } from "@/lib/flash"; |
| 28 | -import { formatDateTime } from "@/lib/format"; | 28 | +import { formatDate } from "@/lib/format"; |
| 29 | import { usePreferences, useT } from "@/stores/preferences-context"; | 29 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 30 | 30 | ||
| 31 | const TERM_PAGE_SIZE = 10; | 31 | const TERM_PAGE_SIZE = 10; |
| @@ -100,7 +100,7 @@ function TermsContent() { | |||
| 100 | size: 150, | 100 | size: 150, |
| 101 | minSize: 145, | 101 | minSize: 145, |
| 102 | meta: { cellClass: "whitespace-nowrap" }, | 102 | meta: { cellClass: "whitespace-nowrap" }, |
| 103 | - cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDateTime(cell.row.original.starts_at, locale())}</span>, | 103 | + cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDate(cell.row.original.starts_at, locale())}</span>, |
| 104 | }, | 104 | }, |
| 105 | { | 105 | { |
| 106 | accessorKey: "ends_at", | 106 | accessorKey: "ends_at", |
| @@ -108,7 +108,7 @@ function TermsContent() { | |||
| 108 | size: 150, | 108 | size: 150, |
| 109 | minSize: 145, | 109 | minSize: 145, |
| 110 | meta: { cellClass: "whitespace-nowrap" }, | 110 | meta: { cellClass: "whitespace-nowrap" }, |
| 111 | - cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDateTime(cell.row.original.ends_at, locale())}</span>, | 111 | + cell: (cell) => <span class="whitespace-nowrap text-sm">{formatDate(cell.row.original.ends_at, locale())}</span>, |
| 112 | }, | 112 | }, |
| 113 | { | 113 | { |
| 114 | accessorKey: "archived_at", | 114 | accessorKey: "archived_at", |
| @@ -247,6 +247,7 @@ function TermsContent() { | |||
| 247 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> | 247 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> |
| 248 | </Show> | 248 | </Show> |
| 249 | <DataTable | 249 | <DataTable |
| 250 | + urlState | ||
| 250 | title={t("terms.title")} | 251 | title={t("terms.title")} |
| 251 | description={t("terms.subtitle")} | 252 | description={t("terms.subtitle")} |
| 252 | actions={ | 253 | actions={ |
src/pages/work-log-page.tsxmodified+1 -0
| @@ -118,6 +118,7 @@ function WorkLogContent() { | |||
| 118 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> | 118 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> |
| 119 | </Show> | 119 | </Show> |
| 120 | <DataTable | 120 | <DataTable |
| 121 | + urlState | ||
| 121 | title={t("work.entries")} | 122 | title={t("work.entries")} |
| 122 | description={t("work.ready")} | 123 | description={t("work.ready")} |
| 123 | columns={columns()} | 124 | columns={columns()} |
src/routes/router.tsxmodified+4 -0
| @@ -200,6 +200,10 @@ const coursesRoute = createRoute({ | |||
| 200 | validateSearch: (search: Record<string, unknown>) => ({ | 200 | validateSearch: (search: Record<string, unknown>) => ({ |
| 201 | action: search.action === "new" ? "new" : undefined, | 201 | action: search.action === "new" ? "new" : undefined, |
| 202 | kind: search.kind === "course" || search.kind === "study" || search.kind === "club" ? search.kind : undefined, | 202 | kind: search.kind === "course" || search.kind === "study" || search.kind === "club" ? search.kind : undefined, |
| 203 | + // List state (see src/lib/url-state.ts); declared so validation keeps it. | ||
| 204 | + q: typeof search.q === "string" || typeof search.q === "number" ? String(search.q) : undefined, | ||
| 205 | + page: typeof search.page === "number" && search.page > 1 ? search.page : undefined, | ||
| 206 | + taught: search.taught === "taught" || search.taught === "untaught" ? search.taught : undefined, | ||
| 203 | }), | 207 | }), |
| 204 | component: CoursesPage, | 208 | component: CoursesPage, |
| 205 | }); | 209 | }); |
src/stores/quick-actions.tsadded+20 -0
| @@ -0,0 +1,20 @@ | |||
| 1 | +import { createSignal, onCleanup } from "solid-js"; | ||
| 2 | + | ||
| 3 | +// Surfaces that dock something at the bottom of a phone screen — the study | ||
| 4 | +// chat's composer, the message compose sheet — put the floating action button | ||
| 5 | +// away while they are up, the same way the shell's own overlays do. A count | ||
| 6 | +// rather than a flag, so two holders never release each other's hold. | ||
| 7 | +const [holds, setHolds] = createSignal(0); | ||
| 8 | + | ||
| 9 | +export const quickActionsSuppressed = () => holds() > 0; | ||
| 10 | + | ||
| 11 | +/** | ||
| 12 | + * Hide the phone quick-action button until the calling owner (component or | ||
| 13 | + * effect run) is disposed. Call it from a component body to hide for the | ||
| 14 | + * component's lifetime, or inside a `createEffect` branch to hide while a | ||
| 15 | + * condition holds. | ||
| 16 | + */ | ||
| 17 | +export function suppressQuickActions() { | ||
| 18 | + setHolds((count) => count + 1); | ||
| 19 | + onCleanup(() => setHolds((count) => count - 1)); | ||
| 20 | +} | ||