@reshaped/utilities 4.0.3 → 4.1.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.
Files changed (44) hide show
  1. package/dist/a11y/TrapFocus.js +81 -48
  2. package/dist/a11y/focus.js +1 -1
  3. package/dist/a11y/index.js +3 -3
  4. package/dist/a11y/tests/Chain.test.js +1 -1
  5. package/dist/a11y/tests/TrapFocus.test.js +52 -1
  6. package/dist/a11y/tests/TrapScreenReader.test.js +1 -1
  7. package/dist/a11y/tests/focus.test.js +1 -1
  8. package/dist/a11y/tests/keyboardMode.test.js +1 -1
  9. package/dist/css/StyleCache.d.ts +2 -2
  10. package/dist/css/StyleCache.js +11 -7
  11. package/dist/css/index.js +2 -2
  12. package/dist/css/tests/StyleCache.test.js +20 -8
  13. package/dist/css/tests/classNames.test.js +1 -1
  14. package/dist/dom/findClosestScrollableContainer.d.ts +1 -1
  15. package/dist/dom/index.js +3 -3
  16. package/dist/dom/tests/findClosestScrollableContainer.test.js +1 -1
  17. package/dist/dom/tests/findParent.test.js +1 -1
  18. package/dist/flyout/Flyout.js +3 -3
  19. package/dist/flyout/index.js +1 -1
  20. package/dist/flyout/tests/Flyout.test.js +1 -1
  21. package/dist/flyout/utilities/applyPosition.js +30 -12
  22. package/dist/flyout/utilities/calculateLayoutAdjustment.js +15 -8
  23. package/dist/flyout/utilities/calculatePosition.js +2 -2
  24. package/dist/flyout/utilities/isFullyVisible.js +1 -1
  25. package/dist/flyout/utilities/tests/applyPosition.test.js +21 -1
  26. package/dist/flyout/utilities/tests/calculateLayoutAdjustment.test.js +70 -2
  27. package/dist/flyout/utilities/tests/calculatePosition.test.js +1 -1
  28. package/dist/flyout/utilities/tests/centerBySize.test.js +1 -1
  29. package/dist/flyout/utilities/tests/getPositionFallbacks.test.js +1 -1
  30. package/dist/flyout/utilities/tests/getRTLPosition.test.js +1 -1
  31. package/dist/flyout/utilities/tests/isFullyVisible.test.js +1 -1
  32. package/dist/helpers/index.js +1 -1
  33. package/dist/helpers/tests/rafThrottle.test.js +1 -1
  34. package/dist/i18n/index.js +1 -1
  35. package/dist/i18n/tests/isRTL.test.js +1 -1
  36. package/dist/index.js +6 -6
  37. package/dist/internal.js +4 -4
  38. package/dist/scroll/index.js +2 -2
  39. package/dist/scroll/lock.d.ts +2 -2
  40. package/dist/scroll/lock.js +21 -16
  41. package/dist/scroll/lockSafari.js +2 -2
  42. package/dist/scroll/lockStandard.js +8 -9
  43. package/dist/scroll/tests/lock.test.js +74 -3
  44. package/package.json +3 -3
@@ -1,12 +1,16 @@
1
1
  var _a;
2
- import keys from "../constants/keys.js";
3
- import { getShadowRoot } from "../dom/index.js";
4
- import Chain from "./Chain.js";
5
- import { focusElement, getActiveElement, getFocusableElements, getFocusData } from "./focus.js";
6
- import { checkKeyboardMode } from "./keyboardMode.js";
7
- import TrapScreenReader from "./TrapScreenReader.js";
2
+ import keys from "../constants/keys";
3
+ import { getShadowRoot } from "../dom";
4
+ import Chain from "./Chain";
5
+ import { focusElement, getActiveElement, getFocusableElements, getFocusData } from "./focus";
6
+ import { checkKeyboardMode } from "./keyboardMode";
7
+ import TrapScreenReader from "./TrapScreenReader";
8
8
  class TrapFocus {
9
9
  static chain = new Chain();
10
+ // Monotonic counter bumped on every trap() call. Used by the deferred
11
+ // observer to tell whether a newer trap was triggered after this one.
12
+ static #globalTrapCounter = 0;
13
+ #trapCounter = 0;
10
14
  #chainId;
11
15
  #root = null;
12
16
  #trigger = null;
@@ -84,51 +88,33 @@ class TrapFocus {
84
88
  const tailItem = _a.chain.tailId && _a.chain.get(_a.chain.tailId);
85
89
  return tailItem && tailItem.data.#root === this.#root;
86
90
  };
91
+ #getFocusable = () => {
92
+ if (!this.#root)
93
+ return [];
94
+ return getFocusableElements(this.#root, {
95
+ additionalElement: this.#options.includeTrigger ? this.#trigger : undefined,
96
+ });
97
+ };
87
98
  /**
88
- * Trap the focus, add observer and keyboard event listeners
89
- * and create a chain item
99
+ * Establish the trap once there is something focusable inside.
100
+ * Stays a no-op while the container is empty, so an empty container remains
101
+ * deferred until its observer detects focusable content being added.
90
102
  */
