The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Stabilize OverflowingList state and focus (#27847)
Raphaël Bosi2b935be33105
diff --git a/packages/twenty-docs/snippets/ui/generated/components/layout/overflowing-list.mdx b/packages/twenty-docs/snippets/ui/generated/components/layout/overflowing-list.mdxindex ad49ff12fc7..e50df329d57 100644--- a/packages/twenty-docs/snippets/ui/generated/components/layout/overflowing-list.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/layout/overflowing-list.mdx@@ -11,18 +11,49 @@* npx nx generate:ui twenty-docs*/}+<ParamField body="actionsRef" type="RefObject<PopoverRootActions | null>">+ Ref exposing the Popover close() and unmount() methods. After preventUnmountOnClose(), call unmount() when the caller-owned exit finishes.+</ParamField>+<ParamField body="children" type="ReactElement<unknown, string | JSXElementConstructor<any>>[]" required>- Complete ordered list of elements, each with a stable key.+ Complete ordered list of elements, each with a stable key. The popup contains the complete list, including items visible in the compact row.+</ParamField>++<ParamField body="defaultOpen" type="boolean" default="false">+ Initial popup visibility when uncontrolled. Defaults to false.</ParamField><ParamField body="maxInlineCount" type="number">- Maximum number of items mounted in the compact row. The popup still contains every item.+ Maximum number of items visible in the compact row. Available width can reduce this count further. The popup still contains the complete list.+</ParamField>++<ParamField body="onOpenChange" type="((open: boolean, eventDetails: PopoverRootChangeEventDetails) => void)">+ Receives the requested open state and unchanged Base UI event details, including reason, event, trigger, cancel() and preventUnmountOnClose().+</ParamField>++<ParamField body="open" type="boolean">+ Controlled popup visibility. A popup can appear only when items overflow.</ParamField><ParamField body="overflowLabel" type="string" default="Show all items">- Accessible label for the popup. The overflow button is named by its visible count followed by this label. Defaults to Show all items.+ Accessible label for the popup. The default overflow button is named by its visible count followed by this label. Defaults to Show all items.+</ParamField>++<ParamField body="popupProps" type="Omit<PopoverPopupProps, "children">">+ Popover.Popup native props, handlers, ref, render composition and focus options for the overflow content. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default.+</ParamField>++<ParamField body="ref" type="Ref<HTMLDivElement>">+ Ref forwarded to the compact row root div.</ParamField><ParamField body="showOverflowCount" type="boolean">- Shows the overflow count on hover and keyboard focus by default. Use true to show it whenever items overflow, or false to omit the trigger. An open popup stays open until it is dismissed.+ Shows the count on hover, keyboard focus or while open by default. Use true to keep it visible whenever items overflow, or false to hide the count and clip the row. An already-open popup stays open until dismissed. Empty lists and lists that fit have no trigger.+</ParamField>++<ParamField body="triggerProps" type="Omit<+ ComponentPropsWithRef<typeof Popover.Trigger>,+ 'handle' | 'payload' | 'ref'+ > & { ref?: Ref<HTMLElement> }">+ Popover.Trigger native props, handlers, ref, children and render composition for the count button. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default. Custom components must forward supplied props and ref.</ParamField>diff --git a/packages/twenty-docs/snippets/ui/generated/surfaces/dialog.mdx b/packages/twenty-docs/snippets/ui/generated/surfaces/dialog.mdxindex bdabd5d9167..892163a39cc 100644--- a/packages/twenty-docs/snippets/ui/generated/surfaces/dialog.mdx+++ b/packages/twenty-docs/snippets/ui/generated/surfaces/dialog.mdx@@ -99,7 +99,7 @@A payload to pass to the dialog when it is opened.</ParamField>-<ParamField body="Trigger.ref" type="((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (RefObject<...> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)))) | null">+<ParamField body="Trigger.ref" type="((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null">Ref to the trigger button, or the element supplied through render.</ParamField>diff --git a/packages/twenty-docs/snippets/ui/generated/surfaces/tooltip.mdx b/packages/twenty-docs/snippets/ui/generated/surfaces/tooltip.mdxindex be71e9172a3..59bee50d802 100644--- a/packages/twenty-docs/snippets/ui/generated/surfaces/tooltip.mdx+++ b/packages/twenty-docs/snippets/ui/generated/surfaces/tooltip.mdx@@ -300,7 +300,7 @@A payload to pass to the tooltip when it is opened.</ParamField>-<ParamField body="Trigger.ref" type="((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (RefObject<...> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)))) | null">+<ParamField body="Trigger.ref" type="((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null">Ref to the rendered trigger element, a button by default.</ParamField>diff --git a/packages/twenty-docs/ui/components/layout/overflowing-list.mdx b/packages/twenty-docs/ui/components/layout/overflowing-list.mdxindex 7e338e91783..0c299d6897b 100644--- a/packages/twenty-docs/ui/components/layout/overflowing-list.mdx+++ b/packages/twenty-docs/ui/components/layout/overflowing-list.mdx@@ -1,14 +1,14 @@---title: OverflowingList-description: Fit a row of items into the available space and reveal the complete list in a popup.+description: Fit a row of items into the available space and show the complete list in a popup.---import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';import OverflowingListReference from '/snippets/ui/generated/components/layout/overflowing-list.mdx';-`OverflowingList` measures its available width, keeps the fitting items in a compact row, and offers a `+N` button for the remaining items. It updates when the container or item content changes.+`OverflowingList` measures its available width, keeps fitting items in a compact row, and offers a `+N` button that opens the complete list in a popup. The count updates when the container, item content or ordered list changes. Empty lists and lists that fit have no overflow button or exposed popup.-Supply the complete ordered list as keyed elements. Your application owns each item's content, actions, and data.+Supply the complete ordered list as keyed elements. Your application owns each item's content, actions and data. The compact row remains visible when the popup opens. The popup repeats the complete list, including the items that fit in the row.```tsximport { OverflowingList } from 'twenty-ui/components/layout';@@ -39,17 +39,89 @@ export const TeamList = () => (## Count visibility-The overflow button appears on pointer hover or keyboard focus by default. Set `showOverflowCount` to `true` to keep it visible whenever items overflow. Set it to `false` only when the surrounding interface provides another way to access the complete list. A popup that is already open stays open until it is dismissed, even if `showOverflowCount` changes to `false`.+| `showOverflowCount` | Behavior when items overflow |+| ------------------- | ---------------------------------------------------------------------------- |+| Omitted | Shows the count on pointer hover, keyboard focus or while the popup is open. |+| `true` | Keeps the count visible. |+| `false` | Hides the count and clips the row. An open popup stays open until dismissed. |-## Limit inline mounting+The default mode keeps the current count visibility while an inline item is focused, so showing the count does not push that item out of the row. Focusing the count button makes the count visible.-Use `maxInlineCount` when rendering a large collection or expensive item content. This caps only the compact row. The popup receives the complete list, including items beyond the cap. It does not fetch missing items or virtualize the popup.+Use `false` when the surrounding interface provides another way to access the hidden items. Changing it to `false` hides the count without dismissing an already-open popup. `open` and `defaultOpen` can still expose the complete list when items overflow. Removing the overflow items or widening the list until everything fits closes the popup and removes the count button. The count always describes the items outside the compact row.-## Popup behavior+`maxInlineCount` caps the number of visible row items. Available width can reduce that number further. The popup still contains the complete list. It does not fetch missing items or virtualize the popup.-Enter, Space, and pointer activation open a non-modal popup with the complete list. Escape closes it and restores focus to the overflow button. Assistive technologies announce the button by its visible count followed by `overflowLabel`, for example "+3 Show all teams". An outside interaction also closes it. The popup uses the surrounding theme and supports ordinary content, links, and buttons without turning them into menu items.+## Popup state-Overflow-trigger and popup interactions do not activate a clickable field host. Each list owns its measurement and popup state independently. Native `div` attributes, styles, class names, and refs apply to the compact row.+The list owns its popup state when `open` is omitted. Use `defaultOpen` for its initial state. The default is `false`; an initially open popup still requires overflowing items.++Pass `open` and update it in `onOpenChange` to own the popup state. The callback receives the requested boolean and the installed [Popover](/ui/primitives/surfaces/popover) event details, including `reason`, `event`, `trigger`, `cancel()` and `preventUnmountOnClose()`. Calling `cancel()` prevents the requested state change. In controlled use, update your state only for changes you accept.++Pass `actionsRef` to receive the Popover `close()` and `unmount()` methods. `close()` requests closure through `onOpenChange` and respects cancellation. If your callback calls `preventUnmountOnClose()` to run a caller-owned exit, call `actionsRef.current?.unmount()` when that exit finishes. This releases the retained popup without removing the list and allows it to open again.++```tsx+import { useState } from 'react';+import { OverflowingList } from 'twenty-ui/components/layout';+import { Tag } from 'twenty-ui/primitives/data-display';+import { Button } from 'twenty-ui/primitives/input';++const TEAMS = ['Design', 'Engineering', 'Support', 'Operations'];++export const ControlledTeamList = () => {+ const [open, setOpen] = useState(false);++ return (+ <OverflowingList+ open={open}+ onOpenChange={setOpen}+ showOverflowCount+ overflowLabel="Show all teams"+ style={{ width: 220 }}+ triggerProps={{ render: <Button variant="outline" size="sm" /> }}+ >+ {TEAMS.map((team) => (+ <Tag key={team} color="blue">+ {team}+ </Tag>+ ))}+ </OverflowingList>+ );+};+```++<StoryEmbed+ storyId="ui-components-overflowinglist--controlled"+ title="Controlled state with a custom trigger"+ height={280}+/>++## Native targets and composition++Native `div` attributes, handlers, styles, class names and refs on `OverflowingList` target the compact row root. Use `triggerProps` for the count button and `popupProps` for the popup content div. Both retain their Popover part's native props, handlers, ref and element/function `render` composition.++Customize the trigger with `triggerProps.render`, as in the controlled example, or supply `triggerProps.children` to replace `+N`. Custom components must [forward the supplied props and ref](/ui/primitives/overview#custom-components). Custom popup components must also render the supplied children; OverflowingList owns the item content. `overflowLabel` defaults to "Show all items". The default button's accessible name combines its count and that label, for example "+3 Show all teams". Override `triggerProps['aria-label']` or `popupProps['aria-label']` when their content needs a different name.++`OverflowingList` stops `click`, `mousedown`, `pointerdown`, `keydown` and `keyup` propagation on the trigger and popup by default. This keeps opening the popup and interacting with its items from activating a surrounding field or picker. A handler supplied through `triggerProps` or `popupProps` replaces the default for that event. Call `event.stopPropagation()` in your handler to retain blocking, or omit it to allow that event to bubble. Other events keep their defaults. Handlers on a custom `render` element compose with the supplied props as usual.++When a popup click override allows bubbling, the installed Base UI portal can dispatch that click to a surrounding React ancestor twice with the same native event. This also occurs with a plain `Popover`. OverflowingList preserves that upstream behavior; it does not guarantee one ancestor callback per native popup event when bubbling is enabled.++## Keyboard and focus++Enter, Space and pointer activation open a non-modal popup. Escape and outside interaction dismiss it. Ordinary dismissal restores focus to the count button. Focus already on a visible inline item or an outside control is preserved. The popup supports content, links and buttons with their native keyboard behavior; it does not turn them into menu items or add menu arrow navigation.++Use `popupProps.initialFocus` and `popupProps.finalFocus` to customize opening and dismissal focus through the installed Popover contract.++Each list owns its responsive measurements independently. Unmounting one list releases its observers and leaves other lists working.++## Server rendering and hydration++Server markup includes the first `maxInlineCount` items, or all items when the cap is omitted. Width measurement and popup content become available after client mounting.++Hydration reuses the provisional row and applies responsive measurement after client mounting. Row and popup children are separate rendered instances. Keep state shared between those locations in the caller.++## Migration++The popup continues to show the complete list and uses "Show all items" by default. `showOverflowCount={false}` preserves the clipped row and hides the count. It does not dismiss an already-open popup. The trigger and popup retain their default blocking for click, mousedown, pointerdown, keydown and keyup. Override an individual handler through `triggerProps` or `popupProps` when the surrounding interface should receive that event.## Propsdiff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsxindex 5de57c10ddc..ca91050f567 100644--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx@@ -5,6 +5,7 @@ import { phoneCountryPickerTest } from '@/__stories__/twenty-ui-gallery/utils/phimport { phoneCountryPickerTriggerTest } from '@/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTriggerTest';import { breadcrumbTest } from '@/__stories__/twenty-ui-gallery/utils/breadcrumbTest';import { imageInputTest } from '@/__stories__/twenty-ui-gallery/utils/imageInputTest';+import { overflowingListApiTest } from '@/__stories__/twenty-ui-gallery/utils/overflowingListApiTest';import { overflowingListEventIsolationTest } from '@/__stories__/twenty-ui-gallery/utils/overflowingListEventIsolationTest';import { overflowingListGeometryTest } from '@/__stories__/twenty-ui-gallery/utils/overflowingListGeometryTest';import { overflowingListPopupTest } from '@/__stories__/twenty-ui-gallery/utils/overflowingListPopupTest';@@ -694,6 +695,18 @@ export const InlineBannerPreact: Story = createGalleryStory({play: inlineBannerTest,});+export const OverflowingListApiReact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-overflowing-list-api',+ runtime: 'react',+ play: overflowingListApiTest,+});++export const OverflowingListApiPreact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-overflowing-list-api',+ runtime: 'preact',+ play: overflowingListApiTest,+});+export const OverflowingListPopupReact: Story = createGalleryStory({frontComponentBundleName: 'twenty-ui-overflowing-list',runtime: 'react',diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.mdindex a1c23713e5d..2b39270c47c 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md@@ -16,6 +16,12 @@ NumberField checks locale formatting and localized paste, controlled empty valuePopover composes Portal, Positioner, Popup, Arrow and Viewport. Its focused React/Preact cases check controlled trigger requests, native attributes, Button render composition, DOM refs and callback reasons. These checks do not establish popup visibility, geometry or dismissal support. The omitted-container popup still requires C04/C05/C07 renderer acceptance.+OverflowingList keeps fitting items in its compact row and shows the complete list in its popup. The original fixture covers full popup contents and default event isolation. The `twenty-ui-overflowing-list-api` fixture exercises controlled and defaultOpen state, callback reasons and native events, cancelable Escape, root/trigger/popup refs with render composition, and public `actionsRef.close()` and `actionsRef.unmount()` in React and Preact. The deferred-close example retains the closed popup after `preventUnmountOnClose()`, releases it when the caller finishes its exit, and opens it again. The trigger and popup block click, mousedown, pointerdown, keydown and keyup by default. Each supplied handler replaces its default, so the API fixture explicitly allows trigger and popup clicks to bubble while recording their native event type. These API cases do not complete the separate C04 portal, C05 measurement/geometry, C06 scrolling or C07 dismissal acceptance. Existing OverflowingList responsive measurement and independent-instance evidence remains with C05.++In standalone React, when a popup click override allows bubbling, the installed Base UI FloatingPortal can dispatch that click to a surrounding React ancestor twice, with the same native event in both callbacks. This is reproduced by a plain Popover. OverflowingList preserves the supplied popup callback without promising one ancestor callback per native popup event when bubbling is enabled.++The SDK registers native handlers on physical elements. The API fixture overrides the default click blocking and asserts native trigger bubbling and popup callback preservation. Logical portal bubbling to a surrounding React ancestor remains a separate C04 gap in React and Preact: the diagnostic parent count reaches 1 after the trigger click and stays at 1 after the popup item click, instead of reaching 2.+Dropdown checks controlled opening, native action refs and Button render composition, disabled callback suppression, action callbacks, page navigation, option selection and click-to-close in both runtimes. The portal fixture preserves all 16 rows and checks attachment along the physical collision side, overlap with the trigger and confinement to the owner portal area. A temporary constrained long-menu probe passed End-key focus and scrolling in both runtimes: a 128px popup scrolled to 386px and kept the last item visible. Outside-host dismissal remains a C07 renderer limitation. Clicking the host action invokes that action, while Dropdown remains expanded with its popup mounted. Search, broader keyboard navigation and focus restoration are not established by these checks.Typography composition checks constrained text, explicit links, semantic elements, refs and native focus handlers in both runtimes. Overflow tooltip popup acceptance still depends on renderer portal and geometry support.@@ -68,7 +74,8 @@ effect within the interaction timeout.| `twenty-ui-list-item` | ListItemButton and ListItem (native action composition, visual rows, explicit button/link/Dropdown.ActionItem owners, refs/events/focus/keyboard, disabled behavior and sibling controls) || `twenty-ui-settings-row` | SettingsRow || `twenty-ui-tabs` | Tabs and TabButton |-| `twenty-ui-overflowing-list` | OverflowingList |+| `twenty-ui-overflowing-list` | OverflowingList (complete popup contents, compact row and default event isolation) |+| `twenty-ui-overflowing-list-api` | OverflowingList (controlled/defaultOpen state, callback details and cancellation, native refs and render composition) || `twenty-ui-phone-country-picker` | PhoneCountryPicker || `twenty-ui-currency-picker` | CurrencyPicker || `twenty-ui-progress` | Progress parts, ProgressBar, ProgressRing and MetricRow (native composition, range normalization, indeterminate values and geometry) |diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListApiExample.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListApiExample.tsxnew file mode 100644index 00000000000..a978a8a1aa4--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListApiExample.tsx@@ -0,0 +1,106 @@+import { isString } from '@sniptt/guards';+import { useRef, useState } from 'react';+import { OverflowingList } from 'twenty-ui/components/layout';+import { Button } from 'twenty-ui/primitives/input';++import { OverflowingListDeferredCloseExample } from './OverflowingListDeferredCloseExample';++export const OverflowingListApiExample = () => {+ const [isOpen, setIsOpen] = useState(false);+ const [isEscapeBlocked, setIsEscapeBlocked] = useState(true);+ const [lastChange, setLastChange] = useState('none');+ const [nativeTargets, setNativeTargets] = useState('unread');+ const [parentActivations, setParentActivations] = useState(0);+ const [lastPopupClick, setLastPopupClick] = useState('none');+ const [lastTriggerClick, setLastTriggerClick] = useState('none');+ const rootRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const popupRef = useRef<HTMLDivElement>(null);++ return (+ <>+ <div+ role="presentation"+ onClick={() => setParentActivations((count) => count + 1)}+ >+ <OverflowingList+ ref={rootRef}+ data-native-root="controlled"+ open={isOpen}+ onOpenChange={(nextOpen, details) => {+ setLastChange(+ `${nextOpen}:${details.reason}:${details.event.type}`,+ );+ setNativeTargets(+ [+ rootRef.current?.getAttribute('data-native-root'),+ triggerRef.current?.getAttribute('data-native-trigger'),+ popupRef.current?.getAttribute('data-native-popup'),+ ].join(','),+ );++ if (isEscapeBlocked && details.reason === 'escape-key') {+ details.cancel();+ return;+ }++ setIsOpen(nextOpen);+ }}+ showOverflowCount+ maxInlineCount={1}+ overflowLabel="Controlled overflow items"+ style={{ width: 300 }}+ triggerProps={{+ ref: triggerRef,+ render: <Button variant="outline" data-native-trigger="custom" />,+ 'aria-label': 'Custom overflow trigger',+ onClick: (event) => setLastTriggerClick(event.nativeEvent.type),+ }}+ popupProps={{+ ref: popupRef,+ render: <section data-native-popup="section" />,+ onClick: (event) => {+ const targetText =+ 'textContent' in event.target &&+ isString(event.target.textContent)+ ? event.target.textContent+ : '';++ setLastPopupClick(`${event.nativeEvent.type}:${targetText}`);+ },+ }}+ >+ {['Controlled Alpha', 'Controlled Bravo', 'Controlled Charlie'].map(+ (target) => (+ <Button key={target}>{target}</Button>+ ),+ )}+ </OverflowingList>+ </div>+ <Button onClick={() => setIsOpen(true)}>Open controlled overflow</Button>+ <Button onClick={() => setIsOpen(false)}>+ Close controlled overflow+ </Button>+ <Button onClick={() => setIsEscapeBlocked(false)}>+ Allow overflow Escape+ </Button>+ <OverflowingList+ defaultOpen+ showOverflowCount+ maxInlineCount={0}+ overflowLabel="Initially open overflow"+ style={{ width: 300 }}+ >+ {[<Button key="initial">Initially hidden item</Button>]}+ </OverflowingList>+ <OverflowingListDeferredCloseExample />+ <output aria-label="Overflow trigger click">{lastTriggerClick}</output>+ <output aria-label="Overflow popup click">{lastPopupClick}</output>+ <output aria-label="Overflow open changes">{lastChange}</output>+ <output aria-label="Overflow native targets">{nativeTargets}</output>+ <output aria-label="Overflow parent activations">+ {parentActivations}+ </output>+ </>+ );+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListDeferredCloseExample.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListDeferredCloseExample.tsxnew file mode 100644index 00000000000..0aef1205763--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListDeferredCloseExample.tsx@@ -0,0 +1,54 @@+import { isNull } from '@sniptt/guards';+import { type ComponentProps, useRef, useState } from 'react';+import { OverflowingList } from 'twenty-ui/components/layout';+import { Button } from 'twenty-ui/primitives/input';++type OverflowingListActions = NonNullable<+ ComponentProps<typeof OverflowingList>['actionsRef']+>['current'];++export const OverflowingListDeferredCloseExample = () => {+ const [isOpen, setIsOpen] = useState(false);+ const [lastChange, setLastChange] = useState('none');+ const [popupElement, setPopupElement] = useState<HTMLDivElement | null>(null);+ const actionsRef = useRef<OverflowingListActions>(null);++ return (+ <>+ <OverflowingList+ actionsRef={actionsRef}+ open={isOpen}+ onOpenChange={(nextOpen, details) => {+ setLastChange(`${nextOpen}:${details.reason}`);++ if (!nextOpen) {+ details.preventUnmountOnClose();+ }++ setIsOpen(nextOpen);+ }}+ showOverflowCount+ maxInlineCount={1}+ overflowLabel="Deferred overflow items"+ style={{ width: 300 }}+ popupProps={{ ref: setPopupElement }}+ >+ {[+ <Button key="alpha">Deferred Alpha</Button>,+ <Button key="bravo">Deferred Bravo</Button>,+ <Button key="close" onClick={() => actionsRef.current?.close()}>+ Close deferred overflow+ </Button>,+ ]}+ </OverflowingList>+ <Button onClick={() => setIsOpen(true)}>Open deferred overflow</Button>+ <Button onClick={() => actionsRef.current?.unmount()}>+ Complete deferred exit+ </Button>+ <output aria-label="Deferred overflow open changes">{lastChange}</output>+ <output aria-label="Deferred overflow popup mounted">+ {isNull(popupElement) ? 'unmounted' : 'mounted'}+ </output>+ </>+ );+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list-api.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list-api.front-component.tsxnew file mode 100644index 00000000000..0bf5e93ce99--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list-api.front-component.tsx@@ -0,0 +1,17 @@+import { defineFrontComponent } from 'twenty-sdk/define';++import { TwentyUiGalleryCard } from '../shared/front-components/twenty-ui-gallery-card';+import { OverflowingListApiExample } from './components/OverflowingListApiExample';++const OverflowingListApi = () => (+ <TwentyUiGalleryCard title="Overflowing list API">+ <OverflowingListApiExample />+ </TwentyUiGalleryCard>+);++export default defineFrontComponent({+ universalIdentifier: '652141f6-6f4f-4f7b-9333-8c71b2f0b84e',+ name: 'twenty-ui-overflowing-list-api',+ description: 'Controlled popup state, native composition and caller events',+ component: OverflowingListApi,+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListApiTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListApiTest.tsnew file mode 100644index 00000000000..fe37083b95b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListApiTest.ts@@ -0,0 +1,151 @@+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';++export const overflowingListApiTest: TwentyUiGalleryPlayFunction = async ({+ canvasElement,+}) => {+ const canvas = within(canvasElement);+ const page = within(canvasElement.ownerDocument.body);+ await expectFrontComponentMounted(canvas);++ const initialPopup = await page.findByRole('dialog', {+ name: 'Initially open overflow',+ });+ const initiallyHiddenItem = await within(initialPopup).findByRole('button', {+ name: 'Initially hidden item',+ });+ await expect(initiallyHiddenItem).toBeVisible();+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(initialPopup).not.toBeVisible());++ const trigger = canvas.getByRole('button', {+ name: 'Custom overflow trigger',+ });+ await expect(trigger).toHaveTextContent('+2');+ await expect(trigger).toHaveAttribute('data-native-trigger', 'custom');+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await userEvent.click(trigger);++ const popup = await page.findByRole('dialog', {+ name: 'Controlled overflow items',+ });+ await expect(popup.tagName).toBe('SECTION');+ await waitFor(() =>+ expect(canvas.getByLabelText('Overflow open changes')).toHaveTextContent(+ 'true:trigger-press:click',+ ),+ );+ await expect(+ canvas.getByLabelText('Overflow trigger click'),+ ).toHaveTextContent('click');+ await expect(+ canvas.getByLabelText('Overflow parent activations'),+ ).toHaveTextContent('1');+ await waitFor(() =>+ expect(within(popup).getAllByRole('button')).toHaveLength(3),+ );+ await userEvent.click(+ within(popup).getByRole('button', { name: 'Controlled Charlie' }),+ );+ await waitFor(() =>+ expect(canvas.getByLabelText('Overflow popup click')).toHaveTextContent(+ 'click:Controlled Charlie',+ ),+ );++ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(canvas.getByLabelText('Overflow open changes')).toHaveTextContent(+ 'false:escape-key:keydown',+ ),+ );+ await waitFor(async () => {+ await expect(popup).toBeVisible();+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await expect(within(popup).getAllByRole('button')).toHaveLength(3);++ for (const targetName of [+ 'Controlled Alpha',+ 'Controlled Bravo',+ 'Controlled Charlie',+ ]) {+ await expect(+ within(popup).getByRole('button', { name: targetName }),+ ).toBeVisible();+ }+ });+ await expect(+ canvas.getByLabelText('Overflow native targets'),+ ).toHaveTextContent('controlled,custom,section');++ await userEvent.click(+ canvas.getByRole('button', { name: 'Close controlled overflow' }),+ );+ await waitFor(() => expect(popup).not.toBeVisible());+ await userEvent.click(+ canvas.getByRole('button', { name: 'Allow overflow Escape' }),+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Open controlled overflow' }),+ );+ const externallyOpenedPopup = await page.findByRole('dialog', {+ name: 'Controlled overflow items',+ });+ await userEvent.click(+ await within(externallyOpenedPopup).findByRole('button', {+ name: 'Controlled Bravo',+ }),+ );+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(externallyOpenedPopup).not.toBeVisible());+ await waitFor(() => expect(trigger).toHaveFocus());+ await userEvent.click(+ canvas.getByRole('button', { name: 'Open deferred overflow' }),+ );+ const deferredPopup = await page.findByRole('dialog', {+ name: 'Deferred overflow items',+ });+ await waitFor(() =>+ expect(within(deferredPopup).getAllByRole('button')).toHaveLength(3),+ );+ await userEvent.click(+ within(deferredPopup).getByRole('button', {+ name: 'Close deferred overflow',+ }),+ );+ await waitFor(() => {+ expect(+ canvas.getByLabelText('Deferred overflow open changes'),+ ).toHaveTextContent('false:imperative-action');+ expect(deferredPopup).toHaveAttribute('data-closed');+ expect(+ canvas.getByLabelText('Deferred overflow popup mounted'),+ ).toHaveTextContent(/^mounted$/);+ });+ await expect(deferredPopup.isConnected).toBe(true);+ await userEvent.click(+ canvas.getByRole('button', { name: 'Complete deferred exit' }),+ );+ await waitFor(() => {+ expect(deferredPopup.isConnected).toBe(false);+ expect(+ canvas.getByLabelText('Deferred overflow popup mounted'),+ ).toHaveTextContent(/^unmounted$/);+ });+ await userEvent.click(+ canvas.getByRole('button', { name: 'Open deferred overflow' }),+ );+ const reopenedDeferredPopup = await page.findByRole('dialog', {+ name: 'Deferred overflow items',+ });+ await waitFor(() => {+ expect(reopenedDeferredPopup).toBeVisible();+ expect(within(reopenedDeferredPopup).getAllByRole('button')).toHaveLength(+ 3,+ );+ });+ expect(errorHandler).not.toHaveBeenCalled();+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListEventIsolationTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListEventIsolationTest.tsindex 8b69dac9f02..dd724412fc8 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListEventIsolationTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListEventIsolationTest.ts@@ -24,7 +24,9 @@ export const overflowingListEventIsolationTest: TwentyUiGalleryPlayFunction =trigger.focus();await userEvent.keyboard('{Enter}');- const popup = await page.findByRole('dialog', { name: 'Show all targets' });+ const popup = await page.findByRole('dialog', {+ name: 'Show all targets',+ });const lastTarget = within(popup).getByRole('button', { name: 'Delta' });await waitFor(() => expect(lastTarget).toBeVisible());expect(trigger).toHaveAttribute('aria-expanded', 'true');diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListPopupTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListPopupTest.tsindex 9e4a93e05c4..58346a574be 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListPopupTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListPopupTest.ts@@ -59,8 +59,10 @@ const expectTargetsPopupInsideLightThemePortalScope = async ({};const expectTargetsPopupListsInitialTargets = async ({+ canvasElement,reviewersTrigger,targetsPopup,+ targetsTrigger,}: OpenTargetsPopupScenario) => {const targets = within(targetsPopup);for (const targetName of INITIAL_TARGET_NAMES) {@@ -68,6 +70,18 @@ const expectTargetsPopupListsInitialTargets = async ({expect(targets.getByRole('button', { name: targetName })).toBeVisible(),);}+ await expect(targets.getAllByRole('button')).toHaveLength(4);+ for (const targetName of ['Alpha', 'Bravo']) {+ const renderedTargets = within(canvasElement).getAllByRole('button', {+ name: targetName,+ });+ await expect(renderedTargets).toHaveLength(2);++ for (const renderedTarget of renderedTargets) {+ await expect(renderedTarget).toBeVisible();+ }+ }+ await expect(targetsTrigger).toHaveTextContent('+2');await expect(reviewersTrigger).toHaveAttribute('aria-expanded', 'false');};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplay.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplay.tsxindex 8aa111aaf1f..d695db6144d 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplay.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplay.tsx@@ -2,7 +2,7 @@ import { useLingui } from '@lingui/react/macro';import { useFieldFocus } from '@/object-record/record-field/ui/hooks/useFieldFocus';import { useMultiSelectFieldDisplay } from '@/object-record/record-field/ui/meta-types/hooks/useMultiSelectFieldDisplay';import { OverflowingList } from 'twenty-ui/components/layout';-import { Tag } from 'twenty-ui/primitives/data-display';+import { MultiSelectFieldDisplayTag } from '@/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplayTag';import { isDefined } from 'twenty-shared/utils';export const MultiSelectFieldDisplay = () => {@@ -12,7 +12,7 @@ export const MultiSelectFieldDisplay = () => {const { isFocused } = useFieldFocus();- const selectedOptions = fieldValue+ const selectedOptions = isDefined(fieldValue)? fieldDefinition.metadata.options?.filter((option) =>fieldValue.includes(option.value),)@@ -26,9 +26,9 @@ export const MultiSelectFieldDisplay = () => {showOverflowCount={isFocused}>{selectedOptions.map((selectedOption, index) => (- <Tag key={index} color={selectedOption.color}>+ <MultiSelectFieldDisplayTag key={index} color={selectedOption.color}>{selectedOption.label}- </Tag>+ </MultiSelectFieldDisplayTag>))}</OverflowingList>);diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplayTag.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplayTag.tsxnew file mode 100644index 00000000000..1a843670b29--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplayTag.tsx@@ -0,0 +1,4 @@+import { memo } from 'react';+import { Tag } from 'twenty-ui/primitives/data-display';++export const MultiSelectFieldDisplayTag = memo(Tag);diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplay.perf.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplay.perf.stories.tsxindex baa4210a03c..cc8472ea1f0 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplay.perf.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplay.perf.stories.tsx@@ -1,4 +1,5 @@import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';import { useContext, useEffect } from 'react';import { FieldFocusContext } from '@/object-record/record-field/ui/contexts/FieldFocusContext';@@ -8,6 +9,9 @@ import { ComponentDecorator } from 'twenty-ui/testing';import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';import { getFieldDecorator } from '~/testing/decorators/getFieldDecorator';import { getProfilingStory } from '~/testing/profiling/utils/getProfilingStory';+import { MultiSelectFieldDisplayUpdatesExample } from './MultiSelectFieldDisplayUpdatesExample';++const OVERFLOW_TRIGGER_NAME_PATTERN = /Show all items$/;const FieldFocusEffect = () => {const { setIsFocused } = useContext(FieldFocusContext);@@ -16,7 +20,7 @@ const FieldFocusEffect = () => {setIsFocused(true);}, [setIsFocused]);- return <></>;+ return null;};const meta: Meta = {@@ -24,9 +28,9 @@ const meta: Meta = {decorators: [MemoryRouterDecorator,getFieldDecorator('company', 'workPolicy', [- 'Option 1',- 'Option 2',- 'Option 3',+ 'ON_SITE',+ 'HYBRID',+ 'REMOTE_WORK',]),ComponentDecorator,],@@ -71,3 +75,69 @@ export const Performance = getProfilingStory({numberOfRuns: 50,numberOfTestsPerRun: 100,});++export const Updates: Story = {+ render: () => (+ <FieldFocusContextProvider>+ <MultiSelectFieldDisplayUpdatesExample />+ </FieldFocusContextProvider>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await expect(canvas.getByText('On-Site')).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: OVERFLOW_TRIGGER_NAME_PATTERN }),+ ).toBeNull();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Show hybrid option' }),+ );+ await waitFor(async () => {+ await expect(canvas.getByText('Hybrid')).toBeVisible();+ await expect(canvas.queryByText('On-Site')).toBeNull();+ await expect(canvas.queryByText('Remote Work')).toBeNull();+ });++ await userEvent.click(+ canvas.getByRole('button', { name: 'Update option labels' }),+ );+ await expect(await canvas.findByText('Updated Hybrid')).toBeVisible();+ await expect(canvas.queryByText('Hybrid')).toBeNull();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Show all options' }),+ );+ await expect(await canvas.findByText('Updated On-Site')).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: OVERFLOW_TRIGGER_NAME_PATTERN }),+ ).toBeNull();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Enable overflow' }),+ );+ const trigger = await canvas.findByRole('button', {+ name: '+2 Show all items',+ });+ await userEvent.click(trigger);+ const popup = await body.findByRole('dialog', {+ name: 'Show all items',+ });+ await expect(within(popup).getByText('Updated Hybrid')).toBeVisible();+ await expect(within(popup).getByText('Updated Remote Work')).toBeVisible();+ await expect(within(popup).getByText('Updated On-Site')).toBeVisible();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Disable overflow' }),+ );+ await waitFor(async () => {+ await expect(+ body.queryByRole('dialog', { name: 'Show all items' }),+ ).toBeNull();+ await expect(+ canvas.queryByRole('button', { name: OVERFLOW_TRIGGER_NAME_PATTERN }),+ ).toBeNull();+ });+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplayUpdatesExample.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplayUpdatesExample.tsxnew file mode 100644index 00000000000..be47374fa1c--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/MultiSelectFieldDisplayUpdatesExample.tsx@@ -0,0 +1,79 @@+import { useContext, useState } from 'react';++import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';+import { useFieldFocus } from '@/object-record/record-field/ui/hooks/useFieldFocus';+import { MultiSelectFieldDisplay } from '@/object-record/record-field/ui/meta-types/display/components/MultiSelectFieldDisplay';+import { assertFieldMetadata } from '@/object-record/record-field/ui/types/guards/assertFieldMetadata';+import { isFieldMultiSelect } from '@/object-record/record-field/ui/types/guards/isFieldMultiSelect';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { Button } from 'twenty-ui/primitives/input';+import { isDefined } from 'twenty-shared/utils';+import { FieldMetadataType } from '~/generated-metadata/graphql';++export const MultiSelectFieldDisplayUpdatesExample = () => {+ const fieldContext = useContext(FieldContext);+ const { isFocused, setIsFocused } = useFieldFocus();+ const { fieldDefinition } = fieldContext;++ assertFieldMetadata(+ FieldMetadataType.MULTI_SELECT,+ isFieldMultiSelect,+ fieldDefinition,+ );+ const [options, setOptions] = useState(fieldDefinition.metadata.options);++ const setFieldValue = (values: string[]) => {+ jotaiStore.set(+ recordStoreFamilyState.atomFamily(fieldContext.recordId),+ (record) => {+ if (!isDefined(record)) {+ return record;+ }++ return { ...record, [fieldDefinition.metadata.fieldName]: values };+ },+ );+ };++ return (+ <FieldContext.Provider+ value={{+ ...fieldContext,+ fieldDefinition: {+ ...fieldDefinition,+ metadata: { ...fieldDefinition.metadata, options },+ },+ }}+ >+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>+ <Button onClick={() => setFieldValue(['HYBRID'])}>+ Show hybrid option+ </Button>+ <Button+ onClick={() => setFieldValue(options.map((option) => option.value))}+ >+ Show all options+ </Button>+ <Button+ onClick={() =>+ setOptions((currentOptions) =>+ currentOptions.map((option) => ({+ ...option,+ label: `Updated ${option.label}`,+ })),+ )+ }+ >+ Update option labels+ </Button>+ <Button onClick={() => setIsFocused(!isFocused)}>+ {isFocused ? 'Disable overflow' : 'Enable overflow'}+ </Button>+ <div style={{ width: 130 }}>+ <MultiSelectFieldDisplay />+ </div>+ </div>+ </FieldContext.Provider>+ );+};diff --git a/packages/twenty-ui/docs/overflowingListPropDescriptions.ts b/packages/twenty-ui/docs/overflowingListPropDescriptions.tsindex d3745386f32..563403b59a3 100644--- a/packages/twenty-ui/docs/overflowingListPropDescriptions.ts+++ b/packages/twenty-ui/docs/overflowingListPropDescriptions.ts@@ -3,13 +3,25 @@ import { type ComponentProps } from 'react';import { type OverflowingList } from '../src/components/layout/OverflowingList/OverflowingList';export const OVERFLOWING_LIST_PROP_DESCRIPTIONS = {- children: 'Complete ordered list of elements, each with a stable key.',+ children:+ 'Complete ordered list of elements, each with a stable key. The popup contains the complete list, including items visible in the compact row.',showOverflowCount:- 'Shows the overflow count on hover and keyboard focus by default. Use true to show it whenever items overflow, or false to omit the trigger. An open popup stays open until it is dismissed.',+ 'Shows the count on hover, keyboard focus or while open by default. Use true to keep it visible whenever items overflow, or false to hide the count and clip the row. An already-open popup stays open until dismissed. Empty lists and lists that fit have no trigger.',maxInlineCount:- 'Maximum number of items mounted in the compact row. The popup still contains every item.',+ 'Maximum number of items visible in the compact row. Available width can reduce this count further. The popup still contains the complete list.',overflowLabel:- 'Accessible label for the popup. The overflow button is named by its visible count followed by this label. Defaults to Show all items.',+ 'Accessible label for the popup. The default overflow button is named by its visible count followed by this label. Defaults to Show all items.',+ open: 'Controlled popup visibility. A popup can appear only when items overflow.',+ defaultOpen: 'Initial popup visibility when uncontrolled. Defaults to false.',+ actionsRef:+ 'Ref exposing the Popover close() and unmount() methods. After preventUnmountOnClose(), call unmount() when the caller-owned exit finishes.',+ onOpenChange:+ 'Receives the requested open state and unchanged Base UI event details, including reason, event, trigger, cancel() and preventUnmountOnClose().',+ triggerProps:+ 'Popover.Trigger native props, handlers, ref, children and render composition for the count button. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default. Custom components must forward supplied props and ref.',+ popupProps:+ 'Popover.Popup native props, handlers, ref, render composition and focus options for the overflow content. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default.',+ ref: 'Ref forwarded to the compact row root div.',} satisfies Partial<Record<keyof ComponentProps<typeof OverflowingList>, string>>;diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex 394c760ebda..1d5ec8d8ecf 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -7741,7 +7741,7 @@},{"name": "ref",- "type": "((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (RefObject<...> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)))) | null",+ "type": "((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null","required": false,"defaultValue": null,"description": "Ref to the trigger button, or the element supplied through render."@@ -9516,7 +9516,7 @@},{"name": "ref",- "type": "((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (RefObject<...> | ((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)))) | null",+ "type": "((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null","required": false,"defaultValue": null,"description": "Ref to the rendered trigger element, a button by default."@@ -11914,33 +11914,82 @@"entryPoint": "twenty-ui/components/layout","slug": "components/layout/overflowing-list","props": [+ {+ "name": "actionsRef",+ "type": "RefObject<PopoverRootActions | null>",+ "required": false,+ "defaultValue": null,+ "description": "Ref exposing the Popover close() and unmount() methods. After preventUnmountOnClose(), call unmount() when the caller-owned exit finishes."+ },{"name": "children","type": "ReactElement<unknown, string | JSXElementConstructor<any>>[]","required": true,"defaultValue": null,- "description": "Complete ordered list of elements, each with a stable key."+ "description": "Complete ordered list of elements, each with a stable key. The popup contains the complete list, including items visible in the compact row."+ },+ {+ "name": "defaultOpen",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Initial popup visibility when uncontrolled. Defaults to false."},{"name": "maxInlineCount","type": "number","required": false,"defaultValue": null,- "description": "Maximum number of items mounted in the compact row. The popup still contains every item."+ "description": "Maximum number of items visible in the compact row. Available width can reduce this count further. The popup still contains the complete list."+ },+ {+ "name": "onOpenChange",+ "type": "((open: boolean, eventDetails: PopoverRootChangeEventDetails) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Receives the requested open state and unchanged Base UI event details, including reason, event, trigger, cancel() and preventUnmountOnClose()."+ },+ {+ "name": "open",+ "type": "boolean",+ "required": false,+ "defaultValue": null,+ "description": "Controlled popup visibility. A popup can appear only when items overflow."},{"name": "overflowLabel","type": "string","required": false,"defaultValue": "Show all items",- "description": "Accessible label for the popup. The overflow button is named by its visible count followed by this label. Defaults to Show all items."+ "description": "Accessible label for the popup. The default overflow button is named by its visible count followed by this label. Defaults to Show all items."+ },+ {+ "name": "popupProps",+ "type": "Omit<PopoverPopupProps, \"children\">",+ "required": false,+ "defaultValue": null,+ "description": "Popover.Popup native props, handlers, ref, render composition and focus options for the overflow content. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default."+ },+ {+ "name": "ref",+ "type": "Ref<HTMLDivElement>",+ "required": false,+ "defaultValue": null,+ "description": "Ref forwarded to the compact row root div."},{"name": "showOverflowCount","type": "boolean","required": false,"defaultValue": null,- "description": "Shows the overflow count on hover and keyboard focus by default. Use true to show it whenever items overflow, or false to omit the trigger. An open popup stays open until it is dismissed."+ "description": "Shows the count on hover, keyboard focus or while open by default. Use true to keep it visible whenever items overflow, or false to hide the count and clip the row. An already-open popup stays open until dismissed. Empty lists and lists that fit have no trigger."+ },+ {+ "name": "triggerProps",+ "type": "Omit<\n ComponentPropsWithRef<typeof Popover.Trigger>,\n 'handle' | 'payload' | 'ref'\n > & { ref?: Ref<HTMLElement> }",+ "required": false,+ "defaultValue": null,+ "description": "Popover.Trigger native props, handlers, ref, children and render composition for the count button. Click, mousedown, pointerdown, keydown and keyup stop propagation by default. Each supplied event handler replaces its default. Custom components must forward supplied props and ref."}]},diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scssindex c05abf8f283..38949f99074 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss+++ b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss@@ -46,6 +46,10 @@}}+.popupItem {+ display: contents;+}+.trigger {@include focus-ring;diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss.d.ts b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss.d.tsindex bc80d9400b0..fb4db0f6ee0 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss.d.ts+++ b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.module.scss.d.ts@@ -4,6 +4,7 @@ export type Styles = {item: string;trigger: string;popup: string;+ popupItem: string;};declare const styles: Styles;diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsxindex 22dd6a35f3a..9de103abfcd 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx+++ b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx@@ -1,31 +1,43 @@+import { useControlled } from '@base-ui/utils/useControlled';import { useMergedRefs } from '@base-ui/utils/useMergedRefs';+import { useStableCallback } from '@base-ui/utils/useStableCallback';+import { isFunction, isUndefined } from '@sniptt/guards';import { clsx } from 'clsx';-import { type SyntheticEvent, useCallback, useState } from 'react';+import {+ type ComponentProps,+ type SyntheticEvent,+ useRef,+ useState,+} from 'react';import { Popover } from '@ui/primitives/surfaces/Popover/Popover';import { isDefined } from '@ui/utilities/utils/isDefined';import styles from './OverflowingList.module.scss';+import { OverflowingListPopupTarget } from './internal/OverflowingListPopupTarget';import { OverflowingListItem } from './internal/OverflowingListItem';+import { OverflowingListLayoutEffect } from './internal/OverflowingListLayoutEffect';import { useOverflowingListLayout } from './internal/useOverflowingListLayout';-import { useFocusedElementUnmountRef } from './internal/useFocusedElementUnmountRef';+import { useOverflowingListFocus } from './internal/useOverflowingListFocus';import { type OverflowingListProps } from './types/OverflowingListProps';-const stopPropagation = (event: SyntheticEvent) => event.stopPropagation();+type PopoverActions = NonNullable<+ ComponentProps<typeof Popover.Root>['actionsRef']+>['current'];-const STOP_PROPAGATION_PROPS = {- onClick: stopPropagation,- onMouseDown: stopPropagation,- onPointerDown: stopPropagation,- onKeyDown: stopPropagation,- onKeyUp: stopPropagation,-};+const stopPropagation = (event: SyntheticEvent) => event.stopPropagation();export const OverflowingList = ({children,showOverflowCount,maxInlineCount,overflowLabel = 'Show all items',+ open,+ defaultOpen = false,+ onOpenChange,+ actionsRef,+ triggerProps,+ popupProps,className,onMouseEnter,onMouseLeave,@@ -35,127 +47,211 @@ export const OverflowingList = ({...props}: OverflowingListProps) => {const [isHovered, setIsHovered] = useState(false);- const [hasFocus, setHasFocus] = useState(false);- const [isOpen, setIsOpen] = useState(false);- const [focusedItemCountVisibility, setFocusedItemCountVisibility] =- useState<boolean>();- const isCountVisible =- showOverflowCount ??- focusedItemCountVisibility ??- (isHovered || hasFocus || isOpen);+ const [popup, setPopup] = useState<HTMLDivElement | null>(null);+ const [isOpen, setIsOpen] = useControlled({+ controlled: open,+ default: defaultOpen,+ name: 'OverflowingList',+ state: 'open',+ });+ const internalActionsRef = useRef<PopoverActions>(null);+ const popoverActionsRef = actionsRef ?? internalActionsRef;const inlineItemCount =isDefined(maxInlineCount) && Number.isFinite(maxInlineCount)? Math.min(children.length, Math.max(0, Math.floor(maxInlineCount))): children.length;+ const {+ containerRef,+ itemsRef,+ triggerRef,+ visibleItemCount,+ hasOverflow,+ updateLayout,+ } = useOverflowingListLayout({+ itemCount: children.length,+ inlineItemCount,+ });+ const canExpand = hasOverflow && (isOpen || showOverflowCount !== false);+ const isPopupOpen = isOpen && canExpand;+ const {+ hasFocus,+ isCountVisible,+ restoreItemFocus,+ schedulePopupFocusRestoration,+ resetFocusWhenFocusedTriggerUnmounts,+ handleFocusCapture,+ handleBlurCapture,+ } = useOverflowingListFocus({+ containerRef,+ itemsRef,+ triggerRef,+ popup,+ itemCount: children.length,+ canExpand,+ isPopupOpen,+ isOpen,+ isHovered,+ showOverflowCount,+ onFocusCapture,+ onBlurCapture,+ });const isMeasurementEnabled =- showOverflowCount ?? (isHovered || hasFocus || isOpen);- const { containerRef, itemsRef, triggerRef, visibleItemCount, hasOverflow } =- useOverflowingListLayout({- itemCount: children.length,- inlineItemCount,- reserveCountSpace: isCountVisible,- isMeasurementEnabled,- });- const resetFocusState = useCallback(() => {- setHasFocus(false);- setFocusedItemCountVisibility(undefined);- }, []);- const resetFocusWhenFocusedTriggerUnmounts =- useFocusedElementUnmountRef(resetFocusState);+ (showOverflowCount ?? (isHovered || hasFocus)) || isOpen;const mergedRef = useMergedRefs(containerRef, ref);const mergedTriggerRef = useMergedRefs(triggerRef,resetFocusWhenFocusedTriggerUnmounts,+ triggerProps?.ref,);- const displayedItemCount = isMeasurementEnabled- ? visibleItemCount- : inlineItemCount;+ const mergedPopupRef = useMergedRefs(setPopup, popupProps?.ref);+ const displayedItemCount =+ isMeasurementEnabled && showOverflowCount !== false+ ? visibleItemCount+ : inlineItemCount;const hiddenItemCount = children.length - visibleItemCount;- const canExpand = hasOverflow && (isOpen || showOverflowCount !== false);- if (isOpen && !canExpand) {- setIsOpen(false);- }+ const closeUnavailableOverflow = useStableCallback(() => {+ popoverActionsRef.current?.close();+ });return (- <div- {...props}- ref={mergedRef}- className={clsx(styles.root, className)}- onMouseEnter={(event) => {- setIsHovered(true);- onMouseEnter?.(event);- }}- onMouseLeave={(event) => {- setIsHovered(false);- onMouseLeave?.(event);- }}- onFocusCapture={(event) => {- setHasFocus(true);-- if (itemsRef.current?.contains(event.target)) {- setFocusedItemCountVisibility(- (currentVisibility) => currentVisibility ?? isCountVisible,- );- }-- onFocusCapture?.(event);- }}- onBlurCapture={(event) => {- setHasFocus(event.currentTarget.contains(event.relatedTarget));-- if (!itemsRef.current?.contains(event.relatedTarget)) {- setFocusedItemCountVisibility(undefined);- }+ <>+ <div+ {...props}+ ref={mergedRef}+ tabIndex={props.tabIndex ?? -1}+ className={clsx(styles.root, className)}+ onMouseEnter={(event) => {+ setIsHovered(true);+ onMouseEnter?.(event);+ }}+ onMouseLeave={(event) => {+ setIsHovered(false);+ onMouseLeave?.(event);+ }}+ onFocusCapture={handleFocusCapture}+ onBlurCapture={handleBlurCapture}+ >+ <div ref={itemsRef} className={styles.items}>+ {children.slice(0, inlineItemCount).map((child, index) => (+ <OverflowingListItem+ key={child.key ?? index}+ index={index}+ isHidden={index >= displayedItemCount}+ isLastVisible={+ showOverflowCount !== false && index === displayedItemCount - 1+ }+ isInPopup={false}+ onFocusLost={restoreItemFocus}+ >+ {child}+ </OverflowingListItem>+ ))}+ </div>+ {(canExpand || isOpen) && (+ <Popover.Root+ open={isPopupOpen}+ actionsRef={popoverActionsRef}+ onOpenChange={(nextOpen, eventDetails) => {+ onOpenChange?.(nextOpen, eventDetails);- onBlurCapture?.(event);- }}- >- <div ref={itemsRef} className={styles.items}>- {children.slice(0, inlineItemCount).map((child, index) => (- <OverflowingListItem- key={child.key ?? index}- isHidden={index >= displayedItemCount}- isLastVisible={- showOverflowCount !== false && index === displayedItemCount - 1- }- onFocusedItemUnmount={resetFocusState}- >- {child}- </OverflowingListItem>- ))}- </div>- {canExpand && (- <Popover.Root open={isOpen} onOpenChange={setIsOpen}>- <Popover.Trigger- ref={mergedTriggerRef}- type="button"- className={styles.trigger}- data-visible={isCountVisible || undefined}- aria-label={`+${hiddenItemCount} ${overflowLabel}`}- {...STOP_PROPAGATION_PROPS}+ if (!eventDetails.isCanceled) {+ setIsOpen(nextOpen);+ }+ }}>- +{hiddenItemCount}- </Popover.Trigger>- <Popover.Portal>- <Popover.Positioner- anchor={containerRef}- align="start"- sideOffset={-9}- alignOffset={-7}- >- <Popover.Popup- aria-label={overflowLabel}- className={styles.popup}- data-overflowing-list-popup=""- {...STOP_PROPAGATION_PROPS}+ {canExpand && (+ <Popover.Trigger+ type="button"+ aria-label={`+${hiddenItemCount} ${overflowLabel}`}+ {...triggerProps}+ onClick={triggerProps?.onClick ?? stopPropagation}+ onMouseDown={triggerProps?.onMouseDown ?? stopPropagation}+ onPointerDown={triggerProps?.onPointerDown ?? stopPropagation}+ onKeyDown={triggerProps?.onKeyDown ?? stopPropagation}+ onKeyUp={triggerProps?.onKeyUp ?? stopPropagation}+ ref={mergedTriggerRef}+ className={(state) =>+ clsx(+ styles.trigger,+ isFunction(triggerProps?.className)+ ? triggerProps.className(state)+ : triggerProps?.className,+ )+ }+ data-visible={isCountVisible || undefined}>- {children}- </Popover.Popup>- </Popover.Positioner>- </Popover.Portal>- </Popover.Root>- )}- </div>+ {isUndefined(triggerProps?.children)+ ? `+${hiddenItemCount}`+ : triggerProps.children}+ </Popover.Trigger>+ )}+ <Popover.Portal>+ <Popover.Positioner+ anchor={containerRef}+ align="start"+ sideOffset={-9}+ alignOffset={-7}+ >+ <Popover.Popup+ aria-label={overflowLabel}+ {...popupProps}+ onClick={popupProps?.onClick ?? stopPropagation}+ onMouseDown={popupProps?.onMouseDown ?? stopPropagation}+ onPointerDown={popupProps?.onPointerDown ?? stopPropagation}+ onKeyDown={popupProps?.onKeyDown ?? stopPropagation}+ onKeyUp={popupProps?.onKeyUp ?? stopPropagation}+ ref={mergedPopupRef}+ render={(renderProps, state) => (+ <OverflowingListPopupTarget+ props={renderProps}+ state={state}+ render={popupProps?.render}+ />+ )}+ finalFocus={+ popupProps?.finalFocus ?? schedulePopupFocusRestoration+ }+ className={(state) =>+ clsx(+ styles.popup,+ isFunction(popupProps?.className)+ ? popupProps.className(state)+ : popupProps?.className,+ )+ }+ data-overflowing-list-popup=""+ >+ {children.map((child, index) => (+ <OverflowingListItem+ key={child.key ?? index}+ index={index}+ isHidden={false}+ isLastVisible={false}+ isInPopup+ onFocusLost={restoreItemFocus}+ >+ {child}+ </OverflowingListItem>+ ))}+ </Popover.Popup>+ </Popover.Positioner>+ </Popover.Portal>+ </Popover.Root>+ )}+ </div>+ <OverflowingListLayoutEffect+ containerRef={containerRef}+ itemsRef={itemsRef}+ triggerRef={triggerRef}+ itemCount={children.length}+ inlineItemCount={inlineItemCount}+ reserveCountSpace={isCountVisible}+ isMeasurementEnabled={isMeasurementEnabled}+ isOpen={isOpen}+ onLayoutChange={updateLayout}+ onOverflowUnavailable={closeUnavailableOverflow}+ />+ </>);};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.interactions.stories.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.interactions.stories.tsxindex d55fc83dfe7..36971b7cf64 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.interactions.stories.tsx+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.interactions.stories.tsx@@ -1,5 +1,13 @@import { type Meta, type StoryObj } from '@storybook/react-vite';-import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { createRef, StrictMode } from 'react';+import {+ expect,+ fireEvent,+ fn,+ userEvent,+ waitFor,+ within,+} from 'storybook/test';import { Tag } from '@ui/primitives/data-display/Tag/Tag';import { Button } from '@ui/primitives/input/Button/Button';@@ -10,16 +18,49 @@ import { ThemeProvider } from '@ui/theme/ThemeProvider';import { isDefined } from '@ui/utilities/utils/isDefined';import { OverflowingList } from '../OverflowingList';+import { type OverflowingListProps } from '../types/OverflowingListProps';import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';+import { OverflowingListEventBlockingExample } from './OverflowingListEventBlockingExample';+import { OverflowingListActionsExample } from './OverflowingListActionsExample';+import { OverflowingListCanceledCloseExample } from './OverflowingListCanceledCloseExample';+import { OverflowingListControlledExample } from './OverflowingListControlledExample';+import { OverflowingListControlledStateExample } from './OverflowingListControlledStateExample';+import { OverflowingListDisabledTriggerFocusExample } from './OverflowingListDisabledTriggerFocusExample';+import { OverflowingListInstanceCleanupExample } from './OverflowingListInstanceCleanupExample';+import { OverflowingListTriggerRefExample } from './OverflowingListTriggerRefExample';import { OverflowingListControlledFocusExample } from './OverflowingListControlledFocusExample';import { OverflowingListMutableTag } from './OverflowingListMutableTag';+import { OverflowingListFocusExample } from './OverflowingListFocusExample';+import { OverflowingListStateExample } from './OverflowingListStateExample';import { OverflowingListResizeExample } from './OverflowingListResizeExample';import { expectOverflowingListPopupGeometry } from './expectOverflowingListPopupGeometry';+const onEventHost = fn();+const onEventOverride = fn();const onHostClick = fn();const onHostMouseDown = fn();const onHostKeyDown = fn();const onItemClick = fn();+const onRootClick = fn();+const onTriggerClick = fn();+const onPopupClick = fn();+const onPopupRenderClick = fn();+const onPopupRenderKeyDown = fn();+const onOpenChange = fn<NonNullable<OverflowingListProps['onOpenChange']>>();+const onCanceledOpenChange = fn<+ NonNullable<OverflowingListProps['onOpenChange']>+>((_open, details) => details.cancel());+const onCancelableOpenChange = fn<+ NonNullable<OverflowingListProps['onOpenChange']>+>((_open, details) => {+ if (details.reason === 'escape-key') {+ details.cancel();+ }+});+const rootRef = createRef<HTMLDivElement>();+const triggerRef = createRef<HTMLElement>();+const popupRef = createRef<HTMLDivElement>();+const popupRenderRef = createRef<HTMLElement>();const meta: Meta<typeof OverflowingList> = {id: 'ui-components-overflowinglist-interactions',@@ -37,10 +78,20 @@ const meta: Meta<typeof OverflowingList> = {style: { width: 180, alignSelf: 'center' },},beforeEach: () => {+ onEventHost.mockClear();+ onEventOverride.mockClear();onHostClick.mockClear();onHostMouseDown.mockClear();onHostKeyDown.mockClear();onItemClick.mockClear();+ onRootClick.mockClear();+ onTriggerClick.mockClear();+ onPopupClick.mockClear();+ onPopupRenderClick.mockClear();+ onPopupRenderKeyDown.mockClear();+ onOpenChange.mockClear();+ onCanceledOpenChange.mockClear();+ onCancelableOpenChange.mockClear();},};@@ -48,6 +99,7 @@ export default meta;type Story = StoryObj<typeof OverflowingList>;export const Keyboard: Story = {+ args: { onOpenChange },play: async ({ canvasElement, step }) => {const canvas = within(canvasElement);const body = within(canvasElement.ownerDocument.body);@@ -66,6 +118,15 @@ export const Keyboard: Story = {});await waitFor(() => expect(dialog).toHaveFocus());await expectOverflowingListPopupGeometry({ trigger, dialog });+ expect(onOpenChange).toHaveBeenLastCalledWith(+ true,+ expect.objectContaining({+ reason: 'trigger-press',+ trigger,+ event: expect.objectContaining({ type: 'click' }),+ cancel: expect.anything(),+ }),+ );expect(trigger).toHaveAttribute('aria-expanded', 'true');expect(trigger).toHaveAttribute('aria-controls', dialog.id);expect(canvasElement).not.toContainElement(dialog);@@ -76,6 +137,13 @@ export const Keyboard: Story = {);await waitFor(() => expect(trigger).toHaveFocus());expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(onOpenChange).toHaveBeenLastCalledWith(+ false,+ expect.objectContaining({+ reason: 'escape-key',+ event: expect.objectContaining({ type: 'keydown' }),+ }),+ );});}},@@ -96,6 +164,8 @@ export const CompleteListWithInlineCap: Story = {name: /Show all items$/,});+ const inlineCustomer = canvas.getByText('Customer');+expect(trigger).toHaveTextContent('+3');expect(trigger).toHaveAccessibleName('+3 Show all items');expect(canvas.queryByText('Renewal')).not.toBeInTheDocument();@@ -104,6 +174,10 @@ export const CompleteListWithInlineCap: Story = {name: 'Show all items',});+ expect(canvas.getByText('Customer')).toBe(inlineCustomer);+ expect(inlineCustomer).toBeVisible();+ expect(canvas.queryByText('Renewal')).not.toBeInTheDocument();+ expect(trigger).toHaveTextContent('+3');for (const label of ['Customer', 'Partner', 'Priority', 'Renewal']) {await waitFor(() =>expect(within(dialog).getByText(label)).toBeVisible(),@@ -218,6 +292,7 @@ export const CountDisabled: Story = {0,);}+ expect(canvas.getByText('Third item').closest('[inert]')).toBeNull();},};@@ -284,29 +359,31 @@ export const ControlledCountWhileFocused: Story = {},};-export const OpenPopupOutlivesHiddenCount: Story = {+export const CountDisabledWhilePopupOpen: Story = {render: () => <OverflowingListControlledFocusExample />,play: async ({ canvasElement }) => {const canvas = within(canvasElement);const body = within(canvasElement.ownerDocument.body);+ const toggle = canvas.getByRole('button', { name: 'Toggle count' });- await userEvent.click(canvas.getByRole('button', { name: 'Toggle count' }));- await userEvent.click(- await canvas.findByRole('button', { name: /Show all items$/ }),- );+ await userEvent.click(toggle);+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });+ await userEvent.click(trigger);const dialog = await body.findByRole('dialog', {name: 'Show all items',});- const popupToggle = within(dialog).getByRole('button', {- name: 'Toggle count',- });-- await userEvent.click(popupToggle);- await waitFor(() =>- expect(popupToggle).toHaveAttribute('aria-pressed', 'false'),+ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Toggle count' }),);- expect(dialog).toBeVisible();-+ await waitFor(() => expect(dialog).toBeVisible());+ expect(toggle).toHaveAttribute('aria-pressed', 'false');+ expect(trigger).toBeInTheDocument();+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ for (const label of ['Toggle count', 'Second item', 'Third item']) {+ expect(within(dialog).getByText(label)).toBeVisible();+ }await userEvent.keyboard('{Escape}');await waitFor(() =>expect(body.queryByRole('dialog')).not.toBeInTheDocument(),@@ -349,11 +426,12 @@ export const FocusedTriggerRemoval: Story = {const restoredTrigger = await canvas.findByRole('button', {name: /Show all items$/,});+ await waitFor(() => expect(list).toHaveFocus());await waitFor(() => expect(restoredTrigger).toHaveStyle({ opacity: '1' }));},};-export const ClickableFieldHost: Story = {+export const NativeCompositionAndPropagation: Story = {args: { maxInlineCount: 1 },render: (args) => (<div@@ -363,7 +441,33 @@ export const ClickableFieldHost: Story = {onMouseDown={onHostMouseDown}onKeyDown={onHostKeyDown}>- <OverflowingList {...args}>+ <OverflowingList+ {...args}+ ref={rootRef}+ title="Native list root"+ onClick={onRootClick}+ triggerProps={{+ ref: triggerRef,+ render: <Button title="Composed trigger" />,+ children: 'More items',+ onClick: onTriggerClick,+ }}+ popupProps={{+ ref: popupRef,+ render: (+ <section+ ref={popupRenderRef}+ role="dialog"+ title="Composed popup"+ onClick={onPopupRenderClick}+ onKeyDown={onPopupRenderKeyDown}+ >+ <Button>Caller popup content</Button>+ </section>+ ),+ onClick: onPopupClick,+ }}+ >{['First item', 'Second item', 'Third item'].map((label) => (<Button key={label} onClick={onItemClick} style={{ width: 100 }}>{label}@@ -379,15 +483,53 @@ export const ClickableFieldHost: Story = {name: /Show all items$/,});+ expect(rootRef.current).toHaveAttribute('title', 'Native list root');+ expect(triggerRef.current).toBe(trigger);+ expect(trigger).toHaveAttribute('title', 'Composed trigger');+ expect(trigger).toHaveTextContent('More items');+ await userEvent.click(canvas.getByRole('button', { name: 'First item' }));+ await userEvent.keyboard('a');+ expect(onPopupRenderKeyDown).not.toHaveBeenCalled();+ expect(onPopupClick).not.toHaveBeenCalled();+ expect(onPopupRenderClick).not.toHaveBeenCalled();+ onItemClick.mockClear();+ onHostMouseDown.mockClear();+ onHostKeyDown.mockClear();await userEvent.click(trigger);const dialog = await body.findByRole('dialog', {name: 'Show all items',});- await userEvent.click(- within(dialog).getByRole('button', { name: 'Third item' }),- );+ expect(popupRef.current).toBe(dialog);+ expect(popupRenderRef.current).toBe(dialog);+ expect(dialog.tagName).toBe('SECTION');+ expect(dialog).toHaveAttribute('title', 'Composed popup');+ expect(+ within(dialog).queryByRole('button', { name: 'Caller popup content' }),+ ).not.toBeInTheDocument();+ const thirdItem = within(dialog).getByRole('button', {+ name: 'Third item',+ });+ await userEvent.click(thirdItem);expect(onItemClick).toHaveBeenCalledOnce();+ expect(onTriggerClick).toHaveBeenCalledWith(+ expect.objectContaining({ target: trigger }),+ );+ expect(onPopupClick).toHaveBeenCalledWith(+ expect.objectContaining({ target: thirdItem }),+ );+ expect(onPopupRenderClick).toHaveBeenCalledWith(+ expect.objectContaining({ target: thirdItem }),+ );+ expect(onRootClick).toHaveBeenCalledWith(+ expect.objectContaining({ target: thirdItem }),+ );+ expect(onHostClick).toHaveBeenCalledWith(+ expect.objectContaining({ target: thirdItem }),+ );await userEvent.keyboard('{Escape}');+ expect(onPopupRenderKeyDown).toHaveBeenCalledWith(+ expect.objectContaining({ key: 'Escape', target: thirdItem }),+ );await waitFor(() => expect(trigger).toHaveFocus());await userEvent.keyboard('{Enter}');await body.findByRole('dialog', { name: 'Show all items' });@@ -396,12 +538,91 @@ export const ClickableFieldHost: Story = {expect(body.queryByRole('dialog')).not.toBeInTheDocument(),);- expect(onHostClick).not.toHaveBeenCalled();+ expect(onHostClick).toHaveBeenCalled();expect(onHostMouseDown).not.toHaveBeenCalled();expect(onHostKeyDown).not.toHaveBeenCalled();},};+export const DefaultEventBlockingAndOverrides: Story = {+ render: () => (+ <OverflowingListEventBlockingExample+ onHostEvent={onEventHost}+ onOverrideEvent={onEventOverride}+ />+ ),+ play: async ({ canvasElement, step }) => {+ const canvas = within(canvasElement);+ const document = canvasElement.ownerDocument;+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });+ const dialog = await within(document.body).findByRole('dialog', {+ name: 'Show all items',+ });+ const onDocumentMouseDown = fn();+ const eventNames = [+ 'click',+ 'mouseDown',+ 'pointerDown',+ 'keyDown',+ 'keyUp',+ ] as const;++ await waitFor(() => expect(dialog).toBeVisible());+ document.addEventListener('mousedown', onDocumentMouseDown);++ try {+ for (const overrideEvent of [undefined, ...eventNames]) {+ await userEvent.click(+ canvas.getByRole('button', {+ name: isDefined(overrideEvent)+ ? `Allow ${overrideEvent}`+ : 'Default blocking',+ }),+ );++ for (const target of [trigger, dialog]) {+ for (const eventName of eventNames) {+ await step(+ `${target === trigger ? 'Trigger' : 'Popup'} ${eventName} with ${overrideEvent ?? 'default'} blocking`,+ async () => {+ onEventHost.mockClear();+ onEventOverride.mockClear();+ onDocumentMouseDown.mockClear();+ await fireEvent[eventName](target, { key: 'a' });++ if (eventName === overrideEvent) {+ expect(onEventOverride).toHaveBeenCalledWith(+ expect.objectContaining({ target }),+ );+ expect(onEventHost).toHaveBeenCalledWith(+ expect.objectContaining({ target }),+ );++ if (eventName === 'mouseDown') {+ expect(onDocumentMouseDown).toHaveBeenCalledWith(+ expect.objectContaining({ target }),+ );+ }++ return;+ }++ expect(onEventOverride).not.toHaveBeenCalled();+ expect(onEventHost).not.toHaveBeenCalled();+ expect(onDocumentMouseDown).not.toHaveBeenCalled();+ },+ );+ }+ }+ }+ } finally {+ document.removeEventListener('mousedown', onDocumentMouseDown);+ }+ },+};+export const IndependentInstances: Story = {render: (args) => (<>@@ -420,12 +641,16 @@ export const IndependentInstances: Story = {});await userEvent.click(companyTrigger);- await body.findByRole('dialog', { name: 'Show company tags' });+ const companyDialog = await body.findByRole('dialog', {+ name: 'Show company tags',+ });+ await waitFor(() => expect(companyDialog).toHaveFocus());expect(personTrigger).toHaveAttribute('aria-expanded', 'false');await userEvent.click(personTrigger);const personDialog = await body.findByRole('dialog', {name: 'Show person tags',});+ await waitFor(() => expect(personDialog).toHaveFocus());await waitFor(() =>expect(body.queryByRole('dialog', { name: 'Show company tags' }),@@ -471,7 +696,9 @@ export const ScopedThemeAndDirection: Story = {await waitFor(() => expect(dialog).toBeVisible());await expectOverflowingListPopupGeometry({- trigger: within(scope).getByRole('button', { name: /Show all items$/ }),+ trigger: within(scope).getByRole('button', {+ name: /Show all items$/,+ }),dialog,});expect(getComputedStyle(dialog).direction).toBe('rtl');@@ -583,3 +810,597 @@ export const DescendantContentUpdates: Story = {);},};++export const StatefulRowAndPopupAcrossResize: Story = {+ render: () => <OverflowingListStateExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const list = canvas.getByLabelText('Stateful values');+ const firstInlineValue = canvas.getByRole('textbox', {+ name: 'First value',+ });++ await userEvent.type(firstInlineValue, 'Inline value');+ await userEvent.click(+ await canvas.findByRole('button', { name: '+1 Show all items' }),+ );+ const dialog = await body.findByRole('dialog');+ const firstPopupValue = within(dialog).getByRole('textbox', {+ name: 'First value',+ });+ const secondPopupValue = within(dialog).getByRole('textbox', {+ name: 'Second value',+ });++ expect(canvas.getByRole('textbox', { name: 'First value' })).toBe(+ firstInlineValue,+ );+ expect(firstInlineValue).toHaveValue('Inline value');+ expect(firstInlineValue).toBeVisible();+ expect(firstPopupValue).not.toBe(firstInlineValue);+ expect(firstPopupValue).toHaveValue('');+ await userEvent.type(secondPopupValue, 'Popup value');+ const identifiers = [+ ...list.querySelectorAll('[id]'),+ ...dialog.querySelectorAll('[id]'),+ ].map((element) => element.id);+ expect(new Set(identifiers).size).toBe(identifiers.length);+ list.style.width = '320px';+ const secondInlineValue = await canvas.findByRole('textbox', {+ name: 'Second value',+ });++ expect(secondInlineValue).not.toBe(secondPopupValue);+ expect(secondInlineValue).toHaveValue('');+ expect(secondPopupValue).toHaveValue('Popup value');+ expect(secondPopupValue).toHaveFocus();+ expect(firstInlineValue).toHaveValue('Inline value');+ list.style.width = '100px';+ await waitFor(() =>+ expect(+ canvas.queryByRole('textbox', { name: 'Second value' }),+ ).not.toBeInTheDocument(),+ );+ expect(secondPopupValue).toHaveFocus();+ expect(secondPopupValue).toHaveValue('Popup value');+ list.style.width = '800px';+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ expect(firstInlineValue).toHaveValue('Inline value');+ expect(canvas.getByRole('textbox', { name: 'Second value' })).toBe(+ secondInlineValue,+ );+ expect(secondInlineValue).toHaveValue('');+ expect(+ canvas.queryByRole('button', { name: /Show all items/ }),+ ).not.toBeInTheDocument();+ },+};++export const FocusedItemRemoval: Story = {+ render: () => <OverflowingListFocusExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ await canvas.findByRole('button', { name: '+2 Show all items' }),+ );+ const dialog = await body.findByRole('dialog');+ const secondItem = within(dialog).getByRole('button', {+ name: 'Second item',+ });++ await userEvent.click(secondItem);+ expect(+ body.queryByRole('button', { name: 'Second item', hidden: true }),+ ).not.toBeInTheDocument();+ await waitFor(() =>+ expect(+ within(dialog).getByRole('button', { name: 'Third item' }),+ ).toHaveFocus(),+ );+ expect(+ canvas.getByRole('button', { name: '+1 Show all items' }),+ ).toBeVisible();+ await userEvent.keyboard('{Enter}');+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ expect(canvas.getByRole('button', { name: 'First item' })).toHaveFocus();+ },+};++export const ControlledKeyboardAndComposedTrigger: Story = {+ render: () => <OverflowingListControlledExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: /Show all company tags$/,+ });++ await userEvent.tab();+ expect(trigger).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ const dialog = await body.findByRole('dialog', {+ name: 'Show all company tags',+ });+ await waitFor(() => expect(dialog).toHaveFocus());+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ await waitFor(() => expect(trigger).toHaveFocus());+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ },+};++export const FocusedInlineItemBecomesOverflow: Story = {+ args: {+ 'aria-label': 'Responsive focused items',+ style: { width: 250 },+ children: ['First item', 'Second item', 'Third item'].map((label) => (+ <Button key={label} style={{ width: 100 }}>+ {label}+ </Button>+ )),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const list = canvas.getByLabelText('Responsive focused items');+ const firstItem = canvas.getByRole('button', { name: 'First item' });+ const secondItem = canvas.getByRole('button', { name: 'Second item' });++ await userEvent.tab();+ expect(firstItem).toHaveFocus();+ await userEvent.tab();+ expect(secondItem).toHaveFocus();+ list.style.width = '100px';+ await waitFor(() => expect(firstItem).toHaveFocus());+ expect(secondItem.closest('[inert]')).not.toBeNull();+ expect(+ canvas.getByRole('button', { name: '+2 Show all items' }),+ ).toBeVisible();+ },+};++export const ControlledRequests: Story = {+ render: () => <OverflowingListControlledStateExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: '+2 Show all items',+ });+ const apply = canvas.getByRole('button', { name: 'Apply requested state' });++ await userEvent.click(trigger);+ expect(canvas.getByRole('status')).toHaveTextContent('Open requested');+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ await userEvent.click(apply);+ const dialog = await body.findByRole('dialog');+ await waitFor(() => expect(dialog).toBeVisible());+ await userEvent.keyboard('{Escape}');+ expect(canvas.getByRole('status')).toHaveTextContent('Close requested');+ await waitFor(() => expect(dialog).toBeVisible());+ await userEvent.click(apply);+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ await waitFor(() => expect(apply).toHaveFocus());+ },+};++export const CancelableDefaultOpen: Story = {+ args: {+ defaultOpen: true,+ maxInlineCount: 1,+ onOpenChange: onCancelableOpenChange,+ },+ render: (args) => (+ <>+ <OverflowingList {...args} />+ <Button>Outside the list</Button>+ </>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const dialog = await body.findByRole('dialog');+ const trigger = canvas.getByRole('button', {+ name: '+3 Show all items',+ });++ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(trigger).toHaveAttribute('aria-controls', dialog.id);+ await waitFor(() => expect(dialog).toHaveFocus());+ await userEvent.keyboard('{Escape}');+ expect(onCancelableOpenChange).toHaveBeenLastCalledWith(+ false,+ expect.objectContaining({ reason: 'escape-key', isCanceled: true }),+ );+ await waitFor(() => expect(dialog).toBeVisible());+ await userEvent.click(+ canvas.getByRole('button', { name: 'Outside the list' }),+ );+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ await userEvent.click(trigger);+ const reopenedDialog = await body.findByRole('dialog');+ await waitFor(() => expect(reopenedDialog).toBeVisible());+ },+};++export const CanceledOpening: Story = {+ args: { onOpenChange: onCanceledOpenChange },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });++ await userEvent.click(trigger);+ expect(onCanceledOpenChange).toHaveBeenCalledWith(+ true,+ expect.objectContaining({+ reason: 'trigger-press',+ trigger,+ event: expect.objectContaining({ type: 'click' }),+ isCanceled: true,+ }),+ );+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ },+};++export const DisabledTrigger: Story = {+ args: { triggerProps: { disabled: true }, onOpenChange },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });++ expect(trigger).toBeDisabled();+ await userEvent.click(trigger);+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),+ ).not.toBeInTheDocument();+ },+};++export const CallerPreventsOpening: Story = {+ args: {+ triggerProps: { onClick: (event) => event.preventBaseUIHandler() },+ onOpenChange,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByRole('button', { name: /Show all items$/ }),+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),+ ).not.toBeInTheDocument();+ },+};++export const PopupTabNavigation: Story = {+ args: {+ maxInlineCount: 1,+ children: ['First item', 'Second item', 'Third item'].map((label) => (+ <Button key={label}>{label}</Button>+ )),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: '+2 Show all items',+ });++ await userEvent.tab();+ expect(canvas.getByRole('button', { name: 'First item' })).toHaveFocus();+ await userEvent.tab();+ expect(trigger).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ const dialog = await body.findByRole('dialog');+ await waitFor(() =>+ expect(+ within(dialog).getByRole('button', { name: 'First item' }),+ ).toHaveFocus(),+ );+ await userEvent.tab();+ expect(+ within(dialog).getByRole('button', { name: 'Second item' }),+ ).toHaveFocus();+ await userEvent.tab();+ expect(+ within(dialog).getByRole('button', { name: 'Third item' }),+ ).toHaveFocus();+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(trigger).toHaveFocus());+ },+};++export const TriggerRefRerenderPreservesFocus: Story = {+ render: () => <OverflowingListTriggerRefExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });++ await userEvent.tab();+ expect(trigger).toHaveFocus();+ await userEvent.keyboard('r');+ expect(canvas.getByRole('status')).toHaveTextContent('Renders: 1');+ expect(trigger).toHaveFocus();+ expect(canvas.getByRole('button', { name: /Show all items$/ })).toBe(+ trigger,+ );+ },+};++export const IndependentInstanceCleanup: Story = {+ render: () => <OverflowingListInstanceCleanupExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(+ await canvas.findByRole('button', { name: '+2 Company items' }),+ );+ const companyDialog = await body.findByRole('dialog', {+ name: 'Company items',+ });+ await userEvent.click(+ within(companyDialog).getByRole('button', {+ name: 'Remove company list',+ }),+ );+ await waitFor(() =>+ expect(+ body.queryByRole('dialog', { name: 'Company items' }),+ ).not.toBeInTheDocument(),+ );+ expect(+ canvas.queryByRole('button', { name: /Company items$/ }),+ ).not.toBeInTheDocument();+ const personTrigger = canvas.getByRole('button', {+ name: '+3 Person items',+ });+ await userEvent.click(personTrigger);+ const personDialog = await body.findByRole('dialog', {+ name: 'Person items',+ });+ await waitFor(() => expect(personDialog).toBeVisible());+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(personTrigger).toHaveFocus());+ },+};++export const DisabledTriggerFocusFallback: Story = {+ render: () => <OverflowingListDisabledTriggerFocusExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const list = canvas.getByLabelText('Items with disabled trigger');++ await userEvent.click(+ canvas.getByRole('button', { name: 'Remove focused item' }),+ );+ await waitFor(() => expect(list).toHaveFocus());+ expect(+ canvas.getByRole('button', { name: '+1 Show all items' }),+ ).toBeDisabled();+ expect(canvas.getByText('Customer')).toBeVisible();+ },+};++export const DisabledTriggerDismissal: Story = {+ args: {+ 'aria-label': 'List with disabled trigger',+ defaultOpen: true,+ onOpenChange,+ triggerProps: { disabled: true },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const list = canvas.getByLabelText('List with disabled trigger');+ const dialog = await body.findByRole('dialog');++ await waitFor(() => expect(dialog).toHaveFocus());+ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ await waitFor(() => expect(list).toHaveFocus());+ expect(+ canvas.getByRole('button', { name: /Show all items$/ }),+ ).toBeDisabled();+ },+};++export const DefaultOpenMeasuredOverflow: Story = {+ args: { defaultOpen: true, onOpenChange },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: '+2 Show all items',+ });+ const dialog = await body.findByRole('dialog');++ await waitFor(() => expect(dialog).toHaveFocus());+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await waitFor(() =>+ expect(within(dialog).getByText('Partner')).toBeVisible(),+ );+ expect(within(dialog).getByText('Customer')).toBeVisible();+ expect(canvas.getByText('Customer')).toBeVisible();+ },+};++export const CanceledUnavailableClose: Story = {+ parameters: { container: { width: 600, height: 360 } },+ render: () => (+ <StrictMode>+ <OverflowingListCanceledCloseExample />+ </StrictMode>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const list = canvas.getByLabelText('Cancelable responsive tags');+ const status = canvas.getByRole('status');+ const resizeList = async (width: string) => {+ list.style.width = width;+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => {+ requestAnimationFrame(() => resolve());+ });+ });+ };++ await waitFor(() =>+ expect(status).toHaveTextContent('Open: true. Close requests: 1.'),+ );+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();++ for (const width of ['420px', '500px']) {+ await resizeList(width);+ expect(status).toHaveTextContent('Open: true. Close requests: 1.');+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ }++ await userEvent.click(+ canvas.getByRole('button', { name: 'Close requested state' }),+ );+ expect(status).toHaveTextContent('Open: false. Close requests: 1.');+ await userEvent.click(+ canvas.getByRole('button', { name: 'Open requested state' }),+ );+ await waitFor(() =>+ expect(status).toHaveTextContent('Open: true. Close requests: 2.'),+ );+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();++ await resizeList('180px');+ const dialog = await body.findByRole('dialog', { name: 'Show all items' });+ for (const label of ['Customer', 'Partner', 'Priority', 'Renewal']) {+ await waitFor(() =>+ expect(within(dialog).getByText(label)).toBeVisible(),+ );+ }+ expect(canvas.getByText('Customer')).toBeVisible();+ expect(status).toHaveTextContent('Open: true. Close requests: 2.');++ await resizeList('500px');+ await waitFor(() =>+ expect(status).toHaveTextContent('Open: true. Close requests: 3.'),+ );+ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ },+};++export const DeferredCloseActions: Story = {+ parameters: { container: { width: 600, height: 360 } },+ args: { onOpenChange },+ render: (args) => (+ <OverflowingListActionsExample+ deferClose+ onOpenChange={args.onOpenChange}+ />+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });+ const finishExit = canvas.getByRole('button', { name: 'Finish exit' });++ for (const closeAction of ['escape-key', 'imperative-action']) {+ await userEvent.click(trigger);+ const dialog = await body.findByRole('dialog', {+ name: 'Show all items',+ });+ await waitFor(() =>+ expect(+ within(dialog).getByRole('button', { name: 'First item' }),+ ).toHaveFocus(),+ );++ if (closeAction === 'escape-key') {+ await userEvent.keyboard('{Escape}');+ }++ if (closeAction === 'imperative-action') {+ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Close with actions' }),+ );+ }++ await waitFor(() => expect(dialog).not.toBeVisible());+ expect(dialog).toBeInTheDocument();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(onOpenChange).toHaveBeenLastCalledWith(+ false,+ expect.objectContaining({ reason: closeAction }),+ );+ await userEvent.click(finishExit);+ await waitFor(() => expect(dialog).not.toBeInTheDocument());+ await waitFor(() => expect(trigger).toHaveFocus());+ }+ },+};++export const PublicActionsResponsiveClose: Story = {+ parameters: { container: { width: 600, height: 360 } },+ args: { onOpenChange },+ render: (args) => (+ <OverflowingListActionsExample onOpenChange={args.onOpenChange} />+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const list = canvas.getByRole('group', {+ name: 'Items with public actions',+ });+ const trigger = await canvas.findByRole('button', {+ name: /Show all items$/,+ });++ await userEvent.click(trigger);+ const dialog = await body.findByRole('dialog', { name: 'Show all items' });+ await waitFor(() =>+ expect(+ within(dialog).getByRole('button', { name: 'First item' }),+ ).toHaveFocus(),+ );+ list.style.width = '500px';+ await waitFor(() => expect(dialog).not.toBeInTheDocument());+ expect(onOpenChange).toHaveBeenLastCalledWith(+ false,+ expect.objectContaining({ reason: 'imperative-action' }),+ );+ await waitFor(() =>+ expect(canvas.getByRole('button', { name: 'Third item' })).toHaveFocus(),+ );+ expect(+ canvas.queryByRole('button', { name: /Show all items$/ }),+ ).not.toBeInTheDocument();+ },+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.stories.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.stories.tsxindex 789e0ef4951..0ba7f941392 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.stories.tsx+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingList.stories.tsx@@ -6,6 +6,7 @@ import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';import { OverflowingList } from '../OverflowingList';import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';+import { OverflowingListControlledExample } from './OverflowingListControlledExample';const meta: Meta<typeof OverflowingList> = {id: 'ui-components-overflowinglist',@@ -32,12 +33,24 @@ export const Documentation: Story = {render: (args) => (<Section.Root><Section.Header title="Company tags" />- <Text>Open the count to see every tag.</Text>+ <Text>Open the count to see all tags.</Text><OverflowingList {...args} overflowLabel="Show all company tags" /></Section.Root>),};+export const Controlled: Story = {+ render: () => <OverflowingListControlledExample />,+};++export const InitiallyOpen: Story = {+ args: { defaultOpen: true, maxInlineCount: 1 },+};++export const Empty: Story = {+ args: { children: [] },+};+export const CountOnHoverOrFocus: Story = {args: { showOverflowCount: undefined },};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListActionsExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListActionsExample.tsxnew file mode 100644index 00000000000..910711a2538--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListActionsExample.tsx@@ -0,0 +1,55 @@+import { useRef } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Button } from '@ui/primitives/input/Button/Button';+import { type PopoverRootActions } from '@ui/primitives/surfaces/Popover/types/PopoverRootActions';++import { OverflowingList } from '../OverflowingList';+import { type OverflowingListProps } from '../types/OverflowingListProps';++type OverflowingListActionsExampleProps = {+ deferClose?: boolean;+ onOpenChange?: OverflowingListProps['onOpenChange'];+};++export const OverflowingListActionsExample = ({+ deferClose = false,+ onOpenChange,+}: OverflowingListActionsExampleProps) => {+ const actionsRef = useRef<PopoverRootActions>(null);++ return (+ <Section.Root>+ <OverflowingList+ aria-label="Items with public actions"+ role="group"+ actionsRef={actionsRef}+ showOverflowCount+ style={{ width: 180 }}+ onOpenChange={(nextOpen, details) => {+ if (!nextOpen && deferClose) {+ details.preventUnmountOnClose();+ }++ onOpenChange?.(nextOpen, details);+ }}+ >+ {[+ <Button key="first">First item</Button>,+ <Button key="close" onClick={() => actionsRef.current?.close()}>+ Close with actions+ </Button>,+ <Button key="third">Third item</Button>,+ ]}+ </OverflowingList>+ {deferClose && (+ <Button+ onPointerDown={(event) => event.preventDefault()}+ onClick={() => actionsRef.current?.unmount()}+ >+ Finish exit+ </Button>+ )}+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListCanceledCloseExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListCanceledCloseExample.tsxnew file mode 100644index 00000000000..0a0e5fe886b--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListCanceledCloseExample.tsx@@ -0,0 +1,40 @@+import { useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';++import { OverflowingList } from '../OverflowingList';++import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';++export const OverflowingListCanceledCloseExample = () => {+ const [open, setOpen] = useState(true);+ const [closeRequestCount, setCloseRequestCount] = useState(0);++ return (+ <Section.Root>+ <OverflowingList+ aria-label="Cancelable responsive tags"+ open={open}+ showOverflowCount+ style={{ width: 500 }}+ onOpenChange={(nextOpen, details) => {+ if (nextOpen) {+ return;+ }++ details.cancel();+ setCloseRequestCount((count) => count + 1);+ }}+ >+ {OVERFLOWING_LIST_STORY_ITEMS}+ </OverflowingList>+ <Button onClick={() => setOpen(false)}>Close requested state</Button>+ <Button onClick={() => setOpen(true)}>Open requested state</Button>+ <Text role="status">+ Open: {String(open)}. Close requests: {closeRequestCount}.+ </Text>+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledExample.tsxnew file mode 100644index 00000000000..a5e38485359--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledExample.tsx@@ -0,0 +1,29 @@+import { useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';++import { OverflowingList } from '../OverflowingList';+import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';++export const OverflowingListControlledExample = () => {+ const [open, setOpen] = useState(false);++ return (+ <Section.Root>+ <Section.Header title="Company tags" />+ <Text>Open the count to see all tags.</Text>+ <OverflowingList+ open={open}+ onOpenChange={setOpen}+ showOverflowCount+ overflowLabel="Show all company tags"+ style={{ width: 180 }}+ triggerProps={{ render: <Button variant="outline" size="sm" /> }}+ >+ {OVERFLOWING_LIST_STORY_ITEMS}+ </OverflowingList>+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledStateExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledStateExample.tsxnew file mode 100644index 00000000000..fc0db872c59--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListControlledStateExample.tsx@@ -0,0 +1,45 @@+import { useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { OverflowingList } from '../OverflowingList';++export const OverflowingListControlledStateExample = () => {+ const [open, setOpen] = useState(false);+ const [requestedOpen, setRequestedOpen] = useState<boolean>();++ return (+ <Section.Root>+ <OverflowingList+ open={open}+ onOpenChange={setRequestedOpen}+ maxInlineCount={1}+ showOverflowCount+ style={{ width: 180 }}+ >+ {['First item', 'Second item', 'Third item'].map((label) => (+ <Button key={label}>{label}</Button>+ ))}+ </OverflowingList>+ <Button+ onClick={() => {+ if (isDefined(requestedOpen)) {+ setOpen(requestedOpen);+ }+ }}+ >+ Apply requested state+ </Button>+ <Text role="status">+ {!isDefined(requestedOpen)+ ? 'No request'+ : requestedOpen+ ? 'Open requested'+ : 'Close requested'}+ </Text>+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListDisabledTriggerFocusExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListDisabledTriggerFocusExample.tsxnew file mode 100644index 00000000000..7f5a345a956--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListDisabledTriggerFocusExample.tsx@@ -0,0 +1,34 @@+import { useState } from 'react';++import { Tag } from '@ui/primitives/data-display/Tag/Tag';+import { Button } from '@ui/primitives/input/Button/Button';++import { OverflowingList } from '../OverflowingList';++export const OverflowingListDisabledTriggerFocusExample = () => {+ const [hasFocusedItem, setHasFocusedItem] = useState(true);++ const items = [+ <Button key="focused" onClick={() => setHasFocusedItem(false)}>+ Remove focused item+ </Button>,+ <Tag key="customer" color="blue">+ Customer+ </Tag>,+ <Tag key="partner" color="green">+ Partner+ </Tag>,+ ];++ return (+ <OverflowingList+ aria-label="Items with disabled trigger"+ maxInlineCount={1}+ showOverflowCount+ triggerProps={{ disabled: true }}+ style={{ width: 180 }}+ >+ {hasFocusedItem ? items : items.slice(1)}+ </OverflowingList>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListEventBlockingExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListEventBlockingExample.tsxnew file mode 100644index 00000000000..1c35ba44337--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListEventBlockingExample.tsx@@ -0,0 +1,64 @@+import { type SyntheticEvent, useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Button } from '@ui/primitives/input/Button/Button';++import { OverflowingList } from '../OverflowingList';+import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';++type OverflowingListEventBlockingExampleProps = {+ onHostEvent: (event: SyntheticEvent) => void;+ onOverrideEvent: (event: SyntheticEvent) => void;+};++export const OverflowingListEventBlockingExample = ({+ onHostEvent,+ onOverrideEvent,+}: OverflowingListEventBlockingExampleProps) => {+ const [overrideEvent, setOverrideEvent] = useState<+ 'click' | 'mouseDown' | 'pointerDown' | 'keyDown' | 'keyUp'+ >();+ const eventProps = {+ onClick: overrideEvent === 'click' ? onOverrideEvent : undefined,+ onMouseDown: overrideEvent === 'mouseDown' ? onOverrideEvent : undefined,+ onPointerDown:+ overrideEvent === 'pointerDown' ? onOverrideEvent : undefined,+ onKeyDown: overrideEvent === 'keyDown' ? onOverrideEvent : undefined,+ onKeyUp: overrideEvent === 'keyUp' ? onOverrideEvent : undefined,+ };++ return (+ <Section.Root>+ <div+ role="group"+ aria-label="Event host"+ onClick={onHostEvent}+ onMouseDown={onHostEvent}+ onPointerDown={onHostEvent}+ onKeyDown={onHostEvent}+ onKeyUp={onHostEvent}+ >+ <OverflowingList+ open+ maxInlineCount={1}+ showOverflowCount+ style={{ width: 180 }}+ triggerProps={eventProps}+ popupProps={eventProps}+ >+ {OVERFLOWING_LIST_STORY_ITEMS}+ </OverflowingList>+ </div>+ <Button onClick={() => setOverrideEvent(undefined)}>+ Default blocking+ </Button>+ {(['click', 'mouseDown', 'pointerDown', 'keyDown', 'keyUp'] as const).map(+ (eventName) => (+ <Button key={eventName} onClick={() => setOverrideEvent(eventName)}>+ Allow {eventName}+ </Button>+ ),+ )}+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListFocusExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListFocusExample.tsxnew file mode 100644index 00000000000..eacbe5dddfb--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListFocusExample.tsx@@ -0,0 +1,34 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { OverflowingList } from '../OverflowingList';++const ITEM_LABELS = ['First item', 'Second item', 'Third item'];++export const OverflowingListFocusExample = () => {+ const [items, setItems] = useState(ITEM_LABELS);++ return (+ <OverflowingList+ aria-label="Focusable items"+ showOverflowCount+ maxInlineCount={1}+ style={{ width: 180 }}+ >+ {items.map((label) => (+ <Button+ key={label}+ style={{ width: 100 }}+ onClick={() =>+ setItems((currentItems) =>+ currentItems.filter((item) => item !== label),+ )+ }+ >+ {label}+ </Button>+ ))}+ </OverflowingList>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListInstanceCleanupExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListInstanceCleanupExample.tsxnew file mode 100644index 00000000000..9c4b39026e2--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListInstanceCleanupExample.tsx@@ -0,0 +1,43 @@+import { useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Tag } from '@ui/primitives/data-display/Tag/Tag';+import { Button } from '@ui/primitives/input/Button/Button';++import { OverflowingList } from '../OverflowingList';+import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';++export const OverflowingListInstanceCleanupExample = () => {+ const [showCompanyList, setShowCompanyList] = useState(true);++ return (+ <Section.Root>+ {showCompanyList && (+ <OverflowingList+ maxInlineCount={1}+ showOverflowCount+ overflowLabel="Company items"+ style={{ width: 180 }}+ >+ <Tag key="company" color="blue">+ Company+ </Tag>+ <Button key="remove" onClick={() => setShowCompanyList(false)}>+ Remove company list+ </Button>+ <Tag key="deal" color="green">+ Deal+ </Tag>+ </OverflowingList>+ )}+ <OverflowingList+ maxInlineCount={1}+ showOverflowCount+ overflowLabel="Person items"+ style={{ width: 180 }}+ >+ {OVERFLOWING_LIST_STORY_ITEMS}+ </OverflowingList>+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListStateExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListStateExample.tsxnew file mode 100644index 00000000000..34de1c5a965--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListStateExample.tsx@@ -0,0 +1,32 @@+import { useId, useState } from 'react';++import { Input } from '@ui/primitives/input/Input/Input';++import { OverflowingList } from '../OverflowingList';++const StatefulValue = ({ name }: { name: string }) => {+ const identifier = useId();+ const [value, setValue] = useState('');++ return (+ <Input+ id={identifier}+ aria-label={name}+ style={{ width: 100 }}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ );+};++export const OverflowingListStateExample = () => (+ <OverflowingList+ aria-label="Stateful values"+ showOverflowCount+ style={{ width: 180 }}+ >+ {['First value', 'Second value', 'Third value'].map((name) => (+ <StatefulValue key={name} name={name} />+ ))}+ </OverflowingList>+);diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListTriggerRefExample.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListTriggerRefExample.tsxnew file mode 100644index 00000000000..4e19b860f1e--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__stories__/OverflowingListTriggerRefExample.tsx@@ -0,0 +1,34 @@+import { useRef, useState } from 'react';++import { Section } from '@ui/components/layout/Section/Section';+import { Text } from '@ui/primitives/typography/Text/Text';++import { OverflowingList } from '../OverflowingList';+import { OVERFLOWING_LIST_STORY_ITEMS } from './OVERFLOWING_LIST_STORY_ITEMS';++export const OverflowingListTriggerRefExample = () => {+ const triggerRef = useRef<HTMLElement | null>(null);+ const [renderCount, setRenderCount] = useState(0);++ return (+ <Section.Root>+ <OverflowingList+ showOverflowCount+ style={{ width: 180 }}+ triggerProps={{+ ref: (element) => {+ triggerRef.current = element;+ },+ onKeyDown: (event) => {+ if (event.key === 'r') {+ setRenderCount((currentCount) => currentCount + 1);+ }+ },+ }}+ >+ {OVERFLOWING_LIST_STORY_ITEMS}+ </OverflowingList>+ <Text role="status">Renders: {renderCount}</Text>+ </Section.Root>+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/__tests__/OverflowingList.server.test.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/__tests__/OverflowingList.server.test.tsxnew file mode 100644index 00000000000..a834563c9da--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/__tests__/OverflowingList.server.test.tsx@@ -0,0 +1,52 @@+import { act, within } from '@testing-library/react';+import { hydrateRoot, type Root } from 'react-dom/client';+import { renderToString } from 'react-dom/server';+import { expect, it, vi } from 'vitest';++import { OverflowingList } from '../OverflowingList';++it('renders capped inline content on the server and hydrates existing items without warnings', async () => {+ const content = (+ <OverflowingList maxInlineCount={1} showOverflowCount>+ {['First item', 'Second item', 'Third item'].map((label) => (+ <button key={label} type="button">+ {label}+ </button>+ ))}+ </OverflowingList>+ );+ const container = document.createElement('div');+ container.innerHTML = renderToString(content);+ document.body.append(container);+ const serverItem = within(container).getByRole('button', {+ name: 'First item',+ });+ expect(serverItem).toBeVisible();+ expect(within(container).queryByText('Second item')).not.toBeInTheDocument();++ const onRecoverableError = vi.fn();+ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => undefined);+ let root: Root | undefined;++ try {+ await act(async () => {+ root = hydrateRoot(container, content, { onRecoverableError });+ });+ expect(within(container).getByRole('button', { name: 'First item' })).toBe(+ serverItem,+ );+ expect(within(container).getAllByText('First item')).toHaveLength(1);+ expect(+ within(container).queryByText('Second item'),+ ).not.toBeInTheDocument();+ expect(within(container).queryByText('Third item')).not.toBeInTheDocument();+ expect(onRecoverableError).not.toHaveBeenCalled();+ expect(consoleError).not.toHaveBeenCalled();+ } finally {+ await act(async () => root?.unmount());+ consoleError.mockRestore();+ container.remove();+ }+});diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItem.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItem.tsxindex fe842ae5ef8..fc59441f582 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItem.tsx+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItem.tsx@@ -1,34 +1,62 @@-import { type ReactElement } from 'react';+import { useMergedRefs } from '@base-ui/utils/useMergedRefs';+import { useStableCallback } from '@base-ui/utils/useStableCallback';+import { type ReactElement, useRef } from 'react';import styles from '../OverflowingList.module.scss';++import { OverflowingListItemFocusEffect } from './OverflowingListItemFocusEffect';import { useFocusedElementUnmountRef } from './useFocusedElementUnmountRef';type OverflowingListItemProps = {children: ReactElement;+ index: number;isHidden: boolean;isLastVisible: boolean;- onFocusedItemUnmount: () => void;+ isInPopup: boolean;+ onFocusLost: (options: {+ index: number;+ element: HTMLElement;+ isInPopup: boolean;+ }) => void;};export const OverflowingListItem = ({children,+ index,isHidden,isLastVisible,- onFocusedItemUnmount,+ isInPopup,+ onFocusLost,}: OverflowingListItemProps) => {- const resetFocusWhenFocusedItemUnmounts =- useFocusedElementUnmountRef(onFocusedItemUnmount);+ const elementRef = useRef<HTMLDivElement>(null);+ const handleFocusLost = useStableCallback((element: HTMLElement) => {+ onFocusLost({ index, element, isInPopup });+ });+ const restoreFocusWhenFocusedItemUnmounts =+ useFocusedElementUnmountRef(handleFocusLost);+ const mergedRef = useMergedRefs(+ elementRef,+ restoreFocusWhenFocusedItemUnmounts,+ );return (- <div- ref={resetFocusWhenFocusedItemUnmounts}- className={styles.item}- data-hidden={isHidden || undefined}- data-last-visible={isLastVisible || undefined}- aria-hidden={isHidden || undefined}- inert={isHidden}- >- {children}- </div>+ <>+ <div+ ref={mergedRef}+ className={isInPopup ? styles.popupItem : styles.item}+ data-item-index={index}+ data-hidden={isHidden || undefined}+ data-last-visible={isLastVisible || undefined}+ aria-hidden={isHidden || undefined}+ inert={isHidden}+ >+ {children}+ </div>+ <OverflowingListItemFocusEffect+ elementRef={elementRef}+ isHidden={isHidden}+ onFocusLost={handleFocusLost}+ />+ </>);};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItemFocusEffect.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItemFocusEffect.tsxnew file mode 100644index 00000000000..81c0870bdbd--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListItemFocusEffect.tsx@@ -0,0 +1,30 @@+import { type RefObject, memo, useLayoutEffect } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++type OverflowingListItemFocusEffectProps = {+ elementRef: RefObject<HTMLDivElement | null>;+ isHidden: boolean;+ onFocusLost: (element: HTMLElement) => void;+};++export const OverflowingListItemFocusEffect = memo(+ ({+ elementRef,+ isHidden,+ onFocusLost,+ }: OverflowingListItemFocusEffectProps) => {+ useLayoutEffect(() => {+ const element = elementRef.current;+ const hasFocus =+ isDefined(element) &&+ element.contains(element.ownerDocument.activeElement);++ if (isHidden && hasFocus) {+ onFocusLost(element);+ }+ }, [elementRef, isHidden, onFocusLost]);++ return null;+ },+);diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListLayoutEffect.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListLayoutEffect.tsxnew file mode 100644index 00000000000..65f871b8672--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListLayoutEffect.tsx@@ -0,0 +1,163 @@+import { useStableCallback } from '@base-ui/utils/useStableCallback';+import { type RefObject, memo, useLayoutEffect, useRef } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { measureOverflowingListLayout } from './measureOverflowingListLayout';+import { type OverflowingListLayout } from './types/OverflowingListLayout';++const FALLBACK_MEASUREMENT_INTERVAL_MS = 100;++type OverflowingListLayoutEffectProps = {+ containerRef: RefObject<HTMLDivElement | null>;+ itemsRef: RefObject<HTMLDivElement | null>;+ triggerRef: RefObject<HTMLElement | null>;+ itemCount: number;+ inlineItemCount: number;+ reserveCountSpace: boolean;+ isMeasurementEnabled: boolean;+ isOpen: boolean;+ onLayoutChange: (layout: OverflowingListLayout) => void;+ onOverflowUnavailable: () => void;+};++export const OverflowingListLayoutEffect = memo(+ ({+ containerRef,+ itemsRef,+ triggerRef,+ itemCount,+ inlineItemCount,+ reserveCountSpace,+ isMeasurementEnabled,+ isOpen,+ onLayoutChange,+ onOverflowUnavailable,+ }: OverflowingListLayoutEffectProps) => {+ const measureRef = useRef<() => void>(undefined);+ const previousMeasurementRef = useRef<{+ layout: OverflowingListLayout;+ isOpen: boolean;+ }>(undefined);+ const getLayoutInput = useStableCallback(() => ({+ itemCount,+ inlineItemCount,+ reserveCountSpace,+ isOpen,+ }));+ const updateLayout = useStableCallback(onLayoutChange);+ const closeUnavailableOverflow = useStableCallback(onOverflowUnavailable);++ useLayoutEffect(() => {+ const container = containerRef.current;+ const items = itemsRef.current;++ if (!isMeasurementEnabled || !isDefined(container) || !isDefined(items)) {+ previousMeasurementRef.current = undefined;+ return;+ }++ const supportsSynchronousLayout = isDefined(globalThis.ResizeObserver);+ const observedElements = new Set<Element>();+ const measure = () => {+ const itemElements = Array.from(items.children);+ const currentElements = new Set<Element>([container, ...itemElements]);++ if (isDefined(triggerRef.current)) {+ currentElements.add(triggerRef.current);+ }++ for (const element of observedElements) {+ if (!currentElements.has(element)) {+ observer?.unobserve(element);+ observedElements.delete(element);+ }+ }++ for (const element of currentElements) {+ if (!observedElements.has(element)) {+ observer?.observe(element);+ observedElements.add(element);+ }+ }++ const layoutInput = getLayoutInput();++ if (itemElements.length !== layoutInput.inlineItemCount) {+ return;+ }++ const layout = measureOverflowingListLayout({+ container,+ items,+ trigger: triggerRef.current,+ itemElements,+ itemCount: layoutInput.itemCount,+ reserveCountSpace: layoutInput.reserveCountSpace,+ supportsSynchronousLayout,+ });+ const previousMeasurement = previousMeasurementRef.current;+ const wasUnavailableOpen =+ isDefined(previousMeasurement) &&+ previousMeasurement.isOpen &&+ !previousMeasurement.layout.hasOverflow;+ const isUnavailableOpen = layoutInput.isOpen && !layout.hasOverflow;+ previousMeasurementRef.current = { layout, isOpen: layoutInput.isOpen };+ updateLayout(layout);++ if (isUnavailableOpen && !wasUnavailableOpen) {+ closeUnavailableOverflow();+ }+ };++ const observer = supportsSynchronousLayout+ ? new ResizeObserver(measure)+ : undefined;++ measureRef.current = measure;+ measure();++ const contentObserver = new MutationObserver(measure);+ contentObserver.observe(items, {+ attributes: true,+ attributeFilter: ['class', 'style', 'hidden'],+ characterData: true,+ childList: true,+ subtree: true,+ });+ contentObserver.observe(container, { childList: true });++ if (!isDefined(observer)) {+ const interval = setInterval(measure, FALLBACK_MEASUREMENT_INTERVAL_MS);+ window.addEventListener('resize', measure);++ return () => {+ measureRef.current = undefined;+ clearInterval(interval);+ contentObserver.disconnect();+ window.removeEventListener('resize', measure);+ };+ }++ return () => {+ measureRef.current = undefined;+ contentObserver.disconnect();+ observer.disconnect();+ };+ }, [+ containerRef,+ itemsRef,+ triggerRef,+ isMeasurementEnabled,+ getLayoutInput,+ updateLayout,+ closeUnavailableOverflow,+ ]);++ useLayoutEffect(() => {+ measureRef.current?.();+ }, [itemCount, inlineItemCount, reserveCountSpace, isOpen]);++ return null;+ },+);diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListPopupTarget.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListPopupTarget.tsxnew file mode 100644index 00000000000..d3c71b376a7--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/OverflowingListPopupTarget.tsx@@ -0,0 +1,46 @@+import { mergeProps } from '@base-ui/react/merge-props';+import { useMergedRefs } from '@base-ui/utils/useMergedRefs';+import { isFunction } from '@sniptt/guards';+import { cloneElement, isValidElement, type ReactElement } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { type OverflowingListProps } from '../types/OverflowingListProps';++type PopupRender = Exclude<+ NonNullable<NonNullable<OverflowingListProps['popupProps']>['render']>,+ ReactElement+>;++type OverflowingListPopupTargetProps = {+ props: Parameters<PopupRender>[0];+ state: Parameters<PopupRender>[1];+ render: NonNullable<OverflowingListProps['popupProps']>['render'];+};++export const OverflowingListPopupTarget = ({+ props,+ state,+ render,+}: OverflowingListPopupTargetProps) => {+ const renderElement = isValidElement<Parameters<PopupRender>[0]>(render)+ ? render+ : undefined;+ const mergedRef = useMergedRefs(props.ref, renderElement?.props.ref);++ if (isFunction(render)) {+ return render(props, state);+ }++ const mergedProps = {+ ...mergeProps<'div'>(props, renderElement?.props),+ children: props.children,+ ref: mergedRef,+ };++ return isDefined(renderElement) ? (+ cloneElement(renderElement, mergedProps)+ ) : (+ <div {...mergedProps} />+ );+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/focusOverflowingListFallback.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/focusOverflowingListFallback.tsnew file mode 100644index 00000000000..847e0b7dccd--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/focusOverflowingListFallback.ts@@ -0,0 +1,66 @@+import { isDefined } from '@ui/utilities/utils/isDefined';++const FOCUSABLE_ITEM_SELECTOR =+ 'button, a[href], input, select, textarea, [tabindex]';++export const focusOverflowingListFallback = ({+ items,+ popup,+ trigger,+ root,+ removedIndex,+ excludedItem,+}: {+ items: HTMLElement | null;+ popup: HTMLElement | null;+ trigger: HTMLElement | null;+ root: HTMLElement | null;+ removedIndex: number;+ excludedItem?: HTMLElement;+}) => {+ const itemElements = [+ ...Array.from(items?.children ?? []),+ ...Array.from(popup?.children ?? []),+ ].filter((item) => item !== excludedItem);+ const orderedItems = itemElements.sort(+ (firstItem, secondItem) =>+ Math.abs(+ Number(firstItem.getAttribute('data-item-index')) - removedIndex,+ ) -+ Math.abs(+ Number(secondItem.getAttribute('data-item-index')) - removedIndex,+ ) ||+ Number(secondItem.getAttribute('data-item-index')) -+ Number(firstItem.getAttribute('data-item-index')),+ );++ for (const item of orderedItems) {+ if (item.hasAttribute('inert')) {+ continue;+ }++ for (const candidate of Array.from(+ item.querySelectorAll<HTMLElement>(FOCUSABLE_ITEM_SELECTOR),+ )) {+ const isAvailable =+ !candidate.matches(':disabled') &&+ !isDefined(candidate.closest('[inert]'));++ if (isAvailable) {+ candidate.focus();++ if (candidate.ownerDocument.activeElement === candidate) {+ return;+ }+ }+ }+ }++ trigger?.focus();++ if (isDefined(trigger) && trigger.ownerDocument.activeElement === trigger) {+ return;+ }++ root?.focus();+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/measureOverflowingListLayout.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/measureOverflowingListLayout.tsnew file mode 100644index 00000000000..d06cc61cda4--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/measureOverflowingListLayout.ts@@ -0,0 +1,49 @@+import { getVisibleItemCount } from './getVisibleItemCount';+import { measureItemWidths } from './measureItemWidths';+import { type OverflowingListLayout } from './types/OverflowingListLayout';++export const measureOverflowingListLayout = ({+ container,+ items,+ trigger,+ itemElements,+ itemCount,+ reserveCountSpace,+ supportsSynchronousLayout,+}: {+ container: HTMLElement;+ items: HTMLElement;+ trigger: HTMLElement | null;+ itemElements: Element[];+ itemCount: number;+ reserveCountSpace: boolean;+ supportsSynchronousLayout: boolean;+}): OverflowingListLayout => {+ const itemWidths = measureItemWidths({+ items,+ itemElements,+ supportsSynchronousLayout,+ });+ const gap = parseFloat(getComputedStyle(items).columnGap) || 0;+ const containerWidth = container.clientWidth;+ const fittedItemCount = getVisibleItemCount({+ itemWidths,+ availableWidth: containerWidth,+ gap,+ includePartialItem: false,+ });+ const hasOverflow = itemCount > fittedItemCount;+ const triggerWidth = trigger?.offsetWidth ?? 0;+ const availableWidth =+ reserveCountSpace && hasOverflow+ ? Math.max(0, containerWidth - triggerWidth - gap)+ : containerWidth;+ const visibleItemCount = getVisibleItemCount({+ itemWidths,+ availableWidth,+ gap,+ includePartialItem: true,+ });++ return { visibleItemCount, hasOverflow };+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/types/OverflowingListLayout.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/types/OverflowingListLayout.tsnew file mode 100644index 00000000000..0d289279e5c--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/types/OverflowingListLayout.ts@@ -0,0 +1,4 @@+export type OverflowingListLayout = {+ visibleItemCount: number;+ hasOverflow: boolean;+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/useFocusedElementUnmountRef.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useFocusedElementUnmountRef.tsindex 527563ead6a..8a2e03801c0 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/internal/useFocusedElementUnmountRef.ts+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useFocusedElementUnmountRef.ts@@ -3,7 +3,7 @@ import { useCallback } from 'react';import { isDefined } from '@ui/utilities/utils/isDefined';export const useFocusedElementUnmountRef = (- onFocusedElementUnmount: () => void,+ onFocusedElementUnmount: (element: HTMLElement) => void,) =>useCallback((element: HTMLElement | null) => {@@ -12,9 +12,16 @@ export const useFocusedElementUnmountRef = (}return () => {- if (element.contains(element.ownerDocument.activeElement)) {- onFocusedElementUnmount();- }+ const document = element.ownerDocument;+ const hadFocus = element.contains(document.activeElement);++ queueMicrotask(() => {+ const hasLostFocus = document.activeElement === document.body;++ if (hadFocus && !element.isConnected && hasLostFocus) {+ onFocusedElementUnmount(element);+ }+ });};},[onFocusedElementUnmount],diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListFocus.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListFocus.tsnew file mode 100644index 00000000000..0ad94a18010--- /dev/null+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListFocus.ts@@ -0,0 +1,154 @@+import { useStableCallback } from '@base-ui/utils/useStableCallback';+import { type FocusEvent, type RefObject, useCallback, useState } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { type OverflowingListProps } from '../types/OverflowingListProps';++import { focusOverflowingListFallback } from './focusOverflowingListFallback';+import { useFocusedElementUnmountRef } from './useFocusedElementUnmountRef';++type UseOverflowingListFocusOptions = {+ containerRef: RefObject<HTMLDivElement | null>;+ itemsRef: RefObject<HTMLDivElement | null>;+ triggerRef: RefObject<HTMLElement | null>;+ popup: HTMLDivElement | null;+ itemCount: number;+ canExpand: boolean;+ isPopupOpen: boolean;+ isOpen: boolean;+ isHovered: boolean;+ showOverflowCount: OverflowingListProps['showOverflowCount'];+ onFocusCapture: OverflowingListProps['onFocusCapture'];+ onBlurCapture: OverflowingListProps['onBlurCapture'];+};++export const useOverflowingListFocus = ({+ containerRef,+ itemsRef,+ triggerRef,+ popup,+ itemCount,+ canExpand,+ isPopupOpen,+ isOpen,+ isHovered,+ showOverflowCount,+ onFocusCapture,+ onBlurCapture,+}: UseOverflowingListFocusOptions) => {+ const [hasFocus, setHasFocus] = useState(false);+ const [focusedItemCountVisibility, setFocusedItemCountVisibility] =+ useState<boolean>();+ const isCountVisible =+ showOverflowCount ??+ focusedItemCountVisibility ??+ (isHovered || hasFocus || isOpen);+ const restoreItemFocus = useStableCallback(+ ({+ index,+ element,+ isInPopup,+ }: {+ index: number;+ element: HTMLElement;+ isInPopup: boolean;+ }) => {+ focusOverflowingListFallback({+ items: isInPopup && canExpand ? null : itemsRef.current,+ popup: isInPopup && isPopupOpen ? popup : null,+ trigger: triggerRef.current,+ root: containerRef.current,+ removedIndex: index,+ excludedItem: element,+ });+ },+ );+ const restoreTriggerFocus = useCallback(() => {+ const container = containerRef.current;+ container?.focus();+ setHasFocus(container?.ownerDocument.activeElement === container);+ setFocusedItemCountVisibility(undefined);+ }, [containerRef]);+ const restorePopupFocus = useStableCallback(() => {+ if (isPopupOpen) {+ return;+ }++ const container = containerRef.current;+ const document = container?.ownerDocument;+ const activeElement = document?.activeElement;+ const hasFocusedInlineItem =+ isDefined(activeElement) &&+ itemsRef.current?.contains(activeElement) &&+ !isDefined(activeElement.closest('[inert]'));+ const hasExternalFocus =+ isDefined(activeElement) &&+ activeElement !== document?.body &&+ !container?.contains(activeElement) &&+ !popup?.contains(activeElement);++ if (hasFocusedInlineItem || hasExternalFocus) {+ return;+ }++ if (!canExpand) {+ focusOverflowingListFallback({+ items: itemsRef.current,+ popup: null,+ trigger: null,+ root: container,+ removedIndex: itemCount,+ });+ return;+ }++ const trigger = triggerRef.current;++ if (isDefined(trigger) && !trigger.matches(':disabled')) {+ trigger.focus({ preventScroll: true });+ return;+ }++ container?.focus({ preventScroll: true });+ });+ const schedulePopupFocusRestoration = useCallback(() => {+ queueMicrotask(restorePopupFocus);+ return false;+ }, [restorePopupFocus]);+ const resetFocusWhenFocusedTriggerUnmounts =+ useFocusedElementUnmountRef(restoreTriggerFocus);+ const handleFocusCapture = (event: FocusEvent<HTMLDivElement>) => {+ setHasFocus(true);++ if (itemsRef.current?.contains(event.target)) {+ setFocusedItemCountVisibility(+ (currentVisibility) => currentVisibility ?? isCountVisible,+ );+ }++ onFocusCapture?.(event);+ };+ const handleBlurCapture = (event: FocusEvent<HTMLDivElement>) => {+ const hasRelatedFocus =+ event.currentTarget.contains(event.relatedTarget) ||+ (popup?.contains(event.relatedTarget) ?? false);+ setHasFocus(hasRelatedFocus);++ if (!itemsRef.current?.contains(event.relatedTarget)) {+ setFocusedItemCountVisibility(undefined);+ }++ onBlurCapture?.(event);+ };++ return {+ hasFocus,+ isCountVisible,+ restoreItemFocus,+ schedulePopupFocusRestoration,+ resetFocusWhenFocusedTriggerUnmounts,+ handleFocusCapture,+ handleBlurCapture,+ };+};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListLayout.ts b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListLayout.tsindex bfe498676fc..fc0bb4ce125 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListLayout.ts+++ b/packages/twenty-ui/src/components/layout/OverflowingList/internal/useOverflowingListLayout.ts@@ -1,136 +1,30 @@-import { useLayoutEffect, useRef, useState } from 'react';+import { useCallback, useRef, useState } from 'react';-import { isDefined } from '@ui/utilities/utils/isDefined';--import { getVisibleItemCount } from './getVisibleItemCount';-import { measureItemWidths } from './measureItemWidths';--const FALLBACK_MEASUREMENT_INTERVAL_MS = 100;+import { type OverflowingListLayout } from './types/OverflowingListLayout';export const useOverflowingListLayout = ({itemCount,inlineItemCount,- reserveCountSpace,- isMeasurementEnabled,}: {itemCount: number;inlineItemCount: number;- reserveCountSpace: boolean;- isMeasurementEnabled: boolean;}) => {const containerRef = useRef<HTMLDivElement>(null);const itemsRef = useRef<HTMLDivElement>(null);- const triggerRef = useRef<HTMLButtonElement>(null);- const measureRef = useRef<() => void>(undefined);- const layoutInputRef = useRef({ itemCount, reserveCountSpace });- const [visibleItemCount, setVisibleItemCount] = useState(inlineItemCount);- const [hasOverflow, setHasOverflow] = useState(itemCount > inlineItemCount);-- useLayoutEffect(() => {- layoutInputRef.current = { itemCount, reserveCountSpace };- measureRef.current?.();- }, [itemCount, inlineItemCount, reserveCountSpace]);-- useLayoutEffect(() => {- const container = containerRef.current;- const items = itemsRef.current;-- if (!isMeasurementEnabled || !isDefined(container) || !isDefined(items)) {- return;- }-- const supportsSynchronousLayout = isDefined(globalThis.ResizeObserver);- const observedElements = new Set<Element>();- const measure = () => {- const itemElements = Array.from(items.children);- const currentElements = new Set<Element>([container, ...itemElements]);-- if (isDefined(triggerRef.current)) {- currentElements.add(triggerRef.current);- }-- for (const element of observedElements) {- if (!currentElements.has(element)) {- observer?.unobserve(element);- observedElements.delete(element);- }- }-- for (const element of currentElements) {- if (!observedElements.has(element)) {- observer?.observe(element);- observedElements.add(element);- }- }-- const latestLayoutInput = layoutInputRef.current;- const itemWidths = measureItemWidths({- items,- itemElements,- supportsSynchronousLayout,- });- const gap = parseFloat(getComputedStyle(items).columnGap) || 0;- const containerWidth = container.clientWidth;- const fittedItemCount = getVisibleItemCount({- itemWidths,- availableWidth: containerWidth,- gap,- includePartialItem: false,- });- const nextHasOverflow = latestLayoutInput.itemCount > fittedItemCount;- const triggerWidth = triggerRef.current?.offsetWidth ?? 0;- const availableWidth =- latestLayoutInput.reserveCountSpace && nextHasOverflow- ? Math.max(0, containerWidth - triggerWidth - gap)- : containerWidth;-- setHasOverflow(nextHasOverflow);- setVisibleItemCount(- getVisibleItemCount({- itemWidths,- availableWidth,- gap,- includePartialItem: true,- }),- );- };-- const observer = supportsSynchronousLayout- ? new ResizeObserver(measure)- : undefined;-- measureRef.current = measure;- measure();-- const contentObserver = new MutationObserver(measure);- contentObserver.observe(items, {- attributes: true,- attributeFilter: ['class', 'style', 'hidden'],- characterData: true,- childList: true,- subtree: true,+ const triggerRef = useRef<HTMLElement>(null);+ const [layout, setLayout] = useState<OverflowingListLayout>({+ visibleItemCount: inlineItemCount,+ hasOverflow: itemCount > inlineItemCount,+ });+ const updateLayout = useCallback((nextLayout: OverflowingListLayout) => {+ setLayout((currentLayout) => {+ const hasChanged =+ currentLayout.visibleItemCount !== nextLayout.visibleItemCount ||+ currentLayout.hasOverflow !== nextLayout.hasOverflow;++ return hasChanged ? nextLayout : currentLayout;});+ }, []);- contentObserver.observe(container, { childList: true });-- if (!isDefined(observer)) {- const interval = setInterval(measure, FALLBACK_MEASUREMENT_INTERVAL_MS);- window.addEventListener('resize', measure);-- return () => {- measureRef.current = undefined;- clearInterval(interval);- contentObserver.disconnect();- window.removeEventListener('resize', measure);- };- }-- return () => {- measureRef.current = undefined;- contentObserver.disconnect();- observer.disconnect();- };- }, [isMeasurementEnabled]);-- return { containerRef, itemsRef, triggerRef, visibleItemCount, hasOverflow };+ return { containerRef, itemsRef, triggerRef, updateLayout, ...layout };};diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/types/OverflowingListProps.ts b/packages/twenty-ui/src/components/layout/OverflowingList/types/OverflowingListProps.tsindex dfd0885a6b3..8e04001d92b 100644--- a/packages/twenty-ui/src/components/layout/OverflowingList/types/OverflowingListProps.ts+++ b/packages/twenty-ui/src/components/layout/OverflowingList/types/OverflowingListProps.ts@@ -1,11 +1,22 @@-import { type ComponentPropsWithRef, type ReactElement } from 'react';+import { type ComponentPropsWithRef, type ReactElement, type Ref } from 'react';++import { type Popover } from '@ui/primitives/surfaces/Popover/Popover';export type OverflowingListProps = Omit<ComponentPropsWithRef<'div'>,'children'-> & {- children: ReactElement[];- showOverflowCount?: boolean;- maxInlineCount?: number;- overflowLabel?: string;-};+> &+ Pick<+ ComponentPropsWithRef<typeof Popover.Root>,+ 'open' | 'defaultOpen' | 'onOpenChange' | 'actionsRef'+ > & {+ children: ReactElement[];+ showOverflowCount?: boolean;+ maxInlineCount?: number;+ overflowLabel?: string;+ triggerProps?: Omit<+ ComponentPropsWithRef<typeof Popover.Trigger>,+ 'handle' | 'payload' | 'ref'+ > & { ref?: Ref<HTMLElement> };+ popupProps?: Omit<ComponentPropsWithRef<typeof Popover.Popup>, 'children'>;+ };