@y14e/portal 1.2.18 → 1.2.20

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.
package/README.md CHANGED
@@ -10,14 +10,14 @@ npm i @y14e/portal
10
10
 
11
11
  ```ts
12
12
  // npm
13
- import { createPortal } from '@y14e/portal@1.2.18';
13
+ import { createPortal } from '@y14e/portal@1.2.20';
14
14
 
15
15
  // CDNs
16
- import { createPortal } from 'https://esm.sh/@y14e/portal@1.2.18';
16
+ import { createPortal } from 'https://esm.sh/@y14e/portal@1.2.20';
17
17
  // or
18
- import { createPortal } from 'https://cdn.jsdelivr.net/npm/@y14e/portal@1.2.18/+esm';
18
+ import { createPortal } from 'https://cdn.jsdelivr.net/npm/@y14e/portal@1.2.20/+esm';
19
19
  // or
20
- import { createPortal } from 'https://esm.unpkg.com/@y14e/portal@1.2.18';
20
+ import { createPortal } from 'https://esm.unpkg.com/@y14e/portal@1.2.20';
21
21
  ```
22
22
 
23
23
  ## 📦 APIs
@@ -0,0 +1,601 @@
1
+ 'use strict';
2
+
3
+ // node_modules/@y14e/attributes-utils/dist/index.js
4
+ var snapshots = /* @__PURE__ */ new WeakMap();
5
+ function restoreAttributes(elements) {
6
+ for (const element of elements) {
7
+ const snapshot = snapshots.get(element);
8
+ if (!snapshot) {
9
+ continue;
10
+ }
11
+ for (const [attribute, value] of snapshot.entries()) {
12
+ value === null ? element.removeAttribute(attribute) : element.setAttribute(attribute, value);
13
+ }
14
+ snapshots.delete(element);
15
+ }
16
+ }
17
+ function saveAttributes(elements, attributes) {
18
+ elements.forEach((element) => {
19
+ let snapshot = snapshots.get(element);
20
+ if (!snapshot) {
21
+ snapshot = /* @__PURE__ */ new Map();
22
+ snapshots.set(element, snapshot);
23
+ }
24
+ attributes.forEach((attribute) => {
25
+ snapshot.set(attribute, element.getAttribute(attribute));
26
+ });
27
+ });
28
+ }
29
+
30
+ // node_modules/power-focusable/dist/index.js
31
+ var FOCUSABLE_SELECTOR = `:is(a[href], area[href], button, embed, iframe, input:not([type="hidden" i]), object, select, details > summary:first-of-type, textarea, [contenteditable]:not([contenteditable="false" i]), [controls], [tabindex]):not(:disabled, [hidden], [inert], [tabindex="-1"])`;
32
+ function getFocusables(container = document.body, options = {}) {
33
+ if (!(container instanceof Element)) {
34
+ console.warn("Invalid container element. Fallback: <body> element.");
35
+ container = document.body;
36
+ }
37
+ let {
38
+ composed = false,
39
+ filter,
40
+ include,
41
+ skipNegativeTabIndexCheck = false,
42
+ skipVisibilityCheck = false
43
+ } = options;
44
+ if (typeof composed !== "boolean") {
45
+ console.warn("Invalid composed option. Fallback: false.");
46
+ composed = false;
47
+ }
48
+ if (typeof filter !== "undefined" && typeof filter !== "function") {
49
+ console.warn(
50
+ "Invalid filter function. Fallback: no filter function (undefined)."
51
+ );
52
+ filter = void 0;
53
+ }
54
+ if (typeof include !== "undefined" && typeof include !== "function") {
55
+ console.warn(
56
+ "Invalid include function. Fallback: no include function (undefined)."
57
+ );
58
+ include = void 0;
59
+ }
60
+ if (typeof skipNegativeTabIndexCheck !== "boolean") {
61
+ console.warn("Invalid skipNegativeTabIndexCheck option. Fallback: false.");
62
+ skipNegativeTabIndexCheck = false;
63
+ }
64
+ if (typeof skipVisibilityCheck !== "boolean") {
65
+ console.warn("Invalid skipVisibilityCheck option. Fallback: false.");
66
+ skipVisibilityCheck = false;
67
+ }
68
+ const elements = [];
69
+ if (composed || include) {
70
+ let traverse2 = function(node) {
71
+ if (!(node instanceof Element)) {
72
+ return;
73
+ }
74
+ if (isFocusable(node, { skipNegativeTabIndexCheck, skipVisibilityCheck }) || include?.(node)) {
75
+ elements[elements.length] = node;
76
+ }
77
+ const children = getComposedChildren(node);
78
+ for (let i = 0, l = children.length; i < l; i++) {
79
+ const child = children[i];
80
+ child && traverse2(child);
81
+ }
82
+ };
83
+ traverse2(container);
84
+ } else {
85
+ const candidates = container.querySelectorAll(FOCUSABLE_SELECTOR);
86
+ for (let i = 0, l = candidates.length; i < l; i++) {
87
+ const candidate = candidates[i];
88
+ if (candidate && isFocusable(candidate, {
89
+ skipNegativeTabIndexCheck,
90
+ skipVisibilityCheck
91
+ })) {
92
+ elements[elements.length] = candidate;
93
+ }
94
+ }
95
+ }
96
+ const unfiltered = normalizeRadioGroup(sortByTabIndex(elements));
97
+ return filter ? unfiltered.filter(filter) : unfiltered;
98
+ }
99
+ function getNextFocusable(container = document.body, options = {}) {
100
+ return getRelativeFocusable(container, 1, options);
101
+ }
102
+ function getPreviousFocusable(container = document.body, options = {}) {
103
+ return getRelativeFocusable(container, -1, options);
104
+ }
105
+ function isFocusable(element, options = {}) {
106
+ if (!(element instanceof Element)) {
107
+ console.warn("Invalid element");
108
+ return false;
109
+ }
110
+ let { skipNegativeTabIndexCheck = false, skipVisibilityCheck = false } = options;
111
+ if (typeof skipNegativeTabIndexCheck !== "boolean") {
112
+ console.warn("Invalid skipNegativeTabIndexCheck option. Fallback: false.");
113
+ skipNegativeTabIndexCheck = false;
114
+ }
115
+ if (typeof skipVisibilityCheck !== "boolean") {
116
+ console.warn("Invalid skipVisibilityCheck option. Fallback: false.");
117
+ skipVisibilityCheck = false;
118
+ }
119
+ if (element.hasAttribute("hidden") || isInert(element)) {
120
+ return false;
121
+ }
122
+ if (!skipNegativeTabIndexCheck && getTabIndex(element) < 0) {
123
+ return false;
124
+ }
125
+ if (!element.matches(
126
+ skipNegativeTabIndexCheck ? FOCUSABLE_SELECTOR.replace(/(,\s*)?\[tabindex="-1"\]/g, "") : FOCUSABLE_SELECTOR
127
+ )) {
128
+ return false;
129
+ }
130
+ if (isDisabledDeep(element)) {
131
+ return false;
132
+ }
133
+ if (!skipVisibilityCheck && !element.checkVisibility({
134
+ contentVisibilityAuto: true,
135
+ opacityProperty: true,
136
+ visibilityProperty: true
137
+ })) {
138
+ return false;
139
+ }
140
+ return true;
141
+ }
142
+ function getRelativeFocusable(container, offset, options) {
143
+ if (!(container instanceof Element)) {
144
+ console.warn("Invalid container element. Fallback: <body> element.");
145
+ container = document.body;
146
+ }
147
+ let {
148
+ anchor = getActiveElement(),
149
+ composed = false,
150
+ filter,
151
+ include,
152
+ skipNegativeTabIndexCheck = false,
153
+ skipVisibilityCheck = false,
154
+ wrap = false
155
+ } = options;
156
+ if (!(anchor instanceof Element)) {
157
+ const active = getActiveElement();
158
+ if (active instanceof Element) {
159
+ console.warn("Invalid anchor element. Fallback: active element.");
160
+ anchor = active;
161
+ } else {
162
+ console.warn("Invalid anchor element");
163
+ return null;
164
+ }
165
+ }
166
+ if (!containsComposed(container, anchor)) {
167
+ console.warn("Anchor (active) element not within container");
168
+ return null;
169
+ }
170
+ if (typeof composed !== "boolean") {
171
+ console.warn("Invalid composed option. Fallback: false.");
172
+ composed = false;
173
+ }
174
+ if (typeof filter !== "undefined" && typeof filter !== "function") {
175
+ console.warn(
176
+ "Invalid filter function. Fallback: no filter function (undefined)."
177
+ );
178
+ filter = void 0;
179
+ }
180
+ if (typeof include !== "undefined" && typeof include !== "function") {
181
+ console.warn(
182
+ "Invalid include function. Fallback: no include function (undefined)."
183
+ );
184
+ include = void 0;
185
+ }
186
+ if (typeof skipNegativeTabIndexCheck !== "boolean") {
187
+ console.warn("Invalid skipNegativeTabIndexCheck option. Fallback: false.");
188
+ skipNegativeTabIndexCheck = false;
189
+ }
190
+ if (typeof skipVisibilityCheck !== "boolean") {
191
+ console.warn("Invalid skipVisibilityCheck option. Fallback: false.");
192
+ skipVisibilityCheck = false;
193
+ }
194
+ if (typeof wrap !== "boolean") {
195
+ console.warn("Invalid wrap option. Fallback: false.");
196
+ wrap = false;
197
+ }
198
+ const settings = { composed, skipNegativeTabIndexCheck, skipVisibilityCheck };
199
+ if (filter !== void 0) {
200
+ Object.assign(settings, { filter });
201
+ }
202
+ if (include !== void 0) {
203
+ Object.assign(settings, { include });
204
+ }
205
+ const focusables = getFocusables(container, settings);
206
+ const { length } = focusables;
207
+ if (!length) {
208
+ return null;
209
+ }
210
+ const currentIndex = focusables.indexOf(anchor);
211
+ if (currentIndex === -1) {
212
+ return null;
213
+ }
214
+ const offsetIndex = currentIndex + offset;
215
+ if ((offsetIndex < 0 || offsetIndex >= length) && !wrap) {
216
+ return null;
217
+ }
218
+ return focusables[(offsetIndex + length) % length] ?? null;
219
+ }
220
+ function isDisabledDeep(element) {
221
+ let current = element;
222
+ while (current) {
223
+ if (current instanceof ShadowRoot) {
224
+ if (current.mode !== "open") {
225
+ return false;
226
+ }
227
+ current = current.host;
228
+ continue;
229
+ }
230
+ if (!(current instanceof Element)) {
231
+ current = current.parentNode;
232
+ continue;
233
+ }
234
+ if (current === element && isFormControl(current) && isDisabled(current)) {
235
+ return true;
236
+ }
237
+ if (isInert(current)) {
238
+ return true;
239
+ }
240
+ if (isFormControl(element) && current.tagName === "FIELDSET" && isDisabled(current)) {
241
+ if (!current.querySelector(":scope > legend:first-of-type")?.contains(element)) {
242
+ return true;
243
+ }
244
+ }
245
+ current = current.parentNode;
246
+ }
247
+ return false;
248
+ }
249
+ function normalizeRadioGroup(elements) {
250
+ let map = null;
251
+ for (let i = 0, l = elements.length; i < l; i++) {
252
+ const element = elements[i];
253
+ if (!(element instanceof HTMLInputElement)) {
254
+ continue;
255
+ }
256
+ if (!isUngroupedRadio(element)) {
257
+ continue;
258
+ }
259
+ if (!map) {
260
+ map = /* @__PURE__ */ new Map();
261
+ }
262
+ const key = `${element.form?.id ?? "no-form"}::${element.name}`;
263
+ const group = map.get(key) ?? map.set(key, []).get(key);
264
+ if (group) {
265
+ group[group.length] = element;
266
+ }
267
+ }
268
+ if (!map) {
269
+ return elements;
270
+ }
271
+ const placeholder = /* @__PURE__ */ new Set();
272
+ for (const group of map.values()) {
273
+ placeholder.add(group.find((radio) => radio.checked) ?? group[0]);
274
+ }
275
+ return elements.filter(
276
+ (element) => isUngroupedRadio(element) ? placeholder.has(element) : true
277
+ );
278
+ }
279
+ function sortByTabIndex(elements) {
280
+ const ordered = [];
281
+ const natural = [];
282
+ for (let i = 0, l = elements.length; i < l; i++) {
283
+ const element = elements[i];
284
+ if (element) {
285
+ const target = getTabIndex(element) > 0 ? ordered : natural;
286
+ target[target.length] = element;
287
+ }
288
+ }
289
+ ordered.sort((a, b) => getTabIndex(a) - getTabIndex(b));
290
+ let count = 0;
291
+ const sorted = new Array(ordered.length + natural.length);
292
+ for (let i = 0, l = ordered.length; i < l; i++) {
293
+ sorted[count++] = ordered[i];
294
+ }
295
+ for (let i = 0, l = natural.length; i < l; i++) {
296
+ sorted[count++] = natural[i];
297
+ }
298
+ return sorted;
299
+ }
300
+ function containsComposed(container, element) {
301
+ let current = element;
302
+ while (current) {
303
+ if (current === container) {
304
+ return true;
305
+ } else {
306
+ current = current instanceof ShadowRoot ? current.mode === "open" ? current.host : null : current.parentNode;
307
+ }
308
+ }
309
+ return false;
310
+ }
311
+ function getComposedChildren(node) {
312
+ if (node instanceof ShadowRoot) {
313
+ return getChildren(node);
314
+ }
315
+ if (!(node instanceof Element)) {
316
+ return [];
317
+ }
318
+ if (node instanceof HTMLSlotElement) {
319
+ const assigned = node.assignedElements({ flatten: true });
320
+ if (assigned.length) {
321
+ return assigned;
322
+ }
323
+ }
324
+ if (node instanceof HTMLElement && node.shadowRoot?.mode === "open") {
325
+ return getChildren(node.shadowRoot);
326
+ }
327
+ return getChildren(node);
328
+ }
329
+ function focusElement(element) {
330
+ "focus" in element && typeof element.focus === "function" && element.focus();
331
+ }
332
+ function getActiveElement() {
333
+ let current = document.activeElement;
334
+ while (current?.shadowRoot?.activeElement) {
335
+ current = current.shadowRoot.activeElement;
336
+ }
337
+ return current;
338
+ }
339
+ function getChildren(node) {
340
+ const elements = [];
341
+ for (let child = node.firstElementChild; child; child = child.nextElementSibling) {
342
+ elements[elements.length] = child;
343
+ }
344
+ return elements;
345
+ }
346
+ function getTabIndex(element) {
347
+ return "tabIndex" in element ? Number(element.tabIndex) : 0;
348
+ }
349
+ function isDisabled(element) {
350
+ return "disabled" in element && !!element.disabled;
351
+ }
352
+ function isFormControl(element) {
353
+ const name = element.tagName;
354
+ return name === "BUTTON" || name === "INPUT" || name === "SELECT" || name === "TEXTAREA";
355
+ }
356
+ function isInert(element) {
357
+ return "inert" in element && !!element.inert;
358
+ }
359
+ function isUngroupedRadio(element) {
360
+ return element instanceof HTMLInputElement && element.type === "radio" && !!element.name;
361
+ }
362
+
363
+ // src/index.ts
364
+ var VISUALLY_HIDDEN_CSS = `border: 0; clip: rect(0, 0, 0, 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; user-select: none; white-space: nowrap; width: 1px;`;
365
+ function createPortal(host, container = document.body) {
366
+ if (!(host instanceof Element)) {
367
+ console.warn("Invalid host element");
368
+ return () => {
369
+ };
370
+ }
371
+ if (host.hasAttribute("data-portaled")) {
372
+ console.warn("Already portaled");
373
+ return () => {
374
+ };
375
+ }
376
+ if (containsComposed2(host, container)) {
377
+ console.warn("Host element cannot contain the container element");
378
+ return () => {
379
+ };
380
+ }
381
+ const portal = new Portal(host, container);
382
+ return () => portal.destroy();
383
+ }
384
+ var Portal = class {
385
+ #host;
386
+ #container;
387
+ #entranceSentinel;
388
+ #exitSentinel;
389
+ #focusables = /* @__PURE__ */ new Set();
390
+ #controller = null;
391
+ #timer;
392
+ #isDestroyed = false;
393
+ constructor(host, container) {
394
+ this.#host = host;
395
+ if (!(container instanceof Element)) {
396
+ console.warn("Invalid container element. Fallback: <body> element.");
397
+ container = document.body;
398
+ }
399
+ this.#container = container;
400
+ this.#entranceSentinel = this.#createSentinel();
401
+ this.#exitSentinel = this.#createSentinel();
402
+ this.#initialize();
403
+ }
404
+ destroy() {
405
+ if (this.#isDestroyed) {
406
+ return;
407
+ }
408
+ this.#isDestroyed = true;
409
+ this.#controller?.abort();
410
+ this.#controller = null;
411
+ if (this.#timer !== void 0) {
412
+ cancelAnimationFrame(this.#timer);
413
+ this.#timer = void 0;
414
+ }
415
+ restoreAttributes([...this.#focusables]);
416
+ this.#focusables.clear();
417
+ this.#exitSentinel.after(this.#host);
418
+ this.#entranceSentinel.remove();
419
+ this.#exitSentinel.remove();
420
+ this.#host.removeAttribute("data-portaled");
421
+ }
422
+ #initialize() {
423
+ this.#host.before(this.#entranceSentinel);
424
+ this.#entranceSentinel.after(this.#exitSentinel);
425
+ this.#container.append(this.#host);
426
+ this.#update();
427
+ this.#controller = new AbortController();
428
+ const { signal } = this.#controller;
429
+ document.addEventListener("focusin", this.#onFocusIn, {
430
+ capture: true,
431
+ signal
432
+ });
433
+ document.addEventListener("keydown", this.#onKeyDown, {
434
+ capture: true,
435
+ signal
436
+ });
437
+ this.#host.setAttribute("data-portaled", "");
438
+ }
439
+ #onFocusIn = (event) => {
440
+ const current = event.target;
441
+ const before = event.relatedTarget;
442
+ if (!(before instanceof Element)) {
443
+ return;
444
+ }
445
+ if (current === this.#entranceSentinel) {
446
+ if (this.#host.contains(before)) {
447
+ this.#moveFocus("previous");
448
+ return;
449
+ }
450
+ this.#update();
451
+ const first = [...this.#focusables][0];
452
+ if (first) {
453
+ focusElement(first);
454
+ } else {
455
+ const next = getNextFocusable(document.body, {
456
+ anchor: this.#exitSentinel,
457
+ composed: true
458
+ });
459
+ next && focusElement(next);
460
+ }
461
+ } else if (current === this.#exitSentinel) {
462
+ if (this.#host.contains(before)) {
463
+ this.#moveFocus("next");
464
+ return;
465
+ }
466
+ this.#update();
467
+ const last = [...this.#focusables].at(-1);
468
+ if (last) {
469
+ focusElement(last);
470
+ } else {
471
+ const previous = getPreviousFocusable(document.body, {
472
+ anchor: this.#entranceSentinel,
473
+ composed: true
474
+ });
475
+ previous && focusElement(previous);
476
+ }
477
+ }
478
+ };
479
+ #onKeyDown = (event) => {
480
+ const { key, altKey, ctrlKey, metaKey, shiftKey } = event;
481
+ if (key !== "Tab" || altKey || ctrlKey || metaKey) {
482
+ return;
483
+ }
484
+ const active = getActiveElement();
485
+ if (!(active instanceof Element)) {
486
+ return;
487
+ }
488
+ if (!this.#host.contains(active)) {
489
+ return;
490
+ }
491
+ this.#update();
492
+ const focusables = this.#getFocusables();
493
+ if (focusables.length) {
494
+ const index = focusables.indexOf(active);
495
+ if (index !== -1) {
496
+ event.preventDefault();
497
+ const focusable = focusables[index + (shiftKey ? -1 : 1)];
498
+ focusable ? focusElement(focusable) : this.#focusSentinel(shiftKey);
499
+ }
500
+ } else {
501
+ event.preventDefault();
502
+ this.#moveFocus(shiftKey ? "previous" : "next");
503
+ }
504
+ };
505
+ #update() {
506
+ const current = /* @__PURE__ */ new Set([
507
+ ...this.#getFocusables(),
508
+ ...getFocusables(this.#host, { composed: true })
509
+ ]);
510
+ for (const focusable of this.#focusables) {
511
+ if (!current.has(focusable)) {
512
+ focusable.isConnected && restoreAttributes([focusable]);
513
+ this.#focusables.delete(focusable);
514
+ }
515
+ }
516
+ for (const focusable of current) {
517
+ if (!this.#focusables.has(focusable)) {
518
+ this.#focusables.add(focusable);
519
+ saveAttributes([focusable], ["tabindex"]);
520
+ focusable.setAttribute("tabindex", "-1");
521
+ }
522
+ }
523
+ }
524
+ #createSentinel() {
525
+ const sentinel = document.createElement("span");
526
+ sentinel.setAttribute("aria-hidden", "true");
527
+ sentinel.setAttribute("data-portal-sentinel", "");
528
+ sentinel.setAttribute("tabindex", "0");
529
+ sentinel.style.cssText += VISUALLY_HIDDEN_CSS;
530
+ return sentinel;
531
+ }
532
+ #focusSentinel(isPrevious) {
533
+ this.#timer && cancelAnimationFrame(this.#timer);
534
+ this.#timer = requestAnimationFrame(
535
+ () => (isPrevious ? this.#entranceSentinel : this.#exitSentinel).focus()
536
+ );
537
+ }
538
+ #getFocusables() {
539
+ return getFocusables(this.#host, {
540
+ composed: true,
541
+ include: (element) => this.#focusables.has(element)
542
+ });
543
+ }
544
+ #moveFocus(direction) {
545
+ const options = {
546
+ anchor: direction === "previous" ? this.#entranceSentinel : this.#exitSentinel,
547
+ composed: true
548
+ };
549
+ const focusable = direction === "previous" ? getPreviousFocusable(document.body, options) : getNextFocusable(document.body, options);
550
+ focusable && focusElement(focusable);
551
+ }
552
+ };
553
+ function containsComposed2(container, element) {
554
+ let current = element;
555
+ while (current) {
556
+ if (current === container) {
557
+ return true;
558
+ }
559
+ current = current instanceof ShadowRoot ? current.mode === "open" ? current.host : null : current.parentNode;
560
+ }
561
+ return false;
562
+ }
563
+ /**
564
+ * Portal
565
+ * Lightweight DOM portal (teleport) utility with fully focus management.
566
+ * Designed for accessible dialogs, menus, overlays, popovers.
567
+ *
568
+ * @version 1.2.20
569
+ * @author Yusuke Kamiyamane
570
+ * @license MIT
571
+ * @copyright Copyright (c) Yusuke Kamiyamane
572
+ * @see {@link https://github.com/y14e/portal}
573
+ */
574
+ /*! Bundled license information:
575
+
576
+ @y14e/attributes-utils/dist/index.js:
577
+ (**
578
+ * Attributes Utils
579
+ *
580
+ * @version 1.1.2
581
+ * @author Yusuke Kamiyamane
582
+ * @license MIT
583
+ * @copyright Copyright (c) Yusuke Kamiyamane
584
+ * @see {@link https://github.com/y14e/attributes-utils}
585
+ *)
586
+
587
+ power-focusable/dist/index.js:
588
+ (**
589
+ * Power Focusable
590
+ * High-precision focus management utility with full composed tree support.
591
+ * Handles complex focus rules including tabindex ordering, radio groups, inert.
592
+ *
593
+ * @version 4.3.3
594
+ * @author Yusuke Kamiyamane
595
+ * @license MIT
596
+ * @copyright Copyright (c) Yusuke Kamiyamane
597
+ * @see {@link https://github.com/y14e/power-focusable}
598
+ *)
599
+ */
600
+
601
+ exports.createPortal = createPortal;