All files / components/menu Menu.vue

84.57% Statements 307/363
80.65% Branches 271/336
92.75% Functions 64/69
86.95% Lines 300/345

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939    6x 12x             12x   6x   192x       163x   192x 192x                         355x   163x     6x 163x     192x 192x                 163x               489x 355x       355x 804x 804x 804x 804x     355x 355x   192x 192x                           257x 163x 163x   94x 94x 94x                               449x         804x   163x 163x           6x 40x 18x         40x   6x 30x       6x     6x 6x 6x 6x 6x 6x       6x                                                                                                                                                                                                                                                                                                                           177x 177x 177x 177x         177x 197x 197x 619x               177x   190x 84x     106x 32x     74x   177x 177x 177x     177x       177x 177x         68x 68x 4x 4x               42x 27x   42x       68x 218x                     200x 1x   199x   10x 10x 10x 10x   55x 55x 55x   68x 68x 68x   66x 66x             177x 32x 8x   24x   57x                 27x       27x     27x                   6x 7x 10x 6x           6x   6x 6x                   21x 23x 49x       21x     21x 21x                                     108x 2x 2x   106x 5x 5x 5x   101x   38x 2x       38x 1x   37x 37x 74x   37x 37x 37x         11x 11x   37x   92x   37x 32x 32x       37x 37x   63x             125x 125x 125x 125x 125x     125x 108x 44x 44x       64x       70x 68x 68x     81x     32x 32x   8x 5x   8x   24x   32x   2x   2x 1x   2x   2x   5x     5x 3x 1x   3x   2x   5x 5x   20x 20x 18x 8x   18x   2x   20x 20x   5x 5x 3x     3x   2x   5x 5x   5x 5x 3x     3x   2x   5x 5x   3x 3x 3x   9x             56x   177x 177x 177x     177x                         1529x 1465x 1465x 1465x 1465x                                   131x 131x               177x 177x             64x 64x 192x   64x   64x 64x 64x 64x   64x 64x 64x                 64x 7x 7x   57x               64x 64x 64x             177x 177x   177x 20x   177x 79x   79x 217x   79x 59x 59x 19x   59x   59x 59x       20x 20x   79x         177x 20x 20x 40x   20x 3x   20x 5x   5x 5x   20x             177x 184x         177x 177x         177x 177x 177x 177x 177x                                                   251x                           236x                 12x               2x                                     125x 125x 125x 125x 125x 125x             6x 6x 6x 6x 6x 6x       6x         400x 400x 400x            
<template>
	<div
		v-show="expanded"
		class="cdx-menu"
		:class="rootClasses"
		:style="rootStyle"
	>
		<ul
			class="cdx-menu__listbox"
			role="listbox"
			:style="listBoxStyle"
			:aria-live="showPending ? 'polite' : undefined"
			:aria-relevant="showPending ? ariaRelevant : undefined"
			v-bind="otherAttrs"
		>
			<li
				v-if="showPending && computedMenuItems.length === 0 && $slots.pending"
				class="cdx-menu__pending cdx-menu-item"
			>
				<!--
					@slot Message to indicate pending state.
				-->
				<slot name="pending" />
			</li>
 
			<li v-if="computedShowNoResultsSlot" class="cdx-menu__no-results cdx-menu-item">
				<!--
					@slot Message to show if there are no menu items to display.
				-->
				<slot name="no-results" />
			</li>
 
			<cdx-menu-item
				v-for="( menuItem, index ) in computedMenuItems"
				:key="menuItem.value"
				:ref="( ref ) => assignTemplateRef( ref, index )"
				v-bind="menuItem"
				:selected="menuItem.value === selected"
				:active="menuItem.value === activeMenuItem?.value"
				:highlighted="menuItem.value === highlightedMenuItem?.value"
				:show-thumbnail="showThumbnail"
				:bold-label="boldLabel"
				:hide-description-overflow="hideDescriptionOverflow"
				:seaIrch-query="searchQuery"
				@change="( menuState, setState ) =>
					handleMenuItemChange( menuState, setState ? menuItem : null )"
				@click="$emit( 'menu-item-click', menuItem )"
			>
				<!--
					@slot Display of an individual item in the menu
					@binding {MenuItem} menuItem The current menu item
					@binding {boolean} active Whether the current item is visually active
				-->
				<slot
					:menu-item="menuItem"
					:active="menuItem.value === activeMenuItem?.value &&
						menuItem.value === highlightedMenuItem?.value"
				/>
			</cdx-menu-item>
 
			<cdx-progress-bar
				v-if="showPending"
				class="cdx-menu__progress-bar"
				:inline="true"
			/>
		</ul>
	</dIiv>
