@inertiaui/vanilla 0.2.0 → 0.3.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
@@ -1,6 +1,13 @@
1
1
  # Inertia UI Vanilla
2
2
 
3
- A lightweight vanilla TypeScript library providing UI utilities for dialogs, animations, focus management, and common helper functions. Framework-agnostic and designed to integrate seamlessly with Vue, React, or any JavaScript application.
3
+ A lightweight vanilla TypeScript library providing UI utilities for dialogs, animations, focus management, menu navigation, click outside detection, floating element positioning, and common helper functions. Framework-agnostic and designed to integrate seamlessly with Vue, React, or any JavaScript application.
4
+
5
+ This package is part of the [Inertia UI](https://inertiaui.com) suite. Check out our other packages:
6
+
7
+ - **[Inertia Modal](https://inertiaui.com/inertia-modal/docs/)**: Turn any Laravel route into a modal or slideover with a single component. No backend changes needed, with support for nested/stacked modals and inter-modal communication. Works with Vue and React.
8
+ - **[Inertia Table](https://inertiaui.com/inertia-table)**: The most complete data table package for Laravel and Inertia.js. Sorting, searching, and filtering across relationships, bulk actions, CSV/Excel/PDF exports, sticky headers, and much more. Works with Vue and React.
9
+
10
+ [![Inertia UI](https://inertiaui.com/visit-card.jpg)](https://inertiaui.com)
4
11
 
5
12
  ## Installation
6
13
 
@@ -13,13 +20,16 @@ npm install @inertiaui/vanilla
13
20
  - [Scroll Locking](#scroll-locking)
14
21
  - [Focus Management](#focus-management)
15
22
  - [Keyboard Events](#keyboard-events)
23
+ - [Click Outside](#click-outside)
24
+ - [Menu Navigation](#menu-navigation)
25
+ - [Positioning](#positioning)
16
26
  - [Accessibility](#accessibility)
17
27
  - [Animation](#animation)
18
28
  - [Helpers](#helpers)
19
- - [generateId](#generateid)
20
- - [Object Filtering](#object-filtering)
21
- - [String Utilities](#string-utilities)
22
- - [URL Utilities](#url-utilities)
29
+ - [generateId](#generateid)
30
+ - [Object Filtering](#object-filtering)
31
+ - [String Utilities](#string-utilities)
32
+ - [URL Utilities](#url-utilities)
23
33
 
24
34
  ## Scroll Locking
25
35
 
@@ -37,6 +47,7 @@ unlock()
37
47
  ```
38
48
 
39
49
  The function:
50
+
40
51
  - Sets `document.body.style.overflow` to `'hidden'`
41
52
  - Adds padding to compensate for scrollbar width (prevents layout shift)
42
53
  - Returns a cleanup function that can only unlock once
@@ -82,11 +93,7 @@ Creates a focus trap within a container element.
82
93
  ```typescript
83
94
  import { createFocusTrap } from '@inertiaui/vanilla'
84
95
 
85
- const cleanup = createFocusTrap(container, {
86
- initialFocus: true,
87
- initialFocusElement: null,
88
- returnFocus: true,
89
- })
96
+ const cleanup = createFocusTrap(dialogElement)
90
97
 
91
98
  // Later, remove the focus trap
92
99
  cleanup()
@@ -103,6 +110,7 @@ cleanup()
103
110
  #### Behavior
104
111
 
105
112
  The focus trap:
113
+
106
114
  - Listens for Tab key and wraps focus at container boundaries
107
115
  - Prevents focus from leaving the container via Tab or Shift+Tab
108
116
  - Catches focus that escapes (e.g., via mouse click outside)
@@ -111,19 +119,18 @@ The focus trap:
111
119
  - Supports nesting: when multiple traps are active, only the most recently created trap receives focus. Cleaning up the inner trap restores the outer trap.
112
120
 
113
121
  ```typescript
114
- const container = document.getElementById('dialog')
122
+ const container = document.getElementById('dialog')!
115
123
  const submitButton = document.getElementById('submit')
116
124
 
117
125
  const cleanup = createFocusTrap(container, {
118
- initialFocus: true,
119
126
  initialFocusElement: submitButton, // Focus submit button instead of first element
120
- returnFocus: true,
121
127
  })
122
128
  ```
123
129
 
124
130
  #### Focusable Elements
125
131
 
126
132
  The focus trap recognizes these elements as focusable:
133
+
127
134
  - `a[href]`
128
135
  - `button:not([disabled])`
129
136
  - `textarea:not([disabled])`
@@ -169,21 +176,293 @@ const cleanup = onEscapeKey(handleEscape, {
169
176
  The cleanup function pattern integrates well with framework lifecycle hooks:
170
177
 
171
178
  ```typescript
172
- // Vue
173
- onMounted(() => {
174
- cleanup = onEscapeKey(close)
175
- })
176
- onUnmounted(() => {
177
- cleanup()
178
- })
179
+ // Vue (<script setup>)
180
+ const cleanup = onEscapeKey(closeDialog)
181
+ onUnmounted(() => cleanup())
179
182
 
180
183
  // React
181
184
  useEffect(() => {
182
- const cleanup = onEscapeKey(close)
183
- return cleanup
185
+ return onEscapeKey(closeDialog)
184
186
  }, [])
185
187
  ```
186
188
 
189
+ ## Click Outside
190
+
191
+ The `onClickOutside` function detects clicks outside one or more elements and calls a callback. Useful for closing dropdowns, popovers, and modals when the user clicks elsewhere.
192
+
193
+ ### Basic Usage
194
+
195
+ ```typescript
196
+ import { onClickOutside } from '@inertiaui/vanilla'
197
+
198
+ const cleanup = onClickOutside(dropdownElement, (event) => {
199
+ closeDropdown()
200
+ })
201
+
202
+ // Later, remove the listener
203
+ cleanup()
204
+ ```
205
+
206
+ ### Multiple Elements
207
+
208
+ Pass an array of elements to ignore clicks inside any of them:
209
+
210
+ ```typescript
211
+ const cleanup = onClickOutside([triggerButton, dropdownPanel], () => {
212
+ closeDropdown()
213
+ })
214
+ ```
215
+
216
+ ### Portal Support
217
+
218
+ Clicks inside elements with the `data-inertiaui-portal` attribute (or their descendants) are automatically ignored. This prevents portalled content like dropdown menus from being considered "outside":
219
+
220
+ ```html
221
+ <div data-inertiaui-portal>
222
+ <!-- Clicks here won't trigger the callback -->
223
+ </div>
224
+ ```
225
+
226
+ ### Same-Tick Protection
227
+
228
+ The listener registration is deferred by one tick, so the click that triggered the element to open won't immediately close it:
229
+
230
+ ```typescript
231
+ openButton.addEventListener('click', () => {
232
+ dropdown.hidden = false
233
+ // The click on openButton won't trigger the outside handler
234
+ onClickOutside(dropdown, () => { dropdown.hidden = true })
235
+ })
236
+ ```
237
+
238
+ ## Menu Navigation
239
+
240
+ 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.
241
+
242
+ ### Basic Usage
243
+
244
+ ```typescript
245
+ import { createMenuNavigation } from '@inertiaui/vanilla'
246
+
247
+ const cleanup = createMenuNavigation(menuElement)
248
+
249
+ // Later, remove navigation
250
+ cleanup()
251
+ ```
252
+
253
+ ### Options
254
+
255
+ | Option | Type | Default | Description |
256
+ |--------|------|---------|-------------|
257
+ | `itemSelector` | `string` | `'[role="menuitem"]:not([disabled]):not([aria-disabled="true"])'` | CSS selector for menu items |
258
+ | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Arrow key direction |
259
+ | `loop` | `boolean` | `true` | Wrap focus from last to first item |
260
+ | `typeAhead` | `boolean` | `true` | Enable type-ahead character search |
261
+ | `onActivate` | `(item: HTMLElement) => void` | `undefined` | Called when an item is activated via Enter or Space |
262
+
263
+ ### Keyboard Support
264
+
265
+ | Key | Action |
266
+ |-----|--------|
267
+ | `ArrowDown` / `ArrowRight` | Focus next item (depending on orientation) |
268
+ | `ArrowUp` / `ArrowLeft` | Focus previous item (depending on orientation) |
269
+ | `Home` | Focus first item |
270
+ | `End` | Focus last item |
271
+ | `Enter` / `Space` | Activate (click) the focused item |
272
+ | Any character | Type-ahead: focus the first item whose text starts with the typed characters |
273
+
274
+ ### Roving Tabindex
275
+
276
+ The focused item receives `tabindex="0"` while all other items receive `tabindex="-1"`. This allows the menu to participate in the page's tab order with a single tab stop:
277
+
278
+ ```typescript
279
+ const cleanup = createMenuNavigation(menuElement)
280
+
281
+ // First item has tabindex="0", rest have tabindex="-1"
282
+ // Arrow keys move focus and update tabindex accordingly
283
+ ```
284
+
285
+ ### Horizontal Menus
286
+
287
+ For horizontal menus like toolbars, use `orientation: 'horizontal'`:
288
+
289
+ ```typescript
290
+ const cleanup = createMenuNavigation(toolbar, {
291
+ orientation: 'horizontal',
292
+ })
293
+ // ArrowRight/ArrowLeft navigate instead of ArrowDown/ArrowUp
294
+ ```
295
+
296
+ ### Custom Item Selector
297
+
298
+ Use a custom selector for non-standard menu structures:
299
+
300
+ ```typescript
301
+ const cleanup = createMenuNavigation(container, {
302
+ itemSelector: '.menu-item:not(.disabled)',
303
+ })
304
+ ```
305
+
306
+ ### Full Example
307
+
308
+ ```typescript
309
+ import { createMenuNavigation, onClickOutside, onEscapeKey } from '@inertiaui/vanilla'
310
+
311
+ function openMenu(menuElement: HTMLElement) {
312
+ menuElement.hidden = false
313
+
314
+ const cleanups = [
315
+ createMenuNavigation(menuElement, {
316
+ onActivate: (item) => {
317
+ handleMenuAction(item.dataset.action!)
318
+ closeMenu()
319
+ },
320
+ }),
321
+ onClickOutside(menuElement, closeMenu),
322
+ onEscapeKey(closeMenu),
323
+ ]
324
+
325
+ function closeMenu() {
326
+ cleanups.forEach((fn) => fn())
327
+ menuElement.hidden = true
328
+ }
329
+ }
330
+ ```
331
+
332
+ ## Positioning
333
+
334
+ 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.
335
+
336
+ ### supportsAnchorPositioning
337
+
338
+ Check if the browser supports CSS Anchor Positioning:
339
+
340
+ ```typescript
341
+ import { supportsAnchorPositioning } from '@inertiaui/vanilla'
342
+
343
+ if (supportsAnchorPositioning()) {
344
+ // Browser handles positioning via CSS
345
+ } else {
346
+ // JavaScript fallback is used
347
+ }
348
+ ```
349
+
350
+ The result is cached after the first call.
351
+
352
+ ### computePosition
353
+
354
+ Position a floating element relative to a reference element:
355
+
356
+ ```typescript
357
+ import { computePosition } from '@inertiaui/vanilla'
358
+
359
+ const result = computePosition(referenceElement, floatingElement)
360
+ // { x: 100, y: 140, placement: 'bottom-start' }
361
+ ```
362
+
363
+ The function applies positioning styles to the floating element automatically (`position: fixed` with `top` and `left` values).
364
+
365
+ #### Options
366
+
367
+ | Option | Type | Default | Description |
368
+ |--------|------|---------|-------------|
369
+ | `placement` | `Placement` | `'bottom-start'` | Where to position the floating element |
370
+ | `offset` | `number` | `0` | Distance in pixels between reference and floating element |
371
+ | `flip` | `boolean` | `true` | Flip to opposite side when overflowing viewport |
372
+
373
+ #### Placements
374
+
375
+ Twelve placement options are available, combining a side with an optional alignment:
376
+
377
+ | Side | Center | Start | End |
378
+ |------|--------|-------|-----|
379
+ | `top` | `top` | `top-start` | `top-end` |
380
+ | `bottom` | `bottom` | `bottom-start` | `bottom-end` |
381
+ | `left` | `left` | `left-start` | `left-end` |
382
+ | `right` | `right` | `right-start` | `right-end` |
383
+
384
+ The `start` and `end` alignments are RTL-aware for `top` and `bottom` placements.
385
+
386
+ #### Flip Behavior
387
+
388
+ When the floating element would overflow the viewport, it automatically flips to the opposite side:
389
+
390
+ ```typescript
391
+ // If there's no room below, flips to top
392
+ const result = computePosition(reference, floating, {
393
+ placement: 'bottom-start',
394
+ })
395
+ // result.placement may be 'top-start' if it flipped
396
+ ```
397
+
398
+ Disable flipping to keep the element on the specified side:
399
+
400
+ ```typescript
401
+ const result = computePosition(reference, floating, {
402
+ placement: 'bottom-start',
403
+ flip: false,
404
+ })
405
+ ```
406
+
407
+ #### Viewport Clamping
408
+
409
+ The floating element is always clamped to stay within the viewport with a 4px margin, even after flipping.
410
+
411
+ ### autoUpdate
412
+
413
+ Automatically reposition the floating element when the layout changes:
414
+
415
+ ```typescript
416
+ import { computePosition, autoUpdate } from '@inertiaui/vanilla'
417
+
418
+ const cleanup = autoUpdate(referenceElement, floatingElement, () => {
419
+ computePosition(referenceElement, floatingElement, {
420
+ placement: 'bottom-start',
421
+ offset: 8,
422
+ })
423
+ })
424
+
425
+ // Later, stop updating
426
+ cleanup()
427
+ ```
428
+
429
+ `autoUpdate` listens for:
430
+
431
+ - Window `resize` events
432
+ - Window `scroll` events (including nested scrollable containers)
433
+ - Size changes on both the reference and floating elements (via `ResizeObserver`)
434
+
435
+ Updates are batched using `requestAnimationFrame` to avoid layout thrashing.
436
+
437
+ ### CSS Anchor Positioning
438
+
439
+ When the browser supports CSS Anchor Positioning, `computePosition` uses native CSS for positioning. This provides better performance and handles edge cases like scrolling and resizing without JavaScript recalculation. The `autoUpdate` cleanup function automatically removes CSS anchor styles when called.
440
+
441
+ ### Full Example
442
+
443
+ ```typescript
444
+ import { computePosition, autoUpdate } from '@inertiaui/vanilla'
445
+
446
+ function setupTooltip(trigger: HTMLElement, tooltip: HTMLElement) {
447
+ tooltip.style.display = 'block'
448
+
449
+ const cleanup = autoUpdate(trigger, tooltip, () => {
450
+ computePosition(trigger, tooltip, {
451
+ placement: 'top',
452
+ offset: 8,
453
+ })
454
+ })
455
+
456
+ // Initial position
457
+ computePosition(trigger, tooltip, {
458
+ placement: 'top',
459
+ offset: 8,
460
+ })
461
+
462
+ return cleanup
463
+ }
464
+ ```
465
+
187
466
  ## Accessibility
188
467
 
189
468
  Accessibility utilities for managing `aria-hidden` attributes with reference counting support.
@@ -205,11 +484,11 @@ Accepts either an element or a CSS selector:
205
484
 
206
485
  ```typescript
207
486
  // Using selector
208
- const cleanup = markAriaHidden('#app')
487
+ const cleanup1 = markAriaHidden('#app')
209
488
 
210
489
  // Using element
211
- const element = document.getElementById('app')
212
- const cleanup = markAriaHidden(element)
490
+ const element = document.getElementById('app')!
491
+ const cleanup2 = markAriaHidden(element)
213
492
  ```
214
493
 
215
494
  ### Reference Counting
@@ -236,27 +515,27 @@ cleanup2()
236
515
  The original `aria-hidden` value is preserved and restored:
237
516
 
238
517
  ```typescript
239
- const element = document.getElementById('sidebar')
518
+ const element = document.getElementById('sidebar')!
240
519
  element.setAttribute('aria-hidden', 'false')
241
520
 
242
521
  const cleanup = markAriaHidden(element)
243
- console.log(element.getAttribute('aria-hidden')) // 'true'
522
+ element.getAttribute('aria-hidden') // 'true'
244
523
 
245
524
  cleanup()
246
- console.log(element.getAttribute('aria-hidden')) // 'false' (restored)
525
+ element.getAttribute('aria-hidden') // 'false' (restored)
247
526
  ```
248
527
 
249
528
  If the element had no `aria-hidden` attribute, the attribute is removed on cleanup:
250
529
 
251
530
  ```typescript
252
- const element = document.getElementById('main')
531
+ const element = document.getElementById('main')!
253
532
  // No aria-hidden attribute
254
533
 
255
534
  const cleanup = markAriaHidden(element)
256
- console.log(element.getAttribute('aria-hidden')) // 'true'
535
+ element.getAttribute('aria-hidden') // 'true'
257
536
 
258
537
  cleanup()
259
- console.log(element.getAttribute('aria-hidden')) // null (removed)
538
+ element.getAttribute('aria-hidden') // null (removed)
260
539
  ```
261
540
 
262
541
  ### Use with Dialogs
@@ -267,14 +546,16 @@ When a dialog opens, the main content should be marked as `aria-hidden` to preve
267
546
  import { markAriaHidden, lockScroll, createFocusTrap, onEscapeKey } from '@inertiaui/vanilla'
268
547
 
269
548
  function openDialog(dialogElement: HTMLElement) {
549
+ const closeDialog = () => cleanups.forEach(fn => fn())
550
+
270
551
  const cleanups = [
271
552
  markAriaHidden('#app'),
272
553
  lockScroll(),
273
554
  createFocusTrap(dialogElement),
274
- onEscapeKey(() => closeDialog()),
555
+ onEscapeKey(closeDialog),
275
556
  ]
276
557
 
277
- return () => cleanups.forEach(cleanup => cleanup())
558
+ return closeDialog
278
559
  }
279
560
  ```
280
561
 
@@ -388,10 +669,10 @@ const id = generateId()
388
669
  #### Custom Prefix
389
670
 
390
671
  ```typescript
391
- const id = generateId('modal_')
672
+ generateId('modal_')
392
673
  // 'modal_550e8400-e29b-41d4-a716-446655440000'
393
674
 
394
- const id = generateId('dialog-')
675
+ generateId('dialog-')
395
676
  // 'dialog-550e8400-e29b-41d4-a716-446655440000'
396
677
  ```
397
678
 
@@ -408,6 +689,7 @@ In environments where `crypto.randomUUID()` is not available, the function falls
408
689
  #### Use Cases
409
690
 
410
691
  Useful for generating unique IDs for:
692
+
411
693
  - Dialog instances
412
694
  - Form elements requiring unique IDs
413
695
  - Accessibility attributes (`aria-labelledby`, `aria-describedby`)
@@ -577,15 +859,15 @@ isStandardDomEvent('OnClick') // true
577
859
  Useful for distinguishing between standard DOM events and custom events when processing event handlers:
578
860
 
579
861
  ```typescript
580
- const props = {
862
+ const props: Record<string, Function> = {
581
863
  onClick: handleClick,
582
864
  onMouseOver: handleHover,
583
865
  onModalReady: handleModalReady,
584
866
  onUserUpdated: handleUserUpdated,
585
867
  }
586
868
 
587
- const domEvents = {}
588
- const customEvents = {}
869
+ const domEvents: Record<string, Function> = {}
870
+ const customEvents: Record<string, Function> = {}
589
871
 
590
872
  for (const [key, value] of Object.entries(props)) {
591
873
  if (isStandardDomEvent(key)) {
@@ -639,6 +921,51 @@ Useful for determining active navigation states or comparing the current route w
639
921
  const isActive = sameUrlPath(window.location.href, linkHref)
640
922
  ```
641
923
 
924
+ ## Development
925
+
926
+ ### Running the dev server
927
+
928
+ Start Vite to browse the interactive test pages:
929
+
930
+ ```bash
931
+ npx vite --port 3333
932
+ ```
933
+
934
+ Then open `http://localhost:3333` for an overview linking to all test pages.
935
+
936
+ ### Running E2E tests
937
+
938
+ The test suite uses Playwright with Chromium. It automatically starts a Vite dev server:
939
+
940
+ ```bash
941
+ npm run test:e2e
942
+ ```
943
+
944
+ Run a single spec:
945
+
946
+ ```bash
947
+ npx playwright test e2e/menu.spec.ts
948
+ ```
949
+
950
+ Run tests matching a name:
951
+
952
+ ```bash
953
+ npx playwright test -g "ArrowDown"
954
+ ```
955
+
956
+ ### Test structure
957
+
958
+ Each feature has a spec file and a matching HTML page:
959
+
960
+ ```
961
+ e2e/click-outside.spec.ts → e2e/pages/click-outside.html
962
+ e2e/menu.spec.ts → e2e/pages/menu.html
963
+ e2e/focus-trap.spec.ts → e2e/pages/focus-trap.html
964
+ ...
965
+ ```
966
+
967
+ The mapping is handled by a custom fixture in `e2e/test.ts`. HTML pages import directly from the TypeScript source via Vite.
968
+
642
969
  ## TypeScript
643
970
 
644
971
  This library is written in TypeScript and exports the following types:
@@ -650,6 +977,10 @@ import type {
650
977
  EscapeKeyOptions,
651
978
  AnimateOptions,
652
979
  EasingName,
980
+ MenuNavigationOptions,
981
+ Placement,
982
+ PositionOptions,
983
+ PositionResult,
653
984
  } from '@inertiaui/vanilla'
654
985
  ```
655
986
 
package/dist/index.d.ts CHANGED
@@ -19,6 +19,8 @@ export declare interface AnimateOptions {
19
19
  fill?: FillMode;
20
20
  }
21
21
 
22
+ export declare function autoUpdate(reference: HTMLElement, floating: HTMLElement, update: () => void): CleanupFunction;
23
+
22
24
  /**
23
25
  * Cancel any running animations on an element
24
26
  */
@@ -26,8 +28,12 @@ export declare function cancelAnimations(element: HTMLElement): void;
26
28
 
27
29
  export declare type CleanupFunction = () => void;
28
30
 
31
+ export declare function computePosition(reference: HTMLElement, floating: HTMLElement, options?: PositionOptions_2): PositionResult;
32
+
29
33
  export declare function createFocusTrap(container: HTMLElement, options?: FocusTrapOptions): CleanupFunction;
30
34
 
35
+ export declare function createMenuNavigation(container: HTMLElement, options?: MenuNavigationOptions): CleanupFunction;
36
+
31
37
  export declare type EasingName = keyof typeof easings;
32
38
 
33
39
  /**
@@ -65,16 +71,43 @@ export declare function lockScroll(): CleanupFunction;
65
71
 
66
72
  export declare function markAriaHidden(elementOrSelector: Element | string): CleanupFunction;
67
73
 
74
+ export declare interface MenuNavigationOptions {
75
+ itemSelector?: string;
76
+ orientation?: 'vertical' | 'horizontal';
77
+ loop?: boolean;
78
+ typeAhead?: boolean;
79
+ onActivate?: (item: HTMLElement) => void;
80
+ }
81
+
82
+ export declare function onClickOutside(elements: HTMLElement | HTMLElement[], callback: (event: PointerEvent) => void): CleanupFunction;
83
+
68
84
  export declare function onEscapeKey(callback: (event: KeyboardEvent) => void, options?: EscapeKeyOptions): CleanupFunction;
69
85
 
70
86
  export declare function only<T extends Record<string, unknown>>(target: T, keys: string[], ignoreCase?: boolean): Partial<T>;
71
87
 
72
88
  export declare function only(target: string[], keys: string[], ignoreCase?: boolean): string[];
73
89
 
90
+ export declare type Placement = 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' | 'right' | 'right-start' | 'right-end';
91
+
92
+ declare interface PositionOptions_2 {
93
+ placement?: Placement;
94
+ offset?: number;
95
+ flip?: boolean;
96
+ }
97
+ export { PositionOptions_2 as PositionOptions }
98
+
99
+ export declare interface PositionResult {
100
+ x: number;
101
+ y: number;
102
+ placement: Placement;
103
+ }
104
+
74
105
  export declare function rejectNullValues<T>(target: T[]): Exclude<T, null>[];
75
106
 
76
107
  export declare function rejectNullValues<T extends Record<string, unknown>>(target: T): Partial<T>;
77
108
 
78
109
  export declare function sameUrlPath(url1: string | URL | undefined | null, url2: string | URL | undefined | null): boolean;
79
110
 
111
+ export declare function supportsAnchorPositioning(): boolean;
112
+
80
113
  export { }
package/dist/index.js CHANGED
@@ -189,6 +189,20 @@ function createFocusTrap(container, options = {}) {
189
189
  document.addEventListener("focusin", handleTrapFocusIn);
190
190
  }
191
191
  focusTrapStack.push(entry);
192
+ function handleFocusOut(event) {
193
+ if (event.relatedTarget !== null) {
194
+ return;
195
+ }
196
+ queueMicrotask(() => {
197
+ if (!container.contains(container.ownerDocument.activeElement)) {
198
+ const focusableElements = getFocusableElements(container);
199
+ if (focusableElements.length > 0) {
200
+ focusableElements[0].focus();
201
+ }
202
+ }
203
+ });
204
+ }
205
+ container.addEventListener("focusout", handleFocusOut);
192
206
  let rafId;
193
207
  if (initialFocus) {
194
208
  rafId = requestAnimationFrame(() => {
@@ -212,6 +226,7 @@ function createFocusTrap(container, options = {}) {
212
226
  if (rafId !== void 0) {
213
227
  cancelAnimationFrame(rafId);
214
228
  }
229
+ container.removeEventListener("focusout", handleFocusOut);
215
230
  const index = focusTrapStack.indexOf(entry);
216
231
  if (index >= 0) {
217
232
  focusTrapStack.splice(index, 1);
@@ -220,7 +235,7 @@ function createFocusTrap(container, options = {}) {
220
235
  document.removeEventListener("keydown", handleTrapKeyDown);
221
236
  document.removeEventListener("focusin", handleTrapFocusIn);
222
237
  }
223
- if (returnFocus && previouslyFocused && typeof previouslyFocused.focus === "function") {
238
+ if (returnFocus && previouslyFocused && typeof previouslyFocused.focus === "function" && previouslyFocused.isConnected) {
224
239
  previouslyFocused.focus();
225
240
  }
226
241
  };
@@ -283,10 +298,421 @@ function unmarkAriaHidden(element) {
283
298
  ariaHiddenStack.splice(index, 1);
284
299
  }
285
300
  }
301
+ function onClickOutside(elements, callback) {
302
+ const targets = Array.isArray(elements) ? elements : [elements];
303
+ function handler(event) {
304
+ const target = event.target;
305
+ for (const el of targets) {
306
+ if (el.contains(target)) {
307
+ return;
308
+ }
309
+ }
310
+ let node = target;
311
+ while (node) {
312
+ if (node instanceof HTMLElement && node.hasAttribute("data-inertiaui-portal")) {
313
+ return;
314
+ }
315
+ node = node.parentNode;
316
+ }
317
+ callback(event);
318
+ }
319
+ const timeoutId = setTimeout(() => {
320
+ document.addEventListener("pointerdown", handler, true);
321
+ }, 0);
322
+ let cleaned = false;
323
+ return function cleanup() {
324
+ if (cleaned) {
325
+ return;
326
+ }
327
+ cleaned = true;
328
+ clearTimeout(timeoutId);
329
+ document.removeEventListener("pointerdown", handler, true);
330
+ };
331
+ }
332
+ function createMenuNavigation(container, options = {}) {
333
+ const {
334
+ itemSelector = '[role="menuitem"]:not([disabled]):not([aria-disabled="true"])',
335
+ orientation = "vertical",
336
+ loop = true,
337
+ typeAhead = true,
338
+ onActivate
339
+ } = options;
340
+ let typeAheadBuffer = "";
341
+ let typeAheadTimeout;
342
+ function getItems() {
343
+ return Array.from(container.querySelectorAll(itemSelector));
344
+ }
345
+ function getActiveIndex() {
346
+ const items2 = getItems();
347
+ const focused = document.activeElement;
348
+ return items2.indexOf(focused);
349
+ }
350
+ function focusItem(index) {
351
+ const items2 = getItems();
352
+ if (items2.length === 0) {
353
+ return;
354
+ }
355
+ const targetIndex = loop ? (index % items2.length + items2.length) % items2.length : Math.max(0, Math.min(index, items2.length - 1));
356
+ const item = items2[targetIndex];
357
+ items2.forEach((el) => el.setAttribute("tabindex", "-1"));
358
+ item.setAttribute("tabindex", "0");
359
+ item.focus();
360
+ }
361
+ function handleKeyDown(event) {
362
+ const items2 = getItems();
363
+ if (items2.length === 0) {
364
+ return;
365
+ }
366
+ const nextKey = orientation === "vertical" ? "ArrowDown" : "ArrowRight";
367
+ const prevKey = orientation === "vertical" ? "ArrowUp" : "ArrowLeft";
368
+ switch (event.key) {
369
+ case nextKey: {
370
+ event.preventDefault();
371
+ const currentIndex = getActiveIndex();
372
+ focusItem(currentIndex + 1);
373
+ break;
374
+ }
375
+ case prevKey: {
376
+ event.preventDefault();
377
+ const currentIndex = getActiveIndex();
378
+ focusItem(currentIndex - 1);
379
+ break;
380
+ }
381
+ case "Home": {
382
+ event.preventDefault();
383
+ focusItem(0);
384
+ break;
385
+ }
386
+ case "End": {
387
+ event.preventDefault();
388
+ focusItem(items2.length - 1);
389
+ break;
390
+ }
391
+ case "Enter":
392
+ case " ": {
393
+ event.preventDefault();
394
+ const focused = document.activeElement;
395
+ if (items2.includes(focused)) {
396
+ focused.click();
397
+ onActivate == null ? void 0 : onActivate(focused);
398
+ }
399
+ break;
400
+ }
401
+ default: {
402
+ if (typeAhead && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
403
+ event.preventDefault();
404
+ typeAheadBuffer += event.key.toLowerCase();
405
+ if (typeAheadTimeout) {
406
+ clearTimeout(typeAheadTimeout);
407
+ }
408
+ typeAheadTimeout = setTimeout(() => {
409
+ typeAheadBuffer = "";
410
+ }, 350);
411
+ const match = items2.find((item) => {
412
+ const text = (item.textContent || "").trim().toLowerCase();
413
+ return text.startsWith(typeAheadBuffer);
414
+ });
415
+ if (match) {
416
+ const index = items2.indexOf(match);
417
+ focusItem(index);
418
+ }
419
+ }
420
+ break;
421
+ }
422
+ }
423
+ }
424
+ container.addEventListener("keydown", handleKeyDown);
425
+ const items = getItems();
426
+ items.forEach((el, i) => el.setAttribute("tabindex", i === 0 ? "0" : "-1"));
427
+ let rafId;
428
+ if (items.length > 0) {
429
+ rafId = requestAnimationFrame(() => {
430
+ rafId = void 0;
431
+ items[0].focus();
432
+ });
433
+ }
434
+ let cleaned = false;
435
+ return function cleanup() {
436
+ if (cleaned) {
437
+ return;
438
+ }
439
+ cleaned = true;
440
+ if (rafId !== void 0) {
441
+ cancelAnimationFrame(rafId);
442
+ }
443
+ if (typeAheadTimeout) {
444
+ clearTimeout(typeAheadTimeout);
445
+ }
446
+ container.removeEventListener("keydown", handleKeyDown);
447
+ };
448
+ }
449
+ const ANCHOR_CLASS_PREFIX = "iui-anchor-";
450
+ let _supportsAnchor = null;
451
+ function supportsAnchorPositioning() {
452
+ if (_supportsAnchor === null) {
453
+ _supportsAnchor = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("anchor-name", "--a");
454
+ }
455
+ return _supportsAnchor;
456
+ }
457
+ function isRtl() {
458
+ return typeof document !== "undefined" && document.documentElement.dir === "rtl";
459
+ }
460
+ function getOppositePlacement(placement) {
461
+ const map = {
462
+ top: "bottom",
463
+ "top-start": "bottom-start",
464
+ "top-end": "bottom-end",
465
+ bottom: "top",
466
+ "bottom-start": "top-start",
467
+ "bottom-end": "top-end",
468
+ left: "right",
469
+ "left-start": "right-start",
470
+ "left-end": "right-end",
471
+ right: "left",
472
+ "right-start": "left-start",
473
+ "right-end": "left-end"
474
+ };
475
+ return map[placement] || placement;
476
+ }
477
+ function computePositionFromRect(refRect, floatingRect, placement, offset) {
478
+ let x = 0;
479
+ let y = 0;
480
+ const [side, alignment] = placement.split("-");
481
+ const rtl = isRtl();
482
+ switch (side) {
483
+ case "bottom":
484
+ y = refRect.bottom + offset;
485
+ break;
486
+ case "top":
487
+ y = refRect.top - floatingRect.height - offset;
488
+ break;
489
+ case "left":
490
+ x = refRect.left - floatingRect.width - offset;
491
+ break;
492
+ case "right":
493
+ x = refRect.right + offset;
494
+ break;
495
+ }
496
+ if (side === "bottom" || side === "top") {
497
+ const startIsLeft = !rtl;
498
+ switch (alignment) {
499
+ case "start":
500
+ x = startIsLeft ? refRect.left : refRect.right - floatingRect.width;
501
+ break;
502
+ case "end":
503
+ x = startIsLeft ? refRect.right - floatingRect.width : refRect.left;
504
+ break;
505
+ default:
506
+ x = refRect.left + (refRect.width - floatingRect.width) / 2;
507
+ break;
508
+ }
509
+ } else {
510
+ switch (alignment) {
511
+ case "start":
512
+ y = refRect.top;
513
+ break;
514
+ case "end":
515
+ y = refRect.bottom - floatingRect.height;
516
+ break;
517
+ default:
518
+ y = refRect.top + (refRect.height - floatingRect.height) / 2;
519
+ break;
520
+ }
521
+ }
522
+ return { x, y };
523
+ }
524
+ function wouldOverflow(x, y, floatingRect, placement) {
525
+ const [side] = placement.split("-");
526
+ const vw = window.innerWidth;
527
+ const vh = window.innerHeight;
528
+ switch (side) {
529
+ case "bottom":
530
+ return y + floatingRect.height > vh;
531
+ case "top":
532
+ return y < 0;
533
+ case "left":
534
+ return x < 0;
535
+ case "right":
536
+ return x + floatingRect.width > vw;
537
+ default:
538
+ return false;
539
+ }
540
+ }
541
+ function clampToViewport(x, y, floatingRect) {
542
+ const vw = window.innerWidth;
543
+ const vh = window.innerHeight;
544
+ const margin = 4;
545
+ return {
546
+ x: Math.max(margin, Math.min(x, vw - floatingRect.width - margin)),
547
+ y: Math.max(margin, Math.min(y, vh - floatingRect.height - margin))
548
+ };
549
+ }
550
+ function computeWithFallback(reference, floating, options = {}) {
551
+ const { placement = "bottom-start", offset = 0, flip = true } = options;
552
+ const refRect = reference.getBoundingClientRect();
553
+ const floatingRect = floating.getBoundingClientRect();
554
+ let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset);
555
+ let actualPlacement = placement;
556
+ if (flip && wouldOverflow(x, y, floatingRect, placement)) {
557
+ const flipped = getOppositePlacement(placement);
558
+ const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset);
559
+ if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
560
+ x = flippedPos.x;
561
+ y = flippedPos.y;
562
+ actualPlacement = flipped;
563
+ }
564
+ }
565
+ const clamped = clampToViewport(x, y, floatingRect);
566
+ return { x: clamped.x, y: clamped.y, placement: actualPlacement };
567
+ }
568
+ const anchorStyleId = "inertiaui-anchor-styles";
569
+ function ensureAnchorStylesheet() {
570
+ let style = document.getElementById(anchorStyleId);
571
+ if (!style) {
572
+ style = document.createElement("style");
573
+ style.id = anchorStyleId;
574
+ document.head.appendChild(style);
575
+ }
576
+ return style.sheet;
577
+ }
578
+ function findAnchorClass(element) {
579
+ return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
580
+ }
581
+ function setupAnchorPositioning(reference, floating, placement, offset, flip) {
582
+ const id = generateId(ANCHOR_CLASS_PREFIX);
583
+ const anchorName = `--${id}`;
584
+ reference.style.anchorName = anchorName;
585
+ floating.style.positionAnchor = anchorName;
586
+ floating.style.position = "fixed";
587
+ const [side, alignment] = placement.split("-");
588
+ const sheet = ensureAnchorStylesheet();
589
+ const className = id;
590
+ let positionRules = "";
591
+ let tryFallback = "";
592
+ switch (side) {
593
+ case "bottom":
594
+ positionRules += `top: anchor(bottom);`;
595
+ positionRules += `margin-top: ${offset}px;`;
596
+ break;
597
+ case "top":
598
+ positionRules += `bottom: anchor(top);`;
599
+ positionRules += `margin-bottom: ${offset}px;`;
600
+ break;
601
+ case "left":
602
+ positionRules += `right: anchor(left);`;
603
+ positionRules += `margin-right: ${offset}px;`;
604
+ break;
605
+ case "right":
606
+ positionRules += `left: anchor(right);`;
607
+ positionRules += `margin-left: ${offset}px;`;
608
+ break;
609
+ }
610
+ if (side === "bottom" || side === "top") {
611
+ switch (alignment) {
612
+ case "start":
613
+ positionRules += `left: anchor(left);`;
614
+ break;
615
+ case "end":
616
+ positionRules += `right: anchor(right);`;
617
+ break;
618
+ default:
619
+ positionRules += `left: anchor(center); translate: -50% 0;`;
620
+ break;
621
+ }
622
+ } else {
623
+ switch (alignment) {
624
+ case "start":
625
+ positionRules += `top: anchor(top);`;
626
+ break;
627
+ case "end":
628
+ positionRules += `bottom: anchor(bottom);`;
629
+ break;
630
+ default:
631
+ positionRules += `top: anchor(center); translate: 0 -50%;`;
632
+ break;
633
+ }
634
+ }
635
+ if (flip) {
636
+ tryFallback = `position-try-fallbacks: flip-block, flip-inline;`;
637
+ }
638
+ const rule = `.${className} { ${positionRules} ${tryFallback} }`;
639
+ sheet.insertRule(rule, sheet.cssRules.length);
640
+ floating.classList.add(className);
641
+ return className;
642
+ }
643
+ function cleanupAnchorPositioning(reference, floating, className) {
644
+ reference.style.anchorName = "";
645
+ floating.style.positionAnchor = "";
646
+ floating.style.position = "";
647
+ floating.classList.remove(className);
648
+ const style = document.getElementById(anchorStyleId);
649
+ if (style == null ? void 0 : style.sheet) {
650
+ for (let i = 0; i < style.sheet.cssRules.length; i++) {
651
+ const rule = style.sheet.cssRules[i];
652
+ if (rule.selectorText === `.${className}`) {
653
+ style.sheet.deleteRule(i);
654
+ break;
655
+ }
656
+ }
657
+ }
658
+ }
659
+ function computePosition(reference, floating, options = {}) {
660
+ const { placement = "bottom-start", offset = 0, flip = true } = options;
661
+ if (supportsAnchorPositioning()) {
662
+ const existingClass = findAnchorClass(floating);
663
+ if (!existingClass) {
664
+ setupAnchorPositioning(reference, floating, placement, offset, flip);
665
+ }
666
+ const rect = floating.getBoundingClientRect();
667
+ return { x: rect.left, y: rect.top, placement };
668
+ }
669
+ const result = computeWithFallback(reference, floating, { placement, offset, flip });
670
+ floating.style.position = "fixed";
671
+ floating.style.top = `${result.y}px`;
672
+ floating.style.left = `${result.x}px`;
673
+ return result;
674
+ }
675
+ function autoUpdate(reference, floating, update) {
676
+ let rafId;
677
+ function scheduleUpdate() {
678
+ if (rafId !== void 0) {
679
+ return;
680
+ }
681
+ rafId = requestAnimationFrame(() => {
682
+ rafId = void 0;
683
+ update();
684
+ });
685
+ }
686
+ window.addEventListener("resize", scheduleUpdate);
687
+ window.addEventListener("scroll", scheduleUpdate, true);
688
+ const resizeObserver = new ResizeObserver(scheduleUpdate);
689
+ resizeObserver.observe(reference);
690
+ resizeObserver.observe(floating);
691
+ let cleaned = false;
692
+ return function cleanup() {
693
+ if (cleaned) {
694
+ return;
695
+ }
696
+ cleaned = true;
697
+ if (rafId !== void 0) {
698
+ cancelAnimationFrame(rafId);
699
+ }
700
+ window.removeEventListener("resize", scheduleUpdate);
701
+ window.removeEventListener("scroll", scheduleUpdate, true);
702
+ resizeObserver.disconnect();
703
+ const anchorClass = findAnchorClass(floating);
704
+ if (anchorClass) {
705
+ cleanupAnchorPositioning(reference, floating, anchorClass);
706
+ }
707
+ };
708
+ }
286
709
  export {
287
710
  animate,
711
+ autoUpdate,
288
712
  cancelAnimations,
713
+ computePosition,
289
714
  createFocusTrap,
715
+ createMenuNavigation,
290
716
  easings,
291
717
  except,
292
718
  generateId,
@@ -294,8 +720,10 @@ export {
294
720
  kebabCase,
295
721
  lockScroll,
296
722
  markAriaHidden,
723
+ onClickOutside,
297
724
  onEscapeKey,
298
725
  only,
299
726
  rejectNullValues,
300
- sameUrlPath
727
+ sameUrlPath,
728
+ supportsAnchorPositioning
301
729
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",
@@ -37,12 +37,14 @@
37
37
  "dev": "vite build --watch",
38
38
  "build": "vite build",
39
39
  "lint": "eslint src/",
40
- "format": "prettier --write src/ tests/",
41
- "format:check": "prettier --check src/ tests/",
40
+ "format": "prettier --write src/ e2e/",
41
+ "format:check": "prettier --check src/ e2e/",
42
42
  "test": "vitest",
43
+ "test:e2e": "playwright test",
43
44
  "prepublishOnly": "npm run build"
44
45
  },
45
46
  "devDependencies": {
47
+ "@playwright/test": "^1.58.2",
46
48
  "@typescript-eslint/eslint-plugin": "^8.0.0",
47
49
  "@typescript-eslint/parser": "^8.0.0",
48
50
  "@vitest/coverage-v8": "^3.1.0",