@@ -18,12 +18,10 @@ import {
1818 type MouseEvent as ReactMouseEvent ,
1919 memo ,
2020 useImperativeHandle ,
21- useEffect ,
22- useEffectEvent ,
23- useLayoutEffect ,
2421 useRef ,
2522 useState ,
2623} from "react" ;
24+ import { flushSync } from "react-dom" ;
2725
2826import { useComposerDraftStore , type DraftId } from "../composerDraftStore" ;
2927import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon" ;
@@ -465,144 +463,158 @@ function labelTextWidth(label: HTMLElement, range: Range): number {
465463 return Number . isFinite ( maxWidth ) ? Math . min ( width , maxWidth ) : width ;
466464}
467465
468- function useLabelsOverflow ( element : HTMLDivElement | null ) : boolean {
466+ function animateLabelWidths (
467+ previousRects : ReadonlyMap < HTMLElement , DOMRect > ,
468+ animations : Map < HTMLElement , Animation > ,
469+ ) {
470+ for ( const animation of animations . values ( ) ) animation . cancel ( ) ;
471+ animations . clear ( ) ;
472+ if ( window . matchMedia ( "(prefers-reduced-motion: reduce)" ) . matches ) return ;
473+
474+ for ( const [ label , previousRect ] of previousRects ) {
475+ if ( ! label . isConnected ) continue ;
476+ const nextWidth = label . getBoundingClientRect ( ) . width ;
477+ if ( Math . abs ( previousRect . width - nextWidth ) < 0.5 ) continue ;
478+
479+ const animation = label . animate (
480+ [
481+ { width : `${ previousRect . width } px` , maxWidth : `${ previousRect . width } px` } ,
482+ { width : `${ nextWidth } px` , maxWidth : `${ nextWidth } px` } ,
483+ ] ,
484+ {
485+ duration : COMPOSER_CONTEXT_MOTION_DURATION_MS ,
486+ easing : COMPOSER_CONTEXT_MOTION_EASING ,
487+ fill : "backwards" ,
488+ } ,
489+ ) ;
490+ animations . set ( label , animation ) ;
491+ animation . addEventListener (
492+ "finish" ,
493+ ( ) => {
494+ if ( animations . get ( label ) === animation ) animations . delete ( label ) ;
495+ } ,
496+ { once : true } ,
497+ ) ;
498+ }
499+ }
500+
501+ /**
502+ * Whether the strip's labels must collapse to icons. The strip is measured when
503+ * it, a control group or a hosted control resizes, when its text or children
504+ * change, and when fonts load, which covers everything the widths depend on.
505+ */
506+ function useLabelsOverflow ( ) : readonly [
507+ attach : ( element : HTMLDivElement | null ) => ( ( ) => void ) | undefined ,
508+ overflows : boolean ,
509+ ] {
469510 const [ overflows , setOverflows ] = useState ( false ) ;
470- const pendingLabelRectsRef = useRef < Map < HTMLElement , DOMRect > | null > ( null ) ;
471- const labelAnimationsRef = useRef ( new Map < HTMLElement , Animation > ( ) ) ;
472- const measure = useEffectEvent ( ( ) => {
473- const current = element ;
474- const compact = overflows ;
511+
512+ const attach = ( current : HTMLDivElement | null ) => {
475513 if ( ! current ) return ;
476- const stripWidth = current . clientWidth ;
477- if ( stripWidth === 0 ) return ;
478- const stripStyle = getComputedStyle ( current ) ;
479- const available =
480- stripWidth -
481- ( Number . parseFloat ( stripStyle . paddingInlineStart ) || 0 ) -
482- ( Number . parseFloat ( stripStyle . paddingInlineEnd ) || 0 ) ;
483- const contentWidth = ( parent : Element ) : number => {
484- const gap = Number . parseFloat ( getComputedStyle ( parent ) . columnGap ) || 0 ;
485- let width = 0 ;
486- let counted = 0 ;
487- for ( const child of parent . children ) {
514+ const labelAnimations = new Map < HTMLElement , Animation > ( ) ;
515+
516+ const measure = ( ) => {
517+ // The committed attribute, not render state, so a stale closure cannot misread it.
518+ const compact = current . hasAttribute ( "data-compact" ) ;
519+ const stripWidth = current . clientWidth ;
520+ if ( stripWidth === 0 ) return ;
521+ const stripStyle = getComputedStyle ( current ) ;
522+ const available =
523+ stripWidth -
524+ ( Number . parseFloat ( stripStyle . paddingInlineStart ) || 0 ) -
525+ ( Number . parseFloat ( stripStyle . paddingInlineEnd ) || 0 ) ;
526+ const contentWidth = ( parent : Element ) : number => {
527+ const gap = Number . parseFloat ( getComputedStyle ( parent ) . columnGap ) || 0 ;
528+ let width = 0 ;
529+ let counted = 0 ;
530+ for ( const child of parent . children ) {
531+ if ( ! ( child instanceof HTMLElement ) ) continue ;
532+ if ( child . offsetWidth === 0 ) continue ;
533+ const style = getComputedStyle ( child ) ;
534+ const position = style . position ;
535+ if ( position === "absolute" || position === "fixed" ) continue ;
536+ width +=
537+ child . offsetWidth +
538+ ( Number . parseFloat ( style . marginInlineStart ) || 0 ) +
539+ ( Number . parseFloat ( style . marginInlineEnd ) || 0 ) ;
540+ counted += 1 ;
541+ }
542+ return width + gap * Math . max ( 0 , counted - 1 ) ;
543+ } ;
544+ const stripGap = Number . parseFloat ( stripStyle . columnGap ) || 0 ;
545+ let needed = 0 ;
546+ let groups = 0 ;
547+ for ( const child of current . children ) {
488548 if ( ! ( child instanceof HTMLElement ) ) continue ;
489- if ( child . offsetWidth === 0 ) continue ;
490- const style = getComputedStyle ( child ) ;
491- const position = style . position ;
492- if ( position === "absolute" || position === "fixed" ) continue ;
493- width +=
494- child . offsetWidth +
495- ( Number . parseFloat ( style . marginInlineStart ) || 0 ) +
496- ( Number . parseFloat ( style . marginInlineEnd ) || 0 ) ;
497- counted += 1 ;
549+ // Reserve overflowed controls' width to prevent repeated hiding and expansion.
550+ const hostedControls = child . matches ( '[data-chat-resting-composer-controls-host="true"]' )
551+ ? child . querySelector < HTMLElement > ( '[data-chat-composer-resting-controls="true"]' )
552+ : null ;
553+ const hostedMeasurement = hostedControls
554+ ? measureRestingComposerControls ( hostedControls )
555+ : null ;
556+ const width = hostedMeasurement
557+ ? resolveRestingComposerControlsNaturalWidth ( hostedMeasurement )
558+ : contentWidth ( hostedControls ?? child ) ;
559+ if ( width <= 1 ) continue ;
560+ groups += 1 ;
561+ needed += width ;
498562 }
499- return width + gap * Math . max ( 0 , counted - 1 ) ;
500- } ;
501- const stripGap = Number . parseFloat ( stripStyle . columnGap ) || 0 ;
502- let needed = 0 ;
503- let groups = 0 ;
504- for ( const child of current . children ) {
505- if ( ! ( child instanceof HTMLElement ) ) continue ;
506- // Reserve overflowed controls' width to prevent repeated hiding and expansion.
507- const hostedControls = child . matches ( '[data-chat-resting-composer-controls-host="true"]' )
508- ? child . querySelector < HTMLElement > ( '[data-chat-composer-resting-controls="true"]' )
509- : null ;
510- const hostedMeasurement = hostedControls
511- ? measureRestingComposerControls ( hostedControls )
512- : null ;
513- const width = hostedMeasurement
514- ? resolveRestingComposerControlsNaturalWidth ( hostedMeasurement )
515- : contentWidth ( hostedControls ?? child ) ;
516- if ( width <= 1 ) continue ;
517- groups += 1 ;
518- needed += width ;
519- }
520- needed += stripGap * Math . max ( 0 , groups - 1 ) ;
521- const range = document . createRange ( ) ;
522- for ( const label of current . querySelectorAll < HTMLElement > ( "[data-composer-label]" ) ) {
523- needed += Math . max ( 0 , labelTextWidth ( label , range ) - label . getBoundingClientRect ( ) . width ) ;
524- }
525- const nextOverflows = resolveContextStripLabelsCompact ( {
526- compact,
527- neededWidth : needed ,
528- availableWidth : available ,
529- } ) ;
530- if ( nextOverflows !== compact ) {
531- pendingLabelRectsRef . current = new Map (
563+ needed += stripGap * Math . max ( 0 , groups - 1 ) ;
564+ const range = document . createRange ( ) ;
565+ for ( const label of current . querySelectorAll < HTMLElement > ( "[data-composer-label]" ) ) {
566+ needed += Math . max ( 0 , labelTextWidth ( label , range ) - label . getBoundingClientRect ( ) . width ) ;
567+ }
568+ const nextOverflows = resolveContextStripLabelsCompact ( {
569+ compact,
570+ neededWidth : needed ,
571+ availableWidth : available ,
572+ } ) ;
573+ if ( nextOverflows === compact ) return ;
574+ const previousRects = new Map (
532575 Array . from ( current . querySelectorAll < HTMLElement > ( COMPOSER_CONTEXT_LABEL_SELECTOR ) ) . map (
533- ( label ) => [ label , label . getBoundingClientRect ( ) ] ,
576+ ( label ) => [ label , label . getBoundingClientRect ( ) ] as const ,
534577 ) ,
535578 ) ;
536- }
537- setOverflows ( nextOverflows ) ;
538- } ) ;
539-
540- useLayoutEffect ( ( ) => {
541- const previousRects = pendingLabelRectsRef . current ;
542- if ( ! previousRects ) return ;
543- pendingLabelRectsRef . current = null ;
544-
545- for ( const animation of labelAnimationsRef . current . values ( ) ) {
546- animation . cancel ( ) ;
547- }
548- labelAnimationsRef . current . clear ( ) ;
549-
550- if ( window . matchMedia ( "(prefers-reduced-motion: reduce)" ) . matches ) return ;
551-
552- for ( const [ label , previousRect ] of previousRects ) {
553- if ( ! label . isConnected ) continue ;
554- const nextWidth = label . getBoundingClientRect ( ) . width ;
555- if ( Math . abs ( previousRect . width - nextWidth ) < 0.5 ) continue ;
579+ flushSync ( ( ) => setOverflows ( nextOverflows ) ) ;
580+ animateLabelWidths ( previousRects , labelAnimations ) ;
581+ } ;
556582
557- const animation = label . animate (
583+ let stopResize = ( ) => { } ;
584+ const observeSizes = ( ) => {
585+ stopResize ( ) ;
586+ stopResize = observeResize (
558587 [
559- { width : `${ previousRect . width } px` , maxWidth : `${ previousRect . width } px` } ,
560- { width : `${ nextWidth } px` , maxWidth : `${ nextWidth } px` } ,
588+ current ,
589+ ...Array . from ( current . children ) ,
590+ ...Array . from ( current . querySelectorAll ( "[data-chat-composer-resting-controls='true']" ) ) ,
591+ ...Array . from ( current . querySelectorAll ( COMPOSER_CONTEXT_LABEL_SELECTOR ) ) ,
561592 ] ,
562- {
563- duration : COMPOSER_CONTEXT_MOTION_DURATION_MS ,
564- easing : COMPOSER_CONTEXT_MOTION_EASING ,
565- fill : "backwards" ,
566- } ,
593+ measure ,
567594 ) ;
568- labelAnimationsRef . current . set ( label , animation ) ;
569- animation . addEventListener (
570- "finish" ,
571- ( ) => {
572- if ( labelAnimationsRef . current . get ( label ) === animation ) {
573- labelAnimationsRef . current . delete ( label ) ;
574- }
575- } ,
576- { once : true } ,
595+ } ;
596+ observeSizes ( ) ;
597+ // Text and control changes alter natural widths without resizing a hidden
598+ // or squeezed label, so they re-measure too. Only added or removed elements
599+ // can change the observed set; re-subscribing delivers a measure itself.
600+ const mutations = new MutationObserver ( ( records ) => {
601+ const elementsChanged = records . some ( ( record ) =>
602+ [ ...record . addedNodes , ...record . removedNodes ] . some ( ( node ) => node instanceof Element ) ,
577603 ) ;
578- }
579- } ) ;
580-
581- useEffect (
582- ( ) => ( ) => {
583- for ( const animation of labelAnimationsRef . current . values ( ) ) {
584- animation . cancel ( ) ;
585- }
586- } ,
587- [ ] ,
588- ) ;
589-
590- useLayoutEffect ( ( ) => {
591- // oxlint-disable-next-line react/set-state-in-effect -- The label mode comes from measuring the committed DOM, which render cannot read.
592- measure ( ) ;
593- } ) ;
594-
595- useEffect ( ( ) => {
596- if ( ! element ) return ;
597- const stopObserving = observeResize ( element , measure ) ;
604+ if ( elementsChanged ) observeSizes ( ) ;
605+ else measure ( ) ;
606+ } ) ;
607+ mutations . observe ( current , { childList : true , characterData : true , subtree : true } ) ;
598608 document . fonts . addEventListener ( "loadingdone" , measure ) ;
599609 return ( ) => {
600- stopObserving ( ) ;
610+ stopResize ( ) ;
611+ mutations . disconnect ( ) ;
601612 document . fonts . removeEventListener ( "loadingdone" , measure ) ;
613+ for ( const animation of labelAnimations . values ( ) ) animation . cancel ( ) ;
602614 } ;
603- } , [ element ] ) ;
615+ } ;
604616
605- return overflows ;
617+ return [ attach , overflows ] as const ;
606618}
607619
608620export const BranchToolbar = memo ( function BranchToolbar ( {
@@ -698,8 +710,7 @@ export const BranchToolbar = memo(function BranchToolbar({
698710 activeEnvironment : activeEnvironmentOption ,
699711 canPickEnvironment : hasMultipleEnvironments ,
700712 } ) ;
701- const [ stripElement , setStripElement ] = useState < HTMLDivElement | null > ( null ) ;
702- const labelsOverflow = useLabelsOverflow ( stripElement ) ;
713+ const [ attachStrip , labelsOverflow ] = useLabelsOverflow ( ) ;
703714
704715 if ( ! activeProject ) return null ;
705716
@@ -753,7 +764,7 @@ export const BranchToolbar = memo(function BranchToolbar({
753764
754765 return (
755766 < ComposerSurface . ContextStrip
756- ref = { setStripElement }
767+ ref = { attachStrip }
757768 data-compact = { labelsOverflow ? "" : undefined }
758769 className = { cn (
759770 "gap-1 text-xs font-normal text-foreground/70 dark:text-muted-foreground" ,
0 commit comments