The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { MenuAction } from "@react-native-menu/menu"; |
| 2 | import type { AppBarMenuItem } from "./AppBar.types"; |
| 3 | |
| 4 | /** Adapts a `MenuAction` tree and its selection handler to `AppBar` menu items. */ |
| 5 | export function appBarMenuItemsFromActions( |
| 6 | actions: ReadonlyArray<MenuAction>, |
| 7 | onSelect: (id: string) => void, |
| 8 | ): AppBarMenuItem[] { |
| 9 | return actions.map((action, index) => { |
| 10 | const id = action.id ?? String(index); |
| 11 | return action.subactions?.length |
| 12 | ? { |
| 13 | id, |
| 14 | title: action.title, |
| 15 | icon: action.image, |
| 16 | items: appBarMenuItemsFromActions(action.subactions, onSelect), |
| 17 | } |
| 18 | : { |
| 19 | id, |
| 20 | title: action.title, |
| 21 | subtitle: action.subtitle, |
| 22 | icon: action.image, |
| 23 | iconColor: action.imageColor, |
| 24 | selected: action.state === "on", |
| 25 | disabled: action.attributes?.disabled, |
| 26 | onPress: () => onSelect(id), |
| 27 | }; |
| 28 | }); |
| 29 | } |
| 30 | |
| 31 | /** Adapts `AppBar` menu items to a `Menu`'s actions; `findAppBarMenuItem` resolves a selection. */ |
| 32 | export function menuActionsFromAppBarItems(items: ReadonlyArray<AppBarMenuItem>): MenuAction[] { |
| 33 | return items.flatMap((item): MenuAction[] => |
| 34 | "items" in item |
| 35 | ? item.inline && !item.title |
| 36 | ? menuActionsFromAppBarItems(item.items) |
| 37 | : [ |
| 38 | { |
| 39 | id: item.id, |
| 40 | title: item.title ?? "", |
| 41 | image: item.icon, |
| 42 | displayInline: item.inline, |
| 43 | subactions: menuActionsFromAppBarItems(item.items), |
| 44 | }, |
| 45 | ] |
| 46 | : [ |
| 47 | { |
| 48 | id: item.id, |
| 49 | title: item.title, |
| 50 | subtitle: item.subtitle, |
| 51 | image: item.icon, |
| 52 | imageColor: item.iconColor, |
| 53 | state: item.selected ? "on" : undefined, |
| 54 | attributes: |
| 55 | item.disabled || item.destructive |
| 56 | ? { disabled: item.disabled, destructive: item.destructive } |
| 57 | : undefined, |
| 58 | }, |
| 59 | ], |
| 60 | ); |
| 61 | } |
| 62 | |
| 63 | export function findAppBarMenuItem( |
| 64 | items: ReadonlyArray<AppBarMenuItem>, |
| 65 | id: string, |
| 66 | ): Extract<AppBarMenuItem, { readonly onPress: () => void }> | undefined { |
| 67 | for (const item of items) { |
| 68 | if ("items" in item) { |
| 69 | const action = findAppBarMenuItem(item.items, id); |
| 70 | if (action) return action; |
| 71 | } else if (item.id === id) { |
| 72 | return item; |
| 73 | } |
| 74 | } |
| 75 | return undefined; |
| 76 | } |