@inertiaui/vanilla 1.8.1 → 1.9.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
@@ -24,9 +24,11 @@ npm install @inertiaui/vanilla
24
24
  - [Focus Management](#focus-management)
25
25
  - [Keyboard Events](#keyboard-events)
26
26
  - [Click Outside](#click-outside)
27
+ - [Visibility](#visibility)
27
28
  - [Menu Navigation](#menu-navigation)
28
29
  - [Listbox Helpers](#listbox-helpers)
29
30
  - [Reorder](#reorder)
31
+ - [Pointer Drag](#pointer-drag)
30
32
  - [Positioning](#positioning)
31
33
  - [Native Popovers](#native-popovers)
32
34
  - [Tooltip Controllers](#tooltip-controllers)
@@ -36,6 +38,7 @@ npm install @inertiaui/vanilla
36
38
  - [Accessibility](#accessibility)
37
39
  - [Animation](#animation)
38
40
  - [Dark Mode Detection](#dark-mode-detection)
41
+ - [Media Queries](#media-queries)
39
42
  - [RTL Support](#rtl-support)
40
43
  - [Debounce](#debounce)
41
44
  - [Color](#color)
@@ -171,6 +174,39 @@ const focused = focusFirstEnabledElement([
171
174
  // true when an enabled element was focused
172
175
  ```
173
176
 
177
+ ### focusWhenReady
178
+
179
+ `focusWhenReady(target, options)` focuses an element on the next frame, after the current update has rendered. This is useful for moving the focus to a control that a framework re-renders, or that a closing dialog still holds. A disabled element is tried again on every frame until it is enabled, including controls disabled through a parent `fieldset`, and nothing is focused once the element left the document. The function returns a callback that cancels the pending attempt.
180
+
181
+ ```typescript
182
+ import { focusWhenReady } from '@inertiaui/vanilla'
183
+
184
+ removeFilter(filter)
185
+
186
+ const cancel = focusWhenReady(addFilterButton, { preventScroll: true })
187
+ ```
188
+
189
+ You may pass a function to find the element again on every attempt, and a `when` callback to stop without focusing, such as when the user already moved the focus elsewhere. The other options are passed to `focus()`:
190
+
191
+ ```typescript
192
+ focusWhenReady(() => table.querySelector<HTMLElement>(`[data-row="${key}"] button`), {
193
+ preventScroll: true,
194
+ when: () => table.contains(document.activeElement) || document.activeElement === document.body,
195
+ })
196
+ ```
197
+
198
+ ### getAdjacentItem
199
+
200
+ `getAdjacentItem(items, item)` returns the item after `item`, or the one before it when `item` is the last. Use it to pick the element that receives the focus before the focused one is removed:
201
+
202
+ ```typescript
203
+ import { getAdjacentItem, MENU_ITEM_SELECTOR } from '@inertiaui/vanilla'
204
+
205
+ const items = Array.from(menu.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR))
206
+
207
+ getAdjacentItem(items, removedItem)?.focus()
208
+ ```
209
+
174
210
  ## Keyboard Events
175
211
 
176
212
  ### onEscapeKey
@@ -266,6 +302,44 @@ openButton.addEventListener('click', () => {
266
302
  })
267
303
  ```
268
304
 
305
+ ## Visibility
306
+
307
+ `observeVisibility(element, callback, options)` reports whether an element is visible in a scroll container or the viewport. The callback receives `true` or `false` and the `IntersectionObserverEntry`: once when observing starts, and again whenever the visibility changes.
308
+
309
+ ```ts
310
+ import { observeVisibility } from '@inertiaui/vanilla'
311
+
312
+ const visibility = observeVisibility(
313
+ sentinel,
314
+ (visible) => {
315
+ if (visible) {
316
+ loadNextPage()
317
+ }
318
+ },
319
+ { root: list, rootMargin: '200px' },
320
+ )
321
+
322
+ // Later, stop observing
323
+ visibility.cleanup()
324
+ ```
325
+
326
+ | Option | Type | Default | Description |
327
+ |--------|------|---------|-------------|
328
+ | `root` | `Element \| Document \| null` | `null` | The scroll container the element must be visible in. `null` uses the viewport |
329
+ | `rootMargin` | `string` | `'0px'` | Grow or shrink the root's box before checking, such as `'200px'` to report the element early |
330
+ | `threshold` | `number \| number[]` | `0` | Passed to the `IntersectionObserver` |
331
+ | `once` | `boolean` | `false` | Stop observing once the element is visible for the first time |
332
+
333
+ An observer only reports changes, so a sentinel that stays visible while new rows render above it is not reported again. You may call `recheck()` after such an update to report the current visibility on the next frame:
334
+
335
+ ```ts
336
+ await appendRows(page)
337
+
338
+ visibility.recheck()
339
+ ```
340
+
341
+ Without `IntersectionObserver` support, such as during server-side rendering, the callback is never called.
342
+
269
343
  ## Menu Navigation
270
344
 
271
345
  The `createMenuNavigation` function adds keyboard navigation to menu containers, implementing the [WAI-ARIA Menu Pattern](https://www.w3.org/WAI/ARIA/apg/patterns/menu/). It supports arrow key navigation, roving tabindex, type-ahead search, and item activation.
@@ -335,6 +409,8 @@ const cleanup = createMenuNavigation(container, {
335
409
  })
336
410
  ```
337
411
 
412
+ The default selector is exported as `MENU_ITEM_SELECTOR`, which matches the `menuitem` elements that are neither `disabled` nor `aria-disabled="true"`.
413
+
338
414
  ### Full Example
339
415
 
340
416
  ```typescript
@@ -605,6 +681,47 @@ const controller = createReorderableList({
605
681
 
606
682
  With auto-scroll enabled and no `getScrollContainers` callback, the controller discovers scrollable ancestors along both axes on each pointer move.
607
683
 
684
+ ## Pointer Drag
685
+
686
+ `createPointerDrag(element, options)` follows a pointer from a press on the element until its release. The handle captures the pointer, so the drag keeps following it outside the element, and only the pointer that started the drag moves it. Presses with a secondary button or a non-primary pointer are ignored.
687
+
688
+ The `handle` option resolves the element a press drags, which lets one listener serve many handles. Every callback receives the drag state: the `handle`, the `pointerId`, the `origin` and latest `position` in client coordinates, the `delta` between them, whether the handle is written right to left (`rtl`), and the pointer `event`.
689
+
690
+ ```ts
691
+ import { createPointerDrag } from '@inertiaui/vanilla'
692
+
693
+ let startWidth = 0
694
+
695
+ const drag = createPointerDrag(table, {
696
+ handle: (event) => (event.target as Element).closest<HTMLElement>('[data-column-resize]'),
697
+ capture: true,
698
+ onStart(state) {
699
+ state.event.stopPropagation()
700
+ startWidth = state.handle.closest('th')!.getBoundingClientRect().width
701
+ },
702
+ onMove(state) {
703
+ // Dragging toward the end of the row widens the column in both directions.
704
+ resizeColumn(startWidth + state.delta.x * (state.rtl ? -1 : 1))
705
+ },
706
+ onEnd() {
707
+ saveColumnWidths()
708
+ },
709
+ })
710
+
711
+ // Later, cancel an active drag and stop listening
712
+ drag.cleanup()
713
+ ```
714
+
715
+ | Option | Type | Default | Description |
716
+ |--------|------|---------|-------------|
717
+ | `handle` | `(event: PointerEvent) => HTMLElement \| null` | The element | Resolve the element a press drags, or return `null` to ignore the press |
718
+ | `capture` | `boolean` | `false` | Listen for presses in the capture phase, before handlers inside the element |
719
+ | `onStart` | `(state) => boolean \| void` | - | Called when a press starts a drag. Return `false` to ignore the press |
720
+ | `onMove` | `(state) => void` | - | Called for every move of the dragging pointer |
721
+ | `onEnd` | `(state, cancelled) => void` | - | Called once when the drag ends. `cancelled` is `true` for `pointercancel`, a lost pointer capture, `cancel()`, and `cleanup()` |
722
+
723
+ A press that starts a drag has its default action prevented, so it doesn't select text or start a native drag. The returned controller exposes `dragging`, `cancel()` to end the active drag as cancelled, and `cleanup()`.
724
+
608
725
  ## Positioning
609
726
 
610
727
  Utilities for positioning floating elements (dropdowns, tooltips, popovers) relative to a reference element. Uses [CSS Anchor Positioning](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_anchor_positioning) when supported, with an automatic JavaScript fallback.
@@ -771,6 +888,7 @@ const result = positionTopLayerPopover(button, popover, {
771
888
  | `offset` | `number` | `4` | Distance from the reference |
772
889
  | `flip` | `boolean` | `true` | Flip when the preferred side overflows |
773
890
  | `matchReferenceWidth` | `boolean` | `false` | Set width to the reference width, clamped to viewport |
891
+ | `minWidth` | `number` | - | Set the narrowest width, clamped to viewport. Combined with `matchReferenceWidth`, the popover is as wide as the reference but never narrower than `minWidth` |
774
892
  | `viewportMargin` | `number` | `8` | Space kept between the popover and viewport edge |
775
893
  | `anchorPositioning` | `boolean` | `true` | Use CSS Anchor Positioning when supported |
776
894
 
@@ -839,6 +957,14 @@ function setupTooltip(trigger: HTMLElement, tooltip: HTMLElement) {
839
957
 
840
958
  ## Native Popovers
841
959
 
960
+ `supportsNativePopover()` returns whether the browser supports the [Popover API](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API). The controllers below check it themselves, so you only need it to render a fallback, such as leaving out the `popover` attribute:
961
+
962
+ ```typescript
963
+ import { supportsNativePopover } from '@inertiaui/vanilla'
964
+
965
+ panel.popover = supportsNativePopover() ? 'manual' : null
966
+ ```
967
+
842
968
  ### Managed popovers and menus
843
969
 
844
970
  `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.
@@ -1406,6 +1532,21 @@ prefersDarkMode('media')
1406
1532
  prefersDarkMode(() => document.body.dataset.theme === 'dark')
1407
1533
  ```
1408
1534
 
1535
+ ## Media Queries
1536
+
1537
+ `observeMediaQuery(query, callback)` reports whether a media query matches: once right away, and again whenever that changes. It returns a cleanup function. Without `matchMedia`, such as during server-side rendering, the callback is never called.
1538
+
1539
+ ```typescript
1540
+ import { observeMediaQuery } from '@inertiaui/vanilla'
1541
+
1542
+ const cleanup = observeMediaQuery('(max-width: 639px)', (matches) => {
1543
+ compact.value = matches
1544
+ })
1545
+
1546
+ // Later, stop observing
1547
+ cleanup()
1548
+ ```
1549
+
1409
1550
  ## RTL Support
1410
1551
 
1411
1552
  Utilities for detecting and observing right-to-left direction, for the document and for single elements.
package/dist/index.d.ts CHANGED
@@ -123,6 +123,12 @@ export declare function createMenuNavigation(container: HTMLElement, options?: M
123
123
 
124
124
  export declare function createNativePopoverDisclosure(options: NativePopoverDisclosureOptions): NativePopoverDisclosureController;
125
125
 
126
+ /**
127
+ * Track a pointer from a press on the element until its release. The handle captures the pointer, so the drag
128
+ * follows it outside the element, and only the pointer that started the drag moves it.
129
+ */
130
+ export declare function createPointerDrag(element: HTMLElement, options?: PointerDragOptions): PointerDragController;
131
+
126
132
  /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
127
133
  export declare function createPopoverController(options: PopoverControllerOptions): PopoverController;
128
134
 
@@ -241,6 +247,18 @@ export declare interface FocusTrapOptions {
241
247
  returnFocus?: boolean;
242
248
  }
243
249
 
250
+ /**
251
+ * Focus an element on the next frame, after the current update has rendered. A disabled element is tried again
252
+ * on every frame until it is enabled, and nothing is focused once it left the document. Pass a function to find
253
+ * the element again on every attempt. Returns a function that cancels the pending attempt.
254
+ */
255
+ export declare function focusWhenReady(target: HTMLElement | null | undefined | (() => HTMLElement | null | undefined), options?: FocusWhenReadyOptions): () => void;
256
+
257
+ export declare interface FocusWhenReadyOptions extends FocusOptions {
258
+ /** Checked before every attempt. Nothing is focused once it returns false, such as when the user moved on. */
259
+ when?: () => boolean;
260
+ }
261
+
244
262
  /**
245
263
  * Give a panel rendered away from its reference, such as in the body, the
246
264
  * direction the reference is written in. A panel with its own `dir` keeps it.
@@ -277,6 +295,9 @@ export declare interface FormatColorOptions {
277
295
 
278
296
  export declare function generateId(prefix?: string): string;
279
297
 
298
+ /** Get the item after `item` in a list, or the one before it when `item` is the last. */
299
+ export declare function getAdjacentItem<T>(items: readonly T[], item: T): T | undefined;
300
+
280
301
  /**
281
302
  * Return how far each item moves along the axis when the items are laid out in
282
303
  * `order`, a permutation of their indices. The offsets describe the movement
@@ -390,6 +411,9 @@ export declare function markAriaHidden(elementOrSelector: Element | string): Cle
390
411
 
391
412
  export declare function markInert(elementOrSelector: HTMLElement | string): CleanupFunction;
392
413
 
414
+ /** The enabled items of a menu, which its keyboard navigation moves between. */
415
+ export declare const MENU_ITEM_SELECTOR = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])";
416
+
393
417
  export declare interface MenuNavigationOptions {
394
418
  itemSelector?: string;
395
419
  orientation?: 'vertical' | 'horizontal';
@@ -450,6 +474,18 @@ export declare function normalizeHue(number: number): number;
450
474
  */
451
475
  export declare function normalizePercent(number: number): number;
452
476
 
477
+ /**
478
+ * Report whether a media query matches: once right away, and again whenever that changes. Without `matchMedia`,
479
+ * such as during SSR, nothing is reported.
480
+ */
481
+ export declare function observeMediaQuery(query: string, callback: (matches: boolean) => void): CleanupFunction;
482
+
483
+ /**
484
+ * Report whether an element is visible in a scroll container or the viewport: once when observing starts, and
485
+ * again whenever it changes. Without IntersectionObserver support, such as during SSR, nothing is reported.
486
+ */
487
+ export declare function observeVisibility(element: Element, callback: (visible: boolean, entry: IntersectionObserverEntry) => void, options?: VisibilityObserverOptions): VisibilityObserver;
488
+
453
489
  export declare function onceChildrenRendered(element: Element, callback: () => void): void;
454
490
 
455
491
  export declare function onClickOutside(elements: HTMLElement | HTMLElement[], callback: (event: PointerEvent) => void): CleanupFunction;
@@ -533,6 +569,47 @@ export declare function parseRgbColor(input: string): ParsedColor | null;
533
569
 
534
570
  export declare type Placement = 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' | 'right' | 'right-start' | 'right-end';
535
571
 
572
+ export declare interface PointerDragController {
573
+ readonly dragging: boolean;
574
+ /** End the active drag as cancelled. */
575
+ cancel: () => void;
576
+ /** Cancel the active drag and stop listening for presses. */
577
+ cleanup: CleanupFunction;
578
+ }
579
+
580
+ export declare interface PointerDragOptions {
581
+ /** Resolve the element a press drags, or return null to ignore the press. Defaults to the element itself. */
582
+ handle?: (event: PointerEvent) => HTMLElement | null;
583
+ /** Listen for presses in the capture phase, before handlers inside the element see them. */
584
+ capture?: boolean;
585
+ /** Called when a press starts a drag. Return false to ignore the press. */
586
+ onStart?: (state: PointerDragState) => boolean | void;
587
+ onMove?: (state: PointerDragState) => void;
588
+ /** Called once when the drag ends. A cancelled drag ended without a release, such as through `pointercancel`. */
589
+ onEnd?: (state: PointerDragState, cancelled: boolean) => void;
590
+ }
591
+
592
+ export declare interface PointerDragPoint {
593
+ x: number;
594
+ y: number;
595
+ }
596
+
597
+ export declare interface PointerDragState {
598
+ /** The element that holds the pointer capture during the drag. */
599
+ handle: HTMLElement;
600
+ pointerId: number;
601
+ /** Where the press started, in client coordinates. */
602
+ origin: PointerDragPoint;
603
+ /** The latest pointer position, in client coordinates. */
604
+ position: PointerDragPoint;
605
+ /** How far the pointer moved since the press. */
606
+ delta: PointerDragPoint;
607
+ /** Whether the handle is written right to left, read when the press starts. */
608
+ rtl: boolean;
609
+ /** The pointer event that produced this state. */
610
+ event: PointerEvent;
611
+ }
612
+
536
613
  export declare interface PopoverController {
537
614
  readonly native: boolean;
538
615
  readonly isOpen: boolean;
@@ -770,6 +847,9 @@ export declare function sameUrlPath(url1: string | URL | undefined | null, url2:
770
847
 
771
848
  export declare function supportsAnchorPositioning(): boolean;
772
849
 
850
+ /** Determine if the browser supports the native Popover API. */
851
+ export declare function supportsNativePopover(): boolean;
852
+
773
853
  export declare function supportsTopLayerAnchorPositioning(): boolean;
774
854
 
775
855
  export declare function supportsWebAnimations(): boolean;
@@ -802,8 +882,26 @@ export declare interface TopLayerPopoverPositionOptions {
802
882
  offset?: number;
803
883
  flip?: boolean;
804
884
  matchReferenceWidth?: boolean;
885
+ /** The narrowest width of the floating element, which the viewport width still limits. */
886
+ minWidth?: number;
805
887
  viewportMargin?: number;
806
888
  anchorPositioning?: boolean;
807
889
  }
808
890
 
891
+ export declare interface VisibilityObserver {
892
+ /** Report the element's visibility again on the next frame, even when it didn't change. */
893
+ recheck: () => void;
894
+ cleanup: CleanupFunction;
895
+ }
896
+
897
+ export declare interface VisibilityObserverOptions {
898
+ /** The scroll container the element must be visible in. Defaults to the viewport. */
899
+ root?: Element | Document | null;
900
+ /** Grow or shrink the root's box before checking, such as `'200px'` to report the element early. */
901
+ rootMargin?: string;
902
+ threshold?: number | number[];
903
+ /** Stop observing once the element is visible for the first time. */
904
+ once?: boolean;
905
+ }
906
+
809
907
  export { }
package/dist/index.js CHANGED
@@ -371,6 +371,144 @@ function createAnnouncer(regions) {
371
371
  };
372
372
  }
373
373
  //#endregion
374
+ //#region src/rtl.ts
375
+ /**
376
+ * Check whether the document is currently in RTL direction.
377
+ */
378
+ function isRtl() {
379
+ return document.documentElement.dir === "rtl";
380
+ }
381
+ /**
382
+ * Check whether an element is written right to left, from its computed `direction`. Unlike `isRtl()`, this follows a
383
+ * `dir` attribute on any ancestor, such as a right-to-left section in a left-to-right page.
384
+ */
385
+ function isRightToLeft(element) {
386
+ return getComputedStyle(element).direction === "rtl";
387
+ }
388
+ /**
389
+ * Observe changes to the document's `dir` attribute and invoke the callback
390
+ * whenever it changes. Returns a cleanup function to stop observing.
391
+ */
392
+ function onRtlChange(callback) {
393
+ const observer = new MutationObserver(() => {
394
+ callback(document.documentElement.dir === "rtl");
395
+ });
396
+ observer.observe(document.documentElement, {
397
+ attributes: true,
398
+ attributeFilter: ["dir"]
399
+ });
400
+ return () => observer.disconnect();
401
+ }
402
+ /**
403
+ * Give a panel rendered away from its reference, such as in the body, the
404
+ * direction the reference is written in. A panel with its own `dir` keeps it.
405
+ * Returns a cleanup function that removes the direction again.
406
+ */
407
+ function followReferenceDirection(reference, panel) {
408
+ const direction = getComputedStyle(reference).direction;
409
+ if (panel.hasAttribute("dir") || getComputedStyle(panel).direction === direction) return () => {};
410
+ panel.setAttribute("dir", direction);
411
+ return () => {
412
+ if (panel.getAttribute("dir") === direction) panel.removeAttribute("dir");
413
+ };
414
+ }
415
+ //#endregion
416
+ //#region src/drag.ts
417
+ /**
418
+ * Track a pointer from a press on the element until its release. The handle captures the pointer, so the drag
419
+ * follows it outside the element, and only the pointer that started the drag moves it.
420
+ */
421
+ function createPointerDrag(element, options = {}) {
422
+ const capture = options.capture ?? false;
423
+ let state = null;
424
+ let cleaned = false;
425
+ function withPosition(current, event) {
426
+ const position = {
427
+ x: event.clientX,
428
+ y: event.clientY
429
+ };
430
+ return {
431
+ ...current,
432
+ position,
433
+ delta: {
434
+ x: position.x - current.origin.x,
435
+ y: position.y - current.origin.y
436
+ },
437
+ event
438
+ };
439
+ }
440
+ function start(event) {
441
+ if (cleaned || state || event.button !== 0 || event.isPrimary === false) return;
442
+ const handle = options.handle ? options.handle(event) : element;
443
+ if (cleaned || !handle) return;
444
+ const origin = {
445
+ x: event.clientX,
446
+ y: event.clientY
447
+ };
448
+ const next = {
449
+ handle,
450
+ pointerId: event.pointerId,
451
+ origin,
452
+ position: origin,
453
+ delta: {
454
+ x: 0,
455
+ y: 0
456
+ },
457
+ rtl: isRightToLeft(handle),
458
+ event
459
+ };
460
+ if (options.onStart?.(next) === false || cleaned) return;
461
+ event.preventDefault();
462
+ state = next;
463
+ try {
464
+ handle.setPointerCapture(event.pointerId);
465
+ } catch {}
466
+ const document = handle.ownerDocument;
467
+ document.addEventListener("pointermove", move, true);
468
+ document.addEventListener("pointerup", release, true);
469
+ document.addEventListener("pointercancel", release, true);
470
+ document.addEventListener("lostpointercapture", loseCapture, true);
471
+ }
472
+ function move(event) {
473
+ if (!state || event.pointerId !== state.pointerId) return;
474
+ state = withPosition(state, event);
475
+ options.onMove?.(state);
476
+ }
477
+ function release(event) {
478
+ if (!state || event.pointerId !== state.pointerId) return;
479
+ end(event.type === "pointerup" ? withPosition(state, event) : state, event.type !== "pointerup");
480
+ }
481
+ function loseCapture(event) {
482
+ if (state && event.pointerId === state.pointerId) end(state, true);
483
+ }
484
+ function end(ended, cancelled) {
485
+ const { handle, pointerId } = ended;
486
+ const document = handle.ownerDocument;
487
+ state = null;
488
+ document.removeEventListener("pointermove", move, true);
489
+ document.removeEventListener("pointerup", release, true);
490
+ document.removeEventListener("pointercancel", release, true);
491
+ document.removeEventListener("lostpointercapture", loseCapture, true);
492
+ if (typeof handle.hasPointerCapture === "function" && handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
493
+ options.onEnd?.(ended, cancelled);
494
+ }
495
+ function cancel() {
496
+ if (state) end(state, true);
497
+ }
498
+ element.addEventListener("pointerdown", start, capture);
499
+ return {
500
+ get dragging() {
501
+ return state !== null;
502
+ },
503
+ cancel,
504
+ cleanup() {
505
+ cleaned = true;
506
+ element.removeEventListener("pointerdown", start, capture);
507
+ cancel();
508
+ }
509
+ };
510
+ }
511
+ //#endregion
374
512
  //#region src/dialog.ts
375
513
  var FOCUSABLE_SELECTORS = [
376
514
  "a[href]",
@@ -661,8 +799,10 @@ function onClickOutside(elements, callback) {
661
799
  }
662
800
  //#endregion
663
801
  //#region src/menu.ts
802
+ /** The enabled items of a menu, which its keyboard navigation moves between. */
803
+ var MENU_ITEM_SELECTOR = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])";
664
804
  function createMenuNavigation(container, options = {}) {
665
- const { itemSelector = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])", orientation = "vertical", loop = true, typeAhead = true, initialFocus = "first", onActivate } = options;
805
+ const { itemSelector = MENU_ITEM_SELECTOR, orientation = "vertical", loop = true, typeAhead = true, initialFocus = "first", onActivate } = options;
666
806
  let typeAheadBuffer = "";
667
807
  let typeAheadTimeout;
668
808
  function getItems() {
@@ -851,6 +991,47 @@ function createFocusOutDismiss(options) {
851
991
  };
852
992
  }
853
993
  //#endregion
994
+ //#region src/visibility.ts
995
+ /**
996
+ * Report whether an element is visible in a scroll container or the viewport: once when observing starts, and
997
+ * again whenever it changes. Without IntersectionObserver support, such as during SSR, nothing is reported.
998
+ */
999
+ function observeVisibility(element, callback, options = {}) {
1000
+ if (typeof IntersectionObserver === "undefined") return {
1001
+ recheck() {},
1002
+ cleanup() {}
1003
+ };
1004
+ let frame = 0;
1005
+ let stopped = false;
1006
+ const observer = new IntersectionObserver((entries) => {
1007
+ const entry = entries[entries.length - 1];
1008
+ if (stopped || !entry) return;
1009
+ if (options.once && entry.isIntersecting) cleanup();
1010
+ callback(entry.isIntersecting, entry);
1011
+ }, {
1012
+ root: options.root ?? null,
1013
+ rootMargin: options.rootMargin,
1014
+ threshold: options.threshold
1015
+ });
1016
+ function cleanup() {
1017
+ stopped = true;
1018
+ cancelAnimationFrame(frame);
1019
+ observer.disconnect();
1020
+ }
1021
+ observer.observe(element);
1022
+ return {
1023
+ recheck() {
1024
+ if (stopped) return;
1025
+ cancelAnimationFrame(frame);
1026
+ frame = requestAnimationFrame(() => {
1027
+ observer.unobserve(element);
1028
+ observer.observe(element);
1029
+ });
1030
+ },
1031
+ cleanup
1032
+ };
1033
+ }
1034
+ //#endregion
854
1035
  //#region src/reorder.ts
855
1036
  /**
856
1037
  * Attribute a caller places on a drag handle element so the pointer controller
@@ -1604,7 +1785,7 @@ function createPointerReorder(options) {
1604
1785
  //#endregion
1605
1786
  //#region src/focus.ts
1606
1787
  function isDisabledElement(element) {
1607
- return "disabled" in element && element.disabled === true;
1788
+ return "disabled" in element && element.disabled === true || element.matches(":disabled");
1608
1789
  }
1609
1790
  function focusFirstEnabledElement(elements, options) {
1610
1791
  const control = elements.find((candidate) => candidate && !isDisabledElement(candidate));
@@ -1615,47 +1796,30 @@ function focusFirstEnabledElement(elements, options) {
1615
1796
  }
1616
1797
  return false;
1617
1798
  }
1618
- //#endregion
1619
- //#region src/rtl.ts
1620
- /**
1621
- * Check whether the document is currently in RTL direction.
1622
- */
1623
- function isRtl() {
1624
- return document.documentElement.dir === "rtl";
1625
- }
1626
- /**
1627
- * Check whether an element is written right to left, from its computed `direction`. Unlike `isRtl()`, this follows a
1628
- * `dir` attribute on any ancestor, such as a right-to-left section in a left-to-right page.
1629
- */
1630
- function isRightToLeft(element) {
1631
- return getComputedStyle(element).direction === "rtl";
1799
+ /** Get the item after `item` in a list, or the one before it when `item` is the last. */
1800
+ function getAdjacentItem(items, item) {
1801
+ const index = items.indexOf(item);
1802
+ if (index < 0) return;
1803
+ return items[index + 1] ?? items[index - 1];
1632
1804
  }
1633
1805
  /**
1634
- * Observe changes to the document's `dir` attribute and invoke the callback
1635
- * whenever it changes. Returns a cleanup function to stop observing.
1806
+ * Focus an element on the next frame, after the current update has rendered. A disabled element is tried again
1807
+ * on every frame until it is enabled, and nothing is focused once it left the document. Pass a function to find
1808
+ * the element again on every attempt. Returns a function that cancels the pending attempt.
1636
1809
  */
1637
- function onRtlChange(callback) {
1638
- const observer = new MutationObserver(() => {
1639
- callback(document.documentElement.dir === "rtl");
1640
- });
1641
- observer.observe(document.documentElement, {
1642
- attributes: true,
1643
- attributeFilter: ["dir"]
1810
+ function focusWhenReady(target, options = {}) {
1811
+ const { when, ...focusOptions } = options;
1812
+ let frame = requestAnimationFrame(function attempt() {
1813
+ if (when && !when()) return;
1814
+ const element = typeof target === "function" ? target() : target;
1815
+ if (!element?.isConnected) return;
1816
+ if (isDisabledElement(element)) {
1817
+ frame = requestAnimationFrame(attempt);
1818
+ return;
1819
+ }
1820
+ element.focus(focusOptions);
1644
1821
  });
1645
- return () => observer.disconnect();
1646
- }
1647
- /**
1648
- * Give a panel rendered away from its reference, such as in the body, the
1649
- * direction the reference is written in. A panel with its own `dir` keeps it.
1650
- * Returns a cleanup function that removes the direction again.
1651
- */
1652
- function followReferenceDirection(reference, panel) {
1653
- const direction = getComputedStyle(reference).direction;
1654
- if (panel.hasAttribute("dir") || getComputedStyle(panel).direction === direction) return () => {};
1655
- panel.setAttribute("dir", direction);
1656
- return () => {
1657
- if (panel.getAttribute("dir") === direction) panel.removeAttribute("dir");
1658
- };
1822
+ return () => cancelAnimationFrame(frame);
1659
1823
  }
1660
1824
  //#endregion
1661
1825
  //#region src/position/style.ts
@@ -2309,12 +2473,13 @@ function observeTopLayerElementResize(reference, floating, scheduleUpdate, updat
2309
2473
  var autoUpdatedPopovers = /* @__PURE__ */ new WeakSet();
2310
2474
  var settledPlacements = /* @__PURE__ */ new WeakMap();
2311
2475
  function positionTopLayerPopover(reference, floating, options = {}) {
2312
- const { placement = "bottom-start", offset = 4, flip = true, matchReferenceWidth = false, viewportMargin = 8, anchorPositioning = true } = options;
2476
+ const { placement = "bottom-start", offset = 4, flip = true, matchReferenceWidth = false, minWidth, viewportMargin = 8, anchorPositioning = true } = options;
2313
2477
  const viewport = getViewportRect();
2314
2478
  const maxWidth = Math.max(0, Math.floor(viewport.width - viewportMargin * 2));
2315
2479
  setStyleProperty(floating.style, "position", "fixed");
2316
2480
  setStyleProperty(floating.style, "box-sizing", "border-box");
2317
2481
  setStyleProperty(floating.style, "max-width", `${maxWidth}px`);
2482
+ if (minWidth !== void 0) setStyleProperty(floating.style, "min-width", `${Math.min(minWidth, maxWidth)}px`);
2318
2483
  setStyleProperty(floating.style, "overflow-x", "auto");
2319
2484
  setStyleProperty(floating.style, "overflow-y", "auto");
2320
2485
  setStyleProperty(floating.style, "overscroll-behavior", "contain");
@@ -2571,6 +2736,10 @@ function autoUpdateTopLayerPopover(reference, floating, update) {
2571
2736
  }
2572
2737
  //#endregion
2573
2738
  //#region src/nativePopover.ts
2739
+ /** Determine if the browser supports the native Popover API. */
2740
+ function supportsNativePopover() {
2741
+ return typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2742
+ }
2574
2743
  function restoreVisibility(popover, visibility) {
2575
2744
  if (visibility === void 0) {
2576
2745
  popover.style.removeProperty("visibility");
@@ -2681,7 +2850,7 @@ function createNativePopoverDisclosure(options) {
2681
2850
  //#region src/popover.ts
2682
2851
  /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2683
2852
  function createPopoverController(options) {
2684
- const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2853
+ const native = supportsNativePopover();
2685
2854
  let cleanups = [];
2686
2855
  let mountedPanel = null;
2687
2856
  let pointerStartedOpen = false;
@@ -2925,6 +3094,20 @@ function prefersDarkMode(strategy = "auto") {
2925
3094
  return containsDarkClass() || matchesDarkMediaQuery();
2926
3095
  }
2927
3096
  //#endregion
3097
+ //#region src/mediaQuery.ts
3098
+ /**
3099
+ * Report whether a media query matches: once right away, and again whenever that changes. Without `matchMedia`,
3100
+ * such as during SSR, nothing is reported.
3101
+ */
3102
+ function observeMediaQuery(query, callback) {
3103
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return () => {};
3104
+ const media = window.matchMedia(query);
3105
+ const update = () => callback(media.matches);
3106
+ update();
3107
+ media.addEventListener("change", update);
3108
+ return () => media.removeEventListener("change", update);
3109
+ }
3110
+ //#endregion
2928
3111
  //#region src/color.ts
2929
3112
  /**
2930
3113
  * Convert a hex color string to HSL values.
@@ -3281,7 +3464,7 @@ function inheritCssVariables(source, target, options) {
3281
3464
  //#region src/tooltip.ts
3282
3465
  /** Coordinates hover and focus intent without moving focus into the tooltip. */
3283
3466
  function createTooltipController(options) {
3284
- const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
3467
+ const native = supportsNativePopover();
3285
3468
  const delay = options.delay ?? 300;
3286
3469
  let scheduler;
3287
3470
  let hovered = false;
@@ -3505,4 +3688,4 @@ function createDialogController(options) {
3505
3688
  };
3506
3689
  }
3507
3690
  //#endregion
3508
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, captureInlineStyles, computePosition, createAnnouncer, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createLayoutAnimation, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, followReferenceDirection, formatAlpha, formatColor, generateId, getReorderOffsets, getScrollableAncestors, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRightToLeft, 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, replacePlaceholders, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
3691
+ export { MENU_ITEM_SELECTOR, REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, captureInlineStyles, computePosition, createAnnouncer, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createLayoutAnimation, createMenuNavigation, createNativePopoverDisclosure, createPointerDrag, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, focusWhenReady, followReferenceDirection, formatAlpha, formatColor, generateId, getAdjacentItem, getReorderOffsets, getScrollableAncestors, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRightToLeft, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, observeMediaQuery, observeVisibility, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, replacePlaceholders, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsNativePopover, supportsTopLayerAnchorPositioning, supportsWebAnimations };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",