forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

command-palette.tsx480 lines, 17.3 KiBHistoryRawDownload
1import { useNavigate } from "@tanstack/solid-router";
2import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js";
3import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
4import {
5 IconBook,
6 IconCalendar,
7 IconDownload,
8 IconExam,
9 IconGlobe,
10 IconHomework,
11 IconLogout,
12 IconMoon,
13 IconNote,
14 IconPencilQuestion,
15 IconSearch,
16 IconSparkles,
17 IconSun,
18 IconUsers,
19 IconX,
20} from "@/components/ui/icons";
21import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items";
22import { hasMinRole } from "@/lib/roles";
23import { useAuth } from "@/stores/auth-context";
24import { usePreferences, useT } from "@/stores/preferences-context";
25import { cn } from "@/lib/cn";
26
27export type CommandPaletteProps = {
28 open: boolean;
29 onOpenChange: (open: boolean) => void;
30 onOpenCelebi?: () => void;
31 onOpenProfile?: () => void;
32};
33
34type CommandCategory = "actions" | "pages" | "system";
35
36type CommandItem = {
37 id: string;
38 category: CommandCategory;
39 categoryLabel: string;
40 title: string;
41 description?: string;
42 keywords?: string;
43 icon: typeof IconSearch;
44 shortcut?: string;
45 roleBadge?: string;
46 onSelect: () => void;
47};
48
49export function CommandPalette(props: CommandPaletteProps) {
50 const auth = useAuth();
51 const prefs = usePreferences();
52 const t = useT();
53 const navigate = useNavigate();
54
55 const [query, setQuery] = createSignal("");
56 const [selectedIndex, setSelectedIndex] = createSignal(0);
57 let inputRef: HTMLInputElement | undefined;
58 let listRef: HTMLDivElement | undefined;
59
60 const role = () => auth.user()?.role;
61
62 const items = createMemo<CommandItem[]>(() => {
63 const list: CommandItem[] = [];
64 const userRole = role();
65 const isTeacherPlus = hasMinRole(userRole, "teacher");
66 const isStudent = userRole === "student";
67
68 const mod = "Ctrl/Cmd + ";
69
70 // 1. Quick Actions (Hızlı İşlemler)
71 const actionsCategoryLabel = t("command.group.actions");
72
73 if (isTeacherPlus) {
74 list.push({
75 id: "action-create-homework",
76 category: "actions",
77 categoryLabel: actionsCategoryLabel,
78 title: t("command.action.createHomework"),
79 description: t("command.action.createHomeworkDesc"),
80 keywords: "homework odev ekle olustur ders",
81 icon: IconHomework,
82 shortcut: `${mod}H`,
83 roleBadge: t("role.teacher"),
84 onSelect: () => void navigate({ to: "/homework", search: { action: "new" } as any }),
85 });
86
87 list.push({
88 id: "action-create-course",
89 category: "actions",
90 categoryLabel: actionsCategoryLabel,
91 title: t("command.action.createCourse"),
92 description: t("command.action.createCourseDesc"),
93 keywords: "course ders kurs olustur egitim",
94 icon: IconBook,
95 shortcut: `${mod}C`,
96 roleBadge: t("role.teacher"),
97 onSelect: () => void navigate({ to: "/courses", search: { action: "new" } as any }),
98 });
99
100 list.push({
101 id: "action-create-event",
102 category: "actions",
103 categoryLabel: actionsCategoryLabel,
104 title: t("command.action.createEvent"),
105 description: t("command.action.createEventDesc"),
106 keywords: "event etkinlik planla takvim oturum",
107 icon: IconCalendar,
108 shortcut: `${mod}E`,
109 roleBadge: t("role.teacher"),
110 onSelect: () => void navigate({ to: "/events", search: { action: "new" } as any }),
111 });
112
113 list.push({
114 id: "action-create-exam",
115 category: "actions",
116 categoryLabel: actionsCategoryLabel,
117 title: t("command.action.createExam"),
118 description: t("command.action.createExamDesc"),
119 keywords: "exam sinav test hazirla olustur",
120 icon: IconExam,
121 shortcut: `${mod}X`,
122 roleBadge: t("role.teacher"),
123 onSelect: () => void navigate({ to: "/exams", search: { action: "new" } as any }),
124 });
125 }
126
127 // Common Quick Actions for all roles
128 list.push({
129 id: "action-create-note",
130 category: "actions",
131 categoryLabel: actionsCategoryLabel,
132 title: t("command.action.createNote"),
133 description: t("command.action.createNoteDesc"),
134 keywords: "note not ekle ders notu kaydet",
135 icon: IconNote,
136 shortcut: `${mod}N`,
137 onSelect: () => void navigate({ to: "/notes", search: { action: "new" } as any }),
138 });
139
140 list.push({
141 id: "action-import-note",
142 category: "actions",
143 categoryLabel: actionsCategoryLabel,
144 title: t("command.action.importNote"),
145 description: t("command.action.importNoteDesc"),
146 keywords: "import ice aktar pdf txt markdown assistant",
147 icon: IconDownload,
148 onSelect: () => void navigate({ to: "/notes", search: { action: "import" } as any }),
149 });
150
151 list.push({
152 id: "action-ask-question",
153 category: "actions",
154 categoryLabel: actionsCategoryLabel,
155 title: t("command.action.askQuestion"),
156 description: t("command.action.askQuestionDesc"),
157 keywords: "question soru sor havuz ekle topluluk",
158 icon: IconPencilQuestion,
159 shortcut: `${mod}Q`,
160 roleBadge: isStudent ? t("role.student") : undefined,
161 onSelect: () => void navigate({ to: "/questions", search: { action: "new" } as any }),
162 });
163
164 if (props.onOpenCelebi) {
165 list.push({
166 id: "action-ask-celebi",
167 category: "actions",
168 categoryLabel: actionsCategoryLabel,
169 title: t("command.action.askCelebi"),
170 description: t("command.action.askCelebiDesc"),
171 keywords: "celebi ai yapay zeka sohbet asistan yardım",
172 icon: IconSparkles,
173 onSelect: () => props.onOpenCelebi?.(),
174 });
175 }
176
177 if (props.onOpenProfile) {
178 list.push({
179 id: "action-my-profile",
180 category: "actions",
181 categoryLabel: actionsCategoryLabel,
182 title: t("command.action.myProfile"),
183 description: t("command.action.myProfileDesc"),
184 keywords: "profile profil hesabim kullanici sifre",
185 icon: IconUsers,
186 onSelect: () => props.onOpenProfile?.(),
187 });
188 }
189
190 // 2. Navigation Pages (Sayfalar & Gezinme)
191 const pagesCategoryLabel = t("command.group.navigation");
192
193 list.push({
194 id: "page-home",
195 category: "pages",
196 categoryLabel: pagesCategoryLabel,
197 title: t(HOME_ITEM.labelKey),
198 description: t("app.name"),
199 keywords: "home anasayfa kontrol paneli dashboard",
200 icon: HOME_ITEM.Icon,
201 onSelect: () => void navigate({ to: HOME_ITEM.to }),
202 });
203
204 for (const group of visibleNavGroups(userRole)) {
205 const groupName = t(group.labelKey);
206 for (const item of group.items) {
207 list.push({
208 id: `page-${item.to}`,
209 category: "pages",
210 categoryLabel: pagesCategoryLabel,
211 title: t(item.labelKey),
212 description: groupName,
213 keywords: `${item.to} ${t(item.labelKey)} ${groupName}`,
214 icon: item.Icon,
215 onSelect: () => void navigate({ to: item.to }),
216 });
217 }
218 }
219
220 // 3. System Preferences & Account (Sistem & Tercihler)
221 const systemCategoryLabel = t("command.group.system");
222
223 const isDark = prefs.theme() === "dark";
224 list.push({
225 id: "system-theme-toggle",
226 category: "system",
227 categoryLabel: systemCategoryLabel,
228 title: isDark ? t("command.action.themeLight") : t("command.action.themeDark"),
229 description: isDark ? "Açık moda geç" : "Koyu moda geç",
230 keywords: "theme tema koyu acik dark light mode",
231 icon: isDark ? IconSun : IconMoon,
232 onSelect: () => prefs.setTheme(isDark ? "light" : "dark"),
233 });
234
235 const isTr = prefs.locale() === "tr";
236 list.push({
237 id: "system-lang-toggle",
238 category: "system",
239 categoryLabel: systemCategoryLabel,
240 title: isTr ? t("command.action.langEn") : t("command.action.langTr"),
241 description: isTr ? "Switch to English" : "Türkçe diline geç",
242 keywords: "language dil turkce english tr en",
243 icon: IconGlobe,
244 onSelect: () => prefs.setLocale(isTr ? "en" : "tr"),
245 });
246
247 list.push({
248 id: "system-logout",
249 category: "system",
250 categoryLabel: systemCategoryLabel,
251 title: t("command.action.logout"),
252 description: t("command.action.logoutDesc"),
253 keywords: "logout cıkıs oturum kapat ayrıl",
254 icon: IconLogout,
255 onSelect: async () => {
256 await auth.logout();
257 void navigate({ to: "/login" });
258 },
259 });
260
261 return list;
262 });
263
264 const filteredItems = createMemo(() => {
265 const q = query().trim().toLocaleLowerCase(prefs.locale());
266 if (!q) return items();
267 return items().filter((item) =>
268 `${item.title} ${item.description ?? ""} ${item.keywords ?? ""} ${item.categoryLabel}`
269 .toLocaleLowerCase(prefs.locale())
270 .includes(q),
271 );
272 });
273
274 // Group items by category while preserving single flat index order for keyboard navigation
275 const groupedItems = createMemo(() => {
276 const list = filteredItems();
277 const categories: { category: CommandCategory; label: string; items: { item: CommandItem; globalIndex: number }[] }[] = [];
278
279 const map = new Map<CommandCategory, { item: CommandItem; globalIndex: number }[]>();
280
281 list.forEach((item, idx) => {
282 if (!map.has(item.category)) {
283 map.set(item.category, []);
284 }
285 map.get(item.category)!.push({ item, globalIndex: idx });
286 });
287
288 const order: CommandCategory[] = ["actions", "pages", "system"];
289 for (const cat of order) {
290 const itemsInCat = map.get(cat);
291 if (itemsInCat && itemsInCat.length > 0) {
292 categories.push({
293 category: cat,
294 label: itemsInCat[0].item.categoryLabel,
295 items: itemsInCat,
296 });
297 }
298 }
299
300 return categories;
301 });
302
303 const executeItem = (item: CommandItem) => {
304 props.onOpenChange(false);
305 item.onSelect();
306 };
307
308 createEffect(() => {
309 if (!props.open) return;
310 setQuery("");
311 setSelectedIndex(0);
312 queueMicrotask(() => inputRef?.focus());
313 });
314
315 // Reset selected index when query changes
316 createEffect(() => {
317 query();
318 setSelectedIndex(0);
319 });
320
321 // Auto scroll active item into view
322 createEffect(() => {
323 const idx = selectedIndex();
324 if (!listRef) return;
325 const activeEl = listRef.querySelector(`[data-index="${idx}"]`);
326 if (activeEl) {
327 activeEl.scrollIntoView({ block: "nearest" });
328 }
329 });
330
331 const handleKeyDown = (event: KeyboardEvent) => {
332 const list = filteredItems();
333 if (!list.length) return;
334
335 if (event.key === "ArrowDown") {
336 event.preventDefault();
337 setSelectedIndex((prev) => (prev + 1) % list.length);
338 } else if (event.key === "ArrowUp") {
339 event.preventDefault();
340 setSelectedIndex((prev) => (prev - 1 + list.length) % list.length);
341 } else if (event.key === "Enter") {
342 event.preventDefault();
343 const current = list[selectedIndex()];
344 if (current) executeItem(current);
345 }
346 };
347
348 onMount(() => {
349 const onGlobalKeyDown = (event: KeyboardEvent) => {
350 if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
351 event.preventDefault();
352 if (auth.user()) props.onOpenChange(!props.open);
353 }
354 if (event.key === "Escape" && props.open) props.onOpenChange(false);
355 };
356 window.addEventListener("keydown", onGlobalKeyDown);
357 onCleanup(() => window.removeEventListener("keydown", onGlobalKeyDown));
358 });
359
360 return (
361 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
362 <DialogContent 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">
363 <DialogTitle class="sr-only">{t("dashboard.commandCenter")}</DialogTitle>
364 <DialogDescription class="sr-only">{t("common.searchPlaceholder")}</DialogDescription>
365
366 {/* Search Bar Header */}
367 <div class="flex items-center gap-2.5 border-b border-border/80 px-4 py-3 pr-16 bg-muted/20">
368 <IconSearch class="h-4 w-4 text-muted-foreground shrink-0" />
369 <input
370 ref={inputRef}
371 type="text"
372 value={query()}
373 placeholder={t("common.searchPlaceholder")}
374 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"
375 onInput={(event) => setQuery(event.currentTarget.value)}
376 onKeyDown={handleKeyDown}
377 />
378 <Show when={query()}>
379 <button
380 type="button"
381 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"
382 onClick={() => {
383 setQuery("");
384 inputRef?.focus();
385 }}
386 title="Aramayı Temizle"
387 >
388 <IconX class="h-3.5 w-3.5" />
389 </button>
390 <span class="rounded-md bg-secondary px-2 py-0.5 text-xs font-semibold text-muted-foreground shrink-0 font-mono">
391 {filteredItems().length} {t("dashboard.ready").toLowerCase()}
392 </span>
393 </Show>
394 </div>
395
396 {/* Command Items List */}
397 <div ref={listRef} class="max-h-[min(65vh,28rem)] overflow-y-auto p-2 space-y-4">
398 <Show
399 when={filteredItems().length > 0}
400 fallback={<p class="px-3 py-12 text-center text-sm text-muted-foreground">{t("common.noResults")}</p>}
401 >
402 <For each={groupedItems()}>
403 {(group) => (
404 <div class="space-y-1">
405 <div class="px-3 py-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground/70">
406 {group.label}
407 </div>
408 <For each={group.items}>
409 {({ item, globalIndex }) => {
410 const isSelected = () => selectedIndex() === globalIndex;
411 const ItemIcon = item.icon;
412 return (
413 <button
414 type="button"
415 data-index={globalIndex}
416 onClick={() => executeItem(item)}
417 onMouseEnter={() => setSelectedIndex(globalIndex)}
418 class={cn(
419 "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",
420 isSelected()
421 ? "bg-accent text-accent-foreground font-medium shadow-xs"
422 : "text-foreground hover:bg-secondary/60",
423 )}
424 >
425 <div
426 class={cn(
427 "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors",
428 isSelected()
429 ? "bg-primary text-primary-foreground"
430 : "bg-muted text-muted-foreground",
431 )}
432 >
433 <ItemIcon class="h-4 w-4" />
434 </div>
435
436 <div class="min-w-0 flex-1">
437 <div class="flex items-center gap-2">
438 <span class="truncate text-sm font-medium">{item.title}</span>
439 <Show when={item.roleBadge}>
440 <span class="rounded-full bg-secondary border border-border px-2 py-0.2 text-[10px] font-semibold text-muted-foreground">
441 {item.roleBadge}
442 </span>
443 </Show>
444 </div>
445 <Show when={item.description}>
446 <p class="truncate text-xs text-muted-foreground">{item.description}</p>
447 </Show>
448 </div>
449
450 <Show when={item.shortcut}>
451 <kbd class="hidden shrink-0 rounded-md border border-border/80 bg-muted/60 px-2 py-0.5 font-mono text-[10px] font-semibold text-muted-foreground sm:inline-block">
452 {item.shortcut}
453 </kbd>
454 </Show>
455 </button>
456 );
457 }}
458 </For>
459 </div>
460 )}
461 </For>
462 </Show>
463 </div>
464
465 {/* Command Palette Footer */}
466 <div class="flex items-center justify-between border-t border-border/60 bg-muted/30 px-4 py-2 text-xs text-muted-foreground">
467 <span class="truncate">{t("command.shortcutHint")}</span>
468 <div class="flex items-center gap-2 font-mono shrink-0">
469 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-semibold">↑↓</kbd>
470 <span>navigasyon</span>
471 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-semibold">↵</kbd>
472 <span>seç</span>
473 <kbd class="rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-semibold">Esc</kbd>
474 <span>kapat</span>
475 </div>
476 </div>
477 </DialogContent>
478 </Dialog>
479 );
480}