forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

user-search-select.tsx289 lines, 11.4 KiBHistoryRawDownload
1import { Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2import { getUserById, getUserSearch } from "@/api/users";
3import type { PersonRef, Role } from "@/api/client";
4import type { PersonLike } from "@/lib/person";
5import {
6 Combobox,
7 ComboboxContent,
8 ComboboxControl,
9 ComboboxInput,
10 ComboboxItem,
11 ComboboxItemLabel,
12 ComboboxTrigger,
13} from "@/components/ui/combobox";
14import { Label } from "@/components/ui/label";
15import { personLabel } from "@/lib/person";
16import { createStudentClassLabels } from "@/lib/student-classes";
17import { hasMinRole } from "@/lib/roles";
18import { useAuth } from "@/stores/auth-context";
19import { useT } from "@/stores/preferences-context";
20
21const MAX_VISIBLE_RESULTS = 8;
22
23/**
24 * Server-backed user autocomplete on the Kobalte Combobox primitive. Typing
25 * fires a debounced `/users/search` query (previous request aborted); the user
26 * picks a result and `onChange` receives the id.
27 */
28export function UserSearchSelect(props: {
29 id: string;
30 value: string;
31 onChange: (value: string) => void;
32 onSelect?: (user: PersonRef | null) => void;
33 label?: string;
34 excludeIds?: string[];
35 placeholder?: string;
36 emptyMessage?: string;
37 disabled?: boolean;
38 /** Overrides the default "what can I type here" line under the field. */
39 hint?: string;
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;
47}) {
48 const t = useT();
49 const auth = useAuth();
50 // `/users/search` is teacher+ on the backend, so this component must never
51 // fire it for a student or parent — they would only ever 403. Below teacher
52 // the input is disabled and the request is never sent; this is the single
53 // role gate for every UserSearchSelect in the app (messages compose, meal
54 // service, course/class management, …).
55 const canSearch = () => hasMinRole(auth.user()?.role, "teacher");
56 const [query, setQuery] = createSignal("");
57 const [users, setUsers] = createSignal<PersonRef[]>([]);
58 const [selected, setSelected] = createSignal<PersonRef | null>(null);
59 const [loading, setLoading] = createSignal(false);
60 const [open, setOpen] = createSignal(false);
61 let inputRef: HTMLInputElement | undefined;
62 let clearingForOpen = false;
63
64 const options = createMemo(() => {
65 const excluded = new Set(props.excludeIds ?? []);
66 return users().filter((user) => !excluded.has(user.id)).slice(0, MAX_VISIBLE_RESULTS);
67 });
68
69 // A student picker shows the class next to the name: two students can share
70 // a name, and the account id the row used to carry is a uuid nobody reads.
71 // Only students get the extra lookup — see `student-classes`.
72 const classLabels = createStudentClassLabels(() =>
73 props.role === "student" ? options().map((user) => user.id) : [],
74 );
75 const secondaryLine = (user: PersonRef) => {
76 const cls = classLabels()[user.id];
77 return cls ? `${cls} · ${user.username}` : user.username;
78 };
79 // What the input reads after a pick — the name alone is ambiguous, the
80 // username is the thing that is unique and short.
81 const pickedLabel = (user: PersonLike) => {
82 if (!user || typeof user === "string") return personLabel(user);
83 const name = personLabel(user);
84 return name === user.username ? name : `${name} (${user.username})`;
85 };
86
87 // Drop our local selection when the parent clears the bound value.
88 createEffect(() => {
89 if (!props.value && selected()) setSelected(null);
90 });
91
92 // A value set by the parent (an edit form opening on a saved record) has no
93 // picked option behind it, so the input would read as empty. Show the
94 // person it points at: from `initialUser` when given, else one lookup.
95 let resolving: string | null = null;
96 createEffect(() => {
97 const id = props.value;
98 if (!id || selected()?.id === id) return;
99 const preset = props.initialUser;
100 if (preset && preset.id === id) {
101 setSelected(preset);
102 return;
103 }
104 if (!canSearch() || resolving === id) return;
105 resolving = id;
106 void getUserById(id)
107 .then((user) => {
108 if (props.value !== id) return;
109 setSelected({
110 id: user.id,
111 username: user.username,
112 display_name: user.display_name || [user.name, user.surname].filter(Boolean).join(" ") || null,
113 });
114 })
115 .catch(() => {
116 // Unreadable account: leave the field empty rather than show the uuid.
117 })
118 .finally(() => {
119 if (resolving === id) resolving = null;
120 });
121 });
122
123 let controller: AbortController | null = null;
124 let timer: ReturnType<typeof setTimeout> | undefined;
125 // Debounce keystrokes so a typed name is one request, not one per letter.
126 const runSearch = (raw: string) => {
127 const q = raw.trim();
128 controller?.abort();
129 clearTimeout(timer);
130 if (!canSearch()) {
131 // A sub-teacher role reached a picker (e.g. message compose): never call
132 // the teacher+ search endpoint.
133 setUsers([]);
134 setLoading(false);
135 setOpen(false);
136 return;
137 }
138 // An empty query is a request for suggestions: `/users/search?q=` lists
139 // the role's people, so the field works as a dropdown before any typing.
140 // Mark pending now, not after the debounce fires — otherwise the empty
141 // "no students" message flashes during the wait before the request starts.
142 setLoading(true);
143 timer = setTimeout(() => {
144 const ctrl = new AbortController();
145 controller = ctrl;
146 void getUserSearch(q, ctrl.signal, props.role)
147 .then((data) => setUsers(data.items))
148 .catch(() => {
149 if (!ctrl.signal.aborted) setUsers([]);
150 })
151 .finally(() => {
152 if (!ctrl.signal.aborted) setLoading(false);
153 });
154 }, q.length === 0 ? 0 : 300);
155 };
156 // Opening the list starts a fresh search. Kobalte owns the displayed input
157 // value, so clear it through an input event while guarding the saved pick:
158 // an actual user erase still clears an optional selection below.
159 const openSuggestions = () => {
160 if (!canSearch() || props.disabled) return;
161 const needsReset = query().trim() !== "" || !!inputRef?.value;
162 setOpen(true);
163 if (needsReset) {
164 setQuery("");
165 setUsers([]);
166 if (inputRef) {
167 clearingForOpen = true;
168 inputRef.value = "";
169 inputRef.dispatchEvent(new Event("input", { bubbles: true }));
170 clearingForOpen = false;
171 }
172 runSearch("");
173 } else if (users().length === 0 && !loading()) {
174 runSearch("");
175 }
176 };
177 onCleanup(() => {
178 controller?.abort();
179 clearTimeout(timer);
180 });
181
182 const emptyText = createMemo(() => {
183 if (loading() || options().length > 0 || (query().trim() === "" && selected())) return "";
184 return props.emptyMessage ?? (props.role === "teacher" ? t("form.noTeachers") : t("form.noStudents"));
185 });
186
187 return (
188 <div class="space-y-2">
189 <Show when={props.label}>{(label) => <Label for={props.id}>{label()}</Label>}</Show>
190 <Combobox<PersonRef>
191 // Kobalte writes the picked person's name into the input only when
192 // that person is among the options, so a preset one rides along
193 // while nothing is being searched.
194 options={
195 query().trim() === "" && selected() && !options().some((user) => user.id === selected()!.id)
196 ? [selected()!, ...options()]
197 : options()
198 }
199 // Results arrive async, so options is empty at input time. Kobalte
200 // refuses to open an empty collection by default (and would close on
201 // input) — allow it, and control open so the panel stays up while
202 // loading, then results pop in.
203 allowsEmptyCollection
204 open={open()}
205 onOpenChange={(nextOpen, triggerMode) => {
206 if (!nextOpen) setOpen(false);
207 else if (triggerMode === "input") setOpen(true);
208 else openSuggestions();
209 }}
210 value={selected()}
211 onChange={(user) => {
212 setSelected(user);
213 props.onChange(user?.id ?? "");
214 props.onSelect?.(user ?? null);
215 }}
216 onInputChange={(value) => {
217 if (clearingForOpen) return;
218 // Kobalte echoes the picked person's label into the input; that is
219 // not a search, and treating it as one drops the preset person from
220 // the options, which makes Kobalte clear the field again.
221 const current = selected();
222 if (current && value === pickedLabel(current)) {
223 setQuery("");
224 setOpen(false);
225 return;
226 }
227 setQuery(value);
228 // Erasing the field clears the pick — the only way to leave an
229 // optional person (a class's homeroom teacher) unassigned again.
230 if (value.trim() === "" && current) {
231 setSelected(null);
232 props.onChange("");
233 props.onSelect?.(null);
234 }
235 runSearch(value);
236 setOpen(true);
237 }}
238 optionValue="id"
239 optionLabel={(user) => pickedLabel(user)}
240 optionTextValue={(user) => pickedLabel(user)}
241 defaultFilter={() => true}
242 placeholder={props.placeholder ?? t("common.searchPlaceholder")}
243 disabled={props.disabled || !canSearch()}
244 itemComponent={(itemProps) => (
245 <ComboboxItem item={itemProps.item}>
246 <ComboboxItemLabel class="flex min-w-0 flex-col gap-0.5">
247 <span class="truncate font-medium">{personLabel(itemProps.item.rawValue)}</span>
248 <span class="truncate text-xs text-muted-foreground">{secondaryLine(itemProps.item.rawValue)}</span>
249 </ComboboxItemLabel>
250 </ComboboxItem>
251 )}
252 >
253 <ComboboxControl>
254 <ComboboxInput
255 id={props.id}
256 ref={inputRef}
257 autocomplete="off"
258 // Typing into a field that already names someone used to append
259 // to the name ("Ayşe Yılmaz (ayse.yilmaz)Mehmet") and find no one,
260 // so a class's teacher could not be changed. Select it instead.
261 onFocus={(event: FocusEvent) => {
262 (event.currentTarget as HTMLInputElement).select();
263 openSuggestions();
264 }}
265 onClick={openSuggestions}
266 />
267 <ComboboxTrigger />
268 </ComboboxControl>
269 <ComboboxContent>
270 {/* The debounce plus the request leave the panel blank for a moment,
271 which reads as "nothing matches" before the search even ran. */}
272 <Show when={loading() && options().length === 0}>
273 <p class="px-2 py-2 text-xs text-muted-foreground">{t("common.loading")}</p>
274 </Show>
275 <Show when={emptyText()}>
276 <p class="px-2 py-2 text-xs font-medium text-destructive-text">{emptyText()}</p>
277 </Show>
278 </ComboboxContent>
279 </Combobox>
280 <Show when={canSearch()} fallback={<p class="text-xs text-muted-foreground">{t("form.searchNoPermission")}</p>}>
281 {/* An empty combobox looks like a dropdown that failed to load, so it
282 says outright that it is a type-to-search field and what it matches. */}
283 <p class="text-xs text-muted-foreground">
284 {props.hint ?? (props.role === "student" ? t("search.hint.studentPicker") : props.role === "teacher" ? t("search.hint.teacherPicker") : t("search.hint.personPicker"))}
285 </p>
286 </Show>
287 </div>
288 );
289}