All files / components/lookup Lookup.vue

97.82% Statements 90/92
91.42% Branches 64/70
90.47% Functions 19/21
97.82% Lines 90/92

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    1x 7x       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x                                                                                                     39x                                                                                                     39x 39x 39x   39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 16x 14x     39x   89x     39x 39x 50x           39x 39x 39x 39x               13x 4x       13x 5x 5x     8x   13x               8x     8x     8x     8x 3x   8x               2x 2x 2x                           5x 3x   2x   39x   39x     4x     4x 4x   4x   4x             39x   7x           1x     7x 1x     7x   39x                                       1x 1x 1x 1x   70x 70x 70x               13x                       1x                     2x           132x 132x         37x               1x 1x                                                                                                                
<template>
	<div
		ref="rootElement"
		class="cdx-lookup"
		:class="rootClasses"
		:style="rootStyle"
	>
		<cdx-text-input
			ref="textInput"
			v-model="inputValue"
			v-bind="otherAttrs"
			class="cdx-lookup__input"
			role="combobox"
			autocomplete="off"
			aria-autocomplete="list"
			:aria-controls="menuId"
			:aria-expanded="expanded"
			:aria-activedescendant="highlightedId"
			:disabled="computedDisabled"
			:status="status"
			@update:model-value="onUpdateInput"
			@change="$event => $emit( 'change', $event )"
			@focus="onInputFocus"
			@blur="onInputBlur"
			@keydown="onKeydown"
		/>
 
		<cdx-menu
			:id="menuId"
			ref="menu"
			v-model:selected="modelWrapper"
			v-model:expanded="expanded"
			:menu-items="menuItems"
			v-bind="menuConfig"
			@load-more="$emit( 'load-more' )"
		>
			<template #default="{ menuItem }">
				<!--
					@slot Display of an individual item in the menu
					@binding {MenuItemData} menu-item The current menu item
				-->
				<slot name="menu-item" :menu-item="menuItem" />
			</template>
 
			<template #no-results>
				<!--
					@slot Message to show if there are no results to display.
				-->
				<slot name="no-results" />
			</template>
		</cdx-menu>
	</div>
</template>
 
<script lang="ts">
import {
	defineComponent,
	PropType,
	Ref,
	ComponentPublicInstance,
	ref,
	toRef,
	computed,
	watch
} from 'vue';
 
import CdxMenu from '../menu/Menu.vue';
import CdxTextInput from '../text-input/TextInput.vue';
 
import useGeneratedId from '../../composables/useGeneratedId';
import useModelWrapper from '../../composables/useModelWrapper';
import useSplitAttributes from '../../composables/useSplitAttributes';
import useFieldData from '../../composables/useFieldData';
import useFloatingMenu from '../../composables/useFloatingMenu';
 
import { MenuItemData, MenuConfig, ValidationStatusType } from '../../types';
import { ValidationStatusTypes } from '../../constants';
import { makeStringTypeValidator } from '../../utils/stringTypeValidator';
 
const statusValidator = makeStringTypeValidator( ValidationStatusTypes );
 
/**
 * A predictive text input with a dropdown menu of items.
 */
