forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

command-palette.tsx553 lines, 21.2 KiBHistoryRawDownload
1import { useNavigate } from "@tanstack/solid-router";
2import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js";
3import { createResource } from "@/lib/create-resource";
4import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
5import {
6 IconBook,
7 IconCalendar,
8 IconDownload,
9 IconExam,
10 IconGlobe,
11 IconHomework,
12 IconLogout,
13 IconMoon,
14 IconNote,
15 IconSearch,
16 IconSparkles,
17 IconSun,
18 IconUsers,
19 IconX,
20} from "@/components/ui/icons";
21import { getUserSearch } from "@/api/users";
22import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items";
23import { createStudentClassLabels } from "@/lib/student-classes";
24import { hasMinRole } from "@/lib/roles";
25import { useAuth } from "@/stores/auth-context";
26import { useModules } from "@/stores/modules-context";
27import { usePreferences, useT } from "@/stores/preferences-context";
28import { cn } from "@/lib/cn";
29import { matchesSearch } from "@/lib/search-text";
30
31export type CommandPaletteProps = {
32 open: boolean;
33 onOpenChange: (open: boolean) => void;
34 onOpenCelebi?: () => void;
35 onOpenProfile?: () => void;
36};
37
38type CommandCategory = "people" | "actions" | "pages" | "system";
39
40type CommandItem = {
41 id: string;
42 category: CommandCategory;
43 categoryLabel: string;
44 title: string;
45 description?: string;
46 keywords?: string;
47 icon: typeof IconSearch;
48 shortcut?: string;
49 roleBadge?: string;
50 onSelect: () => void;
51};
52
53export function CommandPalette(props: CommandPaletteProps) {
54 const auth = useAuth();
55 const prefs = usePreferences();
56 const t = useT();
57 const navigate = useNavigate();
58 const modules = useModules();
59
60 const [query, setQuery] = createSignal("");
61 const [selectedIndex, setSelectedIndex] = createSignal(0);
62 let inputRef: HTMLInputElement | undefined;
63 let listRef: HTMLDivElement | undefined;
64
65 const role = () => auth.user()?.role;
66
67 // Student lookup moved here from the dashboard hero. `/users/search` is the
68 // app's only search endpoint and the user detail page is admin-only, so the
69 // "people" section exists for admins alone.
70 const [peopleQuery, setPeopleQuery] = createSignal("");
71 let peopleDebounce: ReturnType<typeof setTimeout> | undefined;
72 createEffect(() => {
73 const q = query().trim();
74 clearTimeout(peopleDebounce);
75 peopleDebounce = setTimeout(() => setPeopleQuery(q.length >= 2 ? q : ""), 250);
76 });
77 onCleanup(() => clearTimeout(peopleDebounce));
78 const [people] = createResource(
79 () => (props.open && role() === "admin" && peopleQuery() ? peopleQuery() : null),
80 (q) => getUserSearch(q, undefined, "student", { limit: 6 }),
81 );
82 // Two students called "Ayşe Yılmaz" are only told apart by their class, so
83 // each visible match is resolved to one (see `student-classes`).
84 const classLabels = createStudentClassLabels(() => (people.latest?.items ?? []).map((person) => person.id));
85
86 const items = createMemo<CommandItem[]>(() => {
87 const list: CommandItem[] = [];
88 const userRole = role();
89 const isTeacherPlus = hasMinRole(userRole, "teacher");
90 const isStudent = userRole === "student";
91
92 const mod = "Ctrl/Cmd + ";
93
94 // 1. Quick Actions (Hızlı İşlemler)
95 const actionsCategoryLabel = t("command.group.actions");
96
97 if (isTeacherPlus) {
98 list.push({
99 id: "action-create-homework",
100 category: "actions",
101 categoryLabel: actionsCategoryLabel,
102 title: t("command.action.createHomework"),
103 description: t("command.action.createHomeworkDesc"),
104 keywords: "homework odev ekle olustur ders",
105 icon: IconHomework,
106 shortcut: `${mod}H`,
107 roleBadge: t("role.teacher"),
108 onSelect: () => void navigate({ to: "/homework", search: { action: "new" } as any }),
109 });
110
111 list.push({
112 id: "action-create-course",
113 category: "actions",
114 categoryLabel: actionsCategoryLabel,
115 title: t("command.action.createCourse"),
116 description: t("command.action.createCourseDesc"),
117 keywords: "course ders kurs olustur egitim",
118 icon: IconBook,
119 shortcut: `${mod}C`,
120 roleBadge: t("role.teacher"),
121 onSelect: () => void navigate({ to: "/courses", search: { action: "new" } as any }),
122 });
123
124 list.push({
125 id: "action-create-event",
126 category: "actions",
127 categoryLabel: actionsCategoryLabel,
128 title: t("command.action.createEvent"),
129 description: t("command.action.createEventDesc"),
130 keywords: "event etkinlik planla takvim oturum",
131 icon: IconCalendar,
132 shortcut: `${mod}E`,
133 roleBadge: t("role.teacher"),
134 onSelect: () => void navigate({ to: "/events", search: { action: "new" } as any }),
135 });
136
137 list.push({
138 id: "action-create-exam",
139 category: "actions",
140 categoryLabel: actionsCategoryLabel,
141 title: t("command.action.createExam"),
142 description: t("command.action.createExamDesc"),
143 keywords: "exam sinav test hazirla olustur",
144 icon: IconExam,
145 shortcut: `${mod}X`,
146 roleBadge: t("role.teacher"),
147 onSelect: () => void navigate({ to: "/exams", search: { action: "new" } as any }),
148 });
149 }
150
151 // Common Quick Actions for all roles
152 list.push({
153 id: "action-create-note",
154 category: "actions",
155 categoryLabel: actionsCategoryLabel,
156 title: t("command.action.createNote"),
157 description: t("command.action.createNoteDesc"),
158 keywords: "note not ekle ders notu kaydet",
159 icon: IconNote,
160 shortcut: `${mod}N`,
161 onSelect: () => void navigate({ to: "/notes/new" }),
162 });
163
164 list.push({
165 id: "action-import-note",
166 category: "actions",
167 categoryLabel: actionsCategoryLabel,
168 title: t("command.action.importNote"),
169 description: t("command.action.importNoteDesc"),
170 keywords: "import ice aktar pdf txt markdown assistant",
171 icon: IconDownload,
172 onSelect: () => void navigate({ to: "/notes", search: { action: "import" } as any }),
173 });
174
175 list.push({
176 id: "action-ask-question",
177 category: "actions",
178 categoryLabel: actionsCategoryLabel,
179 title: t("command.action.askQuestion"),
180 description: t("command.action.askQuestionDesc"),
181 keywords: "question soru sor havuz ekle topluluk",
182 icon: IconExam,
183 shortcut: `${mod}Q`,
184 roleBadge: isStudent ? t("role.student") : undefined,
185 onSelect: () => void navigate({ to: "/questions", search: { action: "new" } as any }),
186 });
187
188 if (props.onOpenCelebi) {
189 list.push({
190 id: "action-ask-celebi",
191 category: "actions",
192 categoryLabel: actionsCategoryLabel,
193 title: t("command.action.askCelebi"),
194 description: t("command.action.askCelebiDesc"),
195 keywords: "celebi ai yapay zeka sohbet asistan yardım",
196 icon: IconSparkles,
197 onSelect: () => props.onOpenCelebi?.(),
198 });
199 }
200
201 if (props.onOpenProfile) {
202 list.push({
203 id: "action-my-profile",
204 category: "actions",
205 categoryLabel: actionsCategoryLabel,
206 title: t("command.action.myProfile"),
207 description: t("command.action.myProfileDesc"),
208 keywords: "profile profil hesabim kullanici sifre",
209 icon: IconUsers,
210 onSelect: () => props.onOpenProfile?.(),
211 });
212 }
213
214 // 2. Navigation Pages (Sayfalar & Gezinme)
215 const pagesCategoryLabel = t("command.group.navigation");
216
217 list.push({
218 id: "page-home",
219 category: "pages",
220 categoryLabel: pagesCategoryLabel,
221 title: t(HOME_ITEM.labelKey),
222 description: t("app.name"),
223 keywords: "home anasayfa kontrol paneli dashboard",
224 icon: HOME_ITEM.Icon,
225 onSelect: () => void navigate({ to: HOME_ITEM.to }),
226 });
227
228 for (const group of visibleNavGroups(userRole, modules.enabled())) {
229 const groupName = t(group.labelKey);
230 for (const item of group.items) {
231 // Çelebi and the account-settings entries open an existing shell
232 // surface rather than a route — the palette already offers both
233 // above, wired to the panel/dialog directly.
234 if (item.action) continue;
235 list.push({
236 id: `page-${item.to}`,
237 category: "pages",
238 categoryLabel: pagesCategoryLabel,
239 title: t(item.labelKey),
240 description: groupName,
241 keywords: `${item.to} ${t(item.labelKey)} ${groupName}`,
242 icon: item.Icon,
243 onSelect: () => void navigate({ to: item.to, search: item.search as never }),
244 });
245 }
246 }
247
248 // 3. System Preferences & Account (Sistem & Tercihler)
249 const systemCategoryLabel = t("command.group.system");
250
251 const isDark = prefs.theme() === "dark";
252 list.push({
253 id: "system-theme-toggle",
254 category: "system",
255 categoryLabel: systemCategoryLabel,
256 title: isDark ? t("command.action.themeLight") : t("command.action.themeDark"),
257 description: isDark ? t("command.action.themeLightDesc") : t("command.action.themeDarkDesc"),
258 keywords: "theme tema koyu acik dark light mode",
259 icon: isDark ? IconSun : IconMoon,
260 onSelect: () => prefs.setTheme(isDark ? "light" : "dark"),
261 });
262
263 const isTr = prefs.locale() === "tr";
264 list.push({
265 id: "system-lang-toggle",
266 category: "system",
267 categoryLabel: systemCategoryLabel,
268 title: isTr ? t("command.action.langEn") : t("command.action.langTr"),
269 description: isTr ? t("command.action.langEnDesc") : t("command.action.langTrDesc"),
270 keywords: "language dil turkce english tr en",
271 icon: IconGlobe,
272 onSelect: () => prefs.setLocale(isTr ? "en" : "tr"),
273 });
274
275 list.push({
276 id: "system-logout",
277 category: "system",
278 categoryLabel: systemCategoryLabel,
279 title: t("command.action.logout"),
280 description: t("command.action.logoutDesc"),
281 keywords: "logout cıkıs oturum kapat ayrıl",
282 icon: IconLogout,
283 onSelect: async () => {
284 await auth.logout();
285 void navigate({ to: "/login" });
286 },
287 });
288
289 return list;
290 });
291
292 const filteredItems = createMemo(() => {
293 const q = query().trim();
294 if (!q) return items();
295 const peopleLabel = t("command.group.people");
296 const found: CommandItem[] = (people.latest?.items ?? []).map((person) => ({
297 id: `person-${person.id}`,
298 category: "people",
299 categoryLabel: peopleLabel,
300 title: person.display_name || person.username,
301 description: classLabels()[person.id] ? `${classLabels()[person.id]} · ${person.username}` : person.username,
302 icon: IconUsers,
303 onSelect: () => void navigate({ to: "/admin/users/$id", params: { id: person.id } }),
304 }));
305 return [...found, ...items().filter((item) =>
306 matchesSearch(q, item.title, item.description, item.keywords, item.categoryLabel),
307 )];
308 });
309
310 // Group items by category while preserving single flat index order for keyboard navigation
311 const groupedItems = createMemo(() => {
312 const list = filteredItems();
313 const categories: { category: CommandCategory; label: string; items: { item: CommandItem; globalIndex: number }[] }[] = [];
314
315 const map = new Map<CommandCategory, { item: CommandItem; globalIndex: number }[]>();
316
317 list.forEach((item, idx) => {
318 if (!map.has(item.category)) {
319 map.set(item.category, []);
320 }
321 map.get(item.category)!.push({ item, globalIndex: idx });
322 });
323
324 const order: CommandCategory[] = ["people", "actions", "pages", "system"];
325 for (const cat of order) {
326 const itemsInCat = map.get(cat);
327 if (itemsInCat && itemsInCat.length > 0) {
328 categories.push({
329 category: cat,
330 label: itemsInCat[0].item.categoryLabel,
331 items: itemsInCat,
332 });
333 }
334 }
335
336 return categories;
337 });
338
339 const executeItem = (item: CommandItem) => {
340 props.onOpenChange(false);
341 item.onSelect();
342 };
343
344 createEffect(() => {
345 if (!props.open) return;
346 setQuery("");
347 setSelectedIndex(0);
348 });
349
350 // Reset selected index when query changes
351 createEffect(() => {
352 query();
353 setSelectedIndex(0);
354 });
355
356 // Auto scroll active item into view
357 createEffect(() => {
358 const idx = selectedIndex();
359 if (!listRef) return;
360 const activeEl = listRef.querySelector(`[data-index="${idx}"]`);
361 if (activeEl) {
362 activeEl.scrollIntoView({ block: "nearest" });
363 }
364 });
365
366 const handleKeyDown = (event: KeyboardEvent) => {
367 const list = filteredItems();
368 if (!list.length) return;
369
370 if (event.key === "ArrowDown") {
371 event.preventDefault();
372 setSelectedIndex((prev) => (prev + 1) % list.length);
373 } else if (event.key === "ArrowUp") {
374 event.preventDefault();
375 setSelectedIndex((prev) => (prev - 1 + list.length) % list.length);
376 } else if (event.key === "Enter") {
377 event.preventDefault();
378 const current = list[selectedIndex()];
379 if (current) executeItem(current);
380 }
381 };
382
383 onMount(() => {
384 const onGlobalKeyDown = (event: KeyboardEvent) => {
385 if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
386 event.preventDefault();
387 if (auth.user()) props.onOpenChange(!props.open);
388 }
389 if (event.key === "Escape" && props.open) props.onOpenChange(false);
390 };
391 window.addEventListener("keydown", onGlobalKeyDown);
392 onCleanup(() => window.removeEventListener("keydown", onGlobalKeyDown));
393 });
394
395 return (
396 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
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"
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
401 // palette opened with nothing focused and the first keystroke went
402 // nowhere. Taking the initial focus over hands it to the query field.
403 onOpenAutoFocus={(event) => {
404 event.preventDefault();
405 inputRef?.focus();
406 }}
407 >
408 <DialogTitle class="sr-only">{t("dashboard.commandCenter")}</DialogTitle>
409 <DialogDescription class="sr-only">{t("common.searchPlaceholder")}</DialogDescription>
410
411 {/* Search Bar Header */}
412 <div class="flex items-center gap-2.5 border-b border-border/80 px-4 py-3 pr-16 bg-muted/20">
413 <IconSearch class="h-4 w-4 text-muted-foreground shrink-0" />
414 <input
415 ref={inputRef}
416 type="text"
417 value={query()}
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"
420 onInput={(event) => setQuery(event.currentTarget.value)}
421 onKeyDown={handleKeyDown}
422 // Combobox pattern: focus stays in the field while arrow keys move
423 // an active option that assistive tech follows.
424 role="combobox"
425 aria-label={t("common.searchPlaceholder")}
426 aria-expanded="true"
427 aria-controls="command-palette-list"
428 aria-autocomplete="list"
429 aria-activedescendant={filteredItems().length > 0 ? `command-item-${selectedIndex()}` : undefined}
430 />
431 <Show when={query()}>
432 <button
433 type="button"
434 class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
435 onClick={() => {
436 setQuery("");
437 inputRef?.focus();
438 }}
439 title={t("common.clearSearch")}
440 aria-label={t("common.clearSearch")}
441 >
442 <IconX class="h-3.5 w-3.5" />
443 </button>
444 <span role="status" class="rounded-md bg-secondary px-2 py-0.5 text-xs font-semibold text-muted-foreground shrink-0 font-mono">
445 {filteredItems().length} {t("dashboard.ready").toLowerCase()}
446 </span>
447 </Show>
448 </div>
449
450 {/* What the field accepts — the palette takes names, pages and
451 actions, and an empty box says none of that on its own. */}
452 <Show when={!query()}>
453 <p class="border-b border-border/60 bg-muted/10 px-4 py-2 text-[11px] leading-snug text-muted-foreground">
454 {role() === "admin" ? t("search.hint.commandAdmin") : t("search.hint.command")}
455 </p>
456 </Show>
457
458 {/* Command Items List */}
459 <div
460 ref={listRef}
461 id="command-palette-list"
462 role="listbox"
463 aria-label={t("dashboard.commandCenter")}
464 class="max-h-[min(65vh,28rem)] overflow-y-auto p-2 space-y-4"
465 >
466 <Show
467 when={filteredItems().length > 0}
468 fallback={<p class="px-3 py-12 text-center text-sm text-muted-foreground">{t("common.noResults")}</p>}
469 >
470 <For each={groupedItems()}>
471 {(group, groupIndex) => (
472 <div class="space-y-1" role="group" aria-labelledby={`command-group-${groupIndex()}`}>
473 <div id={`command-group-${groupIndex()}`} class="px-3 py-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground/70">
474 {group.label}
475 </div>
476 <For each={group.items}>
477 {({ item, globalIndex }) => {
478 const isSelected = () => selectedIndex() === globalIndex;
479 const ItemIcon = item.icon;
480 return (
481 <button
482 type="button"
483 id={`command-item-${globalIndex}`}
484 role="option"
485 aria-selected={isSelected()}
486 tabIndex={-1}
487 data-index={globalIndex}
488 onClick={() => executeItem(item)}
489 onMouseEnter={() => setSelectedIndex(globalIndex)}
490 class={cn(
491 "flex w-full min-w-0 items-center gap-3 rounded-xl px-3 py-2.5 text-left outline-hidden transition-colors duration-150",
492 isSelected()
493 ? "bg-accent text-accent-foreground font-medium shadow-xs"
494 : "text-foreground hover:bg-secondary/60",
495 )}
496 >
497 <div
498 class={cn(
499 "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors",
500 isSelected()
501 ? "bg-primary text-primary-foreground"
502 : "bg-muted text-muted-foreground",
503 )}
504 >
505 <ItemIcon class="h-4 w-4" />
506 </div>
507
508 <div class="min-w-0 flex-1">
509 <div class="flex items-center gap-2">
510 <span class="truncate text-sm font-medium">{item.title}</span>
511 <Show when={item.roleBadge}>
512 <span class="rounded-full bg-secondary border border-border px-2 py-0.2 text-[11px] font-semibold text-muted-foreground">
513 {item.roleBadge}
514 </span>
515 </Show>
516 </div>
517 <Show when={item.description}>
518 <p class="truncate text-xs text-muted-foreground">{item.description}</p>
519 </Show>
520 </div>
521
522 <Show when={item.shortcut}>
523 <kbd class="hidden shrink-0 rounded-md border border-border/80 bg-muted/60 px-2 py-0.5 font-mono text-[11px] font-semibold text-muted-foreground sm:inline-block">
524 {item.shortcut}
525 </kbd>
526 </Show>
527 </button>
528 );
529 }}
530 </For>
531 </div>
532 )}
533 </For>
534 </Show>
535 </div>
536
537 {/* Command Palette Footer — keyboard-only guidance, so it is hidden on
538 phones where there are no arrow, enter or escape keys to press. */}
539 <div class="hidden items-center justify-between border-t border-border/60 bg-muted/30 px-4 py-2 text-xs text-muted-foreground sm:flex">
540 <span class="truncate">{t("command.shortcutHint")}</span>
541 <div class="flex items-center gap-2 font-mono shrink-0">
542 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[11px] font-semibold">↑↓</kbd>
543 <span>{t("command.key.navigate")}</span>
544 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[11px] font-semibold">↵</kbd>
545 <span>{t("command.key.select")}</span>
546 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[11px] font-semibold">Esc</kbd>
547 <span>{t("command.key.close")}</span>
548 </div>
549 </div>
550 </DialogContent>
551 </Dialog>
552 );
553}