Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/ve.ui.ModeledFactory.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface ModeledFactory class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Mixin for factories whose items associate with specific models.
9 *
10 * Classes registered with the factory should have a static method named `isCompatibleWith` that
11 * accepts a model and returns a boolean.
12 *
13 * TODO: Create an abstract mixin that specifies which properties a "model" should have
14 *
15 * @class
16 *
17 * @constructor
18 */
19 ve.ui.ModeledFactory = function VeUiModeledFactory() {};
20
21 /* Inheritance */
22
23 OO.initClass( ve.ui.ModeledFactory );
24
25 /* Methods */
26
27 /**
28 * Get a list of symbolic names for classes related to a list of models.
29 *
30 * The lowest compatible item in each inheritance chain will be used.
31 *
32 * Additionally if the model has other model names listed in a static.suppresses
33 * property, those will be hidden when that model is compatible.
34 *
35 * @param {Object[]} models Models to find relationships with
36 * @return {Object[]} List of objects containing `name` and `model` properties, representing
37 * each compatible class's symbolic name and the model it is compatible with
38 */
39 ve.ui.ModeledFactory.prototype.getRelatedItems = function ( models ) {
40 const registry = this.registry;
41
42 /**
43 * Collect the most specific compatible classes for a model.
44 *
45 * @private
46 * @param {Object} m Model to find compatibility with
47 * @return {Function[]} List of compatible classes
48 */
49 function collect( m ) {
50 const candidates = [];
51
52 for ( const n in registry ) {
53 const candidate = registry[ n ];
54 if ( candidate.static.isCompatibleWith( m ) ) {
55 let add = true;
56 for ( let k = 0, kLen = candidates.length; k < kLen; k++ ) {
57 if (
58 candidate.prototype instanceof candidates[ k ] ||
59 ( candidate.static.suppresses && candidate.static.suppresses.indexOf( candidates[ k ].static.name ) !== -1 )
60 ) {
61 candidates.splice( k, 1, candidate );
62 add = false;
63 break;
64 } else if (
65 candidates[ k ].prototype instanceof candidate ||
66 ( candidates[ k ].static.suppresses && candidates[ k ].static.suppresses.indexOf( candidate.static.name ) !== -1 )
67 ) {
68 add = false;
69 break;
70 }
71 }
72 if ( add ) {
73 candidates.push( candidate );
74 }
75 }
76 }
77
78 return candidates;
79 }
80
81 const names = {};
82 const matches = [];
83 // Collect compatible classes and the models they are specifically compatible with,
84 // discarding class's with duplicate symbolic names
85 for ( let i = 0, iLen = models.length; i < iLen; i++ ) {
86 const model = models[ i ];
87 const classes = collect( model );
88 for ( let j = 0, jLen = classes.length; j < jLen; j++ ) {
89 const name = classes[ j ].static.name;
90 if ( !names[ name ] ) {
91 matches.push( { name: name, model: model } );
92 }
93 names[ name ] = true;
94 }
95 }
96
97 return matches;
98 };