@react-aria/landmark 3.0.0-nightly.4552 → 3.0.0-nightly.4558

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.
@@ -0,0 +1,401 @@
1
+ import {useState as $3xCwh$useState, useCallback as $3xCwh$useCallback, useEffect as $3xCwh$useEffect} from "react";
2
+ import {useLayoutEffect as $3xCwh$useLayoutEffect} from "@react-aria/utils";
3
+ import {useSyncExternalStore as $3xCwh$useSyncExternalStore} from "use-sync-external-store/shim/index.js";
4
+
5
+ /*
6
+ * Copyright 2022 Adobe. All rights reserved.
7
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License. You may obtain a copy
9
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software distributed under
12
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
13
+ * OF ANY KIND, either express or implied. See the License for the specific language
14
+ * governing permissions and limitations under the License.
15
+ */
16
+
17
+
18
+ // Increment this version number whenever the
19
+ // LandmarkManagerApi or Landmark interfaces change.
20
+ const $a86207c5d7f7e1fb$var$LANDMARK_API_VERSION = 1;
21
+ // Symbol under which the singleton landmark manager instance is attached to the document.
22
+ const $a86207c5d7f7e1fb$var$landmarkSymbol = Symbol.for("react-aria-landmark-manager");
23
+ function $a86207c5d7f7e1fb$var$subscribe(fn) {
24
+ document.addEventListener("react-aria-landmark-manager-change", fn);
25
+ return ()=>document.removeEventListener("react-aria-landmark-manager-change", fn);
26
+ }
27
+ function $a86207c5d7f7e1fb$var$getLandmarkManager() {
28
+ if (typeof document === "undefined") return null;
29
+ // Reuse an existing instance if it has the same or greater version.
30
+ let instance = document[$a86207c5d7f7e1fb$var$landmarkSymbol];
31
+ if (instance && instance.version >= $a86207c5d7f7e1fb$var$LANDMARK_API_VERSION) return instance;
32
+ // Otherwise, create a new instance and dispatch an event so anything using the existing
33
+ // instance updates and re-registers their landmarks with the new one.
34
+ document[$a86207c5d7f7e1fb$var$landmarkSymbol] = new $a86207c5d7f7e1fb$var$LandmarkManager();
35
+ document.dispatchEvent(new CustomEvent("react-aria-landmark-manager-change"));
36
+ return document[$a86207c5d7f7e1fb$var$landmarkSymbol];
37
+ }
38
+ // Subscribes a React component to the current landmark manager instance.
39
+ function $a86207c5d7f7e1fb$var$useLandmarkManager() {
40
+ return (0, $3xCwh$useSyncExternalStore)($a86207c5d7f7e1fb$var$subscribe, $a86207c5d7f7e1fb$var$getLandmarkManager, $a86207c5d7f7e1fb$var$getLandmarkManager);
41
+ }
42
+ class $a86207c5d7f7e1fb$var$LandmarkManager {
43
+ setupIfNeeded() {
44
+ if (this.isListening) return;
45
+ document.addEventListener("keydown", this.f6Handler, {
46
+ capture: true
47
+ });
48
+ document.addEventListener("focusin", this.focusinHandler, {
49
+ capture: true
50
+ });
51
+ document.addEventListener("focusout", this.focusoutHandler, {
52
+ capture: true
53
+ });
54
+ this.isListening = true;
55
+ }
56
+ teardownIfNeeded() {
57
+ if (!this.isListening || this.landmarks.length > 0 || this.refCount > 0) return;
58
+ document.removeEventListener("keydown", this.f6Handler, {
59
+ capture: true
60
+ });
61
+ document.removeEventListener("focusin", this.focusinHandler, {
62
+ capture: true
63
+ });
64
+ document.removeEventListener("focusout", this.focusoutHandler, {
65
+ capture: true
66
+ });
67
+ this.isListening = false;
68
+ }
69
+ focusLandmark(landmark, direction) {
70
+ var _this_landmarks_find_focus, _this_landmarks_find;
71
+ (_this_landmarks_find = this.landmarks.find((l)=>l.ref.current === landmark)) === null || _this_landmarks_find === void 0 ? void 0 : (_this_landmarks_find_focus = _this_landmarks_find.focus) === null || _this_landmarks_find_focus === void 0 ? void 0 : _this_landmarks_find_focus.call(_this_landmarks_find, direction);
72
+ }
73
+ /**
74
+ * Return set of landmarks with a specific role.
75
+ */ getLandmarksByRole(role) {
76
+ return new Set(this.landmarks.filter((l)=>l.role === role));
77
+ }
78
+ /**
79
+ * Return first landmark with a specific role.
80
+ */ getLandmarkByRole(role) {
81
+ return this.landmarks.find((l)=>l.role === role);
82
+ }
83
+ addLandmark(newLandmark) {
84
+ this.setupIfNeeded();
85
+ if (this.landmarks.find((landmark)=>landmark.ref === newLandmark.ref) || !newLandmark.ref.current) return;
86
+ if (this.landmarks.filter((landmark)=>landmark.role === "main").length > 1) console.error('Page can contain no more than one landmark with the role "main".');
87
+ if (this.landmarks.length === 0) {
88
+ this.landmarks = [
89
+ newLandmark
90
+ ];
91
+ this.checkLabels(newLandmark.role);
92
+ return;
93
+ }
94
+ // Binary search to insert new landmark based on position in document relative to existing landmarks.
95
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
96
+ let start = 0;
97
+ let end = this.landmarks.length - 1;
98
+ while(start <= end){
99
+ let mid = Math.floor((start + end) / 2);
100
+ let comparedPosition = newLandmark.ref.current.compareDocumentPosition(this.landmarks[mid].ref.current);
101
+ let isNewAfterExisting = Boolean(comparedPosition & Node.DOCUMENT_POSITION_PRECEDING || comparedPosition & Node.DOCUMENT_POSITION_CONTAINS);
102
+ if (isNewAfterExisting) start = mid + 1;
103
+ else end = mid - 1;
104
+ }
105
+ this.landmarks.splice(start, 0, newLandmark);
106
+ this.checkLabels(newLandmark.role);
107
+ }
108
+ updateLandmark(landmark) {
109
+ let index = this.landmarks.findIndex((l)=>l.ref === landmark.ref);
110
+ if (index >= 0) {
111
+ this.landmarks[index] = {
112
+ ...this.landmarks[index],
113
+ ...landmark
114
+ };
115
+ this.checkLabels(this.landmarks[index].role);
116
+ }
117
+ }
118
+ removeLandmark(ref) {
119
+ this.landmarks = this.landmarks.filter((landmark)=>landmark.ref !== ref);
120
+ this.teardownIfNeeded();
121
+ }
122
+ /**
123
+ * Warn if there are 2+ landmarks with the same role but no label.
124
+ * Labels for landmarks with the same role must also be unique.
125
+ *
126
+ * See https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions/.
127
+ */ checkLabels(role) {
128
+ let landmarksWithRole = this.getLandmarksByRole(role);
129
+ if (landmarksWithRole.size > 1) {
130
+ let duplicatesWithoutLabel = [
131
+ ...landmarksWithRole
132
+ ].filter((landmark)=>!landmark.label);
133
+ if (duplicatesWithoutLabel.length > 0) console.warn(`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: `, duplicatesWithoutLabel.map((landmark)=>landmark.ref.current));
134
+ else {
135
+ let labels = [
136
+ ...landmarksWithRole
137
+ ].map((landmark)=>landmark.label);
138
+ let duplicateLabels = labels.filter((item, index)=>labels.indexOf(item) !== index);
139
+ duplicateLabels.forEach((label)=>{
140
+ console.warn(`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: `, [
141
+ ...landmarksWithRole
142
+ ].filter((landmark)=>landmark.label === label).map((landmark)=>landmark.ref.current));
143
+ });
144
+ }
145
+ }
146
+ }
147
+ /**
148
+ * Get the landmark that is the closest parent in the DOM.
149
+ * Returns undefined if no parent is a landmark.
150
+ */ closestLandmark(element) {
151
+ let landmarkMap = new Map(this.landmarks.map((l)=>[
152
+ l.ref.current,
153
+ l
154
+ ]));
155
+ let currentElement = element;
156
+ while(currentElement && !landmarkMap.has(currentElement) && currentElement !== document.body && currentElement.parentElement)currentElement = currentElement.parentElement;
157
+ return landmarkMap.get(currentElement);
158
+ }
159
+ /**
160
+ * Gets the next landmark, in DOM focus order, or previous if backwards is specified.
161
+ * If last landmark, next should be the first landmark.
162
+ * If not inside a landmark, will return first landmark.
163
+ * Returns undefined if there are no landmarks.
164
+ */ getNextLandmark(element, { backward: backward }) {
165
+ var _this_landmarks_nextLandmarkIndex_ref_current;
166
+ let currentLandmark = this.closestLandmark(element);
167
+ let nextLandmarkIndex = backward ? this.landmarks.length - 1 : 0;
168
+ if (currentLandmark) nextLandmarkIndex = this.landmarks.indexOf(currentLandmark) + (backward ? -1 : 1);
169
+ let wrapIfNeeded = ()=>{
170
+ // When we reach the end of the landmark sequence, fire a custom event that can be listened for by applications.
171
+ // If this event is canceled, we return immediately. This can be used to implement landmark navigation across iframes.
172
+ if (nextLandmarkIndex < 0) {
173
+ if (!element.dispatchEvent(new CustomEvent("react-aria-landmark-navigation", {
174
+ detail: {
175
+ direction: "backward"
176
+ },
177
+ bubbles: true,
178
+ cancelable: true
179
+ }))) return true;
180
+ nextLandmarkIndex = this.landmarks.length - 1;
181
+ } else if (nextLandmarkIndex >= this.landmarks.length) {
182
+ if (!element.dispatchEvent(new CustomEvent("react-aria-landmark-navigation", {
183
+ detail: {
184
+ direction: "forward"
185
+ },
186
+ bubbles: true,
187
+ cancelable: true
188
+ }))) return true;
189
+ nextLandmarkIndex = 0;
190
+ }
191
+ if (nextLandmarkIndex < 0 || nextLandmarkIndex >= this.landmarks.length) return true;
192
+ return false;
193
+ };
194
+ if (wrapIfNeeded()) return undefined;
195
+ // Skip over hidden landmarks.
196
+ let i = nextLandmarkIndex;
197
+ while((_this_landmarks_nextLandmarkIndex_ref_current = this.landmarks[nextLandmarkIndex].ref.current) === null || _this_landmarks_nextLandmarkIndex_ref_current === void 0 ? void 0 : _this_landmarks_nextLandmarkIndex_ref_current.closest("[aria-hidden=true]")){
198
+ nextLandmarkIndex += backward ? -1 : 1;
199
+ if (wrapIfNeeded()) return undefined;
200
+ if (nextLandmarkIndex === i) break;
201
+ }
202
+ return this.landmarks[nextLandmarkIndex];
203
+ }
204
+ /**
205
+ * Look at next landmark. If an element was previously focused inside, restore focus there.
206
+ * If not, focus the landmark itself.
207
+ * If no landmarks at all, or none with focusable elements, don't move focus.
208
+ */ f6Handler(e) {
209
+ if (e.key === "F6") {
210
+ // If alt key pressed, focus main landmark, otherwise navigate forward or backward based on shift key.
211
+ let handled = e.altKey ? this.focusMain() : this.navigate(e.target, e.shiftKey);
212
+ if (handled) {
213
+ e.preventDefault();
214
+ e.stopPropagation();
215
+ }
216
+ }
217
+ }
218
+ focusMain() {
219
+ let main = this.getLandmarkByRole("main");
220
+ if (main && main.ref.current && document.contains(main.ref.current)) {
221
+ this.focusLandmark(main.ref.current, "forward");
222
+ return true;
223
+ }
224
+ return false;
225
+ }
226
+ navigate(from, backward) {
227
+ let nextLandmark = this.getNextLandmark(from, {
228
+ backward: backward
229
+ });
230
+ if (!nextLandmark) return false;
231
+ // If something was previously focused in the next landmark, then return focus to it
232
+ if (nextLandmark.lastFocused) {
233
+ let lastFocused = nextLandmark.lastFocused;
234
+ if (document.body.contains(lastFocused)) {
235
+ lastFocused.focus();
236
+ return true;
237
+ }
238
+ }
239
+ // Otherwise, focus the landmark itself
240
+ if (nextLandmark.ref.current && document.contains(nextLandmark.ref.current)) {
241
+ this.focusLandmark(nextLandmark.ref.current, backward ? "backward" : "forward");
242
+ return true;
243
+ }
244
+ return false;
245
+ }
246
+ /**
247
+ * Sets lastFocused for a landmark, if focus is moved within that landmark.
248
+ * Lets the last focused landmark know it was blurred if something else is focused.
249
+ */ focusinHandler(e) {
250
+ let currentLandmark = this.closestLandmark(e.target);
251
+ if (currentLandmark && currentLandmark.ref.current !== e.target) this.updateLandmark({
252
+ ref: currentLandmark.ref,
253
+ lastFocused: e.target
254
+ });
255
+ let previousFocusedElement = e.relatedTarget;
256
+ if (previousFocusedElement) {
257
+ let closestPreviousLandmark = this.closestLandmark(previousFocusedElement);
258
+ if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) closestPreviousLandmark.blur();
259
+ }
260
+ }
261
+ /**
262
+ * Track if the focus is lost to the body. If it is, do cleanup on the landmark that last had focus.
263
+ */ focusoutHandler(e) {
264
+ let previousFocusedElement = e.target;
265
+ let nextFocusedElement = e.relatedTarget;
266
+ // the === document seems to be a jest thing for focus to go there on generic blur event such as landmark.blur();
267
+ // browsers appear to send focus instead to document.body and the relatedTarget is null when that happens
268
+ if (!nextFocusedElement || nextFocusedElement === document) {
269
+ let closestPreviousLandmark = this.closestLandmark(previousFocusedElement);
270
+ if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) closestPreviousLandmark.blur();
271
+ }
272
+ }
273
+ createLandmarkController() {
274
+ let instance = this;
275
+ instance.refCount++;
276
+ instance.setupIfNeeded();
277
+ return {
278
+ navigate (direction, opts) {
279
+ let element = (opts === null || opts === void 0 ? void 0 : opts.from) || document.activeElement;
280
+ return instance.navigate(element, direction === "backward");
281
+ },
282
+ focusNext (opts) {
283
+ let element = (opts === null || opts === void 0 ? void 0 : opts.from) || document.activeElement;
284
+ return instance.navigate(element, false);
285
+ },
286
+ focusPrevious (opts) {
287
+ let element = (opts === null || opts === void 0 ? void 0 : opts.from) || document.activeElement;
288
+ return instance.navigate(element, true);
289
+ },
290
+ focusMain () {
291
+ return instance.focusMain();
292
+ },
293
+ dispose () {
294
+ if (instance) {
295
+ instance.refCount--;
296
+ instance.teardownIfNeeded();
297
+ instance = null;
298
+ }
299
+ }
300
+ };
301
+ }
302
+ registerLandmark(landmark) {
303
+ if (this.landmarks.find((l)=>l.ref === landmark.ref)) this.updateLandmark(landmark);
304
+ else this.addLandmark(landmark);
305
+ return ()=>this.removeLandmark(landmark.ref);
306
+ }
307
+ constructor(){
308
+ this.landmarks = [];
309
+ this.isListening = false;
310
+ this.refCount = 0;
311
+ this.version = $a86207c5d7f7e1fb$var$LANDMARK_API_VERSION;
312
+ this.f6Handler = this.f6Handler.bind(this);
313
+ this.focusinHandler = this.focusinHandler.bind(this);
314
+ this.focusoutHandler = this.focusoutHandler.bind(this);
315
+ }
316
+ }
317
+ function $a86207c5d7f7e1fb$export$f50151dbd51cd1d9() {
318
+ // Get the current landmark manager and create a controller using it.
319
+ let instance = $a86207c5d7f7e1fb$var$getLandmarkManager();
320
+ let controller = instance === null || instance === void 0 ? void 0 : instance.createLandmarkController();
321
+ let unsubscribe = $a86207c5d7f7e1fb$var$subscribe(()=>{
322
+ // If the landmark manager changes, dispose the old
323
+ // controller and create a new one.
324
+ controller === null || controller === void 0 ? void 0 : controller.dispose();
325
+ instance = $a86207c5d7f7e1fb$var$getLandmarkManager();
326
+ controller = instance === null || instance === void 0 ? void 0 : instance.createLandmarkController();
327
+ });
328
+ // Return a wrapper that proxies requests to the current controller instance.
329
+ return {
330
+ navigate (direction, opts) {
331
+ return controller.navigate(direction, opts);
332
+ },
333
+ focusNext (opts) {
334
+ return controller.focusNext(opts);
335
+ },
336
+ focusPrevious (opts) {
337
+ return controller.focusPrevious(opts);
338
+ },
339
+ focusMain () {
340
+ return controller.focusMain();
341
+ },
342
+ dispose () {
343
+ controller === null || controller === void 0 ? void 0 : controller.dispose();
344
+ unsubscribe();
345
+ controller = undefined;
346
+ instance = null;
347
+ }
348
+ };
349
+ }
350
+ function $a86207c5d7f7e1fb$export$4cc632584fd87fae(props, ref) {
351
+ const { role: role, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, focus: focus } = props;
352
+ let manager = $a86207c5d7f7e1fb$var$useLandmarkManager();
353
+ let label = ariaLabel || ariaLabelledby;
354
+ let [isLandmarkFocused, setIsLandmarkFocused] = (0, $3xCwh$useState)(false);
355
+ let defaultFocus = (0, $3xCwh$useCallback)(()=>{
356
+ setIsLandmarkFocused(true);
357
+ }, [
358
+ setIsLandmarkFocused
359
+ ]);
360
+ let blur = (0, $3xCwh$useCallback)(()=>{
361
+ setIsLandmarkFocused(false);
362
+ }, [
363
+ setIsLandmarkFocused
364
+ ]);
365
+ (0, $3xCwh$useLayoutEffect)(()=>{
366
+ if (manager) return manager.registerLandmark({
367
+ ref: ref,
368
+ label: label,
369
+ role: role,
370
+ focus: focus || defaultFocus,
371
+ blur: blur
372
+ });
373
+ }, [
374
+ manager,
375
+ label,
376
+ ref,
377
+ role,
378
+ focus,
379
+ defaultFocus,
380
+ blur
381
+ ]);
382
+ (0, $3xCwh$useEffect)(()=>{
383
+ var _ref_current;
384
+ if (isLandmarkFocused) (_ref_current = ref.current) === null || _ref_current === void 0 ? void 0 : _ref_current.focus();
385
+ }, [
386
+ isLandmarkFocused,
387
+ ref
388
+ ]);
389
+ return {
390
+ landmarkProps: {
391
+ role: role,
392
+ tabIndex: isLandmarkFocused ? -1 : undefined,
393
+ "aria-label": ariaLabel,
394
+ "aria-labelledby": ariaLabelledby
395
+ }
396
+ };
397
+ }
398
+
399
+
400
+ export {$a86207c5d7f7e1fb$export$f50151dbd51cd1d9 as createLandmarkController, $a86207c5d7f7e1fb$export$4cc632584fd87fae as useLandmark};
401
+ //# sourceMappingURL=useLandmark.mjs.map