forge
Explore
Log in

Don't you dare go Hollow

🐛 add exam schedule date picker

Browse files at this commit

7c6d289819b8a8d8982585f773ce18da59294a12Burak BoduroğluParent: ae5b1f7
  • fix
    • 🐛 add exam schedule date picker
Show full message
fix: 🐛 add exam schedule date picker

- add a lightweight date picker for exam schedule dates

- open the picker from the date field itself

- keep separate date and time fields with faint example placeholders

- parse scheduled exam dates from the displayed day-first format

- remove unused datetime helper code
src/components/exams/exam-form.tsxmodified+61 -37
@@ -5,33 +5,53 @@ import type { Exam } from "@/api/types";
5 import { EXAM_KINDS, EXAM_MODES } from "@/api/types";5 import { EXAM_KINDS, EXAM_MODES } from "@/api/types";
6 import { Button } from "@/components/ui/button";6 import { Button } from "@/components/ui/button";
7 import { ConfirmDialog } from "@/components/ui/confirm-dialog";7 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
8+import { DatePicker } from "@/components/ui/date-picker";
8 import { IconSave } from "@/components/ui/icons";9 import { IconSave } from "@/components/ui/icons";
9 import { Input } from "@/components/ui/input";10 import { Input } from "@/components/ui/input";
10 import { Label } from "@/components/ui/label";11 import { Label } from "@/components/ui/label";
11 import { Select } from "@/components/ui/select";12 import { Select } from "@/components/ui/select";
12 import { Textarea } from "@/components/ui/textarea";13 import { Textarea } from "@/components/ui/textarea";
13 import { examKindLabel } from "@/lib/exam-labels";14 import { examKindLabel } from "@/lib/exam-labels";
14-import { dateTimeTextToMs, msToDateTimeText } from "@/lib/format";
15 import { useT } from "@/stores/preferences-context";15 import { useT } from "@/stores/preferences-context";
16 16
17 const UI_EXAM_KINDS = EXAM_KINDS.filter((kind) => kind !== "homework");17 const UI_EXAM_KINDS = EXAM_KINDS.filter((kind) => kind !== "homework");
18 18
19-function datePart(value: string): string {19+function dateInputFromMs(ms: number | null | undefined): string {
20- return value.split(" ")[0] ?? "";20+ if (ms == null) return "";
21+ const d = new Date(ms);
22+ const pad = (n: number) => String(n).padStart(2, "0");
23+ return `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()}`;
21 }24 }
22 25
23-function timePart(value: string): string {26+function timeInputFromMs(ms: number | null | undefined): string {
24- return value.split(" ")[1] ?? "";27+ if (ms == null) return "";
28+ const d = new Date(ms);
29+ const pad = (n: number) => String(n).padStart(2, "0");
30+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
25 }31 }
26 32
27-function withDate(value: string, date: string): string {33+function scheduleInputToMs(date: string, time: string): number | null {
28- const time = timePart(value);34+ const dateMatch = date.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
29- return time ? `${date} ${time}` : date;35+ const timeMatch = time.trim().match(/^(\d{2}):(\d{2})$/);
30-}36+ if (!dateMatch || !timeMatch) return null;
31-37+ const [, dayRaw, monthRaw, yearRaw] = dateMatch;
32-function withTime(value: string, time: string): string {38+ const [, hourRaw, minuteRaw] = timeMatch;
33- const date = datePart(value);39+ const day = Number(dayRaw);
34- return date ? `${date} ${time}` : time;40+ const month = Number(monthRaw);
41+ const year = Number(yearRaw);
42+ const hour = Number(hourRaw);
43+ const minute = Number(minuteRaw);
44+ const d = new Date(year, month - 1, day, hour, minute, 0, 0);
45+ if (
46+ d.getFullYear() !== year ||
47+ d.getMonth() !== month - 1 ||
48+ d.getDate() !== day ||
49+ d.getHours() !== hour ||
50+ d.getMinutes() !== minute
51+ ) {
52+ return null;
53+ }
54+ return d.getTime();
35 }55 }
36 56
37 export type ExamFormValues = {57 export type ExamFormValues = {
@@ -57,8 +77,10 @@ export function ExamForm(props: {
57 const [kind, setKind] = createSignal(String(props.initial?.kind && props.initial.kind !== "homework" ? props.initial.kind : "quiz"));77 const [kind, setKind] = createSignal(String(props.initial?.kind && props.initial.kind !== "homework" ? props.initial.kind : "quiz"));
58 const [weight, setWeight] = createSignal(String(props.initial?.weight ?? 1));78 const [weight, setWeight] = createSignal(String(props.initial?.weight ?? 1));
59 const [mode, setMode] = createSignal(String(props.initial?.mode ?? ""));79 const [mode, setMode] = createSignal(String(props.initial?.mode ?? ""));
60- const [startsText, setStartsText] = createSignal(msToDateTimeText(props.initial?.starts_at));80+ const [startsDate, setStartsDate] = createSignal(dateInputFromMs(props.initial?.starts_at));
61- const [endsText, setEndsText] = createSignal(msToDateTimeText(props.initial?.ends_at));81+ const [startsTime, setStartsTime] = createSignal(timeInputFromMs(props.initial?.starts_at));
82+ const [endsDate, setEndsDate] = createSignal(dateInputFromMs(props.initial?.ends_at));
83+ const [endsTime, setEndsTime] = createSignal(timeInputFromMs(props.initial?.ends_at));
62 const [error, setError] = createSignal("");84 const [error, setError] = createSignal("");
63 const [pending, setPending] = createSignal(false);85 const [pending, setPending] = createSignal(false);
64 const [confirmOpen, setConfirmOpen] = createSignal(false);86 const [confirmOpen, setConfirmOpen] = createSignal(false);
@@ -96,8 +118,10 @@ export function ExamForm(props: {
96 setKind("quiz");118 setKind("quiz");
97 setWeight("1");119 setWeight("1");
98 setMode("");120 setMode("");
99- setStartsText("");121+ setStartsDate("");
100- setEndsText("");122+ setStartsTime("");
123+ setEndsDate("");
124+ setEndsTime("");
101 }125 }
102 } catch (err) {126 } catch (err) {
103 setError(formatApiError(err));127 setError(formatApiError(err));
@@ -108,8 +132,8 @@ export function ExamForm(props: {
108 132
109 const handleSubmit = async (e: SubmitEvent) => {133 const handleSubmit = async (e: SubmitEvent) => {
110 e.preventDefault();134 e.preventDefault();
111- const starts_at = mode() ? dateTimeTextToMs(startsText()) : null;135+ const starts_at = mode() ? scheduleInputToMs(startsDate(), startsTime()) : null;
112- const ends_at = mode() ? dateTimeTextToMs(endsText()) : null;136+ const ends_at = mode() ? scheduleInputToMs(endsDate(), endsTime()) : null;
113 const duration_ms = mode() === "async" && starts_at != null && ends_at != null ? ends_at - starts_at : null;137 const duration_ms = mode() === "async" && starts_at != null && ends_at != null ? ends_at - starts_at : null;
114 const v = validate(starts_at, ends_at, duration_ms);138 const v = validate(starts_at, ends_at, duration_ms);
115 if (v) {139 if (v) {
@@ -204,46 +228,46 @@ export function ExamForm(props: {
204 <div class="space-y-1.5">228 <div class="space-y-1.5">
205 <Label for="exam-starts">{t("events.starts")}</Label>229 <Label for="exam-starts">{t("events.starts")}</Label>
206 <div class="grid grid-cols-[minmax(0,1fr)_7rem] gap-2">230 <div class="grid grid-cols-[minmax(0,1fr)_7rem] gap-2">
207- <Input231+ <DatePicker
208 id="exam-starts"232 id="exam-starts"
209- class="rounded-sm"233+ placeholder={t("form.datePlaceholder")}
210- type="date"234+ value={startsDate()}
211- value={datePart(startsText())}
212 required235 required
213- onInput={(e) => setStartsText(withDate(startsText(), e.currentTarget.value))}236+ onChange={setStartsDate}
214 />237 />
215 <Input238 <Input
216 id="exam-starts-time"239 id="exam-starts-time"
217- class="rounded-sm font-mono"240+ class="rounded-sm font-mono placeholder:text-muted-foreground/45"
218- value={timePart(startsText())}241+ inputMode="numeric"
219 placeholder="14:30"242 placeholder="14:30"
220- required
221 pattern="[0-2][0-9]:[0-5][0-9]"243 pattern="[0-2][0-9]:[0-5][0-9]"
244+ value={startsTime()}
245+ required
222 aria-label={t("exams.startTime")}246 aria-label={t("exams.startTime")}
223- onInput={(e) => setStartsText(withTime(startsText(), e.currentTarget.value))}247+ onInput={(e) => setStartsTime(e.currentTarget.value)}
224 />248 />
225 </div>249 </div>
226 </div>250 </div>
227 <div class="space-y-1.5">251 <div class="space-y-1.5">
228 <Label for="exam-ends">{t("events.ends")}</Label>252 <Label for="exam-ends">{t("events.ends")}</Label>
229 <div class="grid grid-cols-[minmax(0,1fr)_7rem] gap-2">253 <div class="grid grid-cols-[minmax(0,1fr)_7rem] gap-2">
230- <Input254+ <DatePicker
231 id="exam-ends"255 id="exam-ends"
232- class="rounded-sm"256+ placeholder={t("form.datePlaceholder")}
233- type="date"257+ value={endsDate()}
234- value={datePart(endsText())}
235 required258 required
236- onInput={(e) => setEndsText(withDate(endsText(), e.currentTarget.value))}259+ onChange={setEndsDate}
237 />260 />
238 <Input261 <Input
239 id="exam-ends-time"262 id="exam-ends-time"
240- class="rounded-sm font-mono"263+ class="rounded-sm font-mono placeholder:text-muted-foreground/45"
241- value={timePart(endsText())}264+ inputMode="numeric"
242 placeholder="15:30"265 placeholder="15:30"
243- required
244 pattern="[0-2][0-9]:[0-5][0-9]"266 pattern="[0-2][0-9]:[0-5][0-9]"
267+ value={endsTime()}
268+ required
245 aria-label={t("exams.endTime")}269 aria-label={t("exams.endTime")}
246- onInput={(e) => setEndsText(withTime(endsText(), e.currentTarget.value))}270+ onInput={(e) => setEndsTime(e.currentTarget.value)}
247 />271 />
248 </div>272 </div>
249 </div>273 </div>
src/components/ui/date-picker.tsxadded+142 -0
@@ -0,0 +1,142 @@
1+import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2+import { Button } from "@/components/ui/button";
3+import { IconCalendar, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";
4+import { Input } from "@/components/ui/input";
5+import { cn } from "@/lib/cn";
6+
7+function pad(value: number): string {
8+ return String(value).padStart(2, "0");
9+}
10+
11+function formatDate(date: Date): string {
12+ return `${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${date.getFullYear()}`;
13+}
14+
15+function parseDate(value: string): Date | null {
16+ const match = value.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
17+ if (!match) return null;
18+ const [, dayRaw, monthRaw, yearRaw] = match;
19+ const day = Number(dayRaw);
20+ const month = Number(monthRaw);
21+ const year = Number(yearRaw);
22+ const date = new Date(year, month - 1, day);
23+ if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
24+ return date;
25+}
26+
27+function sameDay(a: Date | null, b: Date): boolean {
28+ return !!a && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
29+}
30+
31+function monthDays(month: Date): Array<Date | null> {
32+ const year = month.getFullYear();
33+ const monthIndex = month.getMonth();
34+ const first = new Date(year, monthIndex, 1);
35+ const days = new Date(year, monthIndex + 1, 0).getDate();
36+ const blanks = (first.getDay() + 6) % 7;
37+ const cells: Array<Date | null> = Array.from({ length: blanks }, () => null);
38+ for (let day = 1; day <= days; day += 1) cells.push(new Date(year, monthIndex, day));
39+ return cells;
40+}
41+
42+export function DatePicker(props: {
43+ id: string;
44+ value: string;
45+ placeholder: string;
46+ required?: boolean;
47+ class?: string;
48+ onChange: (value: string) => void;
49+}) {
50+ let root: HTMLDivElement | undefined;
51+ const [open, setOpen] = createSignal(false);
52+ const selected = createMemo(() => parseDate(props.value));
53+ const [month, setMonth] = createSignal(selected() ?? new Date());
54+ const days = createMemo(() => monthDays(month()));
55+ const monthLabel = createMemo(() =>
56+ new Intl.DateTimeFormat(undefined, { month: "long", year: "numeric" }).format(month()),
57+ );
58+
59+ createEffect(() => {
60+ const date = selected();
61+ if (date) setMonth(date);
62+ });
63+
64+ createEffect(() => {
65+ if (!open()) return;
66+ const closeOnOutside = (event: MouseEvent) => {
67+ if (root && !root.contains(event.target as Node)) setOpen(false);
68+ };
69+ document.addEventListener("mousedown", closeOnOutside);
70+ onCleanup(() => document.removeEventListener("mousedown", closeOnOutside));
71+ });
72+
73+ const moveMonth = (delta: number) => {
74+ setMonth((current) => new Date(current.getFullYear(), current.getMonth() + delta, 1));
75+ };
76+
77+ const pick = (date: Date) => {
78+ props.onChange(formatDate(date));
79+ setOpen(false);
80+ };
81+
82+ return (
83+ <div ref={root} class="relative">
84+ <div class="relative">
85+ <Input
86+ id={props.id}
87+ class={cn("rounded-sm pr-9 placeholder:text-muted-foreground/45", props.class)}
88+ inputMode="numeric"
89+ placeholder={props.placeholder}
90+ pattern="\d{2}/\d{2}/\d{4}"
91+ value={props.value}
92+ required={props.required}
93+ onFocus={() => setOpen(true)}
94+ onClick={() => setOpen(true)}
95+ onInput={(e) => props.onChange(e.currentTarget.value)}
96+ />
97+ <IconCalendar class="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
98+ </div>
99+ <Show when={open()}>
100+ <div class="absolute z-50 mt-2 w-72 rounded-md border bg-popover p-3 text-popover-foreground shadow-lg">
101+ <div class="mb-3 flex items-center justify-between gap-2">
102+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 p-0" onClick={() => moveMonth(-1)}>
103+ <IconChevronLeft class="h-4 w-4" />
104+ </Button>
105+ <p class="text-sm font-medium capitalize">{monthLabel()}</p>
106+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 p-0" onClick={() => moveMonth(1)}>
107+ <IconChevronRight class="h-4 w-4" />
108+ </Button>
109+ </div>
110+ <div class="grid grid-cols-7 gap-1 text-center text-[11px] font-medium text-muted-foreground">
111+ <span>Pzt</span>
112+ <span>Sal</span>
113+ <span>Çar</span>
114+ <span>Per</span>
115+ <span>Cum</span>
116+ <span>Cmt</span>
117+ <span>Paz</span>
118+ </div>
119+ <div class="mt-1 grid grid-cols-7 gap-1">
120+ <For each={days()}>
121+ {(date) => (
122+ <Show when={date} fallback={<span class="h-8" />}>
123+ {(day) => (
124+ <Button
125+ type="button"
126+ variant={sameDay(selected(), day()) ? "default" : "ghost"}
127+ size="sm"
128+ class="h-8 rounded-sm p-0 text-xs"
129+ onClick={() => pick(day())}
130+ >
131+ {day().getDate()}
132+ </Button>
133+ )}
134+ </Show>
135+ )}
136+ </For>
137+ </div>
138+ </div>
139+ </Show>
140+ </div>
141+ );
142+}
src/i18n/messages.tsmodified+3 -0
@@ -249,6 +249,7 @@ export type MessageKey =
249 | "form.year"249 | "form.year"
250 | "form.month"250 | "form.month"
251 | "form.day"251 | "form.day"
252+ | "form.datePlaceholder"
252 | "form.mark"253 | "form.mark"
253 | "form.studentId"254 | "form.studentId"
254 | "form.selectStudent"255 | "form.selectStudent"
@@ -613,6 +614,7 @@ const en: Dict = {
613 "form.year": "Year",614 "form.year": "Year",
614 "form.month": "Month",615 "form.month": "Month",
615 "form.day": "Day",616 "form.day": "Day",
617+ "form.datePlaceholder": "DD/MM/YYYY",
616 "form.mark": "Mark",618 "form.mark": "Mark",
617 "form.studentId": "Student user id",619 "form.studentId": "Student user id",
618 "form.selectStudent": "Select student",620 "form.selectStudent": "Select student",
@@ -976,6 +978,7 @@ const tr: Dict = {
976 "form.year": "Yıl",978 "form.year": "Yıl",
977 "form.month": "Ay",979 "form.month": "Ay",
978 "form.day": "Gün",980 "form.day": "Gün",
981+ "form.datePlaceholder": "GG/AA/YYYY",
979 "form.mark": "Not",982 "form.mark": "Not",
980 "form.studentId": "Öğrenci kullanıcı id",983 "form.studentId": "Öğrenci kullanıcı id",
981 "form.selectStudent": "Öğrenci seç",984 "form.selectStudent": "Öğrenci seç",
src/lib/format.tsmodified+0 -58
@@ -23,64 +23,6 @@ export function msToLocalInput(ms: number | null | undefined): string {
23 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;23 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
24 }24 }
25 25
26-export function msToDateTimeText(ms: number | null | undefined): string {
27- return msToLocalInput(ms).replace("T", " ");
28-}
29-
30-export function msToLocalDate(ms: number | null | undefined): string {
31- return msToLocalInput(ms).slice(0, 10);
32-}
33-
34-export function msToLocalHour(ms: number | null | undefined): string {
35- return msToLocalInput(ms).slice(11, 13);
36-}
37-
38-export function msToLocalMinute(ms: number | null | undefined): string {
39- return msToLocalInput(ms).slice(14, 16);
40-}
41-
42-export function localPartsToMs(date: string, hour: string, minute: string): number | null {
43- if (!date || !hour || !minute) return null;
44- const [year, month, day] = date.split("-").map(Number);
45- const h = Number(hour);
46- const m = Number(minute);
47- if (![year, month, day, h, m].every(Number.isInteger)) return null;
48- const d = new Date(year, month - 1, day, h, m, 0, 0);
49- if (
50- d.getFullYear() !== year ||
51- d.getMonth() !== month - 1 ||
52- d.getDate() !== day ||
53- d.getHours() !== h ||
54- d.getMinutes() !== m
55- ) {
56- return null;
57- }
58- return d.getTime();
59-}
60-
61-export function dateTimeTextToMs(value: string): number | null {
62- const match = value.trim().match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
63- if (!match) return null;
64- const [, yearRaw, monthRaw, dayRaw, hourRaw, minuteRaw] = match;
65- const year = Number(yearRaw);
66- const month = Number(monthRaw);
67- const day = Number(dayRaw);
68- const hour = Number(hourRaw);
69- const minute = Number(minuteRaw);
70- if (![year, month, day, hour, minute].every(Number.isInteger)) return null;
71- const d = new Date(year, month - 1, day, hour, minute, 0, 0);
72- if (
73- d.getFullYear() !== year ||
74- d.getMonth() !== month - 1 ||
75- d.getDate() !== day ||
76- d.getHours() !== hour ||
77- d.getMinutes() !== minute
78- ) {
79- return null;
80- }
81- return d.getTime();
82-}
83-
84 export function formatDurationMinutes(ms: number | null | undefined, locale: Locale = "en"): string {26 export function formatDurationMinutes(ms: number | null | undefined, locale: Locale = "en"): string {
85 if (ms == null) return "—";27 if (ms == null) return "—";
86 return locale === "tr" ? `${Math.round(ms / 60_000)} dk` : `${Math.round(ms / 60_000)} min`;28 return locale === "tr" ? `${Math.round(ms / 60_000)} dk` : `${Math.round(ms / 60_000)} min`;