Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/dm/nodes/ve.dm.MWTransclusionNode.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel MWTransclusionNode class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * DataModel MediaWiki transclusion node.
10 *
11 * @class
12 * @abstract
13 * @extends ve.dm.LeafNode
14 * @mixes ve.dm.GeneratedContentNode
15 * @mixes ve.dm.FocusableNode
16 *
17 * @constructor
18 * @param {Object} [element] Reference to element in linear model
19 */
20 ve.dm.MWTransclusionNode = function VeDmMWTransclusionNode() {
21 // Parent constructor
22 ve.dm.MWTransclusionNode.super.apply( this, arguments );
23
24 // Mixin constructors
25 ve.dm.GeneratedContentNode.call( this );
26 ve.dm.FocusableNode.call( this );
27
28 // Properties
29 this.partsList = null;
30
31 // Events
32 this.connect( this, { attributeChange: 'onAttributeChange' } );
33 };
34
35 /* Inheritance */
36
37 OO.inheritClass( ve.dm.MWTransclusionNode, ve.dm.LeafNode );
38
39 OO.mixinClass( ve.dm.MWTransclusionNode, ve.dm.GeneratedContentNode );
40
41 OO.mixinClass( ve.dm.MWTransclusionNode, ve.dm.FocusableNode );
42
43 /* Static members */
44
45 ve.dm.MWTransclusionNode.static.name = 'mwTransclusion';
46
47 ve.dm.MWTransclusionNode.static.matchTagNames = null;
48
49 ve.dm.MWTransclusionNode.static.matchRdfaTypes = [ 'mw:Transclusion' ];
50
51 // Transclusion nodes can contain other types, e.g. mw:PageProp/Category.
52 // Allow all other types (null) so they match to this node.
53 ve.dm.MWTransclusionNode.static.allowedRdfaTypes = null;
54
55 // HACK: This prevents any rules with higher specificity from matching,
56 // e.g. LanguageAnnotation which uses a match function
57 ve.dm.MWTransclusionNode.static.matchFunction = function () {
58 return true;
59 };
60
61 ve.dm.MWTransclusionNode.static.enableAboutGrouping = true;
62
63 // We handle rendering ourselves, no need to render attributes from originalDomElements (T207325),
64 // except for data-parsoid/RESTBase ID (T207325)
65 ve.dm.MWTransclusionNode.static.preserveHtmlAttributes = function ( attribute ) {
66 return [ 'data-parsoid', 'id' ].indexOf( attribute ) !== -1;
67 };
68
69 ve.dm.MWTransclusionNode.static.getHashObject = function ( dataElement ) {
70 return {
71 type: dataElement.type,
72 mw: dataElement.attributes.mw
73 };
74 };
75
76 ve.dm.MWTransclusionNode.static.isDiffComparable = function ( element, other ) {
77 function getTemplateNames( parts ) {
78 return parts.map( ( part ) => part.template ? part.template.target.wt : '' ).join( '|' );
79 }
80
81 return ve.dm.MWTransclusionNode.super.static.isDiffComparable.call( this, element, other ) &&
82 getTemplateNames( element.attributes.mw.parts ) === getTemplateNames( other.attributes.mw.parts );
83 };
84
85 /**
86 * Node type to use when the transclusion is inline
87 *
88 * @static
89 * @property {string}
90 * @inheritable
91 */
92 ve.dm.MWTransclusionNode.static.inlineType = 'mwTransclusionInline';
93
94 /**
95 * Node type to use when the transclusion is a block
96 *
97 * @static
98 * @property {string}
99 * @inheritable
100 */
101 ve.dm.MWTransclusionNode.static.blockType = 'mwTransclusionBlock';
102
103 /**
104 * Node type to use when the transclusion is cellable
105 *
106 * @static
107 * @property {string}
108 * @inheritable
109 */
110 ve.dm.MWTransclusionNode.static.cellType = 'mwTransclusionTableCell';
111
112 ve.dm.MWTransclusionNode.static.toDataElement = function ( domElements, converter ) {
113 const mwDataJSON = domElements[ 0 ].getAttribute( 'data-mw' ),
114 mwData = mwDataJSON ? JSON.parse( mwDataJSON ) : {},
115 isInline = this.isHybridInline( domElements, converter ),
116 type = isInline ? this.inlineType : this.blockType;
117
118 const dataElement = {
119 type: type,
120 attributes: {
121 mw: mwData,
122 originalMw: mwDataJSON
123 }
124 };
125
126 if ( ve.dm.TableCellableNode.static.areNodesCellable( domElements ) ) {
127 dataElement.type = this.cellType;
128 ve.dm.TableCellableNode.static.setAttributes( dataElement.attributes, domElements, true );
129 }
130
131 if ( !domElements[ 0 ].getAttribute( 'data-ve-no-generated-contents' ) ) {
132 this.storeGeneratedContents( dataElement, domElements, converter.getStore() );
133 }
134
135 return dataElement;
136 };
137
138 ve.dm.MWTransclusionNode.static.toDomElements = function ( dataElement, doc, converter ) {
139 const store = converter.getStore(),
140 originalMw = dataElement.attributes.originalMw,
141 originalDomElements = store.value( dataElement.originalDomElementsHash );
142
143 function wrapTextNode( node ) {
144 if ( node.nodeType === Node.TEXT_NODE ) {
145 const wrapper = doc.createElement( 'span' );
146 wrapper.appendChild( node );
147 return wrapper;
148 }
149 return node;
150 }
151
152 let els;
153 // If the transclusion is unchanged just send back the
154 // original DOM elements so selser can skip over it
155 if (
156 originalDomElements &&
157 originalMw && ve.compare( dataElement.attributes.mw, JSON.parse( originalMw ) )
158 ) {
159 // originalDomElements is also used for CE rendering so return a copy
160 els = ve.copyDomElements( originalDomElements, doc );
161 } else {
162 let value;
163 if (
164 converter.doesModeNeedRendering() &&
165 // Use getHashObjectForRendering to get the rendering from the store
166 ( value = store.value( store.hashOfValue( null, OO.getHash( [ this.getHashObjectForRendering( dataElement ), undefined ] ) ) ) )
167 ) {
168 // For the clipboard use the current DOM contents so the user has something
169 // meaningful to paste into external applications
170 els = ve.copyDomElements( value, doc );
171 els[ 0 ] = wrapTextNode( els[ 0 ] );
172 } else if ( originalDomElements ) {
173 els = [ doc.createElement( originalDomElements[ 0 ].nodeName ) ];
174 } else if ( dataElement.type === this.cellType ) {
175 els = [ doc.createElement( dataElement.attributes.style === 'header' ? 'th' : 'td' ) ];
176 } else {
177 els = [ doc.createElement( 'span' ) ];
178 }
179 // All we need to send back to Parsoid is the original transclusion marker, with a
180 // reconstructed data-mw property.
181 els[ 0 ].setAttribute( 'typeof', 'mw:Transclusion' );
182 els[ 0 ].setAttribute( 'data-mw', JSON.stringify( dataElement.attributes.mw ) );
183 }
184 if ( converter.isForClipboard() ) {
185 // If the first element is a <link>, <meta> or <style> tag, e.g. a category or TemplateStyles,
186 // ensure it is not destroyed by copy-paste by replacing it with a span
187 if ( els[ 0 ].tagName === 'LINK' || els[ 0 ].tagName === 'META' || els[ 0 ].tagName === 'STYLE' ) {
188 const span = doc.createElement( 'span' );
189 span.setAttribute( 'typeof', 'mw:Transclusion' );
190 span.setAttribute( 'data-mw', els[ 0 ].getAttribute( 'data-mw' ) );
191 els[ 0 ] = span;
192 }
193
194 // Empty spans can get thrown around by Chrome when pasting, so give them a space
195 if ( els[ 0 ].innerHTML === '' ) {
196 els[ 0 ].appendChild( doc.createTextNode( '\u00a0' ) );
197 }
198
199 // Mark the data-mw element as not having valid generated contents with it in case it is
200 // inserted into another editor (e.g. via paste).
201 els[ 0 ].setAttribute( 'data-ve-no-generated-contents', true );
202
203 // ... and mark all but the first child as ignorable
204 for ( let i = 1; i < els.length; i++ ) {
205 // Wrap plain text nodes so we can give them an attribute
206 els[ i ] = wrapTextNode( els[ i ] );
207 els[ i ].setAttribute( 'data-ve-ignore', 'true' );
208 }
209 } else if ( converter.isForPreview() ) {
210 const modelNode = ve.dm.nodeFactory.createFromElement( dataElement );
211 modelNode.setDocument( converter.internalList.getDocument() );
212 const viewNode = ve.ce.nodeFactory.createFromModel( modelNode );
213 // HACK: Node must be attached to check for rendering
214 viewNode.$element.appendTo( 'body' );
215 if ( !viewNode.hasRendering() ) {
216 viewNode.$element.detach();
217 viewNode.onSetup();
218 // HACK: Force the icon to render immediately
219 viewNode.updateInvisibleIconSync( true );
220 els = viewNode.$element.toArray();
221 }
222 viewNode.destroy();
223 viewNode.$element.detach();
224 }
225 return els;
226 };
227
228 ve.dm.MWTransclusionNode.static.describeChanges = function ( attributeChanges ) {
229 const descriptions = [ ve.msg( 'visualeditor-changedesc-mwtransclusion' ) ];
230
231 // This method assumes that the behavior of isDiffComparable above remains
232 // the same, so it doesn't have to consider whether the actual template
233 // involved has changed.
234
235 function getLabel( par ) {
236 // If a parameter is an object with a wt key, we just want the value of that.
237 if ( par && par.wt !== undefined ) {
238 // Can be `''`, and we're okay with that
239 return par.wt;
240 }
241 return par;
242 }
243
244 if ( attributeChanges.mw.from.parts.length === 1 && attributeChanges.mw.to.parts.length === 1 ) {
245 // Single-template transclusion, before and after. Relatively easy to summarize.
246 // TODO: expand this to well-represent transclusions that contain multiple templates.
247
248 // The bits of a template we care about are deeply-nested inside an
249 // attribute. We'll restructure this so that we can pretend template
250 // params are the direct attributes of the template.
251 const params = {};
252 let param;
253 for ( param in attributeChanges.mw.from.parts[ 0 ].template.params ) {
254 params[ param ] = { from: getLabel( attributeChanges.mw.from.parts[ 0 ].template.params[ param ] ) };
255 }
256 for ( param in attributeChanges.mw.to.parts[ 0 ].template.params ) {
257 params[ param ] = ve.extendObject(
258 { to: getLabel( attributeChanges.mw.to.parts[ 0 ].template.params[ param ] ) },
259 params[ param ]
260 );
261 }
262 let paramChanges;
263 for ( param in params ) {
264 // All we know is that *something* changed, without the normal
265 // helpful just-being-given-the-changed-bits, so we have to filter
266 // this ourselves.
267 // Trim string values, and convert empty strings to undefined
268 const from = ( params[ param ].from || '' ).trim() || undefined,
269 to = ( params[ param ].to || '' ).trim() || undefined;
270 if ( from !== to ) {
271 const change = this.describeChange( param, { from: from, to: to } );
272 if ( change ) {
273 if ( !paramChanges ) {
274 paramChanges = document.createElement( 'ul' );
275 descriptions.push( paramChanges );
276 }
277 const listItem = document.createElement( 'li' );
278 if ( typeof change === 'string' ) {
279 listItem.appendChild( document.createTextNode( change ) );
280 } else {
281 change.forEach( ( node ) => {
282 listItem.appendChild( node );
283 } );
284 }
285 paramChanges.appendChild( listItem );
286 }
287 }
288 }
289 }
290 return descriptions;
291 };
292
293 /**
294 * @inheritdoc ve.dm.Node
295 */
296 ve.dm.MWTransclusionNode.static.cloneElement = function () {
297 // Parent method
298 const clone = ve.dm.MWTransclusionNode.super.static.cloneElement.apply( this, arguments );
299 delete clone.attributes.originalMw;
300 return clone;
301 };
302
303 /**
304 * Escape a template parameter. Helper function for #getWikitext.
305 *
306 * @static
307 * @param {string} param Parameter value
308 * @return {string} Escaped parameter value
309 */
310 ve.dm.MWTransclusionNode.static.escapeParameter = function ( param ) {
311 let input = param,
312 output = '',
313 inNowiki = false,
314 bracketStack = 0,
315 linkStack = 0;
316
317 while ( input.length > 0 ) {
318 const match = input.match( /\[\[|]]|{{|}}|\|+|<\/?nowiki>|<nowiki\s*\/>/ );
319 if ( !match ) {
320 output += input;
321 break;
322 }
323 output += input.slice( 0, match.index );
324 input = input.slice( match.index + match[ 0 ].length );
325
326 if ( inNowiki ) {
327 if ( match[ 0 ] === '</nowiki>' ) {
328 inNowiki = false;
329 }
330 output += match[ 0 ];
331 continue;
332 }
333
334 let needsNowiki = true;
335 switch ( match[ 0 ].charAt( 0 ) ) {
336 case '<':
337 if ( match[ 0 ] === '<nowiki>' ) {
338 inNowiki = true;
339 }
340 needsNowiki = false;
341 break;
342 case '[':
343 linkStack++;
344 needsNowiki = false;
345 break;
346 case ']':
347 if ( linkStack > 0 ) {
348 linkStack--;
349 needsNowiki = false;
350 }
351 break;
352 case '{':
353 bracketStack++;
354 needsNowiki = false;
355 break;
356 case '}':
357 if ( bracketStack > 0 ) {
358 bracketStack--;
359 needsNowiki = false;
360 }
361 break;
362 case '|':
363 if ( bracketStack > 0 || linkStack > 0 ) {
364 needsNowiki = false;
365 }
366 break;
367 }
368
369 output += needsNowiki ?
370 '<nowiki>' + match[ 0 ] + '</nowiki>' :
371 match[ 0 ];
372 }
373 return output;
374 };
375
376 /**
377 * Recreate the wikitext for this transclusion, possibly containing multiple template invocations,
378 * mixed with raw wikitext snippets.
379 *
380 * @static
381 * @param {Object} content MW data content
382 * @return {string} Wikitext
383 */
384 ve.dm.MWTransclusionNode.static.getWikitext = function ( content ) {
385 let wikitext = '';
386
387 // Normalize to multi template format
388 if ( content.params ) {
389 content = { parts: [ { template: content } ] };
390 }
391 // Build wikitext from content
392 for ( let i = 0, len = content.parts.length; i < len; i++ ) {
393 const part = content.parts[ i ];
394 if ( part.template ) {
395 // Template
396 const template = part.template;
397 wikitext += '{{' + template.target.wt;
398 for ( const param in template.params ) {
399 wikitext += '|' + param + '=' +
400 this.escapeParameter( template.params[ param ].wt );
401 }
402 wikitext += '}}';
403 } else {
404 // Plain wikitext
405 wikitext += part;
406 }
407 }
408 return wikitext;
409 };
410
411 /* Methods */
412
413 /**
414 * Handle attribute change events.
415 *
416 * @param {string} key Attribute key
417 * @param {string} from Old value
418 * @param {string} to New value
419 */
420 ve.dm.MWTransclusionNode.prototype.onAttributeChange = function ( key ) {
421 if ( key === 'mw' ) {
422 this.partsList = null;
423 }
424 };
425
426 /**
427 * Check if transclusion contains only a single template.
428 *
429 * @param {string|string[]} [allowedTemplates] Names of templates to allow, omit to allow any template name
430 * @return {boolean} Transclusion only contains a single template, which is one of the ones in templates
431 */
432 ve.dm.MWTransclusionNode.prototype.isSingleTemplate = function ( allowedTemplates ) {
433 const templateNS = mw.config.get( 'wgNamespaceIds' ).template,
434 parts = this.getPartsList();
435
436 function normalizeTemplateTitle( name ) {
437 const title = mw.Title.newFromText( name, templateNS );
438 return title ? title.getPrefixedText() : name;
439 }
440
441 // Bail out as early as possible when no filter is given, or it's not a single part anyway
442 const isSingle = parts.length === 1;
443 if ( !isSingle || !allowedTemplates ) {
444 return isSingle;
445 }
446
447 const singlePart = parts[ 0 ];
448 // It's not a template but e.g. a parser function or raw wikitext content
449 if ( !singlePart.templatePage ) {
450 return false;
451 }
452
453 if ( typeof allowedTemplates === 'string' ) {
454 allowedTemplates = [ allowedTemplates ];
455 }
456 return allowedTemplates.some( ( template ) => singlePart.templatePage === normalizeTemplateTitle( template ) );
457 };
458
459 /**
460 * Get a simplified description of the transclusion's parts.
461 *
462 * @return {Object[]} List of objects with either template or content properties
463 */
464 ve.dm.MWTransclusionNode.prototype.getPartsList = function () {
465 if ( !this.partsList ) {
466 this.partsList = [];
467 const content = this.getAttribute( 'mw' );
468 for ( let i = 0; i < content.parts.length; i++ ) {
469 const part = content.parts[ i ];
470 // A template as serialized by {@see ve.dm.MWTemplateModel.serialize}
471 if ( part.template ) {
472 const href = part.template.target.href,
473 page = href ? mw.libs.ve.normalizeParsoidResourceName( href ) : null;
474 this.partsList.push( {
475 template: part.template.target.wt,
476 templatePage: page
477 } );
478 } else {
479 // Raw wikitext as serialized by {@see ve.dm.MWTransclusionContentModel.serialize}
480 this.partsList.push( { content: part } );
481 }
482 }
483 }
484
485 return this.partsList;
486 };
487
488 /**
489 * Wrapper for static method, {@see ve.dm.MWTransclusionNode.static.getWikitext} above.
490 *
491 * @return {string} Wikitext
492 */
493 ve.dm.MWTransclusionNode.prototype.getWikitext = function () {
494 return this.constructor.static.getWikitext( this.getAttribute( 'mw' ) );
495 };
496
497 /* Registration */
498
499 ve.dm.modelRegistry.register( ve.dm.MWTransclusionNode );