All files / ext.wikilambda.app/components/default-view-types ZObjectStringRenderer.vue

97.66% Statements 543/556
88.33% Branches 53/60
84.61% Functions 22/26
97.66% Lines 543/556

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 5571x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 608x 1x 1x 1x 1x 1x 1x 1x 608x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 379x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 242x 54x 54x 54x 188x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 630x 630x 630x 630x 630x 630x 24x 24x 606x 606x 606x 606x 113x 113x 113x 113x 113x 606x 606x 606x 113x 113x 606x 606x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 72x 72x 8x 8x 64x 64x 64x 72x 20x 20x 44x 44x 72x 24x 24x 44x 44x 44x 44x 72x 21x 21x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 2x 2x 2x 2x 2x 2x 2x 2x 2x 23x 1x 1x 1x 1x 1x 1x 1x 20x 19x 19x 19x 23x 1x 1x 23x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x     4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 1x 24x 20x 20x 20x 20x 20x 20x 20x 1x 20x 20x 20x 20x 24x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 606x 100x 100x 100x 100x 100x 100x 100x 1x 1x 1x 1x 1x 1x 1x 47x 47x 1x 1x 24x 24x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
<!--
	WikiLambda Vue component for a ZObject with a string renderer.
 
	@copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
	@license MIT
-->
<template>
	<div class="ext-wikilambda-app-object-string-renderer" data-testid="z-object-string-renderer">
		<!-- If expanded is false, show text field -->
		<template v-if="!expanded || !initialized">
			<p
				v-if="!edit"
				class="ext-wikilambda-app-object-string-renderer__text"
				:class="{ 'ext-wikilambda-app-object-string-renderer__rendering': rendererRunning }"
				data-testid="zobject-string-renderer-text">
				{{ renderedValue }}
			</p>
			<!-- We capture the change event instead of update:modelValue
			to reduce the number of unnecessary calls to the orchestrator -->
			<cdx-text-input
				v-else
				:class="{ 'cdx-text-input--status-error': hasFieldErrors }"
				:model-value="renderedValue"
				:disabled="rendererRunning"
				:placeholder="placeholderValue"
				data-testid="zobject-string-renderer-input"
				@change="setRenderedValue"
			></cdx-text-input>
			<div
				v-if="hasFieldErrors"
				class="ext-wikilambda-app-object-string-renderer__error"
			>
				<cdx-message :type="fieldErrors[0].type" :inline="true">
					<!-- eslint-disable vue/no-v-html -->
					<span v-html="getErrorMessage( fieldErrors[0] )"></span>
				</cdx-message>
				<a v-if="showExamplesLink" @click="openExamplesDialog">
					{{ $i18n( 'wikilambda-string-renderer-examples-title' ).text() }}
				</a>
				<!-- eslint-disable vue/no-v-html -->
				<p
					v-if="showErrorFooter"
					class="ext-wikilambda-app-object-string-renderer__error-footer"
					v-html="$i18n( 'wikilambda-renderer-error-footer-project-chat' ).parse()"
				></p>
			</div>
		</template>
 
		<!-- If expanded is true, show key-value set -->
		<template v-else>
			<wl-z-object-key-value-set
				:row-id="rowId"
				:edit="edit"
				:depth="depth"
				@set-type="setType"
			></wl-z-object-key-value-set>
		</template>
 
		<!-- Renderer examples dialog -->
		<cdx-dialog
			:open="showExamplesDialog"
			:title="$i18n( 'wikilambda-string-renderer-examples-title' ).text()"
			:close-button-label="$i18n( 'wikilamda-dialog-close' ).text()"
			@update:open="showExamplesDialog = false"
		>
			<ul class="ext-wikilambda-app-object-string-renderer__examples">
				<li v-for="example in renderedExamples" :key="example.testZid">
					{{ example.result }}
				</li>
			</ul>
			<template #footer>
				<a
					:href="rendererUrl"
					target="_blank"
					:lang="rendererLabel.langCode"
					:dir="rendererLabel.langDir"
				>{{ rendererLabel.label }}</a>
			</template>
		</cdx-dialog>
	</div>
</template>
 
<script>
const { CdxDialog, CdxMessage, CdxTextInput } = require( '@wikimedia/codex' );
const { defineComponent } = require( 'vue' );
const Constants = require( '../../Constants.js' ),
	ZObjectKeyValueSet = require( './ZObjectKeyValueSet.vue' ),
	errorUtils = require( '../../mixins/errorUtils.js' ),
	typeUtils = require( '../../mixins/typeUtils.js' ).methods,
	{ getValueFromCanonicalZMap, hybridToCanonical } = require( '../../mixins/schemata.js' ).methods,
	{ mapActions, mapGetters } = require( 'vuex' );
 
