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

63.47% Statements 73/115
50.94% Branches 27/53
75.75% Functions 25/33
63.47% Lines 73/115

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                                                                                                                              31x 31x 31x 31x 31x 31x 31x 31x 31x     31x                                                                                   72x                     66x                                     18x 10x       63x 39x   24x   9x   1x   14x             3x     3x       77x 77x     3x       3x     63x       88x     1x     88x     85x     1x 1x 1x                                     66x 66x                                                       34x                           34x                   31x 31x 31x           20x       20x 20x 20x 19x   34x 34x 34x             34x 34x 32x                 34x 13x           13x       19x   1x                                                                                                         32x 32x 32x   32x         32x     32x 1x     31x           31x                       3x                   14x             18x 1x   18x   18x               66x                                                                                                        
<template>
	<!--
		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
	-->
	<span
		class="ext-wikilambda-select-zobject"
		:class="{ 'ext-wikilambda-select-zobject__fitted': fitWidth }"
		:style="{ width: fieldWidth }"
	>
		<div v-if="readonly || viewmode" class="ext-wikilambda-select-zobject__link">
			<a
				:href="typeUrl()"
				:target="referenceLinkTarget"
			>
				{{ selectedText }}
			</a>
		</div>
		<!-- eslint-disable vue/no-v-model-argument -->
		<!-- eslint-disable vue/no-unsupported-features -->
		<!-- TODO: add error state when implemented in codex -->
		<cdx-lookup
			v-else
			:key="lookupKey"
			v-model:selected="selectedValue"
			:class="{ 'ext-wikilambda-select-zobject__input-invalid': validatorIsInvalid }"
			:placeholder="lookupPlaceholder"
			:menu-items="lookupResults"
			:end-icon="lookupIcon"
			:initial-input-value="initialInputValue"
			:status="errorInputStatus"
			@input="onInput"
			@focusout="onFocusOut"
			@focus="onFocus"
		>
			<template #no-results>
				No results found.
			</template>
		</cdx-lookup>
		<cdx-message
			v-if="validatorIsInvalid"
			:inline="true"
			type="error"
		>
			{{ validatorErrorMessage }}
		</cdx-message>
		<cdx-message
			v-if="errorState"
			class="ext-wikilambda-select-zobject__error"
			:type="errorType"
			inline
		>
			{{ errorMessage }}
		</cdx-message>
	</span>
</template>
 
<script>
var Constants = require( '../Constants.js' ),
	CdxLookup = require( '@wikimedia/codex' ).CdxLookup,
	CdxMessage = require( '@wikimedia/codex' ).CdxMessage,
	validator = require( '../mixins/validator.js' ),
	typeUtils = require( '../mixins/typeUtils.js' ),
	mapActions = require( 'vuex' ).mapActions,
	mapGetters = require( 'vuex' ).mapGetters,
	mapMutations = require( 'vuex' ).mapMutations,
	icons = require( '../../../lib/icons.json' );
 
