| 34 | * trigger widths from the DOM. |
| 35 | */ |
| 36 | export const useKebabMenu = <T extends TabValue>({ |
| 37 | tabs, |
| 38 | enabled, |
| 39 | isActive, |
| 40 | overflowTriggerWidth = 44, |
| 41 | }: UseKebabMenuOptions<T>): UseKebabMenuResult<T> => { |
| 42 | const containerRef = useRef<HTMLDivElement>(null); |
| 43 | // Width cache prevents oscillation when overflow tabs are not mounted. |
| 44 | const tabWidthByValueRef = useRef<Record<string, number>>({}); |
| 45 | const [overflowTabValues, setTabValues] = useState<string[]>([]); |
| 46 | |
| 47 | const recalculateOverflow = useCallback( |
| 48 | (availableWidth: number) => { |
| 49 | if (!enabled || !isActive) { |
| 50 | // Keep this update idempotent to avoid render loops. |
| 51 | setTabValues((currentValues) => { |
| 52 | if (currentValues.length === 0) { |
| 53 | return currentValues; |
| 54 | } |
| 55 | return []; |
| 56 | }); |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | const container = containerRef.current; |
| 61 | if (!container) { |
| 62 | return; |
| 63 | } |
| 64 | const tabWidthByValue = measureTabWidths({ |
| 65 | tabs, |
| 66 | container, |
| 67 | previousTabWidthByValue: tabWidthByValueRef.current, |
| 68 | }); |
| 69 | tabWidthByValueRef.current = tabWidthByValue; |
| 70 | const tabGap = getTabGap(container); |
| 71 | |
| 72 | const nextOverflowValues = calculateTabValues({ |
| 73 | tabs, |
| 74 | availableWidth, |
| 75 | tabWidthByValue, |
| 76 | overflowTriggerWidth, |
| 77 | tabGap, |
| 78 | }); |
| 79 | |
| 80 | setTabValues((currentValues) => { |
| 81 | // Avoid state updates when the computed overflow did not change. |
| 82 | if (areStringArraysEqual(currentValues, nextOverflowValues)) { |
| 83 | return currentValues; |
| 84 | } |
| 85 | return nextOverflowValues; |
| 86 | }); |
| 87 | }, |
| 88 | [enabled, isActive, overflowTriggerWidth, tabs], |
| 89 | ); |
| 90 | |
| 91 | useLayoutEffect(() => { |
| 92 | const container = containerRef.current; |
| 93 | if (!enabled || !isActive) { |