|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import Dialog from "@mui/material/Dialog"; |
| 4 | +import { useTheme } from "@mui/material/styles"; |
| 5 | +import Typography from "@mui/material/Typography"; |
| 6 | +import useMediaQuery from "@mui/material/useMediaQuery"; |
| 7 | +import { |
| 8 | + type Command, |
| 9 | + type CommandGroup, |
| 10 | + getPlatform, |
| 11 | + SCORE_CUTOFF, |
| 12 | + scoreCommand, |
| 13 | + useCommandPaletteStore, |
| 14 | + useSearchStore, |
| 15 | +} from "@openmapx/core"; |
| 16 | +import { useTranslations } from "next-intl"; |
| 17 | +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; |
| 18 | +import { CommandPaletteFooter } from "./CommandPaletteFooter"; |
| 19 | +import { CommandPaletteInput } from "./CommandPaletteInput"; |
| 20 | +import { buildDefaultCommandRows, CommandPaletteList } from "./CommandPaletteList"; |
| 21 | +import { COMMAND_PALETTE_LISTBOX_ID, SEARCH_INPUT_ID } from "./constants"; |
| 22 | + |
| 23 | +interface Props { |
| 24 | + /** Command list — provided by `GlobalKeybindings` so the palette, the |
| 25 | + * shortcuts dialog, and the global listener all share a single instance. */ |
| 26 | + commands: Command[]; |
| 27 | +} |
| 28 | + |
| 29 | +// Synthetic id (double-underscore prefix) so it can't collide with any real |
| 30 | +// command id in the `search` group. |
| 31 | +const SEARCH_FALLBACK_ID = "__search-fallback__"; |
| 32 | + |
| 33 | +export function CommandPalette({ commands }: Props) { |
| 34 | + const theme = useTheme(); |
| 35 | + const isXs = useMediaQuery(theme.breakpoints.down("sm")); |
| 36 | + const t = useTranslations("commandPalette"); |
| 37 | + |
| 38 | + const isOpen = useCommandPaletteStore((s) => s.isOpen); |
| 39 | + const close = useCommandPaletteStore((s) => s.close); |
| 40 | + const query = useCommandPaletteStore((s) => s.query); |
| 41 | + const setQuery = useCommandPaletteStore((s) => s.setQuery); |
| 42 | + |
| 43 | + const setSearchQuery = useSearchStore((s) => s.setQuery); |
| 44 | + |
| 45 | + const inputRef = useRef<HTMLInputElement | null>(null); |
| 46 | + const [highlight, setHighlight] = useState(0); |
| 47 | + // Groups the user has expanded via a "+N more" row in this open session. |
| 48 | + // Reset on each palette open so reopening starts collapsed. |
| 49 | + const [expandedGroups, setExpandedGroups] = useState<ReadonlySet<CommandGroup>>(() => new Set()); |
| 50 | + |
| 51 | + const handleQueryChange = useCallback( |
| 52 | + (nextQuery: string) => { |
| 53 | + setQuery(nextQuery); |
| 54 | + setHighlight(0); |
| 55 | + }, |
| 56 | + [setQuery], |
| 57 | + ); |
| 58 | + |
| 59 | + const handleExpandGroup = useCallback((group: CommandGroup) => { |
| 60 | + setExpandedGroups((prev) => { |
| 61 | + if (prev.has(group)) return prev; |
| 62 | + const next = new Set(prev); |
| 63 | + next.add(group); |
| 64 | + return next; |
| 65 | + }); |
| 66 | + }, []); |
| 67 | + |
| 68 | + // Hand-off to SearchBar — runs the user's query through the regular search flow. |
| 69 | + const handleSearchOnMap = useCallback(() => { |
| 70 | + const q = query.trim(); |
| 71 | + close(); |
| 72 | + if (!q) return; |
| 73 | + requestAnimationFrame(() => { |
| 74 | + setSearchQuery(q); |
| 75 | + const el = document.getElementById(SEARCH_INPUT_ID) as HTMLInputElement | null; |
| 76 | + el?.focus(); |
| 77 | + }); |
| 78 | + }, [close, query, setSearchQuery]); |
| 79 | + |
| 80 | + // Ranked filtered list when query is present, otherwise the raw command list. |
| 81 | + // When filtering, the synthetic "Search '<q>' on map" row is always appended so |
| 82 | + // it can be navigated by ↑↓ alongside real matches. |
| 83 | + const ranked = useMemo<Command[] | null>(() => { |
| 84 | + const q = query.trim(); |
| 85 | + if (!q) return null; |
| 86 | + const matches = commands |
| 87 | + .map((c) => ({ c, s: scoreCommand(q, c) })) |
| 88 | + .filter((x) => x.s >= SCORE_CUTOFF) |
| 89 | + .sort((a, b) => b.s - a.s) |
| 90 | + .map((x) => x.c); |
| 91 | + const fallback: Command = { |
| 92 | + id: SEARCH_FALLBACK_ID, |
| 93 | + group: "search", |
| 94 | + label: t("searchOnMap", { query: q }), |
| 95 | + iconKey: "search", |
| 96 | + run: handleSearchOnMap, |
| 97 | + }; |
| 98 | + return [...matches, fallback]; |
| 99 | + }, [commands, query, t, handleSearchOnMap]); |
| 100 | + |
| 101 | + const defaultRows = useMemo( |
| 102 | + () => |
| 103 | + buildDefaultCommandRows(commands, { |
| 104 | + expandedGroups, |
| 105 | + onExpandGroup: handleExpandGroup, |
| 106 | + t: (key, values) => t(key, values), |
| 107 | + }), |
| 108 | + [commands, expandedGroups, handleExpandGroup, t], |
| 109 | + ); |
| 110 | + const visible = useMemo(() => ranked ?? defaultRows, [ranked, defaultRows]); |
| 111 | + const noRealMatches = ranked !== null && ranked.length === 1; // only the fallback |
| 112 | + |
| 113 | + // Reset state on open |
| 114 | + useEffect(() => { |
| 115 | + if (isOpen) { |
| 116 | + setHighlight(0); |
| 117 | + setExpandedGroups(new Set()); |
| 118 | + // Auto-select existing text on re-open |
| 119 | + requestAnimationFrame(() => inputRef.current?.select()); |
| 120 | + } |
| 121 | + }, [isOpen]); |
| 122 | + |
| 123 | + // Keep the highlighted row scrolled into view as the user arrow-keys past the |
| 124 | + // visible area. |
| 125 | + useEffect(() => { |
| 126 | + const cmd = visible[highlight]; |
| 127 | + if (!cmd) return; |
| 128 | + const el = document.getElementById(`command-row-${cmd.id}`); |
| 129 | + el?.scrollIntoView({ block: "nearest" }); |
| 130 | + }, [highlight, visible]); |
| 131 | + |
| 132 | + const runCommand = useCallback( |
| 133 | + (cmd: Command, event?: { metaKey?: boolean; ctrlKey?: boolean }) => { |
| 134 | + // Platform-aware "keep open" modifier so Ctrl+Enter doesn't trigger |
| 135 | + // it on macOS (where the user expects ⌘+Enter only). |
| 136 | + const isMac = getPlatform() === "mac"; |
| 137 | + const keepOpen = isMac ? !!event?.metaKey : !!event?.ctrlKey; |
| 138 | + try { |
| 139 | + const result = cmd.run(); |
| 140 | + if (!keepOpen && result !== false) close(); |
| 141 | + } catch (e) { |
| 142 | + console.error(`[command-palette] '${cmd.id}' failed:`, e); |
| 143 | + } |
| 144 | + }, |
| 145 | + [close], |
| 146 | + ); |
| 147 | + |
| 148 | + const handleKeyDown = useCallback( |
| 149 | + (e: React.KeyboardEvent<HTMLInputElement>) => { |
| 150 | + if (e.key === "ArrowDown") { |
| 151 | + e.preventDefault(); |
| 152 | + setHighlight((h) => (visible.length === 0 ? 0 : (h + 1) % visible.length)); |
| 153 | + return; |
| 154 | + } |
| 155 | + if (e.key === "ArrowUp") { |
| 156 | + e.preventDefault(); |
| 157 | + setHighlight((h) => (visible.length === 0 ? 0 : (h - 1 + visible.length) % visible.length)); |
| 158 | + return; |
| 159 | + } |
| 160 | + if (e.key === "Enter") { |
| 161 | + e.preventDefault(); |
| 162 | + const cmd = visible[highlight]; |
| 163 | + if (cmd) { |
| 164 | + runCommand(cmd, { metaKey: e.metaKey, ctrlKey: e.ctrlKey }); |
| 165 | + } |
| 166 | + return; |
| 167 | + } |
| 168 | + // Escape is handled by the global keybindings listener. |
| 169 | + }, |
| 170 | + [visible, highlight, runCommand], |
| 171 | + ); |
| 172 | + |
| 173 | + const selected = visible[highlight] ?? null; |
| 174 | + const selectedDomId = selected ? `command-row-${selected.id}` : null; |
| 175 | + |
| 176 | + return ( |
| 177 | + <Dialog |
| 178 | + open={isOpen} |
| 179 | + onClose={close} |
| 180 | + fullScreen={isXs} |
| 181 | + maxWidth="sm" |
| 182 | + fullWidth |
| 183 | + slotProps={{ |
| 184 | + paper: { |
| 185 | + sx: { |
| 186 | + position: (isXs ? undefined : "absolute") as "absolute" | undefined, |
| 187 | + top: isXs ? undefined : 80, |
| 188 | + m: isXs ? 0 : 2, |
| 189 | + borderRadius: isXs ? 0 : 2, |
| 190 | + maxHeight: isXs ? "100dvh" : "70dvh", |
| 191 | + display: "flex", |
| 192 | + flexDirection: "column", |
| 193 | + overflow: "hidden", |
| 194 | + }, |
| 195 | + }, |
| 196 | + backdrop: { |
| 197 | + sx: { backgroundColor: "rgba(0,0,0,0.32)" }, |
| 198 | + }, |
| 199 | + }} |
| 200 | + > |
| 201 | + <CommandPaletteInput |
| 202 | + ref={inputRef} |
| 203 | + query={query} |
| 204 | + onQueryChange={handleQueryChange} |
| 205 | + onClose={close} |
| 206 | + onKeyDown={handleKeyDown} |
| 207 | + activeDescendantId={selectedDomId} |
| 208 | + /> |
| 209 | + <div style={{ overflowY: "auto", flex: 1 }}> |
| 210 | + {noRealMatches && ( |
| 211 | + <Typography sx={{ px: 2, py: 1.5, color: "text.secondary", fontSize: 14 }}> |
| 212 | + {t("noResults")} |
| 213 | + </Typography> |
| 214 | + )} |
| 215 | + <CommandPaletteList |
| 216 | + defaultRows={defaultRows} |
| 217 | + rankedOverride={ranked} |
| 218 | + selectedId={selected?.id ?? null} |
| 219 | + listboxId={COMMAND_PALETTE_LISTBOX_ID} |
| 220 | + onRun={(cmd, e) => { |
| 221 | + const evt = e as unknown as { metaKey?: boolean; ctrlKey?: boolean }; |
| 222 | + runCommand(cmd, evt); |
| 223 | + }} |
| 224 | + /> |
| 225 | + </div> |
| 226 | + <CommandPaletteFooter /> |
| 227 | + </Dialog> |
| 228 | + ); |
| 229 | +} |
0 commit comments