All files / components/combobox Combobox.vue

96.29% Statements 78/81
88.23% Branches 45/51
95.23% Functions 20/21
96.29% Lines 78/81

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    1x 9x       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x                                                                                         20x                                                                                                     20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x   51x   20x 20x 31x           20x 20x 20x 20x                   9x 1x 8x 6x   9x                   2x 2x               2x     2x                 5x     5x     3x 2x   1x   20x         20x 11x   20x                                         1x 1x 1x 1x 1x         31x 31x 31x 31x 31x               2x                     1x 1x                           40x                         2x   3x           100x 100x         6x               1x 1x                                                                                                                                      
<template>
	<div
		class="cdx-combobox"
		:class="rootClasses"
		:style="rootStyle"
	>
		<div ref="inputWrapper" class="cdx-combobox__input-wrapper">
			<cdx-text-input
				ref="input"
				v-model="modelWrapper"
				v-bind="otherAttrs"
				class="cdx-combobox__input"
				:aria-activedescendant="highlightedId"
				:aria-expanded="expanded"
				:aria-controls="menuId"
				:disabled="computedDisabled"
				:status="status"
				autocomplete="off"
				role="combobox"
				@keydown="onKeydown"
				@input="$event => $emit( 'input', $event )"
				@change="$event => $emit( 'change', $event )"
				@focus="onInputFocus"
				@blur="onInputBlur"
			/>
 
			<!-- Button is only useful for mouse/touch users, hence skipping it for keyboard
				(`tabindex="-1"`) and assistive technology users (`aria-hidden="true"`). -->
			<cdx-button
				class="cdx-combobox__expand-button"
				aria-hidden="true"
				:disabled="computedDisabled"
				tabindex="-1"
				type="button"
				@mousedown="onButtonMousedown"
				@click="onButtonClick"
			>
				<cdx-icon
					class="cdx-combobox__expand-icon"
					:icon="cdxIconExpand"
				/>
			</cdx-button>
		</div>
 
		<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 menu items to display.
				-->
				<slot name="no-results" />
			</template>
		</cdx-menu>
	</div>
</template>
 
<script lang="ts">
import {
	PropType,
	Ref,
	ComponentPublicInstance,
	computed,
	defineComponent,
	ref,
	toRef,
	watch
} from 'vue';
import { cdxIconExpand } from '@wikimedia/codex-icons';
 
import CdxButton from '../button/Button.vue';
import CdxIcon from '../icon/Icon.vue';
import CdxMenu from '../menu/Menu.vue';
import CdxTextInput from '../text-input/TextInput.vue';
 
import useModelWrapper from '../../composables/useModelWrapper';
import useGeneratedId from '../../composables/useGeneratedId';
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 text input with an expandable menu of predefined items.
 */
