-
-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathCommandPalette.tsx
More file actions
244 lines (228 loc) · 8.53 KB
/
Copy pathCommandPalette.tsx
File metadata and controls
244 lines (228 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"use client";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { api } from "@/server/trpc/react";
import { FEATURE_FLAGS, isFlagEnabled } from "@/utils/flags";
interface CommandPaletteProps {
onClose: () => void;
}
type Item = {
id: string;
label: string;
href: string;
group: string;
sub?: string;
glyph: string;
};
type QuickAction = { label: string; href: string };
// Jobs is flag-gated until launch (auto-on in dev), so the jobs quick action is
// only included when the flag is enabled.
const buildQuickActions = (jobsEnabled: boolean): QuickAction[] => [
{ label: "Go to Feed", href: "/" },
{ label: "Browse Discussions", href: "/discussions" },
...(jobsEnabled ? [{ label: "Find a job", href: "/jobs" }] : []),
{ label: "Write a post", href: "/create" },
{ label: "Saved", href: "/saved" },
{ label: "Notifications", href: "/notifications" },
{ label: "Settings", href: "/settings" },
];
/**
* ⌘K command palette: site-wide search + quick nav. With a query it shows live
* results from `api.search.everything` — Posts, People, Tags — debounced ~300ms;
* with an empty query it falls back to Quick actions. Arrow-key navigation and
* Enter-to-select run over the combined flat list. Mounted only while open (by
* AppShell), which keeps state fresh without a reset effect; AppShell restores
* focus to the trigger on close. Mirrors ui_kits/app/AppShell.jsx → CommandPalette.
*/
export function CommandPalette({ onClose }: CommandPaletteProps) {
const router = useRouter();
const [q, setQ] = useState("");
const [debounced, setDebounced] = useState("");
const [active, setActive] = useState(0);
// Debounce input ~300ms; setState in the timeout satisfies set-state-in-effect.
useEffect(() => {
const t = setTimeout(() => setDebounced(q.trim()), 300);
return () => clearTimeout(t);
}, [q]);
const hasQuery = debounced.length >= 2;
const { data: results, isFetching } = api.search.everything.useQuery(
{ query: debounced, limit: 5 },
{ enabled: hasQuery },
);
const items = useMemo<Item[]>(() => {
if (hasQuery) {
const postItems: Item[] = (results?.posts ?? []).map((p) => ({
id: `p:${p.id}`,
label: p.title,
href: p.href,
group: "Posts",
sub: `${p.upvotes ?? 0} upvotes`,
glyph: "▲",
}));
const peopleItems: Item[] = (results?.people ?? []).map((u) => ({
id: `u:${u.username}`,
label: u.name ?? u.username,
href: `/${u.username}`,
group: "People",
sub: `@${u.username}`,
glyph: "@",
}));
const tagItems: Item[] = (results?.tags ?? []).map((t) => ({
id: `t:${t.slug}`,
label: t.title,
href: `/?tag=${t.slug}`,
group: "Tags",
sub: `${t.postCount ?? 0} posts`,
glyph: "#",
}));
return [...postItems, ...peopleItems, ...tagItems];
}
return buildQuickActions(!!isFlagEnabled(FEATURE_FLAGS.JOBS)).map((a) => ({
id: `a:${a.href}`,
label: a.label,
href: a.href,
group: "Quick actions",
glyph: "›",
}));
}, [hasQuery, results]);
const activeIndex = items.length ? Math.min(active, items.length - 1) : 0;
const go = (href: string) => {
router.push(href);
onClose();
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive(items.length ? (activeIndex + 1) % items.length : 0);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive(
items.length ? (activeIndex - 1 + items.length) % items.length : 0,
);
} else if (e.key === "Enter") {
e.preventDefault();
const item = items[activeIndex];
if (item) go(item.href);
}
};
const groups: { label: string; items: Item[] }[] = [];
for (const item of items) {
const last = groups[groups.length - 1];
if (last && last.label === item.group) last.items.push(item);
else groups.push({ label: item.group, items: [item] });
}
let flatIndex = -1;
return (
<div
onClick={onClose}
className="fixed inset-0 z-[70] flex items-start justify-center px-6 pb-6 pt-[11vh]"
style={{ background: "rgba(4,5,7,0.62)", backdropFilter: "blur(6px)" }}
>
<div
onClick={(e) => e.stopPropagation()}
onKeyDown={onKeyDown}
role="dialog"
aria-modal="true"
aria-label="Search Codú"
className="w-full max-w-[600px] overflow-hidden rounded-xl border border-strong bg-elevated shadow-lg"
>
{/* A subtle thin accent line marks the active field — no focus ring. */}
<div className="flex items-center gap-3 border-b border-hairline px-5 py-4 transition-colors focus-within:border-accent">
<span className="text-lg leading-none text-faint">⌕</span>
<input
autoFocus
value={q}
onChange={(e) => {
setQ(e.target.value);
setActive(0);
}}
placeholder="Search posts, people, tags…"
aria-label="Search"
role="combobox"
aria-expanded="true"
aria-controls="cmdk-list"
// The global focus-visible ring resolves to blue here; opt out and
// let the parent's focus-within accent underline mark the field.
className="flex-1 bg-transparent text-lg text-fg outline-none ring-0 ring-offset-0 placeholder:text-faint focus-visible:ring-0 focus-visible:ring-offset-0"
/>
{/* Desktop closes with the Esc key; mobile gets a tap target. */}
<kbd className="hidden rounded-sm border border-hairline px-1.5 py-0.5 font-mono text-[11px] text-faint sm:inline-flex">
Esc
</kbd>
<button
type="button"
onClick={onClose}
aria-label="Close search"
className="-mr-1 flex h-8 w-8 items-center justify-center rounded-md text-faint transition-colors hover:bg-surface hover:text-fg sm:hidden"
>
<svg
className="h-5 w-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
aria-hidden="true"
>
<path d="M6 6l12 12M18 6L6 18" />
</svg>
</button>
</div>
<div
id="cmdk-list"
role="listbox"
className="max-h-[54vh] overflow-y-auto p-3"
>
{items.length === 0 &&
(hasQuery && isFetching ? (
<div className="p-8 text-center font-mono text-sm text-faint">
{"// "}searching…
</div>
) : (
<div className="p-8 text-center font-mono text-sm text-faint">
{"// "}no matches for “{debounced}”
</div>
))}
{groups.map((group) => (
<div key={group.label} className="mb-2">
<p className="mb-1 px-2.5 font-mono text-[10px] uppercase tracking-[0.18em] text-faint">
{group.label}
</p>
{group.items.map((item) => {
flatIndex += 1;
const isActive = flatIndex === activeIndex;
const idx = flatIndex;
return (
<button
key={item.id}
role="option"
aria-selected={isActive}
onMouseEnter={() => setActive(idx)}
onClick={() => go(item.href)}
className={`flex w-full items-center gap-3 rounded-md px-2.5 py-2 text-left transition-colors ${
isActive ? "bg-surface" : ""
}`}
>
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm border border-hairline font-mono text-[13px] text-faint">
{item.glyph}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-fg">
{item.label}
</span>
{item.sub && (
<span className="block font-mono text-xs text-faint">
{item.sub}
</span>
)}
</span>
</button>
);
})}
</div>
))}
</div>
</div>
</div>
);
}