@primer/react 0.0.0-20260523120913 → 0.0.0-20260526014931

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # @primer/react
2
2
 
3
- ## 0.0.0-20260523120913
3
+ ## 0.0.0-20260526014931
4
+
5
+ ### Patch Changes
6
+
7
+ - Fake entry to force publishing
8
+
9
+ ## 38.25.0
4
10
 
5
11
  ### Minor Changes
6
12
 
@@ -12,18 +18,6 @@
12
18
 
13
19
  - [#7843](https://github.com/primer/react/pull/7843) [`fc571fd`](https://github.com/primer/react/commit/fc571fd8c3899f19a1dd9e77b8a22f6528d776e2) Thanks [@joshblack](https://github.com/joshblack)! - Update useMergedRefs so that in React 18 no warning is emitted
14
20
 
15
- - Fake entry to force publishing
16
-
17
- - [#7875](https://github.com/primer/react/pull/7875) [`1fcc071`](https://github.com/primer/react/commit/1fcc071865a6b9b06988a84864f20a3faa9d523d) Thanks [@mattcosta7](https://github.com/mattcosta7)! - UnderlineNav: Re-architect item measurement to remove a cascading render on
18
- mount. Each `UnderlineNav.Item` no longer dispatches measurement setState calls
19
- back into its parent via context; `UnderlineNav` now walks its rendered items
20
- in a single layout effect and stores widths in refs. Overflow state is
21
- consolidated into one `useState` object (one commit per change), the context
22
- value is memoized, `UnderlineNav.Item` is wrapped in `React.memo`, and the
23
- external-`aria-current` swap was moved out of render-phase setState into a
24
- layout effect. Behavior is unchanged for consumers, but the initial mount and
25
- overflow-state transitions produce far fewer per-item renders.
26
-
27
21
  ## 38.24.0
28
22
 
29
23
  ### Minor Changes
@@ -15,5 +15,7 @@ export type UnderlineNavProps = {
15
15
  */
16
16
  variant?: 'inset' | 'flush';
17
17
  };
18
+ export declare const MORE_BTN_WIDTH = 86;
19
+ export declare const getValidChildren: (children: React.ReactNode) => React.ReactElement<any>[];
18
20
  export declare const UnderlineNav: React.ForwardRefExoticComponent<UnderlineNavProps & React.RefAttributes<unknown>>;
19
21
  //# sourceMappingURL=UnderlineNav.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"UnderlineNav.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/UnderlineNav.tsx"],"names":[],"mappings":"AACA,OAAO,KAAsE,MAAM,OAAO,CAAA;AAoB1F,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;IACzB,YAAY,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,YAAY,CAAC,CAAA;IACjD,EAAE,CAAC,EAAE,KAAK,CAAC,WAAW,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAA;CAC5B,CAAA;AAkHD,eAAO,MAAM,YAAY,mFA+ZxB,CAAA"}
1
+ {"version":3,"file":"UnderlineNav.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/UnderlineNav.tsx"],"names":[],"mappings":"AACA,OAAO,KAA6D,MAAM,OAAO,CAAA;AAmBjF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;IACzB,YAAY,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,YAAY,CAAC,CAAA;IACjD,EAAE,CAAC,EAAE,KAAK,CAAC,WAAW,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAA;CAC5B,CAAA;AAGD,eAAO,MAAM,cAAc,KAAK,CAAA;AAwEhC,eAAO,MAAM,gBAAgB,GAAI,UAAU,KAAK,CAAC,SAAS,KAEgC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,EAChH,CAAA;AAgCD,eAAO,MAAM,YAAY,mFA8SxB,CAAA"}
@@ -1,9 +1,8 @@
1
- import React, { forwardRef, useRef, useState, useEffect, useCallback, useMemo } from 'react';
1
+ import React, { forwardRef, useRef, useState, useEffect, useCallback } from 'react';
2
2
  import { UnderlineNavContext } from './UnderlineNavContext.js';
3
3
  import { useResizeObserver } from '../hooks/useResizeObserver.js';
4
- import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect.js';
5
4
  import VisuallyHidden from '../_VisuallyHidden.js';
6
- import { baseMenuMinWidth, dividerStyles, menuItemStyles } from './styles.js';
5
+ import { dividerStyles, baseMenuMinWidth, menuItemStyles } from './styles.js';
7
6
  import { UnderlineWrapper, UnderlineItemList, LoadingCounter, GAP } from '../internal/components/UnderlineTabbedInterface.js';
8
7
  import { TriangleDownIcon } from '@primer/octicons-react';
9
8
  import { useOnEscapePress } from '../hooks/useOnEscapePress.js';
@@ -22,19 +21,19 @@ import CounterLabel from '../CounterLabel/CounterLabel.js';
22
21
  const MORE_BTN_WIDTH = 86;
23
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.
24
23
  const MORE_BTN_HEIGHT = 45;
25
- const computeOverflow = (navWidth, moreMenuWidth, childArray, childWidths, noIconChildWidths) => {
24
+ const overflowEffect = (navWidth, moreMenuWidth, childArray, childWidthArray, noIconChildWidthArray, updateListAndMenu) => {
26
25
  let iconsVisible = true;
27
- if (childWidths.size === 0) {
28
- return {
26
+ if (childWidthArray.length === 0) {
27
+ updateListAndMenu({
29
28
  items: childArray,
30
- menuItems: [],
31
- iconsVisible
32
- };
29
+ menuItems: []
30
+ }, iconsVisible, false);
31
+ return;
33
32
  }
34
- const numberOfItemsPossible = calculatePossibleItems(childArray, childWidths, navWidth);
35
- const numberOfItemsWithoutIconPossible = calculatePossibleItems(childArray, noIconChildWidths, navWidth);
33
+ const numberOfItemsPossible = calculatePossibleItems(childWidthArray, navWidth);
34
+ const numberOfItemsWithoutIconPossible = calculatePossibleItems(noIconChildWidthArray, navWidth);
36
35
  // We need to take more menu width into account when calculating the number of items possible
37
- const numberOfItemsPossibleWithMoreMenu = calculatePossibleItems(childArray, noIconChildWidths, navWidth, moreMenuWidth || MORE_BTN_WIDTH);
36
+ const numberOfItemsPossibleWithMoreMenu = calculatePossibleItems(noIconChildWidthArray, navWidth, moreMenuWidth || MORE_BTN_WIDTH);
38
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
38
  const items = [];
40
39
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -77,27 +76,26 @@ const computeOverflow = (navWidth, moreMenuWidth, childArray, childWidths, noIco
77
76
  }
78
77
  }
79
78
  }
80
- return {
79
+ updateListAndMenu({
81
80
  items,
82
- menuItems,
83
- iconsVisible
84
- };
81
+ menuItems
82
+ }, iconsVisible, true);
85
83
  };
86
84
  const getValidChildren = children => {
87
85
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
86
  return React.Children.toArray(children).filter(child => /*#__PURE__*/React.isValidElement(child));
89
87
  };
90
- const calculatePossibleItems = (childArray, widthMap, navWidth, moreMenuWidth = 0) => {
88
+ const calculatePossibleItems = (childWidthArray, navWidth, moreMenuWidth = 0) => {
91
89
  const widthToFit = navWidth - moreMenuWidth;
92
- let breakpoint = childArray.length; // assume all items will fit
90
+ let breakpoint = childWidthArray.length; // assume all items will fit
93
91
  let sumsOfChildWidth = 0;
94
- for (const [index, child] of childArray.entries()) {
95
- var _widthMap$get;
96
- const width = (_widthMap$get = widthMap.get(String(child.key))) !== null && _widthMap$get !== void 0 ? _widthMap$get : 0;
97
- sumsOfChildWidth = sumsOfChildWidth + width + GAP;
92
+ for (const [index, childWidth] of childWidthArray.entries()) {
93
+ sumsOfChildWidth = sumsOfChildWidth + childWidth.width + GAP;
98
94
  if (sumsOfChildWidth > widthToFit) {
99
95
  breakpoint = index;
100
96
  break;
97
+ } else {
98
+ continue;
101
99
  }
102
100
  }
103
101
  return breakpoint;
@@ -124,6 +122,7 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
124
122
  className,
125
123
  children
126
124
  }, forwardedRef) => {
125
+ var _listRef$current2;
127
126
  const backupRef = useRef(null);
128
127
  const navRef = forwardedRef !== null && forwardedRef !== void 0 ? forwardedRef : backupRef;
129
128
  const listRef = useRef(null);
@@ -132,70 +131,32 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
132
131
  const containerRef = React.useRef(null);
133
132
  const disclosureWidgetId = useId();
134
133
  const [isWidgetOpen, setIsWidgetOpen] = useState(false);
135
- // Measurement results are stored in refs because only `computeOverflow` reads them;
136
- // they should not trigger re-renders. Keyed by `String(element.key)` so lookups
137
- // are O(1) and survive non-string item children.
138
- const childWidthsRef = useRef(new Map());
139
- const noIconChildWidthsRef = useRef(new Map());
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);
140
139
  const validChildren = getValidChildren(children);
141
- // Stable signature of the children list — when it changes we re-run the
142
- // measurement pass with all items rendered (with icons) in the list. The
143
- // delimiter is U+0000 (NUL) because React rejects NUL inside element keys,
144
- // so consumer-provided keys cannot collide with the separator.
145
- const childrenKey = validChildren.map(c => String(c.key)).join('\u0000');
146
-
147
- // Single consolidated overflow state. Bundling `items`, `menuItems`,
148
- // `iconsVisible`, `measured`, and `childrenKey` together means every
149
- // overflow update — measurement, swap, resize, or children-change reset —
150
- // is exactly one setState call (one commit), instead of fanning out to
151
- // multiple back-to-back commits.
152
140
 
153
- const [overflowState, setOverflowState] = useState(() => ({
141
+ // Responsive props object manages which items are in the list and which items are in the menu.
142
+ const [responsiveProps, setResponsiveProps] = useState({
154
143
  items: validChildren,
155
- menuItems: [],
156
- iconsVisible: true,
157
- measured: false,
158
- childrenKey
159
- }));
160
-
161
- // Derived-state reset: when the children list changes, push everything back into
162
- // the list (with icons) so the next layout effect can measure all items in one
163
- // pass. This is React's recommended "store information from previous renders"
164
- // pattern — calling setState during render lets React discard the in-progress
165
- // render and re-render immediately with the reset state, before paint.
166
- if (overflowState.childrenKey !== childrenKey) {
167
- setOverflowState({
168
- items: validChildren,
169
- menuItems: [],
170
- iconsVisible: true,
171
- measured: false,
172
- childrenKey
173
- });
174
- }
175
-
176
- // Build a key-indexed view of validChildren once per render so the listItems /
177
- // menuItems prop-refresh below is O(N) instead of O(N^2) via Array.prototype.find.
178
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
179
- const validChildrenByKey = new Map();
180
- for (const c of validChildren) validChildrenByKey.set(String(c.key), c);
181
- const {
182
- iconsVisible,
183
- measured: isOverflowMeasured
184
- } = overflowState;
144
+ menuItems: []
145
+ });
185
146
 
186
147
  // Make sure to have the fresh props data for list items when children are changed (keeping aria-current up-to-date)
187
- const listItems = overflowState.items.map(item => {
188
- var _validChildrenByKey$g;
189
- return (_validChildrenByKey$g = validChildrenByKey.get(String(item.key))) !== null && _validChildrenByKey$g !== void 0 ? _validChildrenByKey$g : item;
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;
190
151
  });
191
152
 
192
153
  // Make sure to have the fresh props data for menu items when children are changed (keeping aria-current up-to-date)
193
- const menuItems = overflowState.menuItems.map(item => {
194
- var _validChildrenByKey$g2;
195
- return (_validChildrenByKey$g2 = validChildrenByKey.get(String(item.key))) !== null && _validChildrenByKey$g2 !== void 0 ? _validChildrenByKey$g2 : item;
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;
196
157
  });
197
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
198
- const onlyMenuVisible = overflowState.items.length === 0;
159
+ const onlyMenuVisible = responsiveProps.items.length === 0;
199
160
  if (process.env.NODE_ENV !== "production") {
200
161
  // Practically, this is not a conditional hook, it is just making sure this hook runs only on DEV not PROD.
201
162
  // eslint-disable-next-line react-hooks/rules-of-hooks
@@ -208,145 +169,66 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
208
169
  !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;
209
170
  });
210
171
  }
