forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

user-search-select.tsx193 lines, 7.6 KiBHistoryRawDownload
1import { Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2import { 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 const t = useT();
43 const auth = useAuth();
44 // `/users/search` is teacher+ on the backend, so this component must never
45 // fire it for a student or parent — they would only ever 403. Below teacher
46 // the input is disabled and the request is never sent; this is the single
47 // role gate for every UserSearchSelect in the app (messages compose, meal
48 // service, course/class management, …).
49 const canSearch = () => hasMinRole(auth.user()?.role, "teacher");
50 const [query, setQuery] = createSignal("");
51 const [users, setUsers] = createSignal<PersonRef[]>([]);
52 const [selected, setSelected] = createSignal<PersonRef | null>(null);
53 const [loading, setLoading] = createSignal(false);
54 const [open, setOpen] = createSignal(false);
55
56 const options = createMemo(() => {
57 const excluded = new Set(props.excludeIds ?? []);
58 return users().filter((user) => !excluded.has(user.id)).slice(0, MAX_VISIBLE_RESULTS);
59 });
60
61 // A student picker shows the class next to the name: two students can share
62 // a name, and the account id the row used to carry is a uuid nobody reads.
63 // Only students get the extra lookup — see `student-classes`.
64 const classLabels = createStudentClassLabels(() =>
65 props.role === "student" ? options().map((user) => user.id) : [],
66 );
67 const secondaryLine = (user: PersonRef) => {
68 const cls = classLabels()[user.id];
69 return cls ? `${cls} · ${user.username}` : user.username;
70 };
71 // What the input reads after a pick — the name alone is ambiguous, the
72 // username is the thing that is unique and short.
73 const pickedLabel = (user: PersonLike) => {
74 if (!user || typeof user === "string") return personLabel(user);
75 const name = personLabel(user);
76 return name === user.username ? name : `${name} (${user.username})`;
77 };
78
79 // Drop our local selection when the parent clears the bound value.
80 createEffect(() => {
81 if (!props.value && selected()) setSelected(null);
82 });
83
84 let controller: AbortController | null = null;
85 let timer: ReturnType<typeof setTimeout> | undefined;
86 // Debounce keystrokes so a typed name is one request, not one per letter.
87 const runSearch = (raw: string) => {
88 const q = raw.trim();
89 controller?.abort();
90 clearTimeout(timer);
91 if (!canSearch()) {
92 // A sub-teacher role reached a picker (e.g. message compose): never call
93 // the teacher+ search endpoint.
94 setUsers([]);
95 setLoading(false);
96 setOpen(false);
97 return;
98 }
99 if (q.length === 0) {
100 setUsers([]);
101 setLoading(false);
102 setOpen(false);
103 return;
104 }
105 // Mark pending now, not after the debounce fires — otherwise the empty
106 // "no students" message flashes during the wait before the request starts.
107 setLoading(true);
108 timer = setTimeout(() => {
109 const ctrl = new AbortController();
110 controller = ctrl;
111 void getUserSearch(q, ctrl.signal, props.role)
112 .then((data) => setUsers(data.items))
113 .catch(() => {
114 if (!ctrl.signal.aborted) setUsers([]);
115 })
116 .finally(() => {
117 if (!ctrl.signal.aborted) setLoading(false);
118 });
119 }, 300);
120 };
121 onCleanup(() => {
122 controller?.abort();
123 clearTimeout(timer);
124 });
125
126 const emptyText = createMemo(() => {
127 if (query().trim().length === 0 || loading() || options().length > 0) return "";
128 return props.emptyMessage ?? (props.role === "teacher" ? t("form.noTeachers") : t("form.noStudents"));
129 });
130
131 return (
132 <div class="space-y-2">
133 <Show when={props.label}>{(label) => <Label for={props.id}>{label()}</Label>}</Show>
134 <Combobox<PersonRef>
135 options={options()}
136 // Results arrive async, so options is empty at input time. Kobalte
137 // 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
139 // loading, then results pop in.
140 allowsEmptyCollection
141 open={open() && query().trim().length > 0}
142 onOpenChange={(nextOpen) => setOpen(nextOpen && query().trim().length > 0)}
143 value={selected()}
144 onChange={(user) => {
145 setSelected(user);
146 props.onChange(user?.id ?? "");
147 props.onSelect?.(user ?? null);
148 }}
149 onInputChange={(value) => {
150 setQuery(value);
151 runSearch(value);
152 if (value.trim().length > 0) setOpen(true);
153 }}
154 optionValue="id"
155 optionLabel={(user) => pickedLabel(user)}
156 optionTextValue={(user) => pickedLabel(user)}
157 defaultFilter={() => true}
158 placeholder={props.placeholder ?? t("common.searchPlaceholder")}
159 disabled={props.disabled || !canSearch()}
160 itemComponent={(itemProps) => (
161 <ComboboxItem item={itemProps.item}>
162 <ComboboxItemLabel class="flex min-w-0 flex-col gap-0.5">
163 <span class="truncate font-medium">{personLabel(itemProps.item.rawValue)}</span>
164 <span class="truncate text-xs text-muted-foreground">{secondaryLine(itemProps.item.rawValue)}</span>
165 </ComboboxItemLabel>
166 </ComboboxItem>
167 )}
168 >
169 <ComboboxControl>
170 <ComboboxInput id={props.id} autocomplete="off" />
171 <ComboboxTrigger />
172 </ComboboxControl>
173 <ComboboxContent>
174 {/* The debounce plus the request leave the panel blank for a moment,
175 which reads as "nothing matches" before the search even ran. */}
176 <Show when={loading() && options().length === 0}>
177 <p class="px-2 py-2 text-xs text-muted-foreground">{t("common.loading")}</p>
178 </Show>
179 <Show when={emptyText()}>
180 <p class="px-2 py-2 text-xs font-medium text-destructive-text">{emptyText()}</p>
181 </Show>
182 </ComboboxContent>
183 </Combobox>
184 <Show when={canSearch()} fallback={<p class="text-xs text-muted-foreground">{t("form.searchNoPermission")}</p>}>
185 {/* An empty combobox looks like a dropdown that failed to load, so it
186 says outright that it is a type-to-search field and what it matches. */}
187 <p class="text-xs text-muted-foreground">
188 {props.hint ?? (props.role === "student" ? t("search.hint.studentPicker") : props.role === "teacher" ? t("search.hint.teacherPicker") : t("search.hint.personPicker"))}
189 </p>
190 </Show>
191 </div>
192 );
193}