All files / ext.wikilambda.edit/components/base ZObjectSelector.vue

91.3% Statements 84/92
86.04% Branches 37/43
96% Functions 24/25
91.3% Lines 84/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 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    36x 36x 36x 36x 36x 36x 36x 36x 36x 36x                                                                                         118x             116x                                       134x                   229x               116x                   117x 48x   69x   7x   53x   7x   2x                     184x                       13x                 13x                 26x             7x     7x 7x 7x   7x 6x     13x 13x 13x 13x     13x 11x       13x 13x                   13x       6x       1x                                       39x 39x     39x           39x         39x 39x 26x                     24x 24x           118x 2x   116x 116x 116x   53x 53x 53x   37x 37x 37x   26x   90x         90x 392x                           18x         1x       116x     36x   36x     36x 36x 36x     36x       36x   358x 358x 358x                             116x       5x           5x             36x                                                                                                                                
<!--
	WikiLambda Vue interface module for selecting any ZObject,
	with lookup on name.
 
	Receives an input parameter to filter the type of ZObjects that
	it will search and display (e.g. Z4 for selecting only types)
 
	@copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
	@license MIT
-->
<template>
	<span class="ext-wikilambda-select-zobject">
		<!-- Show fields when edit is false -->
		<cdx-lookup
			:key="lookupKey"
			:selected="selectedValue"
			:disabled="disabled"
			:placeholder="lookupPlaceholder"
			:menu-items="lookupResults"
			:menu-config="lookupConfig"
			:end-icon="lookupIcon"
			:initial-input-value="selectedLabel"
			:status="errorLookupStatus"
			data-testid="z-object-selector-lookup"
			@update:selected="onSelect"
			@input="onInput"
		>
			<template #no-results>
				{{ $i18n( 'wikilambda-zobjectselector-no-results' ).text() }}
			</template>
		</cdx-lookup>
		<div
			v-if="hasFieldErrors"
			class="ext-wikilambda-select-zobject__errors"
		>
			<cdx-message
				v-for="( error, index ) in fieldErrors"
				:key="'field-error-' + rowId + '-' + index"
				:type="error.type"
				:inline="true"
			>
				<!-- eslint-disable vue/no-v-html -->
				<div v-html="getErrorMessage( error )"></div>
			</cdx-message>
		</div>
	</span>
</template>
 
<script>
const { defineComponent } = require( 'vue' );
const Constants = require( '../../Constants.js' ),
	CdxLookup = require( '@wikimedia/codex' ).CdxLookup,
	CdxMessage = require( '@wikimedia/codex' ).CdxMessage,
	errorUtils = require( '../../mixins/errorUtils.js' ),
	typeUtils = require( '../../mixins/typeUtils.js' ),
	mapActions = require( 'vuex' ).mapActions,
	mapGetters = require( 'vuex' ).mapGetters,
	icons = require( '../../../../lib/icons.json' );
 
