@inertiaui/vanilla 1.5.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/dist/index.js CHANGED
@@ -6,21 +6,20 @@ function generateId(prefix = "inertiaui_") {
6
6
  function strToLowercase(key) {
7
7
  return key.toLowerCase();
8
8
  }
9
- function except(target, keys, ignoreCase = false) {
9
+ function filterKeys(target, keys, ignoreCase, include) {
10
10
  if (ignoreCase) keys = keys.map(strToLowercase);
11
- if (Array.isArray(target)) return target.filter((key) => !keys.includes(ignoreCase ? strToLowercase(key) : key));
11
+ const keySet = new Set(keys);
12
+ if (Array.isArray(target)) return target.filter((key) => keySet.has(ignoreCase ? strToLowercase(key) : key) === include);
12
13
  return Object.keys(target).reduce((acc, key) => {
13
- if (!keys.includes(ignoreCase ? strToLowercase(key) : key)) acc[key] = target[key];
14
+ if (keySet.has(ignoreCase ? strToLowercase(key) : key) === include) acc[key] = target[key];
14
15
  return acc;
15
16
  }, {});
16
17
  }
18
+ function except(target, keys, ignoreCase = false) {
19
+ return filterKeys(target, keys, ignoreCase, false);
20
+ }
17
21
  function only(target, keys, ignoreCase = false) {
18
- if (ignoreCase) keys = keys.map(strToLowercase);
19
- if (Array.isArray(target)) return target.filter((key) => keys.includes(ignoreCase ? strToLowercase(key) : key));
20
- return Object.keys(target).reduce((acc, key) => {
21
- if (keys.includes(ignoreCase ? strToLowercase(key) : key)) acc[key] = target[key];
22
- return acc;
23
- }, {});
22
+ return filterKeys(target, keys, ignoreCase, true);
24
23
  }
25
24
  function rejectNullValues(target) {
26
25
  if (Array.isArray(target)) return target.filter((item) => item !== null);
@@ -31,21 +30,22 @@ function rejectNullValues(target) {
31
30
  }
32
31
  function kebabCase(string) {
33
32
  if (!string) return "";
34
- 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();
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
+ }
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]));
35
45
  }
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
- const lowerEventName = eventName.toLowerCase();
38
- return [
39
- /^on(click|dblclick|mousedown|mouseup|mouseover|mouseout|mousemove|mouseenter|mouseleave)$/,
40
- /^on(keydown|keyup|keypress)$/,
41
- /^on(focus|blur|change|input|submit|reset)$/,
42
- /^on(load|unload|error|resize|scroll)$/,
43
- /^on(touchstart|touchend|touchmove|touchcancel)$/,
44
- /^on(pointerdown|pointerup|pointermove|pointerenter|pointerleave|pointercancel)$/,
45
- /^on(drag|dragstart|dragend|dragenter|dragleave|dragover|drop)$/,
46
- /^on(animationstart|animationend|animationiteration)$/,
47
- /^on(transitionstart|transitionend|transitionrun|transitioncancel)$/
48
- ].some((pattern) => pattern.test(lowerEventName));
48
+ return standardDomEventPattern.test(eventName.toLowerCase());
49
49
  }
50
50
  function onceChildrenRendered(element, callback) {
51
51
  if (element.children.length > 0) {
@@ -170,6 +170,27 @@ function cancelSnapshotAnimation(element) {
170
170
  activeSnapshotAnimations.delete(element);
171
171
  }
172
172
  }
173
+ function canBatchSnapshotMeasurements(elements) {
174
+ const targets = new Set(elements);
175
+ if (targets.size !== elements.length) return false;
176
+ const checkedAncestors = /* @__PURE__ */ new Set();
177
+ for (const element of elements) {
178
+ let ancestor = element;
179
+ while (ancestor) {
180
+ let parent = ancestor.assignedSlot ?? ancestor.parentElement;
181
+ if (!parent) {
182
+ const root = ancestor.getRootNode();
183
+ parent = typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.host : null;
184
+ }
185
+ ancestor = parent;
186
+ if (!ancestor) break;
187
+ if (targets.has(ancestor)) return false;
188
+ if (checkedAncestors.has(ancestor)) break;
189
+ checkedAncestors.add(ancestor);
190
+ }
191
+ }
192
+ return true;
193
+ }
173
194
  /**
174
195
  * Capture current element rectangles before a renderer changes their order or
175
196
  * position. Pass the snapshot to animateFromSnapshot after the DOM has updated.
@@ -191,22 +212,29 @@ function animateFromSnapshot(snapshot, elements, options = {}) {
191
212
  ...options
192
213
  };
193
214
  const animations = [];
194
- for (const element of connectedElements(elements)) {
215
+ const targets = connectedElements(elements).filter((element) => snapshot.has(element));
216
+ const measure = (element) => {
195
217
  const before = snapshot.get(element);
196
- if (!before) continue;
197
218
  const after = element.getBoundingClientRect();
198
219
  const running = resolvedOptions.includeCurrentTransform ? currentTranslate(element) : {
199
220
  x: 0,
200
221
  y: 0
201
222
  };
202
- const deltaX = before.left - after.left + running.x;
203
- const deltaY = before.top - after.top + running.y;
223
+ return {
224
+ deltaX: before.left - after.left + running.x,
225
+ deltaY: before.top - after.top + running.y
226
+ };
227
+ };
228
+ const measurements = canBatchSnapshotMeasurements(targets) ? targets.map(measure) : null;
229
+ const animationOptions = resolveAnimationOptions(resolvedOptions);
230
+ for (const [index, element] of targets.entries()) {
231
+ const { deltaX, deltaY } = measurements?.[index] ?? measure(element);
204
232
  if (Math.abs(deltaX) < resolvedOptions.minimumDelta && Math.abs(deltaY) < resolvedOptions.minimumDelta) {
205
233
  cancelSnapshotAnimation(element);
206
234
  continue;
207
235
  }
208
236
  cancelSnapshotAnimation(element);
209
- const animation = element.animate([{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }], resolveAnimationOptions(resolvedOptions));
237
+ const animation = element.animate([{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }], animationOptions);
210
238
  activeSnapshotAnimations.set(element, animation);
211
239
  animations.push(animation);
212
240
  animation.finished.catch(() => animation).finally(() => {
@@ -215,6 +243,133 @@ function animateFromSnapshot(snapshot, elements, options = {}) {
215
243
  }
216
244
  return animations;
217
245
  }
246
+ function nextFrame(run) {
247
+ if (typeof requestAnimationFrame !== "function") return run();
248
+ const frame = requestAnimationFrame(() => run());
249
+ return () => cancelAnimationFrame(frame);
250
+ }
251
+ /**
252
+ * Animate layout changes a renderer makes after a snapshot, keeping track of
253
+ * scheduled and running moves so they can be interrupted.
254
+ */
255
+ function createLayoutAnimation(options = {}) {
256
+ const { schedule = nextFrame, ...animationOptions } = options;
257
+ const pending = /* @__PURE__ */ new Set();
258
+ const running = /* @__PURE__ */ new Set();
259
+ let cleaned = false;
260
+ function animate(snapshot, getElements, callbacks = {}) {
261
+ if (cleaned) return;
262
+ const scheduled = { dropped: false };
263
+ const run = () => {
264
+ if (scheduled.dropped || cleaned) return;
265
+ scheduled.dropped = true;
266
+ pending.delete(scheduled);
267
+ const animations = animateFromSnapshot(snapshot, getElements(), animationOptions);
268
+ animations.forEach((animation) => running.add(animation));
269
+ Promise.allSettled(animations.map((animation) => animation.finished)).then(() => {
270
+ animations.forEach((animation) => running.delete(animation));
271
+ if (!cleaned) callbacks.onSettle?.();
272
+ });
273
+ callbacks.onStart?.(animations);
274
+ };
275
+ pending.add(scheduled);
276
+ try {
277
+ scheduled.cancel = schedule(run);
278
+ } catch (error) {
279
+ scheduled.dropped = true;
280
+ pending.delete(scheduled);
281
+ throw error;
282
+ }
283
+ }
284
+ function cancel() {
285
+ for (const scheduled of pending) {
286
+ scheduled.dropped = true;
287
+ scheduled.cancel?.();
288
+ }
289
+ pending.clear();
290
+ Array.from(running).forEach((animation) => animation.cancel());
291
+ }
292
+ return {
293
+ animate,
294
+ cancel,
295
+ cleanup: () => {
296
+ if (!cleaned) {
297
+ cleaned = true;
298
+ cancel();
299
+ }
300
+ }
301
+ };
302
+ }
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
+ }
218
373
  //#endregion
219
374
  //#region src/dialog.ts
220
375
  var FOCUSABLE_SELECTORS = [
@@ -224,7 +379,7 @@ var FOCUSABLE_SELECTORS = [
224
379
  "input:not([disabled])",
225
380
  "select:not([disabled])",
226
381
  "[tabindex]:not([tabindex=\"-1\"])"
227
- ].join(", ");
382
+ ].map((selector) => `${selector}:not([aria-hidden="true"]):not(input[type="hidden"])`).join(", ");
228
383
  var scrollLockCount = 0;
229
384
  var originalOverflow = "";
230
385
  var originalPaddingRight = "";
@@ -237,8 +392,8 @@ function lockScroll() {
237
392
  originalOverflow = document.body.style.overflow;
238
393
  originalPaddingRight = document.body.style.paddingRight;
239
394
  originalScrollbarGutter = document.documentElement.style.getPropertyValue("scrollbar-gutter");
240
- const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
241
395
  const canReserveScrollbarGutter = supportsScrollbarGutter();
396
+ const scrollbarWidth = canReserveScrollbarGutter ? 0 : window.innerWidth - document.documentElement.clientWidth;
242
397
  if (canReserveScrollbarGutter) document.documentElement.style.setProperty("scrollbar-gutter", "stable");
243
398
  document.body.style.overflow = "hidden";
244
399
  if (!canReserveScrollbarGutter && scrollbarWidth > 0) document.body.style.paddingRight = `${scrollbarWidth}px`;
@@ -260,9 +415,27 @@ function unlockScroll() {
260
415
  else document.documentElement.style.removeProperty("scrollbar-gutter");
261
416
  }
262
417
  }
