@inertiaui/vanilla 1.6.0 → 1.7.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,11 +1,14 @@
1
1
  # Inertia UI Vanilla
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@inertiaui/vanilla)](https://www.npmjs.com/package/@inertiaui/vanilla)
4
+
3
5
  A lightweight vanilla TypeScript library providing UI utilities for dialogs, animations, focus management, menu/listbox navigation, click outside detection, floating and native popover positioning, reorder interactions, color parsing, debounce helpers, and common helper functions. Framework-agnostic and designed to integrate seamlessly with Vue, React, or any JavaScript application.
4
6
 
5
7
  This package is part of the [Inertia UI](https://inertiaui.com) suite. Check out our other packages:
6
8
 
7
9
  - **[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
10
  - **[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.
11
+ - **[Inertia Forms](https://inertiaui.com/inertia-forms)**: Define forms in Laravel and render them with a single Vue or React component. Includes validation, file uploads, conditional fields, and multi-step flows.
9
12
 
10
13
  [![Inertia UI](https://inertiaui.com/visit-card.jpg)](https://inertiaui.com)
11
14
 
@@ -1035,7 +1038,7 @@ The helper is intentionally scoped to caller-selected variables. It does not obs
1035
1038
 
1036
1039
  ## Accessibility
1037
1040
 
1038
- Accessibility utilities for managing `aria-hidden` attributes with reference counting support.
1041
+ Accessibility utilities for managing `aria-hidden` attributes with reference counting support, and for announcing messages to screen readers.
1039
1042
 
1040
1043
  ### markAriaHidden
1041
1044
 
@@ -1144,6 +1147,39 @@ function openDialog(dialogElement: HTMLElement) {
1144
1147
  }
1145
1148
  ```
1146
1149
 
1150
+ ### createAnnouncer
1151
+
1152
+ Announces messages to screen readers through two live regions that you render: one polite and one assertive. Render both regions when the page loads and keep them in the DOM. A screen reader ignores text that a new live region contains when it appears.
1153
+
1154
+ ```html
1155
+ <div class="sr-only" role="status" aria-live="polite" aria-atomic="true"></div>
1156
+ <div class="sr-only" aria-live="assertive" aria-atomic="true"></div>
1157
+ ```
1158
+
1159
+ ```typescript
1160
+ import { createAnnouncer } from '@inertiaui/vanilla'
1161
+
1162
+ const announcer = createAnnouncer({
1163
+ polite: document.querySelector('[aria-live="polite"]')!,
1164
+ assertive: document.querySelector('[aria-live="assertive"]')!,
1165
+ })
1166
+
1167
+ announcer.announce('Invoice saved.', 'polite')
1168
+ announcer.announce('Payment failed.', 'assertive')
1169
+
1170
+ // When the regions unmount
1171
+ announcer.destroy()
1172
+ ```
1173
+
1174
+ The announcer writes only plain text to the regions, so a screen reader does not read buttons or other markup with the message. It also handles the timing that screen readers need:
1175
+
1176
+ - It writes nothing until 150ms after you create it, so the regions exist before their first text arrives.
1177
+ - It joins messages that arrive within 50ms into one announcement for each region.
1178
+ - It empties a region 1 second after its last write, so the virtual cursor does not find old messages.
1179
+ - It empties a region before it writes the same text again, so a repeated message is announced again.
1180
+
1181
+ `destroy()` cancels pending writes and clearing timers, and ignores future announcements. It does not empty the regions.
1182
+
1147
1183
  ## Animation
1148
1184
 
1149
1185
  The animation module provides a simple wrapper around the Web Animations API with Tailwind CSS-compatible easing functions.
@@ -1357,7 +1393,7 @@ prefersDarkMode(() => document.body.dataset.theme === 'dark')
1357
1393
 
1358
1394
  ## RTL Support
1359
1395
 
1360
- Utilities for detecting and observing right-to-left document direction.
1396
+ Utilities for detecting and observing right-to-left direction, for the document and for single elements.
1361
1397
 
1362
1398
  ### isRtl
1363
1399
 
@@ -1386,6 +1422,30 @@ const cleanup = onRtlChange((rtl) => {
1386
1422
  cleanup()
1387
1423
  ```
1388
1424
 
1425
+ ### isRightToLeft
1426
+
1427
+ Check whether an element is written right to left, from its computed `direction`. Unlike `isRtl()`, it follows a `dir` attribute on any ancestor, such as a right-to-left section in a left-to-right page.
1428
+
1429
+ ```typescript
1430
+ import { isRightToLeft } from '@inertiaui/vanilla'
1431
+
1432
+ const forward = isRightToLeft(list) ? 'ArrowLeft' : 'ArrowRight'
1433
+ ```
1434
+
1435
+ ### followReferenceDirection
1436
+
1437
+ Give a panel that renders away from its reference, such as in `document.body`, the direction of the reference. A panel that has its own `dir` attribute keeps it. Returns a cleanup function that removes the direction again.
1438
+
1439
+ ```typescript
1440
+ import { followReferenceDirection } from '@inertiaui/vanilla'
1441
+
1442
+ document.body.append(panel)
1443
+ const cleanup = followReferenceDirection(trigger, panel)
1444
+
1445
+ // When the panel closes
1446
+ cleanup()
1447
+ ```
1448
+
1389
1449
  ## Debounce
1390
1450
 
1391
1451
  ### debounce
@@ -1805,6 +1865,26 @@ for (const [key, value] of Object.entries(props)) {
1805
1865
  // customEvents: { onModalReady, onUserUpdated }
1806
1866
  ```
1807
1867
 
1868
+ #### replacePlaceholders
1869
+
1870
+ Replaces placeholders in the format of Laravel translation strings, such as `:name`, with values.
1871
+
1872
+ ```typescript
1873
+ import { replacePlaceholders } from '@inertiaui/vanilla'
1874
+
1875
+ replacePlaceholders('Hello, :name!', { name: 'Taylor' }) // 'Hello, Taylor!'
1876
+ replacePlaceholders(':count unread', { count: 3 }) // '3 unread'
1877
+ replacePlaceholders('Show :names to :name', { name: 'Taylor', names: 'Jess, Nuno' })
1878
+ // 'Show Jess, Nuno to Taylor'
1879
+ ```
1880
+
1881
+ The replacement follows these rules:
1882
+
1883
+ - A longer key wins over a shorter key that starts it, whatever order the keys have.
1884
+ - A placeholder ends at a character that is not a letter, digit, combining mark, or underscore. `:named` is not `:name` followed by `d`.
1885
+ - A placeholder without a value stays in the string.
1886
+ - The values are written as they are. A value that contains `:count` does not get a count.
1887
+
1808
1888
  ### URL Utilities
1809
1889
 
1810
1890
  #### sameUrlPath
@@ -1897,6 +1977,8 @@ This library is written in TypeScript and exports the following types:
1897
1977
  ```typescript
1898
1978
  import type {
1899
1979
  AnimateOptions,
1980
+ Announcer,
1981
+ AnnouncerPoliteness,
1900
1982
  AutoScrollAxis,
1901
1983
  AutoScrollContainer,
1902
1984
  AutoScrollerOptions,
package/dist/index.d.ts CHANGED
@@ -32,6 +32,13 @@ export declare interface AnimateOptions {
32
32
 
33
33
  export declare type AnimationSnapshot = Map<HTMLElement, DOMRect>;
34
34
 
35
+ export declare interface Announcer {
36
+ announce(text: string, politeness: AnnouncerPoliteness): void;
37
+ destroy(): void;
38
+ }
39
+
40
+ export declare type AnnouncerPoliteness = 'polite' | 'assertive';
41
+
35
42
  export declare type AutoScrollAxis = 'x' | 'y' | 'both';
36
43
 
37
44
  export declare type AutoScrollContainer = Element | Window;
@@ -86,6 +93,12 @@ export declare type ColorFormat = 'hex' | 'rgb' | 'hsl';
86
93
 
87
94
  export declare function computePosition(reference: HTMLElement, floating: HTMLElement, options?: PositionOptions_2): PositionResult;
88
95
 
96
+ /**
97
+ * Announces messages through two persistent, visually hidden live regions. The regions only ever contain
98
+ * plain text, so screen readers do not read button labels or other markup along with a message.
99
+ */
100
+ export declare function createAnnouncer(regions: Record<AnnouncerPoliteness, HTMLElement>): Announcer;
101
+
89
102
  /**
90
103
  * Create a {@link Debouncer} with a fixed delay or a getter read on each schedule.
91
104
  *
@@ -228,6 +241,13 @@ export declare interface FocusTrapOptions {
228
241
  returnFocus?: boolean;
229
242
  }
230
243
 
244
+ /**
245
+ * Give a panel rendered away from its reference, such as in the body, the
246
+ * direction the reference is written in. A panel with its own `dir` keeps it.
247
+ * Returns a cleanup function that removes the direction again.
248
+ */
249
+ export declare function followReferenceDirection(reference: Element, panel: HTMLElement): CleanupFunction;
250
+
231
251
  /**
232
252
  * Format an alpha value as a compact decimal string (e.g. `0.5`, `1`),
233
253
  * dropping trailing zeros.
@@ -308,6 +328,12 @@ export declare interface InlineStyleSnapshot {
308
328
  restore: (properties?: readonly string[]) => void;
309
329
  }
310
330
 
331
+ /**
332
+ * Check whether an element is written right to left, from its computed `direction`. Unlike `isRtl()`, this follows a
333
+ * `dir` attribute on any ancestor, such as a right-to-left section in a left-to-right page.
334
+ */
335
+ export declare function isRightToLeft(element: Element): boolean;
336
+
311
337
  /**
312
338
  * Check whether the document is currently in RTL direction.
313
339
  */
@@ -716,6 +742,13 @@ export declare type ReorderPreviewItem<T> = {
716
742
 
717
743
  export declare type ReorderSource = 'keyboard' | 'pointer';
718
744
 
745
+ /**
746
+ * Replaces Laravel-style placeholders, such as `:name`, with the given values in one pass. A longer key wins over a
747
+ * shorter one that starts it, so `:names` is not read as `:name` followed by `s`. A placeholder followed by a letter,
748
+ * digit, or underscore is left alone, as are placeholders without a value. Values are not searched for placeholders.
749
+ */
750
+ export declare function replacePlaceholders(template: string, params: Record<string, string | number>): string;
751
+
719
752
  export declare function resolveListboxNavigation<T>(options: ListboxNavigationOptions<T>): ListboxNavigationResult;
720
753
 
721
754
  /**
package/dist/index.js CHANGED
@@ -32,6 +32,17 @@ function kebabCase(string) {
32
32
  if (!string) return "";
33
33
  return string.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").replace(/-+/g, "-").toLowerCase();
34
34
  }
35
+ /**
36
+ * Replaces Laravel-style placeholders, such as `:name`, with the given values in one pass. A longer key wins over a
37
+ * shorter one that starts it, so `:names` is not read as `:name` followed by `s`. A placeholder followed by a letter,
38
+ * digit, or underscore is left alone, as are placeholders without a value. Values are not searched for placeholders.
39
+ */
40
+ function replacePlaceholders(template, params) {
41
+ const keys = Object.keys(params).filter((key) => key !== "");
42
+ if (keys.length === 0) return template;
43
+ const pattern = keys.sort((left, right) => right.length - left.length).map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
44
+ return template.replace(new RegExp(`:(${pattern})(?![\\p{L}\\p{N}\\p{M}_])`, "gu"), (_, key) => String(params[key]));
45
+ }
35
46
  var standardDomEventPattern = /* @__PURE__ */ new RegExp("^on(click|dblclick|mousedown|mouseup|mouseover|mouseout|mousemove|mouseenter|mouseleave|keydown|keyup|keypress|focus|blur|change|input|submit|reset|load|unload|error|resize|scroll|touchstart|touchend|touchmove|touchcancel|pointerdown|pointerup|pointermove|pointerenter|pointerleave|pointercancel|drag|dragstart|dragend|dragenter|dragleave|dragover|drop|animationstart|animationend|animationiteration|transitionstart|transitionend|transitionrun|transitioncancel)$");
36
47
  function isStandardDomEvent(eventName) {
37
48
  return standardDomEventPattern.test(eventName.toLowerCase());
@@ -290,6 +301,76 @@ function createLayoutAnimation(options = {}) {
290
301
  };
291
302
  }
292
303
  //#endregion
304
+ //#region src/announcer.ts
305
+ /** Screen readers ignore text added to a live region in the same moment the region appears. */
306
+ var ANNOUNCE_DELAY = 150;
307
+ /** Messages that arrive within this window are announced together. */
308
+ var BATCH_WINDOW = 50;
309
+ /** Clearing the region keeps old text out of the virtual cursor, and lets the same message be announced again. */
310
+ var CLEAR_DELAY = 1e3;
311
+ /**
312
+ * Announces messages through two persistent, visually hidden live regions. The regions only ever contain
313
+ * plain text, so screen readers do not read button labels or other markup along with a message.
314
+ */
315
+ function createAnnouncer(regions) {
316
+ const readyAt = Date.now() + ANNOUNCE_DELAY;
317
+ const queues = {
318
+ polite: [],
319
+ assertive: []
320
+ };
321
+ const timers = /* @__PURE__ */ new Set();
322
+ const clearTimers = {};
323
+ let flushTimer;
324
+ let destroyed = false;
325
+ const later = (callback, delay) => {
326
+ const timer = setTimeout(() => {
327
+ timers.delete(timer);
328
+ callback();
329
+ }, delay);
330
+ timers.add(timer);
331
+ return timer;
332
+ };
333
+ const write = (politeness, text) => {
334
+ const region = regions[politeness];
335
+ const pendingClear = clearTimers[politeness];
336
+ if (pendingClear !== void 0) {
337
+ clearTimeout(pendingClear);
338
+ timers.delete(pendingClear);
339
+ }
340
+ const update = () => {
341
+ region.textContent = text;
342
+ clearTimers[politeness] = later(() => region.textContent = "", CLEAR_DELAY);
343
+ };
344
+ if (region.textContent === "") {
345
+ update();
346
+ return;
347
+ }
348
+ region.textContent = "";
349
+ later(update, BATCH_WINDOW);
350
+ };
351
+ const flush = () => {
352
+ flushTimer = void 0;
353
+ for (const politeness of ["assertive", "polite"]) if (queues[politeness].length > 0) {
354
+ write(politeness, queues[politeness].join(" "));
355
+ queues[politeness] = [];
356
+ }
357
+ };
358
+ return {
359
+ announce(text, politeness) {
360
+ if (destroyed) return;
361
+ queues[politeness].push(text);
362
+ flushTimer ??= later(flush, Math.max(readyAt - Date.now(), BATCH_WINDOW));
363
+ },
364
+ destroy() {
365
+ destroyed = true;
366
+ timers.forEach(clearTimeout);
367
+ timers.clear();
368
+ queues.polite = [];
369
+ queues.assertive = [];
370
+ }
371
+ };
372
+ }
373
+ //#endregion
293
374
  //#region src/dialog.ts
294
375
  var FOCUSABLE_SELECTORS = [
295
376
  "a[href]",
@@ -1535,191 +1616,45 @@ function focusFirstEnabledElement(elements, options) {
1535
1616
  return false;
1536
1617
  }
1537
1618
  //#endregion
1538
- //#region src/position/geometry.ts
1539
- function isRtl$1() {
1540
- return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1541
- }
1542
- /** Whether `start` and `end` placements around the reference run from the right, following its writing direction. */
1543
- function isRightToLeft(reference) {
1544
- return getComputedStyle(reference).direction === "rtl";
1545
- }
1546
- function getOppositePlacement(placement) {
1547
- return {
1548
- top: "bottom",
1549
- "top-start": "bottom-start",
1550
- "top-end": "bottom-end",
1551
- bottom: "top",
1552
- "bottom-start": "top-start",
1553
- "bottom-end": "top-end",
1554
- left: "right",
1555
- "left-start": "right-start",
1556
- "left-end": "right-end",
1557
- right: "left",
1558
- "right-start": "left-start",
1559
- "right-end": "left-end"
1560
- }[placement] || placement;
1561
- }
1562
- function getViewportRect() {
1563
- const visualViewport = window.visualViewport;
1564
- if (visualViewport) return {
1565
- top: visualViewport.offsetTop,
1566
- right: visualViewport.offsetLeft + visualViewport.width,
1567
- bottom: visualViewport.offsetTop + visualViewport.height,
1568
- left: visualViewport.offsetLeft,
1569
- width: visualViewport.width,
1570
- height: visualViewport.height
1571
- };
1572
- return {
1573
- top: 0,
1574
- right: window.innerWidth,
1575
- bottom: window.innerHeight,
1576
- left: 0,
1577
- width: window.innerWidth,
1578
- height: window.innerHeight
1579
- };
1580
- }
1581
- function clamp$1(value, min, max) {
1582
- if (max < min) return min;
1583
- return Math.max(min, Math.min(value, max));
1584
- }
1585
- function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margin) {
1586
- const [side] = placement.split("-");
1587
- const minX = viewport.left + margin;
1588
- const maxX = viewport.right - floatingRect.width - margin;
1589
- const minY = viewport.top + margin;
1590
- const maxY = viewport.bottom - floatingRect.height - margin;
1591
- if (side === "top" || side === "bottom") return {
1592
- x: clamp$1(x, minX, maxX),
1593
- y
1594
- };
1595
- if (side === "left" || side === "right") return {
1596
- x,
1597
- y: clamp$1(y, minY, maxY)
1598
- };
1599
- return {
1600
- x: clamp$1(x, minX, maxX),
1601
- y: clamp$1(y, minY, maxY)
1602
- };
1603
- }
1604
- function topLayerRectOverflowsViewport(rect, viewport) {
1605
- const tolerance = .5;
1606
- return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1607
- }
1608
- function referenceIntersectsViewport(reference) {
1609
- const rect = reference.getBoundingClientRect();
1610
- const viewport = getViewportRect();
1611
- return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right;
1612
- }
1613
- function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1614
- if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1615
- if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
1616
- if (side === "left") return referenceRect.left - viewport.left - offset - margin;
1617
- if (side === "right") return viewport.right - referenceRect.right - offset - margin;
1618
- return viewport.height - margin * 2;
1619
- }
1620
- function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSize, viewport, offset, margin, flip) {
1621
- if (!flip) return preferredPlacement;
1622
- const [side] = preferredPlacement.split("-");
1623
- const oppositePlacement = getOppositePlacement(preferredPlacement);
1624
- const [oppositeSide] = oppositePlacement.split("-");
1625
- const floatingLength = side === "left" || side === "right" ? floatingSize.width : floatingSize.height;
1626
- const preferredSpace = getAvailableSpace(referenceRect, viewport, side, offset, margin);
1627
- const oppositeSpace = getAvailableSpace(referenceRect, viewport, oppositeSide, offset, margin);
1628
- if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1629
- return preferredPlacement;
1630
- }
1631
- function computePositionFromRect(refRect, floatingRect, placement, offset, rtl = isRtl$1()) {
1632
- let x = 0;
1633
- let y = 0;
1634
- const [side, alignment] = placement.split("-");
1635
- switch (side) {
1636
- case "bottom":
1637
- y = refRect.bottom + offset;
1638
- break;
1639
- case "top":
1640
- y = refRect.top - floatingRect.height - offset;
1641
- break;
1642
- case "left":
1643
- x = refRect.left - floatingRect.width - offset;
1644
- break;
1645
- case "right":
1646
- x = refRect.right + offset;
1647
- break;
1648
- }
1649
- if (side === "bottom" || side === "top") {
1650
- const startIsLeft = !rtl;
1651
- switch (alignment) {
1652
- case "start":
1653
- x = startIsLeft ? refRect.left : refRect.right - floatingRect.width;
1654
- break;
1655
- case "end":
1656
- x = startIsLeft ? refRect.right - floatingRect.width : refRect.left;
1657
- break;
1658
- default:
1659
- x = refRect.left + (refRect.width - floatingRect.width) / 2;
1660
- break;
1661
- }
1662
- } else switch (alignment) {
1663
- case "start":
1664
- y = refRect.top;
1665
- break;
1666
- case "end":
1667
- y = refRect.bottom - floatingRect.height;
1668
- break;
1669
- default:
1670
- y = refRect.top + (refRect.height - floatingRect.height) / 2;
1671
- break;
1672
- }
1673
- return {
1674
- x,
1675
- y
1676
- };
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";
1677
1625
  }
1678
- function wouldOverflow(x, y, floatingRect, placement) {
1679
- const [side] = placement.split("-");
1680
- const vw = window.innerWidth;
1681
- const vh = window.innerHeight;
1682
- switch (side) {
1683
- case "bottom": return y + floatingRect.height > vh;
1684
- case "top": return y < 0;
1685
- case "left": return x < 0;
1686
- case "right": return x + floatingRect.width > vw;
1687
- default: return false;
1688
- }
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";
1689
1632
  }
1690
- function clampToViewport(x, y, floatingRect) {
1691
- const vw = window.innerWidth;
1692
- const vh = window.innerHeight;
1693
- const margin = 4;
1694
- return {
1695
- x: Math.max(margin, Math.min(x, vw - floatingRect.width - margin)),
1696
- y: Math.max(margin, Math.min(y, vh - floatingRect.height - margin))
1697
- };
1633
+ /**
1634
+ * Observe changes to the document's `dir` attribute and invoke the callback
1635
+ * whenever it changes. Returns a cleanup function to stop observing.
1636
+ */
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"]
1644
+ });
1645
+ return () => observer.disconnect();
1698
1646
  }
1699
- function computeWithFallback(reference, floating, options = {}, referenceRect) {
1700
- const { placement = "bottom-start", offset = 0, flip = true } = options;
1701
- const refRect = referenceRect ?? reference.getBoundingClientRect();
1702
- const floatingRect = {
1703
- width: floating.offsetWidth,
1704
- height: floating.offsetHeight
1705
- };
1706
- const rtl = isRightToLeft(reference);
1707
- let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset, rtl);
1708
- let actualPlacement = placement;
1709
- if (flip && wouldOverflow(x, y, floatingRect, placement)) {
1710
- const flipped = getOppositePlacement(placement);
1711
- const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset, rtl);
1712
- if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
1713
- x = flippedPos.x;
1714
- y = flippedPos.y;
1715
- actualPlacement = flipped;
1716
- }
1717
- }
1718
- const clamped = clampToViewport(x, y, floatingRect);
1719
- return {
1720
- x: clamped.x,
1721
- y: clamped.y,
1722
- placement: actualPlacement
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");
1723
1658
  };
1724
1659
  }
1725
1660
  //#endregion
@@ -1972,6 +1907,190 @@ function setupTopLayerAnchorPositioning(reference, floating, placement, offset,
1972
1907
  return className;
1973
1908
  }
1974
1909
  //#endregion
1910
+ //#region src/position/geometry.ts
1911
+ function isRtl$1() {
1912
+ return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1913
+ }
1914
+ function getOppositePlacement(placement) {
1915
+ return {
1916
+ top: "bottom",
1917
+ "top-start": "bottom-start",
1918
+ "top-end": "bottom-end",
1919
+ bottom: "top",
1920
+ "bottom-start": "top-start",
1921
+ "bottom-end": "top-end",
1922
+ left: "right",
1923
+ "left-start": "right-start",
1924
+ "left-end": "right-end",
1925
+ right: "left",
1926
+ "right-start": "left-start",
1927
+ "right-end": "left-end"
1928
+ }[placement] || placement;
1929
+ }
1930
+ function getViewportRect() {
1931
+ const visualViewport = window.visualViewport;
1932
+ if (visualViewport) return {
1933
+ top: visualViewport.offsetTop,
1934
+ right: visualViewport.offsetLeft + visualViewport.width,
1935
+ bottom: visualViewport.offsetTop + visualViewport.height,
1936
+ left: visualViewport.offsetLeft,
1937
+ width: visualViewport.width,
1938
+ height: visualViewport.height
1939
+ };
1940
+ return {
1941
+ top: 0,
1942
+ right: window.innerWidth,
1943
+ bottom: window.innerHeight,
1944
+ left: 0,
1945
+ width: window.innerWidth,
1946
+ height: window.innerHeight
1947
+ };
1948
+ }
1949
+ function clamp$1(value, min, max) {
1950
+ if (max < min) return min;
1951
+ return Math.max(min, Math.min(value, max));
1952
+ }
1953
+ function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margin) {
1954
+ const [side] = placement.split("-");
1955
+ const minX = viewport.left + margin;
1956
+ const maxX = viewport.right - floatingRect.width - margin;
1957
+ const minY = viewport.top + margin;
1958
+ const maxY = viewport.bottom - floatingRect.height - margin;
1959
+ if (side === "top" || side === "bottom") return {
1960
+ x: clamp$1(x, minX, maxX),
1961
+ y
1962
+ };
1963
+ if (side === "left" || side === "right") return {
1964
+ x,
1965
+ y: clamp$1(y, minY, maxY)
1966
+ };
1967
+ return {
1968
+ x: clamp$1(x, minX, maxX),
1969
+ y: clamp$1(y, minY, maxY)
1970
+ };
1971
+ }
1972
+ function topLayerRectOverflowsViewport(rect, viewport) {
1973
+ const tolerance = .5;
1974
+ return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1975
+ }
1976
+ function referenceIntersectsViewport(reference) {
1977
+ const rect = reference.getBoundingClientRect();
1978
+ const viewport = getViewportRect();
1979
+ return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right;
1980
+ }
1981
+ function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1982
+ if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1983
+ if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
1984
+ if (side === "left") return referenceRect.left - viewport.left - offset - margin;
1985
+ if (side === "right") return viewport.right - referenceRect.right - offset - margin;
1986
+ return viewport.height - margin * 2;
1987
+ }
1988
+ function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSize, viewport, offset, margin, flip) {
1989
+ if (!flip) return preferredPlacement;
1990
+ const [side] = preferredPlacement.split("-");
1991
+ const oppositePlacement = getOppositePlacement(preferredPlacement);
1992
+ const [oppositeSide] = oppositePlacement.split("-");
1993
+ const floatingLength = side === "left" || side === "right" ? floatingSize.width : floatingSize.height;
1994
+ const preferredSpace = getAvailableSpace(referenceRect, viewport, side, offset, margin);
1995
+ const oppositeSpace = getAvailableSpace(referenceRect, viewport, oppositeSide, offset, margin);
1996
+ if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1997
+ return preferredPlacement;
1998
+ }
1999
+ function computePositionFromRect(refRect, floatingRect, placement, offset, rtl = isRtl$1()) {
2000
+ let x = 0;
2001
+ let y = 0;
2002
+ const [side, alignment] = placement.split("-");
2003
+ switch (side) {
2004
+ case "bottom":
2005
+ y = refRect.bottom + offset;
2006
+ break;
2007
+ case "top":
2008
+ y = refRect.top - floatingRect.height - offset;
2009
+ break;
2010
+ case "left":
2011
+ x = refRect.left - floatingRect.width - offset;
2012
+ break;
2013
+ case "right":
2014
+ x = refRect.right + offset;
2015
+ break;
2016
+ }
2017
+ if (side === "bottom" || side === "top") {
2018
+ const startIsLeft = !rtl;
2019
+ switch (alignment) {
2020
+ case "start":
2021
+ x = startIsLeft ? refRect.left : refRect.right - floatingRect.width;
2022
+ break;
2023
+ case "end":
2024
+ x = startIsLeft ? refRect.right - floatingRect.width : refRect.left;
2025
+ break;
2026
+ default:
2027
+ x = refRect.left + (refRect.width - floatingRect.width) / 2;
2028
+ break;
2029
+ }
2030
+ } else switch (alignment) {
2031
+ case "start":
2032
+ y = refRect.top;
2033
+ break;
2034
+ case "end":
2035
+ y = refRect.bottom - floatingRect.height;
2036
+ break;
2037
+ default:
2038
+ y = refRect.top + (refRect.height - floatingRect.height) / 2;
2039
+ break;
2040
+ }
2041
+ return {
2042
+ x,
2043
+ y
2044
+ };
2045
+ }
2046
+ function wouldOverflow(x, y, floatingRect, placement) {
2047
+ const [side] = placement.split("-");
2048
+ const vw = window.innerWidth;
2049
+ const vh = window.innerHeight;
2050
+ switch (side) {
2051
+ case "bottom": return y + floatingRect.height > vh;
2052
+ case "top": return y < 0;
2053
+ case "left": return x < 0;
2054
+ case "right": return x + floatingRect.width > vw;
2055
+ default: return false;
2056
+ }
2057
+ }
2058
+ function clampToViewport(x, y, floatingRect) {
2059
+ const vw = window.innerWidth;
2060
+ const vh = window.innerHeight;
2061
+ const margin = 4;
2062
+ return {
2063
+ x: Math.max(margin, Math.min(x, vw - floatingRect.width - margin)),
2064
+ y: Math.max(margin, Math.min(y, vh - floatingRect.height - margin))
2065
+ };
2066
+ }
2067
+ function computeWithFallback(reference, floating, options = {}, referenceRect) {
2068
+ const { placement = "bottom-start", offset = 0, flip = true } = options;
2069
+ const refRect = referenceRect ?? reference.getBoundingClientRect();
2070
+ const floatingRect = {
2071
+ width: floating.offsetWidth,
2072
+ height: floating.offsetHeight
2073
+ };
2074
+ const rtl = isRightToLeft(reference);
2075
+ let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset, rtl);
2076
+ let actualPlacement = placement;
2077
+ if (flip && wouldOverflow(x, y, floatingRect, placement)) {
2078
+ const flipped = getOppositePlacement(placement);
2079
+ const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset, rtl);
2080
+ if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
2081
+ x = flippedPos.x;
2082
+ y = flippedPos.y;
2083
+ actualPlacement = flipped;
2084
+ }
2085
+ }
2086
+ const clamped = clampToViewport(x, y, floatingRect);
2087
+ return {
2088
+ x: clamped.x,
2089
+ y: clamped.y,
2090
+ placement: actualPlacement
2091
+ };
2092
+ }
2093
+ //#endregion
1975
2094
  //#region src/position/floating.ts
