@primer/react 0.0.0-20260225044625 → 0.0.0-20260225173407

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 (67) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/dist/Banner/Banner-f672cdf9.css +1 -1
  3. package/dist/Banner/Banner-f672cdf9.css.map +1 -1
  4. package/dist/Blankslate/Blankslate-a039d79a.css +1 -1
  5. package/dist/Blankslate/Blankslate-a039d79a.css.map +1 -1
  6. package/dist/Button/ButtonBase-781fba8b.css +1 -1
  7. package/dist/Button/ButtonBase-781fba8b.css.map +1 -1
  8. package/dist/Heading/Heading-26b4879b.css +1 -1
  9. package/dist/Heading/Heading-26b4879b.css.map +1 -1
  10. package/dist/Skeleton/SkeletonBox-e078be7c.css +1 -1
  11. package/dist/Skeleton/SkeletonBox-e078be7c.css.map +1 -1
  12. package/dist/SkeletonText/SkeletonText-5cf908c1.css +1 -1
  13. package/dist/SkeletonText/SkeletonText-5cf908c1.css.map +1 -1
  14. package/dist/Spinner/Spinner-2dbceeca.css +1 -1
  15. package/dist/Spinner/Spinner-2dbceeca.css.map +1 -1
  16. package/dist/Text/Text-ca7603b7.css +1 -1
  17. package/dist/Text/Text-ca7603b7.css.map +1 -1
  18. package/dist/ToggleSwitch/ToggleSwitch-d1bd60b0.css +2 -0
  19. package/dist/ToggleSwitch/ToggleSwitch-d1bd60b0.css.map +1 -0
  20. package/dist/ToggleSwitch/ToggleSwitch.module.css.js +1 -1
  21. package/dist/Tooltip/Tooltip-fffa9948.css +1 -1
  22. package/dist/Tooltip/Tooltip-fffa9948.css.map +1 -1
  23. package/dist/TooltipV2/Tooltip-5a80d7b2.css +1 -1
  24. package/dist/TooltipV2/Tooltip-5a80d7b2.css.map +1 -1
  25. package/dist/TopicTag/TopicTag-955c0fbf.css +1 -1
  26. package/dist/TopicTag/TopicTag-955c0fbf.css.map +1 -1
  27. package/dist/UnderlineNav/UnderlineNav-9d1ce906.css +2 -0
  28. package/dist/UnderlineNav/UnderlineNav-9d1ce906.css.map +1 -0
  29. package/dist/UnderlineNav/UnderlineNav.d.ts +0 -2
  30. package/dist/UnderlineNav/UnderlineNav.d.ts.map +1 -1
  31. package/dist/UnderlineNav/UnderlineNav.js +395 -288
  32. package/dist/UnderlineNav/UnderlineNav.module.css.js +2 -2
  33. package/dist/UnderlineNav/UnderlineNavContext.d.ts +1 -11
  34. package/dist/UnderlineNav/UnderlineNavContext.d.ts.map +1 -1
  35. package/dist/UnderlineNav/UnderlineNavContext.js +1 -4
  36. package/dist/UnderlineNav/UnderlineNavItem-86b7d4b2.css +2 -0
  37. package/dist/UnderlineNav/UnderlineNavItem-86b7d4b2.css.map +1 -0
  38. package/dist/UnderlineNav/UnderlineNavItem.d.ts +4 -0
  39. package/dist/UnderlineNav/UnderlineNavItem.d.ts.map +1 -1
  40. package/dist/UnderlineNav/UnderlineNavItem.js +8 -23
  41. package/dist/UnderlineNav/UnderlineNavItem.module.css.js +1 -1
  42. package/dist/UnderlineNav/types.d.ts +0 -5
  43. package/dist/UnderlineNav/types.d.ts.map +1 -1
  44. package/dist/experimental/IssueLabel/IssueLabel-d9c2c5cf.css +1 -1
  45. package/dist/experimental/IssueLabel/IssueLabel-d9c2c5cf.css.map +1 -1
  46. package/dist/experimental/UnderlinePanels/UnderlinePanels-162f9aed.css +2 -0
  47. package/dist/experimental/UnderlinePanels/UnderlinePanels-162f9aed.css.map +1 -0
  48. package/dist/experimental/UnderlinePanels/UnderlinePanels.module.css.js +1 -1
  49. package/dist/internal/components/UnderlineTabbedInterface-e91b4f85.css +2 -0
  50. package/dist/internal/components/UnderlineTabbedInterface-e91b4f85.css.map +1 -0
  51. package/dist/internal/components/UnderlineTabbedInterface.d.ts.map +1 -1
  52. package/dist/internal/components/UnderlineTabbedInterface.js +83 -69
  53. package/dist/internal/components/UnderlineTabbedInterface.module.css.js +1 -1
  54. package/package.json +1 -1
  55. package/dist/ToggleSwitch/ToggleSwitch-dee0295d.css +0 -2
  56. package/dist/ToggleSwitch/ToggleSwitch-dee0295d.css.map +0 -1
  57. package/dist/UnderlineNav/UnderlineNav-4344d9b0.css +0 -2
  58. package/dist/UnderlineNav/UnderlineNav-4344d9b0.css.map +0 -1
  59. package/dist/UnderlineNav/UnderlineNavItem-b65e8fd3.css +0 -2
  60. package/dist/UnderlineNav/UnderlineNavItem-b65e8fd3.css.map +0 -1
  61. package/dist/UnderlineNav/styles.d.ts +0 -16
  62. package/dist/UnderlineNav/styles.d.ts.map +0 -1
  63. package/dist/UnderlineNav/styles.js +0 -19
  64. package/dist/experimental/UnderlinePanels/UnderlinePanels-e4b325b9.css +0 -2
  65. package/dist/experimental/UnderlinePanels/UnderlinePanels-e4b325b9.css.map +0 -1
  66. package/dist/internal/components/UnderlineTabbedInterface-4197ee28.css +0 -2
  67. package/dist/internal/components/UnderlineTabbedInterface-4197ee28.css.map +0 -1
