Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor ModelRegistry class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6 ( function () {
7
8 /**
9 * Registry for models.
10 *
11 * To register a new model type, call #register.
12 *
13 * @extends OO.Registry
14 * @constructor
15 */
16 ve.dm.ModelRegistry = function VeDmModelRegistry() {
17 // Parent constructor
18 OO.Registry.call( this );
19 // Map of func presence and tag names to model names
20 // [ { tagName: [modelNamesWithoutFunc] }, { tagName: [modelNamesWithFunc] } ]
21 this.modelsByTag = [ {}, {} ];
22 // Map of func presence and rdfaTypes to model names; only rdfaTypes specified as strings are in here
23 // { matchFunctionPresence: { rdfaType: { tagName: [modelNames] } } }
24 // [ { rdfaType: { tagName: [modelNamesWithoutFunc] } }, { rdfaType: { tagName: [modelNamesWithFunc] } ]
25 this.modelsByTypeAndTag = [];
26 // Map of func presence to array of model names with rdfaType regexps
27 // [ [modelNamesWithoutFunc], [modelNamesWithFunc] ]
28 this.modelsWithTypeRegExps = [ [], [] ];
29 // Map tracking registration order
30 // { nameA: 0, nameB: 1, … }
31 this.registrationOrder = {};
32 this.nextNumber = 0;
33 this.extSpecificTypes = [];
34 };
35
36 /* Inheritance */
37
38 OO.inheritClass( ve.dm.ModelRegistry, OO.Registry );
39
40 /* Private helper functions */
41
42 /**
43 * Helper function for register(). Adds a value to the front of an array in a nested object.
44 * Objects and arrays are created if needed. You can specify one or more keys and a value.
45 *
46 * Specifically:
47 *
48 * - `addType( obj, keyA, value )` does `obj[keyA].unshift( value );`
49 * - `addType( obj, keyA, keyB, value )` does `obj[keyA][keyB].unshift( value )`;
50 * - etc.
51 *
52 * @private
53 * @param {Object} obj Object the array resides in
54 * @param {...string} keys
55 * @param {any} value
56 */
57 function addType( obj, ...keys ) {
58 const value = keys.pop();
59 let o = obj;
60
61 let i, len;
62 for ( i = 0, len = keys.length - 1; i < len; i++ ) {
63 if ( o[ keys[ i ] ] === undefined ) {
64 o[ keys[ i ] ] = {};
65 }
66 o = o[ keys[ i ] ];
67 }
68 o[ keys[ i ] ] = o[ keys[ i ] ] || [];
69 o[ keys[ i ] ].unshift( value );
70 }
71
72 /**
73 * Helper function for unregister().
74 *
75 * Same arguments as addType, except removes the type from the list.
76 *
77 * @private
78 * @param {Object} obj Object the array resides in
79 * @param {...string} keys
80 * @param {any} value to remove
81 */
82 function removeType( obj, ...keys ) {
83 const value = keys.pop(),
84 arr = ve.getProp( obj, ...keys );
85
86 if ( arr ) {
87 const index = arr.indexOf( value );
88 if ( index !== -1 ) {
89 arr.splice( index, 1 );
90 }
91 // TODO: Prune empty array and empty containing objects
92 }
93 }
94
95 /* Public methods */
96
97 /**
98 * Register a model type.
99 *
100 * @param {ve.dm.Model} constructor Subclass of ve.dm.Model
101 * @throws Model names must be strings and must not be empty
102 * @throws Models must be subclasses of ve.dm.Model
103 * @throws No factory associated with this ve.dm.Model subclass
104 */
105 ve.dm.ModelRegistry.prototype.register = function ( constructor ) {
106 const name = constructor.static && constructor.static.name;
107
108 if ( typeof name !== 'string' || name === '' ) {
109 throw new Error( 'Model names must be strings and must not be empty' );
110 }
111 if ( !( constructor.prototype instanceof ve.dm.Model ) ) {
112 throw new Error( 'Models must be subclasses of ve.dm.Model' );
113 }
114 if ( this.lookup( name ) === constructor ) {
115 // Don't allow double registration as it would create duplicate
116 // entries in various caches.
117 return;
118 }
119
120 // Register the model with the right factory
121 if ( constructor.prototype instanceof ve.dm.Annotation ) {
122 ve.dm.annotationFactory.register( constructor );
123 } else if ( constructor.prototype instanceof ve.dm.Node ) {
124 ve.dm.nodeFactory.register( constructor );
125 } else {
126 throw new Error( 'No factory associated with this ve.dm.Model subclass' );
127 }
128
129 // Parent method
130 ve.dm.ModelRegistry.super.prototype.register.call( this, name, constructor );
131
132 const tags = constructor.static.matchTagNames === null ?
133 [ '' ] :
134 constructor.static.matchTagNames;
135 const types = constructor.static.getMatchRdfaTypes() === null ?
136 [ '' ] :
137 constructor.static.getMatchRdfaTypes();
138
139 for ( let i = 0; i < tags.length; i++ ) {
140 // +!!foo is a shorter equivalent of Number( Boolean( foo ) ) or foo ? 1 : 0
141 addType( this.modelsByTag, +!!constructor.static.matchFunction,
142 tags[ i ], name
143 );
144 }
145 for ( let i = 0; i < types.length; i++ ) {
146 if ( types[ i ] instanceof RegExp ) {
147 // TODO: Guard against running this again during subsequent
148 // iterations of the for loop
149 addType( this.modelsWithTypeRegExps, +!!constructor.static.matchFunction, name );
150 } else {
151 for ( let j = 0; j < tags.length; j++ ) {
152 addType( this.modelsByTypeAndTag,
153 +!!constructor.static.matchFunction, types[ i ], tags[ j ], name
154 );
155 }
156 }
157 }
158
159 this.registrationOrder[ name ] = this.nextNumber++;
160 };
161
162 /**
163 * Unregister a model type.
164 *
165 * @param {ve.dm.Model} constructor Subclass of ve.dm.Model
166 * @throws Model names must be strings and must not be empty
167 * @throws Models must be subclasses of ve.dm.Model
168 * @throws No factory associated with this ve.dm.Model subclass
169 */
170 ve.dm.ModelRegistry.prototype.unregister = function ( constructor ) {
171 const name = constructor.static && constructor.static.name;
172
173 if ( typeof name !== 'string' || name === '' ) {
174 throw new Error( 'Model names must be strings and must not be empty' );
175 }
176 if ( !( constructor.prototype instanceof ve.dm.Model ) ) {
177 throw new Error( 'Models must be subclasses of ve.dm.Model' );
178 }
179
180 // Unregister the model from the right factory
181 if ( constructor.prototype instanceof ve.dm.Annotation ) {
182 ve.dm.annotationFactory.unregister( constructor );
183 } else if ( constructor.prototype instanceof ve.dm.Node ) {
184 ve.dm.nodeFactory.unregister( constructor );
185 } else {
186 throw new Error( 'No factory associated with this ve.dm.Model subclass' );
187 }
188
189 // Parent method
190 ve.dm.ModelRegistry.super.prototype.unregister.call( this, name );
191
192 const tags = constructor.static.matchTagNames === null ?
193 [ '' ] :
194 constructor.static.matchTagNames;
195 const types = constructor.static.getMatchRdfaTypes() === null ?
196 [ '' ] :
197 constructor.static.getMatchRdfaTypes();
198
199 for ( let i = 0; i < tags.length; i++ ) {
200 // +!!foo is a shorter equivalent of Number( Boolean( foo ) ) or foo ? 1 : 0
201 removeType( this.modelsByTag, +!!constructor.static.matchFunction,
202 tags[ i ], name
203 );
204 }
205 for ( let i = 0; i < types.length; i++ ) {
206 if ( types[ i ] instanceof RegExp ) {
207 // TODO: Guard against running this again during subsequent
208 // iterations of the for loop
209 removeType( this.modelsWithTypeRegExps, +!!constructor.static.matchFunction, name );
210 } else {
211 for ( let j = 0; j < tags.length; j++ ) {
212 removeType( this.modelsByTypeAndTag,
213 +!!constructor.static.matchFunction, types[ i ], tags[ j ], name
214 );
215 }
216 }
217 }
218
219 delete this.registrationOrder[ name ];
220 };
221
222 /**
223 * Determine which model best matches the given node
224 *
225 * Model matching works as follows:
226 *
227 * Get all models whose tag and rdfaType rules match
228 *
229 * Rank them in order of specificity:
230 *
231 * - tag, rdfaType and func specified
232 * - rdfaType and func specified
233 * - tag and func specified
234 * - func specified
235 * - tag and rdfaType specified
236 * - rdfaType specified
237 * - tag specified
238 * - nothing specified
239 *
240 * If there are multiple candidates with the same specificity, exact matches of strings take precedence over
241 * matches of regular expressions. If there are still multiple candidates, they are ranked in reverse
242 * order of registration (i.e. if A was registered before B, B will rank above A).
243 * The highest-ranking model whose test function does not return false, wins.
244 *
245 * @param {Node} node Node to match (usually an HTMLElement but can also be a Comment node)
246 * @param {boolean} [forceAboutGrouping] If true, only match models with about grouping enabled
247 * @param {string[]} [excludeTypes] Model names to exclude when matching
248 * @return {string|null} Model type, or null if none found
249 */
250 ve.dm.ModelRegistry.prototype.matchElement = function ( node, forceAboutGrouping, excludeTypes ) {
251 const nodeName = node.nodeName.toLowerCase();
252 const types = [];
253
254 const byRegistrationOrderDesc = ( a, b ) => this.registrationOrder[ b ] - this.registrationOrder[ a ];
255
256 const matchTypeRegExps = ( type, tag, withFunc ) => {
257 const matchedModels = [],
258 models = this.modelsWithTypeRegExps[ +withFunc ];
259 for ( let j = 0; j < models.length; j++ ) {
260 if ( excludeTypes && excludeTypes.indexOf( models[ j ] ) !== -1 ) {
261 continue;
262 }
263 const matchTypes = this.registry[ models[ j ] ].static.getMatchRdfaTypes();
264 for ( let k = 0; k < matchTypes.length; k++ ) {
265 if (
266 matchTypes[ k ] instanceof RegExp &&
267 matchTypes[ k ].test( type ) &&
268 (
269 ( tag === '' && this.registry[ models[ j ] ].static.matchTagNames === null ) ||
270 ( this.registry[ models[ j ] ].static.matchTagNames || [] ).indexOf( tag ) !== -1
271 )
272 ) {
273 matchedModels.push( models[ j ] );
274 }
275 }
276 }
277 return matchedModels;
278 };
279
280 const allTypesAllowed = ( model ) => {
281 let allowedTypes = model.static.getAllowedRdfaTypes();
282 const matchTypes = model.static.getMatchRdfaTypes();
283
284 // All types allowed
285 if ( allowedTypes === null ) {
286 return true;
287 }
288
289 if ( matchTypes !== null ) {
290 // Don't modify allowedTypes as it is a pointer to the orignal array
291 allowedTypes = allowedTypes.concat( matchTypes );
292 }
293
294 function checkType( rule, type ) {
295 return rule instanceof RegExp ? rule.test( type ) : rule === type;
296 }
297
298 for ( let j = 0; j < types.length; j++ ) {
299 let typeAllowed = false;
300 for ( let k = 0; k < allowedTypes.length; k++ ) {
301 if ( checkType( allowedTypes[ k ], types[ j ] ) ) {
302 typeAllowed = true;
303 break;
304 }
305 }
306 if ( !typeAllowed ) {
307 return false;
308 }
309 }
310 return true;
311 };
312
313 const matchWithFunc = ( tag ) => {
314 let queue = [],
315 queue2 = [];
316 for ( let j = 0; j < types.length; j++ ) {
317 // Queue string matches and regexp matches separately
318 ve.batchPush( queue, ve.getProp( this.modelsByTypeAndTag, 1, types[ j ], tag ) || [] );
319 if ( excludeTypes ) {
320 queue = OO.simpleArrayDifference( queue, excludeTypes );
321 }
322 ve.batchPush( queue2, matchTypeRegExps( types[ j ], tag, true ) );
323 }
324 // Filter out matches which contain types which aren't allowed
325 queue = queue.filter( ( name ) => allTypesAllowed( this.lookup( name ) ) );
326 queue2 = queue2.filter( ( name ) => allTypesAllowed( this.lookup( name ) ) );
327 if ( forceAboutGrouping ) {
328 // Filter out matches that don't support about grouping
329 queue = queue.filter( ( name ) => this.registry[ name ].static.enableAboutGrouping );
330 queue2 = queue2.filter( ( name ) => this.registry[ name ].static.enableAboutGrouping );
331 }
332 // Try string matches first, then regexp matches
333 queue.sort( byRegistrationOrderDesc );
334 queue2.sort( byRegistrationOrderDesc );
335 ve.batchPush( queue, queue2 );
336 for ( let j = 0; j < queue.length; j++ ) {
337 if ( this.registry[ queue[ j ] ].static.matchFunction( node ) ) {
338 return queue[ j ];
339 }
340 }
341 return null;
342 };
343
344 const matchWithoutFunc = ( tag ) => {
345 let queue = [],
346 queue2 = [],
347 winningName = null;
348 for ( let j = 0; j < types.length; j++ ) {
349 // Queue string and regexp matches separately
350 ve.batchPush( queue, ve.getProp( this.modelsByTypeAndTag, 0, types[ j ], tag ) || [] );
351 if ( excludeTypes ) {
352 queue = OO.simpleArrayDifference( queue, excludeTypes );
353 }
354 ve.batchPush( queue2, matchTypeRegExps( types[ j ], tag, false ) );
355 }
356 // Filter out matches which contain types which aren't allowed
357 queue = queue.filter( ( name ) => allTypesAllowed( this.lookup( name ) ) );
358 queue2 = queue2.filter( ( name ) => allTypesAllowed( this.lookup( name ) ) );
359 if ( forceAboutGrouping ) {
360 // Filter out matches that don't support about grouping
361 queue = queue.filter( ( name ) => this.registry[ name ].static.enableAboutGrouping );
362 queue2 = queue2.filter( ( name ) => this.registry[ name ].static.enableAboutGrouping );
363 }
364 // Only try regexp matches if there are no string matches
365 queue = queue.length > 0 ? queue : queue2;
366 // Find most recently registered
367 for ( let j = 0; j < queue.length; j++ ) {
368 if (
369 winningName === null ||
370 this.registrationOrder[ winningName ] < this.registrationOrder[ queue[ j ] ]
371 ) {
372 winningName = queue[ j ];
373 }
374 }
375 return winningName;
376 };
377
378 if ( node.getAttribute ) {
379 if ( node.getAttribute( 'rel' ) ) {
380 types.push( ...node.getAttribute( 'rel' ).trim().split( /\s+/ ) );
381 }
382 if ( node.getAttribute( 'typeof' ) ) {
383 types.push( ...node.getAttribute( 'typeof' ).trim().split( /\s+/ ) );
384 }
385 if ( node.getAttribute( 'property' ) ) {
386 types.push( ...node.getAttribute( 'property' ).trim().split( /\s+/ ) );
387 }
388 }
389
390 let winner;
391 if ( types.length ) {
392 // func+tag+type match
393 winner = matchWithFunc( nodeName );
394 if ( winner !== null ) {
395 return winner;
396 }
397
398 // func+type match
399 // Only look at rules with no tag specified; if a rule does specify a tag, we've
400 // either already processed it above, or the tag doesn't match
401 winner = matchWithFunc( '' );
402 if ( winner !== null ) {
403 return winner;
404 }
405 }
406
407 // func+tag match
408 let matches = ve.getProp( this.modelsByTag, 1, nodeName ) || [];
409 // No need to sort because individual arrays in modelsByTag are already sorted
410 // correctly
411 for ( let i = 0; i < matches.length; i++ ) {
412 const m = this.registry[ matches[ i ] ];
413 // Only process this one if it doesn't specify types
414 // If it does specify types, then we've either already processed it in the
415 // func+tag+type step above, or its type rule doesn't match
416 if ( m.static.getMatchRdfaTypes() === null && m.static.matchFunction( node ) && allTypesAllowed( m ) ) {
417 return matches[ i ];
418 }
419 }
420
421 // func only
422 // We only need to get the [''][''] array because the other arrays were either
423 // already processed during the steps above, or have a type or tag rule that doesn't
424 // match this node.
425 // No need to sort because individual arrays in modelsByTypeAndTag are already sorted
426 // correctly
427 matches = ve.getProp( this.modelsByTypeAndTag, 1, '', '' ) || [];
428 for ( let i = 0; i < matches.length; i++ ) {
429 const m = this.registry[ matches[ i ] ];
430 if ( m.static.matchFunction( node ) && allTypesAllowed( m ) ) {
431 return matches[ i ];
432 }
433 }
434
435 // tag+type
436 winner = matchWithoutFunc( nodeName );
437 if ( winner !== null ) {
438 return winner;
439 }
440
441 // type only
442 // Only look at rules with no tag specified; if a rule does specify a tag, we've
443 // either already processed it above, or the tag doesn't match
444 winner = matchWithoutFunc( '' );
445 if ( winner !== null ) {
446 return winner;
447 }
448
449 // tag only
450 matches = ve.getProp( this.modelsByTag, 0, nodeName ) || [];
451 // No need to track winningName because the individual arrays in modelsByTag are
452 // already sorted correctly
453 for ( let i = 0; i < matches.length; i++ ) {
454 const m = this.registry[ matches[ i ] ];
455 // Only process this one if it doesn't specify types
456 // If it does specify types, then we've either already processed it in the
457 // tag+type step above, or its type rule doesn't match
458 if ( m.static.getMatchRdfaTypes() === null && allTypesAllowed( m ) ) {
459 return matches[ i ];
460 }
461 }
462
463 // Rules with no type or tag specified
464 // These are the only rules that can still qualify at this point, the others we've either
465 // already processed or have a type or tag rule that disqualifies them
466 matches = ve.getProp( this.modelsByTypeAndTag, 0, '', '' ) || [];
467 for ( let i = 0; i < matches.length; i++ ) {
468 const m = this.registry[ matches[ i ] ];
469 if ( allTypesAllowed( m ) ) {
470 return matches[ i ];
471 }
472 }
473
474 // We didn't find anything, give up
475 return null;
476 };
477
478 /**
479 * Tests whether a node will be modelled as an annotation
480 *
481 * @param {Node} node The node
482 * @return {boolean} Whether the element will be modelled as an annotation
483 */
484 ve.dm.ModelRegistry.prototype.isAnnotation = function ( node ) {
485 const modelClass = this.lookup( this.matchElement( node ) );
486 return ( modelClass && modelClass.prototype ) instanceof ve.dm.Annotation;
487 };
488
489 /* Initialization */
490
491 ve.dm.modelRegistry = new ve.dm.ModelRegistry();
492
493 }() );