export default defineComponent( {
	name: 'CdxLookup',
 
	components: {
		CdxMenu,
		CdxTextInput
	},
 
	/**
	 * We want the input to inherit attributes, not the root element.
	 */
	inheritAttrs: false,
 
	props: {
		/**
		 * Value of the current selection.
		 *
		 * 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>,
			required: true
		},
 
		/**
		 * Menu items.
		 */
		menuItems: {
			type: Array as PropType<MenuItemData[]>,
			required: true
		},
 
		/**
		 * Initial value of the text input.
		 */
		initialInputValue: {
			type: [ String, Number ] as PropType<string|number>,
			default: ''
		},
 
		/**
		 * Whether the entire component is disabled.
		 */
		disabled: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Configuration for various menu features. All properties default to false.
		 *
		 * See the MenuConfig type.
		 */
		menuConfig: {
			type: Object as PropType<MenuConfig>,
			default: () => {
				return {} as MenuConfig;
			}
		},
		/**
		 * `status` property of the TextInput component
		 */
		status: {
			type: String as PropType<ValidationStatusType>,
			default: 'default',
			validator: statusValidator
		}
	},
 
	emits: [
		/**
		 * When the selected value changes.
		 *
		 * @property {string | number | null} selected The new selected value
		 */
		'update:selected',
		/**
		 * 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',
		/**
		 * When the text input value changes.
		 *
		 * @property {string | number} value The new value
		 */
		'input',
		/**
		 * When an input value change is committed by the user (e.g. on blur)
		 *
		 * @property {Event} event
		 */
		'change',
		/**
		 * When the input comes into focus
		 *
		 * @property {FocusEvent} event
		 */
		'focus',
		/**
		 * When the input loses focus
		 *
		 * @property {FocusEvent} event
		 */
		'blur'
	],
 
	setup: ( props, { emit, attrs, slots } ) => {
		// Set up local reactive data
		const rootElement = ref<HTMLDivElement>();
		const textInput = ref<InstanceType<typeof CdxTextInput>>();
		const menu = ref<InstanceType<typeof CdxMenu>>();
		const menuId = useGeneratedId( 'lookup-menu' );
		const pending = ref( false );
		const expanded = ref( false );
		const isActive = ref( false );
		const initialMenuItems = ref( props.menuItems );
 
		const { computedDisabled } = useFieldData( toRef( props, 'disabled' ) );
 
		const selectedProp = toRef( props, 'selected' );
		const modelWrapper = useModelWrapper( selectedProp, emit, 'update:selected' );
		const selectedMenuItem = computed( () =>
			props.menuItems.find( ( item ) => item.value === props.selected )
		);
		const highlightedId = computed( () => menu.value?.getHighlightedMenuItem()?.id );
 
		// This should not be reactive, so we just read the initial value.
		const inputValue = ref( props.initialInputValue );
 
		const internalClasses = computed( () => {
			return {
				'cdx-lookup--disabled': computedDisabled.value,
				'cdx-lookup--pending': pending.value
			};
		} );
 
		// Get helpers from useSplitAttributes.
		const {
			rootClasses,
			rootStyle,
			otherAttrs
		} = useSplitAttributes( attrs, internalClasses );
 
		/**
		 * Handle TextInput model value changes.
		 *
		 * @param newVal
		 */E
		function onUpdateInput( newVal: string|number ) {
			// If there is a selection and it doesn't match the new value, clear it.
			if (
				seleEctedMenuItem.value &&
				selectedMenuItem.value.label !== newVal &&
				selectedMenuItem.value.value !== newVal
			) {
				modelWrapper.value = null;
			}
 
			// If the input is cleared, close the menu (unless there were initial menu items, as
			// the parent component may want to show them again when the input is cleared.
			if ( newVal === '' && initialMenuItems.value.length === 0 ) {
				expanded.value = false;
				pending.value = false;
			} else {
				// If there is a value, set pending to true.
				pending.value = true;
			}
 
			emit( 'input', newVal );
		}
 
		/**
		 * On focus, maybe open the menu.
		 *
		 * @param event The focus event
		 */
		function onInputFocus( event: FocusEvent ) {
			isActive.value = true;
			// One reason to open the menu on focus is if there is input (i.e. the input value is
			// not null nor an empty string). Store whether this is the case in this variable.
			const hasInput = inputValue.value !== null && inputValue.value !== '';
			// Another reason to open the menu on focus is if there are either menu items to show
			// or a "no results" message. Store whether this is the case in this variable.
			const hasMenuItems = !!( props.menuItems.length > 0 || slots[ 'no-results' ] );
			// The menu is open on focus when there are menu items and either an input value or
			// initial menu items passed in, e.g. suggested options.
			if ( hasMenuItems && ( hasInput || initialMenuItems.value.length > 0 ) ) {
				expanded.value = true;
			}
 
			emit( 'focus', event );
		}
 
		/**
		 * On blur, close the menu
		 *
		 * @param event The focus event
		 */
		function onInputBlur( event: FocusEvent ) {
			isActive.value = false;
			expanded.value = false;
			emit( 'blur', event );
		}
 
		/**
		 * Conditionally handle key navigation of the menu.
		 *
		 * For this component, the user should only be able to use key navigation to open the menu
		 * if there are menu items (or no-results slot content) to display.
		 *
		 * The space key should always do its default function of adding a space character,
		 * and doesn't open the menu.
		 *
		 * @param e
		 */
		function onKeydown( e: KeyboardEvent ) {
			if ( !menu.value ||
				computedDisabled.value ||
				props.menuItems.length === 0 && !slots[ 'no-results' ] ||
				e.key === ' ' ) {
				return;
			}
			menu.value.delegateKeyNavigation( e );
		}
 
		useFloatingMenu( textInput as Ref<ComponentPublicInstance>, menu );
 
		// When a new value is selected, update the input value to match.
		watch( selectedProp, ( newVal ) => {
			// If there is a newVal, including an empty string...
			if ( newVal !== null ) {
				// If there is a menu item selected, use the label (or the value, if there is no
				// label). Otherwise, use an empty string.
				const selectedValue = selectedMenuItem.value ?
					( selectedMenuItem.value.label ?? selectedMenuItem.value.value ) :
					'';
 
				if ( inputValue.value !== selectedValue ) {
					// Make sure that the input matches what was selected
					inputValue.value = selectedValue;

					// We emit the new value to make sure that the menu is filtered correctly
					emit( 'input', inputValue.value );
				}
			}
		} );
 
		// When the menu items change, maybe show the menu.
		// This is the main method of opening the menu of the Lookup component, since showing
		// the menu depends mostly on whether there are any items to show.
		watch( toRef( props, 'menuItems' ), ( newVal ) => {
			// Show the menu under certain conditions.
			if (
				// Only show the menu if we were in the pending state (meaning this menuItems change
				// was in response to user input) and the menu is still focused
				isActive.value && pending.value && (
					// Show the menu if there are either menu items or no-results content to show
					newVal.length > 0 || slots[ 'no-results' ]
				)
			) {
				expanded.value = true;
			}
 
			// Hide the menu if there are no menu items and no no-results content
			if ( newVal.length === 0 && !slots[ 'no-results' ] ) {
				expanded.value = false;
			}
 
			// Clear the pending state
			pending.value = false;
		} );
 
		return {
			rootElement,
			textInput,
			menu,
			menuId,
			highlightedId,
			inputValue,
			modelWrapper,
			expanded,
			computedDisabled,
			onInputBlur,
			rootClasses,
			rootStyle,
			otherAttrs,
			onUpdateInput,
			onInputFocus,
			onKeydown
		};
	}
} );
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
@import ( reference ) '../../themes/mixins/pending-state.less';
 
.cdx-lookup {
	position: relative;
	box-sizing: @box-sizing-base;
	vertical-align: middle;
 
	&--pending .cdx-text-input .cdx-text-input__input {
		.cdx-mixin-pending-state();
	}
 
	// Overrides when used within a Dialog component
	.cdx-dialog & {
		// The menu is positioned relative to the dialog backdrop, not the triggering element.
		position: static;
	}
}
</style>