export default defineComponent( {
	name: 'CdxCombobox',
	components: {
		CdxButton,
		CdxIcon,
		CdxMenu,
		CdxTextInput
	},
 
	/**
	 * Attributes applied to this component by a parent will be applied
	 * to the TextInput child component rather than the root element.
	 */
	inheritAttrs: false,
 
	props: {
		/**
		 * Menu items. See the MenuItemData type.
		 */
		menuItems: {
			type: Array as PropType<MenuItemData[]>,
			required: true
		},
 
		/**
		 * Value of the current selection.
		 *
		 * Must be bound with `v-model:selected`.
		 */
		selected: {
			type: [ String, Number ] as PropType<string|number>,
			required: true
		},
 
		/**
		 * Whether the dropdown 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} 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 input value changes via direct use of the input
		 *I
		 * @property {InputEvent} event
		 */
		'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
		 *I
		 * @property {FocusEvent} event
		 */
		'focus',
		/**
		 * When the input loses focus
		 *
		 * @property {FocusEvent} event
		 */
		'blur'
	],
 
	setup( props, { emit, attrs, slots } ) {
		const input = ref<InstanceType<typeof CdxTextInput>>();
		const inputWrapper = ref<HTMLDivElement>();
		const menu = ref<InstanceType<typeof CdxMenu>>();
		const menuId = useGeneratedId( 'combobox' );
		const selectedProp = toRef( props, 'selected' );
		const modelWrapper = useModelWrapper( selectedProp, emit, 'update:selected' );
		const expanded = ref( false );
		const expanderClicked = ref( false );
 
		const highlightedId = computed( () => menu.value?.getHighlightedMenuItem()?.id );
 
		const { computedDisabled } = useFieldData( toRef( props, 'disabled' ) );
 
		const internalClasses = computed( () => {
			return {
				'cdx-combobox--expanded': expanded.value,
				'cdx-combobox--disabled': computedDisabled.value
			};
		} );
 
		// Get helpers from useSplitAttributes.
		const {
			rootClasses,
			rootStyle,
			otherAttrs
		} = useSplitAttributes( attrs, internalClasses );
 
		/**
		 * When the input gains focus, update the state of the menu.
		 * If the menu is collapsed, expand the menu (if there is anything to
		 * display). If the menu was already expanded and the expander was just
		 * clicked, collapse the menu instead.
		 *
		 * @param event
		 */
		function onInputFocus( event: FocusEvent ): void {
			if ( expanderClicked.value && expanded.value ) {
				expanded.value = false;
			} else if ( props.menuItems.length > 0 || slots[ 'no-results' ] ) {
				expanded.value = true;
			}
			emit( 'focus', event );
		}
 
		/**
		 * When the input loses focus, update the state of the menu.
		 * If the menu was expanded and the expander was just clicked,
		 * keep the menu open. Otherwise, close the menu.
		 *
		 * @param event
		 */
		function onInputBlur( event: FocusEvent ): void {
			expanded.value = ( expanderClicked.value && expanded.value );
			emit( 'blur', event );
		}
 
		/**
		 * Set a flag variable *before* the text input loses focus so that
		 * we can correctly determine whether focus changes are due to the
		 * expander button being clicked.
		 */
		function onButtonMousedown(): void {
			if ( computedDisabled.value ) {
				return;
			}
			expanderClicked.value = true;
		}
 
		/**
		 * When clicked, the button will briefly receive focus itself (this is
		 * necessary for correct UX), but then the TextInput is focused
		 * programmatically.
		 */
		function onButtonClick(): void {
			if ( computedDisabled.value ) {
				return;
			}
			input.value?.focus(); // call the public focus() method on TextInput
		}
 
		function onKeydown( e: KeyboardEvent ) {
			if (
				!menu.value ||
				computedDisabled.value ||
				props.menuItems.length === 0 ||
				e.key === ' '
			) {
				return;
			}
			menu.value.delegateKeyNavigation( e );
		}
 
		useFloatingMenu( input as Ref<ComponentPublicInstance>, menu );
 
		/**
		 * No matter what, the flag needs to be reset every time the menu
		 * visibility state changes.
		 */
		watch( expanded, () => {
			expanderClicked.value = false;
		} );
 
		return {
			input,
			inputWrapper,
			menu,
			menuId,
			modelWrapper,
			expanded,
			highlightedId,
			computedDisabled,
			onInputFocus,
			onInputBlur,
			onKeydown,
			onButtonClick,
			onButtonMousedown,
			cdxIconExpand,
			rootClasses,
			rootStyle,
			otherAttrs
		};
	}
} );
 
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
@import ( reference ) '../../themes/mixins/icon-alignment.less';
 
.cdx-combobox {
	display: inline-block;
	position: relative;
 
	&__input-wrapper {
		display: flex;
	}
 
	&__input.cdx-text-input {
		flex: 1 1 auto;
		// Override TextInput `min-width` to allow for the expander button.
		min-width: @min-width-medium - @min-size-interactive-pointer;
		border-top-right-radius: @border-radius-sharp;
		border-bottom-right-radius: @border-radius-sharp;
 
		.cdx-text-input__input {
			border-right-width: 0;
		}
	}
 
	&__expand-button.cdx-button {
		position: relative;
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
	}
 
	&__expand-icon.cdx-icon {
		.cdx-mixin-icon(
			center,
			@min-size-icon-x-small,
			@size-icon-x-small
		);
	}
 
	&--expanded {
		.cdx-combobox__expand-button.cdx-button {
			border-bottom-right-radius: @border-radius-sharp;
		}
	}
 
	// 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>