Debian Codegraph @

extensions/TemplateData/modules/ext.templateDataGenerator.data/Model.js

raw symbols SCIP
1 /**
2 * TemplateData Model
3 *
4 * @class
5 * @mixes OO.EventEmitter
6 *
7 * @constructor
8 */
9 function Model() {
10 // Mixin constructors
11 OO.EventEmitter.call( this );
12
13 // Properties
14 this.description = {};
15
16 this.maps = undefined;
17 this.mapsChanged = false;
18 this.originalMaps = undefined;
19
20 this.format = null;
21
22 this.params = {};
23 this.paramIdentifierCounter = 2;
24 this.sourceCodeParameters = [];
25 this.paramOrder = [];
26 this.paramOrderChanged = false;
27
28 this.originalTemplateDataObject = null;
29 }
30
31 /* Inheritance */
32
33 OO.mixinClass( Model, OO.EventEmitter );
34
35 /* Events */
36
37 /**
38 * @event add-param
39 * @param {string} key Parameter key
40 * @param {Object} data Parameter data
41 */
42
43 /**
44 * @event change-description
45 * @param {string} description New template description
46 * @param {Object} [language] Description language, if supplied
47 */
48
49 /**
50 * @event change-paramOrder
51 * @param {string[]} orderArray Parameter key array in order
52 */
53
54 /**
55 * @event change-property
56 * @param {string} paramKey Parameter key
57 * @param {string} prop Property name
58 * @param {Mixed} value
59 * @param {string} language
60 */
61
62 /**
63 * @event change
64 */
65
66 /* Static Methods */
67
68 /**
69 * Compare two objects or strings
70 *
71 * @param {Object|string} obj1 Base object
72 * @param {Object|string} obj2 Compared object
73 * @param {boolean} [allowSubset] Allow the second object to be a
74 * partial object (or a subset) of the first.
75 * @return {boolean} Objects have equal values
76 */
77 Model.static.compare = function ( obj1, obj2, allowSubset ) {
78 if ( obj1 === obj2 || ( allowSubset && obj2 === undefined ) ) {
79 return true;
80 }
81
82 if ( typeof obj1 !== typeof obj2 ) {
83 return false;
84 }
85
86 return typeof obj1 === 'object' && OO.compare( obj2, obj1, allowSubset );
87 };
88
89 /**
90 * Translate obsolete parameter types into the new types
91 *
92 * @param {string} paramType Given type
93 * @return {string} Normalized non-obsolete type
94 */
95 Model.static.translateObsoleteParamTypes = function ( paramType ) {
96 return paramType.replace( /^string\//, '' );
97 };
98
99 /**
100 * Retrieve information about all legal properties for a parameter.
101 *
102 * @param {boolean} getFullData Retrieve full information about each
103 * parameter. If false, the method will return an array of property
104 * names only.
105 * @return {Object|string[]} Legal property names with or without their
106 * definition data
107 */
108 Model.static.getAllProperties = function ( getFullData ) {
109 const properties = {
110 name: {
111 type: 'string',
112 // Validation regex
113 restrict: /[|=]|}}/
114 },
115 aliases: {
116 type: 'array'
117 },
118 label: {
119 type: 'string',
120 allowLanguages: true
121 },
122 description: {
123 type: 'string',
124 allowLanguages: true
125 },
126 example: {
127 type: 'string',
128 allowLanguages: true
129 },
130 type: {
131 type: 'select',
132 children: [
133 'unknown',
134 'boolean',
135 'content',
136 'wiki-file-name',
137 'line',
138 'number',
139 'date',
140 'wiki-page-name',
141 'string',
142 'wiki-template-name',
143 'unbalanced-wikitext',
144 'url',
145 'wiki-user-name'
146 ],
147 default: 'unknown'
148 },
149 suggestedvalues: {
150 type: 'array'
151 },
152 default: {
153 type: 'string',
154 multiline: true,
155 allowLanguages: true
156 },
157 autovalue: {
158 type: 'string'
159 },
160 status: {
161 type: 'select',
162 children: [
163 'optional',
164 'deprecated',
165 'required',
166 'suggested'
167 ],
168 default: 'optional'
169 },
170 deprecated: {
171 type: 'boolean',
172 // This should only be defined for boolean properties.
173 // Define the property that represents the text value.
174 textValue: 'deprecatedValue'
175 },
176 deprecatedValue: {
177 type: 'string'
178 },
179 required: {
180 type: 'boolean'
181 },
182 suggested: {
183 type: 'boolean'
184 }
185 };
186
187 if ( !getFullData ) {
188 return Object.keys( properties );
189 } else {
190 return properties;
191 }
192 };
193
194 /**
195 * Retrieve the list of property names that allow for multiple languages.
196 *
197 * @return {string[]} Property names
198 */
199 Model.static.getPropertiesWithLanguage = function () {
200 const result = [],
201 propDefinitions = this.getAllProperties( true );
202
203 for ( const prop in propDefinitions ) {
204 if ( propDefinitions[ prop ].allowLanguages ) {
205 result.push( prop );
206 }
207 }
208 return result;
209 };
210
211 /**
212 * Split a string into an array and clean/trim the values
213 *
214 * @param {string} str String to split
215 * @param {string} [delim] Delimeter
216 * @return {string[]} Clean array
217 */
218 Model.static.splitAndTrimArray = function ( str, delim ) {
219 delim = delim || mw.msg( 'comma-separator' );
220
221 const arr = [];
222 str.split( delim ).forEach( ( part ) => {
223 const trimmed = part.trim();
224 if ( trimmed ) {
225 arr.push( trimmed );
226 }
227 } );
228
229 return arr;
230 };
231
232 /**
233 * This is an adjustment of OO.simpleArrayUnion that ignores
234 * empty values when inserting into the unified array.
235 *
236 * @param {...Array} arrays Arrays to union
237 * @return {Array} Union of the arrays
238 */
239 Model.static.arrayUnionWithoutEmpty = function () {
240 const result = OO.simpleArrayUnion.apply( this, arguments );
241
242 // Trim and filter empty strings
243 return result.filter( ( i ) => i.trim() );
244 };
245
246 /**
247 * Create a new mwTemplateData.Model from templatedata object.
248 *
249 * @param {Object|null} tdObject TemplateData parsed object, or null if we are creating a new object.
250 * @param {string[]} paramsInSource Parameter names found in template source
251 * @return {Model} New model
252 */
253 Model.static.newFromObject = function ( tdObject, paramsInSource ) {
254 const model = new Model();
255
256 model.setSourceCodeParameters( paramsInSource || [] );
257
258 // Store the original templatedata object for comparison later
259 model.setOriginalTemplateDataObject( tdObject );
260
261 tdObject = tdObject || { params: {} };
262
263 // Initialize the model
264 model.params = {};
265
266 // Add params
267 if ( tdObject.params ) {
268 for ( const param in tdObject.params ) {
269 model.addParam( param, tdObject.params[ param ] );
270 }
271 }
272
273 // maps
274 if ( tdObject.maps ) {
275 model.setMapInfo( tdObject.maps );
276 }
277
278 model.setTemplateDescription( tdObject.description );
279
280 // Override the param order if it exists in the templatedata string
281 if ( tdObject.paramOrder && tdObject.paramOrder.length > 0 ) {
282 model.setTemplateParamOrder( tdObject.paramOrder );
283 }
284
285 if ( tdObject.format !== undefined ) {
286 model.setTemplateFormat( tdObject.format );
287 }
288
289 return model;
290 };
291
292 /* Methods */
293
294 /**
295 * Go over the importable parameters and check if they are
296 * included in the parameter model. Return the parameter names
297 * that are not included yet.
298 *
299 * @return {string[]} Parameters that are not yet included in
300 * the model
301 */
302 Model.prototype.getMissingParams = function () {
303 const allParamNames = this.getAllParamNames(),
304 sourceCodeParameters = this.sourceCodeParameters;
305
306 return sourceCodeParameters.filter( ( sourceCodeParameter ) => allParamNames.indexOf( sourceCodeParameter ) === -1 );
307 };
308
309 /**
310 * Add imported parameters into the model
311 *
312 * @return {Object} Parameters added. -1 for failure.
313 */
314 Model.prototype.importSourceCodeParameters = function () {
315 const allParamNames = this.getAllParamNames(),
316 existingArray = [],
317 importedArray = [],
318 skippedArray = [];
319
320 // Check existing params
321 allParamNames.forEach( ( paramKey ) => {
322 if ( this.sourceCodeParameters.indexOf( paramKey ) !== -1 ) {
323 existingArray.push( paramKey );
324 }
325 } );
326
327 // Add sourceCodeParameters to the model
328 this.sourceCodeParameters.forEach( ( sourceCodeParameter ) => {
329 if ( existingArray.indexOf( sourceCodeParameter ) === -1 ) {
330 this.addParam( sourceCodeParameter );
331 importedArray.push( sourceCodeParameter );
332 } else {
333 skippedArray.push( sourceCodeParameter );
334 }
335 } );
336
337 return {
338 imported: importedArray,
339 skipped: skippedArray,
340 existing: existingArray
341 };
342 };
343
344 /**
345 * Retrieve all existing language codes in the current templatedata model
346 *
347 * @return {string[]} Language codes in use
348 */
349 Model.prototype.getExistingLanguageCodes = function () {
350 let result = [];
351
352 // Take languages from the template description
353 if ( $.isPlainObject( this.description ) ) {
354 result = Object.keys( this.description );
355 }
356
357 const languageProps = this.constructor.static.getPropertiesWithLanguage();
358 // Go over the parameters
359 for ( const param in this.params ) {
360 // Go over the properties
361 for ( const prop in this.params[ param ] ) {
362 if ( languageProps.indexOf( prop ) !== -1 ) {
363 result = this.constructor.static.arrayUnionWithoutEmpty( result, Object.keys( this.params[ param ][ prop ] ) );
364 }
365 }
366 }
367
368 return result;
369 };
370
371 /**
372 * Add parameter to the model
373 *
374 * @param {string} name
375 * @param {Object} [paramData] Parameter data
376 * @fires add-param
377 * @fires change
378 */
379 Model.prototype.addParam = function ( name, paramData ) {
380 const data = $.extend( true, {}, paramData );
381 const key = this.getNewValidParameterKey( name );
382
383 // Initialize
384 this.params[ key ] = { name: name };
385
386 // Mark the parameter if it is in the template source
387 if ( this.sourceCodeParameters.indexOf( key ) !== -1 ) {
388 this.params[ key ].inSource = true;
389 }
390
391 // Translate types
392 if ( data.type !== undefined ) {
393 data.type = this.constructor.static.translateObsoleteParamTypes( data.type );
394 this.params[ key ].type = data.type;
395 }
396
397 // Get the deprecated value
398 if ( typeof data.deprecated === 'string' ) {
399 this.params[ key ].deprecatedValue = data.deprecated;
400 }
401
402 // Go over the rest of the data
403 if ( data ) {
404 const language = this.getDefaultLanguage();
405 const propertiesWithLanguage = this.constructor.static.getPropertiesWithLanguage();
406 const allProps = this.constructor.static.getAllProperties( true );
407 for ( const prop in data ) {
408 let propToSet = prop;
409 if (
410 // This is to make sure that forwards compatibility is achieved
411 // and the code doesn't die on properties that aren't valid
412 allProps[ prop ] &&
413 // Check if property should have its text represented in another internal property
414 // (for example, deprecated and deprecatedValue)
415 allProps[ prop ].textValue
416 ) {
417 // Set the textValue property
418 propToSet = allProps[ prop ].textValue;
419 // Set the boolean value in the current property
420 this.setParamProperty( key, prop, !!data[ prop ], language );
421 if ( typeof data[ prop ] === 'boolean' ) {
422 // Only set the value of the dependent if the value is a string or
423 // language. Otherwise, if the value is boolean, keep the dependent
424 // empty.
425 continue;
426 }
427 }
428
429 if (
430 propertiesWithLanguage.indexOf( propToSet ) !== -1 &&
431 $.isPlainObject( data[ prop ] )
432 ) {
433 // Add all language properties
434 for ( const lang in data[ prop ] ) {
435 this.setParamProperty( key, propToSet, data[ prop ], lang );
436 }
437 } else {
438 this.setParamProperty( key, propToSet, data[ prop ], language );
439 }
440 }
441 }
442
443 // Add to paramOrder
444 this.addKeyTemplateParamOrder( key );
445
446 // Trigger the add parameter event
447 this.emit( 'add-param', key, this.params[ key ] );
448 this.emit( 'change' );
449 };
450
451 /**
452 * Retrieve an array of all used parameter names. Note that parameter
453 * names can be different than their stored keys.
454 *
455 * @return {string[]} Used parameter names
456 */
457 Model.prototype.getAllParamNames = function () {
458 let result = [];
459 for ( const key in this.params ) {
460 const param = this.params[ key ];
461 result.push( param.name );
462 if ( param.aliases ) {
463 result = result.concat( param.aliases );
464 }
465 }
466
467 return result;
468 };
469
470 /**
471 * Set the template description
472 *
473 * @param {string|Object} desc New template description
474 * @param {string} [language] Description language, if supplied. If not given,
475 * will default to the wiki language.
476 * @fires change-description
477 * @fires change
478 */
479 Model.prototype.setTemplateDescription = function ( desc, language ) {
480 language = language || this.getDefaultLanguage();
481
482 if ( !this.constructor.static.compare( this.description[ language ], desc ) ) {
483 if ( typeof desc === 'object' ) {
484 Object.assign( this.description, desc );
485 this.emit( 'change-description', desc[ language ], language );
486 } else {
487 this.description[ language ] = desc;
488 this.emit( 'change-description', desc, language );
489 }
490 this.emit( 'change' );
491 }
492 };
493
494 /**
495 * Get the template description.
496 *
497 * @param {string} [language] Optional language key
498 * @return {string}
499 */
500 Model.prototype.getTemplateDescription = function ( language ) {
501 language = language || this.getDefaultLanguage();
502 return this.description[ language ];
503 };
504
505 /**
506 * @param {Object|undefined} map New template map info
507 * @fires change-map
508 * @fires change
509 */
510 Model.prototype.setMapInfo = function ( map ) {
511 if ( map !== undefined ) {
512 if ( !this.constructor.static.compare( this.maps, map ) ) {
513 if ( this.mapsChanged === false ) {
514 this.originalMaps = OO.copy( map );
515 this.mapsChanged = true;
516 }
517 this.maps = map;
518 this.emit( 'change-map', map );
519 this.emit( 'change' );
520 }
521 }
522 };
523
524 /**
525 * Get the template info.
526 *
527 * @return {Object|undefined} The template map info.
528 */
529 Model.prototype.getMapInfo = function () {
530 return this.maps;
531 };
532
533 /**
534 * Get the template info.
535 *
536 * @return {Object|undefined} The Original template map info.
537 */
538 Model.prototype.getOriginalMapsInfo = function () {
539 return this.originalMaps;
540 };
541
542 /**
543 * Get a specific parameter's localized property
544 *
545 * @param {string} paramKey Parameter key
546 * @param {string} property Property name
547 * @param {string} [language] Optional language key
548 * @return {string} Parameter property in specified language
549 */
550 Model.prototype.getParamValue = function ( paramKey, property, language ) {
551 language = language || this.getDefaultLanguage();
552 return OO.getProp( this.params, paramKey, property, language ) || '';
553 };
554
555 /**
556 * Get the current wiki language code. Defaults on 'en'.
557 *
558 * @return {string} Wiki language
559 */
560 Model.prototype.getDefaultLanguage = function () {
561 return mw.config.get( 'wgContentLanguage' ) || 'en';
562 };
563
564 /**
565 * Set template param order array.
566 *
567 * @param {string[]} [orderArray] Parameter key array in order
568 * @fires change-paramOrder
569 * @fires change
570 */
571 Model.prototype.setTemplateParamOrder = function ( orderArray ) {
572 orderArray = orderArray || [];
573 // TODO: Make the compare method verify order of array?
574 // Copy the array
575 this.paramOrder = orderArray.slice();
576 this.emit( 'change-paramOrder', orderArray );
577 this.emit( 'change' );
578 };
579
580 /**
581 * Set template format.
582 *
583 * @param {string|null} [format=null] Preferred format
584 * @fires change-format
585 * @fires change
586 */
587 Model.prototype.setTemplateFormat = function ( format ) {
588 format = format || null;
589 if ( this.format !== format ) {
590 this.format = format;
591 this.emit( 'change-format', format );
592 this.emit( 'change' );
593 }
594 };
595
596 /**
597 * Add a key to the end of the paramOrder
598 *
599 * @param {string} key New key the add into the paramOrder
600 * @fires add-paramOrder
601 * @fires change
602 */
603 Model.prototype.addKeyTemplateParamOrder = function ( key ) {
604 if ( this.paramOrder.indexOf( key ) === -1 ) {
605 this.paramOrder.push( key );
606 this.emit( 'add-paramOrder', key );
607 this.emit( 'change' );
608 }
609 };
610
611 /**
612 * TODO: document
613 *
614 * @param {string} key
615 * @param {number} newIndex
616 * @fires change-paramOrder
617 * @fires change
618 */
619 Model.prototype.reorderParamOrderKey = function ( key, newIndex ) {
620 const keyIndex = this.paramOrder.indexOf( key );
621 // Move the parameter, account for left shift if moving forwards
622 this.paramOrder.splice(
623 newIndex - ( newIndex > keyIndex ? 1 : 0 ),
624 0,
625 this.paramOrder.splice( keyIndex, 1 )[ 0 ]
626 );
627
628 this.paramOrderChanged = true;
629
630 // Emit event
631 this.emit( 'change-paramOrder', this.paramOrder );
632 this.emit( 'change' );
633 };
634
635 /**
636 * Add a key to the end of the paramOrder
637 *
638 * @param {string} key New key the add into the paramOrder
639 * @fires change-paramOrder
640 * @fires change
641 */
642 Model.prototype.removeKeyTemplateParamOrder = function ( key ) {
643 const keyPos = this.paramOrder.indexOf( key );
644 if ( keyPos > -1 ) {
645 this.paramOrder.splice( keyPos, 1 );
646 this.emit( 'change-paramOrder', this.paramOrder );
647 this.emit( 'change' );
648 }
649 };
650
651 /**
652 * Retrieve the template paramOrder array
653 *
654 * @return {string[]} orderArray Parameter keys in order
655 */
656 Model.prototype.getTemplateParamOrder = function () {
657 return this.paramOrder;
658 };
659
660 /**
661 * Retrieve the template preferred format
662 *
663 * @return {string|null} Preferred format
664 */
665 Model.prototype.getTemplateFormat = function () {
666 return this.format;
667 };
668
669 /**
670 * Set a specific parameter's property
671 *
672 * @param {string} paramKey Parameter key
673 * @param {string} prop Property name
674 * @param {Mixed} value
675 * @param {string} [language] Value language
676 * @return {boolean} Operation was successful
677 * @fires change-property
678 * @fires change
679 */
680 Model.prototype.setParamProperty = function ( paramKey, prop, value, language ) {
681 const allProps = this.constructor.static.getAllProperties( true );
682 let status = false;
683
684 language = language || this.getDefaultLanguage();
685 if ( !allProps[ prop ] ) {
686 // The property isn't supported yet
687 return status;
688 }
689
690 const propertiesWithLanguage = this.constructor.static.getPropertiesWithLanguage();
691 // Check if the property is split by language code
692 if ( propertiesWithLanguage.indexOf( prop ) !== -1 ) {
693 // Initialize property if necessary
694 if ( !$.isPlainObject( this.params[ paramKey ][ prop ] ) ) {
695 this.params[ paramKey ][ prop ] = {};
696 }
697 value = $.isPlainObject( value ) ? value[ language ] : value;
698 // Compare with language
699 if ( !this.constructor.static.compare( this.params[ paramKey ][ prop ][ language ], value ) ) {
700 this.params[ paramKey ][ prop ][ language ] = value;
701 this.emit( 'change-property', paramKey, prop, value, language );
702 this.emit( 'change' );
703 status = true;
704 }
705 } else {
706 // Compare without language
707 if ( !this.constructor.static.compare( this.params[ paramKey ][ prop ], value ) ) {
708 const oldValue = this.params[ paramKey ][ prop ];
709 this.params[ paramKey ][ prop ] = value;
710
711 let newKey = value;
712 if ( prop === 'name' && oldValue !== value ) {
713 // See if the parameters already has something with this new key
714 if ( this.params[ newKey ] && !this.params[ newKey ].deleted ) {
715 // Change the key to be something else
716 newKey = this.getNewValidParameterKey( newKey );
717 }
718 // Copy param details to new name
719 this.params[ newKey ] = this.params[ paramKey ];
720 // Delete the old param
721 this.params[ paramKey ] = { deleted: true };
722 }
723
724 this.emit( 'change-property', paramKey, prop, value, language );
725 this.emit( 'change' );
726
727 if ( prop === 'name' ) {
728 this.paramOrder[ this.paramOrder.indexOf( paramKey ) ] = newKey;
729 this.paramOrderChanged = true;
730 this.emit( 'change-paramOrder', this.paramOrder );
731 this.emit( 'change' );
732 }
733
734 status = true;
735 }
736 }
737
738 if ( allProps[ prop ].textValue && value === false ) {
739 // Unset the text value if the boolean it depends on is false
740 status = this.setParamProperty( paramKey, allProps[ prop ].textValue, '', language );
741 }
742
743 return status;
744 };
745
746 /**
747 * Mark a parameter for deletion.
748 * Don't actually delete the parameter so we can make sure it is removed
749 * from the final output.
750 *
751 * @param {string} paramKey Parameter key
752 * @fires delete-param
753 * @fires change
754 */
755 Model.prototype.deleteParam = function ( paramKey ) {
756 this.params[ paramKey ].deleted = true;
757 // Remove from paramOrder
758 this.removeKeyTemplateParamOrder( paramKey );
759 this.emit( 'delete-param', paramKey );
760 this.emit( 'change' );
761 };
762
763 /**
764 * Delete all data attached to a parameter
765 *
766 * @param {string} paramKey Parameter key
767 */
768 Model.prototype.emptyParamData = function ( paramKey ) {
769 if ( this.params[ paramKey ] ) {
770 // Delete all data and readd the parameter
771 delete this.params[ paramKey ];
772 this.addParam( paramKey );
773 // Mark this parameter as intentionally emptied
774 this.params[ paramKey ].emptied = true;
775 }
776 };
777
778 /**
779 * Get a parameter property.
780 *
781 * @param {string} paramKey Parameter key
782 * @param {string} prop Parameter property
783 * @return {Mixed|null} Property value if it exists. Returns null if the
784 * parameter key itself doesn't exist.
785 */
786 Model.prototype.getParamProperty = function ( paramKey, prop ) {
787 if ( this.params[ paramKey ] ) {
788 return this.params[ paramKey ][ prop ];
789 }
790 return null;
791 };
792
793 /**
794 * Retrieve a specific parameter data
795 *
796 * @param {string} key Parameter key
797 * @return {Object|undefined} Parameter data
798 */
799 Model.prototype.getParamData = function ( key ) {
800 return this.params[ key ];
801 };
802
803 /**
804 * Return the complete object of all parameters.
805 *
806 * @return {Object} All parameters and their data
807 */
808 Model.prototype.getParams = function () {
809 return this.params;
810 };
811
812 Model.prototype.isParamDeleted = function ( key ) {
813 return this.params[ key ] && this.params[ key ].deleted === true;
814 };
815
816 Model.prototype.isParamExists = function ( key ) {
817 return Object.prototype.hasOwnProperty.call( this.params, key );
818 };
819
820 /**
821 * Set the original templatedata object
822 *
823 * @param {Object|null} templatedataObj TemplateData object
824 */
825 Model.prototype.setOriginalTemplateDataObject = function ( templatedataObj ) {
826 this.originalTemplateDataObject = templatedataObj ? $.extend( true, {}, templatedataObj ) : null;
827 };
828
829 /**
830 * Get full page name
831 *
832 * @param {string} pageName Page name
833 */
834 Model.prototype.setFullPageName = function ( pageName ) {
835 this.fullPageName = pageName;
836 };
837
838 /**
839 * Set parent page
840 *
841 * @param {string} parent Parent page
842 */
843 Model.prototype.setParentPage = function ( parent ) {
844 this.parentPage = parent;
845 };
846
847 /**
848 * Get page full name
849 *
850 * @return {string} Page full name
851 */
852 Model.prototype.getFullPageName = function () {
853 return this.fullPageName;
854 };
855
856 /**
857 * Get parent page
858 *
859 * @return {string} Parent page
860 */
861 Model.prototype.getParentPage = function () {
862 return this.parentPage;
863 };
864
865 /**
866 * Get original Parameters/Info from the model and discard any changes
867 */
868 Model.prototype.restoreOriginalMaps = function () {
869 this.setMapInfo( this.getOriginalMapsInfo() );
870 };
871
872 /**
873 * Get original templatedata object
874 *
875 * @return {Object|null} Templatedata object at the beginning of this editing session, or null
876 * if we're creating a new object.
877 */
878 Model.prototype.getOriginalTemplateDataObject = function () {
879 return this.originalTemplateDataObject;
880 };
881
882 /**
883 * Process the current model and output it
884 *
885 * @return {Object} Templatedata object
886 */
887 Model.prototype.outputTemplateData = function () {
888 const allProps = this.constructor.static.getAllProperties( true ),
889 original = this.getOriginalTemplateDataObject() || {};
890 original.params = original.params || {};
891 const result = $.extend( true, {}, original ),
892 defaultLang = this.getDefaultLanguage();
893
894 let normalizedValue;
895 // Template description
896 if ( this.description[ defaultLang ] !== undefined ) {
897 normalizedValue = this.propRemoveUnusedLanguages( this.description );
898 if ( this.isOutputInLanguageObject( result.description, normalizedValue ) ) {
899 result.description = normalizedValue;
900 } else {
901 // Store only one language as a string
902 result.description = normalizedValue[ defaultLang ];
903 }
904 } else {
905 // Delete description
906 delete result.description;
907 }
908
909 // Template maps
910 if ( this.maps === undefined || Object.keys( this.maps ).length === 0 ) {
911 delete result.maps;
912 } else {
913 result.maps = this.maps;
914 }
915
916 // Param order
917 if ( original.paramOrder || this.paramOrderChanged ) {
918 result.paramOrder = this.paramOrder;
919 } else {
920 delete result.paramOrder;
921 }
922
923 // Format
924 if ( this.format === null ) {
925 delete result.format;
926 } else {
927 result.format = this.format;
928 }
929
930 // Attach sets as-is for now
931 // TODO: Work properly with sets
932 if ( original.sets ) {
933 result.sets = original.sets;
934 }
935
936 // Go over parameters in data
937 for ( const paramKey in this.params ) {
938 const key = paramKey;
939 if ( this.params[ key ].deleted ) {
940 delete result.params[ key ];
941 continue;
942 }
943
944 // If the user intentionally empties a parameter, delete it from
945 // the result and treat it as a new parameter
946 if ( this.params[ key ].emptied ) {
947 delete result.params[ key ];
948 }
949
950 // Check if name was changed and change the key accordingly
951 const name = this.params[ key ].name;
952 const oldKey = key;
953
954 // Notice for clarity:
955 // Whether the parameter name was changed or not the following
956 // consistency with object keys will be observed:
957 // * oldKey: original will use oldKey (for comparison to the old value)
958 // * key: this.params will use key (for storing without conflict)
959 // * name: result will use name (for valid output)
960
961 // Check if param is new
962 if ( !result.params[ name ] ) {
963 // New param. Initialize it
964 result.params[ name ] = {};
965 }
966
967 // Go over all properties
968 for ( const prop in allProps ) {
969 if ( prop === 'status' || prop === 'deprecatedValue' || prop === 'name' ) {
970 continue;
971 }
972
973 switch ( allProps[ prop ].type ) {
974 case 'select':
975 // Only include type if the original included type
976 // or if the current type is not undefined
977 if (
978 original.params[ key ] &&
979 original.params[ key ][ prop ] !== 'unknown' &&
980 this.params[ key ][ prop ] === 'unknown'
981 ) {
982 result.params[ name ][ prop ] = undefined;
983 } else {
984 result.params[ name ][ prop ] = this.params[ key ][ prop ];
985 }
986 break;
987 case 'boolean':
988 if ( !this.params[ key ][ prop ] ) {
989 // Only add a literal false value if there was a false
990 // value before
991 if ( original.params[ oldKey ] && original.params[ oldKey ][ prop ] === false ) {
992 result.params[ name ][ prop ] = false;
993 } else {
994 // Otherwise, delete this value
995 delete result.params[ name ][ prop ];
996 }
997 } else {
998 if ( prop === 'deprecated' ) {
999 result.params[ name ][ prop ] = this.params[ key ].deprecatedValue || true;
1000 // Remove deprecatedValue
1001 delete result.params[ name ].deprecatedValue;
1002 } else {
1003 result.params[ name ][ prop ] = this.params[ key ][ prop ];
1004 }
1005 }
1006 break;
1007 case 'array':
1008 // Only update these if the new templatedata has an
1009 // array that isn't empty
1010 if (
1011 Array.isArray( this.params[ key ][ prop ] ) &&
1012 this.params[ key ][ prop ].length > 0
1013 ) {
1014 result.params[ name ][ prop ] = this.params[ key ][ prop ];
1015 } else {
1016 // If the new array is empty, delete it from the original
1017 delete result.params[ name ][ prop ];
1018 }
1019 break;
1020 default:
1021 // Check if there's a value in the model
1022 if ( this.params[ key ][ prop ] !== undefined ) {
1023 const compareOrig = original.params[ oldKey ] && original.params[ oldKey ][ prop ];
1024 if ( allProps[ prop ].allowLanguages ) {
1025 normalizedValue = this.propRemoveUnusedLanguages( this.params[ key ][ prop ] );
1026 // Check if this should be displayed with language object or directly as string
1027 if ( this.isOutputInLanguageObject( compareOrig || {}, normalizedValue ) ) {
1028 result.params[ name ][ prop ] = normalizedValue;
1029 } else {
1030 // Store only one language as a string
1031 result.params[ name ][ prop ] = normalizedValue[ defaultLang ];
1032 }
1033 } else if ( this.params[ key ][ prop ] ||
1034 // Add empty strings only if the property existed before (empty or not)
1035 compareOrig !== undefined
1036 ) {
1037 // Set up the result
1038 result.params[ name ][ prop ] = this.params[ key ][ prop ];
1039 }
1040 }
1041 break;
1042 }
1043 }
1044 }
1045 return result;
1046 };
1047
1048 /**
1049 * Check the key if it already exists in the parameter list. If it does,
1050 * find a new key that doesn't, and return it.
1051 *
1052 * @param {string} key New parameter key
1053 * @return {string} Valid new parameter key
1054 */
1055 Model.prototype.getNewValidParameterKey = function ( key ) {
1056 if ( this.params[ key ] || this.getAllParamNames().indexOf( key ) !== -1 ) {
1057 // Change the key to be something else
1058 if ( /\d$/.test( key ) ) {
1059 key += '-';
1060 }
1061 key += this.paramIdentifierCounter;
1062 this.paramIdentifierCounter++;
1063 return this.getNewValidParameterKey( key );
1064 }
1065
1066 return key;
1067 };
1068 /**
1069 * Go over a language property and remove empty language key values
1070 *
1071 * @param {Object} propData Property data
1072 * @return {Object} Property data with only used language keys
1073 */
1074 Model.prototype.propRemoveUnusedLanguages = function ( propData ) {
1075 const result = {};
1076 if ( $.isPlainObject( propData ) ) {
1077 for ( const key in propData ) {
1078 if ( propData[ key ] ) {
1079 result[ key ] = propData[ key ];
1080 }
1081 }
1082 }
1083 return result;
1084 };
1085
1086 /**
1087 * Check whether the output of the current parameter property should be
1088 * outputted in full language mode (object) or a simple string.
1089 *
1090 * @param {string|Object} originalPropValue Original property value
1091 * @param {string|Object} newPropValue New property value
1092 * @return {boolean} Output should be a full language object
1093 */
1094 Model.prototype.isOutputInLanguageObject = function ( originalPropValue, newPropValue ) {
1095 if (
1096 (
1097 // The original was already split to languages
1098 typeof originalPropValue === 'object' &&
1099 // Original was not an empty object
1100 !$.isEmptyObject( originalPropValue )
1101 ) ||
1102 (
1103 // The new value is split to languages
1104 typeof newPropValue === 'object' &&
1105 // New object is not empty
1106 !$.isEmptyObject( newPropValue ) &&
1107 (
1108 // The new value doesn't have the default language
1109 newPropValue[ this.getDefaultLanguage() ] === undefined ||
1110 // There is more than just one language in the new property
1111 Object.keys( newPropValue ).length > 1
1112 )
1113 )
1114 ) {
1115 return true;
1116 }
1117 return false;
1118 };
1119
1120 /**
1121 * Set the parameters that are available in the template source code
1122 *
1123 * @param {string[]} sourceParams Parameters available in template source
1124 */
1125 Model.prototype.setSourceCodeParameters = function ( sourceParams ) {
1126 this.sourceCodeParameters = sourceParams;
1127 };
1128
1129 /**
1130 * Get the parameters that are available in the template source code
1131 *
1132 * @return {string[]} Parameters available in template source
1133 */
1134 Model.prototype.getSourceCodeParameters = function () {
1135 return this.sourceCodeParameters;
1136 };
1137
1138 module.exports = Model;