1976
2095
  var SIZE_MARGIN = 8;
1977
2096
  /**
@@ -2469,41 +2588,6 @@ function createNativePopoverDisclosure(options) {
2469
2588
  };
2470
2589
  }
2471
2590
  //#endregion
2472
- //#region src/rtl.ts
2473
- /**
2474
- * Check whether the document is currently in RTL direction.
2475
- */
2476
- function isRtl() {
2477
- return document.documentElement.dir === "rtl";
2478
- }
2479
- /**
2480
- * Observe changes to the document's `dir` attribute and invoke the callback
2481
- * whenever it changes. Returns a cleanup function to stop observing.
2482
- */
2483
- function onRtlChange(callback) {
2484
- const observer = new MutationObserver(() => {
2485
- callback(document.documentElement.dir === "rtl");
2486
- });
2487
- observer.observe(document.documentElement, {
2488
- attributes: true,
2489
- attributeFilter: ["dir"]
2490
- });
2491
- return () => observer.disconnect();
2492
- }
2493
- /**
2494
- * Give a panel rendered away from its reference, such as in the body, the
2495
- * direction the reference is written in. A panel with its own `dir` keeps it.
2496
- * Returns a cleanup function that removes the direction again.
2497
- */
2498
- function followReferenceDirection(reference, panel) {
2499
- const direction = getComputedStyle(reference).direction;
2500
- if (panel.hasAttribute("dir") || getComputedStyle(panel).direction === direction) return () => {};
2501
- panel.setAttribute("dir", direction);
2502
- return () => {
2503
- if (panel.getAttribute("dir") === direction) panel.removeAttribute("dir");
2504
- };
2505
- }
2506
- //#endregion
2507
2591
  //#region src/popover.ts
2508
2592
  /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2509
2593
  function createPopoverController(options) {
@@ -3331,4 +3415,4 @@ function createDialogController(options) {
3331
3415
  };
3332
3416
  }
3333
3417
  //#endregion
3334
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, captureInlineStyles, computePosition, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createLayoutAnimation, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, getReorderOffsets, getScrollableAncestors, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
3418
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",