Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/dm/models/ve.dm.MWTemplateModel.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel MWTemplateModel class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Represents a template invocation that's part of a (possibly unbalanced) sequence of template
10 * invocations and raw wikitext snippets. Meant to be an item in a {@see ve.dm.MWTransclusionModel}.
11 * Holds a back-reference to its parent.
12 *
13 * Holds a reference to the specification of the template, i.e. how the template is documented via
14 * TemplateData. The actual invocation might be entirely different, missing parameters as well as
15 * containing undocumented ones.
16 *
17 * @class
18 * @extends ve.dm.MWTransclusionPartModel
19 *
20 * @constructor
21 * @param {ve.dm.MWTransclusionModel} transclusion
22 * @param {Object} target Template target
23 * @param {string} target.wt Template name as originally used in the wikitext, including optional
24 * whitespace
25 * @param {string} [target.href] Hypertext reference to target, e.g. "./Template:Example"
26 */
27 ve.dm.MWTemplateModel = function VeDmMWTemplateModel( transclusion, target ) {
28 // Parent constructor
29 ve.dm.MWTemplateModel.super.call( this, transclusion );
30
31 // Properties
32 this.target = target;
33
34 // TODO: Either here or in uses of this constructor we need to validate the title
35 this.title = target.href ? mw.libs.ve.normalizeParsoidResourceName( target.href ) : null;
36 this.orderedParameterNames = null;
37 this.params = {};
38 this.spec = new ve.dm.MWTemplateSpecModel( this );
39 this.originalData = null;
40 };
41
42 /* Inheritance */
43
44 OO.inheritClass( ve.dm.MWTemplateModel, ve.dm.MWTransclusionPartModel );
45
46 /* Events */
47
48 /**
49 * Emitted when a new parameter was added to the template.
50 *
51 * @event ve.dm.MWTemplateModel#add
52 * @param {ve.dm.MWParameterModel} param Added param
53 */
54
55 /**
56 * Emitted when a parameter was removed from the template.
57 *
58 * @event ve.dm.MWTemplateModel#remove
59 * @param {ve.dm.MWParameterModel} param Removed param
60 */
61
62 /**
63 * Emitted when anything changed, e.g. a parameter was added or removed, or a parameter's value
64 * edited.
65 *
66 * @event ve.dm.MWTemplateModel#change
67 */
68
69 /* Static Methods */
70
71 /**
72 * Data is in the format provided by Parsoid.
73 *
74 * @param {ve.dm.MWTransclusionModel} transclusion Transclusion template is in
75 * @param {Object} data Template data
76 * @param {Object} data.params
77 * @param {string} data.params.wt Wikitext
78 * @return {ve.dm.MWTemplateModel} New template model
79 */
80 ve.dm.MWTemplateModel.newFromData = function ( transclusion, data ) {
81 const template = new ve.dm.MWTemplateModel( transclusion, data.target );
82
83 for ( const key in data.params ) {
84 template.addParameter(
85 new ve.dm.MWParameterModel( template, key, data.params[ key ].wt )
86 );
87 }
88
89 template.setOriginalData( data );
90
91 return template;
92 };
93
94 /**
95 * Name is equivalent to what would be entered between double brackets, defaulting to the Template
96 * namespace, using a leading colon to access other namespaces.
97 *
98 * @param {ve.dm.MWTransclusionModel} transclusion Transclusion template is in
99 * @param {string|mw.Title} name Template name
100 * @return {ve.dm.MWTemplateModel|null} New template model
101 */
102 ve.dm.MWTemplateModel.newFromName = function ( transclusion, name ) {
103 const templateNs = mw.config.get( 'wgNamespaceIds' ).template;
104 let title;
105 if ( name instanceof mw.Title ) {
106 title = name;
107 name = title.getRelativeText( templateNs );
108 } else {
109 title = mw.Title.newFromText( name, templateNs );
110 }
111 if ( title !== null ) {
112 const href = title.getPrefixedText();
113 return new ve.dm.MWTemplateModel( transclusion, { href: href, wt: name } );
114 }
115
116 return null;
117 };
118
119 /* Methods */
120
121 /**
122 * @return {Object} Template target
123 */
124 ve.dm.MWTemplateModel.prototype.getTarget = function () {
125 return this.target;
126 };
127
128 /**
129 * @return {string|null} Prefixed template title including the "Template:" namespace, if available.
130 * Use {@see ve.dm.MWTemplateSpecModel.getLabel} for a human-readable label without the namespace.
131 */
132 ve.dm.MWTemplateModel.prototype.getTitle = function () {
133 return this.title;
134 };
135
136 /**
137 * @return {string|null} Prefixed page name including the `Template:` namespace, but with syntax
138 * elements like `subst:` stripped.
139 */
140 ve.dm.MWTemplateModel.prototype.getTemplateDataQueryTitle = function () {
141 // FIXME: This currently doesn't strip localized versions of these magic words.
142 // Strip magic words {{subst:…}} and {{safesubst:…}}
143 const name = this.target.wt.trim().replace( /^(?:safe)?subst:/i, '' ),
144 templateNs = mw.config.get( 'wgNamespaceIds' ).template,
145 title = mw.Title.newFromText( name, templateNs );
146 return title ? title.getPrefixedText() : this.getTitle();
147 };
148
149 /**
150 * @return {ve.dm.MWTemplateSpecModel} Template specification
151 */
152 ve.dm.MWTemplateModel.prototype.getSpec = function () {
153 return this.spec;
154 };
155
156 /**
157 * Get all parameters that are currently present in this template invocation in the order as they
158 * originally appear in the wikitext. This is critical for {@see serialize}. Might contain
159 * placeholders with the parameter name "".
160 *
161 * @return {Object.<string,ve.dm.MWParameterModel>} Parameters keyed by name or alias
162 */
163 ve.dm.MWTemplateModel.prototype.getParameters = function () {
164 return this.params;
165 };
166
167 /**
168 * @param {string} name Parameter name or alias as originally used in the wikitext
169 * @return {ve.dm.MWParameterModel|undefined}
170 */
171 ve.dm.MWTemplateModel.prototype.getParameter = function ( name ) {
172 return this.params[ name ];
173 };
174
175 /**
176 * Check if a parameter with this name or one of its aliases is currently part of this template.
177 *
178 * @param {string} name Parameter name or alias
179 * @return {boolean} Parameter is in the template
180 */
181 ve.dm.MWTemplateModel.prototype.hasParameter = function ( name ) {
182 return this.getOriginalParameterName( name ) in this.params;
183 };
184
185 /**
186 * @param {string} name Parameter name or alias
187 * @return {string} Parameter name or alias as originally used in the wikitext
188 */
189 ve.dm.MWTemplateModel.prototype.getOriginalParameterName = function ( name ) {
190 if ( name in this.params ) {
191 return name;
192 }
193 const aliases = this.spec.getParameterAliases( name );
194 // FIXME: Should use .filter() when we dropped IE11 support
195 for ( let i = 0; i < aliases.length; i++ ) {
196 if ( aliases[ i ] in this.params ) {
197 return aliases[ i ];
198 }
199 }
200 return this.spec.getPrimaryParameterName( name );
201 };
202
203 /**
204 * Get all current and potential parameter names in a canonical order that's always the same,
205 * unrelated to how the parameters appear in the wikitext. Parameter names and aliases documented
206 * via TemplateData are first, in their documented order. Undocumented parameters are sorted with
207 * numeric names first, followed by alphabetically sorted names. The unnamed placeholder parameter
208 * is last.
209 *
210 * @return {string[]}
211 */
212 ve.dm.MWTemplateModel.prototype.getAllParametersOrdered = function () {
213 const spec = this.spec,
214 usedAliases = {};
215
216 let primaryName;
217 for ( const alias in this.params ) {
218 if ( spec.isParameterAlias( alias ) ) {
219 primaryName = spec.getPrimaryParameterName( alias );
220 if ( !usedAliases[ primaryName ] ) {
221 // Skip primary name when it's not used, otherwise move it to the front
222 usedAliases[ primaryName ] = primaryName in this.params ? [ primaryName ] : [];
223 }
224 // Append aliases in their original order (not documented order)
225 usedAliases[ primaryName ].push( alias );
226 }
227 }
228
229 let parameters = spec.getCanonicalParameterOrder();
230
231 // Restore aliases originally used in the wikitext. The spec doesn't know which alias was used.
232 for ( primaryName in usedAliases ) {
233 const i = parameters.indexOf( primaryName );
234 // TODO: parameters.splice( i, 1, ...usedAliases[ primaryName ] ) when we can use ES6
235 parameters = parameters.slice( 0, i ).concat( usedAliases[ primaryName ],
236 parameters.slice( i + 1 ) );
237 }
238
239 // Restore the placeholder, if present. The spec doesn't keep track of placeholders.
240 if ( '' in this.params ) {
241 parameters.push( '' );
242 }
243
244 // TODO: cache results
245 return parameters;
246 };
247
248 /**
249 * Returns the same parameters as {@see getParameters}, i.e. parameters that are currently present
250 * in this template invocation, but sorted in a canonical order for presentational purposes.
251 *
252 * Don't use this if you need the parameters as they originally appear in the wikitext, or if you
253 * don't care about an order. Use {@see getParameters} together with `Object.keys()` instead.
254 *
255 * @return {string[]} Sorted list of parameter names
256 */
257 ve.dm.MWTemplateModel.prototype.getOrderedParameterNames = function () {
258 if ( !this.orderedParameterNames ) {
259 const params = this.params;
260 this.orderedParameterNames = this.getAllParametersOrdered().filter( ( name ) => name in params );
261 }
262 return this.orderedParameterNames;
263 };
264
265 /**
266 * @param {ve.dm.MWParameterModel} param Parameter to add
267 * @fires ve.dm.MWTemplateModel#add
268 * @fires ve.dm.MWTemplateModel#change
269 */
270 ve.dm.MWTemplateModel.prototype.addParameter = function ( param ) {
271 const name = param.getName();
272 if ( name in this.params ) {
273 return;
274 }
275
276 this.orderedParameterNames = null;
277 this.params[ name ] = param;
278 this.spec.fillFromTemplate();
279 // This forwards change events from the nested ve.dm.MWParameterModel upwards. The array
280 // syntax is a way to call `this.emit( 'change' )`.
281 param.connect( this, { change: [ 'emit', 'change' ] } );
282 this.emit( 'add', param );
283 this.emit( 'change' );
284 };
285
286 /**
287 * Remove a parameter from this MWTemplateModel, and emit events which result in removing the
288 * parameter from the UI. Note this does *not* remove the parameter from the linked specification.
289 *
290 * @param {ve.dm.MWParameterModel} [param]
291 * @fires ve.dm.MWTemplateModel#remove
292 * @fires ve.dm.MWTemplateModel#change
293 */
294 ve.dm.MWTemplateModel.prototype.removeParameter = function ( param ) {
295 if ( param ) {
296 this.orderedParameterNames = null;
297 delete this.params[ param.getName() ];
298 param.disconnect( this );
299 this.emit( 'remove', param );
300 this.emit( 'change' );
301 }
302 };
303
304 /**
305 * Add all non-existing required and suggested parameters, if any.
306 */
307 ve.dm.MWTemplateModel.prototype.addPromptedParameters = function () {
308 const params = this.params,
309 spec = this.spec,
310 names = spec.getKnownParameterNames();
311
312 for ( let i = 0; i < names.length; i++ ) {
313 const name = names[ i ];
314 const foundAlias = spec.getParameterAliases( name ).some( ( alias ) => alias in params );
315 if (
316 !foundAlias &&
317 !params[ name ] &&
318 (
319 spec.isParameterRequired( name ) ||
320 spec.isParameterSuggested( name )
321 )
322 ) {
323 this.addParameter( new ve.dm.MWParameterModel( this, names[ i ] ) );
324 }
325 }
326 };
327
328 /**
329 * Set original data, to be used as a base for serialization.
330 *
331 * @private
332 * @param {Object} data Original data
333 * @param {Object.<string,Object>} [data.params]
334 */
335 ve.dm.MWTemplateModel.prototype.setOriginalData = function ( data ) {
336 this.originalData = data;
337 };
338
339 /**
340 * @inheritdoc
341 */
342 ve.dm.MWTemplateModel.prototype.serialize = function () {
343 const origData = this.originalData || {},
344 origParams = origData.params || {},
345 template = { target: this.target, params: {} },
346 spec = this.spec,
347 params = this.params;
348
349 for ( const name in params ) {
350 if ( name === '' ) {
351 continue;
352 }
353
354 if (
355 // Don't add empty parameters (T101075)
356 params[ name ].getValue() === '' &&
357 // …unless they were present before the edit
358 !Object.prototype.hasOwnProperty.call( origParams, name ) &&
359 // …unless they are required (T276989)
360 !spec.isParameterRequired( name )
361 ) {
362 continue;
363 }
364
365 const origName = params[ name ].getOriginalName();
366 template.params[ origName ] = ve.extendObject(
367 {},
368 origParams[ origName ],
369 { wt: params[ name ].getValue() }
370 );
371
372 }
373
374 // Performs a non-deep extend, so this won't reintroduce
375 // deleted parameters (T75134)
376 return { template: ve.extendObject( {}, origData, template ) };
377 };
378
379 /**
380 * @inheritdoc
381 */
382 ve.dm.MWTemplateModel.prototype.containsValuableData = function () {
383 const params = this.params;
384
385 return Object.keys( params ).some( ( name ) => {
386 // Skip unnamed placeholders
387 if ( !name ) {
388 return false;
389 }
390
391 const param = params[ name ],
392 value = param.getValue();
393 return value &&
394 // This will automatically be restored, see {@see ve.dm.MWParameterModel.getValue}
395 value !== param.getAutoValue() &&
396 // While this isn't always meaningless, it typically is, and it's easy to restore
397 value !== param.getDefaultValue();
398 } );
399 };