Skip to content

Commit

Permalink
Extract computeDropdownTriggerCompositeId
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Aug 26, 2024
1 parent e0baf77 commit a2fe333
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions packages/dataviews/src/dataviews-layouts/list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import type { Action, NormalizedField, ViewListProps } from '../../types';

interface ListViewItemProps< Item > {
actions: Action< Item >[];
id?: string;
id: string;
isSelected: boolean;
item: Item;
mediaField?: NormalizedField< Item >;
Expand All @@ -56,6 +56,10 @@ const {
DropdownMenuV2: DropdownMenu,
} = unlock( componentsPrivateApis );

function computeDropdownTriggerCompositeId( domId: string ) {
return `${ domId }-dropdown`;
}

function ListItem< Item >( {
actions,
id,
Expand Down Expand Up @@ -262,7 +266,9 @@ function ListItem< Item >( {
<DropdownMenu
trigger={
<CompositeItem
id={ `${ id }-dropdown` }
id={ computeDropdownTriggerCompositeId(
id
) }
render={
<Button
size="small"
Expand Down Expand Up @@ -324,8 +330,13 @@ export default function ViewList< Item >( props: ViewListProps< Item > ) {
const baseId = useInstanceId( ViewList, 'view-list' );

const getItemDomId = useCallback(
( item?: Item ) =>
item ? `${ baseId }-${ getItemId( item ) }` : undefined,
( item?: Item ) => {
if ( ! item ) {
return;
}

return `${ baseId }-${ getItemId( item ) }`;
},
[ baseId, getItemId ]
);

Expand Down Expand Up @@ -397,7 +408,12 @@ export default function ViewList< Item >( props: ViewListProps< Item > ) {

const selectItemDropdownTrigger = ( itemIndex: number ) => {
const item = data[ itemIndex ];
const nextCompositeActiveId = `${ getItemDomId( item ) }-dropdown`;
const itemDomId = getItemDomId( item );
if ( ! itemDomId ) {
return;
}
const nextCompositeActiveId =
computeDropdownTriggerCompositeId( itemDomId );
setActiveCompositeId( nextCompositeActiveId );
(
document.querySelector( `#${ nextCompositeActiveId }` ) as
Expand Down Expand Up @@ -443,7 +459,9 @@ export default function ViewList< Item >( props: ViewListProps< Item > ) {
setActiveId={ setActiveCompositeId }
>
{ data.map( ( item ) => {
const id = getItemDomId( item );
// Since `item` is guaranteed not to be undefined, we can safely
// let typescript know that `id` is not undefined either.
const id = getItemDomId( item )!;
return (
<ListItem
key={ id }
Expand Down

0 comments on commit a2fe333

Please sign in to comment.