Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel MetaList class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel meta list.
9 *
10 * @class
11 * @mixes OO.EventEmitter
12 *
13 * @constructor
14 * @param {ve.dm.Document} doc Document model
15 */
16 ve.dm.MetaList = function VeDmMetaList( doc ) {
17 // Mixin constructors
18 OO.EventEmitter.call( this );
19
20 this.doc = doc;
21
22 // Sorted array of attached ve.dm.MetaItem nodes in document order
23 this.items = [];
24
25 // The meta list is constructed before the model tree is built, so
26 // we don't need to initialise this item list, just listen to changes
27 this.doc.connect( this, {
28 nodeAttached: 'onNodeAttached',
29 nodeDetached: 'onNodeDetached'
30 } );
31 };
32
33 /* Inheritance */
34
35 OO.mixinClass( ve.dm.MetaList, OO.EventEmitter );
36
37 /* Events */
38
39 /**
40 * @event ve.dm.MetaList#insert
41 * @param {ve.dm.MetaItem} item Item that was inserted
42 */
43
44 /**
45 * @event ve.dm.MetaList#remove
46 * @param {ve.dm.MetaItem} item Item that was removed
47 */
48
49 /* Methods */
50
51 /**
52 * If a ve.dm.MetaItem was attached, insert it into items in document order
53 *
54 * @param {ve.dm.Node} node The node that was attached
55 */
56 ve.dm.MetaList.prototype.onNodeAttached = function ( node ) {
57 const offsetPath = node.getOffsetPath();
58 if ( node instanceof ve.dm.MetaItem ) {
59 const i = OO.binarySearch( this.items, ( other ) => ve.compareTuples( offsetPath, other.getOffsetPath() ), true );
60 this.items.splice( i, 0, node );
61 this.emit( 'insert', node );
62 }
63 };
64
65 /**
66 * If a ve.dm.MetaItem was detached, remove it from items
67 *
68 * @param {ve.dm.Node} node The node that was detached
69 */
70 ve.dm.MetaList.prototype.onNodeDetached = function ( node ) {
71 if ( node instanceof ve.dm.MetaItem ) {
72 const i = this.items.indexOf( node );
73 if ( i !== -1 ) {
74 this.items.splice( i, 1 );
75 this.emit( 'remove', node );
76 }
77 }
78 };
79
80 ve.dm.MetaList.prototype.indexOf = function ( item, group ) {
81 const items = group ? this.getItemsInGroup( group ) : this.items;
82 return items.indexOf( item );
83 };
84
85 /**
86 * Get all items in a group.
87 *
88 * This function returns a shallow copy, so the array isn't returned by reference but the items
89 * themselves are.
90 *
91 * @param {string} group
92 * @return {ve.dm.MetaItem[]} Array of items in the group (shallow copy)
93 */
94 ve.dm.MetaList.prototype.getItemsInGroup = function ( group ) {
95 return this.items.filter( ( item ) => item.getGroup() === group );
96 };
97
98 /**
99 * Get all items in the list.
100 *
101 * This function returns a shallow copy, so the array isn't returned by reference but the items
102 * themselves are.
103 *
104 * @return {ve.dm.MetaItem[]} Array of items in the list
105 */
106 ve.dm.MetaList.prototype.getItems = function () {
107 return this.items.slice();
108 };