module.exports = exports = defineComponent( {
	name: 'wl-z-object-string-renderer',
	components: {
		'cdx-dialog': CdxDialog,
		'cdx-message': CdxMessage,
		'cdx-text-input': CdxTextInput,
		'wl-z-object-key-value-set': ZObjectKeyValueSet
	},
	mixins: [ errorUtils ],
	props: {
		rowId: {
			type: Number,
			required: false,
			default: 0
		},
		edit: {
			type: Boolean,
			required: true
		},
		depth: {
			type: Number,
			required: true
		},
		type: {
			type: String,
			required: false,
			default: undefined
		},
		expanded: {
			type: Boolean,
			required: true
		}
	},
	data: function () {
		return {
			blankObject: undefined,
			initialized: false,
			renderedValue: '',
			rendererRunning: false,
			showExamplesDialog: false,
			showExamplesLink: false,
			showErrorFooter: false,
			pendingPromises: []
		};
	},
	computed: Object.assign( mapGetters( [
		'createObjectByType',
		'getCurrentView',
		'getLabelData',
		'getPassingTestZids',
		'getParserZid',
		'getRendererZid',
		'getRendererExamples',
		'getStoredObject',
		'getUserLangCode',
		'getUserLangZid',
		'getZObjectAsJsonById',
		'isCreateNewPage'
	] ), {
		/**
		 * Return the stored type object
		 *
		 * @return {Object}
		 */
		typeObject: function () {
			return this.getStoredObject( this.type );
		},
		/**
		 * Return renderer function Zid
		 *
		 * @return {string}
		 */
		rendererZid: function () {
			return this.getRendererZid( this.type );
		},
		/**
		 * Return renderer LabelData
		 *
		 * @return {LabelData}
		 */
		rendererLabel: function () {
			return this.getLabelData( this.rendererZid );
		},
		/**
		 * Return the url for the renderer wiki page
		 *
		 * @return {string}
		 */
		rendererUrl: function () {
			return '/view/' + this.getUserLangCode + '/' + this.rendererZid;
		},
		/**
		 * Return parser function Zid
		 *
		 * @return {string}
		 */
		parserZid: function () {
			return this.getParserZid( this.type );
		},
		/**
		 * Returns the rendered examples in case the renderer
		 * tests were run.
		 *
		 * @return {Array}
		 */
		renderedExamples: function () {
			return this.getRendererExamples( this.rendererZid );
		},
		/**
		 * Return a dynamically generated placeholder for the renderer field
		 * using the available tests for the renderer function. If none are
		 * available, returns the fallback placeholder message.
		 *
		 * When the renderer is running, show the Renderer running message.
		 *
		 * @return {string}
		 */
		placeholderValue: function () {
			if ( this.renderedExamples.length > 0 ) {
				const example = this.renderedExamples[ 0 ].result;
				return this.$i18n( 'wikilambda-string-renderer-field-example', example ).text();
			}
			return '';
		},
		/**
		 * Filters the passing test zids array and returns an array with the
		 * test objects for those which are wellformed. We consider wellformed
		 * tests those which have a call to the renderer function on the first
		 * level, directly under the Test call key/Z20K1.
		 *
		 * @return {Array}
		 */
		validRendererTests: function () {
			// We return an empty array if not initialized so that the
			// component forces a value change in validRendererTests on expanse
			// and collapse, and the watch function is re-run again if it had
			// been interrupted. This can happen if there are multiple nested
			// ZObjectStringRenderer fields.
			if ( !this.initialized ) {
				return [];
			}
 
			return this.getPassingTestZids( this.rendererZid )
				// For each test Zid, get the stored test object
				.map( ( zid ) => {
					const zobject = this.getStoredObject( zid );
					return {
						zid,
						zobject: zobject ? zobject[ Constants.Z_PERSISTENTOBJECT_VALUE ] : undefined
					};
				} )
				// Filter out undefined or not wellformed test objects
				.filter( ( test ) => typeUtils.isTruthyOrEqual( test.zobject, [
					Constants.Z_TESTER_CALL,
					Constants.Z_FUNCTION_CALL_FUNCTION
				], this.rendererZid ) );
		}
	} ),
	methods: Object.assign( mapActions( [
		'getTestResults',
		'runRendererTest',
		'runRenderer',
		'runParser',
		'setError'
	] ), {
		/**
		 * If the object type is changed, surface the event so that
		 * the ZObjectKeyValue parent component makes the type change.
		 *
		 * @param {Object} payload
		 */
		setType: function ( payload ) {
			this.$emit( 'set-type', payload );
		},
		/**
		 * Update the local renderedValue variable with the new
		 * value and trigger the function call to generate the new
		 * parsed object and set its keys in the global store.
		 *
		 * @param {Object} event
		 */
		setRenderedValue: function ( event ) {
			this.renderedValue = event.target.value;
			this.generateParsedValue();
		},
		/**
		 * Trigger the call to the Renderer function for this type
		 * passing the current object values, and set the returned string
		 * in the local renderedValue variable.
		 */
		generateRenderedValue: function () {
			// If we are in view mode, only generate rendered value once.
			if ( !this.edit && this.initialized ) {
				return;
			}
 
			// If we are in edit mode, only generate rendered value if the object is not
			// blank. For this we need to wait till the typeObject has been fetched.
			if ( this.edit && !this.typeObject ) {
				return;
			}
 
			// If typeObject is available, initialize the model blank object.
			if ( this.typeObject && !this.blankObject ) {
				this.initializeBlankObject();
			}
 
			const zobject = hybridToCanonical( this.getZObjectAsJsonById( this.rowId ) );
 
			// If zobject is blank, exit renderer.
			if ( JSON.stringify( zobject ) === JSON.stringify( this.blankObject ) ) {
				return;
			}
			this.rendererRunning = true;
			this.renderedValue = this.$i18n( 'wikilambda-string-renderer-running' ).text();
 
			this.runRenderer( {
				rendererZid: this.rendererZid,
				zobject,
				zlang: this.getUserLangZid
			} ).then( ( data ) => {
				this.clearRendererError();
				const response = data.response[ Constants.Z_RESPONSEENVELOPE_VALUE ];
				if ( response === Constants.Z_VOID ) {
					// Renderer returned void:
					// get error from metadata object and show examples link
					this.renderedValue = this.edit ? '' :
						this.$i18n( 'wikilambda-renderer-view-invalid-result' ).text();
					this.showExamplesLink = ( this.renderedExamples.length > 0 );
					const metadata = data.response[ Constants.Z_RESPONSEENVELOPE_METADATA ];
					const errorMessage = this.extractErrorMessage( metadata );
					this.setRendererError( errorMessage || this.$i18n( 'wikilambda-renderer-unknown-error',
						this.rendererZid ).parse() );
				} else if ( typeUtils.getZObjectType( response ) !== Constants.Z_STRING ) {
					// Renderer returned unexpected type:
					// show unexpected result error and project chat footer
					this.renderedValue = this.edit ? '' :
						this.i18n( 'wikilambda-renderer-view-invalid-result' ).text();
					this.showErrorFooter = true;
					this.setRendererError( this.$i18n( 'wikilambda-renderer-unexpected-result-error',
						this.rendererZid ).parse() );
				} else {
					// Success: Update the locally saved renderedValue with the response
					this.renderedValue = response;
				}
			} ).catch( () => {
				this.clearRendererError();
				this.setRendererError( this.$i18n( 'wikilambda-renderer-api-error' ).text() );
			} );
		},
		/**
		 * Trigger the call to the Parser function for this type
		 * passing the current rendererValue, and set the returned object
		 * in the global store.
		 */
		generateParsedValue: function () {
			this.runParser( {
				parserZid: this.parserZid,
				zobject: this.renderedValue,
				zlang: this.getUserLangZid,
				wait: true
			} ).then( ( data ) => {
				this.clearRendererError();
				const response = data.response[ Constants.Z_RESPONSEENVELOPE_VALUE ];
				if ( response === Constants.Z_VOID ) {
					// Parser returned void:
					// * Resolve parser promise
					// * get error from metadata object and show examples link
					data.resolver.resolve();
					this.clearParsedValue();
					const metadata = data.response[ Constants.Z_RESPONSEENVELOPE_METADATA ];
					const errorMessage = this.extractErrorMessage( metadata );
					this.showExamplesLink = ( this.renderedExamples.length > 0 );
					this.setRendererError( errorMessage || this.$i18n( 'wikilambda-parser-unknown-error',
						this.parserZid ).parse() );
				} else if ( typeUtils.getZObjectType( response ) !== this.type ) {
					// Parser return unexpected type:
					// * Resolve parser promise
					// * show unexpected result error and project chat footer
					data.resolver.resolve();
					this.clearParsedValue();
					this.showErrorFooter = true;
					this.setRendererError( this.$i18n( 'wikilambda-parser-unexpected-result-error',
						this.parserZid ).parse() );
				} else {
					// Success:
					// Parent component (ZObjectKeyValue) should:
					// * Set the value of the returned ZObject
					// * Resolve parser promise once the changes are persisted
					this.pendingPromises.push( data.resolver );
					this.$emit( 'set-value', {
						keyPath: [],
						value: response,
						callback: () => data.resolver.resolve()
					} );
				}
			} ).catch( () => {
				this.clearRendererError();
				this.setRendererError( this.$i18n( 'wikilambda-renderer-api-error' ).text() );
			} );
		},
		/**
		 * Resets the parsed key-values to a blank state.
		 * To do this, it emits a setType event with the current type
		 * which will make the parent ZObjectKeyValue component run
		 * the changeType action.
		 */
		clearParsedValue: function () {
			this.$emit( 'set-value', {
				keyPath: [],
				value: this.blankObject
			} );
		},
		/**
		 * Saves the given error message for current rowId
		 *
		 * @param {string} errorMessage
		 */
		setRendererError: function ( errorMessage ) {
			this.setError( {
				rowId: this.rowId,
				errorType: Constants.errorTypes.ERROR,
				errorMessage
			} );
		},
		/**
		 * Clears renderer field errors
		 */
		clearRendererError: function () {
			this.showExamplesLink = false;
			this.showErrorFooter = false;
			this.rendererRunning = false;
			this.clearFieldErrors();
		},
		/**
		 * Runs the test results for the renderer function. This
		 * call must be treated asynchronously, so all the results
		 * will be gathered as reactive computed properties.
		 */
		generateRendererExamples: function () {
			if ( this.edit ) {
				this.getTestResults( {
					zFunctionId: this.rendererZid
				} ).then( () => {
					// At this point getPassingTestZids is already returning the existing tests.
					// If none exist and we are creating a new object, expand to key-value set
					const setExpanded = (
						( this.isCreateNewPage || this.getCurrentView === Constants.VIEWS.FUNCTION_EVALUATOR ) &&
						( this.getPassingTestZids( this.rendererZid ).length === 0 )
					);
					this.$emit( 'expand', setExpanded );
					this.initialized = true;
				} );
			} else {
				this.$emit( 'expand', false );
				this.initialized = true;
			}
		},
		/**
		 * Given a metadata object of a failed function call, extracts the value
		 * of the Z500K1 key and, if it contains a message, returns it
		 *
		 * @param {Object} metadata
		 * @return {string}
		 */
		extractErrorMessage: function ( metadata ) {
			const error = getValueFromCanonicalZMap( metadata, 'errors' );
			const errorInfo = error[ Constants.Z_ERROR_VALUE ][ Constants.Z_GENERIC_ERROR_VALUE ];
			return ( ( typeof errorInfo === 'string' ) && ( !!errorInfo ) ) ? errorInfo : undefined;
		},
		/**
		 * Opens the dialog with the renderer examples, if any.
		 */
		openExamplesDialog: function () {
			this.showExamplesDialog = true;
		},
		/**
		 * Create the model for a blank object of this type and store it locally.
		 * This initialization will only be run once, and only when we know for
		 * sure that the typeObject is available.
		 */
		initializeBlankObject: function () {
			this.blankObject = hybridToCanonical( this.createObjectByType( { type: this.type } ) );
		}
	} ),
	watch: {
		/**
		 * Watch the prop expanded. When the field is collapsed
		 * generate the rendered value. When the field is expanded
		 * we clear the renderer errors.
		 *
		 * @param {boolean} value
		 */
		expanded: function ( value ) {
			if ( value === false ) {
				this.generateRenderedValue();
			} else {
				if ( this.edit ) {
					this.clearRendererError();
				}
			}
		},
		/**
		 * Watch the computed property validRendererTests and whenever those
		 * are updated, run the renderer function test with the user language
		 * as second input.
		 *
		 * @param {Array} tests
		 */
		validRendererTests: function ( tests ) {
			for ( const test of tests ) {
				this.runRendererTest( {
					rendererZid: this.rendererZid,
					testZid: test.zid,
					test: test.zobject,
					zlang: this.getUserLangZid
				} );
			}
		},
		/**
		 * Watch the typeObject and whenever it's updated, generate the
		 * rendered value, in case the initial generateRenderedValue call
		 * is called before the type object has been fetched.
		 */
		typeObject: function () {
			this.generateRenderedValue();
		}
	},
	mounted: function () {
		this.generateRenderedValue();
		this.generateRendererExamples();
	},
	beforeUnmount: function () {
		// In the case of an abrupt unmount, resolve all pending promises
		this.pendingPromises.forEach( ( resolver ) => {
			resolver.resolve();
		} );
	}
} );
</script>
 
<style lang="less">
@import '../../ext.wikilambda.app.variables.less';
 
.ext-wikilambda-app-object-string-renderer {
	.ext-wikilambda-app-object-string-renderer__text {
		margin: 0;
		line-height: @spacing-200;
	}
 
	.ext-wikilambda-app-object-string-renderer__rendering {
		color: @color-placeholder;
	}
 
	.ext-wikilambda-app-object-string-renderer__error {
		margin-top: @spacing-25;
	}
 
	.ext-wikilambda-app-object-string-renderer__error-footer {
		margin: 0;
		color: @color-subtle;
	}
}
</style>