211
-
212
- // Returns the measured "no icon" width for an item, looking up by element key.
213
- // Previously this was a text-based lookup, which silently returned 0 when an
214
- // item's children weren't a plain string and caused the swap math to degenerate.
215
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
216
- const getItemNoIconWidth = item => {
217
- var _noIconChildWidthsRef;
218
- return (_noIconChildWidthsRef = noIconChildWidthsRef.current.get(String(item.key))) !== null && _noIconChildWidthsRef !== void 0 ? _noIconChildWidthsRef : 0;
219
- };
220
-
221
- // Pure: returns the {items, menuItems} that result from promoting
222
- // `prospectiveListItem` (currently at position `indexOfProspectiveListItem`
223
- // in `currentMenuItems`) into `currentItems`. Does not call setState.
224
- const computeSwap = (currentItems, currentMenuItems, prospectiveListItem, indexOfProspectiveListItem) => {
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) => {
225
177
  var _navRef$current$getBo, _navRef$current, _listRef$current$getB, _listRef$current;
226
- const widthToFitIntoList = getItemNoIconWidth(prospectiveListItem);
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
227
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);
228
182
 
229
- // How many items at the end of the list have to move to the menu to make
230
- // room for the promoted item.
231
- let widthToSwap = 0;
232
- let breakpoint = 0;
233
- for (const [index, item] of [...currentItems].reverse().entries()) {
234
- widthToSwap += getItemNoIconWidth(item);
235
- if (widthToFitIntoList < widthToSwap + availableSpace) {
236
- breakpoint = index;
237
- break;
238
- }
239
- }
240
- const indexToSliceAt = currentItems.length - 1 - breakpoint;
241
- const itemsLeftInList = currentItems.slice(0, indexToSliceAt);
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);
242
189
  const updatedItemList = [...itemsLeftInList, prospectiveListItem];
