| 1 | /*! |
| 2 | * OOjs v7.0.1 |
| 3 | * https://www.mediawiki.org/wiki/OOjs |
| 4 | * |
| 5 | * Copyright 2011-2023 OOjs Team and other contributors. |
| 6 | * Released under the MIT license |
| 7 | * https://oojs.mit-license.org |
| 8 | */ |
| 9 | ( function ( global ) { |
| 10 | |
| 11 | 'use strict'; |
| 12 | |
| 13 | /* exported slice, toString */ |
| 14 | /** |
| 15 | * Namespace for all classes, static methods and static properties. |
| 16 | * |
| 17 | * @namespace OO |
| 18 | */ |
| 19 | var |
| 20 | // eslint-disable-next-line no-redeclare |
| 21 | OO = {}, |
| 22 | // Optimisation: Local reference to methods from a global prototype |
| 23 | hasOwn = OO.hasOwnProperty, |
| 24 | slice = Array.prototype.slice, |
| 25 | // eslint-disable-next-line no-redeclare |
| 26 | toString = OO.toString; |
| 27 | |
| 28 | /* Class Methods */ |
| 29 | |
| 30 | /** |
| 31 | * Utility to initialize a class for OO inheritance. |
| 32 | * |
| 33 | * Currently this just initializes an empty static object. |
| 34 | * |
| 35 | * @memberof OO |
| 36 | * @method initClass |
| 37 | * @param {Function} fn |
| 38 | */ |
| 39 | OO.initClass = function ( fn ) { |
| 40 | fn.static = fn.static || {}; |
| 41 | }; |
| 42 | |
| 43 | /** |
| 44 | * Inherit from prototype to another using Object#create. |
| 45 | * |
| 46 | * Beware: This redefines the prototype, call before setting your prototypes. |
| 47 | * |
| 48 | * Beware: This redefines the prototype, can only be called once on a function. |
| 49 | * If called multiple times on the same function, the previous prototype is lost. |
| 50 | * This is how prototypal inheritance works, it can only be one straight chain |
| 51 | * (just like classical inheritance in PHP for example). If you need to work with |
| 52 | * multiple constructors consider storing an instance of the other constructor in a |
| 53 | * property instead, or perhaps use a mixin (see OO.mixinClass). |
| 54 | * |
| 55 | * function Thing() {} |
| 56 | * Thing.prototype.exists = function () {}; |
| 57 | * |
| 58 | * function Person() { |
| 59 | * Person.super.apply( this, arguments ); |
| 60 | * } |
| 61 | * OO.inheritClass( Person, Thing ); |
| 62 | * Person.static.defaultEyeCount = 2; |
| 63 | * Person.prototype.walk = function () {}; |
| 64 | * |
| 65 | * function Jumper() { |
| 66 | * Jumper.super.apply( this, arguments ); |
| 67 | * } |
| 68 | * OO.inheritClass( Jumper, Person ); |
| 69 | * Jumper.prototype.jump = function () {}; |
| 70 | * |
| 71 | * Jumper.static.defaultEyeCount === 2; |
| 72 | * var x = new Jumper(); |
| 73 | * x.jump(); |
| 74 | * x.walk(); |
| 75 | * x instanceof Thing && x instanceof Person && x instanceof Jumper; |
| 76 | * |
| 77 | * @memberof OO |
| 78 | * @method inheritClass |
| 79 | * @param {Function} targetFn |
| 80 | * @param {Function} originFn |
| 81 | * @throws {Error} If target already inherits from origin |
| 82 | */ |
| 83 | OO.inheritClass = function ( targetFn, originFn ) { |
| 84 | if ( !originFn ) { |
| 85 | throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn + ')' ); |
| 86 | } |
| 87 | if ( targetFn.prototype instanceof originFn ) { |
| 88 | throw new Error( 'inheritClass: Target already inherits from origin' ); |
| 89 | } |
| 90 | |
| 91 | var targetConstructor = targetFn.prototype.constructor; |
| 92 | |
| 93 | // [DEPRECATED] Provide .parent as alias for code supporting older browsers which |
| 94 | // allows people to comply with their style guide. |
| 95 | targetFn.super = targetFn.parent = originFn; |
| 96 | |
| 97 | targetFn.prototype = Object.create( originFn.prototype, { |
| 98 | // Restore constructor property of targetFn |
| 99 | constructor: { |
| 100 | value: targetConstructor, |
| 101 | enumerable: false, |
| 102 | writable: true, |
| 103 | configurable: true |
| 104 | } |
| 105 | } ); |
| 106 | |
| 107 | // Extend static properties - always initialize both sides |
| 108 | OO.initClass( originFn ); |
| 109 | targetFn.static = Object.create( originFn.static ); |
| 110 | }; |
| 111 | |
| 112 | /** |
| 113 | * Copy over *own* prototype properties of a mixin. |
| 114 | * |
| 115 | * The 'constructor' (whether implicit or explicit) is not copied over. |
| 116 | * |
| 117 | * This does not create inheritance to the origin. If you need inheritance, |
| 118 | * use OO.inheritClass instead. |
| 119 | * |
| 120 | * Beware: This can redefine a prototype property, call before setting your prototypes. |
| 121 | * |
| 122 | * Beware: Don't call before OO.inheritClass. |
| 123 | * |
| 124 | * function Foo() {} |
| 125 | * function Context() {} |
| 126 | * |
| 127 | * // Avoid repeating this code |
| 128 | * function ContextLazyLoad() {} |
| 129 | * ContextLazyLoad.prototype.getContext = function () { |
| 130 | * if ( !this.context ) { |
| 131 | * this.context = new Context(); |
| 132 | * } |
| 133 | * return this.context; |
| 134 | * }; |
| 135 | * |
| 136 | * function FooBar() {} |
| 137 | * OO.inheritClass( FooBar, Foo ); |
| 138 | * OO.mixinClass( FooBar, ContextLazyLoad ); |
| 139 | * |
| 140 | * @memberof OO |
| 141 | * @method mixinClass |
| 142 | * @param {Function} targetFn |
| 143 | * @param {Function} originFn |
| 144 | */ |
| 145 | OO.mixinClass = function ( targetFn, originFn ) { |
| 146 | if ( !originFn ) { |
| 147 | throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn + ')' ); |
| 148 | } |
| 149 | |
| 150 | var key; |
| 151 | // Copy prototype properties |
| 152 | for ( key in originFn.prototype ) { |
| 153 | if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) { |
| 154 | targetFn.prototype[ key ] = originFn.prototype[ key ]; |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // Copy static properties - always initialize both sides |
| 159 | OO.initClass( targetFn ); |
| 160 | if ( originFn.static ) { |
| 161 | for ( key in originFn.static ) { |
| 162 | if ( hasOwn.call( originFn.static, key ) ) { |
| 163 | targetFn.static[ key ] = originFn.static[ key ]; |
| 164 | } |
| 165 | } |
| 166 | } else { |
| 167 | OO.initClass( originFn ); |
| 168 | } |
| 169 | }; |
| 170 | |
| 171 | /** |
| 172 | * Test whether one class is a subclass of another, without instantiating it. |
| 173 | * |
| 174 | * Every class is considered a subclass of Object and of itself. |
| 175 | * |
| 176 | * @memberof OO |
| 177 | * @method isSubClass |
| 178 | * @param {Function} testFn The class to be tested |
| 179 | * @param {Function} baseFn The base class |
| 180 | * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it) |
| 181 | */ |
| 182 | OO.isSubclass = function ( testFn, baseFn ) { |
| 183 | return testFn === baseFn || testFn.prototype instanceof baseFn; |
| 184 | }; |
| 185 | |
| 186 | /* Object Methods */ |
| 187 | |
| 188 | /** |
| 189 | * Get a deeply nested property of an object using variadic arguments, protecting against |
| 190 | * undefined property errors. |
| 191 | * |
| 192 | * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;` |
| 193 | * except that the former protects against JS errors if one of the intermediate properties |
| 194 | * is undefined. Instead of throwing an error, this function will return undefined in |
| 195 | * that case. |
| 196 | * |
| 197 | * @memberof OO |
| 198 | * @method getProp |
| 199 | * @param {Object} obj |
| 200 | * @param {...any} [keys] |
| 201 | * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined |
| 202 | */ |
| 203 | OO.getProp = function ( obj ) { |
| 204 | var retval = obj; |
| 205 | for ( var i = 1; i < arguments.length; i++ ) { |
| 206 | if ( retval === undefined || retval === null ) { |
| 207 | // Trying to access a property of undefined or null causes an error |
| 208 | return undefined; |
| 209 | } |
| 210 | retval = retval[ arguments[ i ] ]; |
| 211 | } |
| 212 | return retval; |
| 213 | }; |
| 214 | |
| 215 | /** |
| 216 | * Set a deeply nested property of an object using variadic arguments, protecting against |
| 217 | * undefined property errors. |
| 218 | * |
| 219 | * `OO.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that |
| 220 | * the former protects against JS errors if one of the intermediate properties is |
| 221 | * undefined. Instead of throwing an error, undefined intermediate properties will be |
| 222 | * initialized to an empty object. If an intermediate property is not an object, or if obj itself |
| 223 | * is not an object, this function will silently abort. |
| 224 | * |
| 225 | * @memberof OO |
| 226 | * @method setProp |
| 227 | * @param {Object} obj |
| 228 | * @param {...any} [keys] |
| 229 | * @param {any} [value] |
| 230 | */ |
| 231 | OO.setProp = function ( obj ) { |
| 232 | if ( Object( obj ) !== obj || arguments.length < 2 ) { |
| 233 | return; |
| 234 | } |
| 235 | var prop = obj; |
| 236 | for ( var i = 1; i < arguments.length - 2; i++ ) { |
| 237 | if ( prop[ arguments[ i ] ] === undefined ) { |
| 238 | prop[ arguments[ i ] ] = {}; |
| 239 | } |
| 240 | if ( Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) { |
| 241 | return; |
| 242 | } |
| 243 | prop = prop[ arguments[ i ] ]; |
| 244 | } |
| 245 | prop[ arguments[ arguments.length - 2 ] ] = arguments[ arguments.length - 1 ]; |
| 246 | }; |
| 247 | |
| 248 | /** |
| 249 | * Delete a deeply nested property of an object using variadic arguments, protecting against |
| 250 | * undefined property errors, and deleting resulting empty objects. |
| 251 | * |
| 252 | * @memberof OO |
| 253 | * @method deleteProp |
| 254 | * @param {Object} obj |
| 255 | * @param {...any} [keys] |
| 256 | */ |
| 257 | OO.deleteProp = function ( obj ) { |
| 258 | if ( Object( obj ) !== obj || arguments.length < 2 ) { |
| 259 | return; |
| 260 | } |
| 261 | var prop = obj; |
| 262 | var props = [ prop ]; |
| 263 | var i = 1; |
| 264 | for ( ; i < arguments.length - 1; i++ ) { |
| 265 | if ( |
| 266 | prop[ arguments[ i ] ] === undefined || |
| 267 | Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] |
| 268 | ) { |
| 269 | return; |
| 270 | } |
| 271 | prop = prop[ arguments[ i ] ]; |
| 272 | props.push( prop ); |
| 273 | } |
| 274 | delete prop[ arguments[ i ] ]; |
| 275 | // Walk back through props removing any plain empty objects |
| 276 | while ( |
| 277 | props.length > 1 && |
| 278 | ( prop = props.pop() ) && |
| 279 | |
| 280 | OO.isPlainObject( prop ) && !Object.keys( prop ).length |
| 281 | ) { |
| 282 | delete props[ props.length - 1 ][ arguments[ props.length ] ]; |
| 283 | } |
| 284 | }; |
| 285 | |
| 286 | /** |
| 287 | * Create a new object that is an instance of the same |
| 288 | * constructor as the input, inherits from the same object |
| 289 | * and contains the same own properties. |
| 290 | * |
| 291 | * This makes a shallow non-recursive copy of own properties. |
| 292 | * To create a recursive copy of plain objects, use #copy. |
| 293 | * |
| 294 | * var foo = new Person( mom, dad ); |
| 295 | * foo.setAge( 21 ); |
| 296 | * var foo2 = OO.cloneObject( foo ); |
| 297 | * foo.setAge( 22 ); |
| 298 | * |
| 299 | * // Then |
| 300 | * foo2 !== foo; // true |
| 301 | * foo2 instanceof Person; // true |
| 302 | * foo2.getAge(); // 21 |
| 303 | * foo.getAge(); // 22 |
| 304 | * |
| 305 | * @memberof OO |
| 306 | * @method cloneObject |
| 307 | * @param {Object} origin |
| 308 | * @return {Object} Clone of origin |
| 309 | */ |
| 310 | OO.cloneObject = function ( origin ) { |
| 311 | var r = Object.create( origin.constructor.prototype ); |
| 312 | |
| 313 | for ( var key in origin ) { |
| 314 | if ( hasOwn.call( origin, key ) ) { |
| 315 | r[ key ] = origin[ key ]; |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | return r; |
| 320 | }; |
| 321 | |
| 322 | /** |
| 323 | * Get an array of all property values in an object. |
| 324 | * |
| 325 | * @memberof OO |
| 326 | * @method getObjectValues |
| 327 | * @param {Object} obj Object to get values from |
| 328 | * @return {Array} List of object values |
| 329 | */ |
| 330 | OO.getObjectValues = function ( obj ) { |
| 331 | if ( obj !== Object( obj ) ) { |
| 332 | throw new TypeError( 'Called on non-object' ); |
| 333 | } |
| 334 | |
| 335 | var values = []; |
| 336 | for ( var key in obj ) { |
| 337 | if ( hasOwn.call( obj, key ) ) { |
| 338 | values[ values.length ] = obj[ key ]; |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | return values; |
| 343 | }; |
| 344 | |
| 345 | /** |
| 346 | * Use binary search to locate an element in a sorted array. |
| 347 | * |
| 348 | * searchFunc is given an element from the array. `searchFunc(elem)` must return a number |
| 349 | * above 0 if the element we're searching for is to the right of (has a higher index than) elem, |
| 350 | * below 0 if it is to the left of elem, or zero if it's equal to elem. |
| 351 | * |
| 352 | * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns |
| 353 | * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use |
| 354 | * `searchFunc = cmp.bind( null, value )`. |
| 355 | * |
| 356 | * @memberof OO |
| 357 | * @method binarySearch |
| 358 | * @param {Array} arr Array to search in |
| 359 | * @param {Function} searchFunc Search function |
| 360 | * @param {boolean} [forInsertion] If not found, return index where val could be inserted |
| 361 | * @return {number|null} Index where val was found, or null if not found |
| 362 | */ |
| 363 | OO.binarySearch = function ( arr, searchFunc, forInsertion ) { |
| 364 | var left = 0; |
| 365 | var right = arr.length; |
| 366 | while ( left < right ) { |
| 367 | // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster |
| 368 | // eslint-disable-next-line no-bitwise |
| 369 | var mid = ( left + right ) >> 1; |
| 370 | var cmpResult = searchFunc( arr[ mid ] ); |
| 371 | if ( cmpResult < 0 ) { |
| 372 | right = mid; |
| 373 | } else if ( cmpResult > 0 ) { |
| 374 | left = mid + 1; |
| 375 | } else { |
| 376 | return mid; |
| 377 | } |
| 378 | } |
| 379 | return forInsertion ? right : null; |
| 380 | }; |
| 381 | |
| 382 | /** |
| 383 | * Recursively compare properties between two objects. |
| 384 | * |
| 385 | * A false result may be caused by property inequality or by properties in one object missing from |
| 386 | * the other. An asymmetrical test may also be performed, which checks only that properties in the |
| 387 | * first object are present in the second object, but not the inverse. |
| 388 | * |
| 389 | * If either a or b is null or undefined it will be treated as an empty object. |
| 390 | * |
| 391 | * @memberof OO |
| 392 | * @method compare |
| 393 | * @param {Object|undefined|null} a First object to compare |
| 394 | * @param {Object|undefined|null} b Second object to compare |
| 395 | * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's |
| 396 | * (i.e. a is a subset of b) |
| 397 | * @return {boolean} If the objects contain the same values as each other |
| 398 | */ |
| 399 | OO.compare = function ( a, b, asymmetrical ) { |
| 400 | if ( a === b ) { |
| 401 | return true; |
| 402 | } |
| 403 | |
| 404 | a = a || {}; |
| 405 | b = b || {}; |
| 406 | |
| 407 | if ( typeof a.nodeType === 'number' && typeof a.isEqualNode === 'function' ) { |
| 408 | return a.isEqualNode( b ); |
| 409 | } |
| 410 | |
| 411 | for ( var k in a ) { |
| 412 | if ( !hasOwn.call( a, k ) || a[ k ] === undefined || a[ k ] === b[ k ] ) { |
| 413 | // Ignore undefined values, because there is no conceptual difference between |
| 414 | // a key that is absent and a key that is present but whose value is undefined. |
| 415 | continue; |
| 416 | } |
| 417 | |
| 418 | var aValue = a[ k ]; |
| 419 | var bValue = b[ k ]; |
| 420 | var aType = typeof aValue; |
| 421 | var bType = typeof bValue; |
| 422 | if ( aType !== bType || |
| 423 | ( |
| 424 | ( aType === 'string' || aType === 'number' || aType === 'boolean' ) && |
| 425 | aValue !== bValue |
| 426 | ) || |
| 427 | ( aValue === Object( aValue ) && !OO.compare( aValue, bValue, true ) ) ) { |
| 428 | return false; |
| 429 | } |
| 430 | } |
| 431 | // If the check is not asymmetrical, recursing with the arguments swapped will verify our result |
| 432 | return asymmetrical ? true : OO.compare( b, a, true ); |
| 433 | }; |
| 434 | |
| 435 | /** |
| 436 | * Create a plain deep copy of any kind of object. |
| 437 | * |
| 438 | * Copies are deep, and will either be an object or an array depending on `source`. |
| 439 | * |
| 440 | * @memberof OO |
| 441 | * @method copy |
| 442 | * @param {Object} source Object to copy |
| 443 | * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are |
| 444 | * added to the clone |
| 445 | * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the |
| 446 | * nodeCallback returns a value other than undefined, the returned value is used instead of |
| 447 | * attempting to clone. |
| 448 | * @return {Object} Copy of source object |
| 449 | */ |
| 450 | OO.copy = function ( source, leafCallback, nodeCallback ) { |
| 451 | var destination; |
| 452 | |
| 453 | if ( nodeCallback ) { |
| 454 | // Extensibility: check before attempting to clone source. |
| 455 | destination = nodeCallback( source ); |
| 456 | if ( destination !== undefined ) { |
| 457 | return destination; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | if ( Array.isArray( source ) ) { |
| 462 | // Array (fall through) |
| 463 | destination = new Array( source.length ); |
| 464 | } else if ( source && typeof source.clone === 'function' ) { |
| 465 | // Duck type object with custom clone method |
| 466 | return leafCallback ? leafCallback( source.clone() ) : source.clone(); |
| 467 | } else if ( source && typeof source.cloneNode === 'function' ) { |
| 468 | // DOM Node |
| 469 | return leafCallback ? |
| 470 | leafCallback( source.cloneNode( true ) ) : |
| 471 | source.cloneNode( true ); |
| 472 | } else if ( OO.isPlainObject( source ) ) { |
| 473 | // Plain objects (fall through) |
| 474 | destination = {}; |
| 475 | } else { |
| 476 | // Non-plain objects (incl. functions) and primitive values |
| 477 | return leafCallback ? leafCallback( source ) : source; |
| 478 | } |
| 479 | |
| 480 | // source is an array or a plain object |
| 481 | for ( var key in source ) { |
| 482 | destination[ key ] = OO.copy( source[ key ], leafCallback, nodeCallback ); |
| 483 | } |
| 484 | |
| 485 | // This is an internal node, so we don't apply the leafCallback. |
| 486 | return destination; |
| 487 | }; |
| 488 | |
| 489 | /** |
| 490 | * Generate a hash of an object based on its name and data. |
| 491 | * |
| 492 | * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse> |
| 493 | * |
| 494 | * To avoid two objects with the same values generating different hashes, we utilize the replacer |
| 495 | * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may |
| 496 | * not be the fastest way to do this; we should investigate this further. |
| 497 | * |
| 498 | * Objects and arrays are hashed recursively. When hashing an object that has a .getHash() |
| 499 | * function, we call that function and use its return value rather than hashing the object |
| 500 | * ourselves. This allows classes to define custom hashing. |
| 501 | * |
| 502 | * @memberof OO |
| 503 | * @method getHash |
| 504 | * @param {Object} val Object to generate hash for |
| 505 | * @return {string} Hash of object |
| 506 | */ |
| 507 | OO.getHash = function ( val ) { |
| 508 | return JSON.stringify( val, OO.getHash.keySortReplacer ); |
| 509 | }; |
| 510 | |
| 511 | /** |
| 512 | * Sort objects by key (helper function for OO.getHash). |
| 513 | * |
| 514 | * This is a callback passed into JSON.stringify. |
| 515 | * |
| 516 | * @memberof OO |
| 517 | * @method getHash_keySortReplacer |
| 518 | * @param {string} key Property name of value being replaced |
| 519 | * @param {any} val Property value to replace |
| 520 | * @return {any} Replacement value |
| 521 | */ |
| 522 | OO.getHash.keySortReplacer = function ( key, val ) { |
| 523 | if ( val && typeof val.getHashObject === 'function' ) { |
| 524 | // This object has its own custom hash function, use it |
| 525 | val = val.getHashObject(); |
| 526 | } |
| 527 | if ( !Array.isArray( val ) && Object( val ) === val ) { |
| 528 | // Only normalize objects when the key-order is ambiguous |
| 529 | // (e.g. any object not an array). |
| 530 | var normalized = {}; |
| 531 | |
| 532 | var keys = Object.keys( val ).sort(); |
| 533 | for ( var i = 0, len = keys.length; i < len; i++ ) { |
| 534 | normalized[ keys[ i ] ] = val[ keys[ i ] ]; |
| 535 | } |
| 536 | return normalized; |
| 537 | } else { |
| 538 | // Primitive values and arrays get stable hashes |
| 539 | // by default. Lets those be stringified as-is. |
| 540 | return val; |
| 541 | } |
| 542 | }; |
| 543 | |
| 544 | /** |
| 545 | * Get the unique values of an array, removing duplicates. |
| 546 | * |
| 547 | * @memberof OO |
| 548 | * @method unique |
| 549 | * @param {Array} arr Array |
| 550 | * @return {Array} Unique values in array |
| 551 | */ |
| 552 | OO.unique = function ( arr ) { |
| 553 | return Array.from( new Set( arr ) ); |
| 554 | }; |
| 555 | |
| 556 | /** |
| 557 | * Compute the union (duplicate-free merge) of a set of arrays. |
| 558 | * |
| 559 | * @memberof OO |
| 560 | * @method simpleArrayUnion |
| 561 | * @param {Array} a First array |
| 562 | * @param {...Array} rest Arrays to union |
| 563 | * @return {Array} Union of the arrays |
| 564 | */ |
| 565 | OO.simpleArrayUnion = function ( a, ...rest ) { |
| 566 | var set = new Set( a ); |
| 567 | |
| 568 | for ( var i = 0; i < rest.length; i++ ) { |
| 569 | var arr = rest[ i ]; |
| 570 | for ( var j = 0; j < arr.length; j++ ) { |
| 571 | set.add( arr[ j ] ); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | return Array.from( set ); |
| 576 | }; |
| 577 | |
| 578 | /** |
| 579 | * Combine arrays (intersection or difference). |
| 580 | * |
| 581 | * An intersection checks the item exists in 'b' while difference checks it doesn't. |
| 582 | * |
| 583 | * @private |
| 584 | * @param {Array} a First array |
| 585 | * @param {Array} b Second array |
| 586 | * @param {boolean} includeB Whether to items in 'b' |
| 587 | * @return {Array} Combination (intersection or difference) of arrays |
| 588 | */ |
| 589 | function simpleArrayCombine( a, b, includeB ) { |
| 590 | var set = new Set( b ); |
| 591 | var result = []; |
| 592 | |
| 593 | for ( var j = 0; j < a.length; j++ ) { |
| 594 | var isInB = set.has( a[ j ] ); |
| 595 | if ( isInB === includeB ) { |
| 596 | result.push( a[ j ] ); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | return result; |
| 601 | } |
| 602 | |
| 603 | /** |
| 604 | * Compute the intersection of two arrays (items in both arrays). |
| 605 | * |
| 606 | * @memberof OO |
| 607 | * @method simpleArrayIntersection |
| 608 | * @param {Array} a First array |
| 609 | * @param {Array} b Second array |
| 610 | * @return {Array} Intersection of arrays |
| 611 | */ |
| 612 | OO.simpleArrayIntersection = function ( a, b ) { |
| 613 | return simpleArrayCombine( a, b, true ); |
| 614 | }; |
| 615 | |
| 616 | /** |
| 617 | * Compute the difference of two arrays (items in 'a' but not 'b'). |
| 618 | * |
| 619 | * @memberof OO |
| 620 | * @method simpleArrayDifference |
| 621 | * @param {Array} a First array |
| 622 | * @param {Array} b Second array |
| 623 | * @return {Array} Intersection of arrays |
| 624 | */ |
| 625 | OO.simpleArrayDifference = function ( a, b ) { |
| 626 | return simpleArrayCombine( a, b, false ); |
| 627 | }; |
| 628 | |
| 629 | /* eslint-disable-next-line no-redeclare */ |
| 630 | /* global hasOwn, toString */ |
| 631 | |
| 632 | /** |
| 633 | * Assert whether a value is a plain object or not. |
| 634 | * |
| 635 | * @memberof OO |
| 636 | * @param {any} obj |
| 637 | * @return {boolean} |
| 638 | */ |
| 639 | OO.isPlainObject = function ( obj ) { |
| 640 | // Optimise for common case where internal [[Class]] property is not "Object" |
| 641 | if ( !obj || toString.call( obj ) !== '[object Object]' ) { |
| 642 | return false; |
| 643 | } |
| 644 | |
| 645 | var proto = Object.getPrototypeOf( obj ); |
| 646 | |
| 647 | // Objects without prototype (e.g., `Object.create( null )`) are considered plain |
| 648 | if ( !proto ) { |
| 649 | return true; |
| 650 | } |
| 651 | |
| 652 | // The 'isPrototypeOf' method is set on Object.prototype. |
| 653 | return hasOwn.call( proto, 'isPrototypeOf' ); |
| 654 | }; |
| 655 | |
| 656 | /* global hasOwn, slice */ |
| 657 | |
| 658 | ( function () { |
| 659 | |
| 660 | /** |
| 661 | * @class |
| 662 | */ |
| 663 | OO.EventEmitter = function OoEventEmitter() { |
| 664 | // Properties |
| 665 | |
| 666 | /** |
| 667 | * Storage of bound event handlers by event name. |
| 668 | * |
| 669 | * @private |
| 670 | * @property {Object} bindings |
| 671 | */ |
| 672 | this.bindings = {}; |
| 673 | }; |
| 674 | |
| 675 | OO.initClass( OO.EventEmitter ); |
| 676 | |
| 677 | /* Private helper functions */ |
| 678 | |
| 679 | /** |
| 680 | * Validate a function or method call in a context |
| 681 | * |
| 682 | * For a method name, check that it names a function in the context object |
| 683 | * |
| 684 | * @private |
| 685 | * @param {Function|string} method Function or method name |
| 686 | * @param {any} context The context of the call |
| 687 | * @throws {Error} A method name is given but there is no context |
| 688 | * @throws {Error} In the context object, no property exists with the given name |
| 689 | * @throws {Error} In the context object, the named property is not a function |
| 690 | */ |
| 691 | function validateMethod( method, context ) { |
| 692 | // Validate method and context |
| 693 | if ( typeof method === 'string' ) { |
| 694 | // Validate method |
| 695 | if ( context === undefined || context === null ) { |
| 696 | throw new Error( 'Method name "' + method + '" has no context.' ); |
| 697 | } |
| 698 | if ( typeof context[ method ] !== 'function' ) { |
| 699 | // Technically the property could be replaced by a function before |
| 700 | // call time. But this probably signals a typo. |
| 701 | throw new Error( 'Property "' + method + '" is not a function' ); |
| 702 | } |
| 703 | } else if ( typeof method !== 'function' ) { |
| 704 | throw new Error( 'Invalid callback. Function or method name expected.' ); |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | /** |
| 709 | * @private |
| 710 | * @param {OO.EventEmitter} eventEmitter Event emitter |
| 711 | * @param {string} event Event name |
| 712 | * @param {Object} binding |
| 713 | */ |
| 714 | function addBinding( eventEmitter, event, binding ) { |
| 715 | var bindings; |
| 716 | // Auto-initialize bindings list |
| 717 | if ( hasOwn.call( eventEmitter.bindings, event ) ) { |
| 718 | bindings = eventEmitter.bindings[ event ]; |
| 719 | } else { |
| 720 | bindings = eventEmitter.bindings[ event ] = []; |
| 721 | } |
| 722 | // Add binding |
| 723 | bindings.push( binding ); |
| 724 | } |
| 725 | |
| 726 | /* Methods */ |
| 727 | |
| 728 | /** |
| 729 | * Add a listener to events of a specific event. |
| 730 | * |
| 731 | * The listener can be a function or the string name of a method; if the latter, then the |
| 732 | * name lookup happens at the time the listener is called. |
| 733 | * |
| 734 | * @param {string} event Type of event to listen to |
| 735 | * @param {Function|string} method Function or method name to call when event occurs |
| 736 | * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments |
| 737 | * @param {Object} [context=null] Context object for function or method call |
| 738 | * @return {OO.EventEmitter} |
| 739 | * @throws {Error} Listener argument is not a function or a valid method name |
| 740 | */ |
| 741 | OO.EventEmitter.prototype.on = function ( event, method, args, context ) { |
| 742 | validateMethod( method, context ); |
| 743 | |
| 744 | // Ensure consistent object shape (optimisation) |
| 745 | addBinding( this, event, { |
| 746 | method: method, |
| 747 | args: args, |
| 748 | context: ( arguments.length < 4 ) ? null : context, |
| 749 | once: false |
| 750 | } ); |
| 751 | return this; |
| 752 | }; |
| 753 | |
| 754 | /** |
| 755 | * Add a one-time listener to a specific event. |
| 756 | * |
| 757 | * @param {string} event Type of event to listen to |
| 758 | * @param {Function} listener Listener to call when event occurs |
| 759 | * @return {OO.EventEmitter} |
| 760 | */ |
| 761 | OO.EventEmitter.prototype.once = function ( event, listener ) { |
| 762 | validateMethod( listener ); |
| 763 | |
| 764 | // Ensure consistent object shape (optimisation) |
| 765 | addBinding( this, event, { |
| 766 | method: listener, |
| 767 | args: undefined, |
| 768 | context: null, |
| 769 | once: true |
| 770 | } ); |
| 771 | return this; |
| 772 | }; |
| 773 | |
| 774 | /** |
| 775 | * Remove a specific listener from a specific event. |
| 776 | * |
| 777 | * @param {string} event Type of event to remove listener from |
| 778 | * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed |
| 779 | * to "on". Omit to remove all listeners. |
| 780 | * @param {Object} [context=null] Context object function or method call |
| 781 | * @return {OO.EventEmitter} |
| 782 | * @throws {Error} Listener argument is not a function or a valid method name |
| 783 | */ |
| 784 | OO.EventEmitter.prototype.off = function ( event, method, context ) { |
| 785 | if ( arguments.length === 1 ) { |
| 786 | // Remove all bindings for event |
| 787 | delete this.bindings[ event ]; |
| 788 | return this; |
| 789 | } |
| 790 | |
| 791 | validateMethod( method, context ); |
| 792 | |
| 793 | if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) { |
| 794 | // No matching bindings |
| 795 | return this; |
| 796 | } |
| 797 | |
| 798 | // Default to null context |
| 799 | if ( arguments.length < 3 ) { |
| 800 | context = null; |
| 801 | } |
| 802 | |
| 803 | // Remove matching handlers |
| 804 | var bindings = this.bindings[ event ]; |
| 805 | var i = bindings.length; |
| 806 | while ( i-- ) { |
| 807 | if ( bindings[ i ].method === method && bindings[ i ].context === context ) { |
| 808 | bindings.splice( i, 1 ); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | // Cleanup if now empty |
| 813 | if ( bindings.length === 0 ) { |
| 814 | delete this.bindings[ event ]; |
| 815 | } |
| 816 | return this; |
| 817 | }; |
| 818 | |
| 819 | /** |
| 820 | * Emit an event. |
| 821 | * |
| 822 | * All listeners for the event will be called synchronously, in an |
| 823 | * unspecified order. If any listeners throw an exception, this won't |
| 824 | * disrupt the calls to the remaining listeners; however, the exception |
| 825 | * won't be thrown until the next tick. |
| 826 | * |
| 827 | * Listeners should avoid mutating the emitting object, as this is |
| 828 | * something of an anti-pattern which can easily result in |
| 829 | * hard-to-understand code with hidden side-effects and dependencies. |
| 830 | * |
| 831 | * @param {string} event Type of event |
| 832 | * @param {...any} [args] Arguments passed to the event handler |
| 833 | * @return {boolean} Whether the event was handled by at least one listener |
| 834 | */ |
| 835 | OO.EventEmitter.prototype.emit = function ( event ) { |
| 836 | if ( !hasOwn.call( this.bindings, event ) ) { |
| 837 | return false; |
| 838 | } |
| 839 | |
| 840 | // Slicing ensures that we don't get tripped up by event |
| 841 | // handlers that add/remove bindings |
| 842 | var bindings = this.bindings[ event ].slice(); |
| 843 | var args = slice.call( arguments, 1 ); |
| 844 | for ( var i = 0; i < bindings.length; i++ ) { |
| 845 | var binding = bindings[ i ]; |
| 846 | var method; |
| 847 | if ( typeof binding.method === 'string' ) { |
| 848 | // Lookup method by name (late binding) |
| 849 | method = binding.context[ binding.method ]; |
| 850 | } else { |
| 851 | method = binding.method; |
| 852 | } |
| 853 | if ( binding.once ) { |
| 854 | // Unbind before calling, to avoid any nested triggers. |
| 855 | this.off( event, method ); |
| 856 | } |
| 857 | try { |
| 858 | method.apply( |
| 859 | binding.context, |
| 860 | binding.args ? binding.args.concat( args ) : args |
| 861 | ); |
| 862 | } catch ( e ) { |
| 863 | // If one listener has an unhandled error, don't have it |
| 864 | // take down the emitter. But rethrow asynchronously so |
| 865 | // debuggers can break with a full async stack trace. |
| 866 | setTimeout( ( function ( error ) { |
| 867 | throw error; |
| 868 | } ).bind( null, e ) ); |
| 869 | } |
| 870 | |
| 871 | } |
| 872 | return true; |
| 873 | }; |
| 874 | |
| 875 | /** |
| 876 | * Emit an event, propagating the first exception some listener throws |
| 877 | * |
| 878 | * All listeners for the event will be called synchronously, in an |
| 879 | * unspecified order. If any listener throws an exception, this won't |
| 880 | * disrupt the calls to the remaining listeners. The first exception |
| 881 | * thrown will be propagated back to the caller; any others won't be |
| 882 | * thrown until the next tick. |
| 883 | * |
| 884 | * Listeners should avoid mutating the emitting object, as this is |
| 885 | * something of an anti-pattern which can easily result in |
| 886 | * hard-to-understand code with hidden side-effects and dependencies. |
| 887 | * |
| 888 | * @param {string} event Type of event |
| 889 | * @param {...any} [args] Arguments passed to the event handler |
| 890 | * @return {boolean} Whether the event was handled by at least one listener |
| 891 | */ |
| 892 | OO.EventEmitter.prototype.emitThrow = function ( event ) { |
| 893 | // We tolerate code duplication with #emit, because the |
| 894 | // alternative is an extra level of indirection which will |
| 895 | // appear in very many stack traces. |
| 896 | if ( !hasOwn.call( this.bindings, event ) ) { |
| 897 | return false; |
| 898 | } |
| 899 | |
| 900 | var firstError; |
| 901 | // Slicing ensures that we don't get tripped up by event |
| 902 | // handlers that add/remove bindings |
| 903 | var bindings = this.bindings[ event ].slice(); |
| 904 | var args = slice.call( arguments, 1 ); |
| 905 | for ( var i = 0; i < bindings.length; i++ ) { |
| 906 | var binding = bindings[ i ]; |
| 907 | var method; |
| 908 | if ( typeof binding.method === 'string' ) { |
| 909 | // Lookup method by name (late binding) |
| 910 | method = binding.context[ binding.method ]; |
| 911 | } else { |
| 912 | method = binding.method; |
| 913 | } |
| 914 | if ( binding.once ) { |
| 915 | // Unbind before calling, to avoid any nested triggers. |
| 916 | this.off( event, method ); |
| 917 | } |
| 918 | try { |
| 919 | method.apply( |
| 920 | binding.context, |
| 921 | binding.args ? binding.args.concat( args ) : args |
| 922 | ); |
| 923 | } catch ( e ) { |
| 924 | if ( firstError === undefined ) { |
| 925 | firstError = e; |
| 926 | } else { |
| 927 | // If one listener has an unhandled error, don't have it |
| 928 | // take down the emitter. But rethrow asynchronously so |
| 929 | // debuggers can break with a full async stack trace. |
| 930 | setTimeout( ( function ( error ) { |
| 931 | throw error; |
| 932 | } ).bind( null, e ) ); |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | } |
| 937 | if ( firstError !== undefined ) { |
| 938 | throw firstError; |
| 939 | } |
| 940 | return true; |
| 941 | }; |
| 942 | |
| 943 | /** |
| 944 | * Connect event handlers to an object. |
| 945 | * |
| 946 | * @param {Object} context Object to call methods on when events occur |
| 947 | * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods |
| 948 | * List of event bindings keyed by event name containing either method names, functions or |
| 949 | * arrays containing method name or function followed by a list of arguments to be passed to |
| 950 | * callback before emitted arguments. |
| 951 | * @return {OO.EventEmitter} |
| 952 | */ |
| 953 | OO.EventEmitter.prototype.connect = function ( context, methods ) { |
| 954 | for ( var event in methods ) { |
| 955 | var method = methods[ event ]; |
| 956 | var args; |
| 957 | // Allow providing additional args |
| 958 | if ( Array.isArray( method ) ) { |
| 959 | args = method.slice( 1 ); |
| 960 | method = method[ 0 ]; |
| 961 | } else { |
| 962 | args = []; |
| 963 | } |
| 964 | // Add binding |
| 965 | this.on( event, method, args, context ); |
| 966 | } |
| 967 | return this; |
| 968 | }; |
| 969 | |
| 970 | /** |
| 971 | * Disconnect event handlers from an object. |
| 972 | * |
| 973 | * @param {Object} context Object to disconnect methods from |
| 974 | * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] |
| 975 | * List of event bindings keyed by event name. Values can be either method names, functions or |
| 976 | * arrays containing a method name. |
| 977 | * NOTE: To allow matching call sites with connect(), array values are allowed to contain the |
| 978 | * parameters as well, but only the method name is used to find bindings. It is discouraged to |
| 979 | * have multiple bindings for the same event to the same listener, but if used (and only the |
| 980 | * parameters vary), disconnecting one variation of (event name, event listener, parameters) |
| 981 | * will disconnect other variations as well. |
| 982 | * @return {OO.EventEmitter} |
| 983 | */ |
| 984 | OO.EventEmitter.prototype.disconnect = function ( context, methods ) { |
| 985 | var event; |
| 986 | if ( methods ) { |
| 987 | // Remove specific connections to the context |
| 988 | for ( event in methods ) { |
| 989 | var method = methods[ event ]; |
| 990 | if ( Array.isArray( method ) ) { |
| 991 | method = method[ 0 ]; |
| 992 | } |
| 993 | this.off( event, method, context ); |
| 994 | } |
| 995 | } else { |
| 996 | // Remove all connections to the context |
| 997 | for ( event in this.bindings ) { |
| 998 | var bindings = this.bindings[ event ]; |
| 999 | var i = bindings.length; |
| 1000 | while ( i-- ) { |
| 1001 | // bindings[i] may have been removed by the previous step's |
| 1002 | // this.off so check it still exists |
| 1003 | if ( bindings[ i ] && bindings[ i ].context === context ) { |
| 1004 | this.off( event, bindings[ i ].method, context ); |
| 1005 | } |
| 1006 | } |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | return this; |
| 1011 | }; |
| 1012 | |
| 1013 | }() ); |
| 1014 | |
| 1015 | ( function () { |
| 1016 | |
| 1017 | /** |
| 1018 | * Contain and manage a list of @{link OO.EventEmitter} items. |
| 1019 | * |
| 1020 | * Aggregates and manages their events collectively. |
| 1021 | * |
| 1022 | * This mixin must be used in a class that also mixes in @{link OO.EventEmitter}. |
| 1023 | * |
| 1024 | * @abstract |
| 1025 | * @class |
| 1026 | */ |
| 1027 | OO.EmitterList = function OoEmitterList() { |
| 1028 | this.items = []; |
| 1029 | this.aggregateItemEvents = {}; |
| 1030 | }; |
| 1031 | |
| 1032 | OO.initClass( OO.EmitterList ); |
| 1033 | |
| 1034 | /* Events */ |
| 1035 | |
| 1036 | /** |
| 1037 | * Item has been added. |
| 1038 | * |
| 1039 | * @event OO.EmitterList#add |
| 1040 | * @param {OO.EventEmitter} item Added item |
| 1041 | * @param {number} index Index items were added at |
| 1042 | */ |
| 1043 | |
| 1044 | /** |
| 1045 | * Item has been moved to a new index. |
| 1046 | * |
| 1047 | * @event OO.EmitterList#move |
| 1048 | * @param {OO.EventEmitter} item Moved item |
| 1049 | * @param {number} index Index item was moved to |
| 1050 | * @param {number} oldIndex The original index the item was in |
| 1051 | */ |
| 1052 | |
| 1053 | /** |
| 1054 | * Item has been removed. |
| 1055 | * |
| 1056 | * @event OO.EmitterList#remove |
| 1057 | * @param {OO.EventEmitter} item Removed item |
| 1058 | * @param {number} index Index the item was removed from |
| 1059 | */ |
| 1060 | |
| 1061 | /** |
| 1062 | * The list has been cleared of items. |
| 1063 | * |
| 1064 | * @event OO.EmitterList#clear |
| 1065 | */ |
| 1066 | |
| 1067 | /* Methods */ |
| 1068 | |
| 1069 | /** |
| 1070 | * Normalize requested index to fit into the bounds of the given array. |
| 1071 | * |
| 1072 | * @private |
| 1073 | * @static |
| 1074 | * @param {Array} arr Given array |
| 1075 | * @param {number|undefined} index Requested index |
| 1076 | * @return {number} Normalized index |
| 1077 | */ |
| 1078 | function normalizeArrayIndex( arr, index ) { |
| 1079 | return ( index === undefined || index < 0 || index >= arr.length ) ? |
| 1080 | arr.length : |
| 1081 | index; |
| 1082 | } |
| 1083 | |
| 1084 | /** |
| 1085 | * Get all items. |
| 1086 | * |
| 1087 | * @return {OO.EventEmitter[]} Items in the list |
| 1088 | */ |
| 1089 | OO.EmitterList.prototype.getItems = function () { |
| 1090 | return this.items.slice( 0 ); |
| 1091 | }; |
| 1092 | |
| 1093 | /** |
| 1094 | * Get the index of a specific item. |
| 1095 | * |
| 1096 | * @param {OO.EventEmitter} item Requested item |
| 1097 | * @return {number} Index of the item |
| 1098 | */ |
| 1099 | OO.EmitterList.prototype.getItemIndex = function ( item ) { |
| 1100 | return this.items.indexOf( item ); |
| 1101 | }; |
| 1102 | |
| 1103 | /** |
| 1104 | * Get number of items. |
| 1105 | * |
| 1106 | * @return {number} Number of items in the list |
| 1107 | */ |
| 1108 | OO.EmitterList.prototype.getItemCount = function () { |
| 1109 | return this.items.length; |
| 1110 | }; |
| 1111 | |
| 1112 | /** |
| 1113 | * Check if a list contains no items. |
| 1114 | * |
| 1115 | * @return {boolean} Group is empty |
| 1116 | */ |
| 1117 | OO.EmitterList.prototype.isEmpty = function () { |
| 1118 | return !this.items.length; |
| 1119 | }; |
| 1120 | |
| 1121 | /** |
| 1122 | * Aggregate the events emitted by the group. |
| 1123 | * |
| 1124 | * When events are aggregated, the group will listen to all contained items for the event, |
| 1125 | * and then emit the event under a new name. The new event will contain an additional leading |
| 1126 | * parameter containing the item that emitted the original event. Other arguments emitted from |
| 1127 | * the original event are passed through. |
| 1128 | * |
| 1129 | * @param {Object.<string,string|null>} events An object keyed by the name of the event that |
| 1130 | * should be aggregated (e.g., ‘click’) and the value of the new name to use |
| 1131 | * (e.g., ‘groupClick’). A `null` value will remove aggregated events. |
| 1132 | * @throws {Error} If aggregation already exists |
| 1133 | */ |
| 1134 | OO.EmitterList.prototype.aggregate = function ( events ) { |
| 1135 | var i, item; |
| 1136 | for ( var itemEvent in events ) { |
| 1137 | var groupEvent = events[ itemEvent ]; |
| 1138 | |
| 1139 | // Remove existing aggregated event |
| 1140 | if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { |
| 1141 | // Don't allow duplicate aggregations |
| 1142 | if ( groupEvent ) { |
| 1143 | throw new Error( 'Duplicate item event aggregation for ' + itemEvent ); |
| 1144 | } |
| 1145 | // Remove event aggregation from existing items |
| 1146 | for ( i = 0; i < this.items.length; i++ ) { |
| 1147 | item = this.items[ i ]; |
| 1148 | if ( item.connect && item.disconnect ) { |
| 1149 | var remove = {}; |
| 1150 | remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; |
| 1151 | item.disconnect( this, remove ); |
| 1152 | } |
| 1153 | } |
| 1154 | // Prevent future items from aggregating event |
| 1155 | delete this.aggregateItemEvents[ itemEvent ]; |
| 1156 | } |
| 1157 | |
| 1158 | // Add new aggregate event |
| 1159 | if ( groupEvent ) { |
| 1160 | // Make future items aggregate event |
| 1161 | this.aggregateItemEvents[ itemEvent ] = groupEvent; |
| 1162 | // Add event aggregation to existing items |
| 1163 | for ( i = 0; i < this.items.length; i++ ) { |
| 1164 | item = this.items[ i ]; |
| 1165 | if ( item.connect && item.disconnect ) { |
| 1166 | var add = {}; |
| 1167 | add[ itemEvent ] = [ 'emit', groupEvent, item ]; |
| 1168 | item.connect( this, add ); |
| 1169 | } |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | }; |
| 1174 | |
| 1175 | /** |
| 1176 | * Add items to the list. |
| 1177 | * |
| 1178 | * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or |
| 1179 | * an array of items to add |
| 1180 | * @param {number} [index] Index to add items at. If no index is |
| 1181 | * given, or if the index that is given is invalid, the item |
| 1182 | * will be added at the end of the list. |
| 1183 | * @return {OO.EmitterList} |
| 1184 | * @fires OO.EmitterList#add |
| 1185 | * @fires OO.EmitterList#move |
| 1186 | */ |
| 1187 | OO.EmitterList.prototype.addItems = function ( items, index ) { |
| 1188 | if ( !Array.isArray( items ) ) { |
| 1189 | items = [ items ]; |
| 1190 | } |
| 1191 | |
| 1192 | if ( items.length === 0 ) { |
| 1193 | return this; |
| 1194 | } |
| 1195 | |
| 1196 | index = normalizeArrayIndex( this.items, index ); |
| 1197 | for ( var i = 0; i < items.length; i++ ) { |
| 1198 | var oldIndex = this.items.indexOf( items[ i ] ); |
| 1199 | if ( oldIndex !== -1 ) { |
| 1200 | // Move item to new index |
| 1201 | index = this.moveItem( items[ i ], index ); |
| 1202 | this.emit( 'move', items[ i ], index, oldIndex ); |
| 1203 | } else { |
| 1204 | // insert item at index |
| 1205 | index = this.insertItem( items[ i ], index ); |
| 1206 | this.emit( 'add', items[ i ], index ); |
| 1207 | } |
| 1208 | index++; |
| 1209 | } |
| 1210 | |
| 1211 | return this; |
| 1212 | }; |
| 1213 | |
| 1214 | /** |
| 1215 | * Move an item from its current position to a new index. |
| 1216 | * |
| 1217 | * The item is expected to exist in the list. If it doesn't, |
| 1218 | * the method will throw an exception. |
| 1219 | * |
| 1220 | * @private |
| 1221 | * @param {OO.EventEmitter} item Items to add |
| 1222 | * @param {number} newIndex Index to move the item to |
| 1223 | * @return {number} The index the item was moved to |
| 1224 | * @throws {Error} If item is not in the list |
| 1225 | */ |
| 1226 | OO.EmitterList.prototype.moveItem = function ( item, newIndex ) { |
| 1227 | var existingIndex = this.items.indexOf( item ); |
| 1228 | |
| 1229 | if ( existingIndex === -1 ) { |
| 1230 | throw new Error( 'Item cannot be moved, because it is not in the list.' ); |
| 1231 | } |
| 1232 | |
| 1233 | newIndex = normalizeArrayIndex( this.items, newIndex ); |
| 1234 | |
| 1235 | // Remove the item from the current index |
| 1236 | this.items.splice( existingIndex, 1 ); |
| 1237 | |
| 1238 | // If necessary, adjust new index after removal |
| 1239 | if ( existingIndex < newIndex ) { |
| 1240 | newIndex--; |
| 1241 | } |
| 1242 | |
| 1243 | // Move the item to the new index |
| 1244 | this.items.splice( newIndex, 0, item ); |
| 1245 | |
| 1246 | return newIndex; |
| 1247 | }; |
| 1248 | |
| 1249 | /** |
| 1250 | * Utility method to insert an item into the list, and |
| 1251 | * connect it to aggregate events. |
| 1252 | * |
| 1253 | * Don't call this directly unless you know what you're doing. |
| 1254 | * Use #addItems instead. |
| 1255 | * |
| 1256 | * This method can be extended in child classes to produce |
| 1257 | * different behavior when an item is inserted. For example, |
| 1258 | * inserted items may also be attached to the DOM or may |
| 1259 | * interact with some other nodes in certain ways. Extending |
| 1260 | * this method is allowed, but if overridden, the aggregation |
| 1261 | * of events must be preserved, or behavior of emitted events |
| 1262 | * will be broken. |
| 1263 | * |
| 1264 | * If you are extending this method, please make sure the |
| 1265 | * parent method is called. |
| 1266 | * |
| 1267 | * @protected |
| 1268 | * @param {OO.EventEmitter|Object} item Item to add |
| 1269 | * @param {number} index Index to add items at |
| 1270 | * @return {number} The index the item was added at |
| 1271 | */ |
| 1272 | OO.EmitterList.prototype.insertItem = function ( item, index ) { |
| 1273 | // Throw an error if null or item is not an object. |
| 1274 | if ( item === null || typeof item !== 'object' ) { |
| 1275 | throw new Error( 'Expected object, but item is ' + typeof item ); |
| 1276 | } |
| 1277 | |
| 1278 | // Add the item to event aggregation |
| 1279 | if ( item.connect && item.disconnect ) { |
| 1280 | var events = {}; |
| 1281 | for ( var event in this.aggregateItemEvents ) { |
| 1282 | events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ]; |
| 1283 | } |
| 1284 | item.connect( this, events ); |
| 1285 | } |
| 1286 | |
| 1287 | index = normalizeArrayIndex( this.items, index ); |
| 1288 | |
| 1289 | // Insert into items array |
| 1290 | this.items.splice( index, 0, item ); |
| 1291 | return index; |
| 1292 | }; |
| 1293 | |
| 1294 | /** |
| 1295 | * Remove items. |
| 1296 | * |
| 1297 | * @param {OO.EventEmitter|OO.EventEmitter[]} items Items to remove |
| 1298 | * @return {OO.EmitterList} |
| 1299 | * @fires OO.EmitterList#remove |
| 1300 | */ |
| 1301 | OO.EmitterList.prototype.removeItems = function ( items ) { |
| 1302 | if ( !Array.isArray( items ) ) { |
| 1303 | items = [ items ]; |
| 1304 | } |
| 1305 | |
| 1306 | if ( items.length === 0 ) { |
| 1307 | return this; |
| 1308 | } |
| 1309 | |
| 1310 | // Remove specific items |
| 1311 | for ( var i = 0; i < items.length; i++ ) { |
| 1312 | var item = items[ i ]; |
| 1313 | var index = this.items.indexOf( item ); |
| 1314 | if ( index !== -1 ) { |
| 1315 | if ( item.connect && item.disconnect ) { |
| 1316 | // Disconnect all listeners from the item |
| 1317 | item.disconnect( this ); |
| 1318 | } |
| 1319 | this.items.splice( index, 1 ); |
| 1320 | this.emit( 'remove', item, index ); |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | return this; |
| 1325 | }; |
| 1326 | |
| 1327 | /** |
| 1328 | * Clear all items. |
| 1329 | * |
| 1330 | * @return {OO.EmitterList} |
| 1331 | * @fires OO.EmitterList#clear |
| 1332 | */ |
| 1333 | OO.EmitterList.prototype.clearItems = function () { |
| 1334 | var cleared = this.items.splice( 0, this.items.length ); |
| 1335 | |
| 1336 | // Disconnect all items |
| 1337 | for ( var i = 0; i < cleared.length; i++ ) { |
| 1338 | var item = cleared[ i ]; |
| 1339 | if ( item.connect && item.disconnect ) { |
| 1340 | item.disconnect( this ); |
| 1341 | } |
| 1342 | } |
| 1343 | |
| 1344 | this.emit( 'clear' ); |
| 1345 | |
| 1346 | return this; |
| 1347 | }; |
| 1348 | |
| 1349 | }() ); |
| 1350 | |
| 1351 | /** |
| 1352 | * Manage a sorted list of OO.EmitterList objects. |
| 1353 | * |
| 1354 | * The sort order is based on a callback that compares two items. The return value of |
| 1355 | * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero |
| 1356 | * if a is equal to b. The callback should only return zero if the two objects are |
| 1357 | * considered equal. |
| 1358 | * |
| 1359 | * When an item changes in a way that could affect their sorting behavior, it must |
| 1360 | * emit the {@link OO.SortedEmitterList#event:itemSortChange itemSortChange} event. |
| 1361 | * This will cause it to be re-sorted automatically. |
| 1362 | * |
| 1363 | * This mixin must be used in a class that also mixes in {@link OO.EventEmitter}. |
| 1364 | * |
| 1365 | * @abstract |
| 1366 | * @class |
| 1367 | * @mixes OO.EmitterList |
| 1368 | * @param {Function} sortingCallback Callback that compares two items. |
| 1369 | */ |
| 1370 | OO.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) { |
| 1371 | // Mixin constructors |
| 1372 | OO.EmitterList.call( this ); |
| 1373 | |
| 1374 | this.sortingCallback = sortingCallback; |
| 1375 | |
| 1376 | // Listen to sortChange event and make sure |
| 1377 | // we re-sort the changed item when that happens |
| 1378 | this.aggregate( { |
| 1379 | sortChange: 'itemSortChange' |
| 1380 | } ); |
| 1381 | |
| 1382 | this.connect( this, { |
| 1383 | itemSortChange: 'onItemSortChange' |
| 1384 | } ); |
| 1385 | }; |
| 1386 | |
| 1387 | OO.mixinClass( OO.SortedEmitterList, OO.EmitterList ); |
| 1388 | |
| 1389 | /* Events */ |
| 1390 | |
| 1391 | /** |
| 1392 | * An item has changed properties that affect its sort positioning |
| 1393 | * inside the list. |
| 1394 | * |
| 1395 | * @private |
| 1396 | * @event OO.SortedEmitterList#itemSortChange |
| 1397 | */ |
| 1398 | |
| 1399 | /* Methods */ |
| 1400 | |
| 1401 | /** |
| 1402 | * Handle a case where an item changed a property that relates |
| 1403 | * to its sorted order. |
| 1404 | * |
| 1405 | * @param {OO.EventEmitter} item Item in the list |
| 1406 | */ |
| 1407 | OO.SortedEmitterList.prototype.onItemSortChange = function ( item ) { |
| 1408 | // Remove the item |
| 1409 | this.removeItems( item ); |
| 1410 | // Re-add the item so it is in the correct place |
| 1411 | this.addItems( item ); |
| 1412 | }; |
| 1413 | |
| 1414 | /** |
| 1415 | * Change the sorting callback for this sorted list. |
| 1416 | * |
| 1417 | * The callback receives two items. The return value of callback(a, b) must be less than zero |
| 1418 | * if a < b, greater than zero if a > b, and zero if a is equal to b. |
| 1419 | * |
| 1420 | * @param {Function} sortingCallback Sorting callback |
| 1421 | */ |
| 1422 | OO.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) { |
| 1423 | var items = this.getItems(); |
| 1424 | |
| 1425 | this.sortingCallback = sortingCallback; |
| 1426 | |
| 1427 | // Empty the list |
| 1428 | this.clearItems(); |
| 1429 | // Re-add the items in the new order |
| 1430 | this.addItems( items ); |
| 1431 | }; |
| 1432 | |
| 1433 | /** |
| 1434 | * Add items to the sorted list. |
| 1435 | * |
| 1436 | * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or |
| 1437 | * an array of items to add |
| 1438 | * @return {OO.SortedEmitterList} |
| 1439 | */ |
| 1440 | OO.SortedEmitterList.prototype.addItems = function ( items ) { |
| 1441 | if ( !Array.isArray( items ) ) { |
| 1442 | items = [ items ]; |
| 1443 | } |
| 1444 | |
| 1445 | if ( items.length === 0 ) { |
| 1446 | return this; |
| 1447 | } |
| 1448 | |
| 1449 | for ( var i = 0; i < items.length; i++ ) { |
| 1450 | // Find insertion index |
| 1451 | var insertionIndex = this.findInsertionIndex( items[ i ] ); |
| 1452 | |
| 1453 | // Check if the item exists using the sorting callback |
| 1454 | // and remove it first if it exists |
| 1455 | if ( |
| 1456 | // First make sure the insertion index is not at the end |
| 1457 | // of the list (which means it does not point to any actual |
| 1458 | // items) |
| 1459 | insertionIndex <= this.items.length && |
| 1460 | // Make sure there actually is an item in this index |
| 1461 | this.items[ insertionIndex ] && |
| 1462 | // The callback returns 0 if the items are equal |
| 1463 | this.sortingCallback( this.items[ insertionIndex ], items[ i ] ) === 0 |
| 1464 | ) { |
| 1465 | // Remove the existing item |
| 1466 | this.removeItems( this.items[ insertionIndex ] ); |
| 1467 | } |
| 1468 | |
| 1469 | // Insert item at the insertion index |
| 1470 | var index = this.insertItem( items[ i ], insertionIndex ); |
| 1471 | this.emit( 'add', items[ i ], index ); |
| 1472 | } |
| 1473 | |
| 1474 | return this; |
| 1475 | }; |
| 1476 | |
| 1477 | /** |
| 1478 | * Find the index a given item should be inserted at. If the item is already |
| 1479 | * in the list, this will return the index where the item currently is. |
| 1480 | * |
| 1481 | * @param {OO.EventEmitter} item Items to insert |
| 1482 | * @return {number} The index the item should be inserted at |
| 1483 | */ |
| 1484 | OO.SortedEmitterList.prototype.findInsertionIndex = function ( item ) { |
| 1485 | var list = this; |
| 1486 | |
| 1487 | return OO.binarySearch( |
| 1488 | this.items, |
| 1489 | // Fake a this.sortingCallback.bind( null, item ) call here |
| 1490 | // otherwise this doesn't pass tests in phantomJS |
| 1491 | function ( otherItem ) { |
| 1492 | return list.sortingCallback( item, otherItem ); |
| 1493 | }, |
| 1494 | true |
| 1495 | ); |
| 1496 | |
| 1497 | }; |
| 1498 | |
| 1499 | /* global hasOwn */ |
| 1500 | |
| 1501 | /** |
| 1502 | * A map interface for associating arbitrary data with a symbolic name. Used in |
| 1503 | * place of a plain object to provide additional {@link OO.Registry#register registration} |
| 1504 | * or {@link OO.Registry#lookup lookup} functionality. |
| 1505 | * |
| 1506 | * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>. |
| 1507 | * |
| 1508 | * @class |
| 1509 | * @mixes OO.EventEmitter |
| 1510 | */ |
| 1511 | OO.Registry = function OoRegistry() { |
| 1512 | // Mixin constructors |
| 1513 | OO.EventEmitter.call( this ); |
| 1514 | |
| 1515 | // Properties |
| 1516 | this.registry = {}; |
| 1517 | }; |
| 1518 | |
| 1519 | /* Inheritance */ |
| 1520 | |
| 1521 | OO.mixinClass( OO.Registry, OO.EventEmitter ); |
| 1522 | |
| 1523 | /* Events */ |
| 1524 | |
| 1525 | /** |
| 1526 | * @event OO.Registry#register |
| 1527 | * @param {string} name |
| 1528 | * @param {any} data |
| 1529 | */ |
| 1530 | |
| 1531 | /** |
| 1532 | * @event OO.Registry#unregister |
| 1533 | * @param {string} name |
| 1534 | * @param {any} data Data removed from registry |
| 1535 | */ |
| 1536 | |
| 1537 | /* Methods */ |
| 1538 | |
| 1539 | /** |
| 1540 | * Associate one or more symbolic names with some data. |
| 1541 | * |
| 1542 | * Any existing entry with the same name will be overridden. |
| 1543 | * |
| 1544 | * @param {string|string[]} name Symbolic name or list of symbolic names |
| 1545 | * @param {any} data Data to associate with symbolic name |
| 1546 | * @fires OO.Registry#register |
| 1547 | * @throws {Error} Name argument must be a string or array |
| 1548 | */ |
| 1549 | OO.Registry.prototype.register = function ( name, data ) { |
| 1550 | if ( typeof name === 'string' ) { |
| 1551 | this.registry[ name ] = data; |
| 1552 | this.emit( 'register', name, data ); |
| 1553 | } else if ( Array.isArray( name ) ) { |
| 1554 | for ( var i = 0, len = name.length; i < len; i++ ) { |
| 1555 | this.register( name[ i ], data ); |
| 1556 | } |
| 1557 | } else { |
| 1558 | throw new Error( 'Name must be a string or array, cannot be a ' + typeof name ); |
| 1559 | } |
| 1560 | }; |
| 1561 | |
| 1562 | /** |
| 1563 | * Remove one or more symbolic names from the registry. |
| 1564 | * |
| 1565 | * @param {string|string[]} name Symbolic name or list of symbolic names |
| 1566 | * @fires OO.Registry#unregister |
| 1567 | * @throws {Error} Name argument must be a string or array |
| 1568 | */ |
| 1569 | OO.Registry.prototype.unregister = function ( name ) { |
| 1570 | if ( typeof name === 'string' ) { |
| 1571 | var data = this.lookup( name ); |
| 1572 | if ( data !== undefined ) { |
| 1573 | delete this.registry[ name ]; |
| 1574 | this.emit( 'unregister', name, data ); |
| 1575 | } |
| 1576 | } else if ( Array.isArray( name ) ) { |
| 1577 | for ( var i = 0, len = name.length; i < len; i++ ) { |
| 1578 | this.unregister( name[ i ] ); |
| 1579 | } |
| 1580 | } else { |
| 1581 | throw new Error( 'Name must be a string or array, cannot be a ' + typeof name ); |
| 1582 | } |
| 1583 | }; |
| 1584 | |
| 1585 | /** |
| 1586 | * Get data for a given symbolic name. |
| 1587 | * |
| 1588 | * @param {string} name Symbolic name |
| 1589 | * @return {any|undefined} Data associated with symbolic name |
| 1590 | */ |
| 1591 | OO.Registry.prototype.lookup = function ( name ) { |
| 1592 | if ( hasOwn.call( this.registry, name ) ) { |
| 1593 | return this.registry[ name ]; |
| 1594 | } |
| 1595 | }; |
| 1596 | |
| 1597 | /** |
| 1598 | * @class |
| 1599 | * @extends OO.Registry |
| 1600 | */ |
| 1601 | OO.Factory = function OoFactory() { |
| 1602 | // Parent constructor |
| 1603 | OO.Factory.super.call( this ); |
| 1604 | }; |
| 1605 | |
| 1606 | /* Inheritance */ |
| 1607 | |
| 1608 | OO.inheritClass( OO.Factory, OO.Registry ); |
| 1609 | |
| 1610 | /* Methods */ |
| 1611 | |
| 1612 | /** |
| 1613 | * Register a class with the factory. |
| 1614 | * |
| 1615 | * function MyClass() {}; |
| 1616 | * OO.initClass( MyClass ); |
| 1617 | * MyClass.key = 'hello'; |
| 1618 | * |
| 1619 | * // Register class with the factory |
| 1620 | * factory.register( MyClass ); |
| 1621 | * |
| 1622 | * // Instantiate a class based on its registered key (also known as a "symbolic name") |
| 1623 | * factory.create( 'hello' ); |
| 1624 | * |
| 1625 | * @param {Function} constructor Class to use when creating an object |
| 1626 | * @param {string} [key] The key for #create(). |
| 1627 | * This parameter is usually omitted in favour of letting the class declare |
| 1628 | * its own key, through `MyClass.key`. |
| 1629 | * For backwards-compatiblity with OOjs 6.0 (2021) and older, it can also be declared |
| 1630 | * via `MyClass.static.name`. |
| 1631 | * @throws {Error} If a parameter is invalid |
| 1632 | */ |
| 1633 | OO.Factory.prototype.register = function ( constructor, key ) { |
| 1634 | if ( typeof constructor !== 'function' ) { |
| 1635 | throw new Error( 'constructor must be a function, got ' + typeof constructor ); |
| 1636 | } |
| 1637 | if ( arguments.length <= 1 ) { |
| 1638 | key = constructor.key || ( constructor.static && constructor.static.name ); |
| 1639 | } |
| 1640 | if ( typeof key !== 'string' || key === '' ) { |
| 1641 | throw new Error( 'key must be a non-empty string' ); |
| 1642 | } |
| 1643 | |
| 1644 | // Parent method |
| 1645 | OO.Factory.super.prototype.register.call( this, key, constructor ); |
| 1646 | }; |
| 1647 | |
| 1648 | /** |
| 1649 | * Unregister a class from the factory. |
| 1650 | * |
| 1651 | * @param {string|Function} key Constructor function or key to unregister |
| 1652 | * @throws {Error} If a parameter is invalid |
| 1653 | */ |
| 1654 | OO.Factory.prototype.unregister = function ( key ) { |
| 1655 | if ( typeof key === 'function' ) { |
| 1656 | key = key.key || ( key.static && key.static.name ); |
| 1657 | } |
| 1658 | if ( typeof key !== 'string' || key === '' ) { |
| 1659 | throw new Error( 'key must be a non-empty string' ); |
| 1660 | } |
| 1661 | |
| 1662 | // Parent method |
| 1663 | OO.Factory.super.prototype.unregister.call( this, key ); |
| 1664 | }; |
| 1665 | |
| 1666 | /** |
| 1667 | * Create an object based on a key. |
| 1668 | * |
| 1669 | * The key is used to look up the class to use, with any subsequent arguments passed to the |
| 1670 | * constructor function. |
| 1671 | * |
| 1672 | * @param {string} key Class key |
| 1673 | * @param {...any} [args] Arguments to pass to the constructor |
| 1674 | * @return {Object} The new object |
| 1675 | * @throws {Error} Unknown key |
| 1676 | */ |
| 1677 | OO.Factory.prototype.create = function ( key, ...args ) { |
| 1678 | var constructor = this.lookup( key ); |
| 1679 | if ( !constructor ) { |
| 1680 | throw new Error( 'No class registered by that key: ' + key ); |
| 1681 | } |
| 1682 | |
| 1683 | return new constructor( ...args ); |
| 1684 | }; |
| 1685 | |
| 1686 | /* eslint-env node */ |
| 1687 | |
| 1688 | /* istanbul ignore next */ |
| 1689 | if ( typeof module !== 'undefined' && module.exports ) { |
| 1690 | module.exports = OO; |
| 1691 | } else { |
| 1692 | global.OO = OO; |
| 1693 | } |
| 1694 | |
| 1695 | }( this ) ); |