forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

profile-form.tsx231 lines, 9.6 KiBHistoryRawDownload
1import { For, Show, createSignal } from "solid-js";
2import { patchMe } from "@/api/users";
3import type { ProfileUpdate, User } from "@/api/client";
4import { formatApiError } from "@/api/client";
5import { Alert } from "@/components/ui/alert";
6import { Button } from "@/components/ui/button";
7import { DatePicker } from "@/components/ui/date-picker";
8import { Input } from "@/components/ui/input";
9import { Label } from "@/components/ui/label";
10import { Select } from "@/components/ui/select";
11import { Textarea } from "@/components/ui/textarea";
12import { createFlash } from "@/lib/flash";
13import { hasMinRole } from "@/lib/roles";
14import { useT } from "@/stores/preferences-context";
15
16const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
17const PHONE_RE = /^\+?[\d\s().-]{7,20}$/;
18const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
19
20function isFutureDate(iso: string) {
21 const d = new Date(`${iso}T00:00:00Z`);
22 if (Number.isNaN(d.getTime())) return true;
23 const tomorrow = new Date();
24 tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
25 tomorrow.setUTCHours(0, 0, 0, 0);
26 return d.getTime() > tomorrow.getTime();
27}
28
29function dateInputFromIso(iso: string | null | undefined): string {
30 if (!iso) return "";
31 const match = iso.match(/^(\d{4})-(\d{2})-(\d{2})$/);
32 if (!match) return "";
33 const [, year, month, day] = match;
34 return `${day}/${month}/${year}`;
35}
36
37function isoFromDateInput(value: string): string {
38 const match = value.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
39 if (!match) return value.trim();
40 const [, day, month, year] = match;
41 return `${year}-${month}-${day}`;
42}
43
44export function ProfileForm(props: {
45 user: User;
46 /**
47 * `display_name` and `bio` ride the same PATCH but do not live on `User` —
48 * GET /auth/me never returns them, only GET /users/{id}/profile does. Pass
49 * them where a profile is in hand; omit them and the fields stay hidden
50 * rather than silently offering to clear values they cannot see.
51 */
52 profile?: { display_name: string | null; bio: string | null; branch?: string | null };
53 /** The school's branş vocabulary (settings.branches); the picker hides when empty. */
54 branches?: string[];
55 maxDisplayNameLen?: number;
56 maxBioLen?: number;
57 /**
58 * Offer the school-issued student number. It is the office's field, not the
59 * account holder's, so only the admin surface passes this; it stays hidden
60 * for anyone editing their own profile. Ignored for a non-student role,
61 * which the server refuses a number for anyway.
62 */
63 editStudentNumber?: boolean;
64 maxStudentNumberLen?: number;
65 onSaved: () => void;
66 onSave?: (body: ProfileUpdate) => Promise<User>;
67}) {
68 const t = useT();
69 const [name, setName] = createSignal(props.user.name ?? "");
70 const [surname, setSurname] = createSignal(props.user.surname ?? "");
71 const [email, setEmail] = createSignal(props.user.email ?? "");
72 const [phone, setPhone] = createSignal(props.user.phone ?? "");
73 const [birthDate, setBirthDate] = createSignal(dateInputFromIso(props.user.birth_date));
74 const [displayName, setDisplayName] = createSignal(props.profile?.display_name ?? "");
75 const [bio, setBio] = createSignal(props.profile?.bio ?? "");
76 const [branch, setBranch] = createSignal(props.profile?.branch ?? "");
77 const [studentNumber, setStudentNumber] = createSignal(props.user.student_number ?? "");
78 const showStudentNumber = () => !!props.editStudentNumber && props.user.role === "student";
79 // Branş is a teacher's field; a stored value outside the list still shows so
80 // saving the form never silently drops it.
81 const branchOptions = () => {
82 const list = props.branches ?? [];
83 const stored = props.profile?.branch;
84 return stored && !list.includes(stored) ? [stored, ...list] : list;
85 };
86 const showBranch = () => !!props.profile && hasMinRole(props.user.role, "teacher") && branchOptions().length > 0;
87 const [error, setError] = createSignal("");
88 const [flash, setFlash] = createFlash();
89 const [pending, setPending] = createSignal(false);
90
91 const validate = (): string | null => {
92 const e = email().trim();
93 const p = phone().trim();
94 const b = isoFromDateInput(birthDate());
95 if (e && !EMAIL_RE.test(e)) return t("profile.emailInvalid");
96 if (p && !PHONE_RE.test(p)) return t("profile.phoneInvalid");
97 if (b && (!DATE_RE.test(b) || isFutureDate(b))) return t("profile.dateInvalid");
98 return null;
99 };
100
101 const buildBody = (): ProfileUpdate => {
102 const b: ProfileUpdate = {};
103 const n = name().trim();
104 const s = surname().trim();
105 const e = email().trim();
106 const p = phone().trim();
107 const d = isoFromDateInput(birthDate());
108 if (n !== (props.user.name ?? "")) b.name = n;
109 if (s !== (props.user.surname ?? "")) b.surname = s;
110 if (e !== (props.user.email ?? "")) b.email = e;
111 if (p !== (props.user.phone ?? "")) b.phone = p;
112 if (d !== (props.user.birth_date ?? "")) b.birth_date = d;
113 // Blank clears it server-side, which is how the office un-numbers a student.
114 if (showStudentNumber() && studentNumber().trim() !== (props.user.student_number ?? "")) {
115 b.student_number = studentNumber().trim();
116 }
117 if (props.profile) {
118 // An empty string clears the field server-side; an omitted key keeps it.
119 const dn = displayName().trim();
120 const bi = bio().trim();
121 if (dn !== (props.profile.display_name ?? "")) b.display_name = dn;
122 if (bi !== (props.profile.bio ?? "")) b.bio = bi;
123 if (showBranch() && branch() !== (props.profile.branch ?? "")) b.branch = branch();
124 }
125 return b;
126 };
127
128 const submit = async (e: Event) => {
129 e.preventDefault();
130 setError("");
131 const msg = validate();
132 if (msg) { setError(msg); return; }
133 const body = buildBody();
134 if (Object.keys(body).length === 0) { props.onSaved(); return; }
135 setPending(true);
136 try {
137 await (props.onSave ?? patchMe)(body);
138 props.onSaved();
139 setFlash(t("common.saved"));
140 } catch (err) {
141 setError(formatApiError(err));
142 } finally {
143 setPending(false);
144 }
145 };
146
147 return (
148 <form onSubmit={submit} class="flex min-h-full flex-col space-y-4">
149 <Show when={flash()}>
150 <Alert variant="success">{flash()}</Alert>
151 </Show>
152 <div class="grid gap-3 sm:grid-cols-2">
153 <div class="space-y-1.5">
154 <Label for="pf-name">{t("profile.name")}</Label>
155 <Input id="pf-name" class="h-10" value={name()} onInput={(e) => setName(e.currentTarget.value)} />
156 </div>
157 <div class="space-y-1.5">
158 <Label for="pf-surname">{t("profile.surname")}</Label>
159 <Input id="pf-surname" class="h-10" value={surname()} onInput={(e) => setSurname(e.currentTarget.value)} />
160 </div>
161 </div>
162 <Show when={props.profile}>
163 <div class="space-y-1.5">
164 <Label for="pf-display-name">{t("profile.displayName")}</Label>
165 <Input
166 id="pf-display-name"
167 class="h-10"
168 maxlength={props.maxDisplayNameLen}
169 value={displayName()}
170 onInput={(e) => setDisplayName(e.currentTarget.value)}
171 />
172 <p class="text-xs text-muted-foreground">{t("profile.displayNameHint")}</p>
173 </div>
174 <div class="space-y-1.5">
175 <Label for="pf-bio">{t("profile.bio")}</Label>
176 <Textarea
177 id="pf-bio"
178 rows={3}
179 maxlength={props.maxBioLen}
180 value={bio()}
181 onInput={(e) => setBio(e.currentTarget.value)}
182 />
183 <p class="text-xs text-muted-foreground">
184 {t("profile.bioHint")}
185 <Show when={props.maxBioLen}>
186 {(max) => <span class="ml-1 tabular-nums">{bio().length} / {max()}</span>}
187 </Show>
188 </p>
189 </div>
190 </Show>
191 <Show when={showBranch()}>
192 <div class="space-y-1.5">
193 <Label for="pf-branch">{t("profile.branch")}</Label>
194 <Select id="pf-branch" class="h-10" value={branch()} onChange={(e) => setBranch(e.currentTarget.value)}>
195 <option value="">{t("profile.branchNone")}</option>
196 <For each={branchOptions()}>{(name) => <option value={name}>{name}</option>}</For>
197 </Select>
198 </div>
199 </Show>
200 <Show when={showStudentNumber()}>
201 <div class="space-y-1.5">
202 <Label for="pf-student-number">{t("roster.studentNumber")}</Label>
203 <Input
204 id="pf-student-number"
205 class="h-10"
206 maxlength={props.maxStudentNumberLen}
207 value={studentNumber()}
208 onInput={(e) => setStudentNumber(e.currentTarget.value)}
209 />
210 <p class="text-xs text-muted-foreground">{t("admin.studentNumberHint")}</p>
211 </div>
212 </Show>
213 <div class="space-y-1.5">
214 <Label for="pf-email">{t("profile.email")}</Label>
215 <Input id="pf-email" class="h-10" type="email" value={email()} onInput={(e) => setEmail(e.currentTarget.value)} />
216 </div>
217 <div class="space-y-1.5">
218 <Label for="pf-phone">{t("profile.phone")}</Label>
219 <Input id="pf-phone" class="h-10" type="tel" value={phone()} onInput={(e) => setPhone(e.currentTarget.value)} />
220 </div>
221 <div class="space-y-1.5">
222 <Label for="pf-birth">{t("profile.birthDate")}</Label>
223 <DatePicker id="pf-birth" class="h-10" placeholder={t("form.datePlaceholder")} value={birthDate()} onChange={setBirthDate} />
224 </div>
225 {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{error()}</p>}
226 <div class="!mt-auto sticky bottom-0 -mx-5 flex justify-end border-t border-border-hairline bg-surface-base px-5 pb-1 pt-4">
227 <Button type="submit" class="w-full sm:w-auto" disabled={pending()}>{t("common.save")}</Button>
228 </div>
229 </form>
230 );
231}