243
- const itemsToAddToMenu = currentItems.slice(indexToSliceAt);
244
- const updatedMenuItems = [...currentMenuItems];
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)
245
194
  updatedMenuItems.splice(indexOfProspectiveListItem, 1, ...itemsToAddToMenu);
246
- return {
195
+ callback({
247
196
  items: updatedItemList,
248
197
  menuItems: updatedMenuItems
249
- };
250
- };
251
- const swapMenuItemWithListItem = (prospectiveListItem, indexOfProspectiveListItem) => {
252
- const swap = computeSwap(overflowState.items, menuItems, prospectiveListItem, indexOfProspectiveListItem);
253
- setOverflowState(prev => ({
254
- items: swap.items,
255
- menuItems: swap.menuItems,
256
- iconsVisible: false,
257
- measured: true,
258
- childrenKey: prev.childrenKey
259
- }));
198
+ }, false, true);
260
199
  };
261
-
262
- // Single combined layout effect that performs measurement (when needed) and
263
- // the external-aria-current promotion (when needed), then commits at most
264
- // one setOverflowState per pass. Replaces the previous two effects (each of
265
- // which produced its own commit) and removes the render-phase setState that
266
- // the original component used to do the same swap from inside menuItems.map.
267
- //
268
- // Why no deps array: the swap branch depends on `aria-current` which lives
269
- // on item props (not on `overflowState`); a deps-driven effect would not
270
- // notice prop-only changes without rebuilding a signature. The body
271
- // short-circuits cheaply on every render where neither pass needs to run.
272
- useIsomorphicLayoutEffect(() => {
273
- var _next;
274
- const listEl = listRef.current;
275
- const navEl = navRef.current;
276
- if (!listEl || !navEl) return;
277
- let next = null;
278
-
279
- // Pass 1: measurement (runs once after each remeasure trigger).
280
- if (!isOverflowMeasured) {
281
- var _moreMenuRef$current$, _moreMenuRef$current;
282
- const widths = new Map();
283
- const noIconWidths = new Map();
284
- const itemEls = listEl.querySelectorAll('[data-underlinenav-item="true"]');
285
-
286
- // The N-th [data-underlinenav-item] element corresponds to validChildren[N]
287
- // because the measurement pass runs only when all items are in the list,
288
- // in render order. Pair them up positionally so we can key widths by the
289
- // element's React key.
290
- const upToBoundary = Math.min(itemEls.length, validChildren.length);
291
- for (let index = 0; index < upToBoundary; index++) {
292
- const liEl = itemEls[index];
293
- const linkEl = liEl.querySelector('a, button');
294
- if (!linkEl) continue;
295
- const child = validChildren[index];
296
- const key = String(child.key);
297
- const domRect = linkEl.getBoundingClientRect();
298
- const iconEl = linkEl.querySelector('[data-component="icon"]');
299
- let iconWidthWithMargin = 0;
300
- if (iconEl) {
301
- const style = getComputedStyle(iconEl);
302
- iconWidthWithMargin = iconEl.getBoundingClientRect().width + (parseFloat(style.marginRight) || 0) + (parseFloat(style.marginLeft) || 0);
303
- }
304
- widths.set(key, domRect.width);
305
- noIconWidths.set(key, domRect.width - iconWidthWithMargin);
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;
306
209
  }
307
- childWidthsRef.current = widths;
308
- noIconChildWidthsRef.current = noIconWidths;
309
- const navWidth = navEl.getBoundingClientRect().width;
310
- if (navWidth === 0) return;
311
- 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;
312
- const result = computeOverflow(navWidth, moreMenuWidth, validChildren, widths, noIconWidths);
313
- next = {
314
- items: result.items,
315
- menuItems: result.menuItems,
316
- iconsVisible: result.iconsVisible,
317
- measured: true,
318
- childrenKey: overflowState.childrenKey
319
- };
320
210
  }
321
-
322
- // Pass 2: external-aria-current promotion. Operates on the freshest
323
- // (post-measurement) items so it can fold into the same setState.
324
- const considered = (_next = next) !== null && _next !== void 0 ? _next : overflowState;
325
- if (considered.measured && considered.items.length > 0) {
326
- // Look at FRESH props (current aria-current) by remapping through
327
- // validChildrenByKey (O(1) per lookup; the previous .find() pattern was
328
- // O(N) and ran inside a .map() — quadratic on every commit).
329
- const freshMenuItems = considered.menuItems.map(item => {
330
- var _validChildrenByKey$g3;
331
- return (_validChildrenByKey$g3 = validChildrenByKey.get(String(item.key))) !== null && _validChildrenByKey$g3 !== void 0 ? _validChildrenByKey$g3 : item;
332
- });
333
- const indexOfCurrent = freshMenuItems.findIndex(item => {
334
- const c = item.props['aria-current'];
335
- return Boolean(c) && c !== 'false';
336
- });
337
- if (indexOfCurrent !== -1) {
338
- const swap = computeSwap(considered.items, freshMenuItems, freshMenuItems[indexOfCurrent], indexOfCurrent);
339
- next = {
340
- items: swap.items,
341
- menuItems: swap.menuItems,
342
- iconsVisible: false,
343
- measured: true,
344
- childrenKey: considered.childrenKey
345
- };
346
- }
211
+ return breakpoint;
212
+ }
213
+ const updateListAndMenu = useCallback((props, displayIcons, overflowMeasured) => {
214
+ setResponsiveProps(props);
215
+ setIconsVisible(displayIcons);
216
+ if (overflowMeasured) {
217
+ setIsOverflowMeasured(true);
347
218
  }
348
- if (next) setOverflowState(next);
349
- });
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;
230
+ });
231
+ }, []);
350
232
  const closeOverlay = React.useCallback(() => {
351
233
  setIsWidgetOpen(false);
352
234
  }, [setIsWidgetOpen]);
