-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-palette.tsx
More file actions
211 lines (188 loc) · 5.32 KB
/
command-palette.tsx
File metadata and controls
211 lines (188 loc) · 5.32 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
import { useState } from "preact/hooks";
import { listen, query, SigmaType, useListener, useSigma } from "preact-sigma";
type Command = {
id: string;
title: string;
keywords: readonly string[];
};
class UsageLedger {
counts = new Map<string, number>();
get(id: string) {
return this.counts.get(id) ?? 0;
}
increment(id: string) {
this.counts.set(id, this.get(id) + 1);
}
}
const matchesText = query((command: Command, draft: string) => {
const needle = draft.trim().toLowerCase();
if (!needle) {
return true;
}
return (
command.title.toLowerCase().includes(needle) ||
command.keywords.some((keyword) => keyword.toLowerCase().includes(needle))
);
});
const SearchHistory = new SigmaType<{
items: string[];
}>("SearchHistory")
.defaultState({
items: [],
})
.actions({
remember(query: string) {
const value = query.trim();
if (!value) {
return;
}
this.items = [value, ...this.items.filter((item) => item !== value)].slice(0, 5);
},
});
interface SearchHistory extends InstanceType<typeof SearchHistory> {}
const CommandPalette = new SigmaType<
{
commands: Command[];
cursor: number;
draft: string;
history: SearchHistory;
usage: UsageLedger;
},
{
ran: Command;
}
>("CommandPalette")
.defaultState({
commands: [
{ id: "inbox", title: "Open inbox", keywords: ["mail", "messages", "triage"] },
{ id: "capture", title: "Capture note", keywords: ["write", "quick", "idea"] },
{ id: "focus", title: "Start focus timer", keywords: ["pomodoro", "deep work"] },
{ id: "theme", title: "Toggle theme", keywords: ["appearance", "dark", "light"] },
],
cursor: 0,
draft: "",
history: () => new SearchHistory(),
usage: () => new UsageLedger(),
})
.computed({
visibleCommands() {
return this.commands.filter((command) => matchesText(command, this.draft));
},
activeCommand() {
return this.visibleCommands[this.cursor] ?? null;
},
})
.queries({
canRun() {
return this.activeCommand !== null;
},
usageCount(id: string) {
return this.usage.get(id);
},
})
.actions({
setDraft(draft: string) {
this.draft = draft;
this.cursor = 0;
},
move(step: number) {
if (this.visibleCommands.length === 0) {
this.cursor = 0;
return;
}
const lastIndex = this.visibleCommands.length - 1;
this.cursor = Math.max(0, Math.min(lastIndex, this.cursor + step));
},
seedDraftFromHistory() {
const latest = this.history.items[0];
if (latest) {
this.setDraft(latest);
}
},
runActive() {
const command = this.activeCommand;
if (!command || !this.canRun()) {
return;
}
this.history.remember(this.draft || command.title);
this.usage.increment(command.id);
this.emit("ran", command);
this.draft = "";
this.cursor = 0;
},
})
.setup(function () {
return [
listen(window, "keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "k") {
event.preventDefault();
this.seedDraftFromHistory();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
this.move(1);
} else if (event.key === "ArrowUp") {
event.preventDefault();
this.move(-1);
} else if (event.key === "Enter") {
this.runActive();
}
}),
];
});
interface CommandPalette extends InstanceType<typeof CommandPalette> {}
export function CommandPaletteExample() {
const palette = useSigma(() => new CommandPalette());
const [lastRun, setLastRun] = useState<string>("Nothing yet");
useListener(palette, "ran", (command) => {
setLastRun(`${command.title} (${palette.usageCount(command.id)} runs)`);
});
return (
<section>
<p>
<strong>Command palette</strong>: setup-owned keyboard shortcuts, computed getters, tracked
queries with args, typed events, nested sigma state, and a mutable custom class instance.
</p>
<label>
Search
<input
value={palette.draft}
onInput={(event) => palette.setDraft((event.currentTarget as HTMLInputElement).value)}
placeholder="Try: note, timer, inbox"
/>
</label>
<div>
<button type="button" onClick={() => palette.move(-1)}>
Up
</button>
<button type="button" onClick={() => palette.move(1)}>
Down
</button>
<button type="button" onClick={() => palette.runActive()} disabled={!palette.canRun()}>
Run
</button>
</div>
<p>Last run: {lastRun}</p>
<ul>
{palette.visibleCommands.map((command, index) => (
<li key={command.id}>
<button
type="button"
onClick={() => {
palette.setDraft(command.title);
palette.runActive();
}}
style={{
fontWeight: index === palette.cursor ? "700" : "400",
}}
>
{command.title} · used {palette.usageCount(command.id)} times
</button>
</li>
))}
</ul>
<p>History: {palette.history.items.join(" / ") || "empty"}</p>
</section>
);
}