| 662 | |
| 663 | /** The menu trigger ui pattern class. */ |
| 664 | export class MenuTriggerPattern<V> { |
| 665 | /** Whether the menu trigger is expanded. */ |
| 666 | readonly expanded = signal(false); |
| 667 | |
| 668 | /** Whether the menu trigger has received interaction. */ |
| 669 | readonly hasBeenInteracted = signal(false); |
| 670 | |
| 671 | /** The pending focus target when the menu is opened before the menu instance is available. */ |
| 672 | readonly pendingFocus = signal<'first' | 'last' | undefined>(undefined); |
| 673 | |
| 674 | /** The role of the menu trigger. */ |
| 675 | readonly role = () => 'button'; |
| 676 | |
| 677 | /** Whether the menu trigger has a popup. */ |
| 678 | readonly hasPopup = () => true; |
| 679 | |
| 680 | /** The menu associated with the trigger. */ |
| 681 | readonly menu: SignalLike<MenuPattern<V> | undefined>; |
| 682 | |
| 683 | /** The tab index of the menu trigger. */ |
| 684 | readonly tabIndex = computed(() => |
| 685 | this.expanded() && this.menu()?.inputs.activeItem() ? -1 : 0, |
| 686 | ); |
| 687 | |
| 688 | /** Whether the menu trigger is disabled. */ |
| 689 | readonly disabled = () => this.inputs.disabled(); |
| 690 | |
| 691 | /** Handles keyboard events for the menu trigger. */ |
| 692 | readonly keydownManager = computed(() => { |
| 693 | return new KeyboardEventManager() |
| 694 | .on(' ', () => this.open({first: true})) |
| 695 | .on('Enter', () => this.open({first: true})) |
| 696 | .on('ArrowDown', () => this.open({first: true})) |
| 697 | .on('ArrowUp', () => this.open({last: true})) |
| 698 | .on('Escape', () => this.close({refocus: true})); |
| 699 | }); |
| 700 | |
| 701 | constructor(readonly inputs: MenuTriggerInputs<V>) { |
| 702 | this.menu = this.inputs.menu; |
| 703 | } |
| 704 | |
| 705 | /** Flushes any pending focus when the menu instance becomes available. */ |
| 706 | pendingFocusEffect(): void { |
| 707 | const menu = this.inputs.menu(); |
| 708 | const intent = this.pendingFocus(); |
| 709 | const items = menu?.items(); |
| 710 | |
| 711 | // We check the items so that we don't try calling into |
| 712 | // `first/last` until the items are actually available. |
| 713 | if (menu && intent && items?.length) { |
| 714 | if (intent === 'first') { |
| 715 | menu.first(); |
| 716 | } else if (intent === 'last') { |
| 717 | menu.last(); |
| 718 | } |
| 719 | this.pendingFocus.set(undefined); |
| 720 | } |
| 721 | } |