@inertiaui/vanilla 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,6 +26,9 @@ npm install @inertiaui/vanilla
26
26
  - [Reorder](#reorder)
27
27
  - [Positioning](#positioning)
28
28
  - [Native Popovers](#native-popovers)
29
+ - [Tooltip Controllers](#tooltip-controllers)
30
+ - [Dialog Controllers](#dialog-controllers)
31
+ - [CSS Variable Inheritance](#css-variable-inheritance)
29
32
  - [Accessibility](#accessibility)
30
33
  - [Animation](#animation)
31
34
  - [Dark Mode Detection](#dark-mode-detection)
@@ -151,7 +154,7 @@ Elements with `aria-hidden="true"` are excluded. (Elements with `disabled` are a
151
154
 
152
155
  ### focusFirstEnabledElement
153
156
 
154
- Focuses the first non-disabled element in a list of candidates. Nullish values are ignored, and the function returns whether anything was focused.
157
+ Focuses the first non-disabled element in a list of candidates. Nullish values are ignored, and the function returns whether anything was focused. An optional second argument accepts native `FocusOptions`, including `{ preventScroll: true }`.
155
158
 
156
159
  ```typescript
157
160
  import { focusFirstEnabledElement } from '@inertiaui/vanilla'
@@ -282,6 +285,7 @@ cleanup()
282
285
  | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Arrow key direction |
283
286
  | `loop` | `boolean` | `true` | Wrap focus from last to first item |
284
287
  | `typeAhead` | `boolean` | `true` | Enable type-ahead character search |
288
+ | `initialFocus` | `'first' \| 'last'` | `'first'` | Initial enabled item to focus and give the active tab stop |
285
289
  | `onActivate` | `(item: HTMLElement) => void` | `undefined` | Called when an item is activated via Enter or Space |
286
290
 
287
291
  ### Keyboard Support
@@ -687,6 +691,75 @@ function setupTooltip(trigger: HTMLElement, tooltip: HTMLElement) {
687
691
 
688
692
  ## Native Popovers
689
693
 
694
+ ### Managed popovers and menus
695
+
696
+ `createPopoverController` composes the disclosure, positioning, dismissal, and menu helpers into a framework-independent lifecycle. It supports native auto popovers and a positioned fallback. The existing `createNativePopoverDisclosure` API below remains available for consumers that need to manage each step themselves.
697
+
698
+ ```html
699
+ <button id="trigger" aria-haspopup="menu" aria-expanded="false" aria-controls="menu">Actions</button>
700
+ <div id="menu" role="menu" hidden>
701
+ <button role="menuitem">Edit</button>
702
+ <button role="menuitem">Archive</button>
703
+ </div>
704
+ ```
705
+
706
+ ```typescript
707
+ import { createPopoverController } from '@inertiaui/vanilla'
708
+
709
+ const trigger = document.querySelector<HTMLElement>('#trigger')!
710
+ const menu = document.querySelector<HTMLElement>('#menu')!
711
+ const controller = createPopoverController({
712
+ reference: () => trigger,
713
+ popover: () => menu,
714
+ position: { placement: 'bottom-start', offset: 8 },
715
+ menu: true,
716
+ onOpenChange(open) {
717
+ trigger.setAttribute('aria-expanded', String(open))
718
+ menu.hidden = !open
719
+ if (open) queueMicrotask(() => controller.mount())
720
+ },
721
+ })
722
+
723
+ if (controller.native) menu.setAttribute('popover', 'auto')
724
+ trigger.addEventListener('pointerdown', controller.onPointerDown)
725
+ trigger.addEventListener('click', controller.toggle)
726
+ trigger.addEventListener('keydown', controller.onKeydown)
727
+ trigger.addEventListener('focusout', controller.onFocusOut)
728
+
729
+ // On disposal, also remove the four trigger listeners if the trigger remains in the DOM.
730
+ // The caller owns rendering and removing the panel.
731
+ controller.cleanup()
732
+ ```
733
+
734
+ In Vue, call `mount()` after the open panel has rendered with `nextTick()`. In React, call it from a layout effect and return `cleanup()` from that effect. Cleanup preserves logical open state so an effect can safely clean up and remount. It hides the native panel and removes the controller's listeners, timers, positioning observers, menu navigation, and mount-hook resources. Use `close()` for a state change and a close notification.
735
+
736
+ Keep native panels in their original DOM ancestry: the browser places them in the top layer without losing CSS inheritance. Fallback panels need a suitable DOM container; inside a modal dialog, keep them within that dialog. The controller does not move elements, assign classes, copy theme tokens, or animate. Set the panel's `role`, trigger ARIA attributes, and `popover="auto"` when `native` is true. Without `menu: true`, callers choose initial panel focus through `onOpened`.
737
+
738
+ | Option | Description |
739
+ |--------|-------------|
740
+ | `reference`, `popover` | Getters returning the current elements or `null` while unmounted |
741
+ | `position` | `TopLayerPopoverPositionOptions`; getters can supply current placement and offset |
742
+ | `menu` | Enables menu navigation, ArrowDown/ArrowUp opening, and closing after a menu-item click |
743
+ | `onOpenChange(open)` | Updates the framework's rendering state |
744
+ | `onMount({ reference, popover, native })` | Applies consumer behavior after positioning; may return a cleanup function |
745
+ | `onOpened()` | Runs after the panel is mounted and its handlers are installed |
746
+ | `onClosed()` | Runs when explicitly closed or dismissed; cleanup alone does not call it |
747
+
748
+ The controller resolves top/bottom `start` and `end` placement against the reference element's computed direction, including local RTL scopes. It follows scrolling and resizing, constrains panels to the viewport, restores trigger focus on Escape, and preserves focus when the user moves to another control. Menu clicks finish bubbling before dismissal, allowing framework-delegated item handlers to run. ArrowUp opens at the last enabled item with a matching roving tab stop.
749
+
750
+ | Controller member | Description |
751
+ |-------------------|-------------|
752
+ | `native`, `isOpen` | Read-only native support and current logical open state |
753
+ | `open()`, `close(restoreFocus?)` | Change open state; `close()` normally restores focus only when focus is inside the panel or on the body |
754
+ | `toggle(event?)` | Toggles state; pass the click event together with the pointerdown handler to avoid reopening after native light dismissal |
755
+ | `mount()` | Attaches behavior after rendering the open panel |
756
+ | `cleanup()` | Detaches behavior without changing logical open state |
757
+ | `onPointerDown`, `onKeydown`, `onFocusOut` | Handlers to bind to the trigger |
758
+
759
+ Consumer-specific theme or animation behavior can live in `onMount`. Return its cleanup so it also runs when a panel is dismissed, unmounted, or remounted. Use `prefersReducedMotion()` before starting consumer animations.
760
+
761
+ ### Low-level native disclosure
762
+
690
763
  `createNativePopoverDisclosure` coordinates open state, native `showPopover()`/`hidePopover()`, top-layer positioning, auto-updates, toggle-event sync, and optional focus-out dismissal.
691
764
 
692
765
  ```typescript
@@ -746,6 +819,69 @@ popover.addEventListener('focusout', (event) => {
746
819
  | `startAutoUpdate()` | Starts `autoUpdateTopLayerPopover` |
747
820
  | `cleanupPopover()` | Cleans focus-out and positioning listeners |
748
821
 
822
+ ## Tooltip Controllers
823
+
824
+ `createTooltipController(options)` coordinates hover and focus intent, delayed opening, positioning, Escape dismissal, and cleanup. It never moves focus. It keeps a tooltip open while either pointer or keyboard focus remains in its trigger, and ignores completion of an obsolete closing transition.
825
+
826
+ ```ts
827
+ import { createTooltipController } from '@inertiaui/vanilla'
828
+
829
+ const tooltip = createTooltipController({
830
+ reference: () => triggerElement,
831
+ tooltip: () => tooltipElement,
832
+ enabled: () => Boolean(text),
833
+ delay: () => delay,
834
+ position: { placement: 'top', offset: 6 },
835
+ onOpenChange: (open) => setVisible(open),
836
+ })
837
+ ```
838
+
839
+ Bind `onMouseEnter`, `onMouseLeave`, `onFocusIn`, and `onFocusOut` to the trigger. After rendering the tooltip, call `mount()`. Call `cleanup()` before removing its DOM or disposing its owner; call `hide()` to dismiss it. `isOpen` and `native` are readonly values, not framework reactive state. Bridge changes through `onOpenChange`.
840
+
841
+ Render native tooltips with `popover="manual"` and `role="tooltip"`, ideally within the trigger's DOM ancestry. For fallback tooltips, choose the portal destination yourself (inside any surrounding modal) and supply appropriate positioning/stacking styles. CSS width limits are preserved. Supply a stable tooltip ID and connect the trigger's `aria-describedby` while visible.
842
+
843
+ Optional `onMount({ reference, popover, native })` can return a cleanup callback. `transition(visible)` can return a promise; hiding waits for it. The consumer owns animation styles, cancellation, and reduced-motion policy. `cleanup()` cancels delayed opening and removes mounted behavior while preserving logical open state, so a framework can replay `mount()` safely.
844
+
845
+ ## Dialog Controllers
846
+
847
+ `createDialogController(options)` adds native modal behavior, or a focus-trapped fallback when `showModal` is unavailable. It balances scroll locks, restores focus, and restricts fallback Escape handling to the top dialog. The fallback marks siblings along the dialog ancestry inert, preserving accessibility of the dialog itself.
848
+
849
+ ```ts
850
+ import { createDialogController } from '@inertiaui/vanilla'
851
+
852
+ const dialog = createDialogController({
853
+ dialog: () => dialogElement,
854
+ panel: () => panelElement,
855
+ onOpenChange: (open) => setVisible(open),
856
+ onCancel: () => requestCancel(),
857
+ })
858
+
859
+ dialog.open()
860
+ // After rendering:
861
+ dialog.mount()
862
+ // Close and await any supplied transition:
863
+ await dialog.close()
864
+ ```
865
+
866
+ Use `<dialog>` when `native` is true. Otherwise render a container with `role="dialog"`, `aria-modal="true"`, a backdrop, and appropriate styles. Supply accessible labels in either case. The controller calls `onCancel` for Escape; the consumer decides whether to close, so controlled components can honor their existing cancellation contract.
867
+
868
+ `transition(visible)` and `onMount({ dialog, panel, native })` follow the same transition/cleanup contract as tooltips. Reopening during a closing transition keeps the dialog open. Call `cleanup()` before removing DOM or disposing the owner. It releases mounted behavior without changing logical `isOpen`, allowing framework effect replay. Call `close()` for an actual state change.
869
+
870
+ ## CSS Variable Inheritance
871
+
872
+ `inheritCssVariables(source, target, { filter, mediaQueries })` copies selected computed custom properties to a portal and returns a cleanup function. It watches ancestor class/style changes and the supplied media queries. Cleanup restores prior inline values and priorities when its own value is still present; consumer value overrides are preserved.
873
+
874
+ ```ts
875
+ import { inheritCssVariables } from '@inertiaui/vanilla'
876
+
877
+ const cleanup = inheritCssVariables(trigger, portal, {
878
+ filter: (name) => name.startsWith('--my-component-'),
879
+ mediaQueries: ['(prefers-color-scheme: dark)'],
880
+ })
881
+ ```
882
+
883
+ The helper is intentionally scoped to caller-selected variables. It does not observe stylesheet edits, arbitrary attribute selectors, or reparenting: remount it when the source ancestry changes. Native top-layer elements retain ordinary DOM inheritance and generally do not need this helper.
884
+
749
885
  ## Accessibility
750
886
 
751
887
  Accessibility utilities for managing `aria-hidden` attributes with reference counting support.
@@ -1086,7 +1222,9 @@ Create a timeout-based debouncer with an explicit millisecond delay. This is use
1086
1222
  ```typescript
1087
1223
  import { createDebouncer } from '@inertiaui/vanilla'
1088
1224
 
1089
- const debouncer = createDebouncer(250)
1225
+ // A number or a getter evaluated for each new schedule.
1226
+ let delay = 250
1227
+ const debouncer = createDebouncer(() => delay)
1090
1228
 
1091
1229
  input.addEventListener('input', () => {
1092
1230
  debouncer.schedule(() => {
@@ -1098,6 +1236,8 @@ input.addEventListener('input', () => {
1098
1236
  debouncer.cancel()
1099
1237
  ```
1100
1238
 
1239
+ `pending` is readonly and true only while a callback is scheduled. Both cancellation and callback dispatch clear it.
1240
+
1101
1241
  ### detectFramerate
1102
1242
 
1103
1243
  Detect the browser's current framerate. Returns a Promise that resolves with the detected FPS (capped to the 30–240 range). Falls back to 60 if `requestAnimationFrame` is unavailable or detection times out.
@@ -1587,6 +1727,9 @@ import type {
1587
1727
  ListboxNavigationOptions,
1588
1728
  ListboxNavigationResult,
1589
1729
  MenuNavigationOptions,
1730
+ PopoverController,
1731
+ PopoverControllerOptions,
1732
+ PopoverMountContext,
1590
1733
  NativePopoverCloseOptions,
1591
1734
  NativePopoverDisclosureController,
1592
1735
  NativePopoverDisclosureOptions,
package/dist/index.d.ts CHANGED
@@ -80,11 +80,14 @@ export declare type ColorFormat = 'hex' | 'rgb' | 'hsl';
80
80
  export declare function computePosition(reference: HTMLElement, floating: HTMLElement, options?: PositionOptions_2): PositionResult;
81
81
 
82
82
  /**
83
- * Create a {@link Debouncer} with a fixed delay.
83
+ * Create a {@link Debouncer} with a fixed delay or a getter read on each schedule.
84
84
  *
85
85
  * @param delay - Milliseconds to wait after the latest `schedule()` call.
86
86
  */
87
- export declare function createDebouncer(delay: number): Debouncer;
87
+ export declare function createDebouncer(delay: number | (() => number)): Debouncer;
88
+
89
+ /** Controls modal behavior while the consumer owns rendering and transitions. */
90
+ export declare function createDialogController(options: DialogControllerOptions): DialogController;
88
91
 
89
92
  export declare function createFocusOutDismiss(options: FocusOutDismissOptions): FocusOutDismissController;
90
93
 
@@ -94,6 +97,9 @@ export declare function createMenuNavigation(container: HTMLElement, options?: M
94
97
 
95
98
  export declare function createNativePopoverDisclosure(options: NativePopoverDisclosureOptions): NativePopoverDisclosureController;
96
99
 
100
+ /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
101
+ export declare function createPopoverController(options: PopoverControllerOptions): PopoverController;
102
+
97
103
  /**
98
104
  * Framework-neutral list reorder controller. It combines item registration,
99
105
  * live pointer preview ordering, keyboard moves, pointer commits, bounds, and
@@ -102,6 +108,14 @@ export declare function createNativePopoverDisclosure(options: NativePopoverDisc
102
108
  */
103
109
  export declare function createReorderableList<T>(options: ReorderableListOptions<T>): ReorderableListController<T>;
104
110
 
111
+ /** Coordinates hover and focus intent without moving focus into the tooltip. */
112
+ export declare function createTooltipController(options: TooltipControllerOptions): TooltipController;
113
+
114
+ export declare interface CssVariableInheritanceOptions {
115
+ filter: (name: string) => boolean;
116
+ mediaQueries?: readonly string[];
117
+ }
118
+
105
119
  export declare type DarkModeStrategy = 'auto' | 'class' | 'selector' | 'media' | (() => boolean);
106
120
 
107
121
  /**
@@ -117,6 +131,8 @@ export declare function debounce<T extends (...args: unknown[]) => void>(fn: T):
117
131
  * call and queues a fresh one `delay` milliseconds out.
118
132
  */
119
133
  export declare interface Debouncer {
134
+ /** Whether a scheduled callback is waiting to run. */
135
+ readonly pending: boolean;
120
136
  /** Queue `fn` to run after `delay` ms, cancelling any pending call. */
121
137
  schedule(fn: () => void): void;
122
138
  /** Cancel a pending call, if any. */
@@ -130,6 +146,30 @@ export declare interface Debouncer {
130
146
  */
131
147
  export declare function detectFramerate(): Promise<number>;
132
148
 
149
+ export declare interface DialogController {
150
+ readonly native: boolean;
151
+ readonly isOpen: boolean;
152
+ open: () => void;
153
+ close: () => Promise<void>;
154
+ mount: () => void;
155
+ cleanup: CleanupFunction;
156
+ }
157
+
158
+ export declare interface DialogControllerOptions {
159
+ dialog: () => HTMLElement | null;
160
+ panel: () => HTMLElement | null;
161
+ onOpenChange?: (open: boolean) => void;
162
+ onCancel?: () => void;
163
+ onMount?: (context: DialogMountContext) => CleanupFunction | void;
164
+ transition?: (visible: boolean) => void | Promise<unknown>;
165
+ }
166
+
167
+ export declare interface DialogMountContext {
168
+ dialog: HTMLElement;
169
+ panel: HTMLElement;
170
+ native: boolean;
171
+ }
172
+
133
173
  export declare type EasingName = keyof typeof easings;
134
174
 
135
175
  /**
@@ -153,7 +193,7 @@ export declare function except<T extends Record<string, unknown>>(target: T, key
153
193
 
154
194
  export declare function except(target: string[], keys: string[], ignoreCase?: boolean): string[];
155
195
 
156
- export declare function focusFirstEnabledElement(elements: Array<HTMLElement | null | undefined>): boolean;
196
+ export declare function focusFirstEnabledElement(elements: Array<HTMLElement | null | undefined>, options?: FocusOptions): boolean;
157
197
 
158
198
  export declare interface FocusOutDismissController {
159
199
  markOpen: () => void;
@@ -229,6 +269,9 @@ export declare interface HslColor {
229
269
  */
230
270
  export declare function hslToHex(h: number, s: number, l: number): string;
231
271
 
272
+ /** Copy selected computed custom properties and restore owned inline values on cleanup. */
273
+ export declare function inheritCssVariables(source: HTMLElement, target: HTMLElement, options: CssVariableInheritanceOptions): () => void;
274
+
232
275
  /**
233
276
  * Check whether the document is currently in RTL direction.
234
277
  */
@@ -262,6 +305,7 @@ export declare interface MenuNavigationOptions {
262
305
  orientation?: 'vertical' | 'horizontal';
263
306
  loop?: boolean;
264
307
  typeAhead?: boolean;
308
+ initialFocus?: 'first' | 'last';
265
309
  onActivate?: (item: HTMLElement) => void;
266
310
  }
267
311
 
@@ -399,6 +443,36 @@ export declare function parseRgbColor(input: string): ParsedColor | null;
399
443
 
400
444
  export declare type Placement = 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' | 'right' | 'right-start' | 'right-end';
401
445
 
446
+ export declare interface PopoverController {
447
+ readonly native: boolean;
448
+ readonly isOpen: boolean;
449
+ open: () => void;
450
+ close: (restoreFocus?: boolean) => void;
451
+ toggle: (event?: MouseEvent) => void;
452
+ mount: () => void;
453
+ cleanup: CleanupFunction;
454
+ onKeydown: (event: KeyboardEvent) => void;
455
+ onFocusOut: (event: FocusEvent) => void;
456
+ onPointerDown: () => void;
457
+ }
458
+
459
+ export declare interface PopoverControllerOptions {
460
+ reference: () => HTMLElement | null;
461
+ popover: () => HTMLElement | null;
462
+ position: TopLayerPopoverPositionOptions;
463
+ menu?: boolean;
464
+ onOpenChange?: (open: boolean) => void;
465
+ onMount?: (context: PopoverMountContext) => CleanupFunction | void;
466
+ onOpened?: () => void;
467
+ onClosed?: () => void;
468
+ }
469
+
470
+ export declare interface PopoverMountContext {
471
+ reference: HTMLElement;
472
+ popover: HTMLElement;
473
+ native: boolean;
474
+ }
475
+
402
476
  declare interface PositionOptions_2 {
403
477
  placement?: Placement;
404
478
  offset?: number;
@@ -547,6 +621,29 @@ export declare function supportsTopLayerAnchorPositioning(): boolean;
547
621
 
548
622
  export declare function supportsWebAnimations(): boolean;
549
623
 
624
+ export declare interface TooltipController {
625
+ readonly native: boolean;
626
+ readonly isOpen: boolean;
627
+ mount: () => void;
628
+ cleanup: CleanupFunction;
629
+ hide: () => Promise<void>;
630
+ onMouseEnter: () => void;
631
+ onMouseLeave: () => void;
632
+ onFocusIn: () => void;
633
+ onFocusOut: (event: FocusEvent) => void;
634
+ }
635
+
636
+ export declare interface TooltipControllerOptions {
637
+ reference: () => HTMLElement | null;
638
+ tooltip: () => HTMLElement | null;
639
+ enabled?: () => boolean;
640
+ delay?: number | (() => number);
641
+ position?: PositionOptions_2;
642
+ onOpenChange?: (open: boolean) => void;
643
+ onMount?: (context: PopoverMountContext) => CleanupFunction | void;
644
+ transition?: (visible: boolean) => void | Promise<unknown>;
645
+ }
646
+
550
647
  export declare interface TopLayerPopoverPositionOptions {
551
648
  placement?: Placement;
552
649
  offset?: number;
package/dist/index.js CHANGED
@@ -490,7 +490,7 @@ function onClickOutside(elements, callback) {
490
490
  //#endregion
491
491
  //#region src/menu.ts
492
492
  function createMenuNavigation(container, options = {}) {
493
- const { itemSelector = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])", orientation = "vertical", loop = true, typeAhead = true, onActivate } = options;
493
+ const { itemSelector = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])", orientation = "vertical", loop = true, typeAhead = true, initialFocus = "first", onActivate } = options;
494
494
  let typeAheadBuffer = "";
495
495
  let typeAheadTimeout;
496
496
  function getItems() {
@@ -559,11 +559,12 @@ function createMenuNavigation(container, options = {}) {
559
559
  }
560
560
  container.addEventListener("keydown", handleKeyDown);
561
561
  const items = getItems();
562
- items.forEach((el, i) => el.setAttribute("tabindex", i === 0 ? "0" : "-1"));
562
+ const initialIndex = initialFocus === "last" ? items.length - 1 : 0;
563
+ items.forEach((el, i) => el.setAttribute("tabindex", i === initialIndex ? "0" : "-1"));
563
564
  let rafId;
564
565
  if (items.length > 0) rafId = requestAnimationFrame(() => {
565
566
  rafId = void 0;
566
- items[0].focus();
567
+ items[initialIndex].focus();
567
568
  });
568
569
  let cleaned = false;
569
570
  return function cleanup() {
@@ -1223,10 +1224,11 @@ function createPointerReorder(options) {
1223
1224
  function isDisabledElement(element) {
1224
1225
  return "disabled" in element && element.disabled === true;
1225
1226
  }
1226
- function focusFirstEnabledElement(elements) {
1227
+ function focusFirstEnabledElement(elements, options) {
1227
1228
  const control = elements.find((candidate) => candidate && !isDisabledElement(candidate));
1228
1229
  if (control) {
1229
- control.focus();
1230
+ if (options) control.focus(options);
1231
+ else control.focus();
1230
1232
  return true;
1231
1233
  }
1232
1234
  return false;
@@ -2084,6 +2086,144 @@ function createNativePopoverDisclosure(options) {
2084
2086
  };
2085
2087
  }
2086
2088
  //#endregion
2089
+ //#region src/popover.ts
2090
+ /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2091
+ function createPopoverController(options) {
2092
+ const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2093
+ let cleanups = [];
2094
+ let mountedPanel = null;
2095
+ let pointerStartedOpen = false;
2096
+ let focusLast = false;
2097
+ const disclosure = createNativePopoverDisclosure({
2098
+ reference: options.reference,
2099
+ popover: options.popover,
2100
+ get position() {
2101
+ let placement = options.position.placement ?? "bottom-start";
2102
+ const reference = options.reference();
2103
+ if (reference && getComputedStyle(reference).direction === "rtl" && /^(top|bottom)-/.test(placement)) placement = placement.replace(/start|end/, (side) => side === "start" ? "end" : "start");
2104
+ return {
2105
+ ...options.position,
2106
+ placement,
2107
+ anchorPositioning: native && options.position.anchorPositioning !== false
2108
+ };
2109
+ },
2110
+ focusOut: {
2111
+ container: options.reference,
2112
+ shouldIgnore: () => !!options.popover()?.contains(document.activeElement),
2113
+ onDismiss: () => close(false)
2114
+ },
2115
+ onOpenChange: options.onOpenChange
2116
+ });
2117
+ function cleanup(hide = true) {
2118
+ cleanups.forEach((cleanup) => cleanup());
2119
+ cleanups = [];
2120
+ disclosure.cleanupPopover();
2121
+ if (hide && native && mountedPanel?.matches(":popover-open")) mountedPanel.hidePopover();
2122
+ mountedPanel = null;
2123
+ }
2124
+ function returnFocus() {
2125
+ const reference = options.reference();
2126
+ (reference?.matches("button, input, select, textarea, a[href], [tabindex]") ? reference : reference?.querySelector("button:not([disabled]), input, select, textarea, a[href], [tabindex]"))?.focus({ preventScroll: true });
2127
+ }
2128
+ function shouldReturnFocus() {
2129
+ return typeof document !== "undefined" && (!!mountedPanel?.contains(document.activeElement) || document.activeElement === document.body);
2130
+ }
2131
+ function close(restoreFocus = shouldReturnFocus()) {
2132
+ disclosure.closePopover({
2133
+ hide: false,
2134
+ onClose() {
2135
+ cleanup();
2136
+ if (restoreFocus) returnFocus();
2137
+ options.onClosed?.();
2138
+ }
2139
+ });
2140
+ }
2141
+ function onKeydown(event) {
2142
+ if (event.key === "Escape" && disclosure.isOpen) {
2143
+ event.preventDefault();
2144
+ event.stopPropagation();
2145
+ close(true);
2146
+ } else if (options.menu && !disclosure.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2147
+ event.preventDefault();
2148
+ focusLast = event.key === "ArrowUp";
2149
+ disclosure.openPopover();
2150
+ }
2151
+ }
2152
+ function mount() {
2153
+ const reference = options.reference();
2154
+ const panel = options.popover();
2155
+ if (!disclosure.isOpen || !reference || !panel) return;
2156
+ cleanup();
2157
+ mountedPanel = panel;
2158
+ const onBeforeToggle = (event) => {
2159
+ const restoreFocus = shouldReturnFocus();
2160
+ disclosure.handlePopoverToggle(event, { onClose() {
2161
+ cleanup(false);
2162
+ if (restoreFocus) returnFocus();
2163
+ options.onClosed?.();
2164
+ } });
2165
+ };
2166
+ panel.addEventListener("beforetoggle", onBeforeToggle);
2167
+ panel.addEventListener("keydown", onKeydown);
2168
+ panel.addEventListener("focusout", disclosure.handleFocusOut);
2169
+ cleanups.push(() => {
2170
+ panel.removeEventListener("beforetoggle", onBeforeToggle);
2171
+ panel.removeEventListener("keydown", onKeydown);
2172
+ panel.removeEventListener("focusout", disclosure.handleFocusOut);
2173
+ });
2174
+ if (native) disclosure.showPopover();
2175
+ else {
2176
+ disclosure.updatePosition();
2177
+ cleanups.push(onClickOutside([reference, panel], () => close()));
2178
+ cleanups.push(onEscapeKey(() => close(true)));
2179
+ }
2180
+ disclosure.startAutoUpdate();
2181
+ const cleanupMount = options.onMount?.({
2182
+ reference,
2183
+ popover: panel,
2184
+ native
2185
+ });
2186
+ if (cleanupMount) cleanups.push(cleanupMount);
2187
+ if (options.menu) {
2188
+ cleanups.push(createMenuNavigation(panel, { initialFocus: focusLast ? "last" : "first" }));
2189
+ focusLast = false;
2190
+ const onClick = (event) => {
2191
+ if (event.target.closest("[role=\"menuitem\"]")) {
2192
+ const timer = setTimeout(() => {
2193
+ if (mountedPanel === panel) close();
2194
+ }, 0);
2195
+ cleanups.push(() => clearTimeout(timer));
2196
+ }
2197
+ };
2198
+ panel.addEventListener("click", onClick);
2199
+ cleanups.push(() => panel.removeEventListener("click", onClick));
2200
+ }
2201
+ options.onOpened?.();
2202
+ }
2203
+ function toggle(event) {
2204
+ const wasOpen = !!event?.detail && pointerStartedOpen;
2205
+ pointerStartedOpen = false;
2206
+ if (wasOpen) close();
2207
+ else disclosure.togglePopover(() => disclosure.openPopover(), () => close());
2208
+ }
2209
+ return {
2210
+ native,
2211
+ get isOpen() {
2212
+ return disclosure.isOpen;
2213
+ },
2214
+ open: () => disclosure.openPopover(),
2215
+ close,
2216
+ mount,
2217
+ cleanup,
2218
+ toggle,
2219
+ onKeydown,
2220
+ onFocusOut: disclosure.handleFocusOut,
2221
+ onPointerDown: () => {
2222
+ pointerStartedOpen = disclosure.isOpen;
2223
+ }
2224
+ };
2225
+ }
2226
+ //#endregion
2087
2227
  //#region src/blank.ts
2088
2228
  /**
2089
2229
  * Port of Laravel's `blank` function.
@@ -2114,7 +2254,7 @@ function debounce(fn) {
2114
2254
  };
2115
2255
  }
2116
2256
  /**
2117
- * Create a {@link Debouncer} with a fixed delay.
2257
+ * Create a {@link Debouncer} with a fixed delay or a getter read on each schedule.
2118
2258
  *
2119
2259
  * @param delay - Milliseconds to wait after the latest `schedule()` call.
2120
2260
  */
@@ -2131,11 +2271,14 @@ function createDebouncer(delay) {
2131
2271
  timer = setTimeout(() => {
2132
2272
  timer = null;
2133
2273
  fn();
2134
- }, delay);
2274
+ }, typeof delay === "function" ? delay() : delay);
2135
2275
  };
2136
2276
  return {
2137
2277
  schedule,
2138
- cancel
2278
+ cancel,
2279
+ get pending() {
2280
+ return timer !== null;
2281
+ }
2139
2282
  };
2140
2283
  }
2141
2284
  /**
@@ -2475,4 +2618,267 @@ function formatColor(color, format = "hex", options = {}) {
2475
2618
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2476
2619
  }
2477
2620
  //#endregion
2478
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, computePosition, createDebouncer, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, createReorderableList, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, hexToHsl, hexToRgb, hslToHex, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
2621
+ //#region src/cssVariables.ts
2622
+ /** Copy selected computed custom properties and restore owned inline values on cleanup. */
2623
+ function inheritCssVariables(source, target, options) {
2624
+ const view = source.ownerDocument.defaultView;
2625
+ if (!view) return () => {};
2626
+ const original = /* @__PURE__ */ new Map();
2627
+ const applied = /* @__PURE__ */ new Map();
2628
+ function restore(name) {
2629
+ const previous = original.get(name);
2630
+ if (previous && target.style.getPropertyValue(name) === applied.get(name)) if (previous.value) target.style.setProperty(name, previous.value, previous.priority);
2631
+ else target.style.removeProperty(name);
2632
+ original.delete(name);
2633
+ applied.delete(name);
2634
+ }
2635
+ function update() {
2636
+ const computed = view.getComputedStyle(source);
2637
+ const names = /* @__PURE__ */ new Set();
2638
+ for (const name of Array.from(computed)) {
2639
+ if (!name.startsWith("--") || !options.filter(name)) continue;
2640
+ const value = computed.getPropertyValue(name).trim();
2641
+ if (!value) continue;
2642
+ names.add(name);
2643
+ if (!original.has(name)) original.set(name, {
2644
+ value: target.style.getPropertyValue(name),
2645
+ priority: target.style.getPropertyPriority(name)
2646
+ });
2647
+ if (applied.get(name) !== value) {
2648
+ target.style.setProperty(name, value);
2649
+ applied.set(name, value);
2650
+ }
2651
+ }
2652
+ for (const name of applied.keys()) if (!names.has(name)) restore(name);
2653
+ }
2654
+ update();
2655
+ const observer = new MutationObserver(update);
2656
+ for (let ancestor = source; ancestor; ancestor = ancestor.parentElement) observer.observe(ancestor, {
2657
+ attributes: true,
2658
+ attributeFilter: ["class", "style"]
2659
+ });
2660
+ const media = (options.mediaQueries ?? []).map((query) => view.matchMedia(query));
2661
+ media.forEach((query) => query.addEventListener("change", update));
2662
+ return () => {
2663
+ observer.disconnect();
2664
+ media.forEach((query) => query.removeEventListener("change", update));
2665
+ for (const name of applied.keys()) restore(name);
2666
+ };
2667
+ }
2668
+ //#endregion
2669
+ //#region src/tooltip.ts
2670
+ /** Coordinates hover and focus intent without moving focus into the tooltip. */
2671
+ function createTooltipController(options) {
2672
+ const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2673
+ const scheduler = createDebouncer(options.delay ?? 300);
2674
+ let hovered = false;
2675
+ let focused = false;
2676
+ let closing = false;
2677
+ let revision = 0;
2678
+ let mounted = null;
2679
+ let cleanups = [];
2680
+ const disclosure = createNativePopoverDisclosure({
2681
+ reference: options.reference,
2682
+ popover: options.tooltip,
2683
+ get position() {
2684
+ return {
2685
+ placement: "top",
2686
+ offset: 6,
2687
+ ...options.position
2688
+ };
2689
+ },
2690
+ onOpenChange: options.onOpenChange
2691
+ });
2692
+ function cleanup() {
2693
+ revision++;
2694
+ closing = false;
2695
+ scheduler.cancel();
2696
+ cleanups.forEach((cleanup) => cleanup());
2697
+ cleanups = [];
2698
+ disclosure.cleanupPopover();
2699
+ if (native && mounted?.matches(":popover-open")) mounted.hidePopover();
2700
+ mounted = null;
2701
+ }
2702
+ async function hide() {
2703
+ scheduler.cancel();
2704
+ if (!disclosure.isOpen || closing) return;
2705
+ closing = true;
2706
+ const current = ++revision;
2707
+ await options.transition?.(false);
2708
+ if (current !== revision) return;
2709
+ disclosure.closePopover({
2710
+ hide: false,
2711
+ onClose: cleanup
2712
+ });
2713
+ }
2714
+ function requestShow() {
2715
+ if (options.enabled?.() === false) return;
2716
+ if (closing) {
2717
+ revision++;
2718
+ closing = false;
2719
+ options.transition?.(true);
2720
+ }
2721
+ if (disclosure.isOpen) return;
2722
+ scheduler.schedule(() => {
2723
+ if ((hovered || focused) && options.enabled?.() !== false) disclosure.openPopover();
2724
+ });
2725
+ }
2726
+ function dismissIfIdle() {
2727
+ if (!hovered && !focused) hide();
2728
+ }
2729
+ function mount() {
2730
+ const reference = options.reference();
2731
+ const tooltip = options.tooltip();
2732
+ if (!disclosure.isOpen || !reference || !tooltip) return;
2733
+ cleanup();
2734
+ mounted = tooltip;
2735
+ if (native) tooltip.showPopover();
2736
+ const updatePosition = () => computePosition(reference, tooltip, {
2737
+ placement: "top",
2738
+ offset: 6,
2739
+ ...options.position
2740
+ });
2741
+ updatePosition();
2742
+ cleanups.push(autoUpdateTopLayerPopover(reference, tooltip, updatePosition));
2743
+ const release = options.onMount?.({
2744
+ reference,
2745
+ popover: tooltip,
2746
+ native
2747
+ });
2748
+ if (release) cleanups.push(release);
2749
+ const escape = (event) => {
2750
+ if (event.key !== "Escape") return;
2751
+ if (event.target instanceof Node && reference.contains(event.target)) {
2752
+ event.preventDefault();
2753
+ event.stopPropagation();
2754
+ }
2755
+ hide();
2756
+ };
2757
+ reference.ownerDocument.addEventListener("keydown", escape, true);
2758
+ cleanups.push(() => reference.ownerDocument.removeEventListener("keydown", escape, true));
2759
+ options.transition?.(true);
2760
+ }
2761
+ return {
2762
+ native,
2763
+ get isOpen() {
2764
+ return disclosure.isOpen;
2765
+ },
2766
+ mount,
2767
+ cleanup,
2768
+ hide,
2769
+ onMouseEnter() {
2770
+ hovered = true;
2771
+ requestShow();
2772
+ },
2773
+ onMouseLeave() {
2774
+ hovered = false;
2775
+ dismissIfIdle();
2776
+ },
2777
+ onFocusIn() {
2778
+ focused = true;
2779
+ requestShow();
2780
+ },
2781
+ onFocusOut(event) {
2782
+ if (event.relatedTarget instanceof Node && options.reference()?.contains(event.relatedTarget)) return;
2783
+ focused = false;
2784
+ dismissIfIdle();
2785
+ }
2786
+ };
2787
+ }
2788
+ //#endregion
2789
+ //#region src/modalDialog.ts
2790
+ var dialogs = [];
2791
+ /** Controls modal behavior while the consumer owns rendering and transitions. */
2792
+ function createDialogController(options) {
2793
+ const native = typeof HTMLDialogElement !== "undefined" && typeof HTMLDialogElement.prototype.showModal === "function";
2794
+ const entry = {};
2795
+ let open = false;
2796
+ let closing = false;
2797
+ let revision = 0;
2798
+ let mounted = null;
2799
+ let previousFocus = null;
2800
+ let cleanups = [];
2801
+ function cleanup() {
2802
+ revision++;
2803
+ closing = false;
2804
+ const top = dialogs[dialogs.length - 1] === entry;
2805
+ const index = dialogs.indexOf(entry);
2806
+ if (index !== -1) dialogs.splice(index, 1);
2807
+ cleanups.forEach((cleanup) => cleanup());
2808
+ cleanups = [];
2809
+ if (native && mounted?.open) mounted.close();
2810
+ if (!native && top && previousFocus?.isConnected) previousFocus.focus({ preventScroll: true });
2811
+ previousFocus = null;
2812
+ mounted = null;
2813
+ }
2814
+ function show() {
2815
+ revision++;
2816
+ if (closing) {
2817
+ closing = false;
2818
+ options.transition?.(true);
2819
+ }
2820
+ if (open) return;
2821
+ open = true;
2822
+ options.onOpenChange?.(true);
2823
+ }
2824
+ async function close() {
2825
+ if (!open || closing) return;
2826
+ closing = true;
2827
+ const current = ++revision;
2828
+ await options.transition?.(false);
2829
+ if (current !== revision) return;
2830
+ open = false;
2831
+ cleanup();
2832
+ options.onOpenChange?.(false);
2833
+ }
2834
+ function mount() {
2835
+ const dialog = options.dialog();
2836
+ const panel = options.panel();
2837
+ if (!open || !dialog || !panel) return;
2838
+ cleanup();
2839
+ mounted = dialog;
2840
+ previousFocus = dialog.ownerDocument.activeElement;
2841
+ dialogs.push(entry);
2842
+ cleanups.push(lockScroll());
2843
+ if (native) {
2844
+ const cancel = (event) => {
2845
+ event.preventDefault();
2846
+ options.onCancel?.();
2847
+ };
2848
+ dialog.addEventListener("cancel", cancel);
2849
+ cleanups.push(() => dialog.removeEventListener("cancel", cancel));
2850
+ dialog.showModal();
2851
+ } else {
2852
+ for (let current = dialog; current?.parentElement; current = current.parentElement) {
2853
+ for (const sibling of Array.from(current.parentElement.children)) if (sibling !== current && sibling instanceof HTMLElement) cleanups.push(markInert(sibling));
2854
+ if (current.parentElement === dialog.ownerDocument.body) break;
2855
+ }
2856
+ cleanups.push(createFocusTrap(panel, { returnFocus: false }));
2857
+ cleanups.push(onEscapeKey((event) => {
2858
+ if (event.defaultPrevented || dialogs[dialogs.length - 1] !== entry) return;
2859
+ event.preventDefault();
2860
+ event.stopPropagation();
2861
+ options.onCancel?.();
2862
+ }));
2863
+ }
2864
+ const release = options.onMount?.({
2865
+ dialog,
2866
+ panel,
2867
+ native
2868
+ });
2869
+ if (release) cleanups.push(release);
2870
+ options.transition?.(true);
2871
+ }
2872
+ return {
2873
+ native,
2874
+ get isOpen() {
2875
+ return open;
2876
+ },
2877
+ open: show,
2878
+ close,
2879
+ mount,
2880
+ cleanup
2881
+ };
2882
+ }
2883
+ //#endregion
2884
+ export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, computePosition, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.3.1",
3
+ "version": "1.5.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",