-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
KBarResults.tsx
194 lines (179 loc) · 5.97 KB
/
KBarResults.tsx
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
import * as React from "react";
import { useVirtual } from "react-virtual";
import { ActionImpl } from "./action/ActionImpl";
import { getListboxItemId, KBAR_LISTBOX } from "./KBarSearch";
import { useKBar } from "./useKBar";
import { usePointerMovedSinceMount } from "./utils";
const START_INDEX = 0;
interface RenderParams<T = ActionImpl | string> {
item: T;
active: boolean;
}
interface KBarResultsProps {
items: any[];
onRender: (params: RenderParams) => React.ReactElement;
maxHeight?: number;
}
export const KBarResults: React.FC<KBarResultsProps> = (props) => {
const activeRef = React.useRef<HTMLDivElement>(null);
const parentRef = React.useRef(null);
// store a ref to all items so we do not have to pass
// them as a dependency when setting up event listeners.
const itemsRef = React.useRef(props.items);
itemsRef.current = props.items;
const rowVirtualizer = useVirtual({
size: itemsRef.current.length,
parentRef,
});
const { query, search, currentRootActionId, activeIndex, options } = useKBar(
(state) => ({
search: state.searchQuery,
currentRootActionId: state.currentRootActionId,
activeIndex: state.activeIndex,
})
);
React.useEffect(() => {
const handler = (event) => {
if (event.isComposing) {
return;
}
if (event.key === "ArrowUp" || (event.ctrlKey && event.key === "p")) {
event.preventDefault();
event.stopPropagation();
query.setActiveIndex((index) => {
let nextIndex = index > START_INDEX ? index - 1 : index;
// avoid setting active index on a group
if (typeof itemsRef.current[nextIndex] === "string") {
if (nextIndex === 0) return index;
nextIndex -= 1;
}
return nextIndex;
});
} else if (
event.key === "ArrowDown" ||
(event.ctrlKey && event.key === "n")
) {
event.preventDefault();
event.stopPropagation();
query.setActiveIndex((index) => {
let nextIndex =
index < itemsRef.current.length - 1 ? index + 1 : index;
// avoid setting active index on a group
if (typeof itemsRef.current[nextIndex] === "string") {
if (nextIndex === itemsRef.current.length - 1) return index;
nextIndex += 1;
}
return nextIndex;
});
} else if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
// storing the active dom element in a ref prevents us from
// having to calculate the current action to perform based
// on the `activeIndex`, which we would have needed to add
// as part of the dependencies array.
activeRef.current?.click();
}
};
window.addEventListener("keydown", handler, {capture: true});
return () => window.removeEventListener("keydown", handler, {capture: true});
}, [query]);
// destructuring here to prevent linter warning to pass
// entire rowVirtualizer in the dependencies array.
const { scrollToIndex } = rowVirtualizer;
React.useEffect(() => {
scrollToIndex(activeIndex, {
// ensure that if the first item in the list is a group
// name and we are focused on the second item, to not
// scroll past that group, hiding it.
align: activeIndex <= 1 ? "end" : "auto",
});
}, [activeIndex, scrollToIndex]);
React.useEffect(() => {
// TODO(tim): fix scenario where async actions load in
// and active index is reset to the first item. i.e. when
// users register actions and bust the `useRegisterActions`
// cache, we won't want to reset their active index as they
// are navigating the list.
query.setActiveIndex(
// avoid setting active index on a group
typeof props.items[START_INDEX] === "string"
? START_INDEX + 1
: START_INDEX
);
}, [search, currentRootActionId, props.items, query]);
const execute = React.useCallback(
(item: RenderParams["item"]) => {
if (typeof item === "string") return;
if (item.command) {
item.command.perform(item);
query.toggle();
} else {
query.setSearch("");
query.setCurrentRootAction(item.id);
}
options.callbacks?.onSelectAction?.(item);
},
[query, options]
);
const pointerMoved = usePointerMovedSinceMount();
return (
<div
ref={parentRef}
style={{
maxHeight: props.maxHeight || 400,
position: "relative",
overflow: "auto",
}}
>
<div
role="listbox"
id={KBAR_LISTBOX}
style={{
height: `${rowVirtualizer.totalSize}px`,
width: "100%",
}}
>
{rowVirtualizer.virtualItems.map((virtualRow) => {
const item = itemsRef.current[virtualRow.index];
const handlers = typeof item !== "string" && {
onPointerMove: () =>
pointerMoved &&
activeIndex !== virtualRow.index &&
query.setActiveIndex(virtualRow.index),
onPointerDown: () => query.setActiveIndex(virtualRow.index),
onClick: () => execute(item),
};
const active = virtualRow.index === activeIndex;
return (
<div
ref={active ? activeRef : null}
id={getListboxItemId(virtualRow.index)}
role="option"
aria-selected={active}
key={virtualRow.index}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
{...handlers}
>
{React.cloneElement(
props.onRender({
item,
active,
}),
{
ref: virtualRow.measureRef,
}
)}
</div>
);
})}
</div>
</div>
);
};