@@ -373,66 +255,36 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
373
255
  ignoreClickRefs: [moreMenuBtnRef]
374
256
  });
375
257
  useResizeObserver(resizeObserverEntries => {
376
- var _moreMenuRef$current$2, _moreMenuRef$current2;
258
+ var _moreMenuRef$current$, _moreMenuRef$current;
377
259
  const navWidth = resizeObserverEntries[0].contentRect.width;
378
- if (navWidth === 0) return;
379
- const moreMenuWidth = (_moreMenuRef$current$2 = (_moreMenuRef$current2 = moreMenuRef.current) === null || _moreMenuRef$current2 === void 0 ? void 0 : _moreMenuRef$current2.getBoundingClientRect().width) !== null && _moreMenuRef$current$2 !== void 0 ? _moreMenuRef$current$2 : 0;
380
- const result = computeOverflow(navWidth, moreMenuWidth, validChildren, childWidthsRef.current, noIconChildWidthsRef.current);
381
- setOverflowState(prev => ({
382
- items: result.items,
383
- menuItems: result.menuItems,
384
- iconsVisible: result.iconsVisible,
385
- measured: childWidthsRef.current.size > 0 || prev.measured,
386
- childrenKey: prev.childrenKey
387
- }));
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);
388
262
  }, navRef);
