Skip to content

Commit

Permalink
allow for nested arrays of controls
Browse files Browse the repository at this point in the history
  • Loading branch information
chad1008 committed May 9, 2023
1 parent 404330b commit 5d317f9
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
2 changes: 1 addition & 1 deletion packages/components/src/dropdown-menu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ A human-readable label to present as accessibility text on the focused collapsed

- Required: Yes

#### `controls:` `DropdownOption[]`
#### `controls:` `DropdownOption[] | DropdownOption[][]`

An array of objects describing the options to be shown in the expanded menu.

Expand Down
10 changes: 5 additions & 5 deletions packages/components/src/dropdown-menu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { menu } from '@wordpress/icons';
import Button from '../button';
import Dropdown from '../dropdown';
import { NavigableMenu } from '../navigable-container';
import type { DropdownMenuProps } from './types';
import type { Controls, DropdownMenuProps, NormalizedControls } from './types';

function mergeProps<
T extends { className?: string; [ key: string ]: unknown }
Expand Down Expand Up @@ -139,15 +139,15 @@ function DropdownMenu( dropdownMenuProps: DropdownMenuProps ) {
}

// Normalize controls to nested array of objects (sets of controls)
let controlSets: NonNullable< typeof controls >[];
let controlSets: NormalizedControls;
if ( controls?.length ) {
// @ts-expect-error The check below is needed because `DropdownMenus`
// rendered by `ToolBarGroup` receive controls as a nested array.
controlSets = controls;
if ( ! Array.isArray( controlSets[ 0 ] ) ) {
// This is not ideal but was introduced to avoid runtime changes,
// see above comment.
controlSets = [ controls as unknown as typeof controls ];
// This is not ideal, but at this point we know that `controls` is
// not a nested array, even if TypeScript doesn't.
controlSets = [ controls as Controls ];
}
}

Expand Down
6 changes: 4 additions & 2 deletions packages/components/src/dropdown-menu/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ type DropdownOption = {
role?: HTMLElement[ 'role' ];
};

export type Controls = DropdownOption[];
export type NormalizedControls = DropdownOption[][];

type DropdownCallbackProps = {
isOpen: boolean;
onToggle: () => void;
Expand Down Expand Up @@ -139,6 +142,5 @@ export type DropdownMenuProps = {
*
* A valid DropdownMenu must specify a `controls` or `children` prop, or both.
*/

controls?: DropdownOption[];
controls?: Controls | NormalizedControls;
};

0 comments on commit 5d317f9

Please sign in to comment.