@@ -1,119 +1,267 @@
1
- import React, { forwardRef, useRef, useState, useEffect, useCallback } from 'react';
1
+ import React, { forwardRef, useRef, useState, useMemo, useEffect, useCallback } from 'react';
2
2
  import { UnderlineNavContext } from './UnderlineNavContext.js';
3
- import { useResizeObserver } from '../hooks/useResizeObserver.js';
4
3
  import VisuallyHidden from '../_VisuallyHidden.js';
5
- import { dividerStyles, baseMenuMinWidth, menuItemStyles } from './styles.js';
6
- import { UnderlineWrapper, UnderlineItemList, LoadingCounter, GAP } from '../internal/components/UnderlineTabbedInterface.js';
4
+ import { UnderlineWrapper, UnderlineItemList, LoadingCounter } from '../internal/components/UnderlineTabbedInterface.js';
7
5
  import { TriangleDownIcon } from '@primer/octicons-react';
8
6
  import { useOnEscapePress } from '../hooks/useOnEscapePress.js';
9
7
  import { useOnOutsideClick } from '../hooks/useOnOutsideClick.js';
10
8
  import { useId } from '../hooks/useId.js';
11
9
  import { ActionList } from '../ActionList/index.js';
12
10
  import { invariant } from '../utils/invariant.js';
11
+ import { clsx } from 'clsx';
13
12
  import classes from './UnderlineNav.module.css.js';
14
- import { getAnchoredPosition } from '@primer/behaviors';
15
13
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
16
14
  import { ButtonComponent } from '../Button/Button.js';
17
15
  import CounterLabel from '../CounterLabel/CounterLabel.js';
18
16
 
19
- // When page is loaded, we don't have ref for the more button as it is not on the DOM yet.
20
- // However, we need to calculate number of possible items when the more button present as well. So using the width of the more button as a constant.
21
- const MORE_BTN_WIDTH = 86;
22
- // The height is needed to make sure we don't have a layout shift when the more button is the only item in the nav.
23
- const MORE_BTN_HEIGHT = 45;
24
- const overflowEffect = (navWidth, moreMenuWidth, childArray, childWidthArray, noIconChildWidthArray, updateListAndMenu) => {
25
- let iconsVisible = true;
26
- if (childWidthArray.length === 0) {
27
- updateListAndMenu({
28
- items: childArray,
29
- menuItems: []
30
- }, iconsVisible, false);
31
- return;
32
- }
33
- const numberOfItemsPossible = calculatePossibleItems(childWidthArray, navWidth);
34
- const numberOfItemsWithoutIconPossible = calculatePossibleItems(noIconChildWidthArray, navWidth);
35
- // We need to take more menu width into account when calculating the number of items possible
36
- const numberOfItemsPossibleWithMoreMenu = calculatePossibleItems(noIconChildWidthArray, navWidth, moreMenuWidth || MORE_BTN_WIDTH);
37
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
- const items = [];
39
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- const menuItems = [];
41
-
42
- // First, we check if we can fit all the items with their icons
43
- if (childArray.length <= numberOfItemsPossible) {
44
- items.push(...childArray);
45
- } else if (childArray.length <= numberOfItemsWithoutIconPossible) {
46
- // if we can't fit all the items with their icons, we check if we can fit all the items without their icons
47
- iconsVisible = false;
48
- items.push(...childArray);
49
- } else {
50
- // if we can't fit all the items without their icons, we keep the icons hidden and show the ones that doesn't fit into the list in the overflow menu
51
- iconsVisible = false;
17
+ // Threshold for considering an item "fully visible" in IntersectionObserver
18
+ const VISIBILITY_THRESHOLD = 0.95;
52
19
 
53
- /* Below is an accessibility requirement. Never show only one item in the overflow menu.
54
- * If there is only one item left to display in the overflow menu according to the calculation,
55
- * we need to pull another item from the list into the overflow menu.
56
- */
57
- const numberOfItemsInMenu = childArray.length - numberOfItemsPossibleWithMoreMenu;
58
- const numberOfListItems = numberOfItemsInMenu === 1 ? numberOfItemsPossibleWithMoreMenu - 1 : numberOfItemsPossibleWithMoreMenu;
59
- for (const [index, child] of childArray.entries()) {
60
- if (index < numberOfListItems) {
61
- items.push(child);
62
- } else {
63
- const ariaCurrent = child.props['aria-current'];
64
- const isCurrent = Boolean(ariaCurrent) && ariaCurrent !== 'false';
65
- // We need to make sure to keep the selected item always visible.
66
- // To do that, we swap the selected item with the last item in the list to make it visible. (When there is at least 1 item in the list to swap.)
67
- if (isCurrent && numberOfListItems > 0) {
68
- // If selected item couldn't make in to the list, we swap it with the last item in the list.
69
- const indexToReplaceAt = numberOfListItems - 1; // because we are replacing the last item in the list
70
- // splice method modifies the array by removing 1 item here at the given index and replace it with the "child" element then returns the removed item.
71
- const propsectiveAction = items.splice(indexToReplaceAt, 1, child)[0];
72
- menuItems.push(propsectiveAction);
73
- } else {
74
- menuItems.push(child);
75
- }
76
- }
77
- }
78
- }
79
- updateListAndMenu({
80
- items,
81
- menuItems
82
- }, iconsVisible, true);
83
- };
20
+ // Approximate width of the "More" button + divider. IO's rootMargin shrinks the
21
+ // detection zone by this amount so items overflow before reaching the list edge,
22
+ // leaving room for the button.
23
+ const MORE_BTN_WIDTH = 80;
84
24
  const getValidChildren = children => {
85
25
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
26
  return React.Children.toArray(children).filter(child => /*#__PURE__*/React.isValidElement(child));
87
27
  };
