@zag-js/popover 0.0.0-20220802150625

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Chakra UI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # @zag-js/popover
2
+
3
+ Core logic for the popover widget implemented as a state machine
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ yarn add @zag-js/popover
9
+ # or
10
+ npm i @zag-js/popover
11
+ ```
12
+
13
+ ## Contribution
14
+
15
+ Yes please! See the [contributing guidelines](https://github.com/chakra-ui/zag/blob/main/CONTRIBUTING.md) for details.
16
+
17
+ ## Licence
18
+
19
+ This project is licensed under the terms of the [MIT license](https://github.com/chakra-ui/zag/blob/main/LICENSE).
@@ -0,0 +1,103 @@
1
+ import { RequiredBy, CommonProperties, MaybeElement, Context, PropTypes, NormalizeProps } from '@zag-js/types';
2
+ import * as _zag_js_core from '@zag-js/core';
3
+ import { StateMachine } from '@zag-js/core';
4
+ import { DismissableElementHandlers } from '@zag-js/dismissable';
5
+ import { PositioningOptions } from '@zag-js/popper';
6
+
7
+ declare type ElementIds = Partial<{
8
+ anchor: string;
9
+ trigger: string;
10
+ content: string;
11
+ title: string;
12
+ description: string;
13
+ closeBtn: string;
14
+ }>;
15
+ declare type PublicContext = DismissableElementHandlers & CommonProperties & {
16
+ /**
17
+ * The ids of the elements in the popover. Useful for composition.
18
+ */
19
+ ids?: ElementIds;
20
+ /**
21
+ * Whether the popover should be modal. When set to `true`:
22
+ * - interaction with outside elements will be disabled
23
+ * - only popover content will be visible to screen readers
24
+ * - scrolling is blocked
25
+ * - focus is trapped within the popover
26
+ *
27
+ * @default false
28
+ */
29
+ modal?: boolean;
30
+ /**
31
+ * Whether the popover is rendered in a portal
32
+ */
33
+ portalled?: boolean;
34
+ /**
35
+ * Whether to automatically set focus on the first focusable
36
+ * content within the popover when opened.
37
+ */
38
+ autoFocus?: boolean;
39
+ /**
40
+ * The element to focus on when the popover is opened.
41
+ */
42
+ initialFocusEl?: MaybeElement | (() => MaybeElement);
43
+ /**
44
+ * Whether to close the popover when the user clicks outside of the popover.
45
+ */
46
+ closeOnInteractOutside?: boolean;
47
+ /**
48
+ * Whether to close the popover when the escape key is pressed.
49
+ */
50
+ closeOnEsc?: boolean;
51
+ /**
52
+ * Function invoked when the popover is opened.
53
+ */
54
+ onOpenChange?: (open: boolean) => void;
55
+ /**
56
+ * The user provided options used to position the popover content
57
+ */
58
+ positioning: PositioningOptions;
59
+ /**
60
+ * Whether to open the popover on page load
61
+ */
62
+ defaultOpen?: boolean;
63
+ };
64
+ declare type UserDefinedContext = RequiredBy<PublicContext, "id">;
65
+ declare type ComputedContext = Readonly<{
66
+ /**
67
+ * @computed
68
+ * The computed value of `portalled`
69
+ */
70
+ currentPortalled: boolean;
71
+ }>;
72
+ declare type PrivateContext = Context<{
73
+ /**
74
+ * Whether to prevent returning focus to the trigger
75
+ */
76
+ focusTriggerOnClose?: boolean;
77
+ }>;
78
+ declare type MachineContext = PublicContext & ComputedContext & PrivateContext;
79
+ declare type MachineState = {
80
+ value: "unknown" | "open" | "closed";
81
+ };
82
+ declare type State = StateMachine.State<MachineContext, MachineState>;
83
+ declare type Send = StateMachine.Send<StateMachine.AnyEventObject>;
84
+
85
+ declare function connect<T extends PropTypes>(state: State, send: Send, normalize: NormalizeProps<T>): {
86
+ portalled: boolean;
87
+ isOpen: boolean;
88
+ open(): void;
89
+ close(): void;
90
+ arrowProps: T["element"];
91
+ innerArrowProps: T["element"];
92
+ anchorProps: T["element"];
93
+ triggerProps: T["button"];
94
+ positionerProps: T["element"];
95
+ contentProps: T["element"];
96
+ titleProps: T["element"];
97
+ descriptionProps: T["element"];
98
+ closeButtonProps: T["button"];
99
+ };
100
+
101
+ declare function machine(ctx: UserDefinedContext): _zag_js_core.Machine<MachineContext, MachineState, _zag_js_core.StateMachine.AnyEventObject>;
102
+
103
+ export { UserDefinedContext as Context, connect, machine };
package/dist/index.js ADDED
@@ -0,0 +1,607 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ connect: () => connect,
24
+ machine: () => machine
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // ../../utilities/dom/dist/index.mjs
29
+ var dataAttr = (guard) => {
30
+ return guard ? "" : void 0;
31
+ };
32
+ var runIfFn = (v, ...a) => {
33
+ const res = typeof v === "function" ? v(...a) : v;
34
+ return res ?? void 0;
35
+ };
36
+ var hasProp = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
37
+ function isDocument(el) {
38
+ return el.nodeType === Node.DOCUMENT_NODE;
39
+ }
40
+ function isWindow(value) {
41
+ return (value == null ? void 0 : value.toString()) === "[object Window]";
42
+ }
43
+ function isFrame(element) {
44
+ return element.localName === "iframe";
45
+ }
46
+ function getDocument(el) {
47
+ if (isWindow(el))
48
+ return el.document;
49
+ if (isDocument(el))
50
+ return el;
51
+ return (el == null ? void 0 : el.ownerDocument) ?? document;
52
+ }
53
+ function defineDomHelpers(helpers) {
54
+ const dom2 = {
55
+ getRootNode: (ctx) => {
56
+ var _a;
57
+ return ((_a = ctx.getRootNode) == null ? void 0 : _a.call(ctx)) ?? document;
58
+ },
59
+ getDoc: (ctx) => getDocument(dom2.getRootNode(ctx)),
60
+ getWin: (ctx) => dom2.getDoc(ctx).defaultView ?? window,
61
+ getActiveElement: (ctx) => dom2.getDoc(ctx).activeElement,
62
+ getById: (ctx, id) => dom2.getRootNode(ctx).getElementById(id)
63
+ };
64
+ return {
65
+ ...dom2,
66
+ ...helpers
67
+ };
68
+ }
69
+ function contains(parent, child) {
70
+ if (!parent)
71
+ return false;
72
+ return parent === child || isHTMLElement(parent) && isHTMLElement(child) && parent.contains(child);
73
+ }
74
+ function isHTMLElement(v) {
75
+ return typeof v === "object" && (v == null ? void 0 : v.nodeType) === Node.ELEMENT_NODE && typeof (v == null ? void 0 : v.nodeName) === "string";
76
+ }
77
+ function isVisible(el) {
78
+ if (!isHTMLElement(el))
79
+ return false;
80
+ return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
81
+ }
82
+ var isModifiedEvent = (v) => v.ctrlKey || v.altKey || v.metaKey;
83
+ function hasNegativeTabIndex(element) {
84
+ const tabIndex = parseInt(element.getAttribute("tabindex") || "0", 10);
85
+ return tabIndex < 0;
86
+ }
87
+ var focusableSelector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false']), details > summary:first-of-type";
88
+ var getFocusables = (container, includeContainer = false) => {
89
+ if (!container)
90
+ return [];
91
+ const elements = Array.from(container.querySelectorAll(focusableSelector));
92
+ const include = includeContainer == true || includeContainer == "if-empty" && elements.length === 0;
93
+ if (include && isHTMLElement(container) && isFocusable(container)) {
94
+ elements.unshift(container);
95
+ }
96
+ const focusableElements = elements.filter(isFocusable);
97
+ focusableElements.forEach((element, i) => {
98
+ if (isFrame(element) && element.contentDocument) {
99
+ const frameBody = element.contentDocument.body;
100
+ focusableElements.splice(i, 1, ...getFocusables(frameBody));
101
+ }
102
+ });
103
+ return focusableElements;
104
+ };
105
+ function isFocusable(element) {
106
+ if (!element)
107
+ return false;
108
+ return element.matches(focusableSelector) && isVisible(element);
109
+ }
110
+ function getTabbables(container, includeContainer) {
111
+ if (!container)
112
+ return [];
113
+ const elements = Array.from(container.querySelectorAll(focusableSelector));
114
+ const tabbableElements = elements.filter(isTabbable);
115
+ if (includeContainer && isTabbable(container)) {
116
+ tabbableElements.unshift(container);
117
+ }
118
+ tabbableElements.forEach((element, i) => {
119
+ if (isFrame(element) && element.contentDocument) {
120
+ const frameBody = element.contentDocument.body;
121
+ const allFrameTabbable = getTabbables(frameBody);
122
+ tabbableElements.splice(i, 1, ...allFrameTabbable);
123
+ }
124
+ });
125
+ if (!tabbableElements.length && includeContainer) {
126
+ return elements;
127
+ }
128
+ return tabbableElements;
129
+ }
130
+ function isTabbable(el) {
131
+ return isFocusable(el) && !hasNegativeTabIndex(el);
132
+ }
133
+ function getFirstTabbable(container, includeContainer) {
134
+ const [first] = getTabbables(container, includeContainer);
135
+ return first || null;
136
+ }
137
+ function getLastTabbable(container, includeContainer) {
138
+ const elements = getTabbables(container, includeContainer);
139
+ return elements[elements.length - 1] || null;
140
+ }
141
+ var isRef = (v) => hasProp(v, "current");
142
+ function addDomEvent(target, eventName, handler, options) {
143
+ const node = isRef(target) ? target.current : runIfFn(target);
144
+ node == null ? void 0 : node.addEventListener(eventName, handler, options);
145
+ return () => {
146
+ node == null ? void 0 : node.removeEventListener(eventName, handler, options);
147
+ };
148
+ }
149
+ function nextTick(fn) {
150
+ const set = /* @__PURE__ */ new Set();
151
+ function raf2(fn2) {
152
+ const id = globalThis.requestAnimationFrame(fn2);
153
+ set.add(() => globalThis.cancelAnimationFrame(id));
154
+ }
155
+ raf2(() => raf2(fn));
156
+ return function cleanup() {
157
+ set.forEach(function(fn2) {
158
+ fn2();
159
+ });
160
+ };
161
+ }
162
+ function raf(fn) {
163
+ const id = globalThis.requestAnimationFrame(fn);
164
+ return function cleanup() {
165
+ globalThis.cancelAnimationFrame(id);
166
+ };
167
+ }
168
+
169
+ // src/popover.connect.ts
170
+ var import_popper = require("@zag-js/popper");
171
+
172
+ // ../../utilities/core/dist/index.mjs
173
+ function nextIndex(v, idx, opts = {}) {
174
+ const { step = 1, loop = true } = opts;
175
+ const next2 = idx + step;
176
+ const len = v.length;
177
+ const last2 = len - 1;
178
+ if (idx === -1)
179
+ return step > 0 ? 0 : last2;
180
+ if (next2 < 0)
181
+ return loop ? last2 : 0;
182
+ if (next2 >= len)
183
+ return loop ? 0 : idx > len ? len : idx;
184
+ return next2;
185
+ }
186
+ function next(v, idx, opts = {}) {
187
+ return v[nextIndex(v, idx, opts)];
188
+ }
189
+ var runIfFn2 = (v, ...a) => {
190
+ const res = typeof v === "function" ? v(...a) : v;
191
+ return res ?? void 0;
192
+ };
193
+
194
+ // src/popover.dom.ts
195
+ var dom = defineDomHelpers({
196
+ getActiveEl: (ctx) => dom.getDoc(ctx).activeElement,
197
+ getAnchorId: (ctx) => {
198
+ var _a;
199
+ return ((_a = ctx.ids) == null ? void 0 : _a.anchor) ?? `popover:${ctx.id}:anchor`;
200
+ },
201
+ getTriggerId: (ctx) => {
202
+ var _a;
203
+ return ((_a = ctx.ids) == null ? void 0 : _a.trigger) ?? `popover:${ctx.id}:trigger`;
204
+ },
205
+ getContentId: (ctx) => {
206
+ var _a;
207
+ return ((_a = ctx.ids) == null ? void 0 : _a.content) ?? `popover:${ctx.id}:content`;
208
+ },
209
+ getPositionerId: (ctx) => `popover:${ctx.id}:popper`,
210
+ getArrowId: (ctx) => `popover:${ctx.id}:arrow`,
211
+ getTitleId: (ctx) => {
212
+ var _a;
213
+ return ((_a = ctx.ids) == null ? void 0 : _a.title) ?? `popover:${ctx.id}:title`;
214
+ },
215
+ getDescriptionId: (ctx) => {
216
+ var _a;
217
+ return ((_a = ctx.ids) == null ? void 0 : _a.description) ?? `popover:${ctx.id}:desc`;
218
+ },
219
+ getCloseButtonId: (ctx) => {
220
+ var _a;
221
+ return ((_a = ctx.ids) == null ? void 0 : _a.closeBtn) ?? `popover:${ctx.id}:close-button`;
222
+ },
223
+ getAnchorEl: (ctx) => dom.getById(ctx, dom.getAnchorId(ctx)),
224
+ getTriggerEl: (ctx) => dom.getById(ctx, dom.getTriggerId(ctx)),
225
+ getContentEl: (ctx) => dom.getById(ctx, dom.getContentId(ctx)),
226
+ getPositionerEl: (ctx) => dom.getById(ctx, dom.getPositionerId(ctx)),
227
+ getTitleEl: (ctx) => dom.getById(ctx, dom.getTitleId(ctx)),
228
+ getDescriptionEl: (ctx) => dom.getById(ctx, dom.getDescriptionId(ctx)),
229
+ getFocusableEls: (ctx) => getFocusables(dom.getContentEl(ctx)),
230
+ getFirstFocusableEl: (ctx) => dom.getFocusableEls(ctx)[0],
231
+ getDocTabbableEls: (ctx) => getTabbables(dom.getDoc(ctx).body),
232
+ getTabbableEls: (ctx) => getTabbables(dom.getContentEl(ctx), "if-empty"),
233
+ getFirstTabbableEl: (ctx) => getFirstTabbable(dom.getContentEl(ctx), "if-empty"),
234
+ getLastTabbableEl: (ctx) => getLastTabbable(dom.getContentEl(ctx), "if-empty"),
235
+ getInitialFocusEl: (ctx) => {
236
+ let el = runIfFn2(ctx.initialFocusEl);
237
+ if (!el && ctx.autoFocus)
238
+ el = dom.getFirstFocusableEl(ctx);
239
+ if (!el)
240
+ el = dom.getContentEl(ctx);
241
+ return el;
242
+ }
243
+ });
244
+
245
+ // src/popover.connect.ts
246
+ function connect(state, send, normalize) {
247
+ const isOpen = state.matches("open");
248
+ const currentPlacement = state.context.currentPlacement;
249
+ const portalled = state.context.currentPortalled;
250
+ const rendered = state.context.renderedElements;
251
+ const popperStyles = (0, import_popper.getPlacementStyles)({
252
+ measured: !!state.context.isPlacementComplete,
253
+ placement: currentPlacement
254
+ });
255
+ return {
256
+ portalled,
257
+ isOpen,
258
+ open() {
259
+ send("OPEN");
260
+ },
261
+ close() {
262
+ send("CLOSE");
263
+ },
264
+ arrowProps: normalize.element({
265
+ id: dom.getArrowId(state.context),
266
+ "data-part": "arrow",
267
+ style: popperStyles.arrow
268
+ }),
269
+ innerArrowProps: normalize.element({
270
+ "data-part": "arrow-inner",
271
+ style: popperStyles.innerArrow
272
+ }),
273
+ anchorProps: normalize.element({
274
+ "data-part": "anchor",
275
+ id: dom.getAnchorId(state.context)
276
+ }),
277
+ triggerProps: normalize.button({
278
+ "data-part": "trigger",
279
+ type: "button",
280
+ "data-placement": currentPlacement,
281
+ id: dom.getTriggerId(state.context),
282
+ "aria-haspopup": "dialog",
283
+ "aria-expanded": isOpen,
284
+ "data-expanded": dataAttr(isOpen),
285
+ "aria-controls": dom.getContentId(state.context),
286
+ onClick() {
287
+ send("TOGGLE");
288
+ },
289
+ onBlur(event) {
290
+ send({ type: "TRIGGER_BLUR", target: event.relatedTarget });
291
+ }
292
+ }),
293
+ positionerProps: normalize.element({
294
+ id: dom.getPositionerId(state.context),
295
+ "data-part": "positioner",
296
+ style: popperStyles.floating
297
+ }),
298
+ contentProps: normalize.element({
299
+ "data-part": "content",
300
+ id: dom.getContentId(state.context),
301
+ tabIndex: -1,
302
+ role: "dialog",
303
+ hidden: !isOpen,
304
+ "data-expanded": dataAttr(isOpen),
305
+ "aria-labelledby": rendered.title ? dom.getTitleId(state.context) : void 0,
306
+ "aria-describedby": rendered.description ? dom.getDescriptionId(state.context) : void 0,
307
+ "data-placement": currentPlacement
308
+ }),
309
+ titleProps: normalize.element({
310
+ "data-part": "title",
311
+ id: dom.getTitleId(state.context)
312
+ }),
313
+ descriptionProps: normalize.element({
314
+ "data-part": "description",
315
+ id: dom.getDescriptionId(state.context)
316
+ }),
317
+ closeButtonProps: normalize.button({
318
+ "data-part": "close-button",
319
+ id: dom.getCloseButtonId(state.context),
320
+ type: "button",
321
+ "aria-label": "close",
322
+ onClick() {
323
+ send("REQUEST_CLOSE");
324
+ }
325
+ })
326
+ };
327
+ }
328
+
329
+ // src/popover.machine.ts
330
+ var import_aria_hidden = require("@zag-js/aria-hidden");
331
+ var import_core = require("@zag-js/core");
332
+ var import_dismissable = require("@zag-js/dismissable");
333
+ var import_popper2 = require("@zag-js/popper");
334
+ var import_remove_scroll = require("@zag-js/remove-scroll");
335
+ var import_focus_trap = require("focus-trap");
336
+ var { and, or, not } = import_core.guards;
337
+ function machine(ctx) {
338
+ return (0, import_core.createMachine)(
339
+ {
340
+ id: "popover",
341
+ initial: "unknown",
342
+ context: {
343
+ closeOnInteractOutside: true,
344
+ closeOnEsc: true,
345
+ autoFocus: true,
346
+ modal: false,
347
+ positioning: {
348
+ placement: "bottom",
349
+ ...ctx.positioning
350
+ },
351
+ currentPlacement: void 0,
352
+ ...ctx,
353
+ focusTriggerOnClose: true,
354
+ renderedElements: {
355
+ title: true,
356
+ description: true,
357
+ anchor: false
358
+ }
359
+ },
360
+ computed: {
361
+ currentPortalled: (ctx2) => !!ctx2.modal || !!ctx2.portalled
362
+ },
363
+ states: {
364
+ unknown: {
365
+ on: {
366
+ SETUP: {
367
+ target: ctx.defaultOpen ? "open" : "closed",
368
+ actions: "checkRenderedElements"
369
+ }
370
+ }
371
+ },
372
+ closed: {
373
+ entry: "invokeOnClose",
374
+ on: {
375
+ TOGGLE: "open",
376
+ OPEN: "open"
377
+ }
378
+ },
379
+ open: {
380
+ activities: [
381
+ "trapFocus",
382
+ "preventScroll",
383
+ "hideContentBelow",
384
+ "computePlacement",
385
+ "trackInteractionOutside",
386
+ "trackTabKeyDown"
387
+ ],
388
+ entry: ["setInitialFocus", "invokeOnOpen"],
389
+ on: {
390
+ CLOSE: "closed",
391
+ REQUEST_CLOSE: {
392
+ target: "closed",
393
+ actions: "focusTriggerIfNeeded"
394
+ },
395
+ TOGGLE: "closed",
396
+ TRIGGER_BLUR: {
397
+ guard: not("isRelatedTargetWithinContent"),
398
+ target: "closed"
399
+ },
400
+ TAB: [
401
+ {
402
+ guard: and("isTriggerFocused", "portalled"),
403
+ actions: "focusFirstTabbableElement"
404
+ },
405
+ {
406
+ guard: and("isLastTabbableElement", "closeOnInteractOutside", "portalled"),
407
+ target: "closed",
408
+ actions: "focusNextTabbableElementAfterTrigger"
409
+ }
410
+ ],
411
+ SHIFT_TAB: {
412
+ guard: and(or("isFirstTabbableElement", "isContentFocused"), "portalled"),
413
+ actions: "focusTriggerIfNeeded"
414
+ }
415
+ }
416
+ }
417
+ }
418
+ },
419
+ {
420
+ activities: {
421
+ computePlacement(ctx2) {
422
+ ctx2.currentPlacement = ctx2.positioning.placement;
423
+ const anchorEl = ctx2.renderedElements.anchor ? dom.getAnchorEl(ctx2) : dom.getTriggerEl(ctx2);
424
+ return (0, import_popper2.getPlacement)(anchorEl, dom.getPositionerEl(ctx2), {
425
+ ...ctx2.positioning,
426
+ onComplete(data) {
427
+ ctx2.currentPlacement = data.placement;
428
+ ctx2.isPlacementComplete = true;
429
+ },
430
+ onCleanup() {
431
+ ctx2.currentPlacement = void 0;
432
+ ctx2.isPlacementComplete = false;
433
+ }
434
+ });
435
+ },
436
+ trackInteractionOutside(ctx2, _evt, { send }) {
437
+ return (0, import_dismissable.trackDismissableElement)(dom.getContentEl(ctx2), {
438
+ pointerBlocking: ctx2.modal,
439
+ exclude: dom.getTriggerEl(ctx2),
440
+ onEscapeKeyDown(event) {
441
+ var _a;
442
+ (_a = ctx2.onEscapeKeyDown) == null ? void 0 : _a.call(ctx2, event);
443
+ if (ctx2.closeOnEsc)
444
+ return;
445
+ ctx2.focusTriggerOnClose = true;
446
+ event.preventDefault();
447
+ },
448
+ onInteractOutside(event) {
449
+ var _a;
450
+ (_a = ctx2.onInteractOutside) == null ? void 0 : _a.call(ctx2, event);
451
+ if (event.defaultPrevented)
452
+ return;
453
+ ctx2.focusTriggerOnClose = !(event.detail.focusable || event.detail.contextmenu);
454
+ if (!ctx2.closeOnInteractOutside) {
455
+ event.preventDefault();
456
+ }
457
+ },
458
+ onPointerDownOutside(event) {
459
+ var _a;
460
+ (_a = ctx2.onPointerDownOutside) == null ? void 0 : _a.call(ctx2, event);
461
+ },
462
+ onFocusOutside(event) {
463
+ var _a;
464
+ (_a = ctx2.onFocusOutside) == null ? void 0 : _a.call(ctx2, event);
465
+ if (ctx2.currentPortalled) {
466
+ event.preventDefault();
467
+ }
468
+ },
469
+ onDismiss() {
470
+ send({ type: "REQUEST_CLOSE", src: "#interact-outside" });
471
+ }
472
+ });
473
+ },
474
+ trackTabKeyDown(ctx2, _evt, { send }) {
475
+ if (ctx2.modal)
476
+ return;
477
+ return addDomEvent(
478
+ dom.getWin(ctx2),
479
+ "keydown",
480
+ (event) => {
481
+ const isTabKey = event.key === "Tab" && !isModifiedEvent(event);
482
+ if (!isTabKey)
483
+ return;
484
+ send({
485
+ type: event.shiftKey ? "SHIFT_TAB" : "TAB",
486
+ preventDefault: () => event.preventDefault()
487
+ });
488
+ },
489
+ true
490
+ );
491
+ },
492
+ hideContentBelow(ctx2) {
493
+ if (!ctx2.modal)
494
+ return;
495
+ let cleanup;
496
+ nextTick(() => {
497
+ cleanup = (0, import_aria_hidden.ariaHidden)([dom.getContentEl(ctx2), dom.getTriggerEl(ctx2)]);
498
+ });
499
+ return () => cleanup == null ? void 0 : cleanup();
500
+ },
501
+ preventScroll(ctx2) {
502
+ if (!ctx2.modal)
503
+ return;
504
+ return (0, import_remove_scroll.preventBodyScroll)(dom.getDoc(ctx2));
505
+ },
506
+ trapFocus(ctx2) {
507
+ if (!ctx2.modal)
508
+ return;
509
+ let trap;
510
+ nextTick(() => {
511
+ const el = dom.getContentEl(ctx2);
512
+ if (!el)
513
+ return;
514
+ trap = (0, import_focus_trap.createFocusTrap)(el, {
515
+ escapeDeactivates: false,
516
+ allowOutsideClick: true,
517
+ returnFocusOnDeactivate: true,
518
+ document: dom.getDoc(ctx2),
519
+ fallbackFocus: el,
520
+ initialFocus: runIfFn2(ctx2.initialFocusEl)
521
+ });
522
+ try {
523
+ trap.activate();
524
+ } catch {
525
+ }
526
+ });
527
+ return () => trap == null ? void 0 : trap.deactivate();
528
+ }
529
+ },
530
+ guards: {
531
+ portalled: (ctx2) => ctx2.currentPortalled,
532
+ isRelatedTargetWithinContent: (ctx2, evt) => contains(dom.getContentEl(ctx2), evt.target),
533
+ closeOnInteractOutside: (ctx2) => !!ctx2.closeOnInteractOutside,
534
+ isContentFocused: (ctx2) => dom.getContentEl(ctx2) === dom.getActiveEl(ctx2),
535
+ isTriggerFocused: (ctx2) => dom.getTriggerEl(ctx2) === dom.getActiveEl(ctx2),
536
+ isFirstTabbableElement: (ctx2) => dom.getFirstTabbableEl(ctx2) === dom.getActiveEl(ctx2),
537
+ isLastTabbableElement: (ctx2) => dom.getLastTabbableEl(ctx2) === dom.getActiveEl(ctx2)
538
+ },
539
+ actions: {
540
+ checkRenderedElements(ctx2) {
541
+ raf(() => {
542
+ Object.assign(ctx2.renderedElements, {
543
+ title: !!dom.getTitleEl(ctx2),
544
+ description: !!dom.getDescriptionEl(ctx2),
545
+ anchor: !!dom.getAnchorEl(ctx2)
546
+ });
547
+ });
548
+ },
549
+ setInitialFocus(ctx2) {
550
+ raf(() => {
551
+ var _a;
552
+ (_a = dom.getInitialFocusEl(ctx2)) == null ? void 0 : _a.focus();
553
+ });
554
+ },
555
+ focusTriggerIfNeeded(ctx2) {
556
+ if (!ctx2.focusTriggerOnClose)
557
+ return;
558
+ raf(() => {
559
+ var _a;
560
+ return (_a = dom.getTriggerEl(ctx2)) == null ? void 0 : _a.focus();
561
+ });
562
+ },
563
+ focusFirstTabbableElement(ctx2, evt) {
564
+ var _a;
565
+ evt.preventDefault();
566
+ (_a = dom.getFirstTabbableEl(ctx2)) == null ? void 0 : _a.focus();
567
+ },
568
+ invokeOnOpen(ctx2, evt) {
569
+ var _a;
570
+ if (evt.type !== "SETUP") {
571
+ (_a = ctx2.onOpenChange) == null ? void 0 : _a.call(ctx2, true);
572
+ }
573
+ },
574
+ invokeOnClose(ctx2, evt) {
575
+ var _a;
576
+ if (evt.type !== "SETUP") {
577
+ (_a = ctx2.onOpenChange) == null ? void 0 : _a.call(ctx2, false);
578
+ }
579
+ },
580
+ focusNextTabbableElementAfterTrigger(ctx2, evt) {
581
+ const content = dom.getContentEl(ctx2);
582
+ const button = dom.getTriggerEl(ctx2);
583
+ if (!content || !button)
584
+ return;
585
+ const lastTabbable = dom.getLastTabbableEl(ctx2);
586
+ if (lastTabbable !== dom.getActiveEl(ctx2))
587
+ return;
588
+ let tabbables = dom.getDocTabbableEls(ctx2);
589
+ let elementAfterTrigger = next(tabbables, tabbables.indexOf(button), { loop: false });
590
+ if (elementAfterTrigger === content) {
591
+ tabbables = tabbables.filter((el) => !contains(content, el));
592
+ elementAfterTrigger = next(tabbables, tabbables.indexOf(button), { loop: false });
593
+ }
594
+ if (!elementAfterTrigger || elementAfterTrigger === button)
595
+ return;
596
+ evt.preventDefault();
597
+ raf(() => elementAfterTrigger == null ? void 0 : elementAfterTrigger.focus());
598
+ }
599
+ }
600
+ }
601
+ );
602
+ }
603
+ // Annotate the CommonJS export names for ESM import in node:
604
+ 0 && (module.exports = {
605
+ connect,
606
+ machine
607
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,579 @@
1
+ // ../../utilities/dom/dist/index.mjs
2
+ var dataAttr = (guard) => {
3
+ return guard ? "" : void 0;
4
+ };
5
+ var runIfFn = (v, ...a) => {
6
+ const res = typeof v === "function" ? v(...a) : v;
7
+ return res ?? void 0;
8
+ };
9
+ var hasProp = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
10
+ function isDocument(el) {
11
+ return el.nodeType === Node.DOCUMENT_NODE;
12
+ }
13
+ function isWindow(value) {
14
+ return (value == null ? void 0 : value.toString()) === "[object Window]";
15
+ }
16
+ function isFrame(element) {
17
+ return element.localName === "iframe";
18
+ }
19
+ function getDocument(el) {
20
+ if (isWindow(el))
21
+ return el.document;
22
+ if (isDocument(el))
23
+ return el;
24
+ return (el == null ? void 0 : el.ownerDocument) ?? document;
25
+ }
26
+ function defineDomHelpers(helpers) {
27
+ const dom2 = {
28
+ getRootNode: (ctx) => {
29
+ var _a;
30
+ return ((_a = ctx.getRootNode) == null ? void 0 : _a.call(ctx)) ?? document;
31
+ },
32
+ getDoc: (ctx) => getDocument(dom2.getRootNode(ctx)),
33
+ getWin: (ctx) => dom2.getDoc(ctx).defaultView ?? window,
34
+ getActiveElement: (ctx) => dom2.getDoc(ctx).activeElement,
35
+ getById: (ctx, id) => dom2.getRootNode(ctx).getElementById(id)
36
+ };
37
+ return {
38
+ ...dom2,
39
+ ...helpers
40
+ };
41
+ }
42
+ function contains(parent, child) {
43
+ if (!parent)
44
+ return false;
45
+ return parent === child || isHTMLElement(parent) && isHTMLElement(child) && parent.contains(child);
46
+ }
47
+ function isHTMLElement(v) {
48
+ return typeof v === "object" && (v == null ? void 0 : v.nodeType) === Node.ELEMENT_NODE && typeof (v == null ? void 0 : v.nodeName) === "string";
49
+ }
50
+ function isVisible(el) {
51
+ if (!isHTMLElement(el))
52
+ return false;
53
+ return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
54
+ }
55
+ var isModifiedEvent = (v) => v.ctrlKey || v.altKey || v.metaKey;
56
+ function hasNegativeTabIndex(element) {
57
+ const tabIndex = parseInt(element.getAttribute("tabindex") || "0", 10);
58
+ return tabIndex < 0;
59
+ }
60
+ var focusableSelector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false']), details > summary:first-of-type";
61
+ var getFocusables = (container, includeContainer = false) => {
62
+ if (!container)
63
+ return [];
64
+ const elements = Array.from(container.querySelectorAll(focusableSelector));
65
+ const include = includeContainer == true || includeContainer == "if-empty" && elements.length === 0;
66
+ if (include && isHTMLElement(container) && isFocusable(container)) {
67
+ elements.unshift(container);
68
+ }
69
+ const focusableElements = elements.filter(isFocusable);
70
+ focusableElements.forEach((element, i) => {
71
+ if (isFrame(element) && element.contentDocument) {
72
+ const frameBody = element.contentDocument.body;
73
+ focusableElements.splice(i, 1, ...getFocusables(frameBody));
74
+ }
75
+ });
76
+ return focusableElements;
77
+ };
78
+ function isFocusable(element) {
79
+ if (!element)
80
+ return false;
81
+ return element.matches(focusableSelector) && isVisible(element);
82
+ }
83
+ function getTabbables(container, includeContainer) {
84
+ if (!container)
85
+ return [];
86
+ const elements = Array.from(container.querySelectorAll(focusableSelector));
87
+ const tabbableElements = elements.filter(isTabbable);
88
+ if (includeContainer && isTabbable(container)) {
89
+ tabbableElements.unshift(container);
90
+ }
91
+ tabbableElements.forEach((element, i) => {
92
+ if (isFrame(element) && element.contentDocument) {
93
+ const frameBody = element.contentDocument.body;
94
+ const allFrameTabbable = getTabbables(frameBody);
95
+ tabbableElements.splice(i, 1, ...allFrameTabbable);
96
+ }
97
+ });
98
+ if (!tabbableElements.length && includeContainer) {
99
+ return elements;
100
+ }
101
+ return tabbableElements;
102
+ }
103
+ function isTabbable(el) {
104
+ return isFocusable(el) && !hasNegativeTabIndex(el);
105
+ }
106
+ function getFirstTabbable(container, includeContainer) {
107
+ const [first] = getTabbables(container, includeContainer);
108
+ return first || null;
109
+ }
110
+ function getLastTabbable(container, includeContainer) {
111
+ const elements = getTabbables(container, includeContainer);
112
+ return elements[elements.length - 1] || null;
113
+ }
114
+ var isRef = (v) => hasProp(v, "current");
115
+ function addDomEvent(target, eventName, handler, options) {
116
+ const node = isRef(target) ? target.current : runIfFn(target);
117
+ node == null ? void 0 : node.addEventListener(eventName, handler, options);
118
+ return () => {
119
+ node == null ? void 0 : node.removeEventListener(eventName, handler, options);
120
+ };
121
+ }
122
+ function nextTick(fn) {
123
+ const set = /* @__PURE__ */ new Set();
124
+ function raf2(fn2) {
125
+ const id = globalThis.requestAnimationFrame(fn2);
126
+ set.add(() => globalThis.cancelAnimationFrame(id));
127
+ }
128
+ raf2(() => raf2(fn));
129
+ return function cleanup() {
130
+ set.forEach(function(fn2) {
131
+ fn2();
132
+ });
133
+ };
134
+ }
135
+ function raf(fn) {
136
+ const id = globalThis.requestAnimationFrame(fn);
137
+ return function cleanup() {
138
+ globalThis.cancelAnimationFrame(id);
139
+ };
140
+ }
141
+
142
+ // src/popover.connect.ts
143
+ import { getPlacementStyles } from "@zag-js/popper";
144
+
145
+ // ../../utilities/core/dist/index.mjs
146
+ function nextIndex(v, idx, opts = {}) {
147
+ const { step = 1, loop = true } = opts;
148
+ const next2 = idx + step;
149
+ const len = v.length;
150
+ const last2 = len - 1;
151
+ if (idx === -1)
152
+ return step > 0 ? 0 : last2;
153
+ if (next2 < 0)
154
+ return loop ? last2 : 0;
155
+ if (next2 >= len)
156
+ return loop ? 0 : idx > len ? len : idx;
157
+ return next2;
158
+ }
159
+ function next(v, idx, opts = {}) {
160
+ return v[nextIndex(v, idx, opts)];
161
+ }
162
+ var runIfFn2 = (v, ...a) => {
163
+ const res = typeof v === "function" ? v(...a) : v;
164
+ return res ?? void 0;
165
+ };
166
+
167
+ // src/popover.dom.ts
168
+ var dom = defineDomHelpers({
169
+ getActiveEl: (ctx) => dom.getDoc(ctx).activeElement,
170
+ getAnchorId: (ctx) => {
171
+ var _a;
172
+ return ((_a = ctx.ids) == null ? void 0 : _a.anchor) ?? `popover:${ctx.id}:anchor`;
173
+ },
174
+ getTriggerId: (ctx) => {
175
+ var _a;
176
+ return ((_a = ctx.ids) == null ? void 0 : _a.trigger) ?? `popover:${ctx.id}:trigger`;
177
+ },
178
+ getContentId: (ctx) => {
179
+ var _a;
180
+ return ((_a = ctx.ids) == null ? void 0 : _a.content) ?? `popover:${ctx.id}:content`;
181
+ },
182
+ getPositionerId: (ctx) => `popover:${ctx.id}:popper`,
183
+ getArrowId: (ctx) => `popover:${ctx.id}:arrow`,
184
+ getTitleId: (ctx) => {
185
+ var _a;
186
+ return ((_a = ctx.ids) == null ? void 0 : _a.title) ?? `popover:${ctx.id}:title`;
187
+ },
188
+ getDescriptionId: (ctx) => {
189
+ var _a;
190
+ return ((_a = ctx.ids) == null ? void 0 : _a.description) ?? `popover:${ctx.id}:desc`;
191
+ },
192
+ getCloseButtonId: (ctx) => {
193
+ var _a;
194
+ return ((_a = ctx.ids) == null ? void 0 : _a.closeBtn) ?? `popover:${ctx.id}:close-button`;
195
+ },
196
+ getAnchorEl: (ctx) => dom.getById(ctx, dom.getAnchorId(ctx)),
197
+ getTriggerEl: (ctx) => dom.getById(ctx, dom.getTriggerId(ctx)),
198
+ getContentEl: (ctx) => dom.getById(ctx, dom.getContentId(ctx)),
199
+ getPositionerEl: (ctx) => dom.getById(ctx, dom.getPositionerId(ctx)),
200
+ getTitleEl: (ctx) => dom.getById(ctx, dom.getTitleId(ctx)),
201
+ getDescriptionEl: (ctx) => dom.getById(ctx, dom.getDescriptionId(ctx)),
202
+ getFocusableEls: (ctx) => getFocusables(dom.getContentEl(ctx)),
203
+ getFirstFocusableEl: (ctx) => dom.getFocusableEls(ctx)[0],
204
+ getDocTabbableEls: (ctx) => getTabbables(dom.getDoc(ctx).body),
205
+ getTabbableEls: (ctx) => getTabbables(dom.getContentEl(ctx), "if-empty"),
206
+ getFirstTabbableEl: (ctx) => getFirstTabbable(dom.getContentEl(ctx), "if-empty"),
207
+ getLastTabbableEl: (ctx) => getLastTabbable(dom.getContentEl(ctx), "if-empty"),
208
+ getInitialFocusEl: (ctx) => {
209
+ let el = runIfFn2(ctx.initialFocusEl);
210
+ if (!el && ctx.autoFocus)
211
+ el = dom.getFirstFocusableEl(ctx);
212
+ if (!el)
213
+ el = dom.getContentEl(ctx);
214
+ return el;
215
+ }
216
+ });
217
+
218
+ // src/popover.connect.ts
219
+ function connect(state, send, normalize) {
220
+ const isOpen = state.matches("open");
221
+ const currentPlacement = state.context.currentPlacement;
222
+ const portalled = state.context.currentPortalled;
223
+ const rendered = state.context.renderedElements;
224
+ const popperStyles = getPlacementStyles({
225
+ measured: !!state.context.isPlacementComplete,
226
+ placement: currentPlacement
227
+ });
228
+ return {
229
+ portalled,
230
+ isOpen,
231
+ open() {
232
+ send("OPEN");
233
+ },
234
+ close() {
235
+ send("CLOSE");
236
+ },
237
+ arrowProps: normalize.element({
238
+ id: dom.getArrowId(state.context),
239
+ "data-part": "arrow",
240
+ style: popperStyles.arrow
241
+ }),
242
+ innerArrowProps: normalize.element({
243
+ "data-part": "arrow-inner",
244
+ style: popperStyles.innerArrow
245
+ }),
246
+ anchorProps: normalize.element({
247
+ "data-part": "anchor",
248
+ id: dom.getAnchorId(state.context)
249
+ }),
250
+ triggerProps: normalize.button({
251
+ "data-part": "trigger",
252
+ type: "button",
253
+ "data-placement": currentPlacement,
254
+ id: dom.getTriggerId(state.context),
255
+ "aria-haspopup": "dialog",
256
+ "aria-expanded": isOpen,
257
+ "data-expanded": dataAttr(isOpen),
258
+ "aria-controls": dom.getContentId(state.context),
259
+ onClick() {
260
+ send("TOGGLE");
261
+ },
262
+ onBlur(event) {
263
+ send({ type: "TRIGGER_BLUR", target: event.relatedTarget });
264
+ }
265
+ }),
266
+ positionerProps: normalize.element({
267
+ id: dom.getPositionerId(state.context),
268
+ "data-part": "positioner",
269
+ style: popperStyles.floating
270
+ }),
271
+ contentProps: normalize.element({
272
+ "data-part": "content",
273
+ id: dom.getContentId(state.context),
274
+ tabIndex: -1,
275
+ role: "dialog",
276
+ hidden: !isOpen,
277
+ "data-expanded": dataAttr(isOpen),
278
+ "aria-labelledby": rendered.title ? dom.getTitleId(state.context) : void 0,
279
+ "aria-describedby": rendered.description ? dom.getDescriptionId(state.context) : void 0,
280
+ "data-placement": currentPlacement
281
+ }),
282
+ titleProps: normalize.element({
283
+ "data-part": "title",
284
+ id: dom.getTitleId(state.context)
285
+ }),
286
+ descriptionProps: normalize.element({
287
+ "data-part": "description",
288
+ id: dom.getDescriptionId(state.context)
289
+ }),
290
+ closeButtonProps: normalize.button({
291
+ "data-part": "close-button",
292
+ id: dom.getCloseButtonId(state.context),
293
+ type: "button",
294
+ "aria-label": "close",
295
+ onClick() {
296
+ send("REQUEST_CLOSE");
297
+ }
298
+ })
299
+ };
300
+ }
301
+
302
+ // src/popover.machine.ts
303
+ import { ariaHidden } from "@zag-js/aria-hidden";
304
+ import { createMachine, guards } from "@zag-js/core";
305
+ import { trackDismissableElement } from "@zag-js/dismissable";
306
+ import { getPlacement } from "@zag-js/popper";
307
+ import { preventBodyScroll } from "@zag-js/remove-scroll";
308
+ import { createFocusTrap } from "focus-trap";
309
+ var { and, or, not } = guards;
310
+ function machine(ctx) {
311
+ return createMachine(
312
+ {
313
+ id: "popover",
314
+ initial: "unknown",
315
+ context: {
316
+ closeOnInteractOutside: true,
317
+ closeOnEsc: true,
318
+ autoFocus: true,
319
+ modal: false,
320
+ positioning: {
321
+ placement: "bottom",
322
+ ...ctx.positioning
323
+ },
324
+ currentPlacement: void 0,
325
+ ...ctx,
326
+ focusTriggerOnClose: true,
327
+ renderedElements: {
328
+ title: true,
329
+ description: true,
330
+ anchor: false
331
+ }
332
+ },
333
+ computed: {
334
+ currentPortalled: (ctx2) => !!ctx2.modal || !!ctx2.portalled
335
+ },
336
+ states: {
337
+ unknown: {
338
+ on: {
339
+ SETUP: {
340
+ target: ctx.defaultOpen ? "open" : "closed",
341
+ actions: "checkRenderedElements"
342
+ }
343
+ }
344
+ },
345
+ closed: {
346
+ entry: "invokeOnClose",
347
+ on: {
348
+ TOGGLE: "open",
349
+ OPEN: "open"
350
+ }
351
+ },
352
+ open: {
353
+ activities: [
354
+ "trapFocus",
355
+ "preventScroll",
356
+ "hideContentBelow",
357
+ "computePlacement",
358
+ "trackInteractionOutside",
359
+ "trackTabKeyDown"
360
+ ],
361
+ entry: ["setInitialFocus", "invokeOnOpen"],
362
+ on: {
363
+ CLOSE: "closed",
364
+ REQUEST_CLOSE: {
365
+ target: "closed",
366
+ actions: "focusTriggerIfNeeded"
367
+ },
368
+ TOGGLE: "closed",
369
+ TRIGGER_BLUR: {
370
+ guard: not("isRelatedTargetWithinContent"),
371
+ target: "closed"
372
+ },
373
+ TAB: [
374
+ {
375
+ guard: and("isTriggerFocused", "portalled"),
376
+ actions: "focusFirstTabbableElement"
377
+ },
378
+ {
379
+ guard: and("isLastTabbableElement", "closeOnInteractOutside", "portalled"),
380
+ target: "closed",
381
+ actions: "focusNextTabbableElementAfterTrigger"
382
+ }
383
+ ],
384
+ SHIFT_TAB: {
385
+ guard: and(or("isFirstTabbableElement", "isContentFocused"), "portalled"),
386
+ actions: "focusTriggerIfNeeded"
387
+ }
388
+ }
389
+ }
390
+ }
391
+ },
392
+ {
393
+ activities: {
394
+ computePlacement(ctx2) {
395
+ ctx2.currentPlacement = ctx2.positioning.placement;
396
+ const anchorEl = ctx2.renderedElements.anchor ? dom.getAnchorEl(ctx2) : dom.getTriggerEl(ctx2);
397
+ return getPlacement(anchorEl, dom.getPositionerEl(ctx2), {
398
+ ...ctx2.positioning,
399
+ onComplete(data) {
400
+ ctx2.currentPlacement = data.placement;
401
+ ctx2.isPlacementComplete = true;
402
+ },
403
+ onCleanup() {
404
+ ctx2.currentPlacement = void 0;
405
+ ctx2.isPlacementComplete = false;
406
+ }
407
+ });
408
+ },
409
+ trackInteractionOutside(ctx2, _evt, { send }) {
410
+ return trackDismissableElement(dom.getContentEl(ctx2), {
411
+ pointerBlocking: ctx2.modal,
412
+ exclude: dom.getTriggerEl(ctx2),
413
+ onEscapeKeyDown(event) {
414
+ var _a;
415
+ (_a = ctx2.onEscapeKeyDown) == null ? void 0 : _a.call(ctx2, event);
416
+ if (ctx2.closeOnEsc)
417
+ return;
418
+ ctx2.focusTriggerOnClose = true;
419
+ event.preventDefault();
420
+ },
421
+ onInteractOutside(event) {
422
+ var _a;
423
+ (_a = ctx2.onInteractOutside) == null ? void 0 : _a.call(ctx2, event);
424
+ if (event.defaultPrevented)
425
+ return;
426
+ ctx2.focusTriggerOnClose = !(event.detail.focusable || event.detail.contextmenu);
427
+ if (!ctx2.closeOnInteractOutside) {
428
+ event.preventDefault();
429
+ }
430
+ },
431
+ onPointerDownOutside(event) {
432
+ var _a;
433
+ (_a = ctx2.onPointerDownOutside) == null ? void 0 : _a.call(ctx2, event);
434
+ },
435
+ onFocusOutside(event) {
436
+ var _a;
437
+ (_a = ctx2.onFocusOutside) == null ? void 0 : _a.call(ctx2, event);
438
+ if (ctx2.currentPortalled) {
439
+ event.preventDefault();
440
+ }
441
+ },
442
+ onDismiss() {
443
+ send({ type: "REQUEST_CLOSE", src: "#interact-outside" });
444
+ }
445
+ });
446
+ },
447
+ trackTabKeyDown(ctx2, _evt, { send }) {
448
+ if (ctx2.modal)
449
+ return;
450
+ return addDomEvent(
451
+ dom.getWin(ctx2),
452
+ "keydown",
453
+ (event) => {
454
+ const isTabKey = event.key === "Tab" && !isModifiedEvent(event);
455
+ if (!isTabKey)
456
+ return;
457
+ send({
458
+ type: event.shiftKey ? "SHIFT_TAB" : "TAB",
459
+ preventDefault: () => event.preventDefault()
460
+ });
461
+ },
462
+ true
463
+ );
464
+ },
465
+ hideContentBelow(ctx2) {
466
+ if (!ctx2.modal)
467
+ return;
468
+ let cleanup;
469
+ nextTick(() => {
470
+ cleanup = ariaHidden([dom.getContentEl(ctx2), dom.getTriggerEl(ctx2)]);
471
+ });
472
+ return () => cleanup == null ? void 0 : cleanup();
473
+ },
474
+ preventScroll(ctx2) {
475
+ if (!ctx2.modal)
476
+ return;
477
+ return preventBodyScroll(dom.getDoc(ctx2));
478
+ },
479
+ trapFocus(ctx2) {
480
+ if (!ctx2.modal)
481
+ return;
482
+ let trap;
483
+ nextTick(() => {
484
+ const el = dom.getContentEl(ctx2);
485
+ if (!el)
486
+ return;
487
+ trap = createFocusTrap(el, {
488
+ escapeDeactivates: false,
489
+ allowOutsideClick: true,
490
+ returnFocusOnDeactivate: true,
491
+ document: dom.getDoc(ctx2),
492
+ fallbackFocus: el,
493
+ initialFocus: runIfFn2(ctx2.initialFocusEl)
494
+ });
495
+ try {
496
+ trap.activate();
497
+ } catch {
498
+ }
499
+ });
500
+ return () => trap == null ? void 0 : trap.deactivate();
501
+ }
502
+ },
503
+ guards: {
504
+ portalled: (ctx2) => ctx2.currentPortalled,
505
+ isRelatedTargetWithinContent: (ctx2, evt) => contains(dom.getContentEl(ctx2), evt.target),
506
+ closeOnInteractOutside: (ctx2) => !!ctx2.closeOnInteractOutside,
507
+ isContentFocused: (ctx2) => dom.getContentEl(ctx2) === dom.getActiveEl(ctx2),
508
+ isTriggerFocused: (ctx2) => dom.getTriggerEl(ctx2) === dom.getActiveEl(ctx2),
509
+ isFirstTabbableElement: (ctx2) => dom.getFirstTabbableEl(ctx2) === dom.getActiveEl(ctx2),
510
+ isLastTabbableElement: (ctx2) => dom.getLastTabbableEl(ctx2) === dom.getActiveEl(ctx2)
511
+ },
512
+ actions: {
513
+ checkRenderedElements(ctx2) {
514
+ raf(() => {
515
+ Object.assign(ctx2.renderedElements, {
516
+ title: !!dom.getTitleEl(ctx2),
517
+ description: !!dom.getDescriptionEl(ctx2),
518
+ anchor: !!dom.getAnchorEl(ctx2)
519
+ });
520
+ });
521
+ },
522
+ setInitialFocus(ctx2) {
523
+ raf(() => {
524
+ var _a;
525
+ (_a = dom.getInitialFocusEl(ctx2)) == null ? void 0 : _a.focus();
526
+ });
527
+ },
528
+ focusTriggerIfNeeded(ctx2) {
529
+ if (!ctx2.focusTriggerOnClose)
530
+ return;
531
+ raf(() => {
532
+ var _a;
533
+ return (_a = dom.getTriggerEl(ctx2)) == null ? void 0 : _a.focus();
534
+ });
535
+ },
536
+ focusFirstTabbableElement(ctx2, evt) {
537
+ var _a;
538
+ evt.preventDefault();
539
+ (_a = dom.getFirstTabbableEl(ctx2)) == null ? void 0 : _a.focus();
540
+ },
541
+ invokeOnOpen(ctx2, evt) {
542
+ var _a;
543
+ if (evt.type !== "SETUP") {
544
+ (_a = ctx2.onOpenChange) == null ? void 0 : _a.call(ctx2, true);
545
+ }
546
+ },
547
+ invokeOnClose(ctx2, evt) {
548
+ var _a;
549
+ if (evt.type !== "SETUP") {
550
+ (_a = ctx2.onOpenChange) == null ? void 0 : _a.call(ctx2, false);
551
+ }
552
+ },
553
+ focusNextTabbableElementAfterTrigger(ctx2, evt) {
554
+ const content = dom.getContentEl(ctx2);
555
+ const button = dom.getTriggerEl(ctx2);
556
+ if (!content || !button)
557
+ return;
558
+ const lastTabbable = dom.getLastTabbableEl(ctx2);
559
+ if (lastTabbable !== dom.getActiveEl(ctx2))
560
+ return;
561
+ let tabbables = dom.getDocTabbableEls(ctx2);
562
+ let elementAfterTrigger = next(tabbables, tabbables.indexOf(button), { loop: false });
563
+ if (elementAfterTrigger === content) {
564
+ tabbables = tabbables.filter((el) => !contains(content, el));
565
+ elementAfterTrigger = next(tabbables, tabbables.indexOf(button), { loop: false });
566
+ }
567
+ if (!elementAfterTrigger || elementAfterTrigger === button)
568
+ return;
569
+ evt.preventDefault();
570
+ raf(() => elementAfterTrigger == null ? void 0 : elementAfterTrigger.focus());
571
+ }
572
+ }
573
+ }
574
+ );
575
+ }
576
+ export {
577
+ connect,
578
+ machine
579
+ };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@zag-js/popover",
3
+ "version": "0.0.0-20220802150625",
4
+ "description": "Core logic for the popover widget implemented as a state machine",
5
+ "keywords": [
6
+ "js",
7
+ "machine",
8
+ "xstate",
9
+ "statechart",
10
+ "component",
11
+ "chakra-ui",
12
+ "popover"
13
+ ],
14
+ "author": "Segun Adebayo <sage@adebayosegun.com>",
15
+ "homepage": "https://github.com/chakra-ui/zag#readme",
16
+ "license": "MIT",
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "module": "dist/index.mjs",
20
+ "repository": "https://github.com/chakra-ui/zag/tree/main/packages/popover",
21
+ "sideEffects": false,
22
+ "files": [
23
+ "dist/**/*"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/chakra-ui/zag/issues"
30
+ },
31
+ "dependencies": {
32
+ "@zag-js/aria-hidden": "0.1.1",
33
+ "@zag-js/core": "0.1.9",
34
+ "@zag-js/dismissable": "0.1.3",
35
+ "@zag-js/popper": "0.0.0-20220802150625",
36
+ "@zag-js/remove-scroll": "0.1.3",
37
+ "@zag-js/types": "0.2.3",
38
+ "focus-trap": "6.9.4"
39
+ },
40
+ "devDependencies": {
41
+ "@zag-js/dom-utils": "0.1.8",
42
+ "@zag-js/utils": "0.1.3"
43
+ },
44
+ "scripts": {
45
+ "build-fast": "tsup src/index.ts --format=esm,cjs",
46
+ "start": "pnpm build --watch",
47
+ "build": "tsup src/index.ts --format=esm,cjs --dts",
48
+ "test": "jest --config ../../../jest.config.js --rootDir . --passWithNoTests",
49
+ "lint": "eslint src --ext .ts,.tsx",
50
+ "test-ci": "pnpm test --ci --runInBand",
51
+ "test-watch": "pnpm test --watch -u",
52
+ "typecheck": "tsc --noEmit"
53
+ }
54
+ }