@inertiaui/vanilla 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Inertia UI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,655 @@
1
+ # Inertia UI Vanilla
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.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @inertiaui/vanilla
9
+ ```
10
+
11
+ ## Table of Contents
12
+
13
+ - [Scroll Locking](#scroll-locking)
14
+ - [Focus Management](#focus-management)
15
+ - [Keyboard Events](#keyboard-events)
16
+ - [Accessibility](#accessibility)
17
+ - [Animation](#animation)
18
+ - [Helpers](#helpers)
19
+ - [generateId](#generateid)
20
+ - [Object Filtering](#object-filtering)
21
+ - [String Utilities](#string-utilities)
22
+ - [URL Utilities](#url-utilities)
23
+
24
+ ## Scroll Locking
25
+
26
+ The `lockScroll` function prevents body scroll while dialogs or modals are open, with reference counting support for nested dialogs.
27
+
28
+ ### Basic Usage
29
+
30
+ ```typescript
31
+ import { lockScroll } from '@inertiaui/vanilla'
32
+
33
+ const unlock = lockScroll()
34
+
35
+ // Later, unlock
36
+ unlock()
37
+ ```
38
+
39
+ The function:
40
+ - Sets `document.body.style.overflow` to `'hidden'`
41
+ - Adds padding to compensate for scrollbar width (prevents layout shift)
42
+ - Returns a cleanup function that can only unlock once
43
+
44
+ ### Reference Counting
45
+
46
+ Multiple calls to `lockScroll` are reference counted. The body scroll is only restored when all locks are released:
47
+
48
+ ```typescript
49
+ import { lockScroll } from '@inertiaui/vanilla'
50
+
51
+ const unlock1 = lockScroll()
52
+ const unlock2 = lockScroll()
53
+
54
+ // Body is locked
55
+
56
+ unlock1()
57
+ // Body is still locked (one reference remaining)
58
+
59
+ unlock2()
60
+ // Body scroll is restored
61
+ ```
62
+
63
+ ### Idempotent Unlock
64
+
65
+ Each cleanup function can only unlock once, preventing accidental double-unlocking:
66
+
67
+ ```typescript
68
+ const unlock = lockScroll()
69
+ unlock() // Decrements count
70
+ unlock() // No effect
71
+ unlock() // No effect
72
+ ```
73
+
74
+ ## Focus Management
75
+
76
+ Focus management utilities help create accessible dialogs by trapping focus and managing focusable elements.
77
+
78
+ ### createFocusTrap
79
+
80
+ Creates a focus trap within a container element.
81
+
82
+ ```typescript
83
+ import { createFocusTrap } from '@inertiaui/vanilla'
84
+
85
+ const cleanup = createFocusTrap(container, {
86
+ initialFocus: true,
87
+ initialFocusElement: null,
88
+ returnFocus: true,
89
+ })
90
+
91
+ // Later, remove the focus trap
92
+ cleanup()
93
+ ```
94
+
95
+ #### Options
96
+
97
+ | Option | Type | Default | Description |
98
+ |--------|------|---------|-------------|
99
+ | `initialFocus` | `boolean` | `true` | Focus first element immediately |
100
+ | `initialFocusElement` | `HTMLElement \| null` | `null` | Specific element to focus initially |
101
+ | `returnFocus` | `boolean` | `true` | Return focus to previous element on cleanup |
102
+
103
+ #### Behavior
104
+
105
+ The focus trap:
106
+ - Listens for Tab key and wraps focus at container boundaries
107
+ - Prevents focus from leaving the container via Tab or Shift+Tab
108
+ - Catches focus that escapes (e.g., via mouse click outside)
109
+ - Optionally focuses the first focusable element on creation
110
+ - Optionally returns focus to the previously focused element on cleanup
111
+
112
+ ```typescript
113
+ const container = document.getElementById('dialog')
114
+ const submitButton = document.getElementById('submit')
115
+
116
+ const cleanup = createFocusTrap(container, {
117
+ initialFocus: true,
118
+ initialFocusElement: submitButton, // Focus submit button instead of first element
119
+ returnFocus: true,
120
+ })
121
+ ```
122
+
123
+ #### Focusable Elements
124
+
125
+ The focus trap recognizes these elements as focusable:
126
+ - `a[href]`
127
+ - `button:not([disabled])`
128
+ - `textarea:not([disabled])`
129
+ - `input:not([disabled])`
130
+ - `select:not([disabled])`
131
+ - `[tabindex]:not([tabindex="-1"])`
132
+
133
+ Elements with `aria-hidden` or `disabled` attributes are excluded.
134
+
135
+ ## Keyboard Events
136
+
137
+ ### onEscapeKey
138
+
139
+ Registers an Escape key handler.
140
+
141
+ ```typescript
142
+ import { onEscapeKey } from '@inertiaui/vanilla'
143
+
144
+ const cleanup = onEscapeKey((event) => {
145
+ console.log('Escape pressed!')
146
+ })
147
+
148
+ // Later, remove the handler
149
+ cleanup()
150
+ ```
151
+
152
+ #### Options
153
+
154
+ | Option | Type | Default | Description |
155
+ |--------|------|---------|-------------|
156
+ | `preventDefault` | `boolean` | `false` | Call `event.preventDefault()` |
157
+ | `stopPropagation` | `boolean` | `false` | Call `event.stopPropagation()` |
158
+
159
+ ```typescript
160
+ const cleanup = onEscapeKey(handleEscape, {
161
+ preventDefault: true,
162
+ stopPropagation: true,
163
+ })
164
+ ```
165
+
166
+ ### Cleanup Pattern
167
+
168
+ The cleanup function pattern integrates well with framework lifecycle hooks:
169
+
170
+ ```typescript
171
+ // Vue
172
+ onMounted(() => {
173
+ cleanup = onEscapeKey(close)
174
+ })
175
+ onUnmounted(() => {
176
+ cleanup()
177
+ })
178
+
179
+ // React
180
+ useEffect(() => {
181
+ const cleanup = onEscapeKey(close)
182
+ return cleanup
183
+ }, [])
184
+ ```
185
+
186
+ ## Accessibility
187
+
188
+ Accessibility utilities for managing `aria-hidden` attributes with reference counting support.
189
+
190
+ ### markAriaHidden
191
+
192
+ Marks an element as `aria-hidden="true"` and returns a cleanup function.
193
+
194
+ ```typescript
195
+ import { markAriaHidden } from '@inertiaui/vanilla'
196
+
197
+ const cleanup = markAriaHidden('#app')
198
+
199
+ // Later, restore
200
+ cleanup()
201
+ ```
202
+
203
+ Accepts either an element or a CSS selector:
204
+
205
+ ```typescript
206
+ // Using selector
207
+ const cleanup = markAriaHidden('#app')
208
+
209
+ // Using element
210
+ const element = document.getElementById('app')
211
+ const cleanup = markAriaHidden(element)
212
+ ```
213
+
214
+ ### Reference Counting
215
+
216
+ Like scroll locking, `aria-hidden` management uses reference counting for nested dialogs:
217
+
218
+ ```typescript
219
+ import { markAriaHidden } from '@inertiaui/vanilla'
220
+
221
+ const cleanup1 = markAriaHidden('#app')
222
+ const cleanup2 = markAriaHidden('#app')
223
+
224
+ // Element is aria-hidden="true"
225
+
226
+ cleanup1()
227
+ // Element is still aria-hidden="true" (one reference remaining)
228
+
229
+ cleanup2()
230
+ // Element's aria-hidden is restored to original value
231
+ ```
232
+
233
+ ### Original Value Preservation
234
+
235
+ The original `aria-hidden` value is preserved and restored:
236
+
237
+ ```typescript
238
+ const element = document.getElementById('sidebar')
239
+ element.setAttribute('aria-hidden', 'false')
240
+
241
+ const cleanup = markAriaHidden(element)
242
+ console.log(element.getAttribute('aria-hidden')) // 'true'
243
+
244
+ cleanup()
245
+ console.log(element.getAttribute('aria-hidden')) // 'false' (restored)
246
+ ```
247
+
248
+ If the element had no `aria-hidden` attribute, the attribute is removed on cleanup:
249
+
250
+ ```typescript
251
+ const element = document.getElementById('main')
252
+ // No aria-hidden attribute
253
+
254
+ const cleanup = markAriaHidden(element)
255
+ console.log(element.getAttribute('aria-hidden')) // 'true'
256
+
257
+ cleanup()
258
+ console.log(element.getAttribute('aria-hidden')) // null (removed)
259
+ ```
260
+
261
+ ### Use with Dialogs
262
+
263
+ When a dialog opens, the main content should be marked as `aria-hidden` to prevent screen readers from reading background content:
264
+
265
+ ```typescript
266
+ import { markAriaHidden, lockScroll, createFocusTrap, onEscapeKey } from '@inertiaui/vanilla'
267
+
268
+ function openDialog(dialogElement: HTMLElement) {
269
+ const cleanups = [
270
+ markAriaHidden('#app'),
271
+ lockScroll(),
272
+ createFocusTrap(dialogElement),
273
+ onEscapeKey(() => closeDialog()),
274
+ ]
275
+
276
+ return () => cleanups.forEach(cleanup => cleanup())
277
+ }
278
+ ```
279
+
280
+ ## Animation
281
+
282
+ The animation module provides a simple wrapper around the Web Animations API with Tailwind CSS-compatible easing functions.
283
+
284
+ ### animate
285
+
286
+ Animate an element using the Web Animations API. Returns a promise that resolves when the animation completes.
287
+
288
+ ```typescript
289
+ import { animate } from '@inertiaui/vanilla'
290
+
291
+ await animate(element, [
292
+ { transform: 'scale(0.95)', opacity: 0 },
293
+ { transform: 'scale(1)', opacity: 1 }
294
+ ])
295
+ ```
296
+
297
+ #### Options
298
+
299
+ | Option | Type | Default | Description |
300
+ |--------|------|---------|-------------|
301
+ | `duration` | `number` | `300` | Animation duration in milliseconds |
302
+ | `easing` | `string \| EasingName` | `'inOut'` | Easing function (see below) |
303
+ | `fill` | `FillMode` | `'forwards'` | Animation fill mode |
304
+
305
+ ```typescript
306
+ await animate(element, keyframes, { duration: 200, easing: 'out' })
307
+ ```
308
+
309
+ ### easings
310
+
311
+ Pre-defined easing functions matching Tailwind CSS:
312
+
313
+ ```typescript
314
+ import { easings } from '@inertiaui/vanilla'
315
+
316
+ // Available easings:
317
+ easings.linear // 'linear'
318
+ easings.in // 'cubic-bezier(0.4, 0, 1, 1)'
319
+ easings.out // 'cubic-bezier(0, 0, 0.2, 1)'
320
+ easings.inOut // 'cubic-bezier(0.4, 0, 0.2, 1)'
321
+ ```
322
+
323
+ You can use easing names directly:
324
+
325
+ ```typescript
326
+ await animate(element, keyframes, { easing: 'out' })
327
+ ```
328
+
329
+ Or provide a custom easing string:
330
+
331
+ ```typescript
332
+ await animate(element, keyframes, { easing: 'cubic-bezier(0.68, -0.55, 0.27, 1.55)' })
333
+ ```
334
+
335
+ ### cancelAnimations
336
+
337
+ Cancel any running animations on an element:
338
+
339
+ ```typescript
340
+ import { cancelAnimations } from '@inertiaui/vanilla'
341
+
342
+ cancelAnimations(element)
343
+ ```
344
+
345
+ ### Full Example
346
+
347
+ ```typescript
348
+ import { animate, cancelAnimations } from '@inertiaui/vanilla'
349
+
350
+ async function showModal(modal: HTMLElement) {
351
+ modal.hidden = false
352
+
353
+ await animate(modal, [
354
+ { transform: 'scale(0.95)', opacity: 0 },
355
+ { transform: 'scale(1)', opacity: 1 }
356
+ ], { duration: 150, easing: 'out' })
357
+ }
358
+
359
+ async function hideModal(modal: HTMLElement) {
360
+ await animate(modal, [
361
+ { transform: 'scale(1)', opacity: 1 },
362
+ { transform: 'scale(0.95)', opacity: 0 }
363
+ ], { duration: 100, easing: 'in' })
364
+
365
+ modal.hidden = true
366
+ }
367
+
368
+ function forceHideModal(modal: HTMLElement) {
369
+ cancelAnimations(modal)
370
+ modal.hidden = true
371
+ }
372
+ ```
373
+
374
+ ## Helpers
375
+
376
+ ### generateId
377
+
378
+ Generates a unique ID using `crypto.randomUUID()` with a fallback for environments where it's not available.
379
+
380
+ ```typescript
381
+ import { generateId } from '@inertiaui/vanilla'
382
+
383
+ const id = generateId()
384
+ // 'inertiaui_550e8400-e29b-41d4-a716-446655440000'
385
+ ```
386
+
387
+ #### Custom Prefix
388
+
389
+ ```typescript
390
+ const id = generateId('modal_')
391
+ // 'modal_550e8400-e29b-41d4-a716-446655440000'
392
+
393
+ const id = generateId('dialog-')
394
+ // 'dialog-550e8400-e29b-41d4-a716-446655440000'
395
+ ```
396
+
397
+ #### Fallback
398
+
399
+ In environments where `crypto.randomUUID()` is not available, the function falls back to a combination of timestamp and random string:
400
+
401
+ ```typescript
402
+ // Fallback format:
403
+ // '{prefix}{timestamp}_{random}'
404
+ // 'inertiaui_m5x2k9p_7h3j5k9a2'
405
+ ```
406
+
407
+ #### Use Cases
408
+
409
+ Useful for generating unique IDs for:
410
+ - Dialog instances
411
+ - Form elements requiring unique IDs
412
+ - Accessibility attributes (`aria-labelledby`, `aria-describedby`)
413
+ - Tracking modal instances
414
+
415
+ ```typescript
416
+ const dialogId = generateId('dialog_')
417
+ const titleId = generateId('title_')
418
+ const descId = generateId('desc_')
419
+
420
+ dialog.setAttribute('aria-labelledby', titleId)
421
+ dialog.setAttribute('aria-describedby', descId)
422
+ title.id = titleId
423
+ description.id = descId
424
+ ```
425
+
426
+ ### Object Filtering
427
+
428
+ #### except
429
+
430
+ Returns an object or array without the specified keys/elements.
431
+
432
+ **Objects:**
433
+
434
+ ```typescript
435
+ import { except } from '@inertiaui/vanilla'
436
+
437
+ const obj = { a: 1, b: 2, c: 3 }
438
+ except(obj, ['b'])
439
+ // { a: 1, c: 3 }
440
+ ```
441
+
442
+ **Arrays:**
443
+
444
+ ```typescript
445
+ const arr = ['a', 'b', 'c', 'd']
446
+ except(arr, ['b', 'd'])
447
+ // ['a', 'c']
448
+ ```
449
+
450
+ **Case-Insensitive Matching:**
451
+
452
+ ```typescript
453
+ const obj = { Name: 1, AGE: 2, city: 3 }
454
+ except(obj, ['name', 'age'], true)
455
+ // { city: 3 }
456
+
457
+ const arr = ['Name', 'AGE', 'city']
458
+ except(arr, ['name', 'age'], true)
459
+ // ['city']
460
+ ```
461
+
462
+ #### only
463
+
464
+ Returns an object or array with only the specified keys/elements.
465
+
466
+ **Objects:**
467
+
468
+ ```typescript
469
+ import { only } from '@inertiaui/vanilla'
470
+
471
+ const obj = { a: 1, b: 2, c: 3 }
472
+ only(obj, ['a', 'c'])
473
+ // { a: 1, c: 3 }
474
+ ```
475
+
476
+ **Arrays:**
477
+
478
+ ```typescript
479
+ const arr = ['a', 'b', 'c', 'd']
480
+ only(arr, ['b', 'd'])
481
+ // ['b', 'd']
482
+ ```
483
+
484
+ **Case-Insensitive Matching:**
485
+
486
+ ```typescript
487
+ const obj = { Name: 1, AGE: 2, city: 3 }
488
+ only(obj, ['name', 'city'], true)
489
+ // { Name: 1, city: 3 }
490
+ ```
491
+
492
+ #### rejectNullValues
493
+
494
+ Removes null values from an object or array.
495
+
496
+ **Objects:**
497
+
498
+ ```typescript
499
+ import { rejectNullValues } from '@inertiaui/vanilla'
500
+
501
+ const obj = { a: 1, b: null, c: 3 }
502
+ rejectNullValues(obj)
503
+ // { a: 1, c: 3 }
504
+ ```
505
+
506
+ **Arrays:**
507
+
508
+ ```typescript
509
+ const arr = [1, null, 3, null, 5]
510
+ rejectNullValues(arr)
511
+ // [1, 3, 5]
512
+ ```
513
+
514
+ > **Note:** `rejectNullValues` only removes `null` values, not `undefined`. Use this when you want to keep `undefined` values but remove explicit nulls.
515
+
516
+ ### String Utilities
517
+
518
+ #### kebabCase
519
+
520
+ Converts a string to kebab-case.
521
+
522
+ ```typescript
523
+ import { kebabCase } from '@inertiaui/vanilla'
524
+
525
+ kebabCase('camelCase') // 'camel-case'
526
+ kebabCase('PascalCase') // 'pascal-case'
527
+ kebabCase('snake_case') // 'snake-case'
528
+ kebabCase('already-kebab') // 'already-kebab'
529
+ ```
530
+
531
+ **Handling Special Cases:**
532
+
533
+ ```typescript
534
+ kebabCase('user123Name') // 'user123-name'
535
+ kebabCase('multiple__underscores') // 'multiple-underscores'
536
+ kebabCase('UPPERCASE') // 'u-p-p-e-r-c-a-s-e'
537
+ ```
538
+
539
+ #### isStandardDomEvent
540
+
541
+ Checks if an event name is a standard DOM event.
542
+
543
+ ```typescript
544
+ import { isStandardDomEvent } from '@inertiaui/vanilla'
545
+
546
+ isStandardDomEvent('onClick') // true
547
+ isStandardDomEvent('onMouseOver') // true
548
+ isStandardDomEvent('onKeyDown') // true
549
+ isStandardDomEvent('onCustom') // false
550
+ ```
551
+
552
+ **Supported Event Categories:**
553
+
554
+ - Mouse events: `click`, `dblclick`, `mousedown`, `mouseup`, `mouseover`, `mouseout`, `mousemove`, `mouseenter`, `mouseleave`
555
+ - Keyboard events: `keydown`, `keyup`, `keypress`
556
+ - Form events: `focus`, `blur`, `change`, `input`, `submit`, `reset`
557
+ - Window events: `load`, `unload`, `error`, `resize`, `scroll`
558
+ - Touch events: `touchstart`, `touchend`, `touchmove`, `touchcancel`
559
+ - Pointer events: `pointerdown`, `pointerup`, `pointermove`, `pointerenter`, `pointerleave`, `pointercancel`
560
+ - Drag events: `drag`, `dragstart`, `dragend`, `dragenter`, `dragleave`, `dragover`, `drop`
561
+ - Animation events: `animationstart`, `animationend`, `animationiteration`
562
+ - Transition events: `transitionstart`, `transitionend`, `transitionrun`, `transitioncancel`
563
+
564
+ **Case Insensitive:**
565
+
566
+ ```typescript
567
+ isStandardDomEvent('onclick') // true
568
+ isStandardDomEvent('ONCLICK') // true
569
+ isStandardDomEvent('OnClick') // true
570
+ ```
571
+
572
+ **Use Case:**
573
+
574
+ Useful for distinguishing between standard DOM events and custom events when processing event handlers:
575
+
576
+ ```typescript
577
+ const props = {
578
+ onClick: handleClick,
579
+ onMouseOver: handleHover,
580
+ onModalReady: handleModalReady,
581
+ onUserUpdated: handleUserUpdated,
582
+ }
583
+
584
+ const domEvents = {}
585
+ const customEvents = {}
586
+
587
+ for (const [key, value] of Object.entries(props)) {
588
+ if (isStandardDomEvent(key)) {
589
+ domEvents[key] = value
590
+ } else {
591
+ customEvents[key] = value
592
+ }
593
+ }
594
+
595
+ // domEvents: { onClick, onMouseOver }
596
+ // customEvents: { onModalReady, onUserUpdated }
597
+ ```
598
+
599
+ ### URL Utilities
600
+
601
+ #### sameUrlPath
602
+
603
+ Compares two URLs to determine if they have the same origin and pathname, ignoring query strings and hash fragments.
604
+
605
+ ```typescript
606
+ import { sameUrlPath } from '@inertiaui/vanilla'
607
+
608
+ sameUrlPath('/users/1', '/users/1') // true
609
+ sameUrlPath('/users/1', '/users/1?tab=posts') // true
610
+ sameUrlPath('/users/1', '/users/2') // false
611
+ sameUrlPath('/users', '/posts') // false
612
+ ```
613
+
614
+ **Accepts URL objects:**
615
+
616
+ ```typescript
617
+ const url1 = new URL('https://example.com/users/1')
618
+ const url2 = new URL('https://example.com/users/1?page=2')
619
+
620
+ sameUrlPath(url1, url2) // true
621
+ ```
622
+
623
+ **Handles null/undefined:**
624
+
625
+ ```typescript
626
+ sameUrlPath(null, '/users') // false
627
+ sameUrlPath('/users', undefined) // false
628
+ sameUrlPath(null, null) // false
629
+ ```
630
+
631
+ **Use Case:**
632
+
633
+ Useful for determining active navigation states or comparing the current route with a link destination:
634
+
635
+ ```typescript
636
+ const isActive = sameUrlPath(window.location.href, linkHref)
637
+ ```
638
+
639
+ ## TypeScript
640
+
641
+ This library is written in TypeScript and exports the following types:
642
+
643
+ ```typescript
644
+ import type {
645
+ CleanupFunction,
646
+ FocusTrapOptions,
647
+ EscapeKeyOptions,
648
+ AnimateOptions,
649
+ EasingName,
650
+ } from '@inertiaui/vanilla'
651
+ ```
652
+
653
+ ## License
654
+
655
+ MIT
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tailwind CSS easing functions
3
+ */
4
+ export declare const easings: {
5
+ readonly linear: "linear";
6
+ readonly in: "cubic-bezier(0.4, 0, 1, 1)";
7
+ readonly out: "cubic-bezier(0, 0, 0.2, 1)";
8
+ readonly inOut: "cubic-bezier(0.4, 0, 0.2, 1)";
9
+ };
10
+ export type EasingName = keyof typeof easings;
11
+ export interface AnimateOptions {
12
+ duration?: number;
13
+ easing?: string | EasingName;
14
+ fill?: FillMode;
15
+ }
16
+ /**
17
+ * Animate an element using the Web Animations API.
18
+ * Returns a promise that resolves when the animation completes.
19
+ *
20
+ * @example
21
+ * await animate(element, [
22
+ * { transform: 'scale(0.95)', opacity: 0 },
23
+ * { transform: 'scale(1)', opacity: 1 }
24
+ * ])
25
+ *
26
+ * @example
27
+ * await animate(element, keyframes.fadeIn, { duration: 200 })
28
+ */
29
+ export declare function animate(element: HTMLElement, keyframes: Keyframe[], options?: AnimateOptions): Promise<Animation>;
30
+ /**
31
+ * Cancel any running animations on an element
32
+ */
33
+ export declare function cancelAnimations(element: HTMLElement): void;
@@ -0,0 +1,14 @@
1
+ export type CleanupFunction = () => void;
2
+ export declare function lockScroll(): CleanupFunction;
3
+ export interface FocusTrapOptions {
4
+ initialFocus?: boolean;
5
+ initialFocusElement?: HTMLElement | null;
6
+ returnFocus?: boolean;
7
+ }
8
+ export declare function createFocusTrap(container: HTMLElement, options?: FocusTrapOptions): CleanupFunction;
9
+ export interface EscapeKeyOptions {
10
+ preventDefault?: boolean;
11
+ stopPropagation?: boolean;
12
+ }
13
+ export declare function onEscapeKey(callback: (event: KeyboardEvent) => void, options?: EscapeKeyOptions): CleanupFunction;
14
+ export declare function markAriaHidden(elementOrSelector: Element | string): CleanupFunction;
@@ -0,0 +1,10 @@
1
+ export declare function generateId(prefix?: string): string;
2
+ export declare function except<T extends Record<string, unknown>>(target: T, keys: string[], ignoreCase?: boolean): Partial<T>;
3
+ export declare function except(target: string[], keys: string[], ignoreCase?: boolean): string[];
4
+ export declare function only<T extends Record<string, unknown>>(target: T, keys: string[], ignoreCase?: boolean): Partial<T>;
5
+ export declare function only(target: string[], keys: string[], ignoreCase?: boolean): string[];
6
+ export declare function rejectNullValues<T>(target: T[]): NonNullable<T>[];
7
+ export declare function rejectNullValues<T extends Record<string, unknown>>(target: T): Partial<T>;
8
+ export declare function kebabCase(string: string): string;
9
+ export declare function isStandardDomEvent(eventName: string): boolean;
10
+ export declare function sameUrlPath(url1: string | URL | undefined | null, url2: string | URL | undefined | null): boolean;
@@ -0,0 +1,5 @@
1
+ export { generateId, except, only, rejectNullValues, kebabCase, isStandardDomEvent, sameUrlPath } from './helpers';
2
+ export { easings, animate, cancelAnimations } from './animate';
3
+ export type { EasingName, AnimateOptions } from './animate';
4
+ export { lockScroll, createFocusTrap, onEscapeKey, markAriaHidden } from './dialog';
5
+ export type { CleanupFunction, FocusTrapOptions, EscapeKeyOptions } from './dialog';
package/dist/index.js ADDED
@@ -0,0 +1,282 @@
1
+ function generateId(prefix = "inertiaui_") {
2
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
3
+ return `${prefix}${crypto.randomUUID()}`;
4
+ }
5
+ return `${prefix}${Date.now().toString(36)}_${Math.random().toString(36).substr(2, 9)}`;
6
+ }
7
+ function strToLowercase(key) {
8
+ return typeof key === "string" ? key.toLowerCase() : key;
9
+ }
10
+ function except(target, keys, ignoreCase = false) {
11
+ if (ignoreCase) {
12
+ keys = keys.map(strToLowercase);
13
+ }
14
+ if (Array.isArray(target)) {
15
+ return target.filter((key) => !keys.includes(ignoreCase ? strToLowercase(key) : key));
16
+ }
17
+ return Object.keys(target).reduce((acc, key) => {
18
+ if (!keys.includes(ignoreCase ? strToLowercase(key) : key)) {
19
+ acc[key] = target[key];
20
+ }
21
+ return acc;
22
+ }, {});
23
+ }
24
+ function only(target, keys, ignoreCase = false) {
25
+ if (ignoreCase) {
26
+ keys = keys.map(strToLowercase);
27
+ }
28
+ if (Array.isArray(target)) {
29
+ return target.filter((key) => keys.includes(ignoreCase ? strToLowercase(key) : key));
30
+ }
31
+ return Object.keys(target).reduce((acc, key) => {
32
+ if (keys.includes(ignoreCase ? strToLowercase(key) : key)) {
33
+ acc[key] = target[key];
34
+ }
35
+ return acc;
36
+ }, {});
37
+ }
38
+ function rejectNullValues(target) {
39
+ if (Array.isArray(target)) {
40
+ return target.filter((item) => item !== null);
41
+ }
42
+ return Object.keys(target).reduce((acc, key) => {
43
+ if (key in target && target[key] !== null) {
44
+ acc[key] = target[key];
45
+ }
46
+ return acc;
47
+ }, {});
48
+ }
49
+ function kebabCase(string) {
50
+ if (!string) return "";
51
+ string = string.replace(/_/g, "-");
52
+ string = string.replace(/-+/g, "-");
53
+ if (!/[A-Z]/.test(string)) {
54
+ return string;
55
+ }
56
+ string = string.replace(/\s+/g, "").replace(/_/g, "").replace(/(?:^|\s|-)+([A-Za-z])/g, (_m, p1) => p1.toUpperCase());
57
+ string = string.replace(/(.)(?=[A-Z])/g, "$1-");
58
+ return string.toLowerCase();
59
+ }
60
+ function isStandardDomEvent(eventName) {
61
+ const lowerEventName = eventName.toLowerCase();
62
+ const standardPatterns = [
63
+ /^on(click|dblclick|mousedown|mouseup|mouseover|mouseout|mousemove|mouseenter|mouseleave)$/,
64
+ /^on(keydown|keyup|keypress)$/,
65
+ /^on(focus|blur|change|input|submit|reset)$/,
66
+ /^on(load|unload|error|resize|scroll)$/,
67
+ /^on(touchstart|touchend|touchmove|touchcancel)$/,
68
+ /^on(pointerdown|pointerup|pointermove|pointerenter|pointerleave|pointercancel)$/,
69
+ /^on(drag|dragstart|dragend|dragenter|dragleave|dragover|drop)$/,
70
+ /^on(animationstart|animationend|animationiteration)$/,
71
+ /^on(transitionstart|transitionend|transitionrun|transitioncancel)$/
72
+ ];
73
+ return standardPatterns.some((pattern) => pattern.test(lowerEventName));
74
+ }
75
+ function sameUrlPath(url1, url2) {
76
+ if (!url1 || !url2) {
77
+ return false;
78
+ }
79
+ const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
80
+ const parsed1 = typeof url1 === "string" ? new URL(url1, origin) : url1;
81
+ const parsed2 = typeof url2 === "string" ? new URL(url2, origin) : url2;
82
+ return `${parsed1.origin}${parsed1.pathname}` === `${parsed2.origin}${parsed2.pathname}`;
83
+ }
84
+ const easings = {
85
+ linear: "linear",
86
+ in: "cubic-bezier(0.4, 0, 1, 1)",
87
+ out: "cubic-bezier(0, 0, 0.2, 1)",
88
+ inOut: "cubic-bezier(0.4, 0, 0.2, 1)"
89
+ };
90
+ const defaultOptions = {
91
+ duration: 300,
92
+ easing: "inOut",
93
+ fill: "forwards"
94
+ };
95
+ function animate(element, keyframes, options = {}) {
96
+ const { duration, easing, fill } = { ...defaultOptions, ...options };
97
+ const resolvedEasing = easing in easings ? easings[easing] : easing;
98
+ const animation = element.animate(keyframes, {
99
+ duration,
100
+ easing: resolvedEasing,
101
+ fill
102
+ });
103
+ return animation.finished;
104
+ }
105
+ function cancelAnimations(element) {
106
+ element.getAnimations().forEach((animation) => animation.cancel());
107
+ }
108
+ const FOCUSABLE_SELECTORS = [
109
+ "a[href]",
110
+ "button:not([disabled])",
111
+ "textarea:not([disabled])",
112
+ "input:not([disabled])",
113
+ "select:not([disabled])",
114
+ '[tabindex]:not([tabindex="-1"])'
115
+ ].join(", ");
116
+ let scrollLockCount = 0;
117
+ let originalOverflow = "";
118
+ let originalPaddingRight = "";
119
+ function lockScroll() {
120
+ if (scrollLockCount === 0) {
121
+ originalOverflow = document.body.style.overflow;
122
+ originalPaddingRight = document.body.style.paddingRight;
123
+ const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
124
+ document.body.style.overflow = "hidden";
125
+ if (scrollbarWidth > 0) {
126
+ document.body.style.paddingRight = `${scrollbarWidth}px`;
127
+ }
128
+ }
129
+ scrollLockCount++;
130
+ let unlocked = false;
131
+ return function unlock() {
132
+ if (unlocked) {
133
+ return;
134
+ }
135
+ unlocked = true;
136
+ unlockScroll();
137
+ };
138
+ }
139
+ function unlockScroll() {
140
+ scrollLockCount = Math.max(0, scrollLockCount - 1);
141
+ if (scrollLockCount === 0) {
142
+ document.body.style.overflow = originalOverflow;
143
+ document.body.style.paddingRight = originalPaddingRight;
144
+ }
145
+ }
146
+ function getFocusableElements(container) {
147
+ if (!container) {
148
+ return [];
149
+ }
150
+ return Array.from(container.querySelectorAll(FOCUSABLE_SELECTORS)).filter(
151
+ (el) => !el.hasAttribute("disabled") && !el.getAttribute("aria-hidden")
152
+ );
153
+ }
154
+ function createFocusTrap(container, options = {}) {
155
+ const { initialFocus = true, initialFocusElement = null, returnFocus = true } = options;
156
+ const previouslyFocused = document.activeElement;
157
+ function handleKeyDown(event) {
158
+ if (event.key !== "Tab") {
159
+ return;
160
+ }
161
+ const focusableElements = getFocusableElements(container);
162
+ if (focusableElements.length === 0) {
163
+ return;
164
+ }
165
+ const firstElement = focusableElements[0];
166
+ const lastElement = focusableElements[focusableElements.length - 1];
167
+ if (event.shiftKey) {
168
+ if (document.activeElement === firstElement || !container.contains(document.activeElement)) {
169
+ event.preventDefault();
170
+ lastElement.focus();
171
+ }
172
+ } else {
173
+ if (document.activeElement === lastElement || !container.contains(document.activeElement)) {
174
+ event.preventDefault();
175
+ firstElement.focus();
176
+ }
177
+ }
178
+ }
179
+ function handleFocusIn(event) {
180
+ if (!container.contains(event.target)) {
181
+ const focusableElements = getFocusableElements(container);
182
+ if (focusableElements.length > 0) {
183
+ focusableElements[0].focus();
184
+ }
185
+ }
186
+ }
187
+ document.addEventListener("keydown", handleKeyDown);
188
+ document.addEventListener("focusin", handleFocusIn);
189
+ if (initialFocus) {
190
+ requestAnimationFrame(() => {
191
+ if (initialFocusElement && container.contains(initialFocusElement)) {
192
+ initialFocusElement.focus();
193
+ } else {
194
+ const focusableElements = getFocusableElements(container);
195
+ if (focusableElements.length > 0) {
196
+ focusableElements[0].focus();
197
+ }
198
+ }
199
+ });
200
+ }
201
+ return function cleanup() {
202
+ document.removeEventListener("keydown", handleKeyDown);
203
+ document.removeEventListener("focusin", handleFocusIn);
204
+ if (returnFocus && previouslyFocused && typeof previouslyFocused.focus === "function") {
205
+ previouslyFocused.focus();
206
+ }
207
+ };
208
+ }
209
+ function onEscapeKey(callback, options = {}) {
210
+ const { preventDefault = false, stopPropagation = false } = options;
211
+ function handler(event) {
212
+ if (event.key === "Escape") {
213
+ if (preventDefault) {
214
+ event.preventDefault();
215
+ }
216
+ if (stopPropagation) {
217
+ event.stopPropagation();
218
+ }
219
+ callback(event);
220
+ }
221
+ }
222
+ document.addEventListener("keydown", handler);
223
+ return function cleanup() {
224
+ document.removeEventListener("keydown", handler);
225
+ };
226
+ }
227
+ const ariaHiddenStack = [];
228
+ function markAriaHidden(elementOrSelector) {
229
+ const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
230
+ if (!element) {
231
+ return function noop() {
232
+ };
233
+ }
234
+ const existingIndex = ariaHiddenStack.findIndex((item) => item.element === element);
235
+ if (existingIndex >= 0) {
236
+ ariaHiddenStack[existingIndex].count++;
237
+ } else {
238
+ const originalValue = element.getAttribute("aria-hidden");
239
+ ariaHiddenStack.push({ element, originalValue, count: 1 });
240
+ element.setAttribute("aria-hidden", "true");
241
+ }
242
+ let cleaned = false;
243
+ return function cleanup() {
244
+ if (cleaned) {
245
+ return;
246
+ }
247
+ cleaned = true;
248
+ unmarkAriaHidden(element);
249
+ };
250
+ }
251
+ function unmarkAriaHidden(element) {
252
+ const index = ariaHiddenStack.findIndex((item) => item.element === element);
253
+ if (index < 0) {
254
+ return;
255
+ }
256
+ ariaHiddenStack[index].count--;
257
+ if (ariaHiddenStack[index].count <= 0) {
258
+ const { originalValue } = ariaHiddenStack[index];
259
+ if (originalValue === null) {
260
+ element.removeAttribute("aria-hidden");
261
+ } else {
262
+ element.setAttribute("aria-hidden", originalValue);
263
+ }
264
+ ariaHiddenStack.splice(index, 1);
265
+ }
266
+ }
267
+ export {
268
+ animate,
269
+ cancelAnimations,
270
+ createFocusTrap,
271
+ easings,
272
+ except,
273
+ generateId,
274
+ isStandardDomEvent,
275
+ kebabCase,
276
+ lockScroll,
277
+ markAriaHidden,
278
+ onEscapeKey,
279
+ only,
280
+ rejectNullValues,
281
+ sameUrlPath
282
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@inertiaui/vanilla",
3
+ "version": "0.1.2",
4
+ "author": "Pascal Baljet <pascal@protone.media>",
5
+ "private": false,
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "dev": "vite build --watch",
21
+ "build": "vite build && tsc --emitDeclarationOnly",
22
+ "lint": "eslint src/",
23
+ "format": "prettier --write src/ tests/",
24
+ "test": "vitest",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "devDependencies": {
28
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
29
+ "@typescript-eslint/parser": "^8.0.0",
30
+ "@vitest/coverage-v8": "^3.1.0",
31
+ "@vitest/ui": "^3.1.0",
32
+ "eslint": "^9.0.0",
33
+ "happy-dom": "^20.0.0",
34
+ "prettier": "^3.2.4",
35
+ "typescript": "^5.7.0",
36
+ "vite": "^6.1.0",
37
+ "vite-plugin-dts": "^4.5.0",
38
+ "vitest": "^3.1.0"
39
+ }
40
+ }