@navikt/ds-react 7.32.3 → 7.32.5

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 (47) hide show
  1. package/cjs/accordion/AccordionHeader.js +1 -1
  2. package/cjs/accordion/AccordionHeader.js.map +1 -1
  3. package/cjs/form/combobox/Input/ToggleListButton.js +2 -1
  4. package/cjs/form/combobox/Input/ToggleListButton.js.map +1 -1
  5. package/cjs/modal/Modal.js +12 -0
  6. package/cjs/modal/Modal.js.map +1 -1
  7. package/cjs/modal/ModalUtils.d.ts +3 -2
  8. package/cjs/modal/ModalUtils.js +60 -10
  9. package/cjs/modal/ModalUtils.js.map +1 -1
  10. package/cjs/util/detectBrowser.d.ts +3 -1
  11. package/cjs/util/detectBrowser.js +27 -1
  12. package/cjs/util/detectBrowser.js.map +1 -1
  13. package/cjs/util/hideNonTargetElements.d.ts +8 -0
  14. package/cjs/util/hideNonTargetElements.js +141 -0
  15. package/cjs/util/hideNonTargetElements.js.map +1 -0
  16. package/cjs/util/hooks/useScrollLock.d.ts +11 -0
  17. package/cjs/util/hooks/useScrollLock.js +270 -0
  18. package/cjs/util/hooks/useScrollLock.js.map +1 -0
  19. package/esm/accordion/AccordionHeader.js +1 -1
  20. package/esm/accordion/AccordionHeader.js.map +1 -1
  21. package/esm/form/combobox/Input/ToggleListButton.js +2 -1
  22. package/esm/form/combobox/Input/ToggleListButton.js.map +1 -1
  23. package/esm/modal/Modal.js +13 -1
  24. package/esm/modal/Modal.js.map +1 -1
  25. package/esm/modal/ModalUtils.d.ts +3 -2
  26. package/esm/modal/ModalUtils.js +27 -7
  27. package/esm/modal/ModalUtils.js.map +1 -1
  28. package/esm/util/detectBrowser.d.ts +3 -1
  29. package/esm/util/detectBrowser.js +25 -1
  30. package/esm/util/detectBrowser.js.map +1 -1
  31. package/esm/util/hideNonTargetElements.d.ts +8 -0
  32. package/esm/util/hideNonTargetElements.js +139 -0
  33. package/esm/util/hideNonTargetElements.js.map +1 -0
  34. package/esm/util/hooks/useScrollLock.d.ts +11 -0
  35. package/esm/util/hooks/useScrollLock.js +268 -0
  36. package/esm/util/hooks/useScrollLock.js.map +1 -0
  37. package/package.json +5 -5
  38. package/src/accordion/AccordionHeader.tsx +1 -1
  39. package/src/form/combobox/Input/ToggleListButton.tsx +2 -1
  40. package/src/form/combobox/__tests__/combobox.test.tsx +45 -106
  41. package/src/modal/Modal.test.tsx +13 -24
  42. package/src/modal/Modal.tsx +16 -0
  43. package/src/modal/ModalUtils.ts +35 -7
  44. package/src/util/__tests__/hideNonTargetElements.test.ts +147 -0
  45. package/src/util/detectBrowser.ts +41 -1
  46. package/src/util/hideNonTargetElements.ts +179 -0
  47. package/src/util/hooks/useScrollLock.ts +317 -0
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Modified version of `aria-hidden`-package.
3
+ * - Removed "inert"-functionality.
4
+ * - Removed flexibility for different data-attributes.
5
+ * https://github.com/theKashey/aria-hidden/blob/720e8a8e1cfa047bd299a929d95d47ac860a5c1a/src/index.ts
6
+ */
7
+ import { ownerDocument } from "./owner";
8
+
9
+ type UndoFn = () => void;
10
+
11
+ let ariaHiddenCounter = new WeakMap<Element, number>();
12
+ let markerCounter = new WeakMap<Element, number>();
13
+
14
+ let uncontrolledElementsSet = new WeakSet<Element>();
15
+ let lockCount = 0;
16
+
17
+ const controlAttribute = "aria-hidden";
18
+ const markerName = "data-aksel-hidden";
19
+
20
+ /**
21
+ * Unwraps a Shadow DOM host to find the actual Element in the light DOM.
22
+ */
23
+ function unwrapHost(node: Element | ShadowRoot): Element | null {
24
+ return (
25
+ node &&
26
+ ((node as ShadowRoot).host || unwrapHost(node.parentNode as Element))
27
+ );
28
+ }
29
+
30
+ /**
31
+ * Corrects the target elements by unwrapping Shadow DOM hosts if necessary.
32
+ *
33
+ * @param parent - The parent HTMLElement to check containment against.
34
+ * @param targets - An array of target Elements to correct.
35
+ * @returns An array of corrected Elements that are contained within the parent.
36
+ */
37
+ function correctElements(parent: HTMLElement, targets: Element[]): Element[] {
38
+ return targets
39
+ .map((target) => {
40
+ if (parent.contains(target)) {
41
+ return target;
42
+ }
43
+
44
+ const correctedTarget = unwrapHost(target);
45
+
46
+ if (parent.contains(correctedTarget)) {
47
+ return correctedTarget;
48
+ }
49
+
50
+ return null;
51
+ })
52
+ .filter((x): x is Element => x !== null);
53
+ }
54
+
55
+ /**
56
+ * Applies the aria-hidden attribute to all elements in the body except the specified avoid elements.
57
+ */
58
+ function applyAttributeToOthers(
59
+ uncorrectedAvoidElements: Element[],
60
+ body: HTMLElement,
61
+ ): UndoFn {
62
+ const avoidElements = correctElements(body, uncorrectedAvoidElements);
63
+ const elementsToAvoidWithParents = new Set<Node>();
64
+ const elementsToAvoidUpdating = new Set<Node>(avoidElements);
65
+ const hiddenElements: Element[] = [];
66
+
67
+ avoidElements.forEach(addToAvoidList);
68
+ applyAttributes(body);
69
+ elementsToAvoidWithParents.clear();
70
+
71
+ function addToAvoidList(el: Node | undefined) {
72
+ if (!el || elementsToAvoidWithParents.has(el)) {
73
+ return;
74
+ }
75
+
76
+ elementsToAvoidWithParents.add(el);
77
+ if (el.parentNode) {
78
+ addToAvoidList(el.parentNode);
79
+ }
80
+ }
81
+
82
+ function applyAttributes(parent: Element | null) {
83
+ if (!parent || elementsToAvoidUpdating.has(parent)) {
84
+ return;
85
+ }
86
+
87
+ const parentChildren = parent.children;
88
+
89
+ for (let index = 0; index < parentChildren.length; index += 1) {
90
+ const node = parentChildren[index] as Element;
91
+
92
+ if (elementsToAvoidWithParents.has(node)) {
93
+ applyAttributes(node);
94
+ } else {
95
+ const attr = node.getAttribute(controlAttribute);
96
+
97
+ /*
98
+ * We only check for falsy values here since since arbitrary values
99
+ * (e.g. "true", "foo", "") are all valid for indicating that the element is already hidden.
100
+ */
101
+ const alreadyHidden = attr !== null && attr !== "false";
102
+ const counterValue = (ariaHiddenCounter.get(node) || 0) + 1;
103
+ const markerValue = (markerCounter.get(node) || 0) + 1;
104
+
105
+ ariaHiddenCounter.set(node, counterValue);
106
+ markerCounter.set(node, markerValue);
107
+ hiddenElements.push(node);
108
+
109
+ if (counterValue === 1 && alreadyHidden) {
110
+ uncontrolledElementsSet.add(node);
111
+ }
112
+
113
+ if (markerValue === 1) {
114
+ node.setAttribute(markerName, "");
115
+ }
116
+
117
+ if (!alreadyHidden) {
118
+ node.setAttribute(controlAttribute, "true");
119
+ }
120
+ }
121
+ }
122
+ }
123
+
124
+ lockCount += 1;
125
+
126
+ /* Cleanup */
127
+ return () => {
128
+ for (const element of hiddenElements) {
129
+ const currentCounterValue = ariaHiddenCounter.get(element) || 0;
130
+ const counterValue = currentCounterValue - 1;
131
+ const markerValue = (markerCounter.get(element) || 0) - 1;
132
+
133
+ ariaHiddenCounter.set(element, counterValue);
134
+ markerCounter.set(element, markerValue);
135
+
136
+ if (!counterValue) {
137
+ if (!uncontrolledElementsSet.has(element)) {
138
+ element.removeAttribute(controlAttribute);
139
+ }
140
+
141
+ uncontrolledElementsSet.delete(element);
142
+ }
143
+
144
+ if (!markerValue) {
145
+ element.removeAttribute(markerName);
146
+ }
147
+ }
148
+
149
+ lockCount -= 1;
150
+
151
+ /* Reset */
152
+ if (!lockCount) {
153
+ ariaHiddenCounter = new WeakMap();
154
+ uncontrolledElementsSet = new WeakSet();
155
+ markerCounter = new WeakMap();
156
+ }
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Hides all elements in the document body for assertive technologies except the specified elements with `aria-hidden`.
162
+ * @param avoidElements - An array of elements to avoid hiding.
163
+ * @returns A function that, when called, will undo the hiding of elements.
164
+ */
165
+ function hideNonTargetElements(avoidElements: Element[]): UndoFn {
166
+ const body = ownerDocument(avoidElements[0]).body;
167
+
168
+ /**
169
+ * Assume that elements with `aria-live` or `script` tags should not be hidden.
170
+ * This ensures that live regions and scripts continue to function properly.
171
+ */
172
+ const ingoredElements = Array.from(
173
+ body.querySelectorAll("[aria-live], script"),
174
+ );
175
+
176
+ return applyAttributeToOthers(avoidElements.concat(ingoredElements), body);
177
+ }
178
+
179
+ export { hideNonTargetElements };
@@ -0,0 +1,317 @@
1
+ import { isIOS, isWebKit } from "../detectBrowser";
2
+ import { ownerDocument, ownerWindow } from "../owner";
3
+ import { useClientLayoutEffect } from "./useClientLayoutEffect";
4
+ import { Timeout } from "./useTimeout";
5
+
6
+ let originalHtmlStyles: Partial<CSSStyleDeclaration> = {};
7
+ let originalBodyStyles: Partial<CSSStyleDeclaration> = {};
8
+ let originalHtmlScrollBehavior = "";
9
+
10
+ function hasInsetScrollbars(referenceElement: Element | null) {
11
+ if (typeof document === "undefined") {
12
+ return false;
13
+ }
14
+ const doc = ownerDocument(referenceElement);
15
+ const win = ownerWindow(doc);
16
+ return win.innerWidth - doc.documentElement.clientWidth > 0;
17
+ }
18
+
19
+ function preventScrollBasic(referenceElement: Element | null) {
20
+ const doc = ownerDocument(referenceElement);
21
+ const html = doc.documentElement;
22
+ const originalOverflow = html.style.overflow;
23
+ html.style.overflow = "hidden";
24
+
25
+ return () => {
26
+ html.style.overflow = originalOverflow;
27
+ };
28
+ }
29
+
30
+ function preventScrollStandard(referenceElement: Element | null) {
31
+ const doc = ownerDocument(referenceElement);
32
+ const html = doc.documentElement;
33
+ const body = doc.body;
34
+ const win = ownerWindow(html);
35
+
36
+ let scrollTop = 0;
37
+ let scrollLeft = 0;
38
+ let resizeRaf = 0;
39
+
40
+ /* Pinch-zoom in Safari causes a shift. Just don't lock scroll if there's any pinch-zoom. */
41
+ if (isWebKit && (win.visualViewport?.scale ?? 1) !== 1) {
42
+ return () => {};
43
+ }
44
+
45
+ /**
46
+ * Locks the scroll by applying styles to Html and Body element.
47
+ * Reads the DOM first, then writes to avoid layout thrashing.
48
+ */
49
+ function lockScroll() {
50
+ /* DOM reads: */
51
+
52
+ const htmlStyles = win.getComputedStyle(html);
53
+ const bodyStyles = win.getComputedStyle(body);
54
+
55
+ scrollTop = html.scrollTop;
56
+ scrollLeft = html.scrollLeft;
57
+
58
+ originalHtmlStyles = {
59
+ scrollbarGutter: html.style.scrollbarGutter,
60
+ overflowY: html.style.overflowY,
61
+ overflowX: html.style.overflowX,
62
+ };
63
+ originalHtmlScrollBehavior = html.style.scrollBehavior;
64
+
65
+ originalBodyStyles = {
66
+ position: body.style.position,
67
+ height: body.style.height,
68
+ width: body.style.width,
69
+ boxSizing: body.style.boxSizing,
70
+ overflowY: body.style.overflowY,
71
+ overflowX: body.style.overflowX,
72
+ scrollBehavior: body.style.scrollBehavior,
73
+ };
74
+
75
+ const isScrollableY = html.scrollHeight > html.clientHeight;
76
+ const isScrollableX = html.scrollWidth > html.clientWidth;
77
+ const hasConstantOverflowY =
78
+ htmlStyles.overflowY === "scroll" || bodyStyles.overflowY === "scroll";
79
+ const hasConstantOverflowX =
80
+ htmlStyles.overflowX === "scroll" || bodyStyles.overflowX === "scroll";
81
+
82
+ /* Values can be negative in Firefox */
83
+ const scrollbarWidth = Math.max(0, win.innerWidth - html.clientWidth);
84
+ const scrollbarHeight = Math.max(0, win.innerHeight - html.clientHeight);
85
+
86
+ /*
87
+ * Avoid shift due to <body> margin. NB: This does cause elements to be clipped
88
+ * with whitespace.
89
+ */
90
+ const marginY =
91
+ parseFloat(bodyStyles.marginTop) + parseFloat(bodyStyles.marginBottom);
92
+ const marginX =
93
+ parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight);
94
+
95
+ /**
96
+ * Check support for stable scrollbar gutter to avoid layout shift when scrollbars appear/disappear.
97
+ */
98
+ const supportsStableScrollbarGutter =
99
+ typeof CSS !== "undefined" &&
100
+ CSS.supports?.("scrollbar-gutter", "stable");
101
+
102
+ /*
103
+ * DOM writes:
104
+ * Do not read the DOM past this point!
105
+ */
106
+
107
+ Object.assign(html.style, {
108
+ scrollbarGutter: "stable",
109
+ overflowY:
110
+ !supportsStableScrollbarGutter &&
111
+ (isScrollableY || hasConstantOverflowY)
112
+ ? "scroll"
113
+ : "hidden",
114
+ overflowX:
115
+ !supportsStableScrollbarGutter &&
116
+ (isScrollableX || hasConstantOverflowX)
117
+ ? "scroll"
118
+ : "hidden",
119
+ });
120
+
121
+ Object.assign(body.style, {
122
+ /*
123
+ * Keeps existing positioned children in place (e.g. fixed headers).
124
+ */
125
+ position: "relative",
126
+ /**
127
+ * Limits height to the viewport minus margins/scrollbar compensation to stop vertical overflow from reappearing.
128
+ */
129
+ height:
130
+ marginY || scrollbarHeight
131
+ ? `calc(100dvh - ${marginY + scrollbarHeight}px)`
132
+ : "100dvh",
133
+ /**
134
+ * Mirrors height-logic for width.
135
+ */
136
+ width:
137
+ marginX || scrollbarWidth
138
+ ? `calc(100vw - ${marginX + scrollbarWidth}px)`
139
+ : "100vw",
140
+ /**
141
+ * Ensures the adjusted dimensions include padding/border, matching the measured values.
142
+ */
143
+ boxSizing: "border-box",
144
+ /**
145
+ * Blocks scrollable overflow.
146
+ */
147
+ overflow: "hidden",
148
+ /**
149
+ * Removes smooth-scrolling so immediate position restores occur without animation.
150
+ */
151
+ scrollBehavior: "unset",
152
+ });
153
+
154
+ body.scrollTop = scrollTop;
155
+ body.scrollLeft = scrollLeft;
156
+ html.setAttribute("data-aksel-scroll-locked", "");
157
+ html.style.scrollBehavior = "unset";
158
+ }
159
+
160
+ /**
161
+ * Restores the original scroll position and styles to Html and Body element.
162
+ */
163
+ function cleanup() {
164
+ Object.assign(html.style, originalHtmlStyles);
165
+ Object.assign(body.style, originalBodyStyles);
166
+ html.scrollTop = scrollTop;
167
+ html.scrollLeft = scrollLeft;
168
+ html.removeAttribute("data-aksel-scroll-locked");
169
+ html.style.scrollBehavior = originalHtmlScrollBehavior;
170
+ }
171
+
172
+ /**
173
+ * On resize, restore original styles, then re-apply scroll lock next frame.
174
+ */
175
+ function handleResize() {
176
+ cleanup();
177
+ if (resizeRaf) {
178
+ cancelAnimationFrame(resizeRaf);
179
+ }
180
+
181
+ /**
182
+ * Wait until next frame to re-apply scroll lock ensuring layout has settled after resize.
183
+ */
184
+ resizeRaf = requestAnimationFrame(lockScroll);
185
+ }
186
+
187
+ lockScroll();
188
+ win.addEventListener("resize", handleResize);
189
+
190
+ return () => {
191
+ if (resizeRaf) {
192
+ cancelAnimationFrame(resizeRaf);
193
+ }
194
+ cleanup();
195
+ win.removeEventListener("resize", handleResize);
196
+ };
197
+ }
198
+
199
+ class ScrollLocker {
200
+ lockCount = 0;
201
+ restore: (() => void) | null = null;
202
+ timeoutLock = Timeout.create();
203
+ timeoutUnlock = Timeout.create();
204
+
205
+ /**
206
+ * Aquires a new lock
207
+ * - If first lock, lock document-scroll.
208
+ * - If not first lock, do nothing.
209
+ */
210
+ acquire(referenceElement: Element | null) {
211
+ this.lockCount += 1;
212
+ if (this.lockCount === 1 && this.restore === null) {
213
+ /*
214
+ * Delay locking to avoid layout thrashing when multiple locks/unlocks are requested in quick succession.
215
+ */
216
+ this.timeoutLock.start(0, () => this.lock(referenceElement));
217
+ }
218
+ return this.release;
219
+ }
220
+
221
+ /**
222
+ * Releases a lock
223
+ * - If last lock, unlock document-scroll.
224
+ * - If not last lock, do nothing.
225
+ */
226
+ release = () => {
227
+ this.lockCount -= 1;
228
+ if (this.lockCount === 0 && this.restore) {
229
+ this.timeoutUnlock.start(0, this.unlock);
230
+ }
231
+ };
232
+
233
+ private unlock = () => {
234
+ if (this.lockCount === 0 && this.restore) {
235
+ this.restore?.();
236
+ this.restore = null;
237
+ }
238
+ };
239
+
240
+ private lock(referenceElement: Element | null) {
241
+ if (this.lockCount === 0 || this.restore !== null) {
242
+ return;
243
+ }
244
+
245
+ const doc = ownerDocument(referenceElement);
246
+ const html = doc.documentElement;
247
+ const htmlOverflowY = ownerWindow(html).getComputedStyle(html).overflowY;
248
+
249
+ /* If the site author already hid overflow on <html>, respect it and bail out. */
250
+ if (htmlOverflowY === "hidden" || htmlOverflowY === "clip") {
251
+ this.restore = () => {};
252
+ return;
253
+ }
254
+
255
+ const shouldUseBasicLock = isIOS || !hasInsetScrollbars(referenceElement);
256
+
257
+ /**
258
+ * On iOS, the standard scroll locking method does not work properly if the navbar is collapsed.
259
+ * The following must be researched extensively before activating standard scroll locking on iOS:
260
+ * - Textboxes must scroll into view when focused, and not cause a glitchy scroll animation.
261
+ * - The navbar must not force itself into view and cause layout shift.
262
+ * - Scroll containers must not flicker upon closing a popup when it has an exit animation.
263
+ */
264
+ this.restore = shouldUseBasicLock
265
+ ? preventScrollBasic(referenceElement)
266
+ : preventScrollStandard(referenceElement);
267
+ }
268
+ }
269
+
270
+ const SCROLL_LOCKER = new ScrollLocker();
271
+
272
+ /**
273
+ * Locks the scroll of the document when enabled.
274
+ * @param enabled - Whether to enable the scroll lock.
275
+ */
276
+ function useScrollLock(params: {
277
+ enabled: boolean;
278
+ mounted: boolean;
279
+ open: boolean;
280
+ referenceElement?: Element | null;
281
+ }) {
282
+ const { enabled = true, mounted, open, referenceElement = null } = params;
283
+
284
+ /**
285
+ * When closing elements with "sloppy clicks" (clicks that start inside the element and ends outside),
286
+ * animating out on WebKit browsers (mounted + not open) can cause the whole page to be selected.
287
+ * To prevent this, we temporarily disable user-select on body while the element is animating out.
288
+ * This bug might be fixed in newer WebKit versions.
289
+ *
290
+ * @see https://github.com/mui/base-ui/issues/1135
291
+ */
292
+ useClientLayoutEffect(() => {
293
+ if (enabled && isWebKit && mounted && !open) {
294
+ const doc = ownerDocument(referenceElement);
295
+ const originalUserSelect = doc.body.style.userSelect;
296
+ const originalWebkitUserSelect = doc.body.style.webkitUserSelect;
297
+ doc.body.style.userSelect = "none";
298
+ doc.body.style.webkitUserSelect = "none";
299
+
300
+ return () => {
301
+ doc.body.style.userSelect = originalUserSelect;
302
+ doc.body.style.webkitUserSelect = originalWebkitUserSelect;
303
+ };
304
+ }
305
+ return undefined;
306
+ }, [enabled, mounted, open, referenceElement]);
307
+
308
+ useClientLayoutEffect(() => {
309
+ if (!enabled) {
310
+ return undefined;
311
+ }
312
+
313
+ return SCROLL_LOCKER.acquire(referenceElement);
314
+ }, [enabled, referenceElement]);
315
+ }
316
+
317
+ export { useScrollLock };