263
- function getFocusableElements(container) {
264
- if (!container) return [];
265
- return Array.from(container.querySelectorAll(FOCUSABLE_SELECTORS)).filter((el) => el.getAttribute("aria-hidden") !== "true");
418
+ function getLastFocusableElement(container) {
419
+ let element = container.lastElementChild;
420
+ let descend = true;
421
+ for (let remaining = 32; element && remaining > 0; remaining--) {
422
+ if (descend && element.lastElementChild) {
423
+ element = element.lastElementChild;
424
+ continue;
425
+ }
426
+ if (element.matches(FOCUSABLE_SELECTORS)) return element;
427
+ if (element.previousElementSibling) {
428
+ element = element.previousElementSibling;
429
+ descend = true;
430
+ } else {
431
+ element = element.parentElement;
432
+ if (element === container) return null;
433
+ descend = false;
434
+ }
435
+ }
436
+ if (!element) return null;
437
+ const elements = container.querySelectorAll(FOCUSABLE_SELECTORS);
438
+ return elements[elements.length - 1] ?? null;
266
439
  }
267
440
  var focusTrapStack = [];
268
441
  var lastPointerDownTarget = null;
@@ -275,27 +448,31 @@ function trackPointerDown(event) {
275
448
  function handleTrapKeyDown(event) {
276
449
  if (event.key !== "Tab" || focusTrapStack.length === 0) return;
277
450
  const { container } = focusTrapStack[focusTrapStack.length - 1];
278
- const focusableElements = getFocusableElements(container);
279
- if (focusableElements.length === 0) return;
280
- const firstElement = focusableElements[0];
281
- const lastElement = focusableElements[focusableElements.length - 1];
282
- if (event.shiftKey) {
283
- if (document.activeElement === firstElement || !container.contains(document.activeElement)) {
451
+ const activeElement = document.activeElement;
452
+ const outside = !container.contains(activeElement);
453
+ if (!event.shiftKey && outside) {
454
+ const firstElement = container.querySelector(FOCUSABLE_SELECTORS);
455
+ if (firstElement) {
284
456
  event.preventDefault();
285
- lastElement.focus();
457
+ firstElement.focus();
286
458
  }
287
- } else if (document.activeElement === lastElement || !container.contains(document.activeElement)) {
459
+ return;
460
+ }
461
+ if (event.shiftKey && !outside && activeElement !== container.querySelector(FOCUSABLE_SELECTORS)) return;
462
+ const lastElement = getLastFocusableElement(container);
463
+ if (!lastElement) return;
464
+ if (event.shiftKey) {
288
465
  event.preventDefault();
289
- firstElement.focus();
466
+ lastElement.focus();
467
+ } else if (activeElement === lastElement) {
468
+ event.preventDefault();
469
+ container.querySelector(FOCUSABLE_SELECTORS)?.focus();
290
470
  }
291
471
  }
292
472
  function handleTrapFocusIn(event) {
293
473
  if (focusTrapStack.length === 0) return;
294
474
  const { container } = focusTrapStack[focusTrapStack.length - 1];
295
- if (!container.contains(event.target)) {
296
- const focusableElements = getFocusableElements(container);
297
- if (focusableElements.length > 0) focusableElements[0].focus({ preventScroll: true });
298
- }
475
+ if (!container.contains(event.target)) container.querySelector(FOCUSABLE_SELECTORS)?.focus({ preventScroll: true });
299
476
  }
300
477
  function createFocusTrap(container, options = {}) {
301
478
  const { initialFocus = true, initialFocusElement = null, returnFocus = true } = options;
@@ -311,21 +488,19 @@ function createFocusTrap(container, options = {}) {
311
488
  if (event.relatedTarget !== null) return;
312
489
  const pointerTarget = lastPointerDownTarget;
313
490
  queueMicrotask(() => {
491
+ if (cleaned || focusTrapStack[focusTrapStack.length - 1] !== entry) return;
314
492
  if (container.contains(container.ownerDocument.activeElement)) return;
315
493
  if (pointerTarget instanceof Node && container.contains(pointerTarget)) return;
316
- const focusableElements = getFocusableElements(container);
317
- if (focusableElements.length > 0) focusableElements[0].focus({ preventScroll: true });
494
+ container.querySelector(FOCUSABLE_SELECTORS)?.focus({ preventScroll: true });
318
495
  });
319
496
  }
320
497
  container.addEventListener("focusout", handleFocusOut);
321
498
  let rafId;
322
499
  if (initialFocus) rafId = requestAnimationFrame(() => {
323
500
  rafId = void 0;
501
+ if (focusTrapStack[focusTrapStack.length - 1] !== entry) return;
324
502
  if (initialFocusElement && container.contains(initialFocusElement)) initialFocusElement.focus();
325
- else {
326
- const focusableElements = getFocusableElements(container);
327
- if (focusableElements.length > 0) focusableElements[0].focus();
328
- }
503
+ else container.querySelector(FOCUSABLE_SELECTORS)?.focus();
329
504
  });
330
505
  let cleaned = false;
331
506
  return function cleanup() {
@@ -333,8 +508,11 @@ function createFocusTrap(container, options = {}) {
333
508
  cleaned = true;
334
509
  if (rafId !== void 0) cancelAnimationFrame(rafId);
335
510
  container.removeEventListener("focusout", handleFocusOut);
336
- const index = focusTrapStack.indexOf(entry);
337
- if (index >= 0) focusTrapStack.splice(index, 1);
511
+ if (focusTrapStack[focusTrapStack.length - 1] === entry) focusTrapStack.pop();
512
+ else {
513
+ const index = focusTrapStack.indexOf(entry);
514
+ if (index >= 0) focusTrapStack.splice(index, 1);
515
+ }
338
516
  if (focusTrapStack.length === 0) {
339
517
  document.removeEventListener("keydown", handleTrapKeyDown);
340
518
  document.removeEventListener("focusin", handleTrapFocusIn);
@@ -371,20 +549,19 @@ function onEscapeKey(callback, options = {}) {
371
549
  else document.removeEventListener("keydown", handler);
372
550
  };
373
551
  }
374
- var ariaHiddenStack = [];
375
- var inertStack = [];
552
+ var ariaHiddenStates = /* @__PURE__ */ new WeakMap();
553
+ var inertStates = /* @__PURE__ */ new WeakMap();
376
554
  function supportsNativeInert(element) {
377
555
  return "inert" in element;
378
556
  }
379
557
  function markAriaHidden(elementOrSelector) {
380
558
  const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
381
559
  if (!element) return function noop() {};
382
- const existingIndex = ariaHiddenStack.findIndex((item) => item.element === element);
383
- if (existingIndex >= 0) ariaHiddenStack[existingIndex].count++;
560
+ const existing = ariaHiddenStates.get(element);
561
+ if (existing) existing.count++;
384
562
  else {
385
563
  const originalValue = element.getAttribute("aria-hidden");
386
- ariaHiddenStack.push({
387
- element,
564
+ ariaHiddenStates.set(element, {
388
565
  originalValue,
389
566
  count: 1
390
567
  });
@@ -398,33 +575,29 @@ function markAriaHidden(elementOrSelector) {
398
575
  };
399
576
  }
400
577
  function unmarkAriaHidden(element) {
401
- const index = ariaHiddenStack.findIndex((item) => item.element === element);
402
- if (index < 0) return;
403
- ariaHiddenStack[index].count--;
404
- if (ariaHiddenStack[index].count <= 0) {
405
- const { originalValue } = ariaHiddenStack[index];
578
+ const item = ariaHiddenStates.get(element);
579
+ if (!item) return;
580
+ item.count--;
581
+ if (item.count <= 0) {
582
+ const { originalValue } = item;
406
583
  if (originalValue === null) element.removeAttribute("aria-hidden");
407
584
  else element.setAttribute("aria-hidden", originalValue);
408
- ariaHiddenStack.splice(index, 1);
585
+ ariaHiddenStates.delete(element);
409
586
  }
410
587
  }
411
588
  function markInert(elementOrSelector) {
412
589
  const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
413
590
  if (!element) return function noop() {};
414
- const existingIndex = inertStack.findIndex((item) => item.element === element);
415
- if (existingIndex >= 0) inertStack[existingIndex].count++;
591
+ if (!supportsNativeInert(element)) return markAriaHidden(element);
592
+ const existing = inertStates.get(element);
593
+ if (existing) existing.count++;
416
594
  else {
417
- const originalAriaHidden = element.getAttribute("aria-hidden");
418
- const hasNativeInert = supportsNativeInert(element);
419
- const originalInert = hasNativeInert ? element.inert : false;
420
- inertStack.push({
421
- element,
422
- originalAriaHidden,
595
+ const originalInert = element.inert;
596
+ inertStates.set(element, {
423
597
  originalInert,
424
598
  count: 1
425
599
  });
426
- if (hasNativeInert) element.inert = true;
427
- else element.setAttribute("aria-hidden", "true");
600
+ element.inert = true;
428
601
  }
429
602
  let cleaned = false;
430
603
  return function cleanup() {
@@ -434,15 +607,12 @@ function markInert(elementOrSelector) {
434
607
  };
435
608
  }
436
609
  function unmarkInert(element) {
437
- const index = inertStack.findIndex((item) => item.element === element);
438
- if (index < 0) return;
439
- inertStack[index].count--;
440
- if (inertStack[index].count <= 0) {
441
- const { originalAriaHidden, originalInert } = inertStack[index];
442
- if (supportsNativeInert(element)) element.inert = originalInert;
443
- if (originalAriaHidden === null) element.removeAttribute("aria-hidden");
444
- else element.setAttribute("aria-hidden", originalAriaHidden);
445
- inertStack.splice(index, 1);
610
+ const item = inertStates.get(element);
611
+ if (!item) return;
612
+ item.count--;
613
+ if (item.count <= 0) {
614
+ element.inert = item.originalInert;
615
+ inertStates.delete(element);
446
616
  }
447
617
  }
448
618
  //#endregion
@@ -454,10 +624,12 @@ function onClickOutside(elements, callback) {
454
624
  function handler(event) {
455
625
  const target = event.target;
456
626
  for (const el of targets) if (el.contains(target)) return;
457
- let node = target;
627
+ let node = target instanceof Element ? target : target?.parentElement;
458
628
  while (node) {
459
- if (node instanceof HTMLElement && node.hasAttribute("data-inertiaui-portal")) return;
460
- node = node.parentNode;
629
+ const portal = node.closest("[data-inertiaui-portal]");
630
+ if (!portal) break;
631
+ if (portal instanceof HTMLElement) return;
632
+ node = portal.parentElement;
461
633
  }
462
634
  callback(event);
463
635
  }
@@ -496,40 +668,42 @@ function createMenuNavigation(container, options = {}) {
496
668
  function getItems() {
497
669
  return Array.from(container.querySelectorAll(itemSelector));
498
670
  }
499
- function getActiveIndex() {
500
- const items = getItems();
671
+ function getActiveIndex(items) {
501
672
  const focused = document.activeElement;
502
673
  return items.indexOf(focused);
503
674
  }
504
- function focusItem(index) {
505
- const items = getItems();
675
+ function focusItem(index, items) {
506
676
  if (items.length === 0) return;
507
677
  const item = items[loop ? (index % items.length + items.length) % items.length : Math.max(0, Math.min(index, items.length - 1))];
508
- items.forEach((el) => el.setAttribute("tabindex", "-1"));
509
- item.setAttribute("tabindex", "0");
678
+ items.forEach((el) => {
679
+ const value = el === item ? "0" : "-1";
680
+ if (el.getAttribute("tabindex") !== value) el.setAttribute("tabindex", value);
681
+ });
510
682
  item.focus();
511
683
  }
512
684
  function handleKeyDown(event) {
513
- const items = getItems();
514
- if (items.length === 0) return;
515
685
  const nextKey = orientation === "vertical" ? "ArrowDown" : "ArrowRight";
516
686
  const prevKey = orientation === "vertical" ? "ArrowUp" : "ArrowLeft";
687
+ const typeAheadKey = typeAhead && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
688
+ if (event.key !== nextKey && event.key !== prevKey && event.key !== "Home" && event.key !== "End" && event.key !== "Enter" && event.key !== " " && !typeAheadKey) return;
689
+ const items = getItems();
690
+ if (items.length === 0) return;
517
691
  switch (event.key) {
518
692
  case nextKey:
519
693
  event.preventDefault();
520
- focusItem(getActiveIndex() + 1);
694
+ focusItem(getActiveIndex(items) + 1, items);
521
695
  break;
522
696
  case prevKey:
523
697
  event.preventDefault();
524
- focusItem(getActiveIndex() - 1);
698
+ focusItem(getActiveIndex(items) - 1, items);
525
699
  break;
526
700
  case "Home":
527
701
  event.preventDefault();
528
- focusItem(0);
702
+ focusItem(0, items);
529
703
  break;
530
704
  case "End":
531
705
  event.preventDefault();
532
- focusItem(items.length - 1);
706
+ focusItem(items.length - 1, items);
533
707
  break;
534
708
  case "Enter":
535
709
  case " ": {
@@ -542,7 +716,7 @@ function createMenuNavigation(container, options = {}) {
542
716
  break;
543
717
  }
544
718
  default:
545
- if (typeAhead && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
719
+ if (typeAheadKey) {
546
720
  event.preventDefault();
547
721
  typeAheadBuffer += event.key.toLowerCase();
548
722
  if (typeAheadTimeout) clearTimeout(typeAheadTimeout);
@@ -552,7 +726,7 @@ function createMenuNavigation(container, options = {}) {
552
726
  const match = items.find((item) => {
553
727
  return (item.textContent || "").trim().toLowerCase().startsWith(typeAheadBuffer);
554
728
  });
555
- if (match) focusItem(items.indexOf(match));
729
+ if (match) focusItem(items.indexOf(match), items);
556
730
  }
557
731
  break;
558
732
  }
@@ -695,51 +869,81 @@ function moveArrayItem(items, fromIndex, toIndex) {
695
869
  return nextItems;
696
870
  }
697
871
  function identityOrder(length) {
698
- return Array.from({ length }, (_, index) => index);
872
+ const order = new Array(length);
873
+ for (let index = 0; index < length; index++) order[index] = index;
874
+ return order;
699
875
  }
700
876
  function isHTMLElement(value) {
701
877
  return typeof HTMLElement !== "undefined" && value instanceof HTMLElement;
702
878
  }
703
- function getValidReorderHitBoxes(hitBoxes) {
704
- return hitBoxes.filter((hitBox) => Number.isFinite(hitBox.index) && Number.isFinite(hitBox.left) && Number.isFinite(hitBox.top) && Number.isFinite(hitBox.right) && Number.isFinite(hitBox.bottom) && hitBox.left <= hitBox.right && hitBox.top <= hitBox.bottom);
705
- }
706
- function getOrderedReorderHitBoxes(hitBoxes) {
707
- return getValidReorderHitBoxes(hitBoxes).sort((first, second) => first.index - second.index);
879
+ function isMeasuredHitBox(hitBox) {
880
+ return Number.isFinite(hitBox.index) && Number.isFinite(hitBox.left) && Number.isFinite(hitBox.top) && Number.isFinite(hitBox.right) && Number.isFinite(hitBox.bottom) && hitBox.left <= hitBox.right && hitBox.top <= hitBox.bottom;
881
+ }
882
+ /** Move a point inside the area the measured items cover. */
883
+ function clampToHitBoxes(hitBoxes, point) {
884
+ let left = Infinity;
885
+ let top = Infinity;
886
+ let right = -Infinity;
887
+ let bottom = -Infinity;
888
+ for (const hitBox of hitBoxes) if (isMeasuredHitBox(hitBox)) {
889
+ left = Math.min(left, hitBox.left);
890
+ top = Math.min(top, hitBox.top);
891
+ right = Math.max(right, hitBox.right);
892
+ bottom = Math.max(bottom, hitBox.bottom);
893
+ }
894
+ return {
895
+ clientX: Math.min(Math.max(point.clientX, left), right),
896
+ clientY: Math.min(Math.max(point.clientY, top), bottom)
897
+ };
708
898
  }
709
899
  /**
710
- * Given the on-screen hit boxes of each item and a pointer position, resolve the
711
- * insertion index (0..count) the pointer currently maps to, or `null` when the
712
- * point falls outside the combined bounds. Handles both single-column (vertical
713
- * midpoint) and multi-item rows (horizontal midpoint) layouts.
900
+ * Resolve the insertion index for vertical lists and multi-item rows. Select
901
+ * the first matching item by index (or left edge within a row) in one pass,
902
+ * without sorting or allocating temporary arrays on every pointer move.
714
903
  */
715
904
  function getInsertionIndexFromPoint(hitBoxes, point, options = {}) {
716
- const orderedHitBoxes = getOrderedReorderHitBoxes(hitBoxes);
717
- if (orderedHitBoxes.length === 0) return null;
718
- const left = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.left));
719
- const top = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.top));
720
- const right = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.right));
721
- const bottom = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.bottom));
905
+ let left = Infinity;
906
+ let top = Infinity;
907
+ let right = -Infinity;
908
+ let bottom = -Infinity;
909
+ let firstIndex = Infinity;
910
+ let lastIndex = -Infinity;
911
+ let verticalIndex = Infinity;
912
+ let rowCount = 0;
913
+ let rowMatch = null;
914
+ let rowLast = null;
915
+ let rowMatchStart = 0;
916
+ let rowLastStart = 0;
917
+ const reading = options.rightToLeft ? -1 : 1;
918
+ for (const hitBox of hitBoxes) {
919
+ if (!isMeasuredHitBox(hitBox)) continue;
920
+ left = Math.min(left, hitBox.left);
921
+ top = Math.min(top, hitBox.top);
922
+ right = Math.max(right, hitBox.right);
923
+ bottom = Math.max(bottom, hitBox.bottom);
924
+ firstIndex = Math.min(firstIndex, hitBox.index);
925
+ lastIndex = Math.max(lastIndex, hitBox.index);
926
+ if (point.clientY <= hitBox.top + (hitBox.bottom - hitBox.top) / 2) verticalIndex = Math.min(verticalIndex, hitBox.index);
927
+ if (point.clientY >= hitBox.top && point.clientY <= hitBox.bottom) {
928
+ rowCount++;
929
+ const start = options.rightToLeft ? -hitBox.right : hitBox.left;
930
+ if (!rowLast || start > rowLastStart || start === rowLastStart && hitBox.index > rowLast.index) {
931
+ rowLast = hitBox;
932
+ rowLastStart = start;
933
+ }
934
+ if (reading * point.clientX <= reading * (hitBox.left + (hitBox.right - hitBox.left) / 2) && (!rowMatch || start < rowMatchStart || start === rowMatchStart && hitBox.index < rowMatch.index)) {
935
+ rowMatch = hitBox;
936
+ rowMatchStart = start;
937
+ }
938
+ }
939
+ }
940
+ if (firstIndex === Infinity) return null;
722
941
  const bounds = options.bounds;
723
- const activeLeft = bounds ? Math.min(left, bounds.left) : left;
724
- const activeTop = bounds ? Math.min(top, bounds.top) : top;
725
- const activeRight = bounds ? Math.max(right, bounds.right) : right;
726
- const activeBottom = bounds ? Math.max(bottom, bounds.bottom) : bottom;
727
- if (point.clientX < activeLeft || point.clientX > activeRight || point.clientY < activeTop || point.clientY > activeBottom) return null;
728
- if (point.clientY < top) return orderedHitBoxes[0].index;
729
- if (point.clientY > bottom) return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
730
- const hitBoxesOnCurrentRow = orderedHitBoxes.filter((hitBox) => point.clientY >= hitBox.top && point.clientY <= hitBox.bottom).sort((first, second) => first.left - second.left || first.index - second.index);
731
- if (hitBoxesOnCurrentRow.length > 1) {
732
- for (const hitBox of hitBoxesOnCurrentRow) {
733
- const midpoint = hitBox.left + (hitBox.right - hitBox.left) / 2;
734
- if (point.clientX <= midpoint) return hitBox.index;
735
- }
736
- return hitBoxesOnCurrentRow[hitBoxesOnCurrentRow.length - 1].index + 1;
737
- }
738
- for (const hitBox of orderedHitBoxes) {
739
- const midpoint = hitBox.top + (hitBox.bottom - hitBox.top) / 2;
740
- if (point.clientY <= midpoint) return hitBox.index;
741
- }
742
- return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
942
+ if (point.clientX < (bounds ? Math.min(left, bounds.left) : left) || point.clientX > (bounds ? Math.max(right, bounds.right) : right) || point.clientY < (bounds ? Math.min(top, bounds.top) : top) || point.clientY > (bounds ? Math.max(bottom, bounds.bottom) : bottom)) return null;
943
+ if (point.clientY < top) return firstIndex;
944
+ if (point.clientY > bottom) return lastIndex + 1;
945
+ if (rowCount > 1) return rowMatch ? rowMatch.index : rowLast.index + 1;
946
+ return verticalIndex === Infinity ? lastIndex + 1 : verticalIndex;
743
947
  }
744
948
  /**
745
949
  * Convert an insertion index (0..count) into the destination array index for the
@@ -754,6 +958,43 @@ function resolveTargetIndexFromInsertion(fromIndex, insertionIndex, itemCount) {
754
958
  if (targetIndex < 0 || targetIndex >= itemCount) return null;
755
959
  return targetIndex;
756
960
  }
961
+ function isPermutation(order, count) {
962
+ if (order.length !== count) return false;
963
+ const seen = new Uint8Array(count);
964
+ for (const index of order) {
965
+ if (!Number.isInteger(index) || index < 0 || index >= count || seen[index]) return false;
966
+ seen[index] = 1;
967
+ }
968
+ return true;
969
+ }
970
+ /**
971
+ * Return how far each item moves along the axis when the items are laid out in
972
+ * `order`, a permutation of their indices. The offsets describe the movement
973
+ * between the items packed in their current order and packed in `order`, so items
974
+ * of different sizes line up and an unchanged order returns zero offsets. Each gap
975
+ * between neighboring slots stays in place, or is `gap` in both layouts when
976
+ * given. An order that is not a permutation of the items leaves every item where
977
+ * it is.
978
+ */
979
+ function getReorderOffsets(rects, order, options = {}) {
980
+ const offsets = rects.map(() => 0);
981
+ if (rects.length === 0 || !isPermutation(order, rects.length)) return offsets;
982
+ const [start, end] = options.axis === "x" ? ["left", "right"] : ["top", "bottom"];
983
+ const [leading, trailing] = options.reverse ? [end, start] : [start, end];
984
+ const direction = options.reverse ? -1 : 1;
985
+ let original = 0;
986
+ let target = 0;
987
+ for (const [slot, index] of order.entries()) {
988
+ const rect = rects[slot];
989
+ const next = rects[slot + 1];
990
+ const signedGap = next ? options.gap === void 0 ? next[leading] - rect[trailing] : direction * options.gap : 0;
991
+ offsets[index] += target;
992
+ offsets[slot] -= original;
993
+ target += direction * (rects[index][end] - rects[index][start]) + signedGap;
994
+ original += direction * (rect[end] - rect[start]) + signedGap;
995
+ }
996
+ return offsets;
997
+ }
757
998
  /**
758
999
  * Return true when the event target is a reorder handle carrying
759
1000
  * `REORDERABLE_LIST_HANDLE_ATTRIBUTE="true"`.
@@ -765,6 +1006,7 @@ function isShadowRoot(value) {
765
1006
  return typeof ShadowRoot !== "undefined" && value instanceof ShadowRoot;
766
1007
  }
767
1008
  function getParentNodeAcrossShadowDom(node) {
1009
+ if (node instanceof Element && node.assignedSlot) return node.assignedSlot;
768
1010
  if (node.parentNode) return node.parentNode;
769
1011
  const root = node.getRootNode?.();
770
1012
  return isShadowRoot(root) ? root.host : null;
@@ -803,10 +1045,10 @@ function finiteNumber(value, fallback) {
803
1045
  function canOverflow(value) {
804
1046
  return value === "auto" || value === "scroll" || value === "overlay";
805
1047
  }
806
- function isScrollableElement(element) {
1048
+ function isScrollableElement(element, axis) {
807
1049
  const style = getComputedStyle(element);
808
- const canScrollY = canOverflow(style.overflowY) && element.scrollHeight > element.clientHeight;
809
- const canScrollX = canOverflow(style.overflowX) && element.scrollWidth > element.clientWidth;
1050
+ const canScrollY = axis !== "x" && canOverflow(style.overflowY) && element.scrollHeight > element.clientHeight;
1051
+ const canScrollX = axis !== "y" && canOverflow(style.overflowX) && element.scrollWidth > element.clientWidth;
810
1052
  return canScrollY || canScrollX;
811
1053
  }
812
1054
  function getOwnerWindow(element) {
@@ -816,13 +1058,18 @@ function getOwnerWindow(element) {
816
1058
  function isWindowContainer(container) {
817
1059
  return typeof Window !== "undefined" && container instanceof Window;
818
1060
  }
819
- function getScrollableAncestors(element) {
1061
+ /**
1062
+ * Ancestors of `element` that can scroll, nearest first, followed by its window.
1063
+ * Pass an axis to keep only the ancestors that scroll along it. Shadow roots are
1064
+ * crossed through their hosts.
1065
+ */
1066
+ function getScrollableAncestors(element, axis = "both") {
820
1067
  const containers = [];
821
1068
  const ownerWindow = getOwnerWindow(element);
822
1069
  let node = element;
823
1070
  while (node) {
824
1071
  node = getParentNodeAcrossShadowDom(node);
825
- if (node instanceof Element && isScrollableElement(node)) containers.push(node);
1072
+ if (node instanceof Element && isScrollableElement(node, axis)) containers.push(node);
826
1073
  }
827
1074
  if (ownerWindow) containers.push(ownerWindow);
828
1075
  return containers;
@@ -843,6 +1090,36 @@ function getScrollPosition(container, axis) {
843
1090
  if (isWindowContainer(container)) return axis === "x" ? container.scrollX : container.scrollY;
844
1091
  return axis === "x" ? container.scrollLeft : container.scrollTop;
845
1092
  }
1093
+ /** Keep initial geometry independent of preview transforms, translating only ancestor scroll displacement. */
1094
+ function createScrollAdjustedHitBox(hitBox, element) {
1095
+ const containers = [];
1096
+ const ownerWindow = getOwnerWindow(element);
1097
+ const scrollElement = ownerWindow ? getScrollElement(ownerWindow) : null;
1098
+ const windowLeft = ownerWindow?.scrollX ?? 0;
1099
+ const windowTop = ownerWindow?.scrollY ?? 0;
1100
+ let node = element;
1101
+ while (node = getParentNodeAcrossShadowDom(node)) if (node instanceof Element && node !== scrollElement) containers.push(node);
1102
+ const positions = containers.map((container) => ({
1103
+ container,
1104
+ left: container.scrollLeft,
1105
+ top: container.scrollTop
1106
+ }));
1107
+ return () => {
1108
+ let left = (ownerWindow?.scrollX ?? 0) - windowLeft;
1109
+ let top = (ownerWindow?.scrollY ?? 0) - windowTop;
1110
+ for (const position of positions) {
1111
+ left += position.container.scrollLeft - position.left;
1112
+ top += position.container.scrollTop - position.top;
1113
+ }
1114
+ return {
1115
+ index: hitBox.index,
1116
+ left: hitBox.left - left,
1117
+ top: hitBox.top - top,
1118
+ right: hitBox.right - left,
1119
+ bottom: hitBox.bottom - top
1120
+ };
1121
+ };
1122
+ }
846
1123
  function getMaxScrollPosition(container, axis) {
847
1124
  if (isWindowContainer(container)) {
848
1125
  const scrollElement = getScrollElement(container);
@@ -851,9 +1128,14 @@ function getMaxScrollPosition(container, axis) {
851
1128
  }
852
1129
  return Math.max(0, axis === "x" ? container.scrollWidth - container.clientWidth : container.scrollHeight - container.clientHeight);
853
1130
  }
854
- function canScroll(container, axis, direction) {
1131
+ function scrollsRightToLeft(container) {
1132
+ const element = isWindowContainer(container) ? getScrollElement(container) : container;
1133
+ return element !== null && getComputedStyle(element).direction === "rtl";
1134
+ }
1135
+ function canScroll(container, axis, direction, isRightToLeft) {
855
1136
  const position = getScrollPosition(container, axis);
856
1137
  const maxPosition = getMaxScrollPosition(container, axis);
1138
+ if (axis === "x" && isRightToLeft(container)) return direction < 0 ? position > -maxPosition : position < 0;
857
1139
  return direction < 0 ? position > 0 : position < maxPosition;
858
1140
  }
859
1141
  function edgeIntensity(position, start, end, threshold) {
@@ -864,7 +1146,7 @@ function edgeIntensity(position, start, end, threshold) {
864
1146
  const endIntensity = endDistance < threshold ? (threshold - endDistance) / threshold : 0;
865
1147
  return endIntensity > startIntensity ? endIntensity : -startIntensity;
866
1148
  }
867
- function getAutoScrollVector(container, point, edgeThreshold, maxStep) {
1149
+ function getAutoScrollVector(container, point, edgeThreshold, maxStep, isRightToLeft) {
868
1150
  const rect = getContainerRect(container);
869
1151
  const width = rect.right - rect.left;
870
1152
  const height = rect.bottom - rect.top;
@@ -873,8 +1155,8 @@ function getAutoScrollVector(container, point, edgeThreshold, maxStep) {
873
1155
  const xIntensity = edgeIntensity(point.clientX, rect.left, rect.right, xThreshold);
874
1156
  const yIntensity = edgeIntensity(point.clientY, rect.top, rect.bottom, yThreshold);
875
1157
  return {
876
- left: xIntensity !== 0 && canScroll(container, "x", xIntensity) ? xIntensity * maxStep : 0,
877
- top: yIntensity !== 0 && canScroll(container, "y", yIntensity) ? yIntensity * maxStep : 0
1158
+ left: xIntensity !== 0 && canScroll(container, "x", xIntensity, isRightToLeft) ? xIntensity * maxStep : 0,
1159
+ top: yIntensity !== 0 && canScroll(container, "y", yIntensity, isRightToLeft) ? yIntensity * maxStep : 0
878
1160
  };
879
1161
  }
880
1162
  function scrollContainer(container, left, top) {
@@ -907,10 +1189,19 @@ function createAutoScroller(options = {}) {
907
1189
  let frameId = null;
908
1190
  let lastTimestamp = null;
909
1191
  let cleaned = false;
1192
+ const rightToLeft = /* @__PURE__ */ new Map();
910
1193
  function queueFrame() {
911
1194
  if (cleaned || frameId !== null || typeof requestAnimationFrame !== "function") return;
912
1195
  frameId = requestAnimationFrame(step);
913
1196
  }
1197
+ function readsRightToLeft(container) {
1198
+ let value = rightToLeft.get(container);
1199
+ if (value === void 0) {
1200
+ value = scrollsRightToLeft(container);
1201
+ rightToLeft.set(container, value);
1202
+ }
1203
+ return value;
1204
+ }
914
1205
  function stop() {
915
1206
  if (frameId !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frameId);
916
1207
  latestPoint = null;
@@ -918,6 +1209,7 @@ function createAutoScroller(options = {}) {
918
1209
  containers = [];
919
1210
  frameId = null;
920
1211
  lastTimestamp = null;
1212
+ rightToLeft.clear();
921
1213
  }
922
1214
  function step(timestamp) {
923
1215
  frameId = null;
@@ -928,7 +1220,7 @@ function createAutoScroller(options = {}) {
928
1220
  let handledY = axis === "x";
929
1221
  lastTimestamp = timestamp;
930
1222
  for (const container of containers) {
931
- const vector = getAutoScrollVector(container, latestPoint, edgeThreshold, maxStep);
1223
+ const vector = getAutoScrollVector(container, latestPoint, edgeThreshold, maxStep, readsRightToLeft);
932
1224
  const left = handledX ? 0 : vector.left;
933
1225
  const top = handledY ? 0 : vector.top;
934
1226
  if (left === 0 && top === 0) continue;
@@ -963,8 +1255,7 @@ function createAutoScroller(options = {}) {
963
1255
  return {
964
1256
  update,
965
1257
  stop,
966
- cleanup,
967
- isScrolling: () => frameId !== null
1258
+ cleanup
968
1259
  };
969
1260
  }
970
1261
  var idleState = {
@@ -985,6 +1276,9 @@ function defaultReorderableListBounds(element) {
985
1276
  function getRegisteredItemElements(itemElements) {
986
1277
  return Array.from(itemElements.entries()).sort(([firstIndex], [secondIndex]) => firstIndex - secondIndex).map(([, element]) => element);
987
1278
  }
1279
+ function isValidReorderIndex(index, itemCount) {
1280
+ return Number.isInteger(index) && index >= 0 && index < itemCount;
1281
+ }
988
1282
  /**
989
1283
  * Framework-neutral list reorder controller. It combines item registration,
990
1284
  * live pointer preview ordering, keyboard moves, pointer commits, bounds, and
@@ -995,6 +1289,7 @@ function createReorderableList(options) {
995
1289
  let listElement = null;
996
1290
  let pointerState = idleState;
997
1291
  let dragHitBoxes = null;
1292
+ let dragRightToLeft = false;
998
1293
  let lastPreviewedPointerTargetIndex = null;
999
1294
  const itemElements = /* @__PURE__ */ new Map();
1000
1295
  const itemCount = () => options.getItems().length;
@@ -1014,10 +1309,10 @@ function createReorderableList(options) {
1014
1309
  };
1015
1310
  }).filter((hitBox) => hitBox !== null);
1016
1311
  };
1017
- const getHitBoxes = () => dragHitBoxes ?? measureItemHitBoxes();
1312
+ const getHitBoxes = () => dragHitBoxes?.map((getHitBox) => getHitBox()) ?? measureItemHitBoxes();
1018
1313
  const commitReorder = (fromIndex, toIndex, source, context) => {
1019
1314
  const items = options.getItems();
1020
- if (!canReorder() || fromIndex === toIndex || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length) return null;
1315
+ if (!canReorder() || fromIndex === toIndex || !isValidReorderIndex(fromIndex, items.length) || !isValidReorderIndex(toIndex, items.length)) return null;
1021
1316
  const move = {
1022
1317
  item: items[fromIndex],
1023
1318
  fromIndex,
@@ -1030,11 +1325,20 @@ function createReorderableList(options) {
1030
1325
  return move;
1031
1326
  };
1032
1327
  const pointerReorder = createPointerReorder({
1328
+ onStart: () => {
1329
+ dragHitBoxes = measureItemHitBoxes().map((hitBox) => createScrollAdjustedHitBox(hitBox, itemElements.get(hitBox.index)));
1330
+ const element = listElement ?? itemElements.values().next().value;
1331
+ dragRightToLeft = !!element && getComputedStyle(element).direction === "rtl";
1332
+ },
1333
+ isRightToLeft: () => dragRightToLeft,
1033
1334
  getItemCount: itemCount,
1034
1335
  getHitBoxes,
1035
1336
  getBounds,
1036
1337
  canReorder,
1037
1338
  autoScroll: options.autoScroll ?? false,
1339
+ activationDistance: options.activationDistance,
1340
+ suppressClickAfterDrag: options.suppressClickAfterDrag,
1341
+ getCollisionPoint: options.getCollisionPoint,
1038
1342
  onChange: (state) => {
1039
1343
  if (state.draggedIndex !== null) lastPreviewedPointerTargetIndex = state.targetIndex;
1040
1344
  pointerState = state;
@@ -1077,11 +1381,9 @@ function createReorderableList(options) {
1077
1381
  moveItem: (index, direction) => {
1078
1382
  return commitReorder(index, direction === "up" ? index - 1 : index + 1, "keyboard", { alreadyPreviewed: false });
1079
1383
  },
1080
- pointerDown: (index, event) => {
1081
- dragHitBoxes = measureItemHitBoxes();
1082
- pointerReorder.pointerDown(index, event);
1083
- if (!event.defaultPrevented) dragHitBoxes = null;
1084
- },
1384
+ pointerDown: pointerReorder.pointerDown,
1385
+ getPointer: pointerReorder.getPointer,
1386
+ cancel: pointerReorder.cancel,
1085
1387
  cleanup: () => {
1086
1388
  pointerReorder.cleanup();
1087
1389
  dragHitBoxes = null;
@@ -1099,10 +1401,13 @@ function createReorderableList(options) {
1099
1401
  function createPointerReorder(options) {
1100
1402
  const canReorder = () => (options.canReorder?.() ?? true) && options.getItemCount() > 1;
1101
1403
  let activePointer = null;
1404
+ let pendingPointer = null;
1405
+ let pointer = null;
1102
1406
  let insertionIndex = null;
1103
1407
  let pointerOverReorderArea = false;
1104
1408
  let lastPoint = null;
1105
1409
  let cleaned = false;
1410
+ const activationDistance = finiteNumber(options.activationDistance, 0);
1106
1411
  const autoScrollOptions = options.autoScroll === true ? {} : options.autoScroll || null;
1107
1412
  const autoScroller = autoScrollOptions ? createAutoScroller({
1108
1413
  ...autoScrollOptions,
@@ -1125,18 +1430,32 @@ function createPointerReorder(options) {
1125
1430
  options.onChange?.(currentState());
1126
1431
  }
1127
1432
  function updateInsertionIndex(point) {
1128
- const nextInsertionIndex = getInsertionIndexFromPoint(options.getHitBoxes(), {
1433
+ const hitBoxes = options.getHitBoxes();
1434
+ const nextInsertionIndex = getInsertionIndexFromPoint(hitBoxes, {
1129
1435
  clientX: point.clientX,
1130
1436
  clientY: point.clientY
1131
- }, { bounds: options.getBounds?.() ?? null });
1437
+ }, {
1438
+ bounds: options.getBounds?.() ?? null,
1439
+ rightToLeft: options.isRightToLeft?.()
1440
+ });
1132
1441
  pointerOverReorderArea = nextInsertionIndex !== null;
1133
- if (nextInsertionIndex !== null) insertionIndex = nextInsertionIndex;
1442
+ if (nextInsertionIndex !== null) insertionIndex = getCollisionInsertionIndex(hitBoxes) ?? nextInsertionIndex;
1443
+ }
1444
+ /** The insertion index at the caller's collision point, or null to use the pointer. */
1445
+ function getCollisionInsertionIndex(hitBoxes) {
1446
+ const getCollisionPoint = options.getCollisionPoint;
1447
+ if (!getCollisionPoint || !activePointer || !pointer) return null;
1448
+ const item = activePointer.initialItemBounds;
1449
+ const point = item ? getCollisionPoint(pointer, item) : null;
1450
+ if (!point || !Number.isFinite(point.clientX) || !Number.isFinite(point.clientY)) return null;
1451
+ return getInsertionIndexFromPoint(hitBoxes, clampToHitBoxes(hitBoxes, point), { rightToLeft: options.isRightToLeft?.() });
1134
1452
  }
1135
1453
  function updatePointerPosition(event, shouldAutoScroll) {
1136
1454
  lastPoint = {
1137
1455
  clientX: event.clientX,
1138
1456
  clientY: event.clientY
1139
1457
  };
1458
+ if (pointer) pointer.position = lastPoint;
1140
1459
  updateInsertionIndex(lastPoint);
1141
1460
  if (shouldAutoScroll) autoScroller?.update(lastPoint, activePointer?.scrollElement ?? activePointer?.captureElement ?? null);
1142
1461
  }
@@ -1146,7 +1465,10 @@ function createPointerReorder(options) {
1146
1465
  window.removeEventListener("pointermove", handleWindowPointerMove);
1147
1466
  window.removeEventListener("pointerup", handleWindowPointerUp);
1148
1467
  window.removeEventListener("pointercancel", handleWindowPointerCancel);
1468
+ window.removeEventListener("blur", cancel);
1149
1469
  activePointer = null;
1470
+ pendingPointer = null;
1471
+ pointer = null;
1150
1472
  insertionIndex = null;
1151
1473
  pointerOverReorderArea = false;
1152
1474
  lastPoint = null;
@@ -1159,26 +1481,58 @@ function createPointerReorder(options) {
1159
1481
  } catch {}
1160
1482
  }
1161
1483
  function handleWindowPointerMove(event) {
1484
+ const pending = pendingPointer;
1485
+ if (pending?.pointerId === event.pointerId && pointer) {
1486
+ if (Math.hypot(event.clientX - pointer.origin.clientX, event.clientY - pointer.origin.clientY) < activationDistance) return;
1487
+ pendingPointer = null;
1488
+ if (!canReorder() || !isValidReorderIndex(pending.fromIndex, options.getItemCount())) {
1489
+ stop();
1490
+ return;
1491
+ }
1492
+ activate(pending.fromIndex, event, pending.handle);
1493
+ }
1162
1494
  if (activePointer?.pointerId !== event.pointerId) return;
1163
1495
  event.preventDefault();
1164
1496
  updatePointerPosition(event, true);
1165
1497
  emitChange();
1166
1498
  }
1167
1499
  function handleWindowPointerUp(event) {
1168
- const pointer = activePointer;
1169
- if (!pointer || pointer.pointerId !== event.pointerId) return;
1500
+ if (pendingPointer?.pointerId === event.pointerId) {
1501
+ stop();
1502
+ return;
1503
+ }
1504
+ const active = activePointer;
1505
+ if (!active || active.pointerId !== event.pointerId) return;
1170
1506
  event.preventDefault();
1171
- const fromIndex = pointer.fromIndex;
1507
+ const fromIndex = active.fromIndex;
1172
1508
  const toIndex = pointerOverReorderArea ? resolveTargetIndexFromInsertion(fromIndex, insertionIndex, options.getItemCount()) : null;
1173
- stop();
1174
- emitChange();
1509
+ end();
1175
1510
  if (toIndex !== null && fromIndex !== toIndex) options.onCommit(fromIndex, toIndex, "pointer");
1176
1511
  }
1177
1512
  function handleWindowPointerCancel(event) {
1178
- if (activePointer?.pointerId !== event.pointerId) return;
1513
+ if (pendingPointer?.pointerId === event.pointerId) stop();
1514
+ else if (activePointer?.pointerId === event.pointerId) end(false);
1515
+ }
1516
+ /** Stop an active drag and report the idle state, keeping its click from activating whatever is under the pointer. */
1517
+ function end(suppressFollowingClick = options.suppressClickAfterDrag ?? false) {
1179
1518
  stop();
1519
+ if (suppressFollowingClick) {
1520
+ window.addEventListener("click", suppressClick, { capture: true });
1521
+ window.addEventListener("pointerdown", releaseClick, { capture: true });
1522
+ window.addEventListener("keydown", releaseClick, { capture: true });
1523
+ }
1180
1524
  emitChange();
1181
1525
  }
1526
+ function suppressClick(event) {
1527
+ event.preventDefault();
1528
+ event.stopPropagation();
1529
+ releaseClick();
1530
+ }
1531
+ function releaseClick() {
1532
+ window.removeEventListener("click", suppressClick, { capture: true });
1533
+ window.removeEventListener("pointerdown", releaseClick, { capture: true });
1534
+ window.removeEventListener("keydown", releaseClick, { capture: true });
1535
+ }
1182
1536
  function bindPointerCapture(element, pointerId) {
1183
1537
  if (typeof element.setPointerCapture !== "function") return null;
1184
1538
  try {
@@ -1190,32 +1544,60 @@ function createPointerReorder(options) {
1190
1544
  }
1191
1545
  function pointerDown(index, event) {
1192
1546
  const handle = findReorderHandle(event);
1193
- if (cleaned || !canReorder() || activePointer || event.button !== 0 || event.isPrimary === false || !handle) return;
1547
+ if (cleaned || !canReorder() || !isValidReorderIndex(index, options.getItemCount()) || activePointer || pendingPointer || event.button !== 0 || event.isPrimary === false || !handle) return;
1548
+ const origin = {
1549
+ clientX: event.clientX,
1550
+ clientY: event.clientY
1551
+ };
1552
+ pointer = {
1553
+ origin,
1554
+ position: origin
1555
+ };
1556
+ window.addEventListener("pointermove", handleWindowPointerMove, { passive: false });
1557
+ window.addEventListener("pointerup", handleWindowPointerUp);
1558
+ window.addEventListener("pointercancel", handleWindowPointerCancel);
1559
+ window.addEventListener("blur", cancel);
1560
+ if (activationDistance > 0) {
1561
+ pendingPointer = {
1562
+ fromIndex: index,
1563
+ pointerId: event.pointerId,
1564
+ handle
1565
+ };
1566
+ return;
1567
+ }
1568
+ activate(index, event, handle);
1569
+ emitChange();
1570
+ }
1571
+ /** Turn an accepted press into a drag: measure, claim the pointer, and stop native defaults. */
1572
+ function activate(fromIndex, event, handle) {
1573
+ options.onStart();
1194
1574
  event.preventDefault();
1195
1575
  const captureElement = bindPointerCapture(handle, event.pointerId);
1196
1576
  activePointer = {
1197
- fromIndex: index,
1577
+ fromIndex,
1198
1578
  pointerId: event.pointerId,
1199
1579
  captureElement,
1200
- scrollElement: handle
1580
+ scrollElement: handle,
1581
+ initialItemBounds: options.getHitBoxes().find((hitBox) => hitBox.index === fromIndex) ?? null
1201
1582
  };
1202
- insertionIndex = index;
1583
+ insertionIndex = fromIndex;
1203
1584
  pointerOverReorderArea = true;
1204
- window.addEventListener("pointermove", handleWindowPointerMove, { passive: false });
1205
- window.addEventListener("pointerup", handleWindowPointerUp);
1206
- window.addEventListener("pointercancel", handleWindowPointerCancel);
1207
- emitChange();
1585
+ }
1586
+ function cancel() {
1587
+ if (activePointer) end();
1588
+ else if (pendingPointer) stop();
1208
1589
  }
1209
1590
  function cleanup() {
1210
1591
  if (cleaned) return;
1211
1592
  cleaned = true;
1212
1593
  stop();
1594
+ releaseClick();
1213
1595
  autoScroller?.cleanup();
1214
1596
  }
1215
1597
  return {
1216
1598
  pointerDown,
1217
- getState: currentState,
1218
- isDragging: () => activePointer !== null,
1599
+ getPointer: () => activePointer ? pointer : null,
1600
+ cancel,
1219
1601
  cleanup
1220
1602
  };
1221
1603
  }
@@ -1234,6 +1616,48 @@ function focusFirstEnabledElement(elements, options) {
1234
1616
  return false;
1235
1617
  }
1236
1618
  //#endregion
1619
+ //#region src/rtl.ts
1620
+ /**
1621
+ * Check whether the document is currently in RTL direction.
1622
+ */
1623
+ function isRtl() {
1624
+ return document.documentElement.dir === "rtl";
1625
+ }
1626
+ /**
1627
+ * Check whether an element is written right to left, from its computed `direction`. Unlike `isRtl()`, this follows a
1628
+ * `dir` attribute on any ancestor, such as a right-to-left section in a left-to-right page.
1629
+ */
1630
+ function isRightToLeft(element) {
1631
+ return getComputedStyle(element).direction === "rtl";
1632
+ }
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();
1646
+ }
1647
+ /**
1648
+ * Give a panel rendered away from its reference, such as in the body, the
1649
+ * direction the reference is written in. A panel with its own `dir` keeps it.
1650
+ * Returns a cleanup function that removes the direction again.
1651
+ */
1652
+ function followReferenceDirection(reference, panel) {
1653
+ const direction = getComputedStyle(reference).direction;
1654
+ if (panel.hasAttribute("dir") || getComputedStyle(panel).direction === direction) return () => {};
1655
+ panel.setAttribute("dir", direction);
1656
+ return () => {
1657
+ if (panel.getAttribute("dir") === direction) panel.removeAttribute("dir");
1658
+ };
1659
+ }
1660
+ //#endregion
1237
1661
  //#region src/position/style.ts
1238
1662
  function setStyleProperty(style, property, value) {
1239
1663
  if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
@@ -1283,6 +1707,68 @@ function supportsTopLayerAnchorSizing() {
1283
1707
  return _supportsTopLayerAnchorSizing;
1284
1708
  }
1285
1709
  var anchorStyleId = "inertiaui-anchor-styles";
1710
+ var anchorRules = /* @__PURE__ */ new WeakMap();
1711
+ var referenceAnchors = /* @__PURE__ */ new WeakMap();
1712
+ var anchorOwners = /* @__PURE__ */ new WeakMap();
1713
+ function anchorNames(value) {
1714
+ return value.split(",").map((name) => name.trim()).filter((name) => name.startsWith("--"));
1715
+ }
1716
+ function syncReferenceAnchors(reference, state) {
1717
+ const current = captureStyleProperty(reference.style, "anchor-name");
1718
+ if (current.value !== state.written.value || current.priority !== state.written.priority) state.original = {
1719
+ value: anchorNames(current.value).filter((name) => !state.names.has(name)).join(", ") || (current.value === "none" ? "none" : ""),
1720
+ priority: current.priority
1721
+ };
1722
+ return current;
1723
+ }
1724
+ function acquireReferenceAnchor(reference, floating) {
1725
+ const owner = anchorOwners.get(floating);
1726
+ const canReuse = owner?.reference === reference && floating.classList.contains(owner.className);
1727
+ if (!canReuse) detachAnchorPositioning(reference, floating);
1728
+ const className = canReuse ? owner.className : generateId(ANCHOR_CLASS_PREFIX);
1729
+ const name = `--${className}`;
1730
+ let state = referenceAnchors.get(reference);
1731
+ if (!state) {
1732
+ const original = captureStyleProperty(reference.style, "anchor-name");
1733
+ state = {
1734
+ original,
1735
+ written: original,
1736
+ names: /* @__PURE__ */ new Set()
1737
+ };
1738
+ referenceAnchors.set(reference, state);
1739
+ }
1740
+ const current = syncReferenceAnchors(reference, state);
1741
+ const names = anchorNames(current.value || getComputedStyle(reference).getPropertyValue("anchor-name"));
1742
+ if (!names.includes(name)) {
1743
+ names.push(name);
1744
+ reference.style.setProperty("anchor-name", names.join(", "), current.priority);
1745
+ }
1746
+ state.names.add(name);
1747
+ state.written = captureStyleProperty(reference.style, "anchor-name");
1748
+ anchorOwners.set(floating, {
1749
+ reference,
1750
+ className
1751
+ });
1752
+ return className;
1753
+ }
1754
+ function releaseReferenceAnchor(floating) {
1755
+ const owner = anchorOwners.get(floating);
1756
+ if (!owner) return;
1757
+ const { reference, className } = owner;
1758
+ const state = referenceAnchors.get(reference);
1759
+ const current = syncReferenceAnchors(reference, state);
1760
+ const name = `--${className}`;
1761
+ state.names.delete(name);
1762
+ if (state.names.size === 0) {
1763
+ restoreStyleProperty(reference.style, "anchor-name", state.original);
1764
+ referenceAnchors.delete(reference);
1765
+ } else {
1766
+ const names = anchorNames(current.value).filter((entry) => entry !== name);
1767
+ reference.style.setProperty("anchor-name", names.join(", "), current.priority);
1768
+ state.written = captureStyleProperty(reference.style, "anchor-name");
1769
+ }
1770
+ anchorOwners.delete(floating);
1771
+ }
1286
1772
  function ensureAnchorStylesheet() {
1287
1773
  let style = document.getElementById(anchorStyleId);
1288
1774
  if (!style) {
@@ -1303,38 +1789,52 @@ function removeAnchorRule(className) {
1303
1789
  return;
1304
1790
  }
1305
1791
  }
1792
+ function updateAnchorRule(reference, floating, className, source, sheet) {
1793
+ const cached = anchorRules.get(floating);
1794
+ if (!cached || cached.reference !== reference || cached.source !== source || cached.rule.cssText !== cached.cssText || !Array.from(sheet.cssRules).includes(cached.rule)) {
1795
+ removeAnchorRule(className);
1796
+ const index = sheet.insertRule(source, sheet.cssRules.length);
1797
+ const inserted = sheet.cssRules[index];
1798
+ anchorRules.set(floating, {
1799
+ reference,
1800
+ source,
1801
+ rule: inserted,
1802
+ cssText: inserted.cssText
1803
+ });
1804
+ }
1805
+ }
1306
1806
  function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1307
- const id = generateId(ANCHOR_CLASS_PREFIX);
1308
- const anchorName = `--${id}`;
1309
- reference.style.anchorName = anchorName;
1310
- floating.style.positionAnchor = anchorName;
1311
- floating.style.position = "fixed";
1807
+ const className = acquireReferenceAnchor(reference, floating);
1808
+ const anchorName = `--${className}`;
1809
+ setStyleProperty(floating.style, "position-anchor", anchorName);
1810
+ removeStyleProperty(floating.style, "inset");
1811
+ setStyleProperty(floating.style, "position", "fixed");
1312
1812
  const sheet = ensureAnchorStylesheet();
1313
- const className = id;
1314
- const positionRules = getAnchorPositionRules(placement, offset);
1813
+ const positionRules = getAnchorPositionRules(placement, offset, isRightToLeft(reference));
1315
1814
  let tryFallback = "";
1316
1815
  if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;`;
1317
- const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1318
- sheet.insertRule(rule, sheet.cssRules.length);
1319
- floating.classList.add(className);
1816
+ updateAnchorRule(reference, floating, className, `.${className} { ${positionRules} ${tryFallback} }`, sheet);
1817
+ if (!floating.classList.contains(className)) floating.classList.add(className);
1320
1818
  return className;
1321
1819
  }
1322
1820
  function cleanupAnchorPositioning(reference, floating, className) {
1323
- reference.style.anchorName = "";
1324
- floating.style.positionAnchor = "";
1821
+ anchorRules.delete(floating);
1822
+ releaseReferenceAnchor(floating);
1823
+ removeStyleProperty(floating.style, "position-anchor");
1325
1824
  floating.style.position = "";
1326
1825
  floating.classList.remove(className);
1327
1826
  removeAnchorRule(className);
1328
1827
  }
1329
1828
  function detachAnchorPositioning(reference, floating) {
1330
- reference.style.removeProperty("anchor-name");
1829
+ anchorRules.delete(floating);
1830
+ releaseReferenceAnchor(floating);
1331
1831
  floating.style.removeProperty("position-anchor");
1332
1832
  for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1333
1833
  floating.classList.remove(className);
1334
1834
  removeAnchorRule(className);
1335
1835
  }
1336
1836
  }
1337
- function getAnchorPositionRules(placement, offset) {
1837
+ function getAnchorPositionRules(placement, offset, rtl) {
1338
1838
  const [side, alignment] = placement.split("-");
1339
1839
  let positionRules = "";
1340
1840
  switch (side) {
@@ -1357,10 +1857,10 @@ function getAnchorPositionRules(placement, offset) {
1357
1857
  }
1358
1858
  if (side === "bottom" || side === "top") switch (alignment) {
1359
1859
  case "start":
1360
- positionRules += `left: anchor(left);`;
1860
+ positionRules += rtl ? `right: anchor(right);` : `left: anchor(left);`;
1361
1861
  break;
1362
1862
  case "end":
1363
- positionRules += `right: anchor(right);`;
1863
+ positionRules += rtl ? `left: anchor(left);` : `right: anchor(right);`;
1364
1864
  break;
1365
1865
  default:
1366
1866
  positionRules += `left: anchor(center); translate: -50% 0;`;
@@ -1386,16 +1886,10 @@ function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1386
1886
  return "";
1387
1887
  }
1388
1888
  function setupTopLayerAnchorPositioning(reference, floating, placement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1389
- const existingClass = findAnchorClass(floating);
1390
- const existingAnchorName = existingClass ? `--${existingClass}` : "";
1391
- const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1392
- const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1889
+ const className = acquireReferenceAnchor(reference, floating);
1393
1890
  const anchorName = `--${className}`;
1394
1891
  const sheet = ensureAnchorStylesheet();
1395
- if (canReuseAnchor) removeAnchorRule(className);
1396
- else detachAnchorPositioning(reference, floating);
1397
- reference.style.anchorName = anchorName;
1398
- floating.style.positionAnchor = anchorName;
1892
+ setStyleProperty(floating.style, "position-anchor", anchorName);
1399
1893
  removeStyleProperty(floating.style, "inset");
1400
1894
  removeStyleProperty(floating.style, "top");
1401
1895
  removeStyleProperty(floating.style, "right");
@@ -1408,9 +1902,8 @@ function setupTopLayerAnchorPositioning(reference, floating, placement, offset,
1408
1902
  removeStyleProperty(floating.style, "max-height");
1409
1903
  } else removeStyleProperty(floating.style, "height");
1410
1904
  if (matchReferenceWidth) setStyleProperty(floating.style, "width", `min(anchor-size(width), ${maxWidth}px)`);
1411
- const rule = `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset)} ${flip ? "position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;" : ""} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`;
1412
- sheet.insertRule(rule, sheet.cssRules.length);
1413
- floating.classList.add(className);
1905
+ updateAnchorRule(reference, floating, className, `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset, isRightToLeft(reference))} ${flip ? "position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;" : ""} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`, sheet);
1906
+ if (!floating.classList.contains(className)) floating.classList.add(className);
1414
1907
  return className;
1415
1908
  }
1416
1909
  //#endregion
@@ -1503,11 +1996,10 @@ function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSiz
1503
1996
  if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1504
1997
  return preferredPlacement;
1505
1998
  }
1506
- function computePositionFromRect(refRect, floatingRect, placement, offset) {
1999
+ function computePositionFromRect(refRect, floatingRect, placement, offset, rtl = isRtl$1()) {
1507
2000
  let x = 0;
1508
2001
  let y = 0;
1509
2002
  const [side, alignment] = placement.split("-");
1510
- const rtl = isRtl$1();
1511
2003
  switch (side) {
1512
2004
  case "bottom":
1513
2005
  y = refRect.bottom + offset;
@@ -1575,12 +2067,16 @@ function clampToViewport(x, y, floatingRect) {
1575
2067
  function computeWithFallback(reference, floating, options = {}, referenceRect) {
1576
2068
  const { placement = "bottom-start", offset = 0, flip = true } = options;
1577
2069
  const refRect = referenceRect ?? reference.getBoundingClientRect();
1578
- const floatingRect = floating.getBoundingClientRect();
1579
- let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset);
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);
1580
2076
  let actualPlacement = placement;
1581
2077
  if (flip && wouldOverflow(x, y, floatingRect, placement)) {
1582
2078
  const flipped = getOppositePlacement(placement);
1583
- const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset);
2079
+ const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset, rtl);
1584
2080
  if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
1585
2081
  x = flippedPos.x;
1586
2082
  y = flippedPos.y;
@@ -1623,9 +2119,9 @@ function applySize(reference, floating, offset, side, refRect) {
1623
2119
  floating.style.overflowY = "auto";
1624
2120
  }
1625
2121
  function computePosition(reference, floating, options = {}) {
1626
- const { placement = "bottom-start", offset = 0, flip = true, autoSize = false } = options;
1627
- if (supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1628
- if (!findAnchorClass(floating)) setupAnchorPositioning(reference, floating, placement, offset, flip);
2122
+ const { placement = "bottom-start", offset = 0, flip = true, autoSize = false, anchorPositioning = true } = options;
2123
+ if (anchorPositioning && supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
2124
+ setupAnchorPositioning(reference, floating, placement, offset, flip);
1629
2125
  if (autoSize) applySize(reference, floating, offset);
1630
2126
  const rect = floating.getBoundingClientRect();
1631
2127
  return {
@@ -1634,6 +2130,10 @@ function computePosition(reference, floating, options = {}) {
1634
2130
  placement
1635
2131
  };
1636
2132
  }
2133
+ const anchorClass = findAnchorClass(floating);
2134
+ if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
2135
+ floating.style.position = "fixed";
2136
+ floating.style.inset = "auto";
1637
2137
  let referenceRect;
1638
2138
  if (autoSize) {
1639
2139
  referenceRect = reference.getBoundingClientRect();
@@ -1644,7 +2144,6 @@ function computePosition(reference, floating, options = {}) {
1644
2144
  offset,
1645
2145
  flip
1646
2146
  }, referenceRect);
1647
- floating.style.position = "fixed";
1648
2147
  floating.style.top = `${result.y}px`;
1649
2148
  floating.style.left = `${result.x}px`;
1650
2149
  if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0], referenceRect);
@@ -1774,13 +2273,19 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1774
2273
  setStyleProperty(floating.style, "overscroll-behavior", "contain");
1775
2274
  const referenceRect = reference.getBoundingClientRect();
1776
2275
  const viewportHeight = Math.max(0, Math.floor(viewport.height - viewportMargin * 2));
1777
- if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1778
- if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
2276
+ function resolvePlacement() {
1779
2277
  const measuredRect = floating.getBoundingClientRect();
1780
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
2278
+ return resolveTopLayerPlacement(placement, referenceRect, {
1781
2279
  width: Math.max(measuredRect.width, floating.scrollWidth),
1782
2280
  height: Math.max(measuredRect.height, floating.scrollHeight)
1783
2281
  }, viewport, offset, viewportMargin, flip);
2282
+ }
2283
+ if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
2284
+ let resolvedPlacement = placement;
2285
+ if (flip) {
2286
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
2287
+ resolvedPlacement = resolvePlacement();
2288
+ }
1784
2289
  const [resolvedSide] = resolvedPlacement.split("-");
1785
2290
  const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1786
2291
  if (stretchToAvailableHeight) removeStyleProperty(floating.style, "max-height");
@@ -1803,17 +2308,14 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1803
2308
  setStyleProperty(floating.style, "margin", "0");
1804
2309
  removeStyleProperty(floating.style, "height");
1805
2310
  if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1806
- const measuredRect = floating.getBoundingClientRect();
1807
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1808
- width: Math.max(measuredRect.width, floating.scrollWidth),
1809
- height: Math.max(measuredRect.height, floating.scrollHeight)
1810
- }, viewport, offset, viewportMargin, flip);
2311
+ let resolvedPlacement = placement;
2312
+ if (flip) resolvedPlacement = resolvePlacement();
1811
2313
  const [resolvedSide] = resolvedPlacement.split("-");
1812
2314
  const availableHeight = Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin))));
1813
2315
  if (resolvedSide === "top" || resolvedSide === "bottom") setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1814
2316
  else setStyleProperty(floating.style, "max-height", `${viewportHeight}px`);
1815
2317
  const floatingRect = floating.getBoundingClientRect();
1816
- const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
2318
+ const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset, isRightToLeft(reference));
1817
2319
  const { x, y } = clampTopLayerCoordinates(coordinates.x, coordinates.y, floatingRect, resolvedPlacement, viewport, viewportMargin);
1818
2320
  setStyleProperty(floating.style, "left", `${Math.round(x)}px`);
1819
2321
  setStyleProperty(floating.style, "top", `${Math.round(y)}px`);
@@ -2094,16 +2596,12 @@ function createPopoverController(options) {
2094
2596
  let mountedPanel = null;
2095
2597
  let pointerStartedOpen = false;
2096
2598
  let focusLast = false;
2097
- const disclosure = createNativePopoverDisclosure({
2599
+ const disclosureOptions = {
2098
2600
  reference: options.reference,
2099
2601
  popover: options.popover,
2100
2602
  get position() {
2101
- let placement = options.position.placement ?? "bottom-start";
2102
- const reference = options.reference();
2103
- if (reference && getComputedStyle(reference).direction === "rtl" && /^(top|bottom)-/.test(placement)) placement = placement.replace(/start|end/, (side) => side === "start" ? "end" : "start");
2104
2603
  return {
2105
2604
  ...options.position,
2106
- placement,
2107
2605
  anchorPositioning: native && options.position.anchorPositioning !== false
2108
2606
  };
2109
2607
  },
@@ -2113,11 +2611,15 @@ function createPopoverController(options) {
2113
2611
  onDismiss: () => close(false)
2114
2612
  },
2115
2613
  onOpenChange: options.onOpenChange
2116
- });
2614
+ };
2615
+ let disclosure;
2616
+ function getDisclosure() {
2617
+ return disclosure ??= createNativePopoverDisclosure(disclosureOptions);
2618
+ }
2117
2619
  function cleanup(hide = true) {
2118
2620
  cleanups.forEach((cleanup) => cleanup());
2119
2621
  cleanups = [];
2120
- disclosure.cleanupPopover();
2622
+ disclosure?.cleanupPopover();
2121
2623
  if (hide && native && mountedPanel?.matches(":popover-open")) mountedPanel.hidePopover();
2122
2624
  mountedPanel = null;
2123
2625
  }
@@ -2129,7 +2631,7 @@ function createPopoverController(options) {
2129
2631
  return typeof document !== "undefined" && (!!mountedPanel?.contains(document.activeElement) || document.activeElement === document.body);
2130
2632
  }
2131
2633
  function close(restoreFocus = shouldReturnFocus()) {
2132
- disclosure.closePopover({
2634
+ disclosure?.closePopover({
2133
2635
  hide: false,
2134
2636
  onClose() {
2135
2637
  cleanup();
@@ -2139,25 +2641,26 @@ function createPopoverController(options) {
2139
2641
  });
2140
2642
  }
2141
2643
  function onKeydown(event) {
2142
- if (event.key === "Escape" && disclosure.isOpen) {
2644
+ if (event.key === "Escape" && disclosure?.isOpen) {
2143
2645
  event.preventDefault();
2144
2646
  event.stopPropagation();
2145
2647
  close(true);
2146
- } else if (options.menu && !disclosure.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2648
+ } else if (options.menu && !disclosure?.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2147
2649
  event.preventDefault();
2148
2650
  focusLast = event.key === "ArrowUp";
2149
- disclosure.openPopover();
2651
+ getDisclosure().openPopover();
2150
2652
  }
2151
2653
  }
2152
2654
  function mount() {
2153
2655
  const reference = options.reference();
2154
2656
  const panel = options.popover();
2155
- if (!disclosure.isOpen || !reference || !panel) return;
2657
+ if (!disclosure?.isOpen || !reference || !panel) return;
2658
+ const activeDisclosure = disclosure;
2156
2659
  cleanup();
2157
2660
  mountedPanel = panel;
2158
2661
  const onBeforeToggle = (event) => {
2159
2662
  const restoreFocus = shouldReturnFocus();
2160
- disclosure.handlePopoverToggle(event, { onClose() {
2663
+ activeDisclosure.handlePopoverToggle(event, { onClose() {
2161
2664
  cleanup(false);
2162
2665
  if (restoreFocus) returnFocus();
2163
2666
  options.onClosed?.();
@@ -2165,19 +2668,20 @@ function createPopoverController(options) {
2165
2668
  };
2166
2669
  panel.addEventListener("beforetoggle", onBeforeToggle);
2167
2670
  panel.addEventListener("keydown", onKeydown);
2168
- panel.addEventListener("focusout", disclosure.handleFocusOut);
2671
+ panel.addEventListener("focusout", activeDisclosure.handleFocusOut);
2169
2672
  cleanups.push(() => {
2170
2673
  panel.removeEventListener("beforetoggle", onBeforeToggle);
2171
2674
  panel.removeEventListener("keydown", onKeydown);
2172
- panel.removeEventListener("focusout", disclosure.handleFocusOut);
2675
+ panel.removeEventListener("focusout", activeDisclosure.handleFocusOut);
2173
2676
  });
2174
- if (native) disclosure.showPopover();
2677
+ cleanups.push(followReferenceDirection(reference, panel));
2678
+ if (native) activeDisclosure.showPopover();
2175
2679
  else {
2176
- disclosure.updatePosition();
2680
+ activeDisclosure.updatePosition();
2177
2681
  cleanups.push(onClickOutside([reference, panel], () => close()));
2178
2682
  cleanups.push(onEscapeKey(() => close(true)));
2179
2683
  }
2180
- disclosure.startAutoUpdate();
2684
+ activeDisclosure.startAutoUpdate();
2181
2685
  const cleanupMount = options.onMount?.({
2182
2686
  reference,
2183
2687
  popover: panel,
@@ -2204,22 +2708,22 @@ function createPopoverController(options) {
2204
2708
  const wasOpen = !!event?.detail && pointerStartedOpen;
2205
2709
  pointerStartedOpen = false;
2206
2710
  if (wasOpen) close();
2207
- else disclosure.togglePopover(() => disclosure.openPopover(), () => close());
2711
+ else getDisclosure().togglePopover(() => getDisclosure().openPopover(), () => close());
2208
2712
  }
2209
2713
  return {
2210
2714
  native,
2211
2715
  get isOpen() {
2212
- return disclosure.isOpen;
2716
+ return disclosure?.isOpen ?? false;
2213
2717
  },
2214
- open: () => disclosure.openPopover(),
2718
+ open: () => getDisclosure().openPopover(),
2215
2719
  close,
2216
2720
  mount,
2217
2721
  cleanup,
2218
2722
  toggle,
2219
2723
  onKeydown,
2220
- onFocusOut: disclosure.handleFocusOut,
2724
+ onFocusOut: (event) => getDisclosure().handleFocusOut(event),
2221
2725
  onPointerDown: () => {
2222
- pointerStartedOpen = disclosure.isOpen;
2726
+ pointerStartedOpen = disclosure?.isOpen ?? false;
2223
2727
  }
2224
2728
  };
2225
2729
  }
@@ -2247,8 +2751,9 @@ function blank(value) {
2247
2751
  function debounce(fn) {
2248
2752
  let frame;
2249
2753
  return (...params) => {
2250
- if (frame) cancelAnimationFrame(frame);
2754
+ if (frame !== void 0) cancelAnimationFrame(frame);
2251
2755
  frame = requestAnimationFrame(() => {
2756
+ frame = void 0;
2252
2757
  fn(...params);
2253
2758
  });
2254
2759
  };
@@ -2297,13 +2802,14 @@ function detectFramerate() {
2297
2802
  const lastTime = timestamps.pop();
2298
2803
  const fps = Math.floor(1e3 * 10 / (now - lastTime));
2299
2804
  cancelAnimationFrame(rafId);
2805
+ clearTimeout(timeoutId);
2300
2806
  resolve(Math.min(Math.max(fps, 30), 240));
2301
2807
  return;
2302
2808
  }
2303
2809
  rafId = window.requestAnimationFrame(measure);
2304
2810
  }
2305
2811
  rafId = window.requestAnimationFrame(measure);
2306
- setTimeout(() => {
2812
+ const timeoutId = setTimeout(() => {
2307
2813
  if (rafId !== void 0) cancelAnimationFrame(rafId);
2308
2814
  resolve(60);
2309
2815
  }, 1e3);
@@ -2329,28 +2835,6 @@ function prefersDarkMode(strategy = "auto") {
2329
2835
  return containsDarkClass() || matchesDarkMediaQuery();
2330
2836
  }
2331
2837
  //#endregion
2332
- //#region src/rtl.ts
2333
- /**
2334
- * Check whether the document is currently in RTL direction.
2335
- */
2336
- function isRtl() {
2337
- return document.documentElement.dir === "rtl";
2338
- }
2339
- /**
2340
- * Observe changes to the document's `dir` attribute and invoke the callback
2341
- * whenever it changes. Returns a cleanup function to stop observing.
2342
- */
2343
- function onRtlChange(callback) {
2344
- const observer = new MutationObserver(() => {
2345
- callback(document.documentElement.dir === "rtl");
2346
- });
2347
- observer.observe(document.documentElement, {
2348
- attributes: true,
2349
- attributeFilter: ["dir"]
2350
- });
2351
- return () => observer.disconnect();
2352
- }
2353
- //#endregion
2354
2838
  //#region src/color.ts
2355
2839
  /**
2356
2840
  * Convert a hex color string to HSL values.
@@ -2398,6 +2882,8 @@ function hexToHsl(hex) {
2398
2882
  * Returns string with leading '#'.
2399
2883
  */
2400
2884
  function hslToHex(h, s, l) {
2885
+ h %= 360;
2886
+ if (h < 0) h += 360;
2401
2887
  s /= 100;
2402
2888
  l /= 100;
2403
2889
  const c = (1 - Math.abs(2 * l - 1)) * s;
@@ -2466,11 +2952,11 @@ function formatAlpha(number) {
2466
2952
  * Accepts any input understood by {@link parseHexColor}; falls back to black on invalid input.
2467
2953
  */
2468
2954
  function hexToRgb(hex) {
2469
- const normalized = parseHexColor(hex)?.hex ?? "#000000";
2955
+ const normalized = expandHex(hex) ?? "000000";
2470
2956
  return {
2471
- r: parseInt(normalized.slice(1, 3), 16),
2472
- g: parseInt(normalized.slice(3, 5), 16),
2473
- b: parseInt(normalized.slice(5, 7), 16)
2957
+ r: parseInt(normalized.slice(0, 2), 16),
2958
+ g: parseInt(normalized.slice(2, 4), 16),
2959
+ b: parseInt(normalized.slice(4, 6), 16)
2474
2960
  };
2475
2961
  }
2476
2962
  /**
@@ -2484,6 +2970,11 @@ function rgbToHex(r, g, b) {
2484
2970
  b
2485
2971
  ].map((channel) => clamp(Math.round(channel), 0, 255).toString(16).padStart(2, "0")).join("")}`;
2486
2972
  }
2973
+ function parseChannelNumber(token) {
2974
+ if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)%?$/.test(token)) return null;
2975
+ const number = Number.parseFloat(token);
2976
+ return Number.isFinite(number) ? number : null;
2977
+ }
2487
2978
  /**
2488
2979
  * Parse an alpha channel from a raw string as found in rgba()/hsla() notation.
2489
2980
  *
@@ -2495,8 +2986,8 @@ function rgbToHex(r, g, b) {
2495
2986
  function parseAlphaChannel(rawAlpha) {
2496
2987
  if (rawAlpha === void 0 || rawAlpha.trim() === "") return 1;
2497
2988
  const trimmed = rawAlpha.trim();
2498
- const number = Number.parseFloat(trimmed);
2499
- if (!Number.isFinite(number)) return null;
2989
+ const number = parseChannelNumber(trimmed);
2990
+ if (number === null) return null;
2500
2991
  if (trimmed.endsWith("%")) {
2501
2992
  if (number < 0 || number > 100) return null;
2502
2993
  return normalizeAlpha(number / 100);
@@ -2513,8 +3004,8 @@ function parseAlphaChannel(rawAlpha) {
2513
3004
  */
2514
3005
  function parseRgbChannel(rawChannel) {
2515
3006
  const trimmed = rawChannel.trim();
2516
- const number = Number.parseFloat(trimmed);
2517
- if (!Number.isFinite(number)) return null;
3007
+ const number = parseChannelNumber(trimmed);
3008
+ if (number === null) return null;
2518
3009
  if (trimmed.endsWith("%")) {
2519
3010
  if (number < 0 || number > 100) return null;
2520
3011
  return clamp(Math.round(number / 100 * 255), 0, 255);
@@ -2535,6 +3026,16 @@ function parsedFromHex(hex, alphaValue = 1) {
2535
3026
  alpha: normalizeAlpha(alphaValue)
2536
3027
  };
2537
3028
  }
3029
+ function expandHex(input) {
3030
+ const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(input.trim());
3031
+ if (!match) return null;
3032
+ const raw = match[1];
3033
+ if (raw.length === 3 || raw.length === 4) {
3034
+ const rgb = raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2];
3035
+ return raw.length === 4 ? rgb + raw[3] + raw[3] : rgb;
3036
+ }
3037
+ return raw;
3038
+ }
2538
3039
  /**
2539
3040
  * Parse a hex color string into a {@link ParsedColor}.
2540
3041
  *
@@ -2542,11 +3043,8 @@ function parsedFromHex(hex, alphaValue = 1) {
2542
3043
  * 4/8 digit forms carry an alpha channel. Returns `null` on invalid input.
2543
3044
  */
2544
3045
  function parseHexColor(input) {
2545
- const trimmed = input.trim();
2546
- const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(trimmed);
2547
- if (!match) return null;
2548
- const raw = match[1];
2549
- const expanded = raw.length === 3 || raw.length === 4 ? raw.split("").map((char) => char + char).join("") : raw;
3046
+ const expanded = expandHex(input);
3047
+ if (!expanded) return null;
2550
3048
  const hex = `#${expanded.slice(0, 6)}`;
2551
3049
  const alphaHex = expanded.length === 8 ? expanded.slice(6, 8) : null;
2552
3050
  return parsedFromHex(hex, alphaHex ? parseInt(alphaHex, 16) / 255 : 1);
@@ -2556,7 +3054,7 @@ function parseHexColor(input) {
2556
3054
  * Channels may be numeric (0-255) or percentages. Returns `null` on invalid input.
2557
3055
  */
2558
3056
  function parseRgbColor(input) {
2559
- const match = /^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
3057
+ const match = /^rgba?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)(?:\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?))?\s*\)$/i.exec(input.trim());
2560
3058
  if (!match) return null;
2561
3059
  const r = parseRgbChannel(match[1]);
2562
3060
  const g = parseRgbChannel(match[2]);
@@ -2570,7 +3068,7 @@ function parseRgbColor(input) {
2570
3068
  * Saturation and lightness must be percentages within 0-100. Returns `null` on invalid input.
2571
3069
  */
2572
3070
  function parseHslColor(input) {
2573
- const match = /^hsla?\(\s*([+-]?\d*\.?\d+)\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
3071
+ const match = /^hsla?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%(?:\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?))?\s*\)$/i.exec(input.trim());
2574
3072
  if (!match) return null;
2575
3073
  const h = normalizeHue(Number.parseFloat(match[1]));
2576
3074
  const s = Number.parseFloat(match[2]);
@@ -2618,6 +3116,27 @@ function formatColor(color, format = "hex", options = {}) {
2618
3116
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2619
3117
  }
2620
3118
  //#endregion
3119
+ //#region src/style.ts
3120
+ /**
3121
+ * Remember an element's inline values for some CSS properties, with their
3122
+ * priorities, so temporary changes can be undone without touching other inline
3123
+ * styles. Name properties as in CSS, such as `z-index`.
3124
+ */
3125
+ function captureInlineStyles(element, properties) {
3126
+ const names = properties.slice();
3127
+ const stored = names.map((property) => captureStyleProperty(element.style, property));
3128
+ return { restore: (only) => {
3129
+ if (!only) {
3130
+ names.forEach((property, index) => restoreStyleProperty(element.style, property, stored[index]));
3131
+ return;
3132
+ }
3133
+ for (const property of only) {
3134
+ const index = names.indexOf(property);
3135
+ if (index !== -1) restoreStyleProperty(element.style, property, stored[index]);
3136
+ }
3137
+ } };
3138
+ }
3139
+ //#endregion
2621
3140
  //#region src/cssVariables.ts
2622
3141
  /** Copy selected computed custom properties and restore owned inline values on cleanup. */
2623
3142
  function inheritCssVariables(source, target, options) {
@@ -2634,22 +3153,25 @@ function inheritCssVariables(source, target, options) {
2634
3153
  }
2635
3154
  function update() {
2636
3155
  const computed = view.getComputedStyle(source);
2637
- const names = /* @__PURE__ */ new Set();
3156
+ const values = /* @__PURE__ */ new Map();
2638
3157
  for (const name of Array.from(computed)) {
2639
3158
  if (!name.startsWith("--") || !options.filter(name)) continue;
2640
3159
  const value = computed.getPropertyValue(name).trim();
2641
3160
  if (!value) continue;
2642
- names.add(name);
3161
+ values.set(name, value);
3162
+ }
3163
+ for (const [name, value] of values) {
2643
3164
  if (!original.has(name)) original.set(name, {
2644
3165
  value: target.style.getPropertyValue(name),
2645
3166
  priority: target.style.getPropertyPriority(name)
2646
3167
  });
2647
3168
  if (applied.get(name) !== value) {
3169
+ if (target.style.getPropertyPriority(name)) target.style.removeProperty(name);
2648
3170
  target.style.setProperty(name, value);
2649
3171
  applied.set(name, value);
2650
3172
  }
2651
3173
  }
2652
- for (const name of applied.keys()) if (!names.has(name)) restore(name);
3174
+ for (const name of applied.keys()) if (!values.has(name)) restore(name);
2653
3175
  }
2654
3176
  update();
2655
3177
  const observer = new MutationObserver(update);
@@ -2670,38 +3192,45 @@ function inheritCssVariables(source, target, options) {
2670
3192
  /** Coordinates hover and focus intent without moving focus into the tooltip. */
2671
3193
  function createTooltipController(options) {
2672
3194
  const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2673
- const scheduler = createDebouncer(options.delay ?? 300);
3195
+ const delay = options.delay ?? 300;
3196
+ let scheduler;
2674
3197
  let hovered = false;
2675
3198
  let focused = false;
2676
3199
  let closing = false;
2677
3200
  let revision = 0;
2678
3201
  let mounted = null;
2679
3202
  let cleanups = [];
2680
- const disclosure = createNativePopoverDisclosure({
2681
- reference: options.reference,
2682
- popover: options.tooltip,
2683
- get position() {
2684
- return {
2685
- placement: "top",
2686
- offset: 6,
2687
- ...options.position
2688
- };
2689
- },
2690
- onOpenChange: options.onOpenChange
2691
- });
3203
+ const reference = options.reference;
3204
+ const tooltip = options.tooltip;
3205
+ const onOpenChange = options.onOpenChange;
3206
+ let disclosure;
3207
+ function getDisclosure() {
3208
+ return disclosure ??= createNativePopoverDisclosure({
3209
+ reference,
3210
+ popover: tooltip,
3211
+ get position() {
3212
+ return {
3213
+ placement: "top",
3214
+ offset: 6,
3215
+ ...options.position
3216
+ };
3217
+ },
3218
+ onOpenChange
3219
+ });
3220
+ }
2692
3221
  function cleanup() {
2693
3222
  revision++;
2694
3223
  closing = false;
2695
- scheduler.cancel();
3224
+ scheduler?.cancel();
2696
3225
  cleanups.forEach((cleanup) => cleanup());
2697
3226
  cleanups = [];
2698
- disclosure.cleanupPopover();
3227
+ disclosure?.cleanupPopover();
2699
3228
  if (native && mounted?.matches(":popover-open")) mounted.hidePopover();
2700
3229
  mounted = null;
2701
3230
  }
2702
3231
  async function hide() {
2703
- scheduler.cancel();
2704
- if (!disclosure.isOpen || closing) return;
3232
+ scheduler?.cancel();
3233
+ if (!disclosure?.isOpen || closing) return;
2705
3234
  closing = true;
2706
3235
  const current = ++revision;
2707
3236
  await options.transition?.(false);
@@ -2718,9 +3247,9 @@ function createTooltipController(options) {
2718
3247
  closing = false;
2719
3248
  options.transition?.(true);
2720
3249
  }
2721
- if (disclosure.isOpen) return;
2722
- scheduler.schedule(() => {
2723
- if ((hovered || focused) && options.enabled?.() !== false) disclosure.openPopover();
3250
+ if (disclosure?.isOpen) return;
3251
+ (scheduler ??= createDebouncer(delay)).schedule(() => {
3252
+ if ((hovered || focused) && options.enabled?.() !== false) getDisclosure().openPopover();
2724
3253
  });
2725
3254
  }
2726
3255
  function dismissIfIdle() {
@@ -2729,13 +3258,15 @@ function createTooltipController(options) {
2729
3258
  function mount() {
2730
3259
  const reference = options.reference();
2731
3260
  const tooltip = options.tooltip();
2732
- if (!disclosure.isOpen || !reference || !tooltip) return;
3261
+ if (!disclosure?.isOpen || !reference || !tooltip) return;
2733
3262
  cleanup();
2734
3263
  mounted = tooltip;
3264
+ cleanups.push(followReferenceDirection(reference, tooltip));
2735
3265
  if (native) tooltip.showPopover();
2736
3266
  const updatePosition = () => computePosition(reference, tooltip, {
2737
3267
  placement: "top",
2738
3268
  offset: 6,
3269
+ anchorPositioning: false,
2739
3270
  ...options.position
2740
3271
  });
2741
3272
  updatePosition();
@@ -2761,7 +3292,7 @@ function createTooltipController(options) {
2761
3292
  return {
2762
3293
  native,
2763
3294
  get isOpen() {
2764
- return disclosure.isOpen;
3295
+ return disclosure?.isOpen ?? false;
2765
3296
  },
2766
3297
  mount,
2767
3298
  cleanup,
@@ -2802,8 +3333,11 @@ function createDialogController(options) {
2802
3333
  revision++;
2803
3334
  closing = false;
2804
3335
  const top = dialogs[dialogs.length - 1] === entry;
2805
- const index = dialogs.indexOf(entry);
2806
- if (index !== -1) dialogs.splice(index, 1);
3336
+ if (top) dialogs.pop();
3337
+ else {
3338
+ const index = dialogs.indexOf(entry);
3339
+ if (index !== -1) dialogs.splice(index, 1);
3340
+ }
2807
3341
  cleanups.forEach((cleanup) => cleanup());
2808
3342
  cleanups = [];
2809
3343
  if (native && mounted?.open) mounted.close();
@@ -2881,4 +3415,4 @@ function createDialogController(options) {
2881
3415
  };
2882
3416
  }
2883
3417
  //#endregion
2884
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, computePosition, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
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 };