Debian Codegraph @

extensions/Cite/modules/ve-cite/ve.dm.MWReferenceNode.js

raw symbols SCIP
1 'use strict';
2
3 /*!
4 * VisualEditor DataModel MWReferenceNode class.
5 *
6 * @copyright 2011-2018 VisualEditor Team's Cite sub-team and others; see AUTHORS.txt
7 * @license MIT
8 */
9
10 /**
11 * DataModel MediaWiki reference node.
12 *
13 * @constructor
14 * @extends ve.dm.LeafNode
15 * @mixes ve.dm.FocusableNode
16 * @param {Object} [element] Reference to element in linear model
17 */
18 ve.dm.MWReferenceNode = function VeDmMWReferenceNode() {
19 // Parent constructor
20 ve.dm.MWReferenceNode.super.apply( this, arguments );
21
22 // Mixin constructors
23 ve.dm.FocusableNode.call( this );
24
25 // Event handlers
26 this.connect( this, {
27 root: 'onRoot',
28 unroot: 'onUnroot',
29 attributeChange: 'onAttributeChange'
30 } );
31 };
32
33 /* Inheritance */
34
35 OO.inheritClass( ve.dm.MWReferenceNode, ve.dm.LeafNode );
36
37 OO.mixinClass( ve.dm.MWReferenceNode, ve.dm.FocusableNode );
38
39 /* Static members */
40
41 ve.dm.MWReferenceNode.static.name = 'mwReference';
42
43 ve.dm.MWReferenceNode.static.matchTagNames = null;
44
45 ve.dm.MWReferenceNode.static.matchRdfaTypes = [ 'mw:Extension/ref' ];
46
47 // Handle nodes with mw:Error as this probably just means the ref list doesn't exist (T299672)
48 ve.dm.MWReferenceNode.static.allowedRdfaTypes = [ 'dc:references', 'mw:Error' ];
49
50 ve.dm.MWReferenceNode.static.isContent = true;
51
52 ve.dm.MWReferenceNode.static.disallowedAnnotationTypes = [ 'link' ];
53
54 /**
55 * Regular expression for parsing the listKey attribute
56 *
57 * Use [\s\S]* instead of .* to catch esoteric whitespace (T263698)
58 *
59 * @static
60 * @property {RegExp}
61 * @inheritable
62 */
63 ve.dm.MWReferenceNode.static.listKeyRegex = /^(auto|literal)\/([\s\S]*)$/;
64
65 ve.dm.MWReferenceNode.static.toDataElement = function ( domElements, converter ) {
66 function getReflistItemHtml( id ) {
67 const elem = converter.getHtmlDocument().getElementById( id );
68 return elem && elem.innerHTML;
69 }
70
71 const mwDataJSON = domElements[ 0 ].getAttribute( 'data-mw' );
72 const mwData = mwDataJSON ? JSON.parse( mwDataJSON ) : {};
73 const mwAttrs = mwData.attrs || {};
74 const reflistItemId = ve.getProp( mwData, 'body', 'id' );
75 const body = ve.getProp( mwData, 'body', 'html' ) ||
76 ( reflistItemId && getReflistItemHtml( reflistItemId ) ) ||
77 '';
78 const refGroup = mwAttrs.group || '';
79 const listGroup = this.name + '/' + refGroup;
80 const listKey = !mwAttrs.name ?
81 'auto/' + converter.internalList.getNextUniqueNumber() :
82 'literal/' + mwAttrs.name;
83 const queueResult = converter.internalList.queueItemHtml( listGroup, listKey, body );
84
85 const dataElement = {
86 type: this.name,
87 attributes: {
88 mw: mwData,
89 originalMw: mwDataJSON,
90 listIndex: queueResult.index,
91 listGroup: listGroup,
92 listKey: listKey,
93 refGroup: refGroup,
94 contentsUsed: body !== '' && queueResult.isNew
95 }
96 };
97 if ( mwAttrs.extends && mw.config.get( 'wgCiteSubReferencing' ) ) {
98 dataElement.attributes.extendsRef = mwAttrs.extends ? 'literal/' + mwAttrs.extends : null;
99 }
100 if ( reflistItemId ) {
101 dataElement.attributes.refListItemId = reflistItemId;
102 }
103 return dataElement;
104 };
105
106 ve.dm.MWReferenceNode.static.toDomElements = function ( dataElement, doc, converter ) {
107 const isForClipboard = converter.isForClipboard();
108 const el = doc.createElement( 'sup' );
109
110 el.setAttribute( 'typeof', 'mw:Extension/ref' );
111
112 const mwData = dataElement.attributes.mw ? ve.copy( dataElement.attributes.mw ) : {};
113 mwData.name = 'ref';
114
115 if ( isForClipboard || converter.isForParser() ) {
116 let setContents = dataElement.attributes.contentsUsed;
117
118 // This call rebuilds the document tree if it isn't built already (e.g. on a
119 // document slice), so only use when necessary (i.e. not in preview mode)
120 const itemNode = converter.internalList.getItemNode( dataElement.attributes.listIndex );
121 const itemNodeRange = itemNode.getRange();
122
123 const keyedNodes = converter.internalList
124 .getNodeGroup( dataElement.attributes.listGroup )
125 .keyedNodes[ dataElement.attributes.listKey ];
126
127 const extendsNodes = converter.internalList.getNodeGroup( dataElement.attributes.listGroup ).firstNodes.filter(
128 ( node ) => node.element.attributes.extendsRef === dataElement.attributes.listKey
129 );
130
131 let contentsAlreadySet = false;
132 if ( setContents ) {
133 // Check if a previous node has already set the content. If so, we don't overwrite this
134 // node's contents.
135 if ( keyedNodes ) {
136 for ( let i = 0; i < keyedNodes.length; i++ ) {
137 if (
138 ve.compare(
139 this.getInstanceHashObject( keyedNodes[ i ].element ),
140 this.getInstanceHashObject( dataElement )
141 )
142 ) {
143 break;
144 }
145 if ( keyedNodes[ i ].element.attributes.contentsUsed ) {
146 contentsAlreadySet = true;
147 break;
148 }
149 }
150 }
151 } else {
152 // Check if any other nodes with this key provided content. If not
153 // then we attach the contents to the first reference with this key
154
155 // Check that this is the first reference with its key
156 if (
157 keyedNodes &&
158 ve.compare(
159 this.getInstanceHashObject( dataElement ),
160 this.getInstanceHashObject( keyedNodes[ 0 ].element )
161 )
162 ) {
163 setContents = true;
164 // Check no other reference originally defined the contents
165 // As this is keyedNodes[0] we can start at 1
166 for ( let i = 1; i < keyedNodes.length; i++ ) {
167 if ( keyedNodes[ i ].element.attributes.contentsUsed ) {
168 setContents = false;
169 break;
170 }
171 }
172 }
173 }
174
175 // Add reference contents to data-mw.
176 if ( setContents && !contentsAlreadySet ) {
177 const itemNodeWrapper = doc.createElement( 'div' );
178 const originalHtmlWrapper = doc.createElement( 'div' );
179 converter.getDomSubtreeFromData(
180 itemNode.getDocument().getFullData( itemNodeRange, 'roundTrip' ),
181 itemNodeWrapper
182 );
183 // Returns '' if itemNodeWrapper is empty
184 const itemNodeHtml = itemNodeWrapper.innerHTML;
185 const originalHtml = ve.getProp( mwData, 'body', 'html' ) ||
186 ( ve.getProp( mwData, 'body', 'id' ) !== undefined && itemNode.getAttribute( 'originalHtml' ) ) ||
187 '';
188 originalHtmlWrapper.innerHTML = originalHtml;
189 // Only set body.html if itemNodeHtml and originalHtml are actually different,
190 // or we are writing the clipboard for use in another VE instance
191 if ( isForClipboard || !originalHtmlWrapper.isEqualNode( itemNodeWrapper ) ) {
192 ve.setProp( mwData, 'body', 'html', itemNodeHtml );
193 }
194 }
195
196 // If we have no internal item data for this reference, don't let it get pasted into
197 // another VE document. T110479
198 if ( isForClipboard && itemNodeRange.isCollapsed() ) {
199 el.setAttribute( 'data-ve-ignore', 'true' );
200 }
201
202 // Set extends
203 if ( dataElement.attributes.extendsRef ) {
204 let extendsAttr;
205 const extendsKeyParts = dataElement.attributes.extendsRef.match( this.listKeyRegex );
206 if ( extendsKeyParts[ 1 ] === 'auto' ) {
207 // Allocate a unique list key, then strip the 'literal/'' prefix
208 extendsAttr = converter.internalList.getUniqueListKey(
209 dataElement.attributes.listGroup,
210 dataElement.attributes.extendsRef,
211 // Generate a name starting with ':' to distinguish it from normal names
212 'literal/:'
213 ).slice( 'literal/'.length );
214 } else {
215 extendsAttr = extendsKeyParts[ 2 ];
216 }
217 ve.setProp( mwData, 'attrs', 'extends', extendsAttr );
218 }
219
220 // Generate name
221 let name;
222 const listKeyParts = dataElement.attributes.listKey.match( this.listKeyRegex );
223 if ( listKeyParts[ 1 ] === 'auto' ) {
224 // Only render a name if this key was reused
225 if ( keyedNodes.length > 1 || extendsNodes.length ) {
226 // Allocate a unique list key, then strip the 'literal/'' prefix
227 name = converter.internalList.getUniqueListKey(
228 dataElement.attributes.listGroup,
229 dataElement.attributes.listKey,
230 // Generate a name starting with ':' to distinguish it from normal names
231 'literal/:'
232 ).slice( 'literal/'.length );
233 }
234 } else {
235 // Use literal name
236 name = listKeyParts[ 2 ];
237 }
238 // Set name
239 if ( name !== undefined ) {
240 ve.setProp( mwData, 'attrs', 'name', name );
241 }
242
243 // Set or clear group
244 if ( dataElement.attributes.refGroup !== '' ) {
245 ve.setProp( mwData, 'attrs', 'group', dataElement.attributes.refGroup );
246 } else if ( mwData.attrs ) {
247 delete mwData.attrs.group;
248 }
249 }
250
251 // If mwAttr and originalMw are the same, use originalMw to prevent reserialization,
252 // unless we are writing the clipboard for use in another VE instance
253 // Reserialization has the potential to reorder keys and so change the DOM unnecessarily
254 const originalMw = dataElement.attributes.originalMw;
255 if ( converter.isForParser() && originalMw && ve.compare( mwData, JSON.parse( originalMw ) ) ) {
256 el.setAttribute( 'data-mw', originalMw );
257
258 // Return the original DOM elements if possible
259 if ( dataElement.originalDomElementsHash !== undefined ) {
260 return ve.copyDomElements(
261 converter.getStore().value( dataElement.originalDomElementsHash ), doc );
262 }
263 } else {
264 el.setAttribute( 'data-mw', JSON.stringify( mwData ) );
265
266 // HTML for the external clipboard, it will be ignored by the converter
267 const $link = $( '<a>', doc )
268 .attr( 'data-mw-group', this.getGroup( dataElement ) || null );
269 $( el ).addClass( 'mw-ref reference' ).html(
270 $link.append(
271 $( '<span>', doc ).addClass( 'mw-reflink-text' ).html( this.getIndexLabel( dataElement, converter.internalList ) )
272 )
273 );
274 }
275
276 return [ el ];
277 };
278
279 ve.dm.MWReferenceNode.static.remapInternalListIndexes = function (
280 dataElement, mapping, internalList
281 ) {
282 // Remap listIndex
283 dataElement.attributes.listIndex = mapping[ dataElement.attributes.listIndex ];
284
285 // Remap listKey if it was automatically generated
286 const listKeyParts = dataElement.attributes.listKey.match( this.listKeyRegex );
287 if ( listKeyParts[ 1 ] === 'auto' ) {
288 dataElement.attributes.listKey = 'auto/' + internalList.getNextUniqueNumber();
289 }
290 };
291
292 ve.dm.MWReferenceNode.static.remapInternalListKeys = function ( dataElement, internalList ) {
293 let suffix = '';
294 // Try name, name2, name3, ... until unique
295 while ( internalList.keys.indexOf( dataElement.attributes.listKey + suffix ) !== -1 ) {
296 suffix = suffix ? suffix + 1 : 2;
297 }
298 if ( suffix ) {
299 dataElement.attributes.listKey += suffix;
300 }
301 };
302
303 /**
304 * Gets the group for the reference
305 *
306 * @static
307 * @param {Object} dataElement Element data
308 * @return {string} Group
309 */
310 ve.dm.MWReferenceNode.static.getGroup = function ( dataElement ) {
311 return dataElement.attributes.refGroup;
312 };
313
314 /**
315 * Gets the index label for the reference
316 *
317 * @static
318 * @param {Object} dataElement Element data
319 * @param {ve.dm.InternalList} internalList Internal list
320 * @return {string} Reference label as HTML
321 */
322 ve.dm.MWReferenceNode.static.getIndexLabel = function ( dataElement, internalList ) {
323 const refGroup = dataElement.attributes.refGroup;
324 const indexNumber = dataElement.attributes.placeholder ? '…' :
325 ve.dm.MWReferenceNode.static.findIndexNumber( dataElement, internalList );
326 const label = ( refGroup ? refGroup + ' ' : '' ) + indexNumber;
327
328 return `<span class="cite-bracket">[</span>${ label }<span class="cite-bracket">]</span>`;
329 };
330
331 /**
332 * TODO: replace with a simple property
333 *
334 * @private
335 * @param {Object} dataElement data for the node to be looked up
336 * @param {ve.dm.InternalList} internalList document internalList
337 * @return {string} footnote number ready for rendering
338 */
339 ve.dm.MWReferenceNode.static.findIndexNumber = function ( dataElement, internalList ) {
340 return ve.getProp( dataElement, 'internal', 'overrideIndex' ) ||
341 ve.dm.MWDocumentReferences.static.refsForDoc( internalList.getDocument() )
342 .getIndexLabel( dataElement.attributes.refGroup, dataElement.attributes.listKey );
343 };
344
345 /**
346 * @override
347 * @see ve.dm.Node
348 */
349 ve.dm.MWReferenceNode.static.cloneElement = function () {
350 const clone = ve.dm.MWReferenceNode.super.static.cloneElement.apply( this, arguments );
351 delete clone.attributes.contentsUsed;
352 delete clone.attributes.mw;
353 delete clone.attributes.originalMw;
354 // HACK: Generate a fake hash so this element is never instance comparable to other elements
355 // Without originalMw this hash will not get used in toDomElements
356 clone.originalDomElementsHash = Math.random();
357 return clone;
358 };
359
360 /**
361 * @override
362 * @see ve.dm.LeafNode
363 */
364 ve.dm.MWReferenceNode.static.getHashObject = function ( dataElement ) {
365 // Consider all references in the same group to be comparable:
366 // References can't be usefully compared statically, as they are mostly
367 // defined by the contents of their internal item, which exists
368 // elsewhere in the document.
369 // For diffing, comparing reference indexes is not useful as
370 // they are auto-generated, and the reference list diff is
371 // already handled separately, so will show moves etc.
372 //
373 // If you need to compare references with the same name, use
374 // #getInstanceHashObject
375 return {
376 type: dataElement.type,
377 attributes: {
378 listGroup: dataElement.attributes.listGroup
379 }
380 };
381 };
382
383 /**
384 * Get a hash unique to this instance of the reference
385 *
386 * As #getHashObject has been simplified to make re-used references
387 * all equal (to support visual diffing), provide access to a more
388 * typical hash that can be used to compare instances of reference
389 * which have the same "name".
390 *
391 * @param {Object} dataElement
392 * @return {Object}
393 */
394 ve.dm.MWReferenceNode.static.getInstanceHashObject = function () {
395 return ve.dm.MWReferenceNode.super.static.getHashObject.apply( this, arguments );
396 };
397
398 /**
399 * @override
400 * @see ve.dm.Model
401 */
402 ve.dm.MWReferenceNode.static.describeChange = function ( key, change ) {
403 if ( key === 'refGroup' ) {
404 if ( !change.from ) {
405 return ve.htmlMsg( 'cite-ve-changedesc-ref-group-to', this.wrapText( 'ins', change.to ) );
406 } else if ( !change.to ) {
407 return ve.htmlMsg( 'cite-ve-changedesc-ref-group-from', this.wrapText( 'del', change.from ) );
408 } else {
409 return ve.htmlMsg( 'cite-ve-changedesc-ref-group-both', this.wrapText( 'del', change.from ), this.wrapText( 'ins', change.to ) );
410 }
411 }
412 };
413
414 /* Methods */
415
416 /**
417 * Don't allow reference nodes to be edited if we can't find their contents.
418 *
419 * @override
420 * @see ve.dm.Model
421 */
422 ve.dm.MWReferenceNode.prototype.isEditable = function () {
423 const internalItem = this.getInternalItem();
424 return internalItem && internalItem.getLength() > 0;
425 };
426
427 /**
428 * Gets the internal item node associated with this node
429 *
430 * @return {ve.dm.InternalItemNode} Item node
431 */
432 ve.dm.MWReferenceNode.prototype.getInternalItem = function () {
433 return this.getDocument().getInternalList().getItemNode( this.getAttribute( 'listIndex' ) );
434 };
435
436 /**
437 * Gets the index for the reference
438 *
439 * @return {number} Index
440 */
441 ve.dm.MWReferenceNode.prototype.getIndex = function () {
442 return this.constructor.static.getIndex( this.element, this.getDocument().getInternalList() );
443 };
444
445 /**
446 * Gets the group for the reference
447 *
448 * @return {string} Group
449 */
450 ve.dm.MWReferenceNode.prototype.getGroup = function () {
451 return this.constructor.static.getGroup( this.element );
452 };
453
454 /**
455 * Gets the index label for the reference
456 *
457 * @return {string} Reference label
458 */
459 ve.dm.MWReferenceNode.prototype.getIndexLabel = function () {
460 return this.constructor.static.getIndexLabel(
461 this.element, this.getDocument().getInternalList() );
462 };
463
464 /**
465 * FIXME: This will be replaced by a simple property.
466 *
467 * @return {string} Footnote number ready for rendering
468 */
469 ve.dm.MWReferenceNode.prototype.getIndexNumber = function () {
470 return this.constructor.static.findIndexNumber( this.element, this.getDocument().getInternalList() );
471 };
472
473 /**
474 * Handle the node being attached to the root
475 */
476 ve.dm.MWReferenceNode.prototype.onRoot = function () {
477 this.addToInternalList();
478 };
479
480 /**
481 * Handle the node being detached from the root
482 *
483 * @param {ve.dm.DocumentNode} oldRoot Old document root
484 */
485 ve.dm.MWReferenceNode.prototype.onUnroot = function ( oldRoot ) {
486 if ( this.getDocument().getDocumentNode() === oldRoot ) {
487 this.removeFromInternalList();
488 }
489 };
490
491 /**
492 * Register the node with the internal list
493 */
494 ve.dm.MWReferenceNode.prototype.addToInternalList = function () {
495 if ( this.getRoot() === this.getDocument().getDocumentNode() ) {
496 const attributes = this.element.attributes;
497 this.registeredListGroup = attributes.listGroup;
498 this.registeredListKey = attributes.listKey;
499 this.registeredListIndex = attributes.listIndex;
500 this.getDocument().getInternalList().addNode(
501 this.registeredListGroup,
502 this.registeredListKey,
503 this.registeredListIndex,
504 this
505 );
506 }
507 };
508
509 /**
510 * Unregister the node from the internal list
511 */
512 ve.dm.MWReferenceNode.prototype.removeFromInternalList = function () {
513 if ( !this.registeredListGroup ) {
514 // Don't try to remove if we haven't been added in the first place.
515 return;
516 }
517 this.getDocument().getInternalList().removeNode(
518 this.registeredListGroup,
519 this.registeredListKey,
520 this.registeredListIndex,
521 this
522 );
523 };
524
525 ve.dm.MWReferenceNode.prototype.onAttributeChange = function ( key, from, to ) {
526 if ( key === 'placeholder' ) {
527 this.getDocument().getInternalList().markGroupAsChanged( this.registeredListGroup );
528 }
529 if (
530 ( key !== 'listGroup' && key !== 'listKey' ) ||
531 ( key === 'listGroup' && this.registeredListGroup === to ) ||
532 ( key === 'listKey' && this.registeredListKey === to )
533 ) {
534 return;
535 }
536
537 // Need the old list keys and indexes, so we register them in addToInternalList
538 // They've already been updated in this.element.attributes before this code runs
539 this.removeFromInternalList();
540 this.addToInternalList();
541 };
542
543 /* Registration */
544
545 ve.dm.modelRegistry.register( ve.dm.MWReferenceNode );