| 636 | |
| 637 | /** The menu trigger ui pattern class. */ |
| 638 | export class MenuTriggerPattern<V> { |
| 639 | /** Whether the menu trigger is expanded. */ |
| 640 | readonly expanded = signal(false); |
| 641 | |
| 642 | /** Whether the menu trigger has received interaction. */ |
| 643 | readonly hasBeenInteracted = signal(false); |
| 644 | |
| 645 | /** The pending focus target when the menu is opened before the menu instance is available. */ |
| 646 | readonly pendingFocus = signal<'first' | 'last' | undefined>(undefined); |
| 647 | |
| 648 | /** The role of the menu trigger. */ |
| 649 | readonly role = () => 'button'; |
| 650 | |
| 651 | /** Whether the menu trigger has a popup. */ |
| 652 | readonly hasPopup = () => true; |
| 653 | |
| 654 | /** The menu associated with the trigger. */ |
| 655 | readonly menu: SignalLike<MenuPattern<V> | undefined>; |
| 656 | |
| 657 | /** The tab index of the menu trigger. */ |
| 658 | readonly tabIndex = computed(() => |
| 659 | this.expanded() && this.menu()?.inputs.activeItem() ? -1 : 0, |
| 660 | ); |
| 661 | |
| 662 | /** Whether the menu trigger is disabled. */ |
| 663 | readonly disabled = () => this.inputs.disabled(); |
| 664 | |
| 665 | /** Handles keyboard events for the menu trigger. */ |
| 666 | readonly keydownManager = computed(() => { |
| 667 | return new KeyboardEventManager() |
| 668 | .on(' ', () => this.open({first: true})) |
| 669 | .on('Enter', () => this.open({first: true})) |
| 670 | .on('ArrowDown', () => this.open({first: true})) |
| 671 | .on('ArrowUp', () => this.open({last: true})) |
| 672 | .on('Escape', () => this.close({refocus: true})); |
| 673 | }); |
| 674 | |
| 675 | constructor(readonly inputs: MenuTriggerInputs<V>) { |
| 676 | this.menu = this.inputs.menu; |
| 677 | } |
| 678 | |
| 679 | /** Flushes any pending focus when the menu instance becomes available. */ |
| 680 | pendingFocusEffect(): void { |
| 681 | const menu = this.inputs.menu(); |
| 682 | const intent = this.pendingFocus(); |
| 683 | if (menu && intent) { |
| 684 | if (intent === 'first') { |
| 685 | menu.first(); |
| 686 | } else if (intent === 'last') { |
| 687 | menu.last(); |
| 688 | } |
| 689 | this.pendingFocus.set(undefined); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | /** Handles keyboard events for the menu trigger. */ |
| 694 | onKeydown(event: KeyboardEvent) { |
| 695 | if (!this.inputs.disabled()) { |