// @vue/component
module.exports = exports = {
	name: 'wl-z-object-selector',
	components: {
		'cdx-message': CdxMessage,
		'cdx-lookup': CdxLookup
	},
	mixins: [ validator, typeUtils ],
	inject: {
		viewmode: { default: false }
	},
	props: {
		fitWidth: {
			type: Boolean,
			default: false
		},
		type: {
			type: String,
			default: ''
		},
		returnType: {
			type: String,
			default: ''
		},
		selectedId: {
			type: String,
			default: ''
		},
		initialSelectionLabel: {
			type: String,
			default: ''
		},
		placeholder: {
			type: [ String, Object ],
			default: ''
		},
		readonly: {
			type: Boolean,
			default: false
		},
		usedLanguages: {
			type: Array,
			default: function () {
				return [];
			},
			required: false
		},
		zobjectId: {
			type: Number,
			default: -1
		}
	},
	emits: [ 'input', 'focus-out', 'input-removed' ],
	data: function () {
		return {
			active: false,
			lookupResults: [],
			lookupDelayTimer: null,
			lookupDelayMs: 300,
			inputValue: '',
			valueEmitted: false,
			lookupKey: 1,
			selectedValue: this.selectedId
		};
	},
	computed: $.extend( {},
		mapGetters( {
			zkeyLabels: 'getZkeyLabels',
			zKeys: 'getZkeys',
			getErrors: 'getErrors'
		} ),
		{
			usedLanguageZids: function () {
				return this.usedLanguages.map( function ( language ) {
					return language.Z9K1;
				} );
			},
			lookupPlaceholder: function () {
				if ( this.placeholder ) {
					return this.placeholder;
				}
				switch ( this.type ) {
					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();
				}
			},
			selectedLabel: function () {
				return this.zkeyLabels[ this.selectedId ];
			},
			selectedText: function () {
				Iif ( this.selectedId ) {
					return this.selectedLabel;
				} else {
					return '';
				}
			},
			initialInputValue: function () {
				this.inputValue = this.initialSelectionLabel;
				return this.initialSelectionLabel;
			},
			referenceLinkTarget: function () {
				Iif ( !( this.viewmode || this.readonly ) ) {
					return '_blank';
				}
 
				return;
			},
			lookupIcon: function () {
				return icons.cdxIconExpand;
			},
			isError: function () {
				// the error is not guaranteed to exist
				return this.getErrors[ this.zobjectId ];
			},
			errorType: function () {
				return this.isError ? this.getErrors[ this.zobjectId ].type : null;
			},
			errorState: function () {
				return this.isError ? this.getErrors[ this.zobjectId ].state : false;
			},
			errorInputStatus: function () {
				return this.errorState ? 'error' : 'default';
			},
			errorMessage: function () {
				if ( this.isError ) {
					const messageStr = this.getErrors[ this.zobjectId ].message;
					return this.$i18n( messageStr ).text();
				}
				return null;
			},
			/**
			 * This computed property calculates the width of the field depending on its value
			 *
			 * TODO: Because this is a not a monospace font, the larger the word is, the
			 * less space it occupies in ch, so probably we should remove a %:
			 *
			 * > 1ch is usually wider than the average character width, usually by around 20-30%
			 *
			 * Refs:
			 * https://stackoverflow.com/questions/3392493/adjust-width-of-input-field-to-its-input
			 * https://meyerweb.com/eric/thoughts/2018/06/28/what-is-the-css-ch-unit/
			 *
			 * @return {string}
			 */
			fieldWidth: function () {
				if ( !this.fitWidth ) {
					return 'auto';
				}
				Iif ( this.active ) {
					return '100%';
				}
				// If no value or placeholder, default is 20 characters
				var chars = 20;
				if ( this.selectedText && ( this.selectedText.length > 0 ) ) {
					// Two extra characters to account for inner padding
					chars = this.selectedText.length + 6;
				} else Iif ( this.lookupPlaceholder && ( this.lookupPlaceholder.length > 0 ) ) {
					chars = this.lookupPlaceholder.length + 6;
				}
				// Subtract 20%
				chars = Math.ceil( chars - chars * 0.1 );
				return `${chars}ch`;
			}
		}
	),
	methods: $.extend( {},
		mapActions( [
			'lookupZObject',
			'fetchZKeys',
			'setError'
		] ),
		mapMutations( [ 'addAllZKeyLabels' ] ),
		{
			isExcludedZType: function ( zid ) {
				return (
					( this.type === Constants.Z_TYPE ) &&
					( Constants.EXCLUDED_Z_TYPES.indexOf( zid ) !== -1 )
				);
			},
			hasValidType: function ( zid ) {
				var zidType = this.zKeys[ zid ][ Constants.Z_PERSISTENTOBJECT_VALUE ][ Constants.Z_OBJECT_TYPE ];
				return ( !this.type || // Either the selection isn't type restricted
					(
						this.type === zidType && // Or the specified type matches de ZObject type
						!this.isExcludedZType( zid ) // and ZID is not part of the EXCLUDED_Z_TYPES
					) );
			},
			isUsedLanguage: function ( zid ) {
				return this.usedLanguageZids.indexOf( zid ) !== -1;
			},
 
			/**
			 * Handle get zObject lookup.
			 * update lookup results with label and update zKeyLabels in store.
			 *
			 * @param {string} input
			 */
			getLookupResults: function ( input ) {
				var self = this,
					searchedString = input;
				this.lookupZObject( {
					input: input,
					type: this.type,
					returnType: this.returnType
				} ).then( function ( payload ) {
					// If the string searched has changed, do not show the search result
					Iif ( self.inputValue.indexOf( searchedString ) === -1 ) {
						return;
					}
 
					var zKeys = [];
					self.lookupResults = [];
					if ( payload && payload.length > 0 ) {
						payload.forEach(
							function ( result ) {
								var zid = result.page_title,
									lang = result.page_lang,
									label = result.label;
 
								// TODO (T322757): Show aliases ( result.is_primary === 0 ) differently
 
								// Update lookupResults list
								// If we are searching for Types (this.type === Constants.Z_TYPE)
								// we should exclude Z1, Z2, Z7 and Z9 from the results
								if ( !self.isExcludedZType( zid ) ) {
									if ( self.usedLanguageZids ? !self.isUsedLanguage( zid ) : true ) {
										self.lookupResults.push(
											{
												value: zid,
												label
											}
										);
									}
								}
								// Update zKeyLabels in the Vuex store
								if ( !( zid in self.zkeyLabels ) ) {
									self.addAllZKeyLabels( [ {
										zid,
										label,
										lang
									} ] );
 
									zKeys.push( zid );
								}
							}
						);
						self.fetchZKeys( { zids: zKeys } );
					} else {
						self.validatorSetError( 'wikilambda-noresult' );
					}
				} );
 
			},
			/**
			 * Allow the field to receive a Zid instead of a label and,
			 * if valid and it exists, select and submit it.
			 * If the selector restricts the type, check that the ZObject
			 * type fits this restriction.
			 */
			validateZidInput: function () {
				var self = this,
					normalizedSearchValue = self.inputValue.toUpperCase();
 
				Iif ( this.isUsedLanguage( normalizedSearchValue ) ) {
					return;
				}
				if ( self.isValidZidFormat( normalizedSearchValue ) ) {
					self.fetchZKeys( { zids: [ normalizedSearchValue ] } ).then( function () {
						var label = '';
						self.lookupResults = [];
						// If data is returned, The value will show in the zKeys
						if (
							( normalizedSearchValue in self.zKeys ) &&
							( self.hasValidType( normalizedSearchValue ) )
						) {
							label = self.zkeyLabels[ normalizedSearchValue ];
							self.lookupResults.push( {
								value: normalizedSearchValue,
								label: label + ' (' + normalizedSearchValue + ')'
							} );
						} else {
							self.validatorSetError( 'wikilambda-invalidzobject' );
						}
					} );
				} else {
					self.validatorSetError( 'wikilambda-invalidzobject' );
				}
			},
			// used by ZLabelsBlock, ZMultilingualString and FunctionEditorLanguage components to
			// automatically add and clear labels.
			clearResults: function () {
				this.lookupResults = [];
				this.inputValue = '';
				this.lookupKey += 1;
			},
			/**
			 * On lookup field input, set a timer so that the lookup is not done immediately.
			 *
			 * @param {string} input
			 */
			onInput: function ( input ) {
				var self = this;
				this.valueEmitted = false;
				this.inputValue = input;
 
				Iif ( !input ) {
					this.lookupResults = [];
					return;
				}
 
				this.validatorResetError();
 
				// Just search if more than one characters
				if ( input.length < 2 ) {
					return;
				}
 
				Iif ( self.isValidZidFormat( input.toUpperCase() ) ) {
					clearTimeout( this.lookupDelayTimer );
					this.lookupDelayTimer = setTimeout( function () {
						self.validateZidInput();
					}, this.lookupDelayMs );
				} else {
					self.getLookupResults( input );
				}
			},
			onFocusOut: function () {
				this.active = false;
				this.$emit( 'focus-out' );
			},
			onFocus: function () {
				this.active = true;
				this.$emit( 'focus' );
			},
			typeUrl: function () {
				return new mw.Title( this.selectedId ).getUrl();
			}
		}
	),
	watch: {
		initialSelectionLabel: {
			handler: 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
				Iif ( !this.inputValue ) {
					this.lookupKey += 1;
				}
			}
		},
		selectedValue: {
			handler: function ( zId ) {
				if ( this.selectedValue === null ) {
					this.$emit( 'input-removed' );
				}
				this.$emit( 'input', zId );
 
				this.setError( {
					internalId: this.zobjectId,
					errorState: false
				} );
			}
		}
	},
	mounted: function () {
		this.fetchZKeys( { zids: [
			Constants.Z_STRING,
			Constants.Z_REFERENCE,
			Constants.Z_BOOLEAN,
			Constants.Z_TYPED_LIST
		] } );
	}
};
</script>
 
<style lang="less">
@import '../ext.wikilambda.edit.less';
 
.ext-wikilambda-select-zobject {
	&__fitted {
		transition: @wl-transition-field-expand;
		display: inline-block;
 
		.cdx-text-input__input {
			min-width: auto;
		}
	}
 
	.cdx-text-input__icon {
		svg {
			width: @size-75;
			height: @size-75;
			min-width: @size-75;
			min-height: @size-75;
		}
	}
 
	&__link {
		min-height: 32px;
		display: inline-flex;
		align-items: center;
	}
 
	a {
		display: inline-flex;
	}
 
	&__input-invalid {
		background: #fee;
		border: 2px #f00 solid;
	}
 
	&__error {
		padding-top: 6px;
	}
}
</style>