Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel MWTransclusionModel class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Object literal
10 *
11 * @class ve.dm.MWTransclusionPartInstruction
12 * @private
13 */
14 /**
15 * @property {ve.dm.MWTransclusionPartModel} [remove]
16 * @property {ve.dm.MWTransclusionPartModel} [add]
17 * @property {number} [index]
18 * @property {jQuery.Deferred} [deferred]
19 */
20
21 ( function () {
22 const hasOwn = Object.hasOwnProperty,
23 specCache = {};
24
25 /**
26 * Represents a MediaWiki transclusion, i.e. a sequence of one or more template invocations that
27 * strictly belong to each other (e.g. because they are unbalanced), possibly mixed with raw
28 * wikitext snippets. These individual "parts" are subclasses of ve.dm.MWTransclusionPartModel.
29 *
30 * @class
31 * @mixes OO.EventEmitter
32 *
33 * @constructor
34 * @param {ve.dm.Document} doc Document to use associate with API requests
35 */
36 ve.dm.MWTransclusionModel = function VeDmMWTransclusionModel( doc ) {
37 // Mixin constructors
38 OO.EventEmitter.call( this );
39
40 /**
41 * @property {ve.dm.MWTransclusionPartModel[]} parts
42 * @property {number} uid
43 * @property {jQuery.Promise[]} templateDataApiRequests Currently running API requests. The only
44 * reason to keep these around is to be able to abort them earlier when the template dialog
45 * closes or resets.
46 * @property {Object[]} changeQueue
47 */
48 this.doc = doc;
49 this.parts = [];
50 this.uid = 0;
51 this.templateDataApiRequests = [];
52 this.changeQueue = [];
53 };
54
55 /* Inheritance */
56
57 OO.mixinClass( ve.dm.MWTransclusionModel, OO.EventEmitter );
58
59 /* Events */
60
61 /**
62 * Emitted when a part is added, removed, replaced (e.g. a placeholder with an actual template),
63 * or an existing part changed position.
64 *
65 * @event ve.dm.MWTransclusionPartInstruction#replace
66 * @param {ve.dm.MWTransclusionPartModel|null} removed Removed part
67 * @param {ve.dm.MWTransclusionPartModel|null} added Added or moved part
68 * @param {number} [newPosition] Position the part was added or moved to
69 */
70
71 /**
72 * Emitted when anything changed, including any changes in the content of the parts.
73 *
74 * @event ve.dm.MWTransclusionPartInstruction#change
75 */
76
77 /* Methods */
78
79 /**
80 * Insert transclusion at the end of a surface fragment.
81 *
82 * If forceType is not specified and this is used in async mode, users of this method
83 * should ensure the surface is not accessible while the type is being evaluated.
84 *
85 * @param {ve.dm.SurfaceFragment} surfaceFragment Surface fragment after which to insert.
86 * @param {string} [forceType] Force the type to 'inline' or 'block'. If not
87 * specified it will be evaluated asynchronously.
88 * @return {jQuery.Promise} Promise which resolves when the node has been inserted. If
89 * forceType was specified this will be instant.
90 */
91 ve.dm.MWTransclusionModel.prototype.insertTransclusionNode = function ( surfaceFragment, forceType ) {
92 const deferred = ve.createDeferred(),
93 baseNodeClass = ve.dm.MWTransclusionNode;
94
95 const insertNode = ( isInline, generatedContents ) => {
96 const type = isInline ? baseNodeClass.static.inlineType : baseNodeClass.static.blockType,
97 data = [
98 {
99 type: type,
100 attributes: {
101 mw: this.getPlainObject()
102 }
103 },
104 { type: '/' + type }
105 ];
106
107 // If we just fetched the generated contents, put them in the store
108 // so we don't do a duplicate API call later.
109 if ( generatedContents ) {
110 const nodeClass = ve.dm.modelRegistry.lookup( type );
111 const store = surfaceFragment.getDocument().getStore();
112 const hash = OO.getHash( [ nodeClass.static.getHashObjectForRendering( data[ 0 ] ), undefined ] );
113 store.hash( generatedContents, hash );
114 }
115
116 surfaceFragment.insertContent( data );
117
118 deferred.resolve();
119 };
120
121 if ( forceType ) {
122 insertNode( forceType === 'inline' );
123 } else {
124 ve.init.target.parseWikitextFragment(
125 baseNodeClass.static.getWikitext( this.getPlainObject() ),
126 true,
127 surfaceFragment.getDocument()
128 ).then( ( response ) => {
129 if ( ve.getProp( response, 'visualeditor', 'result' ) === 'success' ) {
130 // This method is only ever run by a client, so it is okay to use jQuery
131 // eslint-disable-next-line no-undef
132 let contentNodes = $.parseHTML( response.visualeditor.content, surfaceFragment.getDocument().getHtmlDocument() ) || [];
133 contentNodes = ve.ce.MWTransclusionNode.static.filterRendering( contentNodes );
134 insertNode(
135 baseNodeClass.static.isHybridInline( contentNodes, ve.dm.converter ),
136 contentNodes
137 );
138 } else {
139 // Request failed - just assume inline
140 insertNode( true );
141 }
142 }, () => {
143 insertNode( true );
144 } );
145 }
146 return deferred.promise();
147 };
148
149 /**
150 * Update transclusion node in a document.
151 *
152 * @param {ve.dm.Surface} surfaceModel Surface model of main document
153 * @param {ve.dm.MWTransclusionNode} node Transclusion node to update
154 */
155 ve.dm.MWTransclusionModel.prototype.updateTransclusionNode = function ( surfaceModel, node ) {
156 const obj = this.getPlainObject();
157
158 if ( obj !== null ) {
159 surfaceModel.getLinearFragment( node.getOuterRange(), true )
160 .changeAttributes( { mw: obj } );
161 } else {
162 surfaceModel.getLinearFragment( node.getOuterRange(), true )
163 .removeContent();
164 }
165 };
166
167 /**
168 * Load from transclusion data, and fetch spec from server.
169 *
170 * @param {Object} data Transclusion data
171 * @return {jQuery.Promise} Promise, resolved when spec is loaded
172 */
173 ve.dm.MWTransclusionModel.prototype.load = function ( data ) {
174 const promises = [];
175
176 // Convert single part format to multi-part format
177 // Parsoid doesn't use this format any more, but we accept it for backwards compatibility
178 if ( data.params && data.target ) {
179 data = { parts: [ { template: data } ] };
180 }
181
182 if ( Array.isArray( data.parts ) ) {
183 for ( let i = 0; i < data.parts.length; i++ ) {
184 const part = data.parts[ i ];
185 if ( part.template ) {
186 const deferred = ve.createDeferred();
187 promises.push( deferred.promise() );
188 this.changeQueue.push( {
189 add: ve.dm.MWTemplateModel.newFromData( this, part.template ),
190 deferred: deferred
191 } );
192 } else if ( typeof part === 'string' ) {
193 const deferred = ve.createDeferred();
194 promises.push( deferred.promise() );
195 this.changeQueue.push( {
196 add: new ve.dm.MWTransclusionContentModel( this, part ),
197 deferred: deferred
198 } );
199 }
200 }
201 setTimeout( this.processChangeQueue.bind( this ) );
202 }
203
204 return ve.promiseAll( promises );
205 };
206
207 /**
208 * Process one or more queue items.
209 *
210 * @private
211 * @param {ve.dm.MWTransclusionPartInstruction[]} queue List of objects containing parts to add and optionally
212 * indexes to add them at, if no index is given parts will be added at the end
213 * @fires ve.dm.MWTransclusionPartInstruction#replace For each item added
214 * @fires ve.dm.MWTransclusionPartInstruction#change
215 */
216 ve.dm.MWTransclusionModel.prototype.resolveChangeQueue = function ( queue ) {
217 const resolveQueue = [];
218
219 for ( let i = 0; i < queue.length; i++ ) {
220 const item = queue[ i ];
221 let remove = 0;
222
223 if ( item.add instanceof ve.dm.MWTemplateModel ) {
224 const title = item.add.getTemplateDataQueryTitle();
225 if ( hasOwn.call( specCache, title ) && specCache[ title ] ) {
226 item.add.getSpec().setTemplateData( specCache[ title ] );
227 }
228 }
229
230 // Use specified index
231 let index = item.index;
232 // Auto-remove if already existing, preserving index
233 const existing = this.parts.indexOf( item.add );
234 if ( existing !== -1 ) {
235 this.removePart( item.add );
236 if ( index && existing + 1 < index ) {
237 index--;
238 }
239 }
240 // Derive index from removal if given
241 if ( index === undefined && item.remove ) {
242 index = this.parts.indexOf( item.remove );
243 if ( index !== -1 ) {
244 remove = 1;
245 }
246 }
247 // Use last index as a last resort
248 if ( index === undefined || index === -1 ) {
249 index = this.parts.length;
250 }
251
252 this.parts.splice( index, remove, item.add );
253 if ( item.add ) {
254 // This forwards change events from the nested ve.dm.MWTransclusionPartModel upwards.
255 // The array syntax is a way to call `this.emit( 'change' )`.
256 item.add.connect( this, { change: [ 'emit', 'change' ] } );
257 }
258 if ( item.remove ) {
259 item.remove.disconnect( this );
260 }
261 this.emit( 'replace', item.remove || null, item.add, index );
262
263 // Resolve promises
264 if ( item.deferred ) {
265 resolveQueue.push( item.deferred );
266 }
267 }
268 this.emit( 'change' );
269
270 // We need to go back and resolve the deferreds after emitting change.
271 // Otherwise we get silly situations like a single change event being
272 // guaranteed after the transclusion loaded promise gets resolved.
273 resolveQueue.forEach( ( queueItem ) => {
274 queueItem.resolve();
275 } );
276 };
277
278 /**
279 * @private
280 */
281 ve.dm.MWTransclusionModel.prototype.processChangeQueue = function () {
282 const templateNamespaceId = mw.config.get( 'wgNamespaceIds' ).template,
283 titles = [];
284
285 if ( !this.changeQueue.length ) {
286 return;
287 }
288
289 const queue = this.changeQueue.slice();
290
291 // Clear shared queue for future calls
292 this.changeQueue.length = 0;
293
294 // Get unique list of template titles that aren't already loaded
295 for ( let i = 0; i < queue.length; i++ ) {
296 const item = queue[ i ];
297 if ( item.add instanceof ve.dm.MWTemplateModel ) {
298 const title = item.add.getTemplateDataQueryTitle(),
299 mwTitle = title ? mw.Title.newFromText( title, templateNamespaceId ) : null;
300 if (
301 // Skip titles that don't have a resolvable href
302 mwTitle &&
303 // Skip already cached data
304 !hasOwn.call( specCache, title ) &&
305 // Skip duplicate titles in the same batch
306 titles.indexOf( title ) === -1
307 ) {
308 titles.push( title );
309 }
310 }
311 }
312
313 // Bypass server for empty lists
314 if ( !titles.length ) {
315 setTimeout( this.resolveChangeQueue.bind( this, queue ) );
316 return;
317 }
318
319 this.templateDataApiRequests.push( this.callTemplateDataApi( titles, queue ) );
320 };
321
322 /**
323 * @private
324 * @param {string[]} titles
325 * @param {ve.dm.MWTransclusionPartInstruction[]} queue
326 * @return {jQuery.Promise}
327 */
328 ve.dm.MWTransclusionModel.prototype.callTemplateDataApi = function ( titles, queue ) {
329 const xhr = ve.init.target.getContentApi( this.doc ).get( {
330 action: 'templatedata',
331 titles: titles,
332 lang: mw.config.get( 'wgUserLanguage' ),
333 includeMissingTitles: '1',
334 redirects: '1'
335 } ).done( this.cacheTemplateDataApiResponse.bind( this ) );
336 xhr.always(
337 this.markRequestAsDone.bind( this, xhr ),
338 this.resolveChangeQueue.bind( this, queue )
339 );
340 return xhr;
341 };
342
343 /**
344 * @private
345 * @param {Object} [data]
346 * @param {Object.<number,ve.dm.MWTemplatePageMetadata>} [data.pages]
347 */
348 ve.dm.MWTransclusionModel.prototype.cacheTemplateDataApiResponse = function ( data ) {
349 if ( !data || !data.pages ) {
350 return;
351 }
352
353 // Keep spec data on hand for future use
354 for ( const id in data.pages ) {
355 const title = data.pages[ id ].title;
356
357 if ( data.pages[ id ].missing ) {
358 // Remember templates that don't exist in the link cache
359 // { title: { missing: true|false }
360 const missingTitle = {};
361 missingTitle[ title ] = { missing: true };
362 ve.init.platform.linkCache.setMissing( missingTitle );
363 } else if ( data.pages[ id ].notemplatedata && !OO.isPlainObject( data.pages[ id ].params ) ) {
364 // (T243868) Prevent asking again for templates that have neither user-provided specs
365 // nor automatically detected params
366 specCache[ title ] = null;
367 } else {
368 specCache[ title ] = data.pages[ id ];
369 }
370 }
371
372 // Follow redirects
373 const aliasMap = data.redirects || [];
374 // Follow MW's normalisation
375 if ( data.normalized ) {
376 ve.batchPush( aliasMap, data.normalized );
377 }
378 // Cross-reference aliased titles.
379 for ( let i = 0; i < aliasMap.length; i++ ) {
380 // Only define the alias if the target exists, otherwise
381 // we create a new property with an invalid "undefined" value.
382 if ( hasOwn.call( specCache, aliasMap[ i ].to ) ) {
383 specCache[ aliasMap[ i ].from ] = specCache[ aliasMap[ i ].to ];
384 }
385 }
386 };
387
388 /**
389 * @private
390 * @param {jQuery.Promise} apiPromise
391 */
392 ve.dm.MWTransclusionModel.prototype.markRequestAsDone = function ( apiPromise ) {
393 // Prune completed request
394 const index = this.templateDataApiRequests.indexOf( apiPromise );
395 if ( index !== -1 ) {
396 this.templateDataApiRequests.splice( index, 1 );
397 }
398 };
399
400 ve.dm.MWTransclusionModel.prototype.abortAllApiRequests = function () {
401 for ( let i = 0; i < this.templateDataApiRequests.length; i++ ) {
402 this.templateDataApiRequests[ i ].abort();
403 }
404 this.templateDataApiRequests.length = 0;
405 };
406
407 /**
408 * Get plain object representation of template transclusion.
409 *
410 * @return {Object|null} Plain object representation, or null if empty
411 */
412 ve.dm.MWTransclusionModel.prototype.getPlainObject = function () {
413 const parts = [];
414
415 for ( let i = 0; i < this.parts.length; i++ ) {
416 const part = this.parts[ i ];
417 const serialization = part.serialize();
418 if ( serialization !== undefined && serialization !== '' ) {
419 parts.push( serialization );
420 }
421 }
422
423 return parts.length ? { parts: parts } : null;
424 };
425
426 /**
427 * @return {string} Next part ID, starting from "part_0", guaranteed to be unique for this
428 * transclusion
429 */
430 ve.dm.MWTransclusionModel.prototype.nextUniquePartId = function () {
431 return 'part_' + this.uid++;
432 };
433
434 /**
435 * Replace asynchronously.
436 *
437 * @param {ve.dm.MWTransclusionPartModel} remove Part to remove
438 * @param {ve.dm.MWTransclusionPartModel} add Part to add
439 * @throws {Error} If part to remove is not valid
440 * @throws {Error} If part to add is not valid
441 * @return {jQuery.Promise} Promise, resolved when part is added
442 */
443 ve.dm.MWTransclusionModel.prototype.replacePart = function ( remove, add ) {
444 const deferred = ve.createDeferred();
445 if (
446 !( remove instanceof ve.dm.MWTransclusionPartModel ) ||
447 !( add instanceof ve.dm.MWTransclusionPartModel )
448 ) {
449 throw new Error( 'Invalid transclusion part' );
450 }
451 this.changeQueue.push( { remove: remove, add: add, deferred: deferred } );
452
453 // Fetch on next yield to process items in the queue together, subsequent calls will
454 // have no effect because the queue will be clear
455 setTimeout( this.processChangeQueue.bind( this ) );
456
457 return deferred.promise();
458 };
459
460 /**
461 * Added asynchronously, but order is preserved.
462 *
463 * @param {ve.dm.MWTransclusionPartModel} part
464 * @param {number} [index] Specific index to add content at, defaults to the end
465 * @throws {Error} If part is not valid
466 * @return {jQuery.Promise} Promise, resolved when part is added
467 */
468 ve.dm.MWTransclusionModel.prototype.addPart = function ( part, index ) {
469 const deferred = ve.createDeferred();
470 if ( !( part instanceof ve.dm.MWTransclusionPartModel ) ) {
471 throw new Error( 'Invalid transclusion part' );
472 }
473 this.changeQueue.push( { add: part, index: index, deferred: deferred } );
474
475 // Fetch on next yield to process items in the queue together, subsequent calls to fetch will
476 // have no effect because the queue will be clear
477 setTimeout( this.processChangeQueue.bind( this ) );
478
479 return deferred.promise();
480 };
481
482 /**
483 * @param {ve.dm.MWTransclusionPartModel} part
484 * @fires ve.dm.MWTransclusionPartInstruction#replace
485 */
486 ve.dm.MWTransclusionModel.prototype.removePart = function ( part ) {
487 const index = this.parts.indexOf( part );
488 if ( index !== -1 ) {
489 this.parts.splice( index, 1 );
490 part.disconnect( this );
491 this.emit( 'replace', part, null );
492 }
493 };
494
495 /**
496 * @return {boolean} True if the transclusion is literally empty or contains only placeholders
497 */
498 ve.dm.MWTransclusionModel.prototype.isEmpty = function () {
499 return this.parts.every( ( part ) => part instanceof ve.dm.MWTemplatePlaceholderModel );
500 };
501
502 /**
503 * @return {boolean} True if this is a single template or template placeholder
504 */
505 ve.dm.MWTransclusionModel.prototype.isSingleTemplate = function () {
506 return this.parts.length === 1 && (
507 this.parts[ 0 ] instanceof ve.dm.MWTemplateModel ||
508 this.parts[ 0 ] instanceof ve.dm.MWTemplatePlaceholderModel
509 );
510 };
511
512 /**
513 * @return {ve.dm.MWTransclusionPartModel[]} All parts in this transclusion
514 */
515 ve.dm.MWTransclusionModel.prototype.getParts = function () {
516 return this.parts;
517 };
518
519 /**
520 * Matching is performed against the first section of the `id`, delimited by a '/'.
521 *
522 * @param {string} [id] Any id, including slash-delimited template parameter ids
523 * @return {ve.dm.MWTransclusionPartModel|undefined} Part with matching ID, if found
524 */
525 ve.dm.MWTransclusionModel.prototype.getPartFromId = function ( id ) {
526 if ( !id ) {
527 return;
528 }
529
530 // For ids from ve.dm.MWParameterModel, compare against the part id
531 // of the parameter instead of the entire model id (e.g. "part_1" instead of "part_1/foo").
532 const partId = id.split( '/', 1 )[ 0 ];
533
534 for ( let i = 0; i < this.parts.length; i++ ) {
535 if ( this.parts[ i ].getId() === partId ) {
536 return this.parts[ i ];
537 }
538 }
539 };
540
541 /**
542 * Get the index of a part or parameter.
543 *
544 * Indexes are linear depth-first addresses in the transclusion tree.
545 *
546 * @param {ve.dm.MWTransclusionPartModel|ve.dm.MWParameterModel} model Part or parameter
547 * @return {number} Page index of model
548 */
549 ve.dm.MWTransclusionModel.prototype.getIndex = function ( model ) {
550 const parts = this.parts;
551
552 let index = 0;
553 for ( let i = 0; i < parts.length; i++ ) {
554 const part = parts[ i ];
555 if ( part === model ) {
556 return index;
557 }
558 index++;
559 if ( part instanceof ve.dm.MWTemplateModel ) {
560 const names = part.getOrderedParameterNames();
561 for ( let j = 0; j < names.length; j++ ) {
562 if ( part.getParameter( names[ j ] ) === model ) {
563 return index;
564 }
565 index++;
566 }
567 }
568 }
569 return -1;
570 };
571
572 /**
573 * Add missing required and suggested parameters to each transclusion.
574 */
575 ve.dm.MWTransclusionModel.prototype.addPromptedParameters = function () {
576 this.parts.forEach( ( part ) => {
577 if ( part instanceof ve.dm.MWTemplateModel ) {
578 part.addPromptedParameters();
579 }
580 } );
581 };
582
583 /**
584 * @return {boolean} True if any transclusion part contains meaningful, non-default user input
585 */
586 ve.dm.MWTransclusionModel.prototype.containsValuableData = function () {
587 return this.parts.some( ( part ) => part.containsValuableData() );
588 };
589
590 /**
591 * Resets the model's state.
592 */
593 ve.dm.MWTransclusionModel.prototype.reset = function () {
594 this.parts = [];
595 this.uid = 0;
596 this.templateDataApiRequests = [];
597 this.changeQueue = [];
598 };
599
600 // Temporary compatibility for https://github.com/femiwiki/Sanctions/pull/118. Remove when not
601 // needed any more.
602 mw.log.deprecate( ve.dm.MWTransclusionModel.prototype, 'abortRequests',
603 ve.dm.MWTransclusionModel.prototype.abortAllApiRequests,
604 'Use "abortAllApiRequests" instead.'
605 );
606
607 }() );