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