@react-aria/landmark 3.0.10 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,519 +0,0 @@
1
- /*
2
- * Copyright 2022 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {AriaLabelingProps, DOMAttributes, FocusableElement, RefObject} from '@react-types/shared';
14
- import {getEventTarget, nodeContains, useLayoutEffect} from '@react-aria/utils';
15
- import {useCallback, useEffect, useState} from 'react';
16
- import {useSyncExternalStore} from 'use-sync-external-store/shim/index.js';
17
-
18
- export type AriaLandmarkRole = 'main' | 'region' | 'search' | 'navigation' | 'form' | 'banner' | 'contentinfo' | 'complementary';
19
-
20
- export interface AriaLandmarkProps extends AriaLabelingProps {
21
- role: AriaLandmarkRole,
22
- focus?: (direction: 'forward' | 'backward') => void
23
- }
24
-
25
- export interface LandmarkAria {
26
- landmarkProps: DOMAttributes
27
- }
28
-
29
- // Increment this version number whenever the
30
- // LandmarkManagerApi or Landmark interfaces change.
31
- const LANDMARK_API_VERSION = 1;
32
-
33
- // Minimal API for LandmarkManager that must continue to work between versions.
34
- // Changes to this interface are considered breaking. New methods/properties are
35
- // safe to add, but changes or removals are not allowed (same as public APIs).
36
- interface LandmarkManagerApi {
37
- version: number,
38
- createLandmarkController(): LandmarkController,
39
- registerLandmark(landmark: Landmark): () => void
40
- }
41
-
42
- // Changes to this interface are considered breaking.
43
- // New properties MUST be optional so that registering a landmark
44
- // from an older version of useLandmark against a newer version of
45
- // LandmarkManager does not crash.
46
- interface Landmark {
47
- ref: RefObject<FocusableElement | null>,
48
- role: AriaLandmarkRole,
49
- label?: string,
50
- lastFocused?: FocusableElement,
51
- focus: (direction: 'forward' | 'backward') => void,
52
- blur: () => void
53
- }
54
-
55
- export interface LandmarkControllerOptions {
56
- /**
57
- * The element from which to start navigating.
58
- * @default document.activeElement
59
- */
60
- from?: FocusableElement
61
- }
62
-
63
- /** A LandmarkController allows programmatic navigation of landmarks. */
64
- export interface LandmarkController {
65
- /** Moves focus to the next landmark. */
66
- focusNext(opts?: LandmarkControllerOptions): boolean,
67
- /** Moves focus to the previous landmark. */
68
- focusPrevious(opts?: LandmarkControllerOptions): boolean,
69
- /** Moves focus to the main landmark. */
70
- focusMain(): boolean,
71
- /** Moves focus either forward or backward in the landmark sequence. */
72
- navigate(direction: 'forward' | 'backward', opts?: LandmarkControllerOptions): boolean,
73
- /**
74
- * Disposes the landmark controller. When no landmarks are registered, and no
75
- * controllers are active, the landmark keyboard listeners are removed from the page.
76
- */
77
- dispose(): void
78
- }
79
-
80
- // Symbol under which the singleton landmark manager instance is attached to the document.
81
- const landmarkSymbol = Symbol.for('react-aria-landmark-manager');
82
-
83
- function subscribe(fn: () => void) {
84
- document.addEventListener('react-aria-landmark-manager-change', fn);
85
- return () => document.removeEventListener('react-aria-landmark-manager-change', fn);
86
- }
87
-
88
- function getLandmarkManager(): LandmarkManagerApi | null {
89
- if (typeof document === 'undefined') {
90
- return null;
91
- }
92
-
93
- // Reuse an existing instance if it has the same or greater version.
94
- let instance = document[landmarkSymbol];
95
- if (instance && instance.version >= LANDMARK_API_VERSION) {
96
- return instance;
97
- }
98
-
99
- // Otherwise, create a new instance and dispatch an event so anything using the existing
100
- // instance updates and re-registers their landmarks with the new one.
101
- document[landmarkSymbol] = new LandmarkManager();
102
- document.dispatchEvent(new CustomEvent('react-aria-landmark-manager-change'));
103
- return document[landmarkSymbol];
104
- }
105
-
106
- // Subscribes a React component to the current landmark manager instance.
107
- function useLandmarkManager(): LandmarkManagerApi | null {
108
- return useSyncExternalStore(subscribe, getLandmarkManager, getLandmarkManager);
109
- }
110
-
111
- class LandmarkManager implements LandmarkManagerApi {
112
- private landmarks: Array<Landmark> = [];
113
- private isListening = false;
114
- private refCount = 0;
115
- public version = LANDMARK_API_VERSION;
116
-
117
- constructor() {
118
- this.f6Handler = this.f6Handler.bind(this);
119
- this.focusinHandler = this.focusinHandler.bind(this);
120
- this.focusoutHandler = this.focusoutHandler.bind(this);
121
- }
122
-
123
- private setupIfNeeded() {
124
- if (this.isListening) {
125
- return;
126
- }
127
- document.addEventListener('keydown', this.f6Handler, {capture: true});
128
- document.addEventListener('focusin', this.focusinHandler, {capture: true});
129
- document.addEventListener('focusout', this.focusoutHandler, {capture: true});
130
- this.isListening = true;
131
- }
132
-
133
- private teardownIfNeeded() {
134
- if (!this.isListening || this.landmarks.length > 0 || this.refCount > 0) {
135
- return;
136
- }
137
- document.removeEventListener('keydown', this.f6Handler, {capture: true});
138
- document.removeEventListener('focusin', this.focusinHandler, {capture: true});
139
- document.removeEventListener('focusout', this.focusoutHandler, {capture: true});
140
- this.isListening = false;
141
- }
142
-
143
- private focusLandmark(landmark: FocusableElement, direction: 'forward' | 'backward') {
144
- this.landmarks.find(l => l.ref.current === landmark)?.focus?.(direction);
145
- }
146
-
147
- /**
148
- * Return set of landmarks with a specific role.
149
- */
150
- private getLandmarksByRole(role: AriaLandmarkRole) {
151
- return new Set(this.landmarks.filter(l => l.role === role));
152
- }
153
-
154
- /**
155
- * Return first landmark with a specific role.
156
- */
157
- private getLandmarkByRole(role: AriaLandmarkRole) {
158
- return this.landmarks.find(l => l.role === role);
159
- }
160
-
161
- private addLandmark(newLandmark: Landmark) {
162
- this.setupIfNeeded();
163
- if (this.landmarks.find(landmark => landmark.ref === newLandmark.ref) || !newLandmark.ref.current) {
164
- return;
165
- }
166
-
167
- if (this.landmarks.filter(landmark => landmark.role === 'main').length > 1 && process.env.NODE_ENV !== 'production') {
168
- console.error('Page can contain no more than one landmark with the role "main".');
169
- }
170
-
171
- if (this.landmarks.length === 0) {
172
- this.landmarks = [newLandmark];
173
- this.checkLabels(newLandmark.role);
174
- return;
175
- }
176
-
177
-
178
- // Binary search to insert new landmark based on position in document relative to existing landmarks.
179
- // https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
180
- let start = 0;
181
- let end = this.landmarks.length - 1;
182
- while (start <= end) {
183
- let mid = Math.floor((start + end) / 2);
184
- let comparedPosition = newLandmark.ref.current.compareDocumentPosition(this.landmarks[mid].ref.current as Node);
185
- let isNewAfterExisting = Boolean((comparedPosition & Node.DOCUMENT_POSITION_PRECEDING) || (comparedPosition & Node.DOCUMENT_POSITION_CONTAINS));
186
-
187
- if (isNewAfterExisting) {
188
- start = mid + 1;
189
- } else {
190
- end = mid - 1;
191
- }
192
- }
193
-
194
- this.landmarks.splice(start, 0, newLandmark);
195
- this.checkLabels(newLandmark.role);
196
- }
197
-
198
- private updateLandmark(landmark: Pick<Landmark, 'ref'> & Partial<Landmark>) {
199
- let index = this.landmarks.findIndex(l => l.ref === landmark.ref);
200
- if (index >= 0) {
201
- this.landmarks[index] = {...this.landmarks[index], ...landmark};
202
- this.checkLabels(this.landmarks[index].role);
203
- }
204
- }
205
-
206
- private removeLandmark(ref: RefObject<Element | null>) {
207
- this.landmarks = this.landmarks.filter(landmark => landmark.ref !== ref);
208
- this.teardownIfNeeded();
209
- }
210
-
211
- /**
212
- * Warn if there are 2+ landmarks with the same role but no label.
213
- * Labels for landmarks with the same role must also be unique.
214
- *
215
- * See https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions/.
216
- */
217
- private checkLabels(role: AriaLandmarkRole) {
218
- let landmarksWithRole = this.getLandmarksByRole(role);
219
- if (landmarksWithRole.size > 1) {
220
- let duplicatesWithoutLabel = [...landmarksWithRole].filter(landmark => !landmark.label);
221
- if (duplicatesWithoutLabel.length > 0 && process.env.NODE_ENV !== 'production') {
222
- console.warn(
223
- `Page contains more than one landmark with the '${role}' role. If two or more landmarks on a page share the same role, all must be labeled with an aria-label or aria-labelledby attribute: `,
224
- duplicatesWithoutLabel.map(landmark => landmark.ref.current)
225
- );
226
- } else if (process.env.NODE_ENV !== 'production') {
227
- let labels = [...landmarksWithRole].map(landmark => landmark.label);
228
- let duplicateLabels = labels.filter((item, index) => labels.indexOf(item) !== index);
229
-
230
- duplicateLabels.forEach((label) => {
231
- console.warn(
232
- `Page contains more than one landmark with the '${role}' role and '${label}' label. If two or more landmarks on a page share the same role, they must have unique labels: `,
233
- [...landmarksWithRole].filter(landmark => landmark.label === label).map(landmark => landmark.ref.current)
234
- );
235
- });
236
- }
237
- }
238
- }
239
-
240
- /**
241
- * Get the landmark that is the closest parent in the DOM.
242
- * Returns undefined if no parent is a landmark.
243
- */
244
- private closestLandmark(element: FocusableElement) {
245
- let landmarkMap = new Map(this.landmarks.map(l => [l.ref.current, l]));
246
- let currentElement = element;
247
- while (currentElement && !landmarkMap.has(currentElement) && currentElement !== document.body && currentElement.parentElement) {
248
- currentElement = currentElement.parentElement;
249
- }
250
- return landmarkMap.get(currentElement);
251
- }
252
-
253
- /**
254
- * Gets the next landmark, in DOM focus order, or previous if backwards is specified.
255
- * If last landmark, next should be the first landmark.
256
- * If not inside a landmark, will return first landmark.
257
- * Returns undefined if there are no landmarks.
258
- */
259
- private getNextLandmark(element: FocusableElement, {backward}: {backward?: boolean }) {
260
- let currentLandmark = this.closestLandmark(element);
261
- let nextLandmarkIndex = backward ? this.landmarks.length - 1 : 0;
262
- if (currentLandmark) {
263
- nextLandmarkIndex = this.landmarks.indexOf(currentLandmark) + (backward ? -1 : 1);
264
- }
265
-
266
- let wrapIfNeeded = () => {
267
- // When we reach the end of the landmark sequence, fire a custom event that can be listened for by applications.
268
- // If this event is canceled, we return immediately. This can be used to implement landmark navigation across iframes.
269
- if (nextLandmarkIndex < 0) {
270
- if (!element.dispatchEvent(new CustomEvent('react-aria-landmark-navigation', {detail: {direction: 'backward'}, bubbles: true, cancelable: true}))) {
271
- return true;
272
- }
273
-
274
- nextLandmarkIndex = this.landmarks.length - 1;
275
- } else if (nextLandmarkIndex >= this.landmarks.length) {
276
- if (!element.dispatchEvent(new CustomEvent('react-aria-landmark-navigation', {detail: {direction: 'forward'}, bubbles: true, cancelable: true}))) {
277
- return true;
278
- }
279
-
280
- nextLandmarkIndex = 0;
281
- }
282
-
283
- if (nextLandmarkIndex < 0 || nextLandmarkIndex >= this.landmarks.length) {
284
- return true;
285
- }
286
-
287
- return false;
288
- };
289
-
290
- if (wrapIfNeeded()) {
291
- return undefined;
292
- }
293
-
294
- // Skip over hidden landmarks.
295
- let i = nextLandmarkIndex;
296
- while (this.landmarks[nextLandmarkIndex].ref.current?.closest('[aria-hidden=true]')) {
297
- nextLandmarkIndex += backward ? -1 : 1;
298
- if (wrapIfNeeded()) {
299
- return undefined;
300
- }
301
-
302
- if (nextLandmarkIndex === i) {
303
- break;
304
- }
305
- }
306
-
307
- return this.landmarks[nextLandmarkIndex];
308
- }
309
-
310
- /**
311
- * Look at next landmark. If an element was previously focused inside, restore focus there.
312
- * If not, focus the landmark itself.
313
- * If no landmarks at all, or none with focusable elements, don't move focus.
314
- */
315
- private f6Handler(e: KeyboardEvent) {
316
- if (e.key === 'F6') {
317
- // If alt key pressed, focus main landmark, otherwise navigate forward or backward based on shift key.
318
- let handled = e.altKey ? this.focusMain() : this.navigate(getEventTarget(e) as FocusableElement, e.shiftKey);
319
- if (handled) {
320
- e.preventDefault();
321
- e.stopPropagation();
322
- }
323
- }
324
- }
325
-
326
- private focusMain() {
327
- let main = this.getLandmarkByRole('main');
328
- if (main && main.ref.current && main.ref.current.isConnected) {
329
- this.focusLandmark(main.ref.current, 'forward');
330
- return true;
331
- }
332
-
333
- return false;
334
- }
335
-
336
- private navigate(from: FocusableElement, backward: boolean) {
337
- let nextLandmark = this.getNextLandmark(from, {
338
- backward
339
- });
340
-
341
- if (!nextLandmark) {
342
- return false;
343
- }
344
-
345
- // If something was previously focused in the next landmark, then return focus to it
346
- if (nextLandmark.lastFocused) {
347
- let lastFocused = nextLandmark.lastFocused;
348
- if (nodeContains(document.body, lastFocused)) {
349
- lastFocused.focus();
350
- return true;
351
- }
352
- }
353
-
354
- // Otherwise, focus the landmark itself
355
- if (nextLandmark.ref.current && nextLandmark.ref.current.isConnected) {
356
- this.focusLandmark(nextLandmark.ref.current, backward ? 'backward' : 'forward');
357
- return true;
358
- }
359
-
360
- return false;
361
- }
362
-
363
- /**
364
- * Sets lastFocused for a landmark, if focus is moved within that landmark.
365
- * Lets the last focused landmark know it was blurred if something else is focused.
366
- */
367
- private focusinHandler(e: FocusEvent) {
368
- let currentLandmark = this.closestLandmark(getEventTarget(e) as FocusableElement);
369
- if (currentLandmark && currentLandmark.ref.current !== getEventTarget(e)) {
370
- this.updateLandmark({ref: currentLandmark.ref, lastFocused: getEventTarget(e) as FocusableElement});
371
- }
372
- let previousFocusedElement = e.relatedTarget as FocusableElement;
373
- if (previousFocusedElement) {
374
- let closestPreviousLandmark = this.closestLandmark(previousFocusedElement);
375
- if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) {
376
- closestPreviousLandmark.blur();
377
- }
378
- }
379
- }
380
-
381
- /**
382
- * Track if the focus is lost to the body. If it is, do cleanup on the landmark that last had focus.
383
- */
384
- private focusoutHandler(e: FocusEvent) {
385
- let previousFocusedElement = getEventTarget(e) as FocusableElement;
386
- let nextFocusedElement = e.relatedTarget;
387
- // the === document seems to be a jest thing for focus to go there on generic blur event such as landmark.blur();
388
- // browsers appear to send focus instead to document.body and the relatedTarget is null when that happens
389
- if (!nextFocusedElement || nextFocusedElement === document) {
390
- let closestPreviousLandmark = this.closestLandmark(previousFocusedElement);
391
- if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) {
392
- closestPreviousLandmark.blur();
393
- }
394
- }
395
- }
396
-
397
- public createLandmarkController(): LandmarkController {
398
- let instance: LandmarkManager | null = this;
399
- instance.refCount++;
400
- instance.setupIfNeeded();
401
- return {
402
- navigate(direction, opts) {
403
- let element = opts?.from || (document!.activeElement as FocusableElement);
404
- return instance!.navigate(element, direction === 'backward');
405
- },
406
- focusNext(opts) {
407
- let element = opts?.from || (document!.activeElement as FocusableElement);
408
- return instance!.navigate(element, false);
409
- },
410
- focusPrevious(opts) {
411
- let element = opts?.from || (document!.activeElement as FocusableElement);
412
- return instance!.navigate(element, true);
413
- },
414
- focusMain() {
415
- return instance!.focusMain();
416
- },
417
- dispose() {
418
- if (instance) {
419
- instance.refCount--;
420
- instance.teardownIfNeeded();
421
- instance = null;
422
- }
423
- }
424
- };
425
- }
426
-
427
- public registerLandmark(landmark: Landmark): () => void {
428
- if (this.landmarks.find(l => l.ref === landmark.ref)) {
429
- this.updateLandmark(landmark);
430
- } else {
431
- this.addLandmark(landmark);
432
- }
433
-
434
- return () => this.removeLandmark(landmark.ref);
435
- }
436
- }
437
-
438
- /** Creates a LandmarkController, which allows programmatic navigation of landmarks. */
439
- export function UNSTABLE_createLandmarkController(): LandmarkController {
440
- // Get the current landmark manager and create a controller using it.
441
- let instance: LandmarkManagerApi | null = getLandmarkManager();
442
- let controller = instance?.createLandmarkController();
443
-
444
- let unsubscribe = subscribe(() => {
445
- // If the landmark manager changes, dispose the old
446
- // controller and create a new one.
447
- controller?.dispose();
448
- instance = getLandmarkManager();
449
- controller = instance?.createLandmarkController();
450
- });
451
-
452
- // Return a wrapper that proxies requests to the current controller instance.
453
- return {
454
- navigate(direction, opts) {
455
- return controller!.navigate(direction, opts);
456
- },
457
- focusNext(opts) {
458
- return controller!.focusNext(opts);
459
- },
460
- focusPrevious(opts) {
461
- return controller!.focusPrevious(opts);
462
- },
463
- focusMain() {
464
- return controller!.focusMain();
465
- },
466
- dispose() {
467
- controller?.dispose();
468
- unsubscribe();
469
- controller = undefined;
470
- instance = null;
471
- }
472
- };
473
- }
474
-
475
- /**
476
- * Provides landmark navigation in an application. Call this with a role and label to register a landmark navigable with F6.
477
- * @param props - Props for the landmark.
478
- * @param ref - Ref to the landmark.
479
- */
480
- export function useLandmark(props: AriaLandmarkProps, ref: RefObject<FocusableElement | null>): LandmarkAria {
481
- const {
482
- role,
483
- 'aria-label': ariaLabel,
484
- 'aria-labelledby': ariaLabelledby,
485
- focus
486
- } = props;
487
- let manager = useLandmarkManager();
488
- let label = ariaLabel || ariaLabelledby;
489
- let [isLandmarkFocused, setIsLandmarkFocused] = useState(false);
490
-
491
- let defaultFocus = useCallback(() => {
492
- setIsLandmarkFocused(true);
493
- }, [setIsLandmarkFocused]);
494
-
495
- let blur = useCallback(() => {
496
- setIsLandmarkFocused(false);
497
- }, [setIsLandmarkFocused]);
498
-
499
- useLayoutEffect(() => {
500
- if (manager) {
501
- return manager.registerLandmark({ref, label, role, focus: focus || defaultFocus, blur});
502
- }
503
- }, [manager, label, ref, role, focus, defaultFocus, blur]);
504
-
505
- useEffect(() => {
506
- if (isLandmarkFocused) {
507
- ref.current?.focus();
508
- }
509
- }, [isLandmarkFocused, ref]);
510
-
511
- return {
512
- landmarkProps: {
513
- role,
514
- tabIndex: isLandmarkFocused ? -1 : undefined,
515
- 'aria-label': ariaLabel,
516
- 'aria-labelledby': ariaLabelledby
517
- }
518
- };
519
- }