Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel InternalList class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel meta item.
9 *
10 * @class
11 * @mixes OO.EventEmitter
12 *
13 * @constructor
14 * @param {ve.dm.Document} doc Document model
15 */
16 ve.dm.InternalList = function VeDmInternalList( doc ) {
17 // Mixin constructors
18 OO.EventEmitter.call( this );
19
20 // Properties
21 this.document = doc;
22 this.itemHtmlQueue = [];
23 this.listNode = null;
24 this.nodes = {};
25 this.groupsChanged = [];
26 this.keyIndexes = {};
27 this.keys = [];
28
29 // Event handlers
30 doc.connect( this, { transact: 'onTransact' } );
31 };
32
33 /* Inheritance */
34
35 OO.mixinClass( ve.dm.InternalList, OO.EventEmitter );
36
37 /* Events */
38
39 /**
40 * @event ve.dm.InternalList#update
41 * @param {string[]} groupsChanged List of groups changed since the last transaction
42 */
43
44 /* Methods */
45
46 /**
47 * Queues up an item's html for parsing later.
48 *
49 * If an item with the specified group and key already exists it will be ignored, unless
50 * the data already stored is an empty string.
51 *
52 * @param {string} groupName Item group
53 * @param {string} key Item key
54 * @param {string} html Item contents
55 * @return {Object} Object containing index of the item in the index-value store
56 * (and also its index in the internal list node), and a flag indicating if it is a new item.
57 */
58 ve.dm.InternalList.prototype.queueItemHtml = function ( groupName, key, html ) {
59 let isNew = false,
60 index = this.getKeyIndex( groupName, key );
61
62 if ( index === undefined ) {
63 index = this.itemHtmlQueue.length;
64 this.keyIndexes[ groupName + '/' + key ] = index;
65 this.itemHtmlQueue.push( html );
66 isNew = true;
67 } else if ( this.itemHtmlQueue[ index ] === '' ) {
68 // Previous value with this key was empty, overwrite value in queue
69 this.itemHtmlQueue[ index ] = html;
70 isNew = true;
71 }
72 return {
73 index: index,
74 isNew: isNew
75 };
76 };
77
78 /**
79 * Gets all the item's HTML strings
80 *
81 * @return {Object} Name-indexed object containing HTMLElements
82 */
83 ve.dm.InternalList.prototype.getItemHtmlQueue = function () {
84 return this.itemHtmlQueue;
85 };
86
87 /**
88 * Gets the internal list's document model
89 *
90 * @return {ve.dm.Document} Document model
91 */
92 ve.dm.InternalList.prototype.getDocument = function () {
93 return this.document;
94 };
95
96 /**
97 * Get the list node
98 *
99 * @return {ve.dm.InternalListNode} List node
100 */
101 ve.dm.InternalList.prototype.getListNode = function () {
102 // Find listNode if not set, or unattached
103 if ( !this.listNode || !this.listNode.doc ) {
104 const nodes = this.getDocument().getDocumentNode().children;
105 for ( let i = nodes.length; i >= 0; i-- ) {
106 if ( nodes[ i ] instanceof ve.dm.InternalListNode ) {
107 this.listNode = nodes[ i ];
108 break;
109 }
110 }
111 }
112 return this.listNode;
113 };
114
115 /**
116 * Get the number it internal items in the internal list.
117 *
118 * @return {number}
119 */
120 ve.dm.InternalList.prototype.getItemNodeCount = function () {
121 return this.getListNode().children.length;
122 };
123
124 /**
125 * Get the item node from a specific index.
126 *
127 * @param {number} index Item index
128 * @return {ve.dm.InternalItemNode} Item node
129 */
130 ve.dm.InternalList.prototype.getItemNode = function ( index ) {
131 return this.getListNode().children[ index ];
132 };
133
134 /**
135 * Get all node groups.
136 *
137 * @return {Object.<string,Object>} Node groups, keyed by group name
138 */
139 ve.dm.InternalList.prototype.getNodeGroups = function () {
140 return this.nodes;
141 };
142
143 /**
144 * Get the node group object for a specified group name.
145 *
146 * @param {string} groupName Name of the group
147 * @return {Object|undefined} Node group object, containing nodes and key order array
148 */
149 ve.dm.InternalList.prototype.getNodeGroup = function ( groupName ) {
150 return this.nodes[ groupName ];
151 };
152
153 /**
154 * Get a unique list key for a given group.
155 *
156 * The returned list key is added to the list of unique list keys used in this group so that it
157 * won't be allocated again. It will also be associated to oldListKey so that if the same oldListKey
158 * is passed in again later, the previously allocated name will be returned.
159 *
160 * @param {string} groupName Name of the group
161 * @param {string} oldListKey Current list key to associate the generated list key with
162 * @param {string} prefix Prefix to distinguish generated keys from non-generated ones
163 * @return {string} Generated unique list key, or existing unique key associated with oldListKey
164 */
165 ve.dm.InternalList.prototype.getUniqueListKey = function ( groupName, oldListKey, prefix ) {
166 const group = this.getNodeGroup( groupName );
167
168 if ( group.uniqueListKeys[ oldListKey ] !== undefined ) {
169 return group.uniqueListKeys[ oldListKey ];
170 }
171
172 let num = 0;
173 while ( group.keyedNodes[ prefix + num ] || group.uniqueListKeysInUse[ prefix + num ] ) {
174 num++;
175 }
176
177 group.uniqueListKeys[ oldListKey ] = prefix + num;
178 group.uniqueListKeysInUse[ prefix + num ] = true;
179 return prefix + num;
180 };
181
182 /**
183 * Get the next number in a monotonically increasing series.
184 *
185 * @return {number} One higher than the return value of the previous call, or 0 on the first call
186 */
187 ve.dm.InternalList.prototype.getNextUniqueNumber = function () {
188 const doc = this.getDocument();
189 const number = ( doc.getStorage( 'internallist-counter' ) || 0 );
190 doc.setStorage( 'internallist-counter', number + 1 );
191 return number;
192 };
193
194 /**
195 * Converts stored item HTML into linear data.
196 *
197 * Each item is an InternalItem, and they are wrapped in an InternalList.
198 * If there are no items an empty array is returned.
199 *
200 * Stored HTML is deleted after conversion.
201 *
202 * @param {ve.dm.Converter} converter
203 * @param {HTMLDocument} doc Document to create nodes in
204 * @return {Array} Linear model data
205 */
206 ve.dm.InternalList.prototype.convertToData = function ( converter, doc ) {
207 const itemHtmlQueue = this.getItemHtmlQueue();
208
209 const list = [];
210 list.push( { type: 'internalList' } );
211 for ( let i = 0, length = itemHtmlQueue.length; i < length; i++ ) {
212 if ( itemHtmlQueue[ i ] !== '' ) {
213 const div = doc.createElement( 'div' );
214 div.innerHTML = itemHtmlQueue[ i ];
215 const itemData = [].concat(
216 { type: 'internalItem' },
217 converter.getDataFromDomSubtree( div ),
218 { type: '/internalItem' }
219 );
220 if ( !converter.isFromClipboard() ) {
221 itemData[ 0 ].attributes = { originalHtml: itemHtmlQueue[ i ] };
222 }
223 ve.batchPush( list, itemData );
224 } else {
225 list.push( { type: 'internalItem' }, { type: '/internalItem' } );
226 }
227 }
228 list.push( { type: '/internalList' } );
229 // After conversion we no longer need the HTML
230 this.itemHtmlQueue = [];
231 return list;
232 };
233
234 /**
235 * Generate a transaction for inserting a new internal item node
236 *
237 * @param {string} groupName Item group
238 * @param {string} key Item key
239 * @param {Array} data Linear model data
240 * @return {Object} Object containing the transaction (or null if none required)
241 * and the new item's index within the list
242 */
243 ve.dm.InternalList.prototype.getItemInsertion = function ( groupName, key, data ) {
244 let index = this.getKeyIndex( groupName, key );
245
246 let tx;
247 if ( index === undefined ) {
248 index = this.getItemNodeCount();
249 this.keyIndexes[ groupName + '/' + key ] = index;
250
251 const itemData = [].concat( { type: 'internalItem' }, data, { type: '/internalItem' } );
252 tx = ve.dm.TransactionBuilder.static.newFromInsertion(
253 this.getDocument(),
254 this.getListNode().getRange().end,
255 itemData
256 );
257 } else {
258 tx = null;
259 }
260
261 return {
262 transaction: tx,
263 index: index
264 };
265 };
266
267 /**
268 * Get position of a key within a group
269 *
270 * @param {string} groupName Name of the group
271 * @param {string} key Name of the key
272 * @return {number} Position within the key ordering for that group
273 */
274 ve.dm.InternalList.prototype.getIndexPosition = function ( groupName, key ) {
275 return this.nodes[ groupName ].indexOrder.indexOf( key );
276 };
277
278 /**
279 * Get the internal item index of a group key if it already exists
280 *
281 * @param {string} groupName Item group
282 * @param {string} key Item name
283 * @return {number|undefined} The index of the group key, or undefined if it doesn't exist yet
284 */
285 ve.dm.InternalList.prototype.getKeyIndex = function ( groupName, key ) {
286 return this.keyIndexes[ groupName + '/' + key ];
287 };
288
289 /**
290 * Add a node.
291 *
292 * @param {string} groupName Item group
293 * @param {string} key Item name
294 * @param {number} index Item index
295 * @param {ve.dm.Node} node Item node
296 */
297 ve.dm.InternalList.prototype.addNode = function ( groupName, key, index, node ) {
298 let group = this.nodes[ groupName ];
299 // The group may not exist yet
300 if ( group === undefined ) {
301 group = this.nodes[ groupName ] = {
302 keyedNodes: {},
303 firstNodes: [],
304 indexOrder: [],
305 uniqueListKeys: {},
306 uniqueListKeysInUse: {}
307 };
308 }
309 let keyedNodes = group.keyedNodes[ key ];
310 this.keys[ index ] = key;
311 // The key may not exist yet
312 if ( keyedNodes === undefined ) {
313 keyedNodes = group.keyedNodes[ key ] = [];
314 }
315 if ( node.getDocument().buildingNodeTree ) {
316 // If the document is building the original node tree
317 // then every item is being added in order, so we don't
318 // need to worry about sorting.
319 keyedNodes.push( node );
320 if ( keyedNodes.length === 1 ) {
321 group.firstNodes[ index ] = node;
322 }
323 } else {
324 // TODO: We could use binary search insertion sort
325 const start = node.getRange().start;
326 let i, len;
327 for ( i = 0, len = keyedNodes.length; i < len; i++ ) {
328 if ( start < keyedNodes[ i ].getRange().start ) {
329 break;
330 }
331 }
332 // 'i' is now the insertion point, so add the node here
333 keyedNodes.splice( i, 0, node );
334 if ( i === 0 ) {
335 group.firstNodes[ index ] = node;
336 }
337 }
338 if ( group.indexOrder.indexOf( index ) === -1 ) {
339 group.indexOrder.push( index );
340 }
341 this.markGroupAsChanged( groupName );
342 };
343
344 /**
345 * Mark a node group as having been changed since the last transaction.
346 *
347 * @param {string} groupName Name of group which has changed
348 */
349 ve.dm.InternalList.prototype.markGroupAsChanged = function ( groupName ) {
350 if ( this.groupsChanged.indexOf( groupName ) === -1 ) {
351 this.groupsChanged.push( groupName );
352 }
353 };
354
355 /**
356 * Handle document transaction events
357 *
358 * @fires ve.dm.InternalList#update
359 */
360 ve.dm.InternalList.prototype.onTransact = function () {
361 if ( this.groupsChanged.length > 0 ) {
362 // length will almost always be 1, so probably better to not cache it
363 for ( let i = 0; i < this.groupsChanged.length; i++ ) {
364 this.sortGroupIndexes( this.nodes[ this.groupsChanged[ i ] ] );
365 }
366 this.emit( 'update', this.groupsChanged );
367 this.groupsChanged = [];
368 }
369 };
370
371 /**
372 * Remove a node.
373 *
374 * @param {string} groupName Item group
375 * @param {string} key Item name
376 * @param {number} index Item index
377 * @param {ve.dm.Node} node Item node
378 */
379 ve.dm.InternalList.prototype.removeNode = function ( groupName, key, index, node ) {
380 const group = this.nodes[ groupName ];
381 const keyedNodes = group.keyedNodes[ key ];
382 for ( let i = 0, len = keyedNodes.length; i < len; i++ ) {
383 if ( keyedNodes[ i ] === node ) {
384 keyedNodes.splice( i, 1 );
385 if ( i === 0 ) {
386 group.firstNodes[ index ] = keyedNodes[ 0 ];
387 }
388 break;
389 }
390 }
391 // If the all the items in this key have been removed
392 // then remove this index from indexOrder and firstNodes
393 if ( keyedNodes.length === 0 ) {
394 delete group.keyedNodes[ key ];
395 delete group.firstNodes[ index ];
396 const j = group.indexOrder.indexOf( index );
397 group.indexOrder.splice( j, 1 );
398 }
399 this.markGroupAsChanged( groupName );
400 };
401
402 /**
403 * Sort the indexOrder array within a group object.
404 *
405 * Items are sorted by the start offset of their firstNode, unless that node
406 * has the 'placeholder' attribute, in which case it moved to the end of the
407 * list, where it should be ignored.
408 *
409 * @param {Object} group
410 */
411 ve.dm.InternalList.prototype.sortGroupIndexes = function ( group ) {
412 // Sort indexOrder
413 group.indexOrder.sort( ( index1, index2 ) => {
414 // Sometimes there is no node at the time of sorting (T350902) so move these to the end to be ignored
415 if ( !group.firstNodes[ index1 ] ) {
416 return !group.firstNodes[ index2 ] ? 0 : 1;
417 }
418 // Sort placeholder nodes to the end, so they don't interfere with numbering
419 if ( group.firstNodes[ index1 ].getAttribute( 'placeholder' ) ) {
420 return group.firstNodes[ index2 ].getAttribute( 'placeholder' ) ? 0 : 1;
421 }
422 return group.firstNodes[ index1 ].getRange().start - group.firstNodes[ index2 ].getRange().start;
423 } );
424 };
425
426 /**
427 * Clone this internal list.
428 *
429 * @param {ve.dm.Document} [doc] The new list's document. Defaults to this list's document.
430 * @return {ve.dm.InternalList} Clone of this internal
431 */
432 ve.dm.InternalList.prototype.clone = function ( doc ) {
433 const clone = new this.constructor( doc || this.getDocument() );
434 // Most properties don't need to be copied, because addNode() will be invoked when the new
435 // document tree is built. But some do need copying:
436 clone.itemHtmlQueue = ve.copy( this.itemHtmlQueue );
437 return clone;
438 };
439
440 /**
441 * Merge another internal list into this one.
442 *
443 * This function updates the state of this list, and returns a mapping from indexes in list to
444 * indexes in this, as well as a set of ranges that should be copied from list's linear model
445 * into this list's linear model by the caller.
446 *
447 * @param {ve.dm.InternalList} list Internal list to merge into this list
448 * @param {number} commonLength The number of elements, counted from the beginning, that the lists have in common
449 * @return {Object} 'mapping' is an object mapping indexes in list to indexes in this; newItemRanges is an array
450 * of ranges of internal nodes in list's document that should be copied into our document
451 */
452 ve.dm.InternalList.prototype.merge = function ( list, commonLength ) {
453 const listLen = list.getItemNodeCount(),
454 newItemRanges = [],
455 mapping = {};
456 let nextIndex = this.getItemNodeCount();
457
458 for ( let i = 0; i < commonLength; i++ ) {
459 mapping[ i ] = i;
460 }
461 for ( let i = commonLength; i < listLen; i++ ) {
462 // Try to find i in list.keyIndexes
463 let key = null;
464 for ( const k in list.keyIndexes ) {
465 if ( list.keyIndexes[ k ] === i ) {
466 key = k;
467 break;
468 }
469 }
470
471 if ( this.keyIndexes[ key ] !== undefined ) {
472 // We already have this key in this internal list. Ignore the duplicate that the other
473 // list is trying to merge in.
474 // NOTE: This case cannot occur in VE currently, but may be possible in the future with
475 // collaborative editing, which is why this code needs to be rewritten before we do
476 // collaborative editing.
477 mapping[ i ] = this.keyIndexes[ key ];
478 } else {
479 mapping[ i ] = nextIndex;
480 if ( key !== null ) {
481 this.keyIndexes[ key ] = nextIndex;
482 }
483 nextIndex++;
484 newItemRanges.push( list.getItemNode( i ).getOuterRange() );
485 }
486 }
487 return {
488 mapping: mapping,
489 newItemRanges: newItemRanges
490 };
491 };