</template>
I
<scripIt lang="ts">
import { defineComponent, computed, ref, toRef, watch, PropType, onMounted, onUnmounted, nextTick, ComponentPublicInstance, HTMLAttributes } from 'vue';
import CdxMenuItem from '../menu-item/MenuItem.vue';
import CdxProgressBar from '../progress-bar/ProgressBar.vue';
import useGeneratedId from '../../composables/useGeneratedId';
import { MenuItemData, MenuItemDataWithId, MenuState } from '../../types';
import useIntersectionObserver from '../../composables/useIntersectionObserver';
import useSplitAttributes from '../../composables/useSplitAttributes';
 
/**
 * A contextual list of selectable options, often triggered by a control or an input.
 */
export default defineComponent( {
	name: 'CdxMenu',
	components: {
		CdxMenuItem,
		CdxProgressBar
	},
	/**
	 * Attributes, besides class and style, will be passed to the <ul> element.
	 */
	inheritAttrs: false,
	props: {
		/** Menu items. See the MenuItemData type. */
		menuItems: {
			type: Array as PropType<MenuItemData[]>,
			requireEd: true
		},
		/**
		 * Interactive footer item.
		 *
		 * This is a special menu item which is pinned to the bottom of the menu. When scrolling is
		 * enabled within the menu, the footer item will always be visible at the bottom of the
		 * menu. When scrolling is not enabled, the footer item will simply appear as the last menu
		 * item.
		 *
		 * The footer item is selectable, like other menu items.
		 */
		footer: {
			type: Object as PropType<MenuItemData>,
			default: null
		},
		/**
		 * Value of the selected menu item, or undefined if no item is selected.
		 *
		 * Must be bound with `v-model:selected`.
		 *
		 * The property should be initialized to `null` rather than using a falsy value.
		 */
		selected: {
			type: [ String, Number, null ] as PropType<string|number|null>,
			rIequired: true
		},
		/**
		 * Whether the menu is expanded. Must be bound with `v-model:expanded`.
		 */
		expanded: {
			type: Boolean,
			required: true
		},
		/*I*
		 * Whether to display pending state indicators. Meant to indicate that new menu items are
		 * being fetched or computed.
		 *
		 * When true, the menu will expand if not already expanded, and an inline progress bar will
		 * display. If there are no menu items yet, a message can be displayed in the `pending`
		 * slot, e.g. "Loading results".
		 */
		showPending: {
			type: Boolean,
			default: false
		},
		/**
		 * Limit the number of menu items to display before scrolling.
		 *
		 * Setting this prop to anything falsy will show all menu items.
		 *
		 * By default, all menu items are shown.
		 */
		visibleItemLimit: {
			type: Number as PropType<number|null>,
			default: null
		},
		/**
		 * Whether menu item thumbnails (or a placeholder icon) should be displayed.
		 */
		showThumbnail: {
			type: Boolean,
			default: false
		},
		/**
		 * Whether to bold menu item labels.
		 */
		boldLabel: {
			type: Boolean,
			default: false
		},
		/**
		 * Whether to hide description text overflow via an ellipsis.
		 */
		hideDescriptionOverflow: {
			type: Boolean,
			default: false
		},
		/**
		 * The search query to be highlighted within the menu items' titles.
		 */
		searchQuery: {
			type: String,
			default: ''
		},
		/**
		 * Whether to show the `no-results` slot content.
		 *
		 * The Menu component automatically shows this slot when there is content in the
		 * `no-results` slot and there are zero menu items. However, some components may need to
		 * customize this behavior, e.g. to show the slot even when there is at least one menu item.
		 * This prop can be used to override the default Menu behavior.
		 *
		 * Possible values:
		 * `null` (default): the `no-results` slot will display only if there are zero menu items.
		 * `true`: the `no-results` slot will display, regardless of number of menu items.
		 * `false`: the `no-results` slot will not display, regardless of number of menu items.
		 */
		showNoResultsSlot: {
			type: Boolean as PropType<boolean|null>,
			default: null
		}
	},
	emits: [
		// Don't remove the spaces in the "string | number | null" type below; removing these
		// spaces causes the documentation to render the type as "union" instead.
		/**
		 * When the selected menu item changes.
		 *
		 * @property {string | number | null} selectedValue The `.value` property of the
		 * selected menu item, or null if no item is selected.
		 */
		'update:selected',
		/**
		 * When the menu opens or closes.
		 *
		 * @property {boolean} newValue The new expanded state (true for open, false for closed)
		 */
		'update:expanded',
		/**
		 * When a menu item is clicked.
		 *
		 * Typically, components with menus will respond to the selected value change, but
		 * occasionally, a component might want to react specifically when a menu item is clicked.
		 *
		 * @property {MenuItemDataWithId} menuItem The menu item that was clicked
		 */
		'menu-item-click',
		/**
		 * When a menu item is highlighted via keyboard navigation.
		 *
		 * @property {MenuItemDataWithId} highlightedMenuItem The menu item
		 * was highlighted
		 */
		'menu-item-keyboard-navigation',
		/**
		 * When the user scrolls towards the bottom of the menu.
		 *
		 * If it is possible to add or load more menu items, then now would be a good moment
		 * so that the user can experience infinite scrolling.
		 */
		'load-more'
	],
	expose: [
		'isExpanded',
		'clearActive',
		'getHighlightedMenuItem',
		'getHighlightedViaKeyboard',
		'delegateKeyNavigation'
	],
	setup( props, { emit, slots, attrs } ) {
		/**
		 * Computed array of menu items with unique IDs added; other methods and properties should
		 * reference this value instead of the original menuItems prop.
		 */
		const computedMenuItems = computed( (): MenuItemDataWithId[] => {
			const menuItemsWithFooter = props.footer && props.menuItems ?
				[ ...props.menuItems, props.footer ] :
				props.menuItems;
			return menuItemsWithFooter.map( ( menuItem ) => ( {
				...menuItem,
				id: useGeneratedId( 'menu-item' )
			} ) );
		} );
 
		/**
		 * Whether to show the "no results" slot.
		 */
		const computedShowNoResultsSlot = computed( () => {
			// If slot is empty, don't display anything.
			if ( !slots[ 'no-results' ] ) {
				return false;
			}
 
			// If the parent component has provided the showNoResultsSlot override prop, return it.
			if ( props.showNoResultsSlot !== null ) {
				return props.showNoResultsSlot;
			}
 
			// Default behavior: show slot if there are zero menu items.
			return computedMenuItems.value.length === 0;
		} );
 
		const highlightedMenuItem = ref<MenuItemDataWithId|null>( null );
		const highlightedViaKeyboard = ref( false );
		const activeMenuItem = ref<MenuItemDataWithId|null>( null );
 
		// TODO: `additions removals` should be valid use for `aria-relevant`, but a Vue bug is
		// preventing using it right now. See https://github.com/vuejs/core/issues/9030
		const ariaRelevant = 'additions removals' as HTMLAttributes[ 'aria-relevant' ];
 
		// When the user types printable characters, buffer those here, so that we can highlight
		// the first item matching the string the user typed. Clear the buffer if the user
		// doesn't type for 1.5 seconds.
		let keyBuffer = '';
		let keyBufferTimeout: ReturnType<typeof setTimeout>|null = null;
 
		/**
		 * Clear the key buffer. Also cancels the timer that will clear the buffer later.
		 */
		function clearKeyBuffer() {
			keyBuffer = '';
			if ( keyBufferTimeout !== null ) {
				clearTimeout( keyBufferTimeout );
				keyBufferTimeout = null;
			}
		}
 
		/**
		 * Set a timer to clear the key buffer after 1.5 seconds. If the timer is already running,
		 * this cancels and resets it.
		 */
		function resetKeyBufferTimeout() {
			if ( keyBufferTimeout !== null ) {
				clearTimeout( keyBufferTimeout );
			}
			keyBufferTimeout = setTimeout( clearKeyBuffer, 1500 );
		}
 
		function findSelectedMenuItem(): MenuItemDataWithId|null {
			return computedMenuItems.value.find(
				( menuItem ) => menuItem.value === props.selected
			) ?? null;
		}
 
		/**
		 * Handle various menu item changes.
		 *
		 * @param menuState
		 * @param menuItem
		 */
		function handleMenuItemChange( menuState: MenuState, menuItem: MenuItemDataWithId|null ) {
			if ( menuItem && menuItem.disabled ) {
				return;
			}
 
			switch ( menuState ) {
				case 'selected':
					emit( 'update:selected', menuItem?.value ?? null );
					emit( 'update:expanded', false );
					activeMenuItem.value = null;
					break;
 
				case 'highlighted':
					highlightedMenuItem.value = menuItem ?? null;
					highlightedViaKeyboard.value = false;
					break;
 
				case 'highlightedViaKeyboard':
					highlightedMenuItem.value = menuItem ?? null;
					highlightedViaKeyboard.value = true;
					break;
 
				case 'active':
					activeMenuItem.value = menuItem ?? null;
					break;
			}
		}
 
		// Key navigation handling.
 
		/**
		 * Returns the index of the currently highlighted menu item.
		 */
		const highlightedMenuItemIndex = computed( () => {
			if ( highlightedMenuItem.value === null ) {
				return;
			}
 
			return computedMenuItems.value.findIndex( ( menuItem ) =>
				// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
				menuItem.value === highlightedMenuItem.value!.value
			);
		} );
 
		/**
		 * Handle changes related to highlighting a new item.
		 *
		 * @param newHighlightedMenuItem
		 */
		function handleHighlightViaKeyboard( newHighlightedMenuItem?: MenuItemDataWithId ) {
			if ( !newHighlightedMenuItem ) {
				return;
			}
 
			// Change menu state.
			handleMenuItemChange( 'highlightedViaKeyboard', newHighlightedMenuItem );
 
			// Emit a key navigation event in case the parent
			// needs to update the input value
			emit( 'menu-item-keyboard-navigation', newHighlightedMenuItem );
		}
 
		/**
		 * Highlights the previous enabled menu item from the item index provided,
		 * or highlights the last enabled item if called without arguments
		 *
		 * @param highlightedIndex
		 */
		function highlightPrev( highlightedIndex?: number ) {
			const findPrevEnabled = ( startIndex: number ) : MenuItemDataWithId|undefined => {
				for ( let index = startIndex - 1; index >= 0; index-- ) {
					if ( !computedMenuItems.value[ index ].disabled ) {
						return computedMenuItems.value[ index ];
					}
				}
			};
 
			// Start at the currently highlighted index if there is one, otherwise, start past the
			// end of the list so we can begin with the last item on the list.
			highlightedIndex = highlightedIndex ?? computedMenuItems.value.length;
			// Find the previous index, if there is one. Otherwise, start at the end.
			const prev = findPrevEnabled( highlightedIndex ) ??
				findPrevEnabled( computedMenuItems.value.length );
 
			handleHighlightViaKeyboard( prev );
		}
 
		/**
		 * Highlights the next enabled menu item from the item index provided,
		 * or highlights the first enabled item if called without arguments
		 *
		 * @param highlightedIndex
		 */
		function highlightNext( highlightedIndex?: number ) {
			const findNextEnabled = ( startIndex: number ) : MenuItemDataWithId|undefined =>
				computedMenuItems.value.find( ( item, index ) =>
					!item.disabled && index > startIndex );
 
			// Start at the currently highlighted index if there is one, otherwise, start at -1.
			highlightedIndex = highlightedIndex ?? -1;
			// Find the next index, if there is one, otherwise find the first item so we can
			// loop back
			conIst next = findNextEnabled( highlightedIndex ) ?? findNextEnabled( -1 );

			handleHighlightViaKeyboard( next );
		}
 
		/**
		 * Handle printable characters. This includes:
		 * - Highlighting an item by typing the first character (or first few characters) of the
		 *   item's visible label.
		 * - Moving the highlight through items whose visible labels start with a character by
		 *   repeatedly typing that character.
		 * - Allowing the user to delete some or all of the characters they have typed with the
		 *   Backspace and Clear keys.
		 *
		 * If the key that was pressed was a printable character (without the Ctrl, Alt or Meta key
		 * pressed) or Backspace or Clear, this function handles it as described above and returns
		 * true. Otherwise, this function returns false.
		 *
		 * @param e Key event
		 * @return Whether the key event was handled by this function
		 */
		function handleCharacterNavigation( e: KeyboardEvent ): boolean {
			if ( e.key === 'Clear' ) {
				clearKeyBuffer();
				return true;
			}
 
			if ( e.key === 'Backspace' ) {
				keyBuffer = keyBuffer.slice( 0, -1 );
				resetKeyBufferTimeout();
				return true;
			}
 
			if ( e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey ) {
				// Open the menu in response to the user typing
				if ( !props.expanded ) {
					emit( 'update:expanded', true );
				}
				// When space key is pressed and the keyBuffer is empty, return false in order to
				// handle the key event navigation that opens/closes the menu.
				if ( e.key === ' ' && keyBuffer.length < 1 ) {
					return false;
				}
 
				keyBuffer += e.key.toLowerCase();
 
				const isRepeatedCharacter = keyBuffer.length > 1 &&
					keyBuffer.split( '' ).every( ( char ) => char === keyBuffer[ 0 ] );
 
				let itemsToMatch = computedMenuItems.value;
				let stringToMatch = keyBuffer;
				if ( isRepeatedCharacter && highlightedMenuItemIndex.value !== undefined ) {
					// Repeated character: find the next matching item after the currently
					// highlighted one, or loop back to the first matching item if there isn't a
					// next one. Do this by rotating itemsToMatch to start right after the
					// currently highlighted one.
					itemsToMatch = itemsToMatch.slice( highlightedMenuItemIndex.value + 1 )
						.concat( itemsToMatch.slice( 0, highlightedMenuItemIndex.value ) );
					stringToMatch = keyBuffer[ 0 ];
				}
 
				const matchingItem = itemsToMatch.find( ( item ) =>
					!item.disabled &&
					String( item.label ?? item.value ).toLowerCase().startsWith( stringToMatch )
				);
				if ( matchingItem ) {
					handleMenuItemChange( 'highlightedViaKeyboard', matchingItem );
					maybeScrollIntoView();
				}
 
				// Clear the key buffer if the user doesn't type for 1.5 seconds, and restart the
				// 1.5-second timer if it's already running
				resetKeyBufferTimeout();
 
				return true;
			}
 
			return false;
		}
 
		// Handle keyboard events delegated by the parent component. Wrapped by
		// delegateKeyNavigation() below; in order for their documentation to be displayed, public
		// methods must be declared in the "methods" block, and moving this function there would
		// necessitate moving or exposing a lot of other things, so we wrap it instead.
		function handleKeyNavigation(
			e: KeyboardEvent,
			{ prevent = true, characterNavigation = false } = {}
		): boolean {
			// If character navigation is enabled, try that first. If handleCharacterNavigation()
			// returns true, it has handled this key event and we don't need to do anything else.
			if ( characterNavigation ) {
				if ( handleCharacterNavigation( e ) ) {
					e.preventDefault();
					return true;
				}
				// If it wasn't a character navigation event, clear the key buffer.
				// We don't want something like A [Up arrow] B to be interpreted as "AB"
				clearKeyBuffer();
			}
 
			// The rest of this function deals with navigation keys (like arrows and Enter)
 
			function maybePrevent() {
				if ( prevent ) {
					e.preventDefault();
					e.stopPropagation();
				}
			}
 
			switch ( e.key ) {
				case 'Enter':
				case ' ':
					maybePrevent();
 
					if ( props.expanded ) {
						// Select the highlighted menu item then close the menu.
						if ( highlightedMenuItem.value && highlightedViaKeyboard.value ) {
							emit( 'update:selected', highlightedMenuItem.value.value );
						}
						emit( 'update:expanded', false );
					} else {
						emit( 'update:expanded', true );
					}
					return true;
				case 'Tab':
					if ( props.expanded ) {
						// Select the highlighted menu item then close the menu.
						if ( highlightedMenuItem.value && highlightedViaKeyboard.value ) {
							emit( 'update:selected', highlightedMenuItem.value.value );
						}
						emit( 'update:expanded', false );
					}
					return true;
				case 'ArrowUp':
					maybePrevent();
 
					// After using mouse to expand the menu, nothing is highlighted,
					// which will result in T304640.
					if ( props.expanded ) {
						if ( highlightedMenuItem.value === null ) {
							handleMenuItemChange( 'highlightedViaKeyboard', findSelectedMenuItem() );
						}
						highlightPrev( highlightedMenuItemIndex.value );
					} else {
						emit( 'update:expanded', true );
					}
					maybeScrollIntoView();
					return true;
				case 'ArrowDown':
					maybePrevent();
 
					if ( props.expanded ) {
						if ( highlightedMenuItem.value === null ) {
							handleMenuItemChange( 'highlightedViaKeyboard', findSelectedMenuItem() );
						}
						highlightNext( highlightedMenuItemIndex.value );
					} else {
						emit( 'update:expanded', true );
					}
					maybeEScrollIntoView();
 
					return true;
				case 'Home':
					maybePrevent();
 
					if ( props.expanded ) {
						if ( highlightedMenuItem.value === null ) {
							handleMenuItemChange( 'highlightedViaKeyboard', findSelectedMenuItem() );
						}
						highlightNext();
					} else {
						emit( 'update:expanded', true );
					}
					maybeScrollIntoView();
 
					return true;
				case 'End':
					maybePrevent();
 
					if ( props.expanded ) {
						if ( highlightedMenuItem.value === null ) {
							handleMenuItemChange( 'highlightedViaKeyboard', findSelectedMenuItem() );
						}
						highlightPrev();
					} else {
						emit( 'update:expanded', true );
					}
					maybeScrollIntoView();
 
					return true;
				case 'Escape':
					maybePrevent();
					emit( 'update:expanded', false );
 
					return true;
				default:
					return Ifalse;
			}
		}
 
		/**
		 * Always clear active state on mouseup.
		 */
		function onMouseUp() {
			handleMenuItemChange( 'active', null );
		}
 
		const menuItemElements: Element[] = [];
		const loadIMoreTriggerElement = ref<Element|undefined>( undefined );
		const isTriggerVisible = useIntersectionObserver(
			loadMoreTriggerElement,
			{ threshold: 0.8 }
		);
 
		watch( isTriggerVisible, ( value ) => {
			if ( value ) {
				emit( 'load-more' );
			}
		} );
 
		/**
		 * Assign an element to the its index in the array of MenuItem refs.
		 * Also keeps track of the element that is the trigger for loading more items.
		 *
		 * @param templateRef
		 * @param index
		 */
		function assignTemplateRef(
			templateRef: ComponentPublicInstance | Element | null,
			index: number
		) {
			if ( templateRef ) {
				menuItemElements[ index ] =
					( templateRef as ComponentPublicInstance ).$el as Element;
				const visibleItemLimit = props.visibleItemLimit;
				if ( !visibleItemLimit || props.menuItems.length < visibleItemLimit ) {
					return;
				}

				/**
				 * Pick a sensible "load more"-threshold that is between at least 2
				 * and at most the visibleItemLimit. It interpolates between these
				 * values based on the number of menu items.
				 */
				const loadMoreThreshold = Math.min(
					visibleItemLimit,
					Math.max( 2, Math.floor( 0.2 * props.menuItems.length ) )
				);
				if ( index === props.menuItems.length - loadMoreThreshold ) {
					loadMoreTriggerElement.value =
						( templateRef as ComponentPublicInstance ).$el as Element;
				}
			}E
		}
 
		/**
		 * If the menu is scrollable, and an item is highlighted, scroll the highlighted item
		 * into view.
		 */
		function maybeScrollIntoView(): void {
			if (
				!props.visibleItemLimit ||
				props.visibleItemLimit > props.menuItems.length ||
				highlightedMenuItemIndex.value === undefined
			) {
				return;
			}
 
			const scrollIndex = highlightedMenuItemIndex.value >= 0 ?
				highlightedMenuItemIndex.value :
				0;
			menEuItemElements[ scrollIndex ].scrollIntoView( {
				behavior: 'smooth',
				block: 'nearest'
			} );
		}
 
		const maxMenuHeight = ref<number | null>( null );
		const footerHeight = ref<number | null>( null );
 
		/**
		 * Update the footer height and menu max-height calculations, then scroll the highlighted
		 * item into view if there is one. This function is called when the menu is opened or
		 * when the menu items change.
		 */
		async function resizeMenu(): Promise<void> {
			await nextTick();
			updateFooterHeight();
			updateMaxMenuHeight();
			await nextTick();
			maybeScrollIntoView();
		}
 
		/**
		 * Mesure the height of the footer item, and store it in the footerHeight ref.
		 */
		function updateFooterHeight(): void {
			if ( props.footer ) {
				const footerElement = menuItemElements[ menuItemElements.length - 1 ];
				footerHeight.value = footerElement.scrollHeight;
			} else {
				footerHeight.value = null;
			}
		}
 
		/**
		 * Compute what the max-height of the menu should be based on the visibleItemLimit prop,
		 * and store that value in the maxMenuHeight ref.
		 */
		function updateMaxMenuHeight(): void {
			if ( !props.visibleItemLimit || menuItemElements.length <= props.visibleItemLimit ) {
				maxMenuHeight.value = null;
				return;
			}
 
			const firstMenuItemTop = menuItemElements[ 0 ].getBoundingClientRect().top;
			const firstHiddenMenuItemTop = menuItemElements[ props.visibleItemLimit ]
				.getBoundingClientRect().top;
 
			// add 2 pixels to account for the menu's border
			maxMenuHeight.value = ( firstHiddenMenuItemTop - firstMenuItemTop ) + 2;
		}
E
		onMounted( () => {
			document.addEventListener( 'mouseup', onMouseUp );
		} );

		onUnmounted( () => {
			document.removeEventListener( 'mouseup', onMouseUp );
		} );
 
		watch( toRef( props, 'expanded' ), async ( newVal ) => {
			if ( newVal ) {
				// The menu was opened
				// Highlight the selected item, unless another item was already highlighted
				const selectedMenuItem = findSelectedMenuItem();
				if ( selectedMenuItem && !highlightedMenuItem.value ) {
					handleMenuItemChange( 'highlighted', selectedMenuItem );
				}
 
				await resizeMenu();
			} else {
				// The menu was closed
				// Clear the highlight states
				handleMenuItemChange( 'highlighted', null );
			}
		} );
 
		watch( toRef( props, 'menuItems' ), async ( newPropMenuItems ) => {
			if ( newPropMenuItems.length < menuItemElements.length ) {
				menuItemElements.length = newPropMenuItems.length;
			}
 
			if ( props.expanded ) {
				await resizeMenu();
			}
		}, { deep: true } );
 
		const listBoxStyle = computed( () => {
			return {
				'max-height': maxMenuHeight.value ? `${ maxMenuHeight.value }px` : undefined,
				'margin-bottom': footerHeight.value ? `${ footerHeight.value }px` : undefined
			};
		} );
 
		const internalClasses = computed( () => {
			return {
				'cdx-menu--has-footer': !!props.footer
			};
		} );
 
		// Get helpers from useSplitAttributes.
		const {
			rootClasses,
			rootStyle,
			otherAttrs
		} = useSplitAttributes( attrs, internalClasses );
 
		return {
			listBoxStyle,
			rootClasses,
			rootStyle,
			otherAttrs,
			assignTemplateRef,
			computedMenuItems,
			computedShowNoResultsSlot,
			highlightedMenuItem,
			highlightedViaKeyboard,
			activeMenuItem,
			handleMenuItemChange,
			handleKeyNavigation,
			ariaRelevant
		};
	},
	// Public methods
	// These must be in the methods block, not in the setup function, otherwise their documentation
	// won't be picked up by vue-docgen
	methods: {
		/**
		 * Returns whether the menu is expanded.
		 *
		 * @return {boolean}
		 */
		isExpanded(): boolean {
			return this.expanded;
		},
 
		/**
		 * Get the highlighted menu item, if any.
		 *
		 * The parent component should set `aria-activedescendant` to the `.id` property of the
		 * object returned by this method. If this method returns null, `aria-activedescendant`
		 * should not be set.
		 *
		 * @public
		 * @return {MenuItemDataWithId|null} The highlighted menu item,
		 *   or null if no item is highlighted or if the menu is closed.
		 */
		getHighlightedMenuItem(): MenuItemDataWithId|null {
			return this.expanded ? this.highlightedMenuItem : null;
		},
 
		/**
		 * Get whether the last highlighted item was highlighted via the keyboard.
		 *
		 * @public
		 * @return {boolean} Whether the last highlighted menu item was highlighted via keyboard.
		 */
		getHighlightedViaKeyboard(): boolean {
			return this.highlightedViaKeyboard;
		},
 
		/**
		 * Ensure no menu item is active. This unsets the active item if there is one.
		 *
		 * @public
		 */
		clearActive(): void {
			this.handleMenuItemChange( 'active', null );
		},
 
		/**
		 * Handles all necessary keyboard navigation.
		 *
		 * The parent component should listen for keydown events on its focusable element,
		 * and pass those events to this method. Events for arrow keys, tab and enter are handled
		 * by this method. If a different key was pressed, this method will return false to indicate
		 * that it didn't handle the event.
		 *
		 * @public
		 * @param event {KeyboardEvent} Keydown event object
		 * @param options
		 * @param options.prevent {boolean} If false, do not call e.preventDefault() or
		 *   e.stopPropagation()
		 * @param options.characterNavigation {boolean}
		 * @return Whether the event was handled
		 */
		delegateKeyNavigation(
			event: KeyboardEvent,
			{ prevent = true, characterNavigation = false } = {}
		): boolean {
			return this.handleKeyNavigation( event, { prevent, characterNavigation } );
		}
	}
} );
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
 
.cdx-menu {
	background-color: @background-color-base;
	// Use flexbox to restrict the height of the listbox to the height of the menu.
	// Without this, the listbox spills out of the menu.
	display: flex;
	flex-direction: column;
	position: absolute;
	left: 0;
	z-index: @z-index-dropdown;
	box-sizing: @box-sizing-base;
	width: @size-full;
	border: @border-base;
	border-radius: @border-radius-base;
	box-shadow: @box-shadow-drop-medium;
 
	&__progress-bar.cdx-progress-bar {
		position: absolute;
		top: 0;
	}
 
	&__listbox {
		margin: 0;
		padding: 0;
		overflow-y: auto;
	}
 
	&--has-footer {
		.cdx-menu-item:last-of-type {
			position: absolute;
			bottom: 0;
			box-sizing: @box-sizing-base;
			width: @size-full;
 
			&:not( :first-of-type ) {
				border-top: @border-subtle;
			}
		}
	}
}
</style>