389
263
 
390
- // Menu anchor position. `undefined` means "use the default right: 0 from
391
- // baseMenuInlineStyles" (the list is wide enough that no anchoring is
392
- // needed). A number means the menu is anchored to that `left` coordinate,
393
- // overriding right.
394
- //
395
- // This used to be computed inline during render by reading
396
- // containerRef.current / listRef.current — refs are mutable and unsafe to
397
- // read during render under concurrent rendering (the first render saw null
398
- // refs and fell through to the unanchored fallback; subsequent renders
399
- // anchored differently, producing a perceptible reflow).
400
- const [menuAnchorLeft, setMenuAnchorLeft] = useState(undefined);
401
- useIsomorphicLayoutEffect(() => {
402
- const container = containerRef.current;
403
- const list = listRef.current;
404
- if (!container || !list) return;
405
- if (list.clientWidth >= baseMenuMinWidth) {
406
- if (menuAnchorLeft !== undefined) setMenuAnchorLeft(undefined);
407
- return;
408
- }
264
+ // Compute menuInlineStyles if needed
265
+ let menuInlineStyles = {
266
+ ...baseMenuInlineStyles
267
+ };
268
+ if (containerRef.current && listRef.current) {
409
269
  const {
410
270
  left
411
- } = getAnchoredPosition(container, list, {
271
+ } = getAnchoredPosition(containerRef.current, listRef.current, {
412
272
  align: 'start',
413
273
  side: 'outside-bottom'
414
274
  });
415
- if (menuAnchorLeft !== left) setMenuAnchorLeft(left);
416
- }, [isWidgetOpen, isOverflowMeasured, menuItems.length, menuAnchorLeft]);
417
-
418
- // Stable context value: a fresh object literal here would re-render every
419
- // consumer (UnderlineNav.Item) on every parent re-render, undoing the
420
- // React.memo on UnderlineNavItem.
421
- const contextValue = useMemo(() => ({
422
- loadingCounters,
423
- iconsVisible
424
- }), [loadingCounters, iconsVisible]);
425
- const menuStyle = menuAnchorLeft !== undefined ? {
426
- ...baseMenuInlineStyles,
427
- right: undefined,
428
- left: menuAnchorLeft,
429
- display: isWidgetOpen ? 'block' : 'none'
430
- } : {
431
- ...baseMenuInlineStyles,
432
- display: isWidgetOpen ? 'block' : 'none'
433
- };
275
+ menuInlineStyles = {
276
+ ...baseMenuInlineStyles,
277
+ right: undefined,
278
+ left
279
+ };
280
+ }
434
281
  return /*#__PURE__*/jsxs(UnderlineNavContext.Provider, {
435
- value: contextValue,
282
+ value: {
283
+ setChildrenWidth,
284
+ setNoIconChildrenWidth,
285
+ loadingCounters,
286
+ iconsVisible
287
+ },
436
288
  children: [ariaLabel && /*#__PURE__*/jsx(VisuallyHidden, {
437
289
  as: "h2",
438
290
  children: `${ariaLabel} navigation`
@@ -479,23 +331,31 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
479
331
  selectionVariant: "single",
480
332
  ref: containerRef,
481
333
  id: disclosureWidgetId,
482
- style: menuStyle,
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
+ },
483
338
  children: menuItems.map((menuItem, index) => {
484
339
  const {
485
340
  children: menuItemChildren,
486
341
  counter,
487
- // Stripped from the spread below; the swap effect reads aria-current
488
- // directly from item.props (not via these destructured locals).
489
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
490
- 'aria-current': _ariaCurrent,
342
+ 'aria-current': ariaCurrent,
491
343
  onSelect,
492
344
  ...menuItemProps
493
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);
353
+ }
494
354
  return /*#__PURE__*/jsx(ActionList.LinkItem, {
495
355
  style: menuItemStyles,
496
356
  onClick: event => {
497
357
  // When there are no items in the list, do not run the swap function as we want to keep everything in the menu.
498
- !onlyMenuVisible && swapMenuItemWithListItem(menuItem, index);
358
+ !onlyMenuVisible && swapMenuItemWithListItem(menuItem, index, event, updateListAndMenu);
499
359
  closeOverlay();
500
360
  focusOnMoreMenuBtn();
501
361
  // fire onSelect event that comes from the UnderlineNav.Item (if it is defined)
@@ -511,7 +371,7 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
511
371
  })
512
372
  })]
513
373
  })
514
- }, String(menuItem.key));
374
+ }, menuItemChildren);
515
375
  })
