import { useNavigate } from "@tanstack/solid-router"; import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"; import { IconBook, IconCalendar, IconDownload, IconExam, IconGlobe, IconHomework, IconLogout, IconMoon, IconNote, IconSearch, IconSparkles, IconSun, IconUsers, IconX, } from "@/components/ui/icons"; import { getUserSearch } from "@/api/users"; import { COMMAND_RECORD_KINDS, COMMAND_RECORD_MIN_QUERY, COMMAND_RECORD_ROUTES, filterCommandRecords, loadCommandRecords, type CommandRecord, type CommandRecordKind, } from "@/lib/command-search"; import { courseKindLabel } from "@/lib/course-kind"; import { formatDate, formatDateTime } from "@/lib/format"; import type { MessageKey } from "@/i18n/messages"; import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items"; import { createStudentClassLabels } from "@/lib/student-classes"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; import { useModules } from "@/stores/modules-context"; import { usePreferences, useT } from "@/stores/preferences-context"; import { cn } from "@/lib/cn"; import { matchesSearch } from "@/lib/search-text"; export type CommandPaletteProps = { open: boolean; onOpenChange: (open: boolean) => void; onOpenCelebi?: () => void; onOpenProfile?: () => void; }; type CommandCategory = "people" | CommandRecordKind | "actions" | "pages" | "system"; const RECORD_GROUP_KEY: Record = { course: "command.group.courses", exam: "command.group.exams", homework: "command.group.homework", event: "command.group.events", }; const RECORD_ICON: Record = { course: IconBook, exam: IconExam, homework: IconHomework, event: IconCalendar, }; type CommandItem = { id: string; category: CommandCategory; categoryLabel: string; title: string; description?: string; keywords?: string; icon: typeof IconSearch; shortcut?: string; roleBadge?: string; onSelect: () => void; }; export function CommandPalette(props: CommandPaletteProps) { const auth = useAuth(); const prefs = usePreferences(); const t = useT(); const navigate = useNavigate(); const modules = useModules(); const [query, setQuery] = createSignal(""); const [selectedIndex, setSelectedIndex] = createSignal(0); let inputRef: HTMLInputElement | undefined; let listRef: HTMLDivElement | undefined; const role = () => auth.user()?.role; // Student lookup moved here from the dashboard hero. `/users/search` is the // app's only search endpoint and the user detail page is admin-only, so the // "people" section exists for admins alone. const [peopleQuery, setPeopleQuery] = createSignal(""); let peopleDebounce: ReturnType | undefined; createEffect(() => { const q = query().trim(); clearTimeout(peopleDebounce); peopleDebounce = setTimeout(() => setPeopleQuery(q.length >= 2 ? q : ""), 250); }); onCleanup(() => clearTimeout(peopleDebounce)); const [people] = createResource( () => (props.open && role() === "admin" && peopleQuery() ? peopleQuery() : null), (q) => getUserSearch(q, undefined, "student", { limit: 6 }), ); // Two students called "Ayşe Yılmaz" are only told apart by their class, so // each visible match is resolved to one (see `student-classes`). const classLabels = createStudentClassLabels(() => (people.latest?.items ?? []).map((person) => person.id)); // Courses, exams, homework and events the user's own list pages show. Only // kinds whose list page is in this user's nav are searched, read once per // open (cached briefly across reopens) and filtered client-side per keystroke. const recordKinds = createMemo(() => { const routes = new Set( visibleNavGroups(role(), modules.enabled()).flatMap((group) => group.items.map((item) => item.to)), ); return COMMAND_RECORD_KINDS.filter((kind) => routes.has(COMMAND_RECORD_ROUTES[kind])); }); const [records] = createResource( () => { const userRole = role(); const kinds = recordKinds(); return props.open && userRole && kinds.length > 0 ? { role: userRole, kinds } : null; }, (source) => loadCommandRecords(source.role, source.kinds), ); const recordDescription = (record: CommandRecord): string | undefined => { const locale = prefs.locale(); switch (record.kind) { case "course": return record.courseKind ? courseKindLabel(record.courseKind, t) : undefined; case "exam": return [record.context, record.at != null ? formatDateTime(record.at, locale) : null].filter(Boolean).join(" · ") || undefined; case "homework": return [record.context, record.at != null ? t("command.homeworkDue", { date: formatDate(record.at, locale) }) : null] .filter(Boolean) .join(" · ") || undefined; case "event": return record.at != null ? formatDateTime(record.at, locale) : undefined; } }; const openRecord = (record: CommandRecord) => { const params = { id: record.id }; if (record.kind === "course") void navigate({ to: "/courses/$id", params }); else if (record.kind === "exam") void navigate({ to: "/exams/$id", params }); else if (record.kind === "homework") void navigate({ to: "/homework/$id", params }); else void navigate({ to: "/events/$id", params }); }; const recordsLoading = () => records.loading && query().trim().length >= COMMAND_RECORD_MIN_QUERY && records.latest === undefined; const items = createMemo(() => { const list: CommandItem[] = []; const userRole = role(); const isTeacherPlus = hasMinRole(userRole, "teacher"); const isStudent = userRole === "student"; const mod = "Ctrl/Cmd + "; // 1. Quick Actions (Hızlı İşlemler) const actionsCategoryLabel = t("command.group.actions"); if (isTeacherPlus) { list.push({ id: "action-create-homework", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.createHomework"), description: t("command.action.createHomeworkDesc"), keywords: "homework odev ekle olustur ders", icon: IconHomework, shortcut: `${mod}H`, roleBadge: t("role.teacher"), onSelect: () => void navigate({ to: "/homework", search: { action: "new" } as any }), }); list.push({ id: "action-create-course", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.createCourse"), description: t("command.action.createCourseDesc"), keywords: "course ders kurs olustur egitim", icon: IconBook, shortcut: `${mod}C`, roleBadge: t("role.teacher"), onSelect: () => void navigate({ to: "/courses", search: { action: "new" } as any }), }); list.push({ id: "action-create-event", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.createEvent"), description: t("command.action.createEventDesc"), keywords: "event etkinlik planla takvim oturum", icon: IconCalendar, shortcut: `${mod}E`, roleBadge: t("role.teacher"), onSelect: () => void navigate({ to: "/events", search: { action: "new" } as any }), }); list.push({ id: "action-create-exam", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.createExam"), description: t("command.action.createExamDesc"), keywords: "exam sinav test hazirla olustur", icon: IconExam, shortcut: `${mod}X`, roleBadge: t("role.teacher"), onSelect: () => void navigate({ to: "/exams", search: { action: "new" } as any }), }); } // Common Quick Actions for all roles list.push({ id: "action-create-note", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.createNote"), description: t("command.action.createNoteDesc"), keywords: "note not ekle ders notu kaydet", icon: IconNote, shortcut: `${mod}N`, onSelect: () => void navigate({ to: "/notes/new" }), }); list.push({ id: "action-import-note", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.importNote"), description: t("command.action.importNoteDesc"), keywords: "import ice aktar pdf txt markdown assistant", icon: IconDownload, onSelect: () => void navigate({ to: "/notes", search: { action: "import" } as any }), }); list.push({ id: "action-ask-question", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.askQuestion"), description: t("command.action.askQuestionDesc"), keywords: "question soru sor havuz ekle topluluk", icon: IconExam, shortcut: `${mod}Q`, roleBadge: isStudent ? t("role.student") : undefined, onSelect: () => void navigate({ to: "/questions", search: { action: "new" } as any }), }); if (props.onOpenCelebi) { list.push({ id: "action-ask-celebi", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.askCelebi"), description: t("command.action.askCelebiDesc"), keywords: "celebi ai yapay zeka sohbet asistan yardım", icon: IconSparkles, onSelect: () => props.onOpenCelebi?.(), }); } if (props.onOpenProfile) { list.push({ id: "action-my-profile", category: "actions", categoryLabel: actionsCategoryLabel, title: t("command.action.myProfile"), description: t("command.action.myProfileDesc"), keywords: "profile profil hesabim kullanici sifre", icon: IconUsers, onSelect: () => props.onOpenProfile?.(), }); } // 2. Navigation Pages (Sayfalar & Gezinme) const pagesCategoryLabel = t("command.group.navigation"); list.push({ id: "page-home", category: "pages", categoryLabel: pagesCategoryLabel, title: t(HOME_ITEM.labelKey), description: t("app.name"), keywords: "home anasayfa kontrol paneli dashboard", icon: HOME_ITEM.Icon, onSelect: () => void navigate({ to: HOME_ITEM.to }), }); for (const group of visibleNavGroups(userRole, modules.enabled())) { const groupName = t(group.labelKey); for (const item of group.items) { // Çelebi and the account-settings entries open an existing shell // surface rather than a route — the palette already offers both // above, wired to the panel/dialog directly. if (item.action) continue; list.push({ id: `page-${item.to}`, category: "pages", categoryLabel: pagesCategoryLabel, title: t(item.labelKey), description: groupName, keywords: `${item.to} ${t(item.labelKey)} ${groupName}`, icon: item.Icon, onSelect: () => void navigate({ to: item.to, search: item.search as never }), }); } } // 3. System Preferences & Account (Sistem & Tercihler) const systemCategoryLabel = t("command.group.system"); const isDark = prefs.theme() === "dark"; list.push({ id: "system-theme-toggle", category: "system", categoryLabel: systemCategoryLabel, title: isDark ? t("command.action.themeLight") : t("command.action.themeDark"), description: isDark ? t("command.action.themeLightDesc") : t("command.action.themeDarkDesc"), keywords: "theme tema koyu acik dark light mode", icon: isDark ? IconSun : IconMoon, onSelect: () => prefs.setTheme(isDark ? "light" : "dark"), }); const isTr = prefs.locale() === "tr"; list.push({ id: "system-lang-toggle", category: "system", categoryLabel: systemCategoryLabel, title: isTr ? t("command.action.langEn") : t("command.action.langTr"), description: isTr ? t("command.action.langEnDesc") : t("command.action.langTrDesc"), keywords: "language dil turkce english tr en", icon: IconGlobe, onSelect: () => prefs.setLocale(isTr ? "en" : "tr"), }); list.push({ id: "system-logout", category: "system", categoryLabel: systemCategoryLabel, title: t("command.action.logout"), description: t("command.action.logoutDesc"), keywords: "logout cıkıs oturum kapat ayrıl", icon: IconLogout, onSelect: async () => { await auth.logout(); void navigate({ to: "/login" }); }, }); return list; }); const filteredItems = createMemo(() => { const q = query().trim(); if (!q) return items(); const peopleLabel = t("command.group.people"); const found: CommandItem[] = (people.latest?.items ?? []).map((person) => ({ id: `person-${person.id}`, category: "people", categoryLabel: peopleLabel, title: person.display_name || person.username, description: classLabels()[person.id] ? `${classLabels()[person.id]} · ${person.username}` : person.username, icon: IconUsers, // Same destination as a row on the students list. onSelect: () => void navigate({ to: "/profile/$userId", params: { userId: person.id } }), })); const matchedRecords: CommandItem[] = filterCommandRecords(records.latest ?? [], q).map((record) => ({ id: `${record.kind}-${record.id}`, category: record.kind, categoryLabel: t(RECORD_GROUP_KEY[record.kind]), title: record.title, description: recordDescription(record), icon: RECORD_ICON[record.kind], onSelect: () => openRecord(record), })); return [...found, ...matchedRecords, ...items().filter((item) => matchesSearch(q, item.title, item.description, item.keywords, item.categoryLabel), )]; }); // Group items by category while preserving single flat index order for keyboard navigation const groupedItems = createMemo(() => { const list = filteredItems(); const categories: { category: CommandCategory; label: string; items: { item: CommandItem; globalIndex: number }[] }[] = []; const map = new Map(); list.forEach((item, idx) => { if (!map.has(item.category)) { map.set(item.category, []); } map.get(item.category)!.push({ item, globalIndex: idx }); }); const order: CommandCategory[] = ["people", ...COMMAND_RECORD_KINDS, "actions", "pages", "system"]; for (const cat of order) { const itemsInCat = map.get(cat); if (itemsInCat && itemsInCat.length > 0) { categories.push({ category: cat, label: itemsInCat[0].item.categoryLabel, items: itemsInCat, }); } } return categories; }); const executeItem = (item: CommandItem) => { props.onOpenChange(false); item.onSelect(); }; createEffect(() => { if (!props.open) return; setQuery(""); setSelectedIndex(0); }); // Reset selected index when query changes createEffect(() => { query(); setSelectedIndex(0); }); // Auto scroll active item into view createEffect(() => { const idx = selectedIndex(); if (!listRef) return; const activeEl = listRef.querySelector(`[data-index="${idx}"]`); if (activeEl) { activeEl.scrollIntoView({ block: "nearest" }); } }); const handleKeyDown = (event: KeyboardEvent) => { const list = filteredItems(); if (!list.length) return; if (event.key === "ArrowDown") { event.preventDefault(); setSelectedIndex((prev) => (prev + 1) % list.length); } else if (event.key === "ArrowUp") { event.preventDefault(); setSelectedIndex((prev) => (prev - 1 + list.length) % list.length); } else if (event.key === "Enter") { event.preventDefault(); const current = list[selectedIndex()]; if (current) executeItem(current); } }; onMount(() => { const onGlobalKeyDown = (event: KeyboardEvent) => { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") { event.preventDefault(); if (auth.user()) props.onOpenChange(!props.open); } if (event.key === "Escape" && props.open) props.onOpenChange(false); }; window.addEventListener("keydown", onGlobalKeyDown); onCleanup(() => window.removeEventListener("keydown", onGlobalKeyDown)); }); return ( { event.preventDefault(); inputRef?.focus(); }} > {t("dashboard.commandCenter")} {t("common.searchPlaceholder")} {/* Search Bar Header */}
setQuery(event.currentTarget.value)} onKeyDown={handleKeyDown} // Combobox pattern: focus stays in the field while arrow keys move // an active option that assistive tech follows. role="combobox" aria-label={t("common.searchPlaceholder")} aria-expanded="true" aria-controls="command-palette-list" aria-autocomplete="list" aria-activedescendant={filteredItems().length > 0 ? `command-item-${selectedIndex()}` : undefined} /> {t("command.resultCount", { count: filteredItems().length })}
{/* What the field accepts — the palette takes names, pages and actions, and an empty box says none of that on its own. */}

{role() === "admin" ? t("search.hint.commandAdmin") : t("search.hint.command")} 0}> {" "} {t("search.hint.commandRecords", { kinds: recordKinds() .map((kind) => t(RECORD_GROUP_KEY[kind]).toLocaleLowerCase(prefs.locale() === "tr" ? "tr-TR" : "en-US")) .join(", "), })}

{t("command.recordsLoading")}

{/* Command Items List */}
0} fallback={

{t("common.noResults")}

} > {(group, groupIndex) => (
{group.label}
{({ item, globalIndex }) => { const isSelected = () => selectedIndex() === globalIndex; const ItemIcon = item.icon; return ( ); }}
)}
{/* Command Palette Footer — keyboard-only guidance, so it is hidden on phones where there are no arrow, enter or escape keys to press. */}
); }