91
- trap = (root, options = {}) => {
92
- const { mode = "dialog", includeTrigger, initialFocusEl } = options;
93
- this.#root = root;
94
- this.#screenReaderTrap = new TrapScreenReader(root);
95
- const trigger = getActiveElement(this.#root);
96
- const focusable = getFocusableElements(this.#root, {
97
- additionalElement: includeTrigger ? trigger : undefined,
98
- });
99
- const pseudoFocus = mode === "selection-menu";
100
- this.#options = { ...options, pseudoFocus };
101
- this.#trigger = trigger;
102
- this.#mutationObserver = new MutationObserver(() => {
103
- if (!this.#root)
104
- return;
105
- if (!this.#isLast())
106
- return;
107
- const currentActiveElement = getActiveElement(this.#root);
108
- // Focus stayed inside the wrapper, no need to refocus
109
- if (this.#root.contains(currentActiveElement))
110
- return;
111
- const focusable = getFocusableElements(this.#root, {
112
- additionalElement: includeTrigger ? trigger : undefined,
113
- });
114
- if (!focusable.length)
115
- return;
116
- focusElement(focusable[0], { pseudoFocus });
117
- });
118
- this.#removeListeners();
119
- this.#mutationObserver.observe(this.#root, { childList: true, subtree: true });
120
- // Don't trap in case there is nothing to focus inside
103
+ #activate = () => {
104
+ if (!this.#root || this.trapped)
105
+ return;
106
+ const { mode, initialFocusEl, pseudoFocus } = this.#options;
107
+ const focusable = this.#getFocusable();
108
+ // Nothing to focus yet — stay deferred.
121
109
  if (!focusable.length && !initialFocusEl)
122
110
  return;
123
111
  this.#addListeners();
124
112
  if (mode === "dialog")
125
- this.#screenReaderTrap.trap();
126
- const currentActiveElement = getActiveElement(this.#root);
127
- const isLastInChain = this.#isLast();
113
+ this.#screenReaderTrap?.trap();
128
114
  // Don't add back to the chain if we're traversing back
129
- if (!isLastInChain) {
115
+ if (!this.#isLast()) {
130
116
  this.#chainId = _a.chain.add(this);
131
- const focusInside = this.#root.contains(currentActiveElement);
117
+ const focusInside = this.#root.contains(getActiveElement(this.#root));
132
118
  if (initialFocusEl) {
133
119
  focusElement(initialFocusEl, { pseudoFocus });
134
120
  // If the focus was moved manually (e.g. with autoFocus) - keep it there
@@ -139,26 +125,73 @@ class TrapFocus {
139
125
  }
140
126
  this.trapped = true;
141
127
  };
128
+ /**
129
+ * Trap the focus, add observer and keyboard event listeners
130
+ * and create a chain item
131
+ */
132
+ trap = (root, options = {}) => {
133
+ const { mode = "dialog" } = options;
134
+ const pseudoFocus = mode === "selection-menu";
135
+ this.#root = root;
136
+ this.#screenReaderTrap = new TrapScreenReader(root);
137
+ this.#trigger = getActiveElement(root);
138
+ this.#options = { ...options, mode, pseudoFocus };
139
+ this.#trapCounter = ++_a.#globalTrapCounter;
140
+ this.#removeListeners();
141
+ this.#mutationObserver?.disconnect();
142
+ this.#mutationObserver = new MutationObserver(() => {
143
+ if (!this.#root)
144
+ return;
145
+ // Still deferred: trap once focusable content is added (e.g. async-loaded
146
+ // dialog content), as long as no newer trap was triggered in the meantime.
147
+ if (!this.trapped) {
148
+ if (this.#trapCounter !== _a.#globalTrapCounter) {
149
+ this.#mutationObserver?.disconnect();
150
+ return;
151
+ }
152
+ this.#activate();
153
+ return;
154
+ }
155
+ // Active trap: keep the focus inside the region if it escaped.
156
+ if (!this.#isLast())
157
+ return;
158
+ if (this.#root.contains(getActiveElement(this.#root)))
159
+ return;
160
+ const focusable = this.#getFocusable();
161
+ if (!focusable.length)
162
+ return;
163
+ focusElement(focusable[0], { pseudoFocus });
164
+ });
165
+ this.#mutationObserver.observe(root, { childList: true, subtree: true });
166
+ this.#activate();
167
+ };
142
168
  /**
143
169
  * Disabled the trap focus for the element,
144
170
  * cleanup all observers/handlers and trap for the previous element in the chain
145
171
  */
146
172
  release = (releaseOptions = {}) => {
147
173
  const { withoutFocusReturn } = releaseOptions;
148
- if (!this.trapped || !this.#chainId || !this.#root)
174
+ if (!this.trapped || !this.#chainId || !this.#root) {
175
+ // A deferred (never-trapped) empty container may still be observing for
176
+ // focusable content — disconnect it so it can't trap after release.
177
+ this.#mutationObserver?.disconnect();
149
178
  return;
179
+ }
150
180
  this.trapped = false;
151
181
  if (this.#trigger && !withoutFocusReturn) {
152
182
  this.#trigger.focus({ preventScroll: !checkKeyboardMode() });
153
183
  }
184
+ const wasTail = _a.chain.tailId === this.#chainId;
154
185
  _a.chain.removePreviousTill(this.#chainId, (item) => document.body.contains(item.data.#trigger));
155
186
  this.#mutationObserver?.disconnect();
156
187
  this.#removeListeners();
157
188
  this.#screenReaderTrap?.release();
158
- const previousItem = _a.chain.tailId && _a.chain.get(_a.chain.tailId);
159
- if (previousItem && previousItem.data.#root) {
160
- const trapInstance = new _a();
161
- trapInstance.trap(previousItem.data.#root, previousItem.data.#options);
189
+ if (wasTail) {
190
+ const previousItem = _a.chain.tailId && _a.chain.get(_a.chain.tailId);
191
+ if (previousItem && previousItem.data.#root) {
192
+ const trapInstance = new _a();
193
+ trapInstance.trap(previousItem.data.#root, previousItem.data.#options);
194
+ }
162
195
  }
163
196
  };
164
197
  }
@@ -1,4 +1,4 @@
1
- import { getShadowRoot } from "../dom/index.js";
1
+ import { getShadowRoot } from "../dom";
2
2
  const pseudoFocusAttribute = "data-rs-focus";
3
3
  export const focusableSelector = 'a,button,input:not([type="hidden"]),textarea,select,details,[tabindex],[contenteditable]';
4
4
  export const getActiveElement = (originEl) => {
@@ -1,3 +1,3 @@
1
- export { focusableSelector, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, } from "./focus.js";
2
- export { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode } from "./keyboardMode.js";
3
- export { default as TrapFocus } from "./TrapFocus.js";
1
+ export { focusableSelector, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, } from "./focus";
2
+ export { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode } from "./keyboardMode";
3
+ export { default as TrapFocus } from "./TrapFocus";
@@ -1,5 +1,5 @@
1
1
  import { beforeEach, describe, expect, test } from "vitest";
2
- import Chain from "../Chain.js";
2
+ import Chain from "../Chain";
3
3
  describe("a11y/Chain", () => {
4
4
  let chain;
5
5
  beforeEach(() => {
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
- import TrapFocus from "../TrapFocus.js";
2
+ import TrapFocus from "../TrapFocus";
3
3
  describe("a11y/TrapFocus", () => {
4
4
  let container;
5
5
  let trigger;
@@ -44,6 +44,57 @@ describe("a11y/TrapFocus", () => {
44
44
  trap.trap(container);
45
45
  expect(trap.trapped).toBeUndefined();
46
46
  });
47
+ test("traps focus once focusable content is added to an empty container", async () => {
48
+ container.innerHTML = `<div>No focusable content yet</div>`;
49
+ const trap = new TrapFocus();
50
+ trap.trap(container);
51
+ expect(trap.trapped).toBeUndefined();
52
+ const btn = document.createElement("button");
53
+ btn.id = "late";
54
+ btn.textContent = "Late";
55
+ container.appendChild(btn);
56
+ // Wait for the MutationObserver callback to run
57
+ await new Promise((resolve) => setTimeout(resolve, 0));
58
+ expect(trap.trapped).toBe(true);
59
+ expect(document.activeElement?.id).toBe("late");
60
+ trap.release();
61
+ });
62
+ test("does not trap added content if another trap was triggered after", async () => {
63
+ container.innerHTML = `<div>No focusable content yet</div>`;
64
+ const deferredTrap = new TrapFocus();
65
+ deferredTrap.trap(container);
66
+ expect(deferredTrap.trapped).toBeUndefined();
67
+ // A newer trap is triggered before the empty container gets content
68
+ const other = document.createElement("div");
69
+ other.innerHTML = `<button id="other-btn">Other</button>`;
70
+ document.body.appendChild(other);
71
+ const otherTrap = new TrapFocus();
72
+ otherTrap.trap(other);
73
+ // Now the originally-empty container receives focusable content
74
+ const btn = document.createElement("button");
75
+ btn.id = "late";
76
+ btn.textContent = "Late";
77
+ container.appendChild(btn);
78
+ await new Promise((resolve) => setTimeout(resolve, 0));
79
+ // The deferred trap must stay inactive and must not steal focus
80
+ expect(deferredTrap.trapped).toBeUndefined();
81
+ expect(document.activeElement?.id).not.toBe("late");
82
+ otherTrap.release();
83
+ document.body.removeChild(other);
84
+ });
85
+ test("releasing an empty container stops it from trapping later", async () => {
86
+ container.innerHTML = `<div>No focusable content yet</div>`;
87
+ const trap = new TrapFocus();
88
+ trap.trap(container);
89
+ trap.release();
90
+ const btn = document.createElement("button");
91
+ btn.id = "late";
92
+ btn.textContent = "Late";
93
+ container.appendChild(btn);
94
+ await new Promise((resolve) => setTimeout(resolve, 0));
95
+ expect(trap.trapped).toBeUndefined();
96
+ expect(document.activeElement?.id).not.toBe("late");
97
+ });
47
98
  test("focuses initialFocusEl when provided", () => {
48
99
  container.innerHTML = `
49
100
  <button id="btn1">Button 1</button>
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "vitest";
2
- import TrapScreenReader from "../TrapScreenReader.js";
2
+ import TrapScreenReader from "../TrapScreenReader";
3
3
  describe("a11y/TrapScreenReader", () => {
4
4
  let container;
5
5
  beforeEach(() => {
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "vitest";
2
- import { focusElement, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, getFocusData, } from "../focus.js";
2
+ import { focusElement, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, getFocusData, } from "../focus";
3
3
  describe("a11y/focus", () => {
4
4
  let container;
5
5
  beforeEach(() => {
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "vitest";
2
- import { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode, keyboardModeAttribute, } from "../keyboardMode.js";
2
+ import { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode, keyboardModeAttribute, } from "../keyboardMode";
3
3
  describe("a11y/keyboardMode", () => {
4
4
  beforeEach(() => {
5
5
  document.documentElement.removeAttribute(keyboardModeAttribute);
@@ -1,7 +1,7 @@
1
1
  type Styles = Record<string, string>;
2
2
  declare class StyleCache {
3
- cache: Map<HTMLElement, Record<string, string>>;
3
+ cache: Map<HTMLElement, Styles>;
4
4
  set: (el: HTMLElement, styles: Styles) => void;
5
- reset: () => void;
5
+ reset: (el: HTMLElement) => void;
6
6
  }
7
7
  export default StyleCache;
@@ -1,19 +1,23 @@
1
1
  class StyleCache {
2
2
  cache = new Map();
3
3
  set = (el, styles) => {
4
+ // Already cached (locked) — keep the originals captured the first time and
5
+ // don't reapply, so locking an element that's already locked is a no-op.
6
+ if (this.cache.has(el))
7
+ return;
4
8
  const originalStyles = {};
5
- const cachedStyles = this.cache.get(el);
6
9
  Object.keys(styles).forEach((key) => {
7
10
  originalStyles[key] = el.style.getPropertyValue(key);
8
11
  });
9
- this.cache.set(el, { ...originalStyles, ...cachedStyles });
12
+ this.cache.set(el, originalStyles);
10
13
  Object.assign(el.style, styles);
11
14
  };
12
- reset = () => {
13
- for (const [el, styles] of this.cache.entries()) {
14
- Object.assign(el.style, styles);
15
- }
16
- this.cache.clear();
15
+ reset = (el) => {
16
+ const styles = this.cache.get(el);
17
+ if (!styles)
18
+ return;
19
+ Object.assign(el.style, styles);
20
+ this.cache.delete(el);
17
21
  };
18
22
  }
19
23
  export default StyleCache;
package/dist/css/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // External
2
- export { default as classNames } from "./classNames.js";
2
+ export { default as classNames } from "./classNames";
3
3
  // Internal
4
- export { default as StyleCache } from "./StyleCache.js";
4
+ export { default as StyleCache } from "./StyleCache";
@@ -1,5 +1,5 @@
1
1
  import { beforeEach, describe, expect, test } from "vitest";
2
- import StyleCache from "../StyleCache.js";
2
+ import StyleCache from "../StyleCache";
3
3
  describe("css/StyleCache", () => {
4
4
  let styleCache;
5
5
  beforeEach(() => {
@@ -12,34 +12,46 @@ describe("css/StyleCache", () => {
12
12
  styleCache.set(el, { color: "blue", overflow: "hidden" });
13
13
  expect(el.style.color).toBe("blue");
14
14
  expect(el.style.overflow).toBe("hidden");
15
- styleCache.reset();
15
+ styleCache.reset(el);
16
16
  expect(el.style.color).toBe("red");
17
17
  expect(el.style.overflow).toBe("visible");
18
18
  });
19
- test("preserves original styles across multiple set calls", () => {
19
+ test("ignores repeated set calls on an already-cached element", () => {
20
20
  const el = document.createElement("div");
21
21
  el.style.color = "red";
22
22
  styleCache.set(el, { color: "blue" });
23
+ // The element is already cached, so this is a no-op (style stays "blue")
23
24
  styleCache.set(el, { color: "green" });
24
- styleCache.reset();
25
+ expect(el.style.color).toBe("blue");
26
+ styleCache.reset(el);
25
27
  expect(el.style.color).toBe("red");
26
28
  });
27
- test("handles multiple elements", () => {
29
+ test("reset only affects the given element", () => {
28
30
  const el1 = document.createElement("div");
29
31
  const el2 = document.createElement("div");
30
32
  el1.style.color = "red";
31
33
  el2.style.color = "blue";
32
34
  styleCache.set(el1, { color: "green" });
33
35
  styleCache.set(el2, { color: "yellow" });
34
- styleCache.reset();
36
+ styleCache.reset(el1);
37
+ // el1 is restored, el2 stays locked
35
38
  expect(el1.style.color).toBe("red");
39
+ expect(el2.style.color).toBe("yellow");
40
+ expect(styleCache.cache.has(el2)).toBe(true);
41
+ styleCache.reset(el2);
36
42
  expect(el2.style.color).toBe("blue");
37
43
  });
38
- test("clears cache after reset", () => {
44
+ test("reset is a no-op for an element that was never cached", () => {
45
+ const el = document.createElement("div");
46
+ el.style.color = "red";
47
+ styleCache.reset(el);
48
+ expect(el.style.color).toBe("red");
49
+ });
50
+ test("removes the element from the cache after reset", () => {
39
51
  const el = document.createElement("div");
40
52
  el.style.color = "red";
41
53
  styleCache.set(el, { color: "blue" });
42
- styleCache.reset();
54
+ styleCache.reset(el);
43
55
  expect(styleCache.cache.size).toBe(0);
44
56
  });
45
57
  });
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import classNames from "../classNames.js";
2
+ import classNames from "../classNames";
3
3
  describe("helpers/classNames", () => {
4
4
  test("returns empty string when no arguments are provided", () => {
5
5
  expect(classNames()).toBe("");
@@ -1,5 +1,5 @@
1
1
  type Args = {
2
2
  el: HTMLElement;
3
3
  };
4
- declare const _default: (args: Args) => HTMLElement | null;
5
4
  export default _default;
5
+ declare function _default(args: Args): HTMLElement | null;
package/dist/dom/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Internal
2
- export { default as findClosestScrollableContainer } from "./findClosestScrollableContainer.js";
3
- export { default as findParent } from "./findParent.js";
4
- export { default as getShadowRoot } from "./getShadowRoot.js";
2
+ export { default as findClosestScrollableContainer } from "./findClosestScrollableContainer";
3
+ export { default as findParent } from "./findParent";
4
+ export { default as getShadowRoot } from "./getShadowRoot";
@@ -1,5 +1,5 @@
1
1
  import { afterEach, describe, expect, test } from "vitest";
2
- import findClosestScrollableContainer from "../findClosestScrollableContainer.js";
2
+ import findClosestScrollableContainer from "../findClosestScrollableContainer";
3
3
  describe("dom/findClosestScrollableContainer", () => {
4
4
  afterEach(() => {
5
5
  document.body.innerHTML = "";
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import findParent from "../findParent.js";
2
+ import findParent from "../findParent";
3
3
  describe("dom/findParent", () => {
4
4
  test("returns null when element has no parent", () => {
5
5
  const element = document.createElement("div");
@@ -1,6 +1,6 @@
1
- import { findClosestScrollableContainer } from "../dom/index.js";
2
- import { rafThrottle } from "../helpers/index.js";
3
- import applyPosition from "./utilities/applyPosition.js";
1
+ import { findClosestScrollableContainer } from "../dom";
2
+ import { rafThrottle } from "../helpers";
3
+ import applyPosition from "./utilities/applyPosition";
4
4
  class Flyout {
5
5
  #active = false;
6
6
  #lastUsedPosition = null;
@@ -1 +1 @@
1
- export { default as Flyout } from "./Flyout.js";
1
+ export { default as Flyout } from "./Flyout";
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
- import Flyout from "../Flyout.js";
2
+ import Flyout from "../Flyout";
3
3
  describe("flyout/Flyout", () => {
4
4
  let content;
5
5
  let trigger;
@@ -1,11 +1,11 @@
1
- import { getShadowRoot } from "../../dom/index.js";
2
- import isRTL from "../../i18n/isRTL.js";
3
- import { RESET_STYLES, VIEWPORT_OFFSET } from "../constants.js";
4
- import calculateLayoutAdjustment from "./calculateLayoutAdjustment.js";
5
- import calculatePosition from "./calculatePosition.js";
6
- import getPositionFallbacks from "./getPositionFallbacks.js";
7
- import getRectFromCoordinates from "./getRectFromCoordinates.js";
8
- import isFullyVisible from "./isFullyVisible.js";
1
+ import { getShadowRoot } from "../../dom";
2
+ import isRTL from "../../i18n/isRTL";
3
+ import { RESET_STYLES, VIEWPORT_OFFSET } from "../constants";
4
+ import calculateLayoutAdjustment from "./calculateLayoutAdjustment";
5
+ import calculatePosition from "./calculatePosition";
6
+ import getPositionFallbacks from "./getPositionFallbacks";
7
+ import getRectFromCoordinates from "./getRectFromCoordinates";
8
+ import isFullyVisible from "./isFullyVisible";
9
9
  /**
10
10
  * Get the viewport-relative rect of the element's containing block.
11
11
  * When the content is inside a positioned ancestor (e.g. a fixed overlay),
@@ -16,11 +16,13 @@ const getContainingBlockRect = (el) => {
16
16
  if (!offsetParent ||
17
17
  offsetParent === document.body ||
18
18
  offsetParent === document.documentElement) {
19
+ // Initial containing block matches documentElement.clientWidth/Height,
20
+ // which excludes the classic scrollbars unlike window.innerWidth/Height
19
21
  return {
20
22
  left: -window.scrollX,
21
23
  top: -window.scrollY,
22
- right: window.innerWidth - window.scrollX,
23
- bottom: window.innerHeight - window.scrollY,
24
+ right: document.documentElement.clientWidth - window.scrollX,
25
+ bottom: document.documentElement.clientHeight - window.scrollY,
24
26
  };
25
27
  }
26
28
  const rect = offsetParent.getBoundingClientRect();
@@ -75,7 +77,7 @@ const applyPosition = (args) => {
75
77
  const adjustedResult = calculateLayoutAdjustment({
76
78
  ...result,
77
79
  fallbackAdjustLayout,
78
- fallbackMinHeight,
80
+ fallbackMinHeight: options?.disableMinHeight ? undefined : fallbackMinHeight,
79
81
  width: options?.width,
80
82
  flyoutBounds,
81
83
  containerBounds,
@@ -107,7 +109,8 @@ const applyPosition = (args) => {
107
109
  });
108
110
  // Try full width positions in case it doesn't fit on any side
109
111
  if (!calculated) {
110
- const smallScreenFallbackPositions = ["top", "bottom"].filter((position) => testOrder.includes(position));
112
+ // Keep the testOrder ordering so the preferred position is tried first
113
+ const smallScreenFallbackPositions = testOrder.filter((position) => position === "top" || position === "bottom");
111
114
  smallScreenFallbackPositions.some((position) => {
112
115
  const tested = testPosition(position, { width: "100%" });
113
116
  const visible = testVisibility(tested);
@@ -116,6 +119,21 @@ const applyPosition = (args) => {
116
119
  return visible;
117
120
  });
118
121
  }
122
+ // Nothing fits with the min height applied, meaning it's larger than the space
123
+ // available on any side, so drop it and pick the position showing the most content
124
+ if (!calculated && fallbackAdjustLayout && fallbackMinHeight) {
125
+ let bestHeight = 0;
126
+ testOrder.forEach((currentPosition) => {
127
+ const tested = testPosition(currentPosition, { width, disableMinHeight: true });
128
+ if (!testVisibility(tested))
129
+ return;
130
+ const testedHeight = tested.styles.height ?? Math.ceil(contentClone.clientHeight);
131
+ if (testedHeight > bestHeight) {
132
+ bestHeight = testedHeight;
133
+ calculated = tested;
134
+ }
135
+ });
136
+ }
119
137
  // None of the positions fit, use the last used position or the default position
120
138
  if (!calculated)
121
139
  calculated = testPosition(lastUsedPosition ?? position, { width });
@@ -1,4 +1,4 @@
1
- import { VIEWPORT_OFFSET } from "../constants.js";
1
+ import { VIEWPORT_OFFSET } from "../constants";
2
2
  const calculateLayoutAdjustment = (args) => {
3
3
  const { position, styles, fallbackAdjustLayout, fallbackMinHeight, width: passedWidth, flyoutBounds, containerBounds, triggerBounds, } = args;
4
4
  const { width: flyoutWidth, height: flyoutHeight } = flyoutBounds;
@@ -28,6 +28,8 @@ const calculateLayoutAdjustment = (args) => {
28
28
  }
29
29
  else if (overflow.bottom > 0) {
30
30
  top = top - overflow.bottom;
31
+ if (bottom !== null)
32
+ bottom = bottom + overflow.bottom;
31
33
  }
32
34
  }
33
35
  else {
@@ -38,17 +40,22 @@ const calculateLayoutAdjustment = (args) => {
38
40
  }
39
41
  else if (overflow.right > 0) {
40
42
  left = left - overflow.right;
43
+ if (right !== null)
44
+ right = right + overflow.right;
41
45
  }
42
46
  }
43
47
  const updatedOverflow = getOverflow();
44
- if (updatedOverflow.top > 0) {
45
- height = Math.max(parseInt(fallbackMinHeight ?? "0"), flyoutHeight - updatedOverflow.top);
46
- top = top + (flyoutHeight - height);
47
- }
48
- else if (updatedOverflow.bottom > 0) {
49
- height = Math.max(parseInt(fallbackMinHeight ?? "0"), flyoutHeight - updatedOverflow.bottom);
48
+ const overflowTop = Math.max(0, updatedOverflow.top);
49
+ const overflowBottom = Math.max(0, updatedOverflow.bottom);
50
+ // Content can overflow on both sides at once, for example when the trigger
51
+ // is scrolled partially out of the container, so both edges have to be trimmed
52
+ if (overflowTop > 0 || overflowBottom > 0) {
53
+ height = Math.max(parseInt(fallbackMinHeight ?? "0"), flyoutHeight - overflowTop - overflowBottom);
54
+ const trimmedHeight = flyoutHeight - height;
55
+ const trimmedTop = Math.min(overflowTop, trimmedHeight);
56
+ top = top + trimmedTop;
50
57
  if (bottom !== null)
51
- bottom = bottom + (flyoutHeight - height);
58
+ bottom = bottom + (trimmedHeight - trimmedTop);
52
59
  }
53
60
  }
54
61
  if (passedWidth === "100%") {
@@ -1,5 +1,5 @@
1
- import centerBySize from "./centerBySize.js";
2
- import getRTLPosition from "./getRTLPosition.js";
1
+ import centerBySize from "./centerBySize";
2
+ import getRTLPosition from "./getRTLPosition";
3
3
  const calculatePosition = (args) => {
4
4
  const { triggerBounds, flyoutBounds, position: passedPosition, rtl, contentGap = 0, contentShift = 0, } = args;
5
5
  const position = rtl ? getRTLPosition(passedPosition) : passedPosition;
@@ -1,4 +1,4 @@
1
- import { VIEWPORT_OFFSET } from "../constants.js";
1
+ import { VIEWPORT_OFFSET } from "../constants";
2
2
  /**
3
3
  * Check if element visually fits within its render container
4
4
  * @param flyoutBounds - Bounds of the flyout content
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
- import applyPosition from "../applyPosition.js";
2
+ import applyPosition from "../applyPosition";
3
3
  describe("flyout/applyPosition", () => {
4
4
  let content;
5
5
  let trigger;
@@ -126,6 +126,26 @@ describe("flyout/applyPosition", () => {
126
126
  });
127
127
  expect(result.position).toBe("start");
128
128
  });
129
+ test("keeps content within the viewport when fallbackMinHeight doesn't fit on any side", () => {
130
+ // Child element keeps its size when content is cloned for the position tests
131
+ const child = document.createElement("div");
132
+ child.style.height = "2000px";
133
+ content.appendChild(child);
134
+ applyPosition({
135
+ content,
136
+ trigger,
137
+ triggerCoordinates: null,
138
+ position: "bottom",
139
+ fallbackPositions: ["bottom", "top"],
140
+ fallbackAdjustLayout: true,
141
+ fallbackMinHeight: `${window.innerHeight * 2}px`,
142
+ lastUsedPosition: null,
143
+ onDeactivate: vi.fn(),
144
+ });
145
+ const height = parseFloat(content.style.height);
146
+ expect(height).toBeGreaterThan(0);
147
+ expect(height).toBeLessThanOrEqual(window.innerHeight - 16);
148
+ });
129
149
  test("removes content clone from DOM after calculation", () => {
130
150
  const initialChildCount = document.body.children.length;
131
151
  applyPosition({
@@ -1,6 +1,6 @@
1
1
  import { beforeEach, describe, expect, test, vi } from "vitest";
2
- import { VIEWPORT_OFFSET } from "../../constants.js";
3
- import calculateLayoutAdjustment from "../calculateLayoutAdjustment.js";
2
+ import { VIEWPORT_OFFSET } from "../../constants";
3
+ import calculateLayoutAdjustment from "../calculateLayoutAdjustment";
4
4
  describe("flyout/calculateLayoutAdjustment", () => {
5
5
  const createBounds = (left, top, width, height) => {
6
6
  return {
@@ -359,6 +359,74 @@ describe("flyout/calculateLayoutAdjustment", () => {
359
359
  expect(result.styles.left).toBe(VIEWPORT_OFFSET);
360
360
  expect(result.styles.width).toBe(984);
361
361
  });
362
+ test("adjusts height when content overflows on both sides", () => {
363
+ const result = calculateLayoutAdjustment({
364
+ position: "bottom",
365
+ styles: {
366
+ // Trigger is scrolled past the container top so content starts above it
367
+ top: -24,
368
+ left: 200,
369
+ bottom: null,
370
+ right: null,
371
+ },
372
+ flyoutBounds: createBounds(0, 0, 150, 2000),
373
+ triggerBounds: createBounds(200, -60, 50, 30),
374
+ containerBounds: { left: 0, top: 0, width: 1000, height: 800 },
375
+ fallbackAdjustLayout: true,
376
+ fallbackMinHeight: undefined,
377
+ width: undefined,
378
+ });
379
+ // overflow.top = 0 + 8 - (-24) = 32
380
+ // overflow.bottom = -24 + 2000 + 8 - 0 - 800 = 1184
381
+ // height = 2000 - 32 - 1184 = 784, trimmed on both edges
382
+ // top = -24 + 32 = 8
383
+ expect(result.styles.top).toBe(VIEWPORT_OFFSET);
384
+ expect(result.styles.height).toBe(800 - VIEWPORT_OFFSET * 2);
385
+ });
386
+ test("adjusts right value when right overflows for vertical position with right set", () => {
387
+ const result = calculateLayoutAdjustment({
388
+ position: "top-end",
389
+ styles: {
390
+ top: 100,
391
+ left: 900, // With flyout width 150, would overflow right edge
392
+ bottom: 500,
393
+ right: -50,
394
+ },
395
+ flyoutBounds: createBounds(0, 0, 150, 200),
396
+ triggerBounds: createBounds(900, 100, 50, 30),
397
+ containerBounds: { left: 0, top: 0, width: 1000, height: 800 },
398
+ fallbackAdjustLayout: true,
399
+ fallbackMinHeight: undefined,
400
+ width: undefined,
401
+ });
402
+ // overflow.right = 900 + 150 + 8 - 0 - 1000 = 58
403
+ // left = 900 - 58 = 842
404
+ // right = -50 + 58 = 8
405
+ expect(result.styles.left).toBe(842);
406
+ expect(result.styles.right).toBe(VIEWPORT_OFFSET);
407
+ });
408
+ test("adjusts bottom value when bottom overflows for horizontal position with bottom set", () => {
409
+ const result = calculateLayoutAdjustment({
410
+ position: "start-bottom",
411
+ styles: {
412
+ top: 700, // With flyout height 200, would overflow bottom edge
413
+ left: 100,
414
+ bottom: -100,
415
+ right: 800,
416
+ },
417
+ flyoutBounds: createBounds(0, 0, 150, 200),
418
+ triggerBounds: createBounds(100, 700, 50, 30),
419
+ containerBounds: { left: 0, top: 0, width: 1000, height: 800 },
420
+ fallbackAdjustLayout: true,
421
+ fallbackMinHeight: undefined,
422
+ width: undefined,
423
+ });
424
+ // overflow.bottom = 700 + 200 + 8 - 0 - 800 = 108
425
+ // top = 700 - 108 = 592
426
+ // bottom = -100 + 108 = 8
427
+ expect(result.styles.top).toBe(592);
428
+ expect(result.styles.bottom).toBe(VIEWPORT_OFFSET);
429
+ });
362
430
  test("adjusts height and updates bottom value when bottom is set", () => {
363
431
  const result = calculateLayoutAdjustment({
364
432
  position: "end",
@@ -1,5 +1,5 @@
1
1
  import { beforeEach, describe, expect, test, vi } from "vitest";
2
- import calculatePosition from "../calculatePosition.js";
2
+ import calculatePosition from "../calculatePosition";
3
3
  describe("flyout/calculatePosition", () => {
4
4
  const createBounds = (left, top, width, height) => {
5
5
  return {
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import centerBySize from "../centerBySize.js";
2
+ import centerBySize from "../centerBySize";
3
3
  describe("flyout/centerBySize", () => {
4
4
  test("centers even value", () => {
5
5
  expect(centerBySize(100, 50)).toEqual(25);
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import getPositionFallbacks from "../getPositionFallbacks.js";
2
+ import getPositionFallbacks from "../getPositionFallbacks";
3
3
  describe("flyout/getPositionFallbacks", () => {
4
4
  test("returns original position first for top-start", () => {
5
5
  const result = getPositionFallbacks("top-start");
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import getRTLPosition from "../getRTLPosition.js";
2
+ import getRTLPosition from "../getRTLPosition";
3
3
  describe("flyout/getRTLPosition", () => {
4
4
  test("keeps top position", () => {
5
5
  expect(getRTLPosition("top")).toEqual("top");
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "vitest";
2
- import isFullyVisible from "../isFullyVisible.js";
2
+ import isFullyVisible from "../isFullyVisible";
3
3
  describe("flyout/isFullyVisible", () => {
4
4
  test("returns true when flyout is fully visible within visual container", () => {
5
5
  const result = isFullyVisible({
@@ -1,2 +1,2 @@
1
1
  // Internal
2
- export { default as rafThrottle } from "./rafThrottle.js";
2
+ export { default as rafThrottle } from "./rafThrottle";
@@ -1,5 +1,5 @@
1
1
  import { beforeEach, describe, expect, test, vi } from "vitest";
2
- import rafThrottle from "../rafThrottle.js";
2
+ import rafThrottle from "../rafThrottle";
3
3
  const waitForNextFrame = () => {
4
4
  return new Promise((resolve) => {
5
5
  requestAnimationFrame(() => {
@@ -1,2 +1,2 @@
1
1
  // External
2
- export { default as isRTL } from "./isRTL.js";
2
+ export { default as isRTL } from "./isRTL";
@@ -1,5 +1,5 @@
1
1
  import { afterAll, beforeEach, describe, expect, test, vi } from "vitest";
2
- import isRTL from "../isRTL.js";
2
+ import isRTL from "../isRTL";
3
3
  describe("i18n/isRTL", () => {
4
4
  beforeEach(() => {
5
5
  document.documentElement.removeAttribute("dir");
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- export { TrapFocus } from "./a11y/index.js";
2
- export { default as keys } from "./constants/keys.js";
3
- export { classNames } from "./css/index.js";
4
- export { Flyout } from "./flyout/index.js";
5
- export { isRTL } from "./i18n/index.js";
6
- export { lockScroll } from "./scroll/index.js";
1
+ export { TrapFocus } from "./a11y";
2
+ export { default as keys } from "./constants/keys";
3
+ export { classNames } from "./css";
4
+ export { Flyout } from "./flyout";
5
+ export { isRTL } from "./i18n";
6
+ export { lockScroll } from "./scroll";
package/dist/internal.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * If you want to use one of these utilities, open an issue or a PR about moving it to the public API file
6
6
  */
7
- export { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode, focusableSelector, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, } from "./a11y/index.js";
8
- export { findParent, getShadowRoot } from "./dom/index.js";
9
- export { rafThrottle } from "./helpers/index.js";
10
- export { disableScroll, enableScroll } from "./scroll/index.js";
7
+ export { activateKeyboardMode, checkKeyboardMode, deactivateKeyboardMode, focusableSelector, focusFirstElement, focusLastElement, focusNextElement, focusPreviousElement, getActiveElement, getFocusableElements, } from "./a11y";
8
+ export { findParent, getShadowRoot } from "./dom";
9
+ export { rafThrottle } from "./helpers";
10
+ export { disableScroll, enableScroll } from "./scroll";
@@ -1,4 +1,4 @@
1
1
  // External
2
- export { lockScroll } from "./lock.js";
2
+ export { lockScroll } from "./lock";
3
3
  // Internal
4
- export { disableScroll, enableScroll } from "./disable.js";
4
+ export { disableScroll, enableScroll } from "./disable";
@@ -2,6 +2,6 @@ export declare const lockScroll: (args?: {
2
2
  containerEl?: HTMLElement | null;
3
3
  originEl?: HTMLElement | null;
4
4
  callback?: () => void;
5
- }) => ((args?: {
5
+ }) => (unlockArgs?: {
6
6
  callback?: () => void;
7
- }) => void) | undefined;
7
+ }) => void;
@@ -1,26 +1,31 @@
1
- import { findClosestScrollableContainer } from "../dom/index.js";
2
- import { isIOS } from "../platform/index.js";
3
- import lockSafariScroll from "./lockSafari.js";
4
- import lockStandardScroll from "./lockStandard.js";
1
+ import { findClosestScrollableContainer } from "../dom";
2
+ import { isIOS } from "../platform";
3
+ import lockSafariScroll from "./lockSafari";
4
+ import lockStandardScroll from "./lockStandard";
5
+ const locks = new WeakMap();
5
6
  export const lockScroll = (args) => {
6
7
  const isIOSLock = isIOS();
7
- let reset = () => { };
8
8
  const container = args?.containerEl ??
9
9
  (args?.originEl && findClosestScrollableContainer({ el: args.originEl })) ??
10
10
  document.documentElement;
11
11
  const lockedDocumentScroll = container === document.documentElement;
12
- // Already locked so no need to lock again and trigger the callback
13
- if (container.style.overflow === "hidden")
14
- return;
15
- if (isIOSLock && lockedDocumentScroll) {
16
- reset = lockSafariScroll();
17
- }
18
- else {
19
- reset = lockStandardScroll({ container });
12
+ let lock = locks.get(container);
13
+ if (!lock) {
14
+ const reset = isIOSLock && lockedDocumentScroll ? lockSafariScroll() : lockStandardScroll({ container });
15
+ lock = { count: 0, reset };
16
+ locks.set(container, lock);
20
17
  }
18
+ lock.count++;
21
19
  args?.callback?.();
22
- return (args) => {
23
- reset();
24
- args?.callback?.();
20
+ let released = false;
21
+ return (unlockArgs) => {
22
+ if (released)
23
+ return;
24
+ released = true;
25
+ if (--lock.count <= 0) {
26
+ lock.reset();
27
+ locks.delete(container);
28
+ }
29
+ unlockArgs?.callback?.();
25
30
  };
26
31
  };
@@ -1,4 +1,4 @@
1
- import { StyleCache } from "../css/index.js";
1
+ import { StyleCache } from "../css";
2
2
  const styleCache = new StyleCache();
3
3
  const lockSafariScroll = () => {
4
4
  const viewport = window.visualViewport;
@@ -13,7 +13,7 @@ const lockSafariScroll = () => {
13
13
  overflow: "hidden",
14
14
  });
15
15
  return () => {
16
- styleCache.reset();
16
+ styleCache.reset(document.body);
17
17
  window.scrollTo({ top: scrollY, left: scrollX, behavior: "instant" });
18
18
  };
19
19
  };
@@ -1,20 +1,19 @@
1
- import { StyleCache } from "../css/index.js";
2
- import { getScrollbarWidth } from "./helpers.js";
1
+ import { StyleCache } from "../css";
2
+ import { getScrollbarWidth } from "./helpers";
3
3
  const styleCache = new StyleCache();
4
4
  const lockStandardScroll = (args) => {
5
5
  const { container } = args;
6
- const rect = container.getBoundingClientRect();
7
- const isOverflowing = rect.left + rect.right < window.innerWidth;
8
- styleCache.set(container, { overflow: "hidden" });
6
+ const isOverflowing = container.scrollHeight > container.clientHeight;
7
+ const styles = { overflow: "hidden" };
9
8
  if (isOverflowing) {
10
9
  if (CSS.supports("scrollbar-gutter", "stable")) {
11
- styleCache.set(container, { scrollbarGutter: "stable" });
10
+ styles.scrollbarGutter = "stable";
12
11
  }
13
12
  else {
14
- const scrollBarWidth = getScrollbarWidth();
15
- styleCache.set(container, { paddingRight: `${scrollBarWidth}px` });
13
+ styles.paddingRight = `${getScrollbarWidth()}px`;
16
14
  }
17
15
  }
18
- return () => styleCache.reset();
16
+ styleCache.set(container, styles);
17
+ return () => styleCache.reset(container);
19
18
  };
20
19
  export default lockStandardScroll;
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
- import { lockScroll } from "../lock.js";
2
+ import { lockScroll } from "../lock";
3
3
  // Mock the platform module to avoid iOS path
4
4
  vi.mock("@/platform", () => ({
5
5
  isIOS: () => false,
@@ -36,6 +36,42 @@ describe("scroll/lockScroll", () => {
36
36
  unlock?.();
37
37
  expect(container.style.overflow).toBe("auto");
38
38
  });
39
+ test("reserves space for the scrollbar on a vertically overflowing container", () => {
40
+ const container = document.createElement("div");
41
+ container.style.overflow = "auto";
42
+ container.style.height = "100px";
43
+ document.body.appendChild(container);
44
+ const content = document.createElement("div");
45
+ content.style.height = "500px";
46
+ container.appendChild(content);
47
+ // The container actually overflows vertically, so locking it removes the
48
+ // vertical scrollbar and must compensate for the horizontal space it took.
49
+ expect(container.scrollHeight).toBeGreaterThan(container.clientHeight);
50
+ const unlock = lockScroll({ containerEl: container });
51
+ // Chromium (the test browser) supports scrollbar-gutter, so the lock
52
+ // reserves the gutter rather than falling back to paddingRight.
53
+ expect(container.style.scrollbarGutter).toBe("stable");
54
+ unlock?.();
55
+ expect(container.style.scrollbarGutter).toBe("");
56
+ document.body.removeChild(container);
57
+ });
58
+ test("does not reserve space when the container does not overflow vertically", () => {
59
+ const container = document.createElement("div");
60
+ container.style.overflow = "auto";
61
+ container.style.height = "200px";
62
+ document.body.appendChild(container);
63
+ const content = document.createElement("div");
64
+ content.style.height = "50px";
65
+ container.appendChild(content);
66
+ // No vertical overflow -> no scrollbar to compensate for.
67
+ expect(container.scrollHeight).not.toBeGreaterThan(container.clientHeight);
68
+ const unlock = lockScroll({ containerEl: container });
69
+ expect(container.style.overflow).toBe("hidden");
70
+ expect(container.style.scrollbarGutter).toBe("");
71
+ expect(container.style.paddingRight).toBe("");
72
+ unlock?.();
73
+ document.body.removeChild(container);
74
+ });
39
75
  test("finds scrollable container from origin element", () => {
40
76
  const scrollableContainer = document.createElement("div");
41
77
  scrollableContainer.style.overflow = "auto";
@@ -52,19 +88,54 @@ describe("scroll/lockScroll", () => {
52
88
  unlock?.();
53
89
  expect(scrollableContainer.style.overflow).toBe("auto");
54
90
  });
55
- test("unlocks after multiple locks", () => {
91
+ test("keeps scroll locked until every stacked lock is released", () => {
56
92
  const unlock1 = lockScroll({});
57
93
  const unlock2 = lockScroll({});
58
94
  expect(document.documentElement.style.overflow).toBe("hidden");
95
+ // The first release must not unlock while a second lock is still held
59
96
  unlock1?.();
97
+ expect(document.documentElement.style.overflow).toBe("hidden");
98
+ // Only the last release actually unlocks the container
99
+ unlock2?.();
60
100
  expect(document.documentElement.style.overflow).toBe("");
101
+ });
102
+ test("ignores repeated calls to the same unlock", () => {
103
+ const unlock1 = lockScroll({});
104
+ const unlock2 = lockScroll({});
105
+ // Calling the first unlock twice must not decrement the count for unlock2
106
+ unlock1?.();
107
+ unlock1?.();
108
+ expect(document.documentElement.style.overflow).toBe("hidden");
61
109
  unlock2?.();
62
110
  expect(document.documentElement.style.overflow).toBe("");
63
111
  });
112
+ test("unlocking one container does not affect another locked container", () => {
113
+ const a = document.createElement("div");
114
+ a.style.overflow = "auto";
115
+ a.style.height = "100px";
116
+ document.body.appendChild(a);
117
+ const b = document.createElement("div");
118
+ b.style.overflow = "scroll";
119
+ b.style.height = "100px";
120
+ document.body.appendChild(b);
121
+ const unlockA = lockScroll({ containerEl: a });
122
+ const unlockB = lockScroll({ containerEl: b });
123
+ expect(a.style.overflow).toBe("hidden");
124
+ expect(b.style.overflow).toBe("hidden");
125
+ unlockA?.();
126
+ // B shares the module-level StyleCache with A, but must stay locked
127
+ expect(a.style.overflow).toBe("auto");
128
+ expect(b.style.overflow).toBe("hidden");
129
+ unlockB?.();
130
+ expect(b.style.overflow).toBe("scroll");
131
+ document.body.removeChild(a);
132
+ document.body.removeChild(b);
133
+ });
64
134
  test("calls lock callback immediately", () => {
65
135
  const lockCb = vi.fn();
66
- lockScroll({ callback: lockCb });
136
+ const unlock = lockScroll({ callback: lockCb });
67
137
  expect(lockCb).toHaveBeenCalledTimes(1);
138
+ unlock?.();
68
139
  });
69
140
  test("calls unlock callback when unlocking", () => {
70
141
  const unlockCb = vi.fn();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reshaped/utilities",
3
- "version": "4.0.3",
3
+ "version": "4.1.0",
4
4
  "description": "Vanilla JS utilities for implementing common UI patterns",
5
5
  "homepage": "https://reshaped.so",
6
6
  "bugs": {
@@ -40,8 +40,8 @@
40
40
  },
41
41
  "scripts": {
42
42
  "clean": "rm -rf dist",
43
- "dev": "tsc-watch --onSuccess \"resolve-tspaths\"",
44
- "build": "tsc && resolve-tspaths",
43
+ "dev": "tsc-watch --onSuccess \"tsc-alias\"",
44
+ "build": "tsc && tsc-alias",
45
45
  "test:browser": "vitest run --project=browser"
46
46
  }
47
47
  }