@soomo/react-text-annotator 3.1.0-staging.1 → 3.1.0-staging.3

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,249 +1,1451 @@
1
- import { computePosition, offset as offset$1, shift as shift$1, flip as flip$1, inline as inline$1 } from "./react-text-annotator.es15.js";
2
- import { autoUpdate, platform } from "./react-text-annotator.es15.js";
3
1
  import * as React from "react";
4
- import { useLayoutEffect, useEffect } from "react";
2
+ import { useLayoutEffect, useEffect, useRef } from "react";
3
+ import { isTypeableCombobox, getDocument, activeElement, contains, isVirtualClick, isVirtualPointerEvent, isSafari, stopEvent, getTarget, isReactEvent, isRootElement, isEventTargetWithin } from "./react-text-annotator.es27.js";
4
+ import { isHTMLElement, isElement, getOverflowAncestors, getNodeName, isLastTraversableNode, getParentNode, getComputedStyle } from "./react-text-annotator.es28.js";
5
+ import { isTabbable, tabbable } from "./react-text-annotator.es29.js";
5
6
  import * as ReactDOM from "react-dom";
6
- var index = typeof document !== "undefined" ? useLayoutEffect : useEffect;
7
- function deepEqual(a, b) {
8
- if (a === b) {
9
- return true;
10
- }
11
- if (typeof a !== typeof b) {
12
- return false;
7
+ import { useFloating as useFloating$1 } from "./react-text-annotator.es16.js";
8
+ import { flip, inline, offset, shift } from "./react-text-annotator.es16.js";
9
+ const SafeReact = {
10
+ ...React
11
+ };
12
+ const useInsertionEffect = SafeReact.useInsertionEffect;
13
+ const useSafeInsertionEffect = useInsertionEffect || ((fn) => fn());
14
+ function useEffectEvent(callback) {
15
+ const ref = React.useRef(() => {
16
+ if (process.env.NODE_ENV !== "production") {
17
+ throw new Error("Cannot call an event handler while rendering.");
18
+ }
19
+ });
20
+ useSafeInsertionEffect(() => {
21
+ ref.current = callback;
22
+ });
23
+ return React.useCallback(function() {
24
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
25
+ args[_key] = arguments[_key];
26
+ }
27
+ return ref.current == null ? void 0 : ref.current(...args);
28
+ }, []);
29
+ }
30
+ let rafId = 0;
31
+ function enqueueFocus(el, options) {
32
+ if (options === void 0) {
33
+ options = {};
13
34
  }
14
- if (typeof a === "function" && a.toString() === b.toString()) {
15
- return true;
35
+ const {
36
+ preventScroll = false,
37
+ cancelPrevious = true,
38
+ sync = false
39
+ } = options;
40
+ cancelPrevious && cancelAnimationFrame(rafId);
41
+ const exec = () => el == null ? void 0 : el.focus({
42
+ preventScroll
43
+ });
44
+ if (sync) {
45
+ exec();
46
+ } else {
47
+ rafId = requestAnimationFrame(exec);
16
48
  }
17
- let length;
18
- let i;
19
- let keys;
20
- if (a && b && typeof a === "object") {
21
- if (Array.isArray(a)) {
22
- length = a.length;
23
- if (length !== b.length) return false;
24
- for (i = length; i-- !== 0; ) {
25
- if (!deepEqual(a[i], b[i])) {
26
- return false;
49
+ }
50
+ var index = typeof document !== "undefined" ? useLayoutEffect : useEffect;
51
+ function _extends() {
52
+ _extends = Object.assign ? Object.assign.bind() : function(target) {
53
+ for (var i = 1; i < arguments.length; i++) {
54
+ var source = arguments[i];
55
+ for (var key in source) {
56
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
57
+ target[key] = source[key];
27
58
  }
28
59
  }
29
- return true;
30
60
  }
31
- keys = Object.keys(a);
32
- length = keys.length;
33
- if (length !== Object.keys(b).length) {
34
- return false;
61
+ return target;
62
+ };
63
+ return _extends.apply(this, arguments);
64
+ }
65
+ let serverHandoffComplete = false;
66
+ let count = 0;
67
+ const genId = () => (
68
+ // Ensure the id is unique with multiple independent versions of Floating UI
69
+ // on <React 18
70
+ "floating-ui-" + Math.random().toString(36).slice(2, 6) + count++
71
+ );
72
+ function useFloatingId() {
73
+ const [id, setId] = React.useState(() => serverHandoffComplete ? genId() : void 0);
74
+ index(() => {
75
+ if (id == null) {
76
+ setId(genId());
35
77
  }
36
- for (i = length; i-- !== 0; ) {
37
- if (!{}.hasOwnProperty.call(b, keys[i])) {
38
- return false;
39
- }
78
+ }, []);
79
+ React.useEffect(() => {
80
+ serverHandoffComplete = true;
81
+ }, []);
82
+ return id;
83
+ }
84
+ const useReactId = SafeReact.useId;
85
+ const useId = useReactId || useFloatingId;
86
+ let devMessageSet;
87
+ if (process.env.NODE_ENV !== "production") {
88
+ devMessageSet = /* @__PURE__ */ new Set();
89
+ }
90
+ function error() {
91
+ var _devMessageSet3;
92
+ for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
93
+ messages[_key2] = arguments[_key2];
94
+ }
95
+ const message = "Floating UI: " + messages.join(" ");
96
+ if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {
97
+ var _devMessageSet4;
98
+ (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);
99
+ console.error(message);
100
+ }
101
+ }
102
+ function createPubSub() {
103
+ const map = /* @__PURE__ */ new Map();
104
+ return {
105
+ emit(event, data) {
106
+ var _map$get;
107
+ (_map$get = map.get(event)) == null || _map$get.forEach((handler) => handler(data));
108
+ },
109
+ on(event, listener) {
110
+ map.set(event, [...map.get(event) || [], listener]);
111
+ },
112
+ off(event, listener) {
113
+ var _map$get2;
114
+ map.set(event, ((_map$get2 = map.get(event)) == null ? void 0 : _map$get2.filter((l) => l !== listener)) || []);
115
+ }
116
+ };
117
+ }
118
+ const FloatingNodeContext = /* @__PURE__ */ React.createContext(null);
119
+ const FloatingTreeContext = /* @__PURE__ */ React.createContext(null);
120
+ const useFloatingParentNodeId = () => {
121
+ var _React$useContext;
122
+ return ((_React$useContext = React.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
123
+ };
124
+ const useFloatingTree = () => React.useContext(FloatingTreeContext);
125
+ function createAttribute(name) {
126
+ return "data-floating-ui-" + name;
127
+ }
128
+ function useLatestRef(value) {
129
+ const ref = useRef(value);
130
+ index(() => {
131
+ ref.current = value;
132
+ });
133
+ return ref;
134
+ }
135
+ function getAncestors(nodes, id) {
136
+ var _nodes$find;
137
+ let allAncestors = [];
138
+ let currentParentId = (_nodes$find = nodes.find((node) => node.id === id)) == null ? void 0 : _nodes$find.parentId;
139
+ while (currentParentId) {
140
+ const currentNode = nodes.find((node) => node.id === currentParentId);
141
+ currentParentId = currentNode == null ? void 0 : currentNode.parentId;
142
+ if (currentNode) {
143
+ allAncestors = allAncestors.concat(currentNode);
40
144
  }
41
- for (i = length; i-- !== 0; ) {
42
- const key = keys[i];
43
- if (key === "_owner" && a.$$typeof) {
44
- continue;
145
+ }
146
+ return allAncestors;
147
+ }
148
+ function getChildren(nodes, id) {
149
+ let allChildren = nodes.filter((node) => {
150
+ var _node$context;
151
+ return node.parentId === id && ((_node$context = node.context) == null ? void 0 : _node$context.open);
152
+ });
153
+ let currentChildren = allChildren;
154
+ while (currentChildren.length) {
155
+ currentChildren = nodes.filter((node) => {
156
+ var _currentChildren;
157
+ return (_currentChildren = currentChildren) == null ? void 0 : _currentChildren.some((n) => {
158
+ var _node$context2;
159
+ return node.parentId === n.id && ((_node$context2 = node.context) == null ? void 0 : _node$context2.open);
160
+ });
161
+ });
162
+ allChildren = allChildren.concat(currentChildren);
163
+ }
164
+ return allChildren;
165
+ }
166
+ let counterMap = /* @__PURE__ */ new WeakMap();
167
+ let uncontrolledElementsSet = /* @__PURE__ */ new WeakSet();
168
+ let markerMap = {};
169
+ let lockCount$1 = 0;
170
+ const supportsInert = () => typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype;
171
+ const unwrapHost = (node) => node && (node.host || unwrapHost(node.parentNode));
172
+ const correctElements = (parent, targets) => targets.map((target) => {
173
+ if (parent.contains(target)) {
174
+ return target;
175
+ }
176
+ const correctedTarget = unwrapHost(target);
177
+ if (parent.contains(correctedTarget)) {
178
+ return correctedTarget;
179
+ }
180
+ return null;
181
+ }).filter((x) => x != null);
182
+ function applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {
183
+ const markerName = "data-floating-ui-inert";
184
+ const controlAttribute = inert ? "inert" : ariaHidden ? "aria-hidden" : null;
185
+ const avoidElements = correctElements(body, uncorrectedAvoidElements);
186
+ const elementsToKeep = /* @__PURE__ */ new Set();
187
+ const elementsToStop = new Set(avoidElements);
188
+ const hiddenElements = [];
189
+ if (!markerMap[markerName]) {
190
+ markerMap[markerName] = /* @__PURE__ */ new WeakMap();
191
+ }
192
+ const markerCounter = markerMap[markerName];
193
+ avoidElements.forEach(keep);
194
+ deep(body);
195
+ elementsToKeep.clear();
196
+ function keep(el) {
197
+ if (!el || elementsToKeep.has(el)) {
198
+ return;
199
+ }
200
+ elementsToKeep.add(el);
201
+ el.parentNode && keep(el.parentNode);
202
+ }
203
+ function deep(parent) {
204
+ if (!parent || elementsToStop.has(parent)) {
205
+ return;
206
+ }
207
+ [].forEach.call(parent.children, (node) => {
208
+ if (getNodeName(node) === "script") return;
209
+ if (elementsToKeep.has(node)) {
210
+ deep(node);
211
+ } else {
212
+ const attr2 = controlAttribute ? node.getAttribute(controlAttribute) : null;
213
+ const alreadyHidden = attr2 !== null && attr2 !== "false";
214
+ const counterValue = (counterMap.get(node) || 0) + 1;
215
+ const markerValue = (markerCounter.get(node) || 0) + 1;
216
+ counterMap.set(node, counterValue);
217
+ markerCounter.set(node, markerValue);
218
+ hiddenElements.push(node);
219
+ if (counterValue === 1 && alreadyHidden) {
220
+ uncontrolledElementsSet.add(node);
221
+ }
222
+ if (markerValue === 1) {
223
+ node.setAttribute(markerName, "");
224
+ }
225
+ if (!alreadyHidden && controlAttribute) {
226
+ node.setAttribute(controlAttribute, "true");
227
+ }
228
+ }
229
+ });
230
+ }
231
+ lockCount$1++;
232
+ return () => {
233
+ hiddenElements.forEach((element) => {
234
+ const counterValue = (counterMap.get(element) || 0) - 1;
235
+ const markerValue = (markerCounter.get(element) || 0) - 1;
236
+ counterMap.set(element, counterValue);
237
+ markerCounter.set(element, markerValue);
238
+ if (!counterValue) {
239
+ if (!uncontrolledElementsSet.has(element) && controlAttribute) {
240
+ element.removeAttribute(controlAttribute);
241
+ }
242
+ uncontrolledElementsSet.delete(element);
45
243
  }
46
- if (!deepEqual(a[key], b[key])) {
47
- return false;
244
+ if (!markerValue) {
245
+ element.removeAttribute(markerName);
48
246
  }
247
+ });
248
+ lockCount$1--;
249
+ if (!lockCount$1) {
250
+ counterMap = /* @__PURE__ */ new WeakMap();
251
+ counterMap = /* @__PURE__ */ new WeakMap();
252
+ uncontrolledElementsSet = /* @__PURE__ */ new WeakSet();
253
+ markerMap = {};
49
254
  }
50
- return true;
255
+ };
256
+ }
257
+ function markOthers(avoidElements, ariaHidden, inert) {
258
+ if (ariaHidden === void 0) {
259
+ ariaHidden = false;
260
+ }
261
+ if (inert === void 0) {
262
+ inert = false;
51
263
  }
52
- return a !== a && b !== b;
264
+ const body = getDocument(avoidElements[0]).body;
265
+ return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll("[aria-live]"))), body, ariaHidden, inert);
53
266
  }
54
- function getDPR(element) {
55
- if (typeof window === "undefined") {
56
- return 1;
267
+ const getTabbableOptions = () => ({
268
+ getShadowRoot: true,
269
+ displayCheck: (
270
+ // JSDOM does not support the `tabbable` library. To solve this we can
271
+ // check if `ResizeObserver` is a real function (not polyfilled), which
272
+ // determines if the current environment is JSDOM-like.
273
+ typeof ResizeObserver === "function" && ResizeObserver.toString().includes("[native code]") ? "full" : "none"
274
+ )
275
+ });
276
+ function getTabbableIn(container, direction) {
277
+ const allTabbable = tabbable(container, getTabbableOptions());
278
+ if (direction === "prev") {
279
+ allTabbable.reverse();
57
280
  }
58
- const win = element.ownerDocument.defaultView || window;
59
- return win.devicePixelRatio || 1;
281
+ const activeIndex = allTabbable.indexOf(activeElement(getDocument(container)));
282
+ const nextTabbableElements = allTabbable.slice(activeIndex + 1);
283
+ return nextTabbableElements[0];
60
284
  }
61
- function roundByDPR(element, value) {
62
- const dpr = getDPR(element);
63
- return Math.round(value * dpr) / dpr;
285
+ function getNextTabbable() {
286
+ return getTabbableIn(document.body, "next");
64
287
  }
65
- function useLatestRef(value) {
66
- const ref = React.useRef(value);
288
+ function getPreviousTabbable() {
289
+ return getTabbableIn(document.body, "prev");
290
+ }
291
+ function isOutsideEvent(event, container) {
292
+ const containerElement = container || event.currentTarget;
293
+ const relatedTarget = event.relatedTarget;
294
+ return !relatedTarget || !contains(containerElement, relatedTarget);
295
+ }
296
+ function disableFocusInside(container) {
297
+ const tabbableElements = tabbable(container, getTabbableOptions());
298
+ tabbableElements.forEach((element) => {
299
+ element.dataset.tabindex = element.getAttribute("tabindex") || "";
300
+ element.setAttribute("tabindex", "-1");
301
+ });
302
+ }
303
+ function enableFocusInside(container) {
304
+ const elements = container.querySelectorAll("[data-tabindex]");
305
+ elements.forEach((element) => {
306
+ const tabindex = element.dataset.tabindex;
307
+ delete element.dataset.tabindex;
308
+ if (tabindex) {
309
+ element.setAttribute("tabindex", tabindex);
310
+ } else {
311
+ element.removeAttribute("tabindex");
312
+ }
313
+ });
314
+ }
315
+ const HIDDEN_STYLES = {
316
+ border: 0,
317
+ clip: "rect(0 0 0 0)",
318
+ height: "1px",
319
+ margin: "-1px",
320
+ overflow: "hidden",
321
+ padding: 0,
322
+ position: "fixed",
323
+ whiteSpace: "nowrap",
324
+ width: "1px",
325
+ top: 0,
326
+ left: 0
327
+ };
328
+ let timeoutId;
329
+ function setActiveElementOnTab(event) {
330
+ if (event.key === "Tab") {
331
+ event.target;
332
+ clearTimeout(timeoutId);
333
+ }
334
+ }
335
+ const FocusGuard = /* @__PURE__ */ React.forwardRef(function FocusGuard2(props, ref) {
336
+ const [role, setRole] = React.useState();
67
337
  index(() => {
68
- ref.current = value;
338
+ if (isSafari()) {
339
+ setRole("button");
340
+ }
341
+ document.addEventListener("keydown", setActiveElementOnTab);
342
+ return () => {
343
+ document.removeEventListener("keydown", setActiveElementOnTab);
344
+ };
345
+ }, []);
346
+ const restProps = {
347
+ ref,
348
+ tabIndex: 0,
349
+ // Role is only for VoiceOver
350
+ role,
351
+ "aria-hidden": role ? void 0 : true,
352
+ [createAttribute("focus-guard")]: "",
353
+ style: HIDDEN_STYLES
354
+ };
355
+ return /* @__PURE__ */ React.createElement("span", _extends({}, props, restProps));
356
+ });
357
+ const PortalContext = /* @__PURE__ */ React.createContext(null);
358
+ const attr = /* @__PURE__ */ createAttribute("portal");
359
+ function useFloatingPortalNode(props) {
360
+ if (props === void 0) {
361
+ props = {};
362
+ }
363
+ const {
364
+ id,
365
+ root
366
+ } = props;
367
+ const uniqueId = useId();
368
+ const portalContext = usePortalContext();
369
+ const [portalNode, setPortalNode] = React.useState(null);
370
+ const portalNodeRef = React.useRef(null);
371
+ index(() => {
372
+ return () => {
373
+ portalNode == null || portalNode.remove();
374
+ queueMicrotask(() => {
375
+ portalNodeRef.current = null;
376
+ });
377
+ };
378
+ }, [portalNode]);
379
+ index(() => {
380
+ if (!uniqueId) return;
381
+ if (portalNodeRef.current) return;
382
+ const existingIdRoot = id ? document.getElementById(id) : null;
383
+ if (!existingIdRoot) return;
384
+ const subRoot = document.createElement("div");
385
+ subRoot.id = uniqueId;
386
+ subRoot.setAttribute(attr, "");
387
+ existingIdRoot.appendChild(subRoot);
388
+ portalNodeRef.current = subRoot;
389
+ setPortalNode(subRoot);
390
+ }, [id, uniqueId]);
391
+ index(() => {
392
+ if (!uniqueId) return;
393
+ if (portalNodeRef.current) return;
394
+ let container = root || (portalContext == null ? void 0 : portalContext.portalNode);
395
+ if (container && !isElement(container)) container = container.current;
396
+ container = container || document.body;
397
+ let idWrapper = null;
398
+ if (id) {
399
+ idWrapper = document.createElement("div");
400
+ idWrapper.id = id;
401
+ container.appendChild(idWrapper);
402
+ }
403
+ const subRoot = document.createElement("div");
404
+ subRoot.id = uniqueId;
405
+ subRoot.setAttribute(attr, "");
406
+ container = idWrapper || container;
407
+ container.appendChild(subRoot);
408
+ portalNodeRef.current = subRoot;
409
+ setPortalNode(subRoot);
410
+ }, [id, root, uniqueId, portalContext]);
411
+ return portalNode;
412
+ }
413
+ function FloatingPortal(props) {
414
+ const {
415
+ children,
416
+ id,
417
+ root = null,
418
+ preserveTabOrder = true
419
+ } = props;
420
+ const portalNode = useFloatingPortalNode({
421
+ id,
422
+ root
69
423
  });
70
- return ref;
424
+ const [focusManagerState, setFocusManagerState] = React.useState(null);
425
+ const beforeOutsideRef = React.useRef(null);
426
+ const afterOutsideRef = React.useRef(null);
427
+ const beforeInsideRef = React.useRef(null);
428
+ const afterInsideRef = React.useRef(null);
429
+ const modal = focusManagerState == null ? void 0 : focusManagerState.modal;
430
+ const open = focusManagerState == null ? void 0 : focusManagerState.open;
431
+ const shouldRenderGuards = (
432
+ // The FocusManager and therefore floating element are currently open/
433
+ // rendered.
434
+ !!focusManagerState && // Guards are only for non-modal focus management.
435
+ !focusManagerState.modal && // Don't render if unmount is transitioning.
436
+ focusManagerState.open && preserveTabOrder && !!(root || portalNode)
437
+ );
438
+ React.useEffect(() => {
439
+ if (!portalNode || !preserveTabOrder || modal) {
440
+ return;
441
+ }
442
+ function onFocus(event) {
443
+ if (portalNode && isOutsideEvent(event)) {
444
+ const focusing = event.type === "focusin";
445
+ const manageFocus = focusing ? enableFocusInside : disableFocusInside;
446
+ manageFocus(portalNode);
447
+ }
448
+ }
449
+ portalNode.addEventListener("focusin", onFocus, true);
450
+ portalNode.addEventListener("focusout", onFocus, true);
451
+ return () => {
452
+ portalNode.removeEventListener("focusin", onFocus, true);
453
+ portalNode.removeEventListener("focusout", onFocus, true);
454
+ };
455
+ }, [portalNode, preserveTabOrder, modal]);
456
+ React.useEffect(() => {
457
+ if (!portalNode) return;
458
+ if (open) return;
459
+ enableFocusInside(portalNode);
460
+ }, [open, portalNode]);
461
+ return /* @__PURE__ */ React.createElement(PortalContext.Provider, {
462
+ value: React.useMemo(() => ({
463
+ preserveTabOrder,
464
+ beforeOutsideRef,
465
+ afterOutsideRef,
466
+ beforeInsideRef,
467
+ afterInsideRef,
468
+ portalNode,
469
+ setFocusManagerState
470
+ }), [preserveTabOrder, portalNode])
471
+ }, shouldRenderGuards && portalNode && /* @__PURE__ */ React.createElement(FocusGuard, {
472
+ "data-type": "outside",
473
+ ref: beforeOutsideRef,
474
+ onFocus: (event) => {
475
+ if (isOutsideEvent(event, portalNode)) {
476
+ var _beforeInsideRef$curr;
477
+ (_beforeInsideRef$curr = beforeInsideRef.current) == null || _beforeInsideRef$curr.focus();
478
+ } else {
479
+ const prevTabbable = getPreviousTabbable() || (focusManagerState == null ? void 0 : focusManagerState.refs.domReference.current);
480
+ prevTabbable == null || prevTabbable.focus();
481
+ }
482
+ }
483
+ }), shouldRenderGuards && portalNode && /* @__PURE__ */ React.createElement("span", {
484
+ "aria-owns": portalNode.id,
485
+ style: HIDDEN_STYLES
486
+ }), portalNode && /* @__PURE__ */ ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /* @__PURE__ */ React.createElement(FocusGuard, {
487
+ "data-type": "outside",
488
+ ref: afterOutsideRef,
489
+ onFocus: (event) => {
490
+ if (isOutsideEvent(event, portalNode)) {
491
+ var _afterInsideRef$curre;
492
+ (_afterInsideRef$curre = afterInsideRef.current) == null || _afterInsideRef$curre.focus();
493
+ } else {
494
+ const nextTabbable = getNextTabbable() || (focusManagerState == null ? void 0 : focusManagerState.refs.domReference.current);
495
+ nextTabbable == null || nextTabbable.focus();
496
+ (focusManagerState == null ? void 0 : focusManagerState.closeOnFocusOut) && (focusManagerState == null ? void 0 : focusManagerState.onOpenChange(false, event.nativeEvent, "focus-out"));
497
+ }
498
+ }
499
+ }));
71
500
  }
72
- function useFloating(options) {
73
- if (options === void 0) {
74
- options = {};
501
+ const usePortalContext = () => React.useContext(PortalContext);
502
+ const FOCUSABLE_ATTRIBUTE = "data-floating-ui-focusable";
503
+ function getFloatingFocusElement(floatingElement) {
504
+ if (!floatingElement) {
505
+ return null;
506
+ }
507
+ return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector("[" + FOCUSABLE_ATTRIBUTE + "]") || floatingElement;
508
+ }
509
+ const LIST_LIMIT = 20;
510
+ let previouslyFocusedElements = [];
511
+ function addPreviouslyFocusedElement(element) {
512
+ previouslyFocusedElements = previouslyFocusedElements.filter((el) => el.isConnected);
513
+ let tabbableEl = element;
514
+ if (!tabbableEl || getNodeName(tabbableEl) === "body") return;
515
+ if (!isTabbable(tabbableEl, getTabbableOptions())) {
516
+ const tabbableChild = tabbable(tabbableEl, getTabbableOptions())[0];
517
+ if (tabbableChild) {
518
+ tabbableEl = tabbableChild;
519
+ }
75
520
  }
521
+ previouslyFocusedElements.push(tabbableEl);
522
+ if (previouslyFocusedElements.length > LIST_LIMIT) {
523
+ previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);
524
+ }
525
+ }
526
+ function getPreviouslyFocusedElement() {
527
+ return previouslyFocusedElements.slice().reverse().find((el) => el.isConnected);
528
+ }
529
+ const VisuallyHiddenDismiss = /* @__PURE__ */ React.forwardRef(function VisuallyHiddenDismiss2(props, ref) {
530
+ return /* @__PURE__ */ React.createElement("button", _extends({}, props, {
531
+ type: "button",
532
+ ref,
533
+ tabIndex: -1,
534
+ style: HIDDEN_STYLES
535
+ }));
536
+ });
537
+ function FloatingFocusManager(props) {
76
538
  const {
77
- placement = "bottom",
78
- strategy = "absolute",
79
- middleware = [],
80
- platform: platform2,
539
+ context,
540
+ children,
541
+ disabled = false,
542
+ order = ["content"],
543
+ guards: _guards = true,
544
+ initialFocus = 0,
545
+ returnFocus = true,
546
+ restoreFocus = false,
547
+ modal = true,
548
+ visuallyHiddenDismiss = false,
549
+ closeOnFocusOut = true
550
+ } = props;
551
+ const {
552
+ open,
553
+ refs,
554
+ nodeId,
555
+ onOpenChange,
556
+ events,
557
+ dataRef,
558
+ floatingId,
81
559
  elements: {
82
- reference: externalReference,
83
- floating: externalFloating
84
- } = {},
85
- transform = true,
86
- whileElementsMounted,
87
- open
88
- } = options;
89
- const [data, setData] = React.useState({
90
- x: 0,
91
- y: 0,
92
- strategy,
93
- placement,
94
- middlewareData: {},
95
- isPositioned: false
96
- });
97
- const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);
98
- if (!deepEqual(latestMiddleware, middleware)) {
99
- setLatestMiddleware(middleware);
100
- }
101
- const [_reference, _setReference] = React.useState(null);
102
- const [_floating, _setFloating] = React.useState(null);
103
- const setReference = React.useCallback((node) => {
104
- if (node !== referenceRef.current) {
105
- referenceRef.current = node;
106
- _setReference(node);
560
+ domReference,
561
+ floating
107
562
  }
108
- }, []);
109
- const setFloating = React.useCallback((node) => {
110
- if (node !== floatingRef.current) {
111
- floatingRef.current = node;
112
- _setFloating(node);
563
+ } = context;
564
+ const ignoreInitialFocus = typeof initialFocus === "number" && initialFocus < 0;
565
+ const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;
566
+ const guards = supportsInert() ? _guards : true;
567
+ const orderRef = useLatestRef(order);
568
+ const initialFocusRef = useLatestRef(initialFocus);
569
+ const returnFocusRef = useLatestRef(returnFocus);
570
+ const tree = useFloatingTree();
571
+ const portalContext = usePortalContext();
572
+ const startDismissButtonRef = React.useRef(null);
573
+ const endDismissButtonRef = React.useRef(null);
574
+ const preventReturnFocusRef = React.useRef(false);
575
+ const isPointerDownRef = React.useRef(false);
576
+ const tabbableIndexRef = React.useRef(-1);
577
+ const isInsidePortal = portalContext != null;
578
+ const floatingFocusElement = getFloatingFocusElement(floating);
579
+ const getTabbableContent = useEffectEvent(function(container) {
580
+ if (container === void 0) {
581
+ container = floatingFocusElement;
113
582
  }
114
- }, []);
115
- const referenceEl = externalReference || _reference;
116
- const floatingEl = externalFloating || _floating;
117
- const referenceRef = React.useRef(null);
118
- const floatingRef = React.useRef(null);
119
- const dataRef = React.useRef(data);
120
- const hasWhileElementsMounted = whileElementsMounted != null;
121
- const whileElementsMountedRef = useLatestRef(whileElementsMounted);
122
- const platformRef = useLatestRef(platform2);
123
- const openRef = useLatestRef(open);
124
- const update = React.useCallback(() => {
125
- if (!referenceRef.current || !floatingRef.current) {
126
- return;
583
+ return container ? tabbable(container, getTabbableOptions()) : [];
584
+ });
585
+ const getTabbableElements = useEffectEvent((container) => {
586
+ const content = getTabbableContent(container);
587
+ return orderRef.current.map((type) => {
588
+ if (domReference && type === "reference") {
589
+ return domReference;
590
+ }
591
+ if (floatingFocusElement && type === "floating") {
592
+ return floatingFocusElement;
593
+ }
594
+ return content;
595
+ }).filter(Boolean).flat();
596
+ });
597
+ React.useEffect(() => {
598
+ preventReturnFocusRef.current = false;
599
+ }, [disabled]);
600
+ React.useEffect(() => {
601
+ if (disabled) return;
602
+ if (!modal) return;
603
+ function onKeyDown(event) {
604
+ if (event.key === "Tab") {
605
+ if (contains(floatingFocusElement, activeElement(getDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {
606
+ stopEvent(event);
607
+ }
608
+ const els = getTabbableElements();
609
+ const target = getTarget(event);
610
+ if (orderRef.current[0] === "reference" && target === domReference) {
611
+ stopEvent(event);
612
+ if (event.shiftKey) {
613
+ enqueueFocus(els[els.length - 1]);
614
+ } else {
615
+ enqueueFocus(els[1]);
616
+ }
617
+ }
618
+ if (orderRef.current[1] === "floating" && target === floatingFocusElement && event.shiftKey) {
619
+ stopEvent(event);
620
+ enqueueFocus(els[0]);
621
+ }
622
+ }
623
+ }
624
+ const doc = getDocument(floatingFocusElement);
625
+ doc.addEventListener("keydown", onKeyDown);
626
+ return () => {
627
+ doc.removeEventListener("keydown", onKeyDown);
628
+ };
629
+ }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent, getTabbableElements]);
630
+ React.useEffect(() => {
631
+ if (disabled) return;
632
+ if (!floating) return;
633
+ function handleFocusIn(event) {
634
+ const target = getTarget(event);
635
+ const tabbableContent = getTabbableContent();
636
+ const tabbableIndex = tabbableContent.indexOf(target);
637
+ if (tabbableIndex !== -1) {
638
+ tabbableIndexRef.current = tabbableIndex;
639
+ }
640
+ }
641
+ floating.addEventListener("focusin", handleFocusIn);
642
+ return () => {
643
+ floating.removeEventListener("focusin", handleFocusIn);
644
+ };
645
+ }, [disabled, floating, getTabbableContent]);
646
+ React.useEffect(() => {
647
+ if (disabled) return;
648
+ if (!closeOnFocusOut) return;
649
+ function handlePointerDown() {
650
+ isPointerDownRef.current = true;
651
+ setTimeout(() => {
652
+ isPointerDownRef.current = false;
653
+ });
654
+ }
655
+ function handleFocusOutside(event) {
656
+ const relatedTarget = event.relatedTarget;
657
+ queueMicrotask(() => {
658
+ const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute("focus-guard")) || tree && (getChildren(tree.nodesRef.current, nodeId).find((node) => {
659
+ var _node$context, _node$context2;
660
+ return contains((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);
661
+ }) || getAncestors(tree.nodesRef.current, nodeId).find((node) => {
662
+ var _node$context3, _node$context4;
663
+ return ((_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating) === relatedTarget || ((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.domReference) === relatedTarget;
664
+ })));
665
+ if (restoreFocus && movedToUnrelatedNode && activeElement(getDocument(floatingFocusElement)) === getDocument(floatingFocusElement).body) {
666
+ if (isHTMLElement(floatingFocusElement)) {
667
+ floatingFocusElement.focus();
668
+ }
669
+ const prevTabbableIndex = tabbableIndexRef.current;
670
+ const tabbableContent = getTabbableContent();
671
+ const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;
672
+ if (isHTMLElement(nodeToFocus)) {
673
+ nodeToFocus.focus();
674
+ }
675
+ }
676
+ if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current && // Fix React 18 Strict Mode returnFocus due to double rendering.
677
+ relatedTarget !== getPreviouslyFocusedElement()) {
678
+ preventReturnFocusRef.current = true;
679
+ onOpenChange(false, event, "focus-out");
680
+ }
681
+ });
682
+ }
683
+ if (floating && isHTMLElement(domReference)) {
684
+ domReference.addEventListener("focusout", handleFocusOutside);
685
+ domReference.addEventListener("pointerdown", handlePointerDown);
686
+ floating.addEventListener("focusout", handleFocusOutside);
687
+ return () => {
688
+ domReference.removeEventListener("focusout", handleFocusOutside);
689
+ domReference.removeEventListener("pointerdown", handlePointerDown);
690
+ floating.removeEventListener("focusout", handleFocusOutside);
691
+ };
127
692
  }
128
- const config = {
129
- placement,
130
- strategy,
131
- middleware: latestMiddleware
132
- };
133
- if (platformRef.current) {
134
- config.platform = platformRef.current;
135
- }
136
- computePosition(referenceRef.current, floatingRef.current, config).then((data2) => {
137
- const fullData = {
138
- ...data2,
139
- // The floating element's position may be recomputed while it's closed
140
- // but still mounted (such as when transitioning out). To ensure
141
- // `isPositioned` will be `false` initially on the next open, avoid
142
- // setting it to `true` when `open === false` (must be specified).
143
- isPositioned: openRef.current !== false
693
+ }, [disabled, domReference, floating, floatingFocusElement, modal, nodeId, tree, portalContext, onOpenChange, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox]);
694
+ React.useEffect(() => {
695
+ var _portalContext$portal;
696
+ if (disabled) return;
697
+ const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll("[" + createAttribute("portal") + "]")) || []);
698
+ if (floating) {
699
+ const insideElements = [floating, ...portalNodes, startDismissButtonRef.current, endDismissButtonRef.current, orderRef.current.includes("reference") || isUntrappedTypeableCombobox ? domReference : null].filter((x) => x != null);
700
+ const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, guards, !guards) : markOthers(insideElements);
701
+ return () => {
702
+ cleanup();
144
703
  };
145
- if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
146
- dataRef.current = fullData;
147
- ReactDOM.flushSync(() => {
148
- setData(fullData);
704
+ }
705
+ }, [disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, guards]);
706
+ index(() => {
707
+ if (disabled || !isHTMLElement(floatingFocusElement)) return;
708
+ const doc = getDocument(floatingFocusElement);
709
+ const previouslyFocusedElement = activeElement(doc);
710
+ queueMicrotask(() => {
711
+ const focusableElements = getTabbableElements(floatingFocusElement);
712
+ const initialFocusValue = initialFocusRef.current;
713
+ const elToFocus = (typeof initialFocusValue === "number" ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;
714
+ const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);
715
+ if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) {
716
+ enqueueFocus(elToFocus, {
717
+ preventScroll: elToFocus === floatingFocusElement
149
718
  });
150
719
  }
151
720
  });
152
- }, [latestMiddleware, placement, strategy, platformRef, openRef]);
721
+ }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableElements, initialFocusRef]);
153
722
  index(() => {
154
- if (open === false && dataRef.current.isPositioned) {
155
- dataRef.current.isPositioned = false;
156
- setData((data2) => ({
157
- ...data2,
158
- isPositioned: false
159
- }));
160
- }
161
- }, [open]);
162
- const isMountedRef = React.useRef(false);
723
+ if (disabled || !floatingFocusElement) return;
724
+ let preventReturnFocusScroll = false;
725
+ const doc = getDocument(floatingFocusElement);
726
+ const previouslyFocusedElement = activeElement(doc);
727
+ const contextData = dataRef.current;
728
+ let openEvent = contextData.openEvent;
729
+ addPreviouslyFocusedElement(previouslyFocusedElement);
730
+ function onOpenChange2(_ref) {
731
+ let {
732
+ open: open2,
733
+ reason,
734
+ event,
735
+ nested
736
+ } = _ref;
737
+ if (open2) {
738
+ openEvent = event;
739
+ }
740
+ if (reason === "escape-key" && refs.domReference.current) {
741
+ addPreviouslyFocusedElement(refs.domReference.current);
742
+ }
743
+ if (reason === "hover" && event.type === "mouseleave") {
744
+ preventReturnFocusRef.current = true;
745
+ }
746
+ if (reason !== "outside-press") return;
747
+ if (nested) {
748
+ preventReturnFocusRef.current = false;
749
+ preventReturnFocusScroll = true;
750
+ } else {
751
+ preventReturnFocusRef.current = !(isVirtualClick(event) || isVirtualPointerEvent(event));
752
+ }
753
+ }
754
+ events.on("openchange", onOpenChange2);
755
+ const fallbackEl = doc.createElement("span");
756
+ fallbackEl.setAttribute("tabindex", "-1");
757
+ fallbackEl.setAttribute("aria-hidden", "true");
758
+ Object.assign(fallbackEl.style, HIDDEN_STYLES);
759
+ if (isInsidePortal && domReference) {
760
+ domReference.insertAdjacentElement("afterend", fallbackEl);
761
+ }
762
+ return () => {
763
+ events.off("openchange", onOpenChange2);
764
+ const activeEl = activeElement(doc);
765
+ const isFocusInsideFloatingTree = contains(floating, activeEl) || tree && getChildren(tree.nodesRef.current, nodeId).some((node) => {
766
+ var _node$context5;
767
+ return contains((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.floating, activeEl);
768
+ });
769
+ const shouldFocusReference = isFocusInsideFloatingTree || openEvent && ["click", "mousedown"].includes(openEvent.type);
770
+ if (shouldFocusReference && refs.domReference.current) {
771
+ addPreviouslyFocusedElement(refs.domReference.current);
772
+ }
773
+ const returnElement = getPreviouslyFocusedElement() || fallbackEl;
774
+ queueMicrotask(() => {
775
+ if (
776
+ // eslint-disable-next-line react-hooks/exhaustive-deps
777
+ returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(returnElement) && // If the focus moved somewhere else after mount, avoid returning focus
778
+ // since it likely entered a different element which should be
779
+ // respected: https://github.com/floating-ui/floating-ui/issues/2607
780
+ (returnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)
781
+ ) {
782
+ returnElement.focus({
783
+ preventScroll: preventReturnFocusScroll
784
+ });
785
+ }
786
+ fallbackEl.remove();
787
+ });
788
+ };
789
+ }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, refs, events, tree, nodeId, isInsidePortal, domReference]);
163
790
  index(() => {
164
- isMountedRef.current = true;
791
+ if (disabled) return;
792
+ if (!portalContext) return;
793
+ portalContext.setFocusManagerState({
794
+ modal,
795
+ closeOnFocusOut,
796
+ open,
797
+ onOpenChange,
798
+ refs
799
+ });
165
800
  return () => {
166
- isMountedRef.current = false;
801
+ portalContext.setFocusManagerState(null);
167
802
  };
168
- }, []);
803
+ }, [disabled, portalContext, modal, open, onOpenChange, refs, closeOnFocusOut]);
804
+ index(() => {
805
+ if (disabled) return;
806
+ if (!floatingFocusElement) return;
807
+ if (typeof MutationObserver !== "function") return;
808
+ if (ignoreInitialFocus) return;
809
+ const handleMutation = () => {
810
+ const tabIndex = floatingFocusElement.getAttribute("tabindex");
811
+ const tabbableContent = getTabbableContent();
812
+ const activeEl = activeElement(getDocument(floating));
813
+ const tabbableIndex = tabbableContent.indexOf(activeEl);
814
+ if (tabbableIndex !== -1) {
815
+ tabbableIndexRef.current = tabbableIndex;
816
+ }
817
+ if (orderRef.current.includes("floating") || activeEl !== refs.domReference.current && tabbableContent.length === 0) {
818
+ if (tabIndex !== "0") {
819
+ floatingFocusElement.setAttribute("tabindex", "0");
820
+ }
821
+ } else if (tabIndex !== "-1") {
822
+ floatingFocusElement.setAttribute("tabindex", "-1");
823
+ }
824
+ };
825
+ handleMutation();
826
+ const observer = new MutationObserver(handleMutation);
827
+ observer.observe(floatingFocusElement, {
828
+ childList: true,
829
+ subtree: true,
830
+ attributes: true
831
+ });
832
+ return () => {
833
+ observer.disconnect();
834
+ };
835
+ }, [disabled, floating, floatingFocusElement, refs, orderRef, getTabbableContent, ignoreInitialFocus]);
836
+ function renderDismissButton(location) {
837
+ if (disabled || !visuallyHiddenDismiss || !modal) {
838
+ return null;
839
+ }
840
+ return /* @__PURE__ */ React.createElement(VisuallyHiddenDismiss, {
841
+ ref: location === "start" ? startDismissButtonRef : endDismissButtonRef,
842
+ onClick: (event) => onOpenChange(false, event.nativeEvent)
843
+ }, typeof visuallyHiddenDismiss === "string" ? visuallyHiddenDismiss : "Dismiss");
844
+ }
845
+ const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);
846
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldRenderGuards && /* @__PURE__ */ React.createElement(FocusGuard, {
847
+ "data-type": "inside",
848
+ ref: portalContext == null ? void 0 : portalContext.beforeInsideRef,
849
+ onFocus: (event) => {
850
+ if (modal) {
851
+ const els = getTabbableElements();
852
+ enqueueFocus(order[0] === "reference" ? els[0] : els[els.length - 1]);
853
+ } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
854
+ preventReturnFocusRef.current = false;
855
+ if (isOutsideEvent(event, portalContext.portalNode)) {
856
+ const nextTabbable = getNextTabbable() || domReference;
857
+ nextTabbable == null || nextTabbable.focus();
858
+ } else {
859
+ var _portalContext$before;
860
+ (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();
861
+ }
862
+ }
863
+ }
864
+ }), !isUntrappedTypeableCombobox && renderDismissButton("start"), children, renderDismissButton("end"), shouldRenderGuards && /* @__PURE__ */ React.createElement(FocusGuard, {
865
+ "data-type": "inside",
866
+ ref: portalContext == null ? void 0 : portalContext.afterInsideRef,
867
+ onFocus: (event) => {
868
+ if (modal) {
869
+ enqueueFocus(getTabbableElements()[0]);
870
+ } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
871
+ if (closeOnFocusOut) {
872
+ preventReturnFocusRef.current = true;
873
+ }
874
+ if (isOutsideEvent(event, portalContext.portalNode)) {
875
+ const prevTabbable = getPreviousTabbable() || domReference;
876
+ prevTabbable == null || prevTabbable.focus();
877
+ } else {
878
+ var _portalContext$afterO;
879
+ (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();
880
+ }
881
+ }
882
+ }
883
+ }));
884
+ }
885
+ const bubbleHandlerKeys = {
886
+ pointerdown: "onPointerDown",
887
+ mousedown: "onMouseDown",
888
+ click: "onClick"
889
+ };
890
+ const captureHandlerKeys = {
891
+ pointerdown: "onPointerDownCapture",
892
+ mousedown: "onMouseDownCapture",
893
+ click: "onClickCapture"
894
+ };
895
+ const normalizeProp = (normalizable) => {
896
+ var _normalizable$escapeK, _normalizable$outside;
897
+ return {
898
+ escapeKey: typeof normalizable === "boolean" ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
899
+ outsidePress: typeof normalizable === "boolean" ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
900
+ };
901
+ };
902
+ function useDismiss(context, props) {
903
+ if (props === void 0) {
904
+ props = {};
905
+ }
906
+ const {
907
+ open,
908
+ onOpenChange,
909
+ elements,
910
+ dataRef
911
+ } = context;
912
+ const {
913
+ enabled = true,
914
+ escapeKey = true,
915
+ outsidePress: unstable_outsidePress = true,
916
+ outsidePressEvent = "pointerdown",
917
+ referencePress = false,
918
+ referencePressEvent = "pointerdown",
919
+ ancestorScroll = false,
920
+ bubbles,
921
+ capture
922
+ } = props;
923
+ const tree = useFloatingTree();
924
+ const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === "function" ? unstable_outsidePress : () => false);
925
+ const outsidePress = typeof unstable_outsidePress === "function" ? outsidePressFn : unstable_outsidePress;
926
+ const insideReactTreeRef = React.useRef(false);
927
+ const endedOrStartedInsideRef = React.useRef(false);
928
+ const {
929
+ escapeKey: escapeKeyBubbles,
930
+ outsidePress: outsidePressBubbles
931
+ } = normalizeProp(bubbles);
932
+ const {
933
+ escapeKey: escapeKeyCapture,
934
+ outsidePress: outsidePressCapture
935
+ } = normalizeProp(capture);
936
+ const closeOnEscapeKeyDown = useEffectEvent((event) => {
937
+ var _dataRef$current$floa;
938
+ if (!open || !enabled || !escapeKey || event.key !== "Escape") {
939
+ return;
940
+ }
941
+ const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
942
+ const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
943
+ if (!escapeKeyBubbles) {
944
+ event.stopPropagation();
945
+ if (children.length > 0) {
946
+ let shouldDismiss = true;
947
+ children.forEach((child) => {
948
+ var _child$context;
949
+ if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
950
+ shouldDismiss = false;
951
+ return;
952
+ }
953
+ });
954
+ if (!shouldDismiss) {
955
+ return;
956
+ }
957
+ }
958
+ }
959
+ onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, "escape-key");
960
+ });
961
+ const closeOnEscapeKeyDownCapture = useEffectEvent((event) => {
962
+ var _getTarget2;
963
+ const callback = () => {
964
+ var _getTarget;
965
+ closeOnEscapeKeyDown(event);
966
+ (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener("keydown", callback);
967
+ };
968
+ (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener("keydown", callback);
969
+ });
970
+ const closeOnPressOutside = useEffectEvent((event) => {
971
+ var _dataRef$current$floa2;
972
+ const insideReactTree = insideReactTreeRef.current;
973
+ insideReactTreeRef.current = false;
974
+ const endedOrStartedInside = endedOrStartedInsideRef.current;
975
+ endedOrStartedInsideRef.current = false;
976
+ if (outsidePressEvent === "click" && endedOrStartedInside) {
977
+ return;
978
+ }
979
+ if (insideReactTree) {
980
+ return;
981
+ }
982
+ if (typeof outsidePress === "function" && !outsidePress(event)) {
983
+ return;
984
+ }
985
+ const target = getTarget(event);
986
+ const inertSelector = "[" + createAttribute("inert") + "]";
987
+ const markers = getDocument(elements.floating).querySelectorAll(inertSelector);
988
+ let targetRootAncestor = isElement(target) ? target : null;
989
+ while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
990
+ const nextParent = getParentNode(targetRootAncestor);
991
+ if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
992
+ break;
993
+ }
994
+ targetRootAncestor = nextParent;
995
+ }
996
+ if (markers.length && isElement(target) && !isRootElement(target) && // Clicked on a direct ancestor (e.g. FloatingOverlay).
997
+ !contains(target, elements.floating) && // If the target root element contains none of the markers, then the
998
+ // element was injected after the floating element rendered.
999
+ Array.from(markers).every((marker) => !contains(targetRootAncestor, marker))) {
1000
+ return;
1001
+ }
1002
+ if (isHTMLElement(target) && floating) {
1003
+ const canScrollX = target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
1004
+ const canScrollY = target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
1005
+ let xCond = canScrollY && event.offsetX > target.clientWidth;
1006
+ if (canScrollY) {
1007
+ const isRTL = getComputedStyle(target).direction === "rtl";
1008
+ if (isRTL) {
1009
+ xCond = event.offsetX <= target.offsetWidth - target.clientWidth;
1010
+ }
1011
+ }
1012
+ if (xCond || canScrollX && event.offsetY > target.clientHeight) {
1013
+ return;
1014
+ }
1015
+ }
1016
+ const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;
1017
+ const targetIsInsideChildren = tree && getChildren(tree.nodesRef.current, nodeId).some((node) => {
1018
+ var _node$context;
1019
+ return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);
1020
+ });
1021
+ if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {
1022
+ return;
1023
+ }
1024
+ const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
1025
+ if (children.length > 0) {
1026
+ let shouldDismiss = true;
1027
+ children.forEach((child) => {
1028
+ var _child$context2;
1029
+ if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
1030
+ shouldDismiss = false;
1031
+ return;
1032
+ }
1033
+ });
1034
+ if (!shouldDismiss) {
1035
+ return;
1036
+ }
1037
+ }
1038
+ onOpenChange(false, event, "outside-press");
1039
+ });
1040
+ const closeOnPressOutsideCapture = useEffectEvent((event) => {
1041
+ var _getTarget4;
1042
+ const callback = () => {
1043
+ var _getTarget3;
1044
+ closeOnPressOutside(event);
1045
+ (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
1046
+ };
1047
+ (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
1048
+ });
1049
+ React.useEffect(() => {
1050
+ if (!open || !enabled) {
1051
+ return;
1052
+ }
1053
+ dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
1054
+ dataRef.current.__outsidePressBubbles = outsidePressBubbles;
1055
+ function onScroll(event) {
1056
+ onOpenChange(false, event, "ancestor-scroll");
1057
+ }
1058
+ const doc = getDocument(elements.floating);
1059
+ escapeKey && doc.addEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
1060
+ outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
1061
+ let ancestors = [];
1062
+ if (ancestorScroll) {
1063
+ if (isElement(elements.domReference)) {
1064
+ ancestors = getOverflowAncestors(elements.domReference);
1065
+ }
1066
+ if (isElement(elements.floating)) {
1067
+ ancestors = ancestors.concat(getOverflowAncestors(elements.floating));
1068
+ }
1069
+ if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) {
1070
+ ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));
1071
+ }
1072
+ }
1073
+ ancestors = ancestors.filter((ancestor) => {
1074
+ var _doc$defaultView;
1075
+ return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
1076
+ });
1077
+ ancestors.forEach((ancestor) => {
1078
+ ancestor.addEventListener("scroll", onScroll, {
1079
+ passive: true
1080
+ });
1081
+ });
1082
+ return () => {
1083
+ escapeKey && doc.removeEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
1084
+ outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
1085
+ ancestors.forEach((ancestor) => {
1086
+ ancestor.removeEventListener("scroll", onScroll);
1087
+ });
1088
+ };
1089
+ }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);
1090
+ React.useEffect(() => {
1091
+ insideReactTreeRef.current = false;
1092
+ }, [outsidePress, outsidePressEvent]);
1093
+ const reference = React.useMemo(() => ({
1094
+ onKeyDown: closeOnEscapeKeyDown,
1095
+ [bubbleHandlerKeys[referencePressEvent]]: (event) => {
1096
+ if (referencePress) {
1097
+ onOpenChange(false, event.nativeEvent, "reference-press");
1098
+ }
1099
+ }
1100
+ }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);
1101
+ const floating = React.useMemo(() => ({
1102
+ onKeyDown: closeOnEscapeKeyDown,
1103
+ onMouseDown() {
1104
+ endedOrStartedInsideRef.current = true;
1105
+ },
1106
+ onMouseUp() {
1107
+ endedOrStartedInsideRef.current = true;
1108
+ },
1109
+ [captureHandlerKeys[outsidePressEvent]]: () => {
1110
+ insideReactTreeRef.current = true;
1111
+ }
1112
+ }), [closeOnEscapeKeyDown, outsidePressEvent]);
1113
+ return React.useMemo(() => enabled ? {
1114
+ reference,
1115
+ floating
1116
+ } : {}, [enabled, reference, floating]);
1117
+ }
1118
+ function useFloatingRootContext(options) {
1119
+ const {
1120
+ open = false,
1121
+ onOpenChange: onOpenChangeProp,
1122
+ elements: elementsProp
1123
+ } = options;
1124
+ const floatingId = useId();
1125
+ const dataRef = React.useRef({});
1126
+ const [events] = React.useState(() => createPubSub());
1127
+ const nested = useFloatingParentNodeId() != null;
1128
+ if (process.env.NODE_ENV !== "production") {
1129
+ const optionDomReference = elementsProp.reference;
1130
+ if (optionDomReference && !isElement(optionDomReference)) {
1131
+ error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `refs.setPositionReference()`", "instead.");
1132
+ }
1133
+ }
1134
+ const [positionReference, setPositionReference] = React.useState(elementsProp.reference);
1135
+ const onOpenChange = useEffectEvent((open2, event, reason) => {
1136
+ dataRef.current.openEvent = open2 ? event : void 0;
1137
+ events.emit("openchange", {
1138
+ open: open2,
1139
+ event,
1140
+ reason,
1141
+ nested
1142
+ });
1143
+ onOpenChangeProp == null || onOpenChangeProp(open2, event, reason);
1144
+ });
1145
+ const refs = React.useMemo(() => ({
1146
+ setPositionReference
1147
+ }), []);
1148
+ const elements = React.useMemo(() => ({
1149
+ reference: positionReference || elementsProp.reference || null,
1150
+ floating: elementsProp.floating || null,
1151
+ domReference: elementsProp.reference
1152
+ }), [positionReference, elementsProp.reference, elementsProp.floating]);
1153
+ return React.useMemo(() => ({
1154
+ dataRef,
1155
+ open,
1156
+ onOpenChange,
1157
+ elements,
1158
+ events,
1159
+ floatingId,
1160
+ refs
1161
+ }), [open, onOpenChange, elements, events, floatingId, refs]);
1162
+ }
1163
+ function useFloating(options) {
1164
+ if (options === void 0) {
1165
+ options = {};
1166
+ }
1167
+ const {
1168
+ nodeId
1169
+ } = options;
1170
+ const internalRootContext = useFloatingRootContext({
1171
+ ...options,
1172
+ elements: {
1173
+ reference: null,
1174
+ floating: null,
1175
+ ...options.elements
1176
+ }
1177
+ });
1178
+ const rootContext = options.rootContext || internalRootContext;
1179
+ const computedElements = rootContext.elements;
1180
+ const [_domReference, setDomReference] = React.useState(null);
1181
+ const [positionReference, _setPositionReference] = React.useState(null);
1182
+ const optionDomReference = computedElements == null ? void 0 : computedElements.reference;
1183
+ const domReference = optionDomReference || _domReference;
1184
+ const domReferenceRef = React.useRef(null);
1185
+ const tree = useFloatingTree();
169
1186
  index(() => {
170
- if (referenceEl) referenceRef.current = referenceEl;
171
- if (floatingEl) floatingRef.current = floatingEl;
172
- if (referenceEl && floatingEl) {
173
- if (whileElementsMountedRef.current) {
174
- return whileElementsMountedRef.current(referenceEl, floatingEl, update);
1187
+ if (domReference) {
1188
+ domReferenceRef.current = domReference;
1189
+ }
1190
+ }, [domReference]);
1191
+ const position = useFloating$1({
1192
+ ...options,
1193
+ elements: {
1194
+ ...computedElements,
1195
+ ...positionReference && {
1196
+ reference: positionReference
175
1197
  }
176
- update();
177
1198
  }
178
- }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
1199
+ });
1200
+ const setPositionReference = React.useCallback((node) => {
1201
+ const computedPositionReference = isElement(node) ? {
1202
+ getBoundingClientRect: () => node.getBoundingClientRect(),
1203
+ contextElement: node
1204
+ } : node;
1205
+ _setPositionReference(computedPositionReference);
1206
+ position.refs.setReference(computedPositionReference);
1207
+ }, [position.refs]);
1208
+ const setReference = React.useCallback((node) => {
1209
+ if (isElement(node) || node === null) {
1210
+ domReferenceRef.current = node;
1211
+ setDomReference(node);
1212
+ }
1213
+ if (isElement(position.refs.reference.current) || position.refs.reference.current === null || // Don't allow setting virtual elements using the old technique back to
1214
+ // `null` to support `positionReference` + an unstable `reference`
1215
+ // callback ref.
1216
+ node !== null && !isElement(node)) {
1217
+ position.refs.setReference(node);
1218
+ }
1219
+ }, [position.refs]);
179
1220
  const refs = React.useMemo(() => ({
180
- reference: referenceRef,
181
- floating: floatingRef,
1221
+ ...position.refs,
182
1222
  setReference,
183
- setFloating
184
- }), [setReference, setFloating]);
1223
+ setPositionReference,
1224
+ domReference: domReferenceRef
1225
+ }), [position.refs, setReference, setPositionReference]);
185
1226
  const elements = React.useMemo(() => ({
186
- reference: referenceEl,
187
- floating: floatingEl
188
- }), [referenceEl, floatingEl]);
189
- const floatingStyles = React.useMemo(() => {
190
- const initialStyles = {
191
- position: strategy,
192
- left: 0,
193
- top: 0
194
- };
195
- if (!elements.floating) {
196
- return initialStyles;
197
- }
198
- const x = roundByDPR(elements.floating, data.x);
199
- const y = roundByDPR(elements.floating, data.y);
200
- if (transform) {
201
- return {
202
- ...initialStyles,
203
- transform: "translate(" + x + "px, " + y + "px)",
204
- ...getDPR(elements.floating) >= 1.5 && {
205
- willChange: "transform"
1227
+ ...position.elements,
1228
+ domReference
1229
+ }), [position.elements, domReference]);
1230
+ const context = React.useMemo(() => ({
1231
+ ...position,
1232
+ ...rootContext,
1233
+ refs,
1234
+ elements,
1235
+ nodeId
1236
+ }), [position, refs, elements, nodeId, rootContext]);
1237
+ index(() => {
1238
+ rootContext.dataRef.current.floatingContext = context;
1239
+ const node = tree == null ? void 0 : tree.nodesRef.current.find((node2) => node2.id === nodeId);
1240
+ if (node) {
1241
+ node.context = context;
1242
+ }
1243
+ });
1244
+ return React.useMemo(() => ({
1245
+ ...position,
1246
+ context,
1247
+ refs,
1248
+ elements
1249
+ }), [position, refs, elements, context]);
1250
+ }
1251
+ const ACTIVE_KEY = "active";
1252
+ const SELECTED_KEY = "selected";
1253
+ function mergeProps(userProps, propsList, elementKey) {
1254
+ const map = /* @__PURE__ */ new Map();
1255
+ const isItem = elementKey === "item";
1256
+ let domUserProps = userProps;
1257
+ if (isItem && userProps) {
1258
+ const {
1259
+ [ACTIVE_KEY]: _,
1260
+ [SELECTED_KEY]: __,
1261
+ ...validProps
1262
+ } = userProps;
1263
+ domUserProps = validProps;
1264
+ }
1265
+ return {
1266
+ ...elementKey === "floating" && {
1267
+ tabIndex: -1,
1268
+ [FOCUSABLE_ATTRIBUTE]: ""
1269
+ },
1270
+ ...domUserProps,
1271
+ ...propsList.map((value) => {
1272
+ const propsOrGetProps = value ? value[elementKey] : null;
1273
+ if (typeof propsOrGetProps === "function") {
1274
+ return userProps ? propsOrGetProps(userProps) : null;
1275
+ }
1276
+ return propsOrGetProps;
1277
+ }).concat(userProps).reduce((acc, props) => {
1278
+ if (!props) {
1279
+ return acc;
1280
+ }
1281
+ Object.entries(props).forEach((_ref) => {
1282
+ let [key, value] = _ref;
1283
+ if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {
1284
+ return;
206
1285
  }
1286
+ if (key.indexOf("on") === 0) {
1287
+ if (!map.has(key)) {
1288
+ map.set(key, []);
1289
+ }
1290
+ if (typeof value === "function") {
1291
+ var _map$get;
1292
+ (_map$get = map.get(key)) == null || _map$get.push(value);
1293
+ acc[key] = function() {
1294
+ var _map$get2;
1295
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1296
+ args[_key] = arguments[_key];
1297
+ }
1298
+ return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map((fn) => fn(...args)).find((val) => val !== void 0);
1299
+ };
1300
+ }
1301
+ } else {
1302
+ acc[key] = value;
1303
+ }
1304
+ });
1305
+ return acc;
1306
+ }, {})
1307
+ };
1308
+ }
1309
+ function useInteractions(propsList) {
1310
+ if (propsList === void 0) {
1311
+ propsList = [];
1312
+ }
1313
+ const referenceDeps = propsList.map((key) => key == null ? void 0 : key.reference);
1314
+ const floatingDeps = propsList.map((key) => key == null ? void 0 : key.floating);
1315
+ const itemDeps = propsList.map((key) => key == null ? void 0 : key.item);
1316
+ const getReferenceProps = React.useCallback(
1317
+ (userProps) => mergeProps(userProps, propsList, "reference"),
1318
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1319
+ referenceDeps
1320
+ );
1321
+ const getFloatingProps = React.useCallback(
1322
+ (userProps) => mergeProps(userProps, propsList, "floating"),
1323
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1324
+ floatingDeps
1325
+ );
1326
+ const getItemProps = React.useCallback(
1327
+ (userProps) => mergeProps(userProps, propsList, "item"),
1328
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1329
+ itemDeps
1330
+ );
1331
+ return React.useMemo(() => ({
1332
+ getReferenceProps,
1333
+ getFloatingProps,
1334
+ getItemProps
1335
+ }), [getReferenceProps, getFloatingProps, getItemProps]);
1336
+ }
1337
+ const componentRoleToAriaRoleMap = /* @__PURE__ */ new Map([["select", "listbox"], ["combobox", "listbox"], ["label", false]]);
1338
+ function useRole(context, props) {
1339
+ var _componentRoleToAriaR;
1340
+ if (props === void 0) {
1341
+ props = {};
1342
+ }
1343
+ const {
1344
+ open,
1345
+ floatingId
1346
+ } = context;
1347
+ const {
1348
+ enabled = true,
1349
+ role = "dialog"
1350
+ } = props;
1351
+ const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;
1352
+ const referenceId = useId();
1353
+ const parentId = useFloatingParentNodeId();
1354
+ const isNested = parentId != null;
1355
+ const reference = React.useMemo(() => {
1356
+ if (ariaRole === "tooltip" || role === "label") {
1357
+ return {
1358
+ ["aria-" + (role === "label" ? "labelledby" : "describedby")]: open ? floatingId : void 0
207
1359
  };
208
1360
  }
209
1361
  return {
210
- position: strategy,
211
- left: x,
212
- top: y
1362
+ "aria-expanded": open ? "true" : "false",
1363
+ "aria-haspopup": ariaRole === "alertdialog" ? "dialog" : ariaRole,
1364
+ "aria-controls": open ? floatingId : void 0,
1365
+ ...ariaRole === "listbox" && {
1366
+ role: "combobox"
1367
+ },
1368
+ ...ariaRole === "menu" && {
1369
+ id: referenceId
1370
+ },
1371
+ ...ariaRole === "menu" && isNested && {
1372
+ role: "menuitem"
1373
+ },
1374
+ ...role === "select" && {
1375
+ "aria-autocomplete": "none"
1376
+ },
1377
+ ...role === "combobox" && {
1378
+ "aria-autocomplete": "list"
1379
+ }
213
1380
  };
214
- }, [strategy, transform, elements.floating, data.x, data.y]);
215
- return React.useMemo(() => ({
216
- ...data,
217
- update,
218
- refs,
219
- elements,
220
- floatingStyles
221
- }), [data, update, refs, elements, floatingStyles]);
1381
+ }, [ariaRole, floatingId, isNested, open, referenceId, role]);
1382
+ const floating = React.useMemo(() => {
1383
+ const floatingProps = {
1384
+ id: floatingId,
1385
+ ...ariaRole && {
1386
+ role: ariaRole
1387
+ }
1388
+ };
1389
+ if (ariaRole === "tooltip" || role === "label") {
1390
+ return floatingProps;
1391
+ }
1392
+ return {
1393
+ ...floatingProps,
1394
+ ...ariaRole === "menu" && {
1395
+ "aria-labelledby": referenceId
1396
+ }
1397
+ };
1398
+ }, [ariaRole, floatingId, referenceId, role]);
1399
+ const item = React.useCallback((_ref) => {
1400
+ let {
1401
+ active,
1402
+ selected
1403
+ } = _ref;
1404
+ const commonProps = {
1405
+ role: "option",
1406
+ ...active && {
1407
+ id: floatingId + "-option"
1408
+ }
1409
+ };
1410
+ switch (role) {
1411
+ case "select":
1412
+ return {
1413
+ ...commonProps,
1414
+ "aria-selected": active && selected
1415
+ };
1416
+ case "combobox": {
1417
+ return {
1418
+ ...commonProps,
1419
+ ...active && {
1420
+ "aria-selected": true
1421
+ }
1422
+ };
1423
+ }
1424
+ }
1425
+ return {};
1426
+ }, [floatingId, role]);
1427
+ return React.useMemo(() => enabled ? {
1428
+ reference,
1429
+ floating,
1430
+ item
1431
+ } : {}, [enabled, reference, floating, item]);
222
1432
  }
223
- const offset = (options, deps) => ({
224
- ...offset$1(options),
225
- options: [options, deps]
226
- });
227
- const shift = (options, deps) => ({
228
- ...shift$1(options),
229
- options: [options, deps]
230
- });
231
- const flip = (options, deps) => ({
232
- ...flip$1(options),
233
- options: [options, deps]
234
- });
235
- const inline = (options, deps) => ({
236
- ...inline$1(options),
237
- options: [options, deps]
238
- });
239
1433
  export {
240
- autoUpdate,
241
- computePosition,
1434
+ FloatingFocusManager,
1435
+ FloatingPortal,
242
1436
  flip,
1437
+ getOverflowAncestors,
243
1438
  inline,
244
1439
  offset,
245
- platform,
246
1440
  shift,
247
- useFloating
1441
+ useDismiss,
1442
+ useFloating,
1443
+ useFloatingParentNodeId,
1444
+ useFloatingPortalNode,
1445
+ useFloatingRootContext,
1446
+ useFloatingTree,
1447
+ useId,
1448
+ useInteractions,
1449
+ useRole
248
1450
  };
249
1451
  //# sourceMappingURL=react-text-annotator.es14.js.map