/
index.tsx
363 lines (319 loc) · 10.6 KB
/
index.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/**
* Welcome to @reach/popover!
*/
import React, { useRef, forwardRef, useEffect } from "react";
import Portal from "@reach/portal";
import { useRect, PRect } from "@reach/rect";
import { getOwnerDocument, useForkedRef } from "@reach/utils";
import tabbable from "tabbable";
////////////////////////////////////////////////////////////////////////////////
/**
* Popover
*/
const Popover = forwardRef<HTMLDivElement, PopoverProps>(function Popover(
props,
ref
) {
return (
<Portal>
<PopoverImpl ref={ref} {...props} />
</Portal>
);
});
export type PopoverProps = {
children: React.ReactNode;
targetRef: React.RefObject<HTMLElement>;
position?: Position;
/**
* Testing this API so we might accept additional nodes that apps can use to
* determine the position of the popover. One example where it may be useful
* is for positioning the popover of a listbox where the cursor rests on top
* of the selected option. Pretty sure this will change so don't use it
* anywehre in public yet!
*/
unstable_observableRefs?: React.RefObject<PossibleNode>[];
} & React.HTMLAttributes<HTMLDivElement>;
if (__DEV__) {
Popover.displayName = "Popover";
}
export default Popover;
////////////////////////////////////////////////////////////////////////////////
/**
* PopoverImpl
*
* Popover is conditionally rendered so we can't start measuring until it shows
* up, so useRect needs to live down here not up in Popover
*/
const PopoverImpl = forwardRef<HTMLDivElement, PopoverProps>(
function PopoverImpl(
{
targetRef,
position = positionDefault,
unstable_observableRefs = [],
...props
},
forwardedRef
) {
const popoverRef = useRef<HTMLDivElement>(null);
const popoverRect = useRect(popoverRef);
const targetRect = useRect(targetRef);
const ref = useForkedRef(popoverRef, forwardedRef);
useSimulateTabNavigationForReactTree(targetRef, popoverRef);
return (
<div
data-reach-popover=""
ref={ref}
{...props}
style={{
position: "absolute",
...getStyles(
position,
targetRect,
popoverRect,
...unstable_observableRefs
),
...props.style,
}}
/>
);
}
);
if (__DEV__) {
PopoverImpl.displayName = "PopoverImpl";
}
////////////////////////////////////////////////////////////////////////////////
function getStyles(
position: Position,
targetRect: PRect | null,
popoverRect: PRect | null,
...unstable_observableRefs: React.RefObject<PossibleNode>[]
): React.CSSProperties {
return popoverRect
? position(
targetRect,
popoverRect,
...unstable_observableRefs.map((ref) => ref.current)
)
: { visibility: "hidden" };
}
function getTopPosition(targetRect: PRect, popoverRect: PRect) {
const { directionUp } = getCollisions(targetRect, popoverRect);
return {
top: directionUp
? `${targetRect.top - popoverRect.height + window.pageYOffset}px`
: `${targetRect.top + targetRect.height + window.pageYOffset}px`,
};
}
export const positionDefault: Position = (targetRect, popoverRect) => {
if (!targetRect || !popoverRect) {
return {};
}
const { directionRight } = getCollisions(targetRect, popoverRect);
return {
left: directionRight
? `${targetRect.right - popoverRect.width + window.pageXOffset}px`
: `${targetRect.left + window.pageXOffset}px`,
...getTopPosition(targetRect, popoverRect),
};
};
export const positionRight: Position = (targetRect, popoverRect) => {
if (!targetRect || !popoverRect) {
return {};
}
const { directionLeft } = getCollisions(targetRect, popoverRect);
return {
left: directionLeft
? `${targetRect.left + window.pageXOffset}px`
: `${targetRect.right - popoverRect.width + window.pageXOffset}px`,
...getTopPosition(targetRect, popoverRect),
};
};
export const positionMatchWidth: Position = (targetRect, popoverRect) => {
if (!targetRect || !popoverRect) {
return {};
}
return {
width: targetRect.width,
left: targetRect.left,
...getTopPosition(targetRect, popoverRect),
};
};
export function getCollisions(
targetRect: PRect,
popoverRect: PRect,
offsetLeft: number = 0,
offsetBottom: number = 0
) {
const collisions = {
top: targetRect.top - popoverRect.height < 0,
right: window.innerWidth < targetRect.left + popoverRect.width - offsetLeft,
bottom:
window.innerHeight <
targetRect.bottom + popoverRect.height - offsetBottom,
left: targetRect.left + targetRect.width - popoverRect.width < 0,
};
const directionRight = collisions.right && !collisions.left;
const directionLeft = collisions.left && !collisions.right;
const directionUp = collisions.bottom && !collisions.top;
const directionDown = collisions.top && !collisions.bottom;
return { directionRight, directionLeft, directionUp, directionDown };
}
// Heads up, my jQuery past haunts this function. This hook scopes the tab
// order to the React element tree, instead of the DOM tree. This way, when the
// user navigates with tab from the targetRef, the tab order moves into the
// popup, and then out of the popup back to the rest of the document.
// (We call targetRef, triggerRef inside this function to avoid confusion with
// event.target)
function useSimulateTabNavigationForReactTree<
T extends HTMLElement = HTMLElement,
P extends HTMLElement = HTMLElement
>(triggerRef: React.RefObject<T>, popoverRef: React.RefObject<P>) {
const ownerDocument = getOwnerDocument(triggerRef.current);
function handleKeyDown(event: KeyboardEvent) {
if (
event.key === "Tab" &&
popoverRef.current &&
tabbable(popoverRef.current).length === 0
) {
return;
}
if (event.key === "Tab" && event.shiftKey) {
if (shiftTabbedFromElementAfterTrigger(event)) {
focusLastTabbableInPopover(event);
} else if (shiftTabbedOutOfPopover(event)) {
focusTriggerRef(event);
} else if (shiftTabbedToBrowserChrome(event)) {
disableTabbablesInPopover();
}
} else if (event.key === "Tab") {
if (tabbedFromTriggerToPopover()) {
focusFirstPopoverTabbable(event);
} else if (tabbedOutOfPopover()) {
focusTabbableAfterTrigger(event);
} else if (tabbedToBrowserChrome(event)) {
disableTabbablesInPopover();
}
}
}
useEffect(() => {
if (ownerDocument) {
ownerDocument.addEventListener("keydown", handleKeyDown);
return () => {
ownerDocument.removeEventListener("keydown", handleKeyDown);
};
}
return;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function getElementAfterTrigger() {
const elements = ownerDocument && tabbable(ownerDocument);
const targetIndex =
elements && triggerRef.current
? elements.indexOf(triggerRef.current)
: -1;
const elementAfterTrigger = elements && elements[targetIndex + 1];
return popoverRef.current &&
popoverRef.current.contains(elementAfterTrigger || null)
? false
: elementAfterTrigger;
}
function tabbedFromTriggerToPopover() {
return triggerRef.current && ownerDocument
? triggerRef.current === ownerDocument.activeElement
: false;
}
function focusFirstPopoverTabbable(event: KeyboardEvent) {
const elements = popoverRef.current && tabbable(popoverRef.current);
if (elements && elements[0]) {
event.preventDefault();
elements[0].focus();
}
}
function tabbedOutOfPopover() {
const inPopover =
popoverRef.current && ownerDocument
? popoverRef.current.contains(ownerDocument.activeElement || null)
: false;
if (inPopover) {
const elements = popoverRef.current && tabbable(popoverRef.current);
return Boolean(
elements &&
ownerDocument &&
elements[elements.length - 1] === ownerDocument.activeElement
);
}
return false;
}
function focusTabbableAfterTrigger(event: KeyboardEvent) {
const elementAfterTrigger = getElementAfterTrigger();
if (elementAfterTrigger) {
event.preventDefault();
elementAfterTrigger.focus();
}
}
function shiftTabbedFromElementAfterTrigger(event: KeyboardEvent) {
if (!event.shiftKey) return;
const elementAfterTrigger = getElementAfterTrigger();
return event.target === elementAfterTrigger;
}
function focusLastTabbableInPopover(event: KeyboardEvent) {
const elements = popoverRef.current && tabbable(popoverRef.current);
const last = elements && elements[elements.length - 1];
if (last) {
event.preventDefault();
last.focus();
}
}
function shiftTabbedOutOfPopover(event: KeyboardEvent) {
const elements = popoverRef.current && tabbable(popoverRef.current);
if (elements) {
return elements.length === 0 ? false : event.target === elements[0];
}
return false;
}
function focusTriggerRef(event: KeyboardEvent) {
event.preventDefault();
triggerRef.current?.focus();
}
function tabbedToBrowserChrome(event: KeyboardEvent) {
const elements =
ownerDocument && popoverRef.current
? tabbable(ownerDocument).filter(
(element) => !popoverRef.current!.contains(element)
)
: null;
return elements ? event.target === elements[elements.length - 1] : false;
}
function shiftTabbedToBrowserChrome(event: KeyboardEvent) {
// we're assuming the popover will never contain the first tabbable
// element, and it better not, because the trigger needs to be tabbable!
return ownerDocument ? event.target === tabbable(ownerDocument)[0] : false;
}
let restoreTabIndexTuplés: [HTMLElement, number][] = [];
function disableTabbablesInPopover() {
const elements = popoverRef.current && tabbable(popoverRef.current);
if (elements) {
elements.forEach((element) => {
restoreTabIndexTuplés.push([element, element.tabIndex]);
element.tabIndex = -1;
});
ownerDocument &&
ownerDocument.addEventListener("focusin", enableTabbablesInPopover);
}
}
function enableTabbablesInPopover() {
ownerDocument &&
ownerDocument.removeEventListener("focusin", enableTabbablesInPopover);
restoreTabIndexTuplés.forEach(([element, tabIndex]) => {
element.tabIndex = tabIndex;
});
}
}
////////////////////////////////////////////////////////////////////////////////
// Types
export type Position = (
targetRect?: PRect | null,
popoverRect?: PRect | null,
...unstable_observableNodes: PossibleNode[]
) => React.CSSProperties;
type PossibleNode = null | undefined | HTMLElement | SVGElement;