Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/ve.dm.Model.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Model class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Base class for DM models.
9 *
10 * @class
11 * @abstract
12 *
13 * @constructor
14 * @param {Object} element Reference to plain object in linear model
15 */
16 ve.dm.Model = function VeDmModel( element ) {
17 // Properties
18 this.element = element || { type: this.constructor.static.name };
19 this.store = null;
20 };
21
22 /* Inheritance */
23
24 OO.initClass( ve.dm.Model );
25
26 /* Static Properties */
27
28 /**
29 * Symbolic name for this model class. Must be set to a unique string by every subclass.
30 *
31 * @static
32 * @property {string}
33 * @inheritable
34 */
35 ve.dm.Model.static.name = null;
36
37 /**
38 * Array of HTML tag names that this model should be a match candidate for.
39 * Empty array means none, null means any.
40 * For more information about element matching, see ve.dm.ModelRegistry.
41 *
42 * @static
43 * @property {string[]}
44 * @inheritable
45 */
46 ve.dm.Model.static.matchTagNames = null;
47
48 /**
49 * Array of RDFa types that this model should be a match candidate for.
50 * Any other types the element might have must be specified in allowedRdfaTypes.
51 * Empty array means none, null means any.
52 * For more information about element matching, see ve.dm.ModelRegistry.
53 *
54 * @static
55 * @property {Array.<string|RegExp>|null}
56 * @inheritable
57 */
58 ve.dm.Model.static.matchRdfaTypes = null;
59
60 /**
61 * Extra RDFa types that the element is allowed to have (but don't by
62 * themselves trigger a match).
63 * Empty array means none, null means any.
64 * For more information about element matching, see ve.dm.ModelRegistry.
65 *
66 * @static
67 * @property {Array.<string|RegExp>|null}
68 * @inheritable
69 */
70 ve.dm.Model.static.allowedRdfaTypes = [];
71
72 /**
73 * Optional function to determine whether this model should match a given element.
74 * Takes a Node and returns true or false.
75 * This function is only called if this model has a chance of "winning"; see
76 * ve.dm.ModelRegistry for more information about element matching.
77 * If set to null, this property is ignored. Setting this to null is not the same as unconditionally
78 * returning true, because the presence or absence of a matchFunction affects the model's
79 * specificity.
80 *
81 * NOTE: This function is NOT a method, within this function "this" will not refer to an instance
82 * of this class (or to anything reasonable, for that matter).
83 *
84 * @static
85 * @property {Function}
86 * @inheritable
87 */
88 ve.dm.Model.static.matchFunction = null;
89
90 /**
91 * Static function to convert a DOM element or set of sibling DOM elements to a linear model element
92 * for this model type.
93 *
94 * This function is only called if this model "won" the matching for the first DOM element, so
95 * domElements[0] will match this model's matching rule. There is usually only one DOM node in
96 * domElements[]. Multiple elements will only be passed if this model supports about groups.
97 * If there are multiple nodes, the nodes are all adjacent siblings in the same about group
98 * (i.e. they are grouped together because they have the same value for the about attribute).
99 *
100 * The converter has some state variables that can be obtained by this function:
101 * - if converter.isExpectingContent() returns true, the converter expects a content element
102 * - if converter.isInWrapper() returns true, the returned element will be put in a wrapper
103 * paragraph generated by the converter (this is only relevant if isExpectingContent() is true)
104 * - converter.canCloseWrapper() returns true if the current wrapper paragraph can be closed,
105 * and false if it can't be closed or if there is no active wrapper
106 *
107 * This function is allowed to return a content element when context indicates that a non-content
108 * element is expected or vice versa. If that happens, the converter deals with it in the following way:
109 *
110 * - if a non-content element is expected but a content element is returned:
111 * - open a wrapper paragraph
112 * - put the returned element in the wrapper
113 * - if a content element is expected but a non-content element is returned:
114 * - if we are in a wrapper paragraph:
115 * - if we can close the wrapper:
116 * - close the wrapper
117 * - insert the returned element right after the end of the wrapper
118 * - if we can't close the wrapper:
119 * - alienate the element
120 * - if we aren't in a wrapper paragraph:
121 * - alienate the element
122 *
123 * For these purposes, annotations are considered content. Meta-items can occur anywhere, so if
124 * a meta-element is returned no special action is taken. Note that "alienate" always means an alien
125 * **node** (ve.dm.AlienNode) will be generated, never an alien meta-item (ve.dm.AlienMetaItem),
126 * regardless of whether the subclass attempting the conversion is a node or a meta-item.
127 *
128 * The returned linear model element must have a type property set to a registered model name
129 * (usually the model's own .static.name, but that's not required). It may optionally have an attributes
130 * property set to an object with key-value pairs. Any other properties are not allowed.
131 *
132 * This function may return a single linear model element, or an array of balanced linear model
133 * data. If this function needs to recursively convert a DOM node (e.g. a child of one of the
134 * DOM elements passed in), it can call converter.getDataFromDomSubtree( domElement ). Note that
135 * if an array is returned, the converter will not descend into the DOM node's children; the model
136 * will be assumed to have handled those children.
137 *
138 * @static
139 * @inheritable
140 * @param {Node[]} domElements DOM elements to convert. Usually only one element
141 * @param {ve.dm.Converter} converter
142 * @return {Object|Array|null} Linear model element, or array with linear model data, or null to alienate
143 */
144 ve.dm.Model.static.toDataElement = function () {
145 return { type: this.name };
146 };
147
148 /**
149 * Static function to convert a linear model data element for this model type back to one or more
150 * DOM elements.
151 *
152 * If this model is a node with handlesOwnChildren set to true, dataElement will be an array of
153 * the linear model data of this node and all of its children, rather than a single element.
154 * In this case, this function may want to recursively convert linear model data to DOM, which can
155 * be done with ve.dm.Converter#getDomSubtreeFromData.
156 *
157 * NOTE: If this function returns multiple DOM elements, the DOM elements produced by the children
158 * of this model (if it's a node and has children) will be attached to the first DOM element in the array.
159 * For annotations, only the first element is used, and any additional elements are ignored.
160 *
161 * @static
162 * @inheritable
163 * @param {Object|Array} dataElement Linear model element or array of linear model data
164 * @param {HTMLDocument} doc HTML document for creating elements
165 * @param {ve.dm.Converter} converter Converter object to optionally call `getDomSubtreeFromData` on
166 * @return {Node[]} DOM elements
167 */
168 ve.dm.Model.static.toDomElements = function ( dataElement, doc ) {
169 if ( this.matchTagNames && this.matchTagNames.length === 1 ) {
170 return [ doc.createElement( this.matchTagNames[ 0 ] ) ];
171 }
172 throw new Error( 've.dm.Model subclass must match a single tag name or implement toDomElements' );
173 };
174
175 /**
176 * Whether this model supports about grouping. When a DOM element matches a model type that has
177 * about grouping enabled, the converter will look for adjacent siblings with the same value for
178 * the about attribute, and ask #toDataElement to produce a single data element for all of those
179 * DOM nodes combined.
180 *
181 * The converter doesn't descend into about groups, i.e. it doesn't convert the children of the
182 * DOM elements that make up the about group. This means the resulting linear model element will
183 * be childless.
184 *
185 * @static
186 * @property {boolean}
187 * @inheritable
188 */
189 ve.dm.Model.static.enableAboutGrouping = false;
190
191 /**
192 * Which HTML attributes should be preserved for this model type. When converting back to DOM,
193 * these HTML attributes will be restored except for attributes that were already set by #toDomElements.
194 *
195 * The value of this property can be one of the following:
196 *
197 * - true, to preserve all attributes (default)
198 * - false, to preserve none
199 * - a function that takes an attribute name and returns true or false
200 *
201 * @static
202 * @property {boolean|Function}
203 * @inheritable
204 */
205 ve.dm.Model.static.preserveHtmlAttributes = true;
206
207 /* Static methods */
208
209 /**
210 * Get hash object of a linear model data element.
211 *
212 * @static
213 * @param {Object} dataElement Data element
214 * @return {Object} Hash object
215 */
216 ve.dm.Model.static.getHashObject = function ( dataElement ) {
217 const hash = {
218 type: dataElement.type,
219 attributes: dataElement.attributes
220 };
221 if ( dataElement.originalDomElementsHash !== undefined ) {
222 hash.originalDomElementsHash = dataElement.originalDomElementsHash;
223 }
224 return hash;
225 };
226
227 /**
228 * Array of RDFa types that this model should be a match candidate for.
229 *
230 * @static
231 * @return {Array.<string|RegExp>|null} Array of strings or regular expressions
232 */
233 ve.dm.Model.static.getMatchRdfaTypes = function () {
234 return this.matchRdfaTypes;
235 };
236
237 /**
238 * Extra RDFa types that the element is allowed to have.
239 *
240 * @static
241 * @return {Array.<string|RegExp>|null} Array of strings or regular expressions
242 */
243 ve.dm.Model.static.getAllowedRdfaTypes = function () {
244 return this.allowedRdfaTypes;
245 };
246
247 /**
248 * Describe attribute changes in the model
249 *
250 * @param {Object} attributeChanges Attribute changes, keyed list containing objects with from and to properties
251 * @param {Object} attributes New attributes
252 * @param {Object} element New element
253 * @return {Array} Descriptions, list of strings or Node arrays
254 */
255 ve.dm.Model.static.describeChanges = function ( attributeChanges ) {
256 const descriptions = [];
257 for ( const key in attributeChanges ) {
258 const change = this.describeChange( key, attributeChanges[ key ] );
259 if ( change ) {
260 descriptions.push( change );
261 }
262 }
263 return descriptions;
264 };
265
266 /**
267 * Describe a single attribute change in the model
268 *
269 * @param {string} key Attribute key
270 * @param {Object} change Change object with from and to properties
271 * @return {string|Node[]|null} Description (string or Node array), or null if nothing to describe
272 */
273 ve.dm.Model.static.describeChange = function ( key, change ) {
274 if ( ( typeof change.from === 'object' && change.from !== null ) || ( typeof change.to === 'object' && change.to !== null ) ) {
275 return ve.htmlMsg( 'visualeditor-changedesc-unknown', key );
276 } else if ( change.from === undefined || change.from === null ) {
277 return ve.htmlMsg( 'visualeditor-changedesc-set', key, this.wrapText( 'ins', change.to ) );
278 } else if ( change.to === undefined || change.to === null ) {
279 return ve.htmlMsg( 'visualeditor-changedesc-unset', key, this.wrapText( 'del', change.from ) );
280 } else if ( key === 'listItemDepth' ) {
281 // listItemDepth is a special key used on nodes which have isDiffedAsList set
282 if ( change.to > change.from ) {
283 return ve.msg( 'visualeditor-changedesc-list-indent' );
284 } else if ( change.to < change.from ) {
285 return ve.msg( 'visualeditor-changedesc-list-outdent' );
286 }
287 } else {
288 // Use String() for string casting as values could be null
289 const diff = this.getAttributeDiff( String( change.from ), String( change.to ) );
290 if ( diff ) {
291 return ve.htmlMsg( 'visualeditor-changedesc-changed-diff', key, diff );
292 } else {
293 return ve.htmlMsg( 'visualeditor-changedesc-changed', key, this.wrapText( 'del', change.from ), this.wrapText( 'ins', change.to ) );
294 }
295 }
296 return null;
297 };
298
299 /**
300 * Compare two attribute strings and return an HTML diff
301 *
302 * @param {string} oldText Old attribute text
303 * @param {string} newText New attribute text
304 * @param {boolean} [allowRemoveInsert] Allow the diff to be a full remove insert
305 * @return {HTMLElement|null} An HTML diff in a span element, or null if the diff
306 * was a simple remove-insert, and allowRemoveInsert wasn't set.
307 */
308 ve.dm.Model.static.getAttributeDiff = function ( oldText, newText, allowRemoveInsert ) {
309 const span = document.createElement( 'span' ),
310 /* global diff_match_patch */
311 // eslint-disable-next-line new-cap
312 differ = new diff_match_patch();
313 let isRemoveInsert = true;
314
315 const diff = differ.diff_main( oldText, newText );
316 differ.diff_cleanupEfficiency( diff );
317
318 diff.forEach( ( part ) => {
319 switch ( part[ 0 ] ) {
320 case -1:
321 span.appendChild( this.wrapText( 'del', part[ 1 ] ) );
322 break;
323 case 1:
324 span.appendChild( this.wrapText( 'ins', part[ 1 ] ) );
325 break;
326 case 0:
327 isRemoveInsert = false;
328 span.appendChild( document.createTextNode( part[ 1 ] ) );
329 break;
330 }
331 } );
332
333 return !isRemoveInsert || allowRemoveInsert ? span : null;
334 };
335
336 /**
337 * Utility function for wrapping text in a tag, equivalent to `$( '<tag>' ).text( text )`
338 *
339 * @param {string} tag Wrapping element's tag
340 * @param {string} text
341 * @return {HTMLElement} Element wrapping text
342 */
343 ve.dm.Model.static.wrapText = function ( tag, text ) {
344 const wrapper = document.createElement( tag );
345 wrapper.appendChild( document.createTextNode( text ) );
346 return wrapper;
347 };
348
349 /**
350 * Check if this element is of the same type as another element for the purposes of diffing.
351 *
352 * @static
353 * @param {Object} element This element
354 * @param {Object} other Another element
355 * @param {ve.dm.HashValueStore} elementStore Store used by this element
356 * @param {ve.dm.HashValueStore} otherStore Store used by other elements
357 * @return {boolean} Elements are of a comparable type
358 */
359 ve.dm.Model.static.isDiffComparable = function ( element, other ) {
360 return element.type === other.type;
361 };
362
363 /* Methods */
364
365 /**
366 * Check whether this node can be inspected by a context item.
367 *
368 * The default implementation always returns true. If your node type is uninspectable in certain
369 * cases, you should override this function.
370 *
371 * @return {boolean} Whether this node is inspectable
372 */
373 ve.dm.Model.prototype.isInspectable = function () {
374 return true;
375 };
376
377 /**
378 * Check whether this node can be edited by a context item
379 *
380 * The default implementation always returns true. If your node type is uneditable in certain
381 * cases, you should override this function.
382 *
383 * @return {boolean} Whether this node is editable
384 */
385 ve.dm.Model.prototype.isEditable = function () {
386 return true;
387 };
388
389 /**
390 * Get a reference to the linear model element.
391 *
392 * @return {Object} Linear model element passed to the constructor, by reference
393 */
394 ve.dm.Model.prototype.getElement = function () {
395 return this.element;
396 };
397
398 /**
399 * Get a reference to the hash-value store used by the element.
400 *
401 * @return {ve.dm.HashValueStore} Hash-value store
402 */
403 ve.dm.Model.prototype.getStore = function () {
404 return this.store;
405 };
406
407 /**
408 * Get the symbolic name of this model's type.
409 *
410 * @return {string} Type name
411 */
412 ve.dm.Model.prototype.getType = function () {
413 return this.constructor.static.name;
414 };
415
416 /**
417 * Get the value of an attribute.
418 *
419 * Return value is by reference if array or object.
420 *
421 * @param {string} key Name of attribute to get
422 * @return {any} Value of attribute, or undefined if no such attribute exists
423 */
424 ve.dm.Model.prototype.getAttribute = function ( key ) {
425 return this.element && this.element.attributes ? this.element.attributes[ key ] : undefined;
426 };
427
428 /**
429 * Get a copy of all attributes.
430 *
431 * Values are by reference if array or object, similar to using the getAttribute method.
432 *
433 * @param {string} [prefix] Only return attributes with this prefix, and remove the prefix from them
434 * @return {Object} Attributes
435 */
436 ve.dm.Model.prototype.getAttributes = function ( prefix ) {
437 const attributes = this.element && this.element.attributes ? this.element.attributes : {};
438 if ( prefix ) {
439 const filtered = {};
440 for ( const key in attributes ) {
441 if ( key.indexOf( prefix ) === 0 ) {
442 filtered[ key.slice( prefix.length ) ] = attributes[ key ];
443 }
444 }
445 return filtered;
446 }
447 return ve.extendObject( {}, attributes );
448 };
449
450 /**
451 * Get the DOM element(s) this model was originally converted from, if any.
452 *
453 * @return {string|undefined} Store hash of DOM elements this model was converted from
454 */
455 ve.dm.Model.prototype.getOriginalDomElementsHash = function () {
456 return this.element ? this.element.originalDomElementsHash : undefined;
457 };
458
459 /**
460 * Get the DOM element(s) this model was originally converted from, if any.
461 *
462 * @param {ve.dm.HashValueStore} store Hash value store where the DOM elements are stored
463 * @return {HTMLElement[]} DOM elements this model was converted from, empty if not applicable
464 */
465 ve.dm.Model.prototype.getOriginalDomElements = function ( store ) {
466 return store.value( this.getOriginalDomElementsHash() ) || [];
467 };
468
469 /**
470 * Get a clone of the model's linear model element.
471 *
472 * The attributes object will be deep-copied.
473 *
474 * @return {Object} Cloned element object
475 */
476 ve.dm.Model.prototype.getClonedElement = function () {
477 return ve.copy( this.element );
478 };
479
480 /**
481 * Get the hash object of the linear model element.
482 *
483 * The actual logic is in a static function as this needs
484 * to be accessible from ve.dm.Converter
485 *
486 * This is a custom hash function for OO#getHash.
487 *
488 * @return {Object} Hash object
489 */
490 ve.dm.Model.prototype.getHashObject = function () {
491 return this.constructor.static.getHashObject( this.element );
492 };
493
494 /**
495 * Check if this element is of the same type as another element for the purposes of diffing.
496 *
497 * Elements which aren't of the same type will always be shown as removal and an insertion,
498 * whereas comarable elements will be shown as an attribute change.
499 *
500 * @param {Object} other Another element
501 * @return {boolean} Elements are of a comparable type
502 */
503 ve.dm.Model.prototype.isDiffComparable = function ( other ) {
504 return this.constructor.static.isDiffComparable( this.element, other.element, this.getStore(), other.getStore() );
505 };