88
- const calculatePossibleItems = (childWidthArray, navWidth, moreMenuWidth = 0) => {
89
- const widthToFit = navWidth - moreMenuWidth;
90
- let breakpoint = childWidthArray.length; // assume all items will fit
91
- let sumsOfChildWidth = 0;
92
- for (const [index, childWidth] of childWidthArray.entries()) {
93
- sumsOfChildWidth = sumsOfChildWidth + childWidth.width + GAP;
94
- if (sumsOfChildWidth > widthToFit) {
95
- breakpoint = index;
96
- break;
28
+
29
+ // ─────────────────────────────────────────────────────────────────────────────
30
+ // Overflow detection via IntersectionObserver + ResizeObserver
31
+ // ─────────────────────────────────────────────────────────────────────────────
32
+ //
33
+ // Layout overview:
34
+ //
35
+ // ┌─ NavWrapper (position: relative) ──────────────────────────────────────┐
36
+ // │ ┌─ OverflowList (overflow: hidden) ─────────────────────────────────┐ │
37
+ // │ │ [Code] [Issues] [PRs] [Discuss] [Actions] ░░░░░░░░░░░░░░░░░░░░░░ │ │
38
+ // │ │ visible items ──────────────────▶│ clipped by overflow: hidden │ │
39
+ // │ └───────────────────────────────────┼───────────────────────────────┘ │
40
+ // │ │ │
41
+ // │ CSS Anchor ─────────┘ │
42
+ // │ Positioning ┌──────────┐ │
43
+ // │ (position-anchor)─▶│ More ▼ │ │
44
+ // │ └──────────┘ │
45
+ // └────────────────────────────────────────────────────────────────────────┘
46
+ //
47
+ // How it works:
48
+ //
49
+ // 1. The <ul> has overflow: hidden. Items that don't fit are clipped.
50
+ //
51
+ // 2. An IntersectionObserver (root = <ul>) detects which items are clipped.
52
+ // rootMargin: '0px -80px 0px 0px' shrinks the detection zone from the
53
+ // right by MORE_BTN_WIDTH, reserving space for the "More" button.
54
+ //
55
+ // 3. When overflow is detected, overflowStartIndex is set via React state.
56
+ // Items from that index onward get aria-hidden + tabIndex={-1} and are
57
+ // duplicated in the overflow dropdown menu.
58
+ //
59
+ // 4. The "More" button uses CSS Anchor Positioning to sit flush after the
60
+ // last visible item. Zero-size anchor markers (<li>) after each item
61
+ // provide anchor points; position-anchor targets the right one.
62
+ //
63
+ // Icon toggle state machine:
64
+ //
65
+ // ┌────────────┐ overflow detected ┌────────────────────────┐
66
+ // │ normal │─────────────────────▶│ trying-without-icons │
67
+ // │ (icons) │ │ (hid icons, waiting) │
68
+ // └────────────┘ └───────────┬────────────┘
69
+ // ▲ │ IO re-fires
70
+ // │ ┌───────────┴────────────┐
71
+ // │ ▼ ▼
72
+ // │ still overflow? no overflow?
73
+ // │ │ │
74
+ // │ ▼ │
75
+ // │ set overflowStartIndex │
76
+ // │ (show More button) │
77
+ // │ │ │
78
+ // │ └────────┬───────────────┘
79
+ // │ ▼
80
+ // │ ┌───────────────────────┐
81
+ // │ │ normal │
82
+ // │ │ (no icons) │
83
+ // │ └───────────┬───────────┘
84
+ // │ │
85
+ // │ RO: list grew past threshold
86
+ // │ │
87
+ // │ ▼
88
+ // │ ┌────────────────────────┐
89
+ // │ │ trying-with-icons │
90
+ // │ │ (re-enabled icons) │
91
+ // │ └───────────┬────────────┘
92
+ // │ │ IO re-fires
93
+ // │ ┌───────────┴────────────┐
94
+ // │ ▼ ▼
95
+ // │ icons fit? overflow?
96
+ // │ │ │
97
+ // │ ▼ ▼
98
+ // └──────────────── clear overflow revert to no icons
99
+ // phase='normal' (back to normal, no icons)
100
+ //
101
+ // ─────────────────────────────────────────────────────────────────────────────
102
+
103
+ /**
104
+ * Sets up IntersectionObserver + ResizeObserver on the nav list to detect
105
+ * which items overflow and manage the icon visibility toggle.
106
+ *
107
+ * Returns a cleanup function that disconnects both observers.
108
+ */
109
+ function setupOverflowObservers(list, wrapper, refs, setOverflowStartIndex) {
110
+ const {
111
+ iconsVisibleRef,
112
+ iconPhaseRef,
113
+ widthWhenIconsDisabledRef,
114
+ visibilityMapRef,
115
+ ioReadyRef
116
+ } = refs;
117
+
118
+ // Toggle icon visibility via CSS data attribute (no React re-render).
119
+ const setIconsVisible = visible => {
120
+ iconsVisibleRef.current = visible;
121
+ wrapper.setAttribute('data-icons-visible', String(visible));
122
+ };
123
+
124
+ // Sync the initial attribute
125
+ wrapper.setAttribute('data-icons-visible', String(iconsVisibleRef.current));
126
+ visibilityMapRef.current.clear();
127
+
128
+ // ── IntersectionObserver ──────────────────────────────────────────────
129
+ const handleIntersection = entries => {
130
+ // Step 1: Update the visibility map with fresh intersection data
131
+ for (const entry of entries) {
132
+ visibilityMapRef.current.set(entry.target, entry.intersectionRatio >= VISIBILITY_THRESHOLD);
133
+ }
134
+
135
+ // Step 2: Find the first non-visible nav item (skip anchor markers)
136
+ const navItems = Array.from(list.children).filter(child => !child.hasAttribute('data-anchor-marker'));
137
+ let firstOverflow = -1;
138
+ for (let i = 0; i < navItems.length; i++) {
139
+ if (visibilityMapRef.current.get(navItems[i]) === false) {
140
+ firstOverflow = i;
141
+ break;
142
+ }
143
+ }
144
+ const hasOverflowNow = firstOverflow !== -1;
145
+ ioReadyRef.current = true;
146
+
147
+ // Step 3: Handle the result based on current icon phase
148
+ if (hasOverflowNow) {
149
+ handleOverflow(firstOverflow, navItems.length, list, refs, setIconsVisible, setOverflowStartIndex);
97
150
  } else {
98
- continue;
151
+ handleNoOverflow(list, refs, setIconsVisible, setOverflowStartIndex);
152
+ }
153
+ };
154
+ const observer = new IntersectionObserver(handleIntersection, {
155
+ root: list,
156
+ rootMargin: `0px -${MORE_BTN_WIDTH}px 0px 0px`,
157
+ threshold: [0, VISIBILITY_THRESHOLD, 1]
158
+ });
159
+
160
+ // Observe only nav items (skip anchor markers)
161
+ for (let i = 0; i < list.children.length; i++) {
162
+ if (!list.children[i].hasAttribute('data-anchor-marker')) {
163
+ observer.observe(list.children[i]);
99
164
  }
100
165
  }
101
- return breakpoint;
102
- };
103
166
 
104
- // Inline styles converted from baseMenuStyles for use as CSSProperties
105
- const baseMenuInlineStyles = {
106
- position: 'absolute',
107
- zIndex: 1,
108
- top: '90%',
109
- boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
110
- borderRadius: 12,
111
- background: 'var(--overlay-bgColor)',
112
- listStyle: 'none',
113
- minWidth: `${baseMenuMinWidth}px`,
114
- maxWidth: '640px',
115
- right: 0
116
- };
167
+ // ── ResizeObserver ────────────────────────────────────────────────────
168
+ // IO won't re-fire when all items are already fully visible and the
169
+ // root just gets wider. RO detects this and triggers icon retry.
170
+ const resizeObserver = new ResizeObserver(() => {
171
+ if (!iconsVisibleRef.current && iconPhaseRef.current === 'normal') {
172
+ const currentWidth = list.clientWidth;
173
+ if (currentWidth > widthWhenIconsDisabledRef.current + 20) {
174
+ setIconsVisible(true);
175
+ iconPhaseRef.current = 'trying-with-icons';
176
+ }
177
+ }
178
+ });
179
+ resizeObserver.observe(list);
180
+ return () => {
181
+ observer.disconnect();
182
+ resizeObserver.disconnect();
183
+ };
184
+ }
185
+
186
+ /** Called by IO when at least one item is clipped. */
187
+ function handleOverflow(firstOverflow, itemCount, list, refs, setIconsVisible, setOverflowStartIndex) {
188
+ const {
189
+ iconPhaseRef,
190
+ iconsVisibleRef,
191
+ widthWhenIconsDisabledRef
192
+ } = refs;
193
+
194
+ // Phase: we tried re-enabling icons but they don't fit. Revert.
195
+ if (iconPhaseRef.current === 'trying-with-icons') {
196
+ setIconsVisible(false);
197
+ iconPhaseRef.current = 'normal';
198
+ widthWhenIconsDisabledRef.current = list.clientWidth;
199
+ return;
200
+ }
201
+
202
+ // Phase: first overflow with icons. Try hiding icons.
203
+ if (iconsVisibleRef.current) {
204
+ setIconsVisible(false);
205
+ iconPhaseRef.current = 'trying-without-icons';
206
+ widthWhenIconsDisabledRef.current = list.clientWidth;
207
+ return;
208
+ }
209
+
210
+ // Phase: we hid icons and it's still overflowing. Accept it.
211
+ if (iconPhaseRef.current === 'trying-without-icons') {
212
+ iconPhaseRef.current = 'normal';
213
+ }
214
+
215
+ // IO uses a negative rootMargin to reserve space for the More button.
216
+ // On a grow transition, items might appear clipped within the shrunken
217
+ // detection zone but actually fit in the full container width (since
218
+ // removing overflow also removes the More button). Check scrollWidth
219
+ // to avoid a false-positive overflow.
220
+ if (list.scrollWidth <= list.clientWidth) {
221
+ setOverflowStartIndex(-1);
222
+ return;
223
+ }
224
+
225
+ // Accessibility: never show only 1 item in the overflow menu.
226
+ let adjustedIndex = firstOverflow;
227
+ const overflowCount = itemCount - firstOverflow;
228
+ if (overflowCount === 1 && itemCount > 1) {
229
+ adjustedIndex = firstOverflow - 1;
230
+ }
231
+ setOverflowStartIndex(adjustedIndex);
232
+ }
233
+
234
+ /** Called by IO when all items are fully visible. */
235
+ function handleNoOverflow(list, refs, setIconsVisible, setOverflowStartIndex) {
236
+ const {
237
+ iconPhaseRef,
238
+ iconsVisibleRef,
239
+ widthWhenIconsDisabledRef
240
+ } = refs;
241
+ if (iconPhaseRef.current === 'trying-without-icons') {
242
+ // Items fit without icons. Keep icons hidden, clear overflow.
243
+ iconPhaseRef.current = 'normal';
244
+ setOverflowStartIndex(-1);
245
+ return;
246
+ }
247
+ if (iconPhaseRef.current === 'trying-with-icons') {
248
+ // Icons fit! Keep them, clear overflow.
249
+ iconPhaseRef.current = 'normal';
250
+ setOverflowStartIndex(-1);
251
+ return;
252
+ }
253
+ if (!iconsVisibleRef.current) {
254
+ // All items fit but icons are hidden. Try re-enabling icons.
255
+ // Don't clear overflow yet to prevent a flash if icons cause overflow.
256
+ const currentWidth = list.clientWidth;
257
+ if (currentWidth > widthWhenIconsDisabledRef.current + 20) {
258
+ setIconsVisible(true);
259
+ iconPhaseRef.current = 'trying-with-icons';
260
+ return; // Wait for next IO fire to decide
261
+ }
262
+ }
263
+ setOverflowStartIndex(-1);
264
+ }
117
265
  const UnderlineNav = /*#__PURE__*/forwardRef(({
118
266
  as = 'nav',
119
267
  'aria-label': ariaLabel,
@@ -122,41 +270,36 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
122
270
  className,
123
271
  children
124
272
  }, forwardedRef) => {
125
- var _listRef$current2;
126
273
  const backupRef = useRef(null);
127
274
  const navRef = forwardedRef !== null && forwardedRef !== void 0 ? forwardedRef : backupRef;
128
275
  const listRef = useRef(null);
129
- const moreMenuRef = useRef(null);
130
276
  const moreMenuBtnRef = useRef(null);
131
- const containerRef = React.useRef(null);
277
+ const menuListRef = useRef(null);
132
278
  const disclosureWidgetId = useId();
133
279
  const [isWidgetOpen, setIsWidgetOpen] = useState(false);
134
- const [iconsVisible, setIconsVisible] = useState(true);
135
- const [childWidthArray, setChildWidthArray] = useState([]);
136
- const [noIconChildWidthArray, setNoIconChildWidthArray] = useState([]);
137
- // Track whether the initial overflow calculation is complete to prevent CLS
138
- const [isOverflowMeasured, setIsOverflowMeasured] = useState(false);
139
- const validChildren = getValidChildren(children);
280
+ // Track icon visibility in a ref (not state) — toggling is done via CSS data attribute
281
+ // on the wrapper, avoiding React re-render cycles.
282
+ const iconsVisibleRef = useRef(true);
283
+ // Index from which items overflow (-1 = no overflow).
284
+ // All items from this index onward are clipped by CSS and duplicated in the overflow menu.
285
+ const [overflowStartIndex, setOverflowStartIndex] = useState(-1);
286
+ // Tracks whether IO has completed its first determination.
287
+ // Before this, the More button is rendered with visibility: hidden to prevent CLS.
288
+ const ioReadyRef = useRef(false);
289
+ const validChildren = useMemo(() => getValidChildren(children), [children]);
290
+ const hasOverflow = overflowStartIndex >= 0 && overflowStartIndex < validChildren.length;
291
+ // When the viewport is too narrow to show any list item. Only the dropdown is shown.
292
+ const onlyMenuVisible = overflowStartIndex === 0;
140
293
 
141
- // Responsive props object manages which items are in the list and which items are in the menu.
142
- const [responsiveProps, setResponsiveProps] = useState({
143
- items: validChildren,
144
- menuItems: []
145
- });
294
+ // Phase tracking for icon toggle (see state machine diagram above).
295
+ const iconPhaseRef = useRef('normal');
146
296
 
147
- // Make sure to have the fresh props data for list items when children are changed (keeping aria-current up-to-date)
148
- const listItems = responsiveProps.items.map(item => {
149
- var _validChildren$find;
150
- return (_validChildren$find = validChildren.find(child => child.key === item.key)) !== null && _validChildren$find !== void 0 ? _validChildren$find : item;
151
- });
297
+ // Tracks the list width when icons were last disabled due to overflow.
298
+ // Icons will only be retried when the list grows beyond this width.
299
+ const widthWhenIconsDisabledRef = useRef(0);
152
300
 
153
- // Make sure to have the fresh props data for menu items when children are changed (keeping aria-current up-to-date)
154
- const menuItems = responsiveProps.menuItems.map(menuItem => {
155
- var _validChildren$find2;
156
- return (_validChildren$find2 = validChildren.find(child => child.key === menuItem.key)) !== null && _validChildren$find2 !== void 0 ? _validChildren$find2 : menuItem;
157
- });
158
- // This is the case where the viewport is too narrow to show any list item with the more menu. In this case, we only show the dropdown
159
- const onlyMenuVisible = responsiveProps.items.length === 0;
301
+ // Visibility map for IntersectionObserver — tracks each element's intersection state
302
+ const visibilityMapRef = useRef(new Map());
160
303
  if (process.env.NODE_ENV !== "production") {
161
304
  // Practically, this is not a conditional hook, it is just making sure this hook runs only on DEV not PROD.
162
305
  // eslint-disable-next-line react-hooks/rules-of-hooks
@@ -169,70 +312,59 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
169
312
  !ariaLabel ? process.env.NODE_ENV !== "production" ? invariant(false, 'Use the `aria-label` prop to provide an accessible label for assistive technology') : invariant(false) : void 0;
170
313
  });
171
314
  }
172
- function getItemsWidth(itemText) {
173
- var _noIconChildWidthArra, _noIconChildWidthArra2;
174
- return (_noIconChildWidthArra = (_noIconChildWidthArra2 = noIconChildWidthArray.find(item => item.text === itemText)) === null || _noIconChildWidthArra2 === void 0 ? void 0 : _noIconChildWidthArra2.width) !== null && _noIconChildWidthArra !== void 0 ? _noIconChildWidthArra : 0;
175
- }
176
- const swapMenuItemWithListItem = (prospectiveListItem, indexOfProspectiveListItem, event, callback) => {
177
- var _navRef$current$getBo, _navRef$current, _listRef$current$getB, _listRef$current;
178
- // get the selected menu item's width
179
- const widthToFitIntoList = getItemsWidth(prospectiveListItem.props.children);
180
- // Check if there is any empty space on the right side of the list
181
- const availableSpace = ((_navRef$current$getBo = (_navRef$current = navRef.current) === null || _navRef$current === void 0 ? void 0 : _navRef$current.getBoundingClientRect().width) !== null && _navRef$current$getBo !== void 0 ? _navRef$current$getBo : 0) - ((_listRef$current$getB = (_listRef$current = listRef.current) === null || _listRef$current === void 0 ? void 0 : _listRef$current.getBoundingClientRect().width) !== null && _listRef$current$getB !== void 0 ? _listRef$current$getB : 0);
182
315
 
183
- // Calculate how many items need to be pulled in to the menu to make room for the selected menu item
184
- // I.e. if we need to pull 2 items in (index 0 and index 1), breakpoint (index) will return 1.
185
- const index = getBreakpointForItemSwapping(widthToFitIntoList, availableSpace);
186
- const indexToSliceAt = responsiveProps.items.length - 1 - index;
187
- // Form the new list of items
188
- const itemsLeftInList = [...responsiveProps.items].slice(0, indexToSliceAt);
189
- const updatedItemList = [...itemsLeftInList, prospectiveListItem];
190
- // Form the new menu items
191
- const itemsToAddToMenu = [...responsiveProps.items].slice(indexToSliceAt);
192
- const updatedMenuItems = [...menuItems];
193
- // Add itemsToAddToMenu array's items to the menu at the index of the prospectiveListItem and remove 1 count of items (prospectiveListItem)
194
- updatedMenuItems.splice(indexOfProspectiveListItem, 1, ...itemsToAddToMenu);
195
- callback({
196
- items: updatedItemList,
197
- menuItems: updatedMenuItems
198
- }, false, true);
199
- };
200
- // How many items do we need to pull in to the menu to make room for the selected menu item.
201
- function getBreakpointForItemSwapping(widthToFitIntoList, availableSpace) {
202
- let widthToSwap = 0;
203
- let breakpoint = 0;
204
- for (const [index, item] of [...responsiveProps.items].reverse().entries()) {
205
- widthToSwap += getItemsWidth(item.props.children);
206
- if (widthToFitIntoList < widthToSwap + availableSpace) {
207
- breakpoint = index;
208
- break;
209
- }
316
+ // Compute display items with aria-current swap.
317
+ // All items are always rendered in the list (CSS clips overflow).
318
+ // If the aria-current item is in the overflow range, swap it with the last visible item.
319
+ const [displayItems, menuItems] = useMemo(() => {
320
+ if (!hasOverflow) {
321
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
322
+ return [validChildren, []];
210
323
  }
211
- return breakpoint;
212
- }
213
- const updateListAndMenu = useCallback((props, displayIcons, overflowMeasured) => {
214
- setResponsiveProps(props);
215
- setIconsVisible(displayIcons);
216
- if (overflowMeasured) {
217
- setIsOverflowMeasured(true);
324
+ const items = [...validChildren];
325
+
326
+ // Collect overflow items
327
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
328
+ const overflow = [];
329
+ for (let i = overflowStartIndex; i < items.length; i++) {
330
+ overflow.push(items[i]);
218
331
  }
219
- }, []);
220
- const setChildrenWidth = useCallback(size => {
221
- setChildWidthArray(arr => {
222
- const newArr = [...arr, size];
223
- return newArr;
224
- });
225
- }, []);
226
- const setNoIconChildrenWidth = useCallback(size => {
227
- setNoIconChildWidthArray(arr => {
228
- const newArr = [...arr, size];
229
- return newArr;
332
+
333
+ // Check if aria-current item is in the overflow range
334
+ const currentOverflowIdx = overflow.findIndex(child => {
335
+ const ac = child.props['aria-current'];
336
+ return Boolean(ac) && ac !== 'false';
230
337
  });
231
- }, []);
232
- const closeOverlay = React.useCallback(() => {
338
+ if (currentOverflowIdx !== -1 && overflowStartIndex > 0) {
339
+ // Swap current item with the last visible item to keep it in view
340
+ const itemIdxInFull = overflowStartIndex + currentOverflowIdx;
341
+ const lastVisibleIdx = overflowStartIndex - 1;
342
+ [items[itemIdxInFull], items[lastVisibleIdx]] = [items[lastVisibleIdx], items[itemIdxInFull]];
343
+ // Update overflow array to reflect the swap
344
+ overflow[currentOverflowIdx] = items[itemIdxInFull];
345
+ }
346
+ return [items, overflow];
347
+ }, [validChildren, overflowStartIndex, hasOverflow]);
348
+
349
+ // See setupOverflowObservers() above for how this works.
350
+ useEffect(() => {
351
+ const list = listRef.current;
352
+ const wrapper = navRef.current;
353
+ if (!list || typeof IntersectionObserver === 'undefined' || typeof ResizeObserver === 'undefined') {
354
+ return;
355
+ }
356
+ return setupOverflowObservers(list, wrapper, {
357
+ iconsVisibleRef,
358
+ iconPhaseRef,
359
+ widthWhenIconsDisabledRef,
360
+ visibilityMapRef,
361
+ ioReadyRef
362
+ }, setOverflowStartIndex);
363
+ }, [validChildren, navRef]);
364
+ const closeOverlay = useCallback(() => {
233
365
  setIsWidgetOpen(false);
234
- }, [setIsWidgetOpen]);
235
- const focusOnMoreMenuBtn = React.useCallback(() => {
366
+ }, []);
367
+ const focusOnMoreMenuBtn = useCallback(() => {
236
368
  var _moreMenuBtnRef$curre;
237
369
  (_moreMenuBtnRef$curre = moreMenuBtnRef.current) === null || _moreMenuBtnRef$curre === void 0 ? void 0 : _moreMenuBtnRef$curre.focus();
238
370
  }, []);
@@ -251,134 +383,109 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
251
383
  }, [isWidgetOpen]);
252
384
  useOnOutsideClick({
253
385
  onClickOutside: closeOverlay,
254
- containerRef,
386
+ containerRef: menuListRef,
255
387
  ignoreClickRefs: [moreMenuBtnRef]
256
388
  });
257
- useResizeObserver(resizeObserverEntries => {
258
- var _moreMenuRef$current$, _moreMenuRef$current;
259
- const navWidth = resizeObserverEntries[0].contentRect.width;
260
- const moreMenuWidth = (_moreMenuRef$current$ = (_moreMenuRef$current = moreMenuRef.current) === null || _moreMenuRef$current === void 0 ? void 0 : _moreMenuRef$current.getBoundingClientRect().width) !== null && _moreMenuRef$current$ !== void 0 ? _moreMenuRef$current$ : 0;
261
- navWidth !== 0 && overflowEffect(navWidth, moreMenuWidth, validChildren, childWidthArray, noIconChildWidthArray, updateListAndMenu);
262
- }, navRef);
263
-
264
- // Compute menuInlineStyles if needed
265
- let menuInlineStyles = {
266
- ...baseMenuInlineStyles
267
- };
268
- if (containerRef.current && listRef.current) {
269
- const {
270
- left
271
- } = getAnchoredPosition(containerRef.current, listRef.current, {
272
- align: 'start',
273
- side: 'outside-bottom'
274
- });
275
- menuInlineStyles = {
276
- ...baseMenuInlineStyles,
277
- right: undefined,
278
- left
279
- };
280
- }
281
389
  return /*#__PURE__*/jsxs(UnderlineNavContext.Provider, {
282
390
  value: {
283
- setChildrenWidth,
284
- setNoIconChildrenWidth,
285
- loadingCounters,
286
- iconsVisible
391
+ loadingCounters
287
392
  },
288
393
  children: [ariaLabel && /*#__PURE__*/jsx(VisuallyHidden, {
289
394
  as: "h2",
290
395
  children: `${ariaLabel} navigation`
291
- }), /*#__PURE__*/jsx(UnderlineWrapper, {
396
+ }), /*#__PURE__*/jsxs(UnderlineWrapper, {
292
397
  as: as,
293
398
  "aria-label": ariaLabel,
294
- className: className,
399
+ className: clsx(className, classes.NavWrapper),
295
400
  ref: navRef,
296
401
  "data-variant": variant,
297
- "data-overflow-measured": isOverflowMeasured ? 'true' : 'false',
298
- children: /*#__PURE__*/jsxs(UnderlineItemList, {
402
+ "data-icons-visible": iconsVisibleRef.current,
403
+ children: [/*#__PURE__*/jsx(UnderlineItemList, {
299
404
  ref: listRef,
300
405
  role: "list",
301
- children: [listItems, menuItems.length > 0 && /*#__PURE__*/jsxs("li", {
302
- ref: moreMenuRef,
303
- style: {
304
- display: 'flex',
305
- alignItems: 'center',
306
- height: `${MORE_BTN_HEIGHT}px`
307
- },
308
- children: [!onlyMenuVisible && /*#__PURE__*/jsx("div", {
309
- style: dividerStyles
310
- }), /*#__PURE__*/jsx(ButtonComponent, {
311
- ref: moreMenuBtnRef,
312
- className: classes.MoreButton,
313
- "aria-controls": disclosureWidgetId,
314
- "aria-expanded": isWidgetOpen,
315
- onClick: onAnchorClick,
316
- trailingAction: TriangleDownIcon,
317
- children: /*#__PURE__*/jsx("span", {
318
- children: onlyMenuVisible ? /*#__PURE__*/jsxs(Fragment, {
319
- children: [/*#__PURE__*/jsxs(VisuallyHidden, {
320
- as: "span",
321
- children: [`${ariaLabel}`, "\xA0"]
322
- }), "Menu"]
323
- }) : /*#__PURE__*/jsxs(Fragment, {
324
- children: ["More", /*#__PURE__*/jsxs(VisuallyHidden, {
325
- as: "span",
326
- children: ["\xA0", `${ariaLabel} items`]
327
- })]
328
- })
329
- })
330
- }), /*#__PURE__*/jsx(ActionList, {
331
- selectionVariant: "single",
332
- ref: containerRef,
333
- id: disclosureWidgetId,
334
- style: {
335
- ...((_listRef$current2 = listRef.current) !== null && _listRef$current2 !== void 0 && _listRef$current2.clientWidth && listRef.current.clientWidth >= baseMenuMinWidth ? baseMenuInlineStyles : menuInlineStyles),
336
- display: isWidgetOpen ? 'block' : 'none'
337
- },
338
- children: menuItems.map((menuItem, index) => {
339
- const {
340
- children: menuItemChildren,
341
- counter,
342
- 'aria-current': ariaCurrent,
343
- onSelect,
344
- ...menuItemProps
345
- } = menuItem.props;
346
-
347
- // This logic is used to pop the selected item out of the menu and into the list when the navigation is control externally
348
- if (Boolean(ariaCurrent) && ariaCurrent !== 'false') {
349
- const event = new MouseEvent('click');
350
- !onlyMenuVisible && swapMenuItemWithListItem(menuItem, index,
351
- // @ts-ignore - not a big deal because it is internally creating an event but ask help
352
- event, updateListAndMenu);
406
+ className: classes.OverflowList,
407
+ children: displayItems.map((item, index) => {
408
+ var _item$key;
409
+ const isOverflowing = hasOverflow && index >= overflowStartIndex;
410
+ return /*#__PURE__*/jsxs(React.Fragment, {
411
+ children: [isOverflowing ? /*#__PURE__*/React.cloneElement(item, {
412
+ 'aria-hidden': 'true'
413
+ }) : item, /*#__PURE__*/jsx("li", {
414
+ role: "presentation",
415
+ "aria-hidden": "true",
416
+ "data-anchor-marker": "",
417
+ className: classes.AnchorMarker,
418
+ style: {
419
+ anchorName: `--nav-anchor-${index}`
353
420
  }
354
- return /*#__PURE__*/jsx(ActionList.LinkItem, {
355
- style: menuItemStyles,
356
- onClick: event => {
357
- // When there are no items in the list, do not run the swap function as we want to keep everything in the menu.
358
- !onlyMenuVisible && swapMenuItemWithListItem(menuItem, index, event, updateListAndMenu);
359
- closeOverlay();
360
- focusOnMoreMenuBtn();
361
- // fire onSelect event that comes from the UnderlineNav.Item (if it is defined)
362
- typeof onSelect === 'function' && onSelect(event);
363
- },
364
- ...menuItemProps,
365
- children: /*#__PURE__*/jsxs("span", {
366
- className: classes.MenuItemContent,
367
- children: [menuItemChildren, loadingCounters ? /*#__PURE__*/jsx(LoadingCounter, {}) : counter !== undefined && /*#__PURE__*/jsx("span", {
368
- "data-component": "counter",
369
- children: /*#__PURE__*/jsx(CounterLabel, {
370
- children: counter
371
- })
372
- })]
373
- })
374
- }, menuItemChildren);
421
+ })]
422
+ }, (_item$key = item.key) !== null && _item$key !== void 0 ? _item$key : index);
423
+ })
424
+ }), (hasOverflow || !ioReadyRef.current) && /*#__PURE__*/jsxs("div", {
425
+ className: clsx(classes.MoreMenuContainer, !hasOverflow && classes.MoreMenuHidden),
426
+ style: {
427
+ positionAnchor: overflowStartIndex > 0 ? `--nav-anchor-${overflowStartIndex - 1}` : undefined
428
+ },
429
+ children: [!onlyMenuVisible && /*#__PURE__*/jsx("div", {
430
+ className: classes.Divider
431
+ }), /*#__PURE__*/jsx(ButtonComponent, {
432
+ ref: moreMenuBtnRef,
433
+ className: classes.MoreButton,
434
+ "aria-controls": disclosureWidgetId,
435
+ "aria-expanded": isWidgetOpen,
436
+ onClick: onAnchorClick,
437
+ trailingAction: TriangleDownIcon,
438
+ children: /*#__PURE__*/jsx("span", {
439
+ children: onlyMenuVisible ? /*#__PURE__*/jsxs(Fragment, {
440
+ children: [/*#__PURE__*/jsxs(VisuallyHidden, {
441
+ as: "span",
442
+ children: [`${ariaLabel}`, "\xA0"]
443
+ }), "Menu"]
444
+ }) : /*#__PURE__*/jsxs(Fragment, {
445
+ children: ["More", /*#__PURE__*/jsxs(VisuallyHidden, {
446
+ as: "span",
447
+ children: ["\xA0", `${ariaLabel} items`]
448
+ })]
375
449
  })
376
- })]
450
+ })
451
+ }), /*#__PURE__*/jsx(ActionList, {
452
+ selectionVariant: "single",
453
+ ref: menuListRef,
454
+ id: disclosureWidgetId,
455
+ className: clsx(classes.OverflowMenu, isWidgetOpen && classes.OverflowMenuOpen),
456
+ children: menuItems.map((menuItem, index) => {
457
+ var _menuItem$key;
458
+ const {
459
+ children: menuItemChildren,
460
+ counter,
461
+ onSelect,
462
+ ...menuItemProps
463
+ } = menuItem.props;
464
+ return /*#__PURE__*/jsx(ActionList.LinkItem, {
465
+ className: classes.MenuItem,
466
+ onClick: event => {
467
+ closeOverlay();
468
+ focusOnMoreMenuBtn();
469
+ // fire onSelect event that comes from the UnderlineNav.Item (if it is defined)
470
+ typeof onSelect === 'function' && onSelect(event);
471
+ },
472
+ ...menuItemProps,
473
+ children: /*#__PURE__*/jsxs("span", {
474
+ className: classes.MenuItemContent,
475
+ children: [menuItemChildren, loadingCounters ? /*#__PURE__*/jsx(LoadingCounter, {}) : counter !== undefined && /*#__PURE__*/jsx("span", {
476
+ "data-component": "counter",
477
+ children: /*#__PURE__*/jsx(CounterLabel, {
478
+ children: counter
479
+ })
480
+ })]
481
+ })
482
+ }, (_menuItem$key = menuItem.key) !== null && _menuItem$key !== void 0 ? _menuItem$key : index);
483
+ })
377
484
  })]
378
- })
485
+ })]
379
486
  })]
380
487
  });
381
488
  });
382
489
  UnderlineNav.displayName = 'UnderlineNav';
383
490
 
384
- export { MORE_BTN_WIDTH, UnderlineNav, getValidChildren };
491
+ export { UnderlineNav };