516
376
  })]
517
377
  })]
@@ -521,4 +381,4 @@ const UnderlineNav = /*#__PURE__*/forwardRef(({
521
381
  });
522
382
  UnderlineNav.displayName = 'UnderlineNav';
523
383
 
524
- export { UnderlineNav };
384
+ export { MORE_BTN_WIDTH, UnderlineNav, getValidChildren };
@@ -1,4 +1,13 @@
1
- export declare const UnderlineNavContext: import("react").Context<{
1
+ import type React from 'react';
2
+ export declare const UnderlineNavContext: React.Context<{
3
+ setChildrenWidth: React.Dispatch<{
4
+ text: string;
5
+ width: number;
6
+ }>;
7
+ setNoIconChildrenWidth: React.Dispatch<{
8
+ text: string;
9
+ width: number;
10
+ }>;
2
11
  loadingCounters: boolean;
3
12
  iconsVisible: boolean;
4
13
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"UnderlineNavContext.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/UnderlineNavContext.tsx"],"names":[],"mappings":"AAEA,eAAO,MAAM,mBAAmB;qBACb,OAAO;kBACV,OAAO;EAIrB,CAAA"}
1
+ {"version":3,"file":"UnderlineNavContext.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/UnderlineNavContext.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B,eAAO,MAAM,mBAAmB;sBACZ,KAAK,CAAC,QAAQ,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAC,CAAC;4BACvC,KAAK,CAAC,QAAQ,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAC,CAAC;qBACpD,OAAO;kBACV,OAAO;EAMrB,CAAA"}
@@ -1,6 +1,8 @@
1
1
  import { createContext } from 'react';
2
2
 
3
3
  const UnderlineNavContext = /*#__PURE__*/createContext({
4
+ setChildrenWidth: () => null,
5
+ setNoIconChildrenWidth: () => null,
4
6
  loadingCounters: false,
5
7
  iconsVisible: true
6
8
  });
@@ -43,7 +43,5 @@ export type UnderlineNavItemProps = {
43
43
  */
44
44
  counter?: number | string;
45
45
  } & LinkProps;
46
- declare const UnderlineNavItemImpl: PolymorphicForwardRefComponent<"a", UnderlineNavItemProps>;
47
- export declare const UnderlineNavItem: typeof UnderlineNavItemImpl;
48
- export {};
46
+ export declare const UnderlineNavItem: PolymorphicForwardRefComponent<"a", UnderlineNavItemProps>;
49
47
  //# sourceMappingURL=UnderlineNavItem.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"UnderlineNavItem.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/UnderlineNavItem.tsx"],"names":[],"mappings":"AACA,OAAO,KAAuC,MAAM,OAAO,CAAA;AAC3D,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,wBAAwB,CAAA;AACrD,OAAO,KAAK,EAAC,mBAAmB,IAAI,8BAA8B,EAAC,MAAM,sBAAsB,CAAA;AAM/F,MAAM,MAAM,SAAS,GAAG;IACtB,QAAQ,CAAC,EAAE,MAAM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CAAC,YAAY,CAAA;IAElC;;QAEI;IACJ,EAAE,CAAC,EAAE,KAAK,CAAC,WAAW,GAAG,GAAG,CAAA;IAE5B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAC1B,GAAG,SAAS,CAAA;AAEb,eAAO,MAAM,gBAAgB,EAgFxB,8BAA8B,CAAC,GAAG,EAAE,qBAAqB,CAAC,CAAA"}
@@ -1,10 +1,11 @@
1
1
  import React, { forwardRef, useRef, useContext } from 'react';
2
2
  import { UnderlineNavContext } from './UnderlineNavContext.js';
3
+ import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect.js';
3
4
  import { UnderlineItem } from '../internal/components/UnderlineTabbedInterface.js';
4
5
  import classes from './UnderlineNavItem.module.css.js';
5
6
  import { jsx } from 'react/jsx-runtime';
6
7
 
7
- const UnderlineNavItemImpl = /*#__PURE__*/forwardRef(({
8
+ const UnderlineNavItem = /*#__PURE__*/forwardRef(({
8
9
  as: Component = 'a',
9
10
  href = '#',
10
11
  children,
@@ -18,9 +19,28 @@ const UnderlineNavItemImpl = /*#__PURE__*/forwardRef(({
18
19
  const backupRef = useRef(null);
19
20
  const ref = forwardedRef !== null && forwardedRef !== void 0 ? forwardedRef : backupRef;
20
21
  const {
22
+ setChildrenWidth,
23
+ setNoIconChildrenWidth,
21
24
  loadingCounters,
22
25
  iconsVisible
23
26
  } = useContext(UnderlineNavContext);
27
+ useIsomorphicLayoutEffect(() => {
28
+ if (ref.current) {
29
+ const domRect = ref.current.getBoundingClientRect();
30
+ const icon = Array.from(ref.current.children).find(child => child.getAttribute('data-component') === 'icon');
31
+ const content = Array.from(ref.current.children).find(child => child.getAttribute('data-component') === 'text');
32
+ const text = content.textContent;
33
+ const iconWidthWithMargin = icon ? icon.getBoundingClientRect().width + Number(getComputedStyle(icon).marginRight.slice(0, -2)) + Number(getComputedStyle(icon).marginLeft.slice(0, -2)) : 0;
34
+ setChildrenWidth({
35
+ text,
36
+ width: domRect.width
37
+ });
38
+ setNoIconChildrenWidth({
39
+ text,
40
+ width: domRect.width - iconWidthWithMargin
41
+ });
42
+ }
43
+ }, [ref, setChildrenWidth, setNoIconChildrenWidth]);
24
44
  const keyDownHandler = React.useCallback(event => {
25
45
  if ((event.key === ' ' || event.key === 'Enter') && !event.defaultPrevented && typeof onSelect === 'function') {
26
46
  onSelect(event);
@@ -33,7 +53,6 @@ const UnderlineNavItemImpl = /*#__PURE__*/forwardRef(({
33
53
  }, [onSelect]);
34
54
  return /*#__PURE__*/jsx("li", {
35
55
  className: classes.UnderlineNavItem,
36
- "data-underlinenav-item": "true",
37
56
  children: /*#__PURE__*/jsx(UnderlineItem, {
38
57
  ref: ref,
39
58
  as: Component,
@@ -50,10 +69,6 @@ const UnderlineNavItemImpl = /*#__PURE__*/forwardRef(({
50
69
  })
51
70
  });
52
71
  });
53
- UnderlineNavItemImpl.displayName = 'UnderlineNavItem';
54
-
55
- // Memoized so that re-renders of UnderlineNav (e.g. when overflow state changes)
56
- // do not re-render every item when the consumer-provided children haven't changed.
57
- const UnderlineNavItem = /*#__PURE__*/React.memo(UnderlineNavItemImpl);
72
+ UnderlineNavItem.displayName = 'UnderlineNavItem';
58
73
 
59
74
  export { UnderlineNavItem };
@@ -1,4 +1,8 @@
1
- export type ChildWidthMap = Map<string, number>;
1
+ export type ChildSize = {
2
+ text: string;
3
+ width: number;
4
+ };
5
+ export type ChildWidthArray = Array<ChildSize>;
2
6
  export type ResponsiveProps = {
3
7
  items: Array<React.ReactElement<any>>;
4
8
  menuItems: Array<React.ReactElement<any>>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/types.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,aAAa,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE/C,MAAM,MAAM,eAAe,GAAG;IAE5B,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAA;IAErC,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAA;CAC1C,CAAA"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/UnderlineNav/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AACD,MAAM,MAAM,eAAe,GAAG,KAAK,CAAC,SAAS,CAAC,CAAA;AAC9C,MAAM,MAAM,eAAe,GAAG;IAE5B,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAA;IAErC,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAA;CAC1C,CAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@primer/react",
3
3
  "type": "module",
4
- "version": "0.0.0-20260523120913",
4
+ "version": "0.0.0-20260526014931",
5
5
  "description": "An implementation of GitHub's Primer Design System using React",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",