module.exports = exports = defineComponent( {
	name: 'wl-z-object-selector',
	components: {
		'cdx-message': CdxMessage,
		'cdx-lookup': CdxLookup
	},
	mixins: [ errorUtils, typeUtils ],
	props: {
		rowId: {
			type: Number,
			default: 0
		},
		selectedZid: {
			type: String,
			default: ''
		},
		disabled: {
			type: Boolean,
			required: false,
			default: false
		},
		type: {
			type: String,
			default: ''
		},
		returnType: {
			type: String,
			default: ''
		},
		strictType: {
			type: Boolean,
			required: false,
			default: false
		},
		placeholder: {
			type: String,
			default: ''
		},
		/**
		 * List of Zids to exclude from selection and from
		 * the lookup results. Must be in uppercase.
		 */
		excludeZids: {
			type: Array,
			default: function () {
				return [];
			},
			required: false
		}
	},
	emits: [ 'input' ],
	data: function () {
		return {
			lookupKey: 1,
			lookupResults: [],
			lookupConfig: {
				boldLabel: true,
				searchQuery: ''
			},
			lookupDelayTimer: null,
			lookupDelayMs: 300,
			inputValue: ''
		};
	},
	computed: Object.assign( mapGetters( [
		'getLabel'
	] ), {
 
		/**
		 * Value model for the internal codex lookup component. It
		 * must be null or the value (Zid) of the selected MenuItem.
		 *
		 * @return {string}
		 */
		selectedValue: function () {
			return this.selectedZid || null;
		},
 
		/**
		 * Human readable label for the selected Zid in the
		 * user language or closest fallback. If the label is
		 * not available it returns the input.
		 *
		 * @return {string}
		 */
		selectedLabel: function () {
			return this.selectedZid ?
				this.getLabel( this.selectedZid ) :
				'';
		},
 
		/**
		 * Icon to display at the end of the Codex Lookup selector
		 *
		 * @return {string}
		 */
		lookupIcon: function () {
			return icons.cdxIconExpand;
		},
 
		/**
		 * Returns the placeholder for the Lookup selector, either
		 * the value passed as an input prop, or a built-in message
		 * depending on the type.
		 *
		 * @return {string}
		 */
		lookupPlaceholder: function () {
			if ( this.placeholder ) {
				return this.placeholder;
			}
			switcIh ( this.type ) {
				case Constants.Z_FUNCTION:
					return this.$i18n( 'wikilambda-function-typeselector-label' ).text();
				case Constants.Z_NATURAL_LANGUAGE:
					return this.$i18n( 'wikilambda-editor-label-addlanguage-label' ).text();
				case Constants.Z_TYPE:
					return this.$i18n( 'wikilambda-typeselector-label' ).text();
				default:
					return this.$i18n( 'wikilambda-zobjectselector-label' ).text();
			}
		},
 
		/**
		 * Status property for the Lookup component (ValidateStatusType).
		 * Can take the values 'default' or 'error':
		 * https://doc.wikimedia.org/codex/latest/components/types-and-constants.html#validationstatustype
		 *
		 * @return {string}
		 */
		errorLookupStatus: function () {
			return this.hasFieldErrors ? 'error' : 'default';
		}
	} ),E
	methods: Object.assign( {},
		mapActions( [
			'lookupZObject',
			'fetchZids'
		] ),
		{
			/**
			 * Whether is in the input list of Zids excluded from selection.
			 * Al the zids in the excludeZids input property must be uppercase.
			 *
			 * @param {string} zid
			 * @return {boolean}
			 */
			isExcludedZid: function ( zid ) {
				return ( this.excludeZids.includes( zid ) || this.isDisallowedType( zid ) );
			},
 
			/**
			 * Whether is in the built-in list of Zids excluded from selection.
			 *
			 * @param {string} zid
			 * @return {boolean}
			 */
			isDisallowedType: function ( zid ) {
				return (
					( this.type === Constants.Z_TYPE ) &&
					Constants.EXCLUDE_FROM_SELECTOR.includes( zid )
				);
			},

			/**
			 * Handle get zObject lookup.
			 * update lookup results with label and update  in store.
			 *
			 * @param {string} input
			 */
			getLookupResults: function ( input ) {
				this.lookupZObject( {
					input,
					type: this.type,
					returnType: this.returnType,
					strictType: this.strictType
				} I).then( ( payload ) => {
					// If the string searched has changed, do not show the search result
					if ( !this.inputValue.includes( input ) ) {
						return;
					}
					const zids = [];
					tIhis.lookupConfig.searchQuery = input;
					this.lookupResults = [];
					// Update lookupResults list
					if ( payload && payload.length > 0 ) {
						payload.forEach( ( result ) => {
 
							// Set up codex MenuItem options
							// https://doc.wikimedia.org/codex/latest/components/demos/menu-item.html
							const value = result.page_title;
							const label = result.label;
							const description = result.type_label;
							const supportingText = ( result.label !== result.match_label ) ? `(${ result.match_label })` : '';
							// If return type is set, reflect mode with icon
							let icon;
							if ( this.returnType ) {
								icon = ( result.page_type === this.type ) ?
									icons.cdxIconInstance :
									icons.cdxIconFunction;
							}
 
							// Exclude everything in the exclude Zids and disallowed types lists
							if ( !this.isExcludedZid( value ) ) {
								this.lookupResults.push( {
									value,
									label,
									description,
									supportingText,
									icon
								} );
							}
 
							// Gather all zids to request them for the data store
							zids.push( value );
						} );
						// Once lookupResults are gathered, fetch and collect all the data;
						// fetchZids makes sure that only the missing zids are requested
						this.fetchZids( { zids } );
					} else {
						this.setSuggestions();
					}
				} );
			},
 
			/**
			 * Clears the ZObjectSelector lookup results.
			 * This doesn't clear the component TextInput.
			 */
			clearResults: function () {
				this.lookupResults = [];
				this.setSuggestions();
				this.inputValue = '';
			},
 
			/**
			 * On field input, perform a backend lookup and set the lookupResults
			 * array. When searching for a Zid, validate and select.
			 *
			 * @param {string} input
			 */
			onInput: function ( input ) {
				this.inputValue = input;
				this.clearFieldErrors();
I
				// If empty input, clear and exit
				if ( !input ) {
					this.clearResults();
					return;
				}
 
				// Just search if more than one characters
				if ( input.length < 2 ) {
					return;
				}
 
				// Search after 300 ms
				clearTimeout( this.lookupDelayTimer );
				this.lookupDelayTimer = setTimeout( () => {
					this.getLookupResults( input );
				}, this.lookupDelayMs );
			},
 
			/**
			 * Model update event, sets the value of the field
			 * either with an empty value or with a selected value
			 * from the menu.
			 *
			 * @param {string} value
			 */
			onSelect: function ( value ) {
				this.clearFieldErrors();
				this.$emit( 'input', value );
			},
 
			/**
			 * Reset lookup to suggestions by type
			 */
			setSuggestions: function () {
				if ( !this.type ) {
					return;
				}
 
				let title = '';
				let suggestedZids = [];
				switch ( this.type ) {
					case Constants.Z_NATURAL_LANGUAGE:
						title = this.$i18n( 'wikilambda-object-selector-suggested-languages' ).text();
						suggestedZids = Constants.SUGGESTIONS.LANGUAGES;
						break;
					case Constants.Z_TYPE:
						title = this.$i18n( 'wikilambda-object-selector-suggested-types' ).text();
						suggestedZids = Constants.SUGGESTIONS.TYPES;
						break;
					default:
						return;
				}
 
				this.lookupResults.push( {
					label: title,
					value: 'suggestion',
					disabled: true
				} );
 
				suggestedZids.forEach( ( zid ) => {
					this.lookupResults.push( {
						value: zid,
						label: this.getLabel( zid ),
						description: this.getLabel( this.type ),
						class: 'ext-wikilambda-select-zobject-suggestion'
					} );
				} );
			}
		}
	),
	watch: {
		selectedLabel: function () {
			// Trigger a rerender when initial input value changes,
			// This might occur due to slow network request for a particular label
			// Also make sure not to trigger rerender if the user has typed an input
			if ( !this.inputValue ) {
				this.lookupKey += 1;
			}
		},
		type: function () {
			this.setSuggestions();
		}
	},
	mounted: function () {
		this.setSuggestions();
	}
} );
</script>
 
<style lang="less">
@import '../../ext.wikilambda.edit.variables.less';
 
.ext-wikilambda-select-zobject {
	.cdx-text-input__end-icon {
		width: @size-icon-x-small;
		height: @size-icon-x-small;
		min-width: @size-icon-x-small;
		min-height: @size-icon-x-small;
	}
 
	&__link {
		min-height: 32px;
		display: inline-flex;
		align-items: center;
	}
 
	a {
		display: inline-flex;
	}
 
	&__errors {
		margin-top: @spacing-50;
		width: max-content;
	}
 
	.cdx-menu {
		.cdx-menu-item.ext-wikilambda-select-zobject-suggestion {
			.cdx-menu-item__text__label,
			.cdx-search-result-title {
				font-weight: @font-weight-normal;
			}
		}
	}
}
</style>