All files / ext.wikilambda.edit/store/modules/zobject submission.js

99.33% Statements 150/151
95% Branches 76/80
100% Functions 10/10
99.33% Lines 149/150

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                21x 21x 21x 21x 21x   21x                   32x 32x 32x 32x         32x   32x           14x 14x 5x 6x           5x       14x 14x 5x 7x           5x   14x                 13x       1x 1x         1x       13x       5x                                         1x       1x         1x         13x     6x             6x           6x 2x       2x     2x         2x       6x         1x       1x       1x         1x     13x               5x       1x 1x         1x       5x         1x 1x         1x       5x         1x 1x         1x   5x                                   17x   17x 17x   17x                                         27x 27x 27x   27x 27x 27x     27x 11x   11x 11x           27x 1x       27x 2x 2x 3x           2x       27x 5x                         5x             5x 20x 20x 20x   20x 8x 8x                           38x 38x 1x   37x 37x 34x 34x 34x   37x     37x 8x                           20x         20x 4x     16x 16x   21x 21x 21x 29x 8x 8x   21x       21x 16x     16x     21x 21x 7x 7x       16x                           13x 13x   29x 29x 29x         29x       29x     29x 29x 33x 33x 33x 7x   26x         29x 2x       13x 13x                       6x       6x 6x 3x 3x     6x       6x 6x 3x 3x          
/*!
 * WikiLambda Vue editor: ZOBject Vuex module to handle pre submission
 * actions (validation, transformations, and submission)
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
 
const Constants = require( '../../../Constants.js' ),
	convertTableToJson = require( '../../../mixins/zobjectUtils.js' ).methods.convertTableToJson,
	hybridToCanonical = require( '../../../mixins/schemata.js' ).methods.hybridToCanonical,
	apiUtils = require( '../../../mixins/api.js' ).methods,
	isTruthyOrEqual = require( '../../../mixins/typeUtils.js' ).methods.isTruthyOrEqual;
 
module.exports = exports = {
	actions: {
		/**
		 * Return a boolean indicating if the current Z Object is valid based on type requirements
		 * Update error store with any errors found while validating
		 *
		 * @param {Object} context
		 * @return {boolean}
		 */
		validateZObject: function ( context ) {
			const zobjectType = context.getters.getCurrentZObjectType,
				zobject = context.getters.getZObjectAsJson,
				contentRowId = context.getters.getZPersistentContentRowId(),
				innerObject = zobject[ Constants.Z_PERSISTENTOBJECT_VALUE ];
 
			let rowId,
				invalidInputs,
				invalidOutputs,
				isValid = true;
 
			switch ( zobjectType ) {
				// Validate ZFunction:
				// * Output type not set
				// * Input type not set
				case Constants.Z_FUNCTION:
					// invalid if a function doesn't have an output type
					invalidOutputs = context.getters.currentZFunctionInvalidOutput;
					if ( invalidOutputs.length > 0 ) {
						for ( const invalidRow of invalidOutputs ) {
							context.dispatch( 'setError', {
								rowId: invalidRow,
								errorCode: Constants.errorCodes.MISSING_FUNCTION_OUTPUT,
								errorType: Constants.errorTypes.ERROR
							} );
						}
						isValid = false;
					}
 
					// invalid if any of the non-empty inputs doesn't have a type
					invalidInputs = context.getters.currentZFunctionInvalidInputs;
					if ( invalidInputs.length > 0 ) {
						for ( const invalidRow of invalidInputs ) {
							context.dispatch( 'setError', {
								rowId: invalidRow,
								errorCode: Constants.errorCodes.MISSING_FUNCTION_INPUT_TYPE,
								errorType: Constants.errorTypes.ERROR
							} );
						}
						isValid = false;
					}
					return isValid;
 
				// Validate ZImplementation:
				// * Implementation function is not defined (Z14K1)
				// * Composition implementation has undefined function call (Z14K2.Z7K1)
				// * Code implementation has undefined code string (Z14K3.Z16K2)
				case Constants.Z_IMPLEMENTATION:
 
					// invalid if a function hasn't been defined
					if ( !isTruthyOrEqual( innerObject, [
						Constants.Z_IMPLEMENTATION_FUNCTION,
						Constants.Z_REFERENCE_ID
					] ) ) {
						rowId = context.getters.getZImplementationFunctionRowId( contentRowId );
						context.dispatch( 'setError', {
							rowId,
							errorCode: Constants.errorCodes.MISSING_TARGET_FUNCTION,
							errorType: Constants.errorTypes.ERROR
						} );
						isValid = false;
					}
 
					// if implementation type is composition
					if ( innerObject[ Constants.Z_IMPLEMENTATION_COMPOSITION ] ) {
						// invalid if composition hasn't been defined
						// or if composition has an undefied Z7K1
						// or if composition has an undefined Z18K1
						if (
							!isTruthyOrEqual( innerObject, [ Constants.Z_IMPLEMENTATION_COMPOSITION ] ) ||
							(
								innerObject[ Constants.Z_IMPLEMENTATION_COMPOSITION ][
									Constants.Z_FUNCTION_CALL_FUNCTION ] &&
								!isTruthyOrEqual( innerObject, [
									Constants.Z_IMPLEMENTATION_COMPOSITION,
									Constants.Z_FUNCTION_CALL_FUNCTION,
									Constants.Z_REFERENCE_ID
								] )
							) ||
							(
								innerObject[ Constants.Z_IMPLEMENTATION_COMPOSITION ][
									Constants.Z_ARGUMENT_REFERENCE_KEY ] &&
								!isTruthyOrEqual( innerObject, [
									Constants.Z_IMPLEMENTATION_COMPOSITION,
									Constants.Z_ARGUMENT_REFERENCE_KEY,
									Constants.Z_STRING_VALUE
								] )
							)
						) {
							rowId = context.getters.getZImplementationContentRowId(
								contentRowId,
								Constants.Z_IMPLEMENTATION_COMPOSITION
							);
							context.dispatch( 'setError', {
								rowId,
								errorCode: Constants.errorCodes.MISSING_IMPLEMENTATION_COMPOSITION,
								errorType: Constants.errorTypes.ERROR
							} );
							isValid = false;
						}
					}
 
					// if implementation type is code
					if ( innerObject[ Constants.Z_IMPLEMENTATION_CODE ] ) {
 
						// invalid if no programming language is defined
						const hasLiteralProgrammingLanguage = isTruthyOrEqual( innerObject, [
							Constants.Z_IMPLEMENTATION_CODE,
							Constants.Z_CODE_LANGUAGE,
							Constants.Z_PROGRAMMING_LANGUAGE_CODE,
							Constants.Z_STRING_VALUE
						] );
 
						const hasReferencedProgrammingLanguage = isTruthyOrEqual( innerObject, [
							Constants.Z_IMPLEMENTATION_CODE,
							Constants.Z_CODE_LANGUAGE,
							Constants.Z_REFERENCE_ID
						] );
 
						if ( !hasReferencedProgrammingLanguage && !hasLiteralProgrammingLanguage ) {
							rowId = context.getters.getZImplementationContentRowId(
								contentRowId,
								Constants.Z_IMPLEMENTATION_CODE
							);
							const langRow = context.getters.getRowByKeyPath( [
								Constants.Z_CODE_LANGUAGE
							], rowId );
							context.dispatch( 'setError', {
								rowId: langRow.id,
								errorCode: Constants.errorCodes.MISSING_IMPLEMENTATION_CODE_LANGUAGE,
								errorType: Constants.errorTypes.ERROR
							} );
							isValid = false;
						}
 
						// invalid if no code is defined
						if ( !isTruthyOrEqual( innerObject, [
							Constants.Z_IMPLEMENTATION_CODE,
							Constants.Z_CODE_CODE,
							Constants.Z_STRING_VALUE
						] ) ) {
							rowId = context.getters.getZImplementationContentRowId(
								contentRowId,
								Constants.Z_IMPLEMENTATION_CODE
							);
							const codeRow = context.getters.getRowByKeyPath( [
								Constants.Z_CODE_CODE,
								Constants.Z_STRING_VALUE
							], rowId );
							context.dispatch( 'setError', {
								rowId: codeRow.id,
								errorCode: Constants.errorCodes.MISSING_IMPLEMENTATION_CODE,
								errorType: Constants.errorTypes.ERROR
							} );
							isValid = false;
						}
					}
					return isValid;
 
				// Validate ZTester:
				// * Tester function is not defined (Z20K1)
				// * Tester call has undefined function call (Z20K2.Z7K1)
				// * Tester validation has undefined function call (Z20K3.Z7K1)
				case Constants.Z_TESTER:
					// invalid if no function is defined
					if ( !isTruthyOrEqual( innerObject, [
						Constants.Z_TESTER_FUNCTION,
						Constants.Z_REFERENCE_ID
					] ) ) {
						rowId = context.getters.getZTesterFunctionRowId( contentRowId );
						context.dispatch( 'setError', {
							rowId,
							errorCode: Constants.errorCodes.MISSING_TARGET_FUNCTION,
							errorType: Constants.errorTypes.ERROR
						} );
						isValid = false;
					}
 
					// invalid if no function call is set
					if ( !isTruthyOrEqual( innerObject, [
						Constants.Z_TESTER_CALL,
						Constants.Z_FUNCTION_CALL_FUNCTION,
						Constants.Z_REFERENCE_ID
					] ) ) {
						rowId = context.getters.getZTesterCallRowId( contentRowId );
						context.dispatch( 'setError', {
							rowId,
							errorCode: Constants.errorCodes.MISSING_TESTER_CALL,
							errorType: Constants.errorTypes.ERROR
						} );
						isValid = false;
					}
 
					// invalid if no result validation is set
					if ( !isTruthyOrEqual( innerObject, [
						Constants.Z_TESTER_VALIDATION,
						Constants.Z_FUNCTION_CALL_FUNCTION,
						Constants.Z_REFERENCE_ID
					] ) ) {
						rowId = context.getters.getZTesterValidationRowId( contentRowId );
						context.dispatch( 'setError', {
							rowId,
							errorCode: Constants.errorCodes.MISSING_TESTER_VALIDATION,
							errorType: Constants.errorTypes.ERROR
						} );
						isValid = false;
					}
					return isValid;
				default:
					return isValid;
			}
		},
 
		/**
		 * Submit a zObject to the api.
		 * The request is handled differently if new or existing object.
		 * Empty labels are removed before submitting.
		 *
		 * @param {Object} context
		 * @param {Object} param
		 * @param {Object} param.summary
		 * @param {boolean} param.disconnectFunctionObjects
		 * @return {Promise}
		 */
		submitZObject: function ( context, { summary, disconnectFunctionObjects = false } ) {
			context.dispatch( 'transformZObjectForSubmission', disconnectFunctionObjects );
 
			const zobject = hybridToCanonical( convertTableToJson( context.getters.getZObjectTable ) );
			const zid = context.getters.isCreateNewPage ? undefined : context.getters.getCurrentZObjectId;
 
			return apiUtils.saveZObject( {
				zobject,
				zid,
				summary
			} );
		},
 
		/**
		 * Runs actions on the global zobject to make it valid for submission.
		 *
		 * - Clears empty monolingual string labels.
		 * - Clears empty monolingual stringset labels.
		 * - Clears empty arguments and argument labels.
		 * - Removes list items marked as invalid.
		 * - Unattaches implementations and testers, if relevant.
		 *
		 * @param {Object} context
		 * @param {boolean} disconnectFunctionObjects
		 */
		transformZObjectForSubmission: function ( context, disconnectFunctionObjects ) {
			// For al objects: remove empty monolingual string and monolingual stringsets
			context.dispatch( 'removeEmptyMonolingualValues', Constants.Z_PERSISTENTOBJECT_LABEL );
			context.dispatch( 'removeEmptyMonolingualValues', Constants.Z_PERSISTENTOBJECT_DESCRIPTION );
			context.dispatch( 'removeEmptyAliasValues' );
 
			const contentRow = context.getters.getRowByKeyPath( [ Constants.Z_PERSISTENTOBJECT_VALUE ], 0 );
			const contentRowId = contentRow ? contentRow.id : 0;
			const type = context.getters.getZObjectTypeByRowId( contentRowId );
 
			// If object is a function, remove empty argument labels and empty arguments
			if ( type === Constants.Z_FUNCTION ) {
				const functionArguments = context.getters.getRowByKeyPath( [ Constants.Z_FUNCTION_ARGUMENTS ],
					contentRowId );
				Eif ( functionArguments ) {
					context.dispatch( 'removeEmptyArguments' );
				}
			}
 
			// If object is a type, remove empty renderer/parser/equality/validator functions
			// TODO (T359869): If there are type keys, remove empty key labels
			if ( type === Constants.Z_TYPE ) {
				context.dispatch( 'removeEmptyTypeFunctions', contentRowId );
			}
 
			// If a list has changed its type, remove invalid list items
			if ( context.getters.hasInvalidListItems ) {
				const invalidLists = context.getters.getInvalidListItems;
				for ( const parentRowId in invalidLists ) {
					context.dispatch( 'removeItemsFromTypedList', {
						parentRowId: parseInt( parentRowId ),
						listItems: invalidLists[ parentRowId ]
					} );
				}
				// clear the collection of list items removed
				context.dispatch( 'clearListItemsForRemoval' );
			}
 
			// Disconnect implementations and testers if necessary
			if ( disconnectFunctionObjects ) {
				context.dispatch( 'disconnectFunctionObjects' );
			}
		},
 
		/**
		 * Removes Z4K3/Validator, Z4K4/Equality, Z4K5/Renderer and Z4K6/Parser key values
		 * when the values are undefined. Assumes that the current object is a Type/Z4. Also
		 * assumes that the given functions are references, and never literals or function calls.
		 *
		 * @param {Object} context
		 * @param {number} rowId
		 */
		removeEmptyTypeFunctions: function ( context, rowId ) {
			const keys = [
				Constants.Z_TYPE_VALIDATOR,
				Constants.Z_TYPE_EQUALITY,
				Constants.Z_TYPE_RENDERER,
				Constants.Z_TYPE_PARSER
			];
 
			for ( const key of keys ) {
				const keyRow = context.getters.getRowByKeyPath( [ key ], rowId );
				Eif ( keyRow ) {
					const value = context.getters.getZReferenceTerminalValue( keyRow.id );
					// If value is empty, remove the key altogether
					if ( !value ) {
						context.dispatch( 'removeRowChildren', keyRow.id );
						context.dispatch( 'removeRow', keyRow.id );
					}
				}
			}
		},
 
		/**
		 * Removes the name or description label language objects with empty monolingual
		 * string or language values from the global zobject.
		 *
		 * @param {Object} context
		 * @param {string} key Z_PERSISTENTOBJECT_LABEL or Z_PERSISTENTOBJECT_DESCRIPTION
		 */
		removeEmptyMonolingualValues: function ( context, key ) {
			const listRow = context.getters.getRowByKeyPath( [ key, Constants.Z_MULTILINGUALSTRING_VALUE ], 0 );
			if ( !listRow ) {
				return;
			}
			const rows = context.getters.getChildrenByParentRowId( listRow.id ).slice( 1 );
			const deleteRows = rows.filter( ( monolingualRow ) => {
				const labelString = context.getters.getZMonolingualTextValue( monolingualRow.id );
				const languageValue = context.getters.getZMonolingualLangValue( monolingualRow.id );
				return !labelString || !languageValue;
			} );
			const deleteRowIds = deleteRows.map( ( row ) => row.id );
 
			// Remove list of invalid items and, once all deleted, recalculate the array keys
			if ( deleteRowIds.length > 0 ) {
				context.dispatch( 'removeItemsFromTypedList', {
					parentRowId: listRow.id,
					listItems: deleteRowIds
				} );
			}
		},
 
		/**
		 * Removes the alias label language objects with empty monolingual string
		 * or language values from the global zobject.
		 *
		 * @param {Object} context
		 */
		removeEmptyAliasValues: function ( context ) {
			const aliasRow = context.getters.getRowByKeyPath( [
				Constants.Z_PERSISTENTOBJECT_ALIASES,
				Constants.Z_MULTILINGUALSTRINGSET_VALUE
			] );
 
			if ( !aliasRow ) {
				return;
			}
 
			const aliasSet = context.getters.getChildrenByParentRowId( aliasRow.id ).slice( 1 );
			for ( const alias of aliasSet ) {
				// Iterate over the values and remove empty ones
				const aliasValues = context.getters.getZMonolingualStringsetValues( alias.id );
				const goodValues = [];
				for ( const value of aliasValues ) {
					if ( !value.value ) {
						context.dispatch( 'removeRowChildren', value.rowId );
						context.dispatch( 'removeRow', value.rowId );
					} else {
						goodValues.push( value );
					}
				}
				// If there are aliases left, recalculate list keys
				if ( goodValues.length > 0 ) {
					const listRow = context.getters.getRowByKeyPath( [
						Constants.Z_MONOLINGUALSTRINGSET_VALUE
					], alias.id );
					context.dispatch( 'recalculateTypedListKeys', listRow.id );
				}
				// If alias has no values or no language, remove whole alias
				const aliasLang = context.getters.getZMonolingualStringsetLang( alias.id );
				if ( !aliasLang || goodValues.length === 0 ) {
					context.dispatch( 'removeRowChildren', alias.id );
					context.dispatch( 'removeRow', alias.id );
				}
			}
			// Recalculate the keys of the list of monolingual string sets
			context.dispatch( 'recalculateTypedListKeys', aliasRow.id );
		},
 
		/**
		 * Removes the function argument label language objects with empty monolingual
		 * string or language values from the global zobject.
		 *
		 * @param {Object} context
		 */
		removeEmptyArguments: function ( context ) {
			// For every argument, we remove it from the list if:
			// 1. argument type is empty, and
			// 2. argument labels are empty
			// Else, we just clear the empty labels
			const inputs = context.getters.getZFunctionInputs();
			for ( const inputRow of inputs ) {
				// Get the value of the input type
				const inputTypeRow = context.getters.getRowByKeyPath( [ Constants.Z_ARGUMENT_TYPE ], inputRow.id );
				const inputTypeMode = context.getters.getZObjectTypeByRowId( inputTypeRow.id );
				const inputTypeValue = ( inputTypeMode === Constants.Z_REFERENCE ) ?
					context.getters.getZReferenceTerminalValue( inputTypeRow.id ) :
					context.getters.getZFunctionCallFunctionId( inputTypeRow.id );
 
				// Get the input labels
				const inputLabelsRow = context.getters.getRowByKeyPath( [
					Constants.Z_ARGUMENT_LABEL,
					Constants.Z_MULTILINGUALSTRING_VALUE
				], inputRow.id );
				const inputLabels = context.getters.getChildrenByParentRowId( inputLabelsRow.id ).slice( 1 );
 
				// Remove labels with empty text or language
				const inputLabelValues = [];
				for ( const labelRow of inputLabels ) {
					const labelValue = context.getters.getZMonolingualTextValue( labelRow.id );
					const languageValue = context.getters.getZMonolingualLangValue( labelRow.id );
					if ( !labelValue || !languageValue ) {
						context.dispatch( 'removeItemFromTypedList', { rowId: labelRow.id } );
					} else {
						inputLabelValues.push( labelValue );
					}
				}
 
				// If input is empty and labels are empty, remove this item
				if ( ( inputTypeValue === undefined ) && ( inputLabelValues.length === 0 ) ) {
					context.dispatch( 'removeItemFromTypedList', { rowId: inputRow.id } );
				}
			}
 
			Eif ( inputs.length > 0 ) {
				context.dispatch( 'recalculateArgumentKeys', inputs[ 0 ].parent );
			}
		},
 
		/**
		 * Remove implementation and tester from a ZObject
		 * The zObject has to be of type function
		 *
		 * @param {Object} context
		 */
		disconnectFunctionObjects: function ( context ) {
			// Disconnect implementations
			const implementationRow = context.getters.getRowByKeyPath( [
				Constants.Z_PERSISTENTOBJECT_VALUE,
				Constants.Z_FUNCTION_IMPLEMENTATIONS
			] );
			const implementations = context.getters.getChildrenByParentRowId( implementationRow.id ).slice( 1 );
			for ( const row of implementations ) {
				context.dispatch( 'removeRowChildren', row.id );
				context.dispatch( 'removeRow', row.id );
			}
			// Disconnect testers
			const testerRow = context.getters.getRowByKeyPath( [
				Constants.Z_PERSISTENTOBJECT_VALUE,
				Constants.Z_FUNCTION_TESTERS
			] );
			const testers = context.getters.getChildrenByParentRowId( testerRow.id ).slice( 1 );
			for ( const row of testers ) {
				context.dispatch( 'removeRowChildren', row.id );
				context.dispatch( 'removeRow', row.id );
			}
		}
	}
};