| 1 | /*! |
| 2 | * VisualEditor utilities. |
| 3 | * |
| 4 | * @copyright See AUTHORS.txt |
| 5 | */ |
| 6 | |
| 7 | /** |
| 8 | * Checks if an object is an instance of one or more classes. |
| 9 | * |
| 10 | * @param {Object} subject Object to check |
| 11 | * @param {Function[]} classes Classes to compare with |
| 12 | * @return {boolean} Object inherits from one or more of the classes |
| 13 | */ |
| 14 | ve.isInstanceOfAny = function ( subject, classes ) { |
| 15 | let i = classes.length; |
| 16 | |
| 17 | while ( classes[ --i ] ) { |
| 18 | if ( subject instanceof classes[ i ] ) { |
| 19 | return true; |
| 20 | } |
| 21 | } |
| 22 | return false; |
| 23 | }; |
| 24 | |
| 25 | /** |
| 26 | * Get a deeply nested property of an object using variadic arguments, protecting against |
| 27 | * undefined property errors. |
| 28 | * |
| 29 | * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;` |
| 30 | * except that the former protects against JS errors if one of the intermediate properties |
| 31 | * is undefined. Instead of throwing an error, this function will return undefined in |
| 32 | * that case. |
| 33 | * |
| 34 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 35 | * |
| 36 | * @method |
| 37 | * @param {Object} obj |
| 38 | * @param {...any} [keys] |
| 39 | * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined |
| 40 | */ |
| 41 | ve.getProp = OO.getProp; |
| 42 | |
| 43 | /** |
| 44 | * Set a deeply nested property of an object using variadic arguments, protecting against |
| 45 | * undefined property errors. |
| 46 | * |
| 47 | * `OO.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that |
| 48 | * the former protects against JS errors if one of the intermediate properties is |
| 49 | * undefined. Instead of throwing an error, undefined intermediate properties will be |
| 50 | * initialized to an empty object. If an intermediate property is not an object, or if obj itself |
| 51 | * is not an object, this function will silently abort. |
| 52 | * |
| 53 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 54 | * |
| 55 | * @method |
| 56 | * @param {Object} obj |
| 57 | * @param {...any} [keys] |
| 58 | * @param {any} [value] |
| 59 | */ |
| 60 | ve.setProp = OO.setProp; |
| 61 | |
| 62 | /** |
| 63 | * Delete a deeply nested property of an object using variadic arguments, protecting against |
| 64 | * undefined property errors, and deleting resulting empty objects. |
| 65 | * |
| 66 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 67 | * |
| 68 | * @method |
| 69 | * @param {Object} obj |
| 70 | * @param {...any} [keys] |
| 71 | */ |
| 72 | ve.deleteProp = OO.deleteProp; |
| 73 | |
| 74 | /** |
| 75 | * Create a new object that is an instance of the same |
| 76 | * constructor as the input, inherits from the same object |
| 77 | * and contains the same own properties. |
| 78 | * |
| 79 | * This makes a shallow non-recursive copy of own properties. |
| 80 | * To create a recursive copy of plain objects, use #copy. |
| 81 | * |
| 82 | * var foo = new Person( mom, dad ); |
| 83 | * foo.setAge( 21 ); |
| 84 | * var foo2 = OO.cloneObject( foo ); |
| 85 | * foo.setAge( 22 ); |
| 86 | * |
| 87 | * // Then |
| 88 | * foo2 !== foo; // true |
| 89 | * foo2 instanceof Person; // true |
| 90 | * foo2.getAge(); // 21 |
| 91 | * foo.getAge(); // 22 |
| 92 | * |
| 93 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 94 | * |
| 95 | * @method |
| 96 | * @param {Object} origin |
| 97 | * @return {Object} Clone of origin |
| 98 | */ |
| 99 | ve.cloneObject = OO.cloneObject; |
| 100 | |
| 101 | /** |
| 102 | * Get an array of all property values in an object. |
| 103 | * |
| 104 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 105 | * |
| 106 | * @method |
| 107 | * @param {Object} obj Object to get values from |
| 108 | * @return {Array} List of object values |
| 109 | */ |
| 110 | ve.getObjectValues = OO.getObjectValues; |
| 111 | |
| 112 | /** |
| 113 | * Use binary search to locate an element in a sorted array. |
| 114 | * |
| 115 | * searchFunc is given an element from the array. `searchFunc(elem)` must return a number |
| 116 | * above 0 if the element we're searching for is to the right of (has a higher index than) elem, |
| 117 | * below 0 if it is to the left of elem, or zero if it's equal to elem. |
| 118 | * |
| 119 | * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns |
| 120 | * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use |
| 121 | * `searchFunc = cmp.bind( null, value )`. |
| 122 | * |
| 123 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 124 | * |
| 125 | * @method |
| 126 | * @param {Array} arr Array to search in |
| 127 | * @param {Function} searchFunc Search function |
| 128 | * @param {boolean} [forInsertion] If not found, return index where val could be inserted |
| 129 | * @return {number|null} Index where val was found, or null if not found |
| 130 | */ |
| 131 | ve.binarySearch = OO.binarySearch; |
| 132 | |
| 133 | /** |
| 134 | * Recursively compare properties between two objects. |
| 135 | * |
| 136 | * A false result may be caused by property inequality or by properties in one object missing from |
| 137 | * the other. An asymmetrical test may also be performed, which checks only that properties in the |
| 138 | * first object are present in the second object, but not the inverse. |
| 139 | * |
| 140 | * If either a or b is null or undefined it will be treated as an empty object. |
| 141 | * |
| 142 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 143 | * |
| 144 | * @method |
| 145 | * @param {Object|undefined|null} a First object to compare |
| 146 | * @param {Object|undefined|null} b Second object to compare |
| 147 | * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's |
| 148 | * (i.e. a is a subset of b) |
| 149 | * @return {boolean} If the objects contain the same values as each other |
| 150 | */ |
| 151 | ve.compare = OO.compare; |
| 152 | |
| 153 | /** |
| 154 | * Create a plain deep copy of any kind of object. |
| 155 | * |
| 156 | * Copies are deep, and will either be an object or an array depending on `source`. |
| 157 | * |
| 158 | * See https://doc.wikimedia.org/oojs/master/OO.html |
| 159 | * |
| 160 | * @method |
| 161 | * @param {Object} source Object to copy |
| 162 | * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are |
| 163 | * added to the clone |
| 164 | * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the |
| 165 | * nodeCallback returns a value other than undefined, the returned value is used instead of |
| 166 | * attempting to clone. |
| 167 | * @return {Object} Copy of source object |
| 168 | */ |
| 169 | ve.copy = OO.copy; |
| 170 | |
| 171 | /** |
| 172 | * @method |
| 173 | * @see OO.ui.debounce |
| 174 | */ |
| 175 | ve.debounce = OO.ui.debounce; |
| 176 | |
| 177 | /** |
| 178 | * @method |
| 179 | * @see OO.ui.throttle |
| 180 | */ |
| 181 | ve.throttle = OO.ui.throttle; |
| 182 | |
| 183 | /** |
| 184 | * Create a jQuery.Deferred-compatible object |
| 185 | * |
| 186 | * See http://api.jquery.com/jQuery.Deferred/ |
| 187 | * |
| 188 | * @method |
| 189 | * @return {jQuery.Deferred} |
| 190 | */ |
| 191 | ve.createDeferred = $.Deferred; |
| 192 | |
| 193 | /** |
| 194 | * Create a promise which resolves when the list of promises has resolved |
| 195 | * |
| 196 | * @param {jQuery.Promise[]} promises List of promises |
| 197 | * @return {jQuery.Promise} Promise which resolves when the list of promises has resolved |
| 198 | */ |
| 199 | ve.promiseAll = function ( promises ) { |
| 200 | return $.when.apply( $, promises ); |
| 201 | }; |
| 202 | |
| 203 | /** |
| 204 | * Copy an array of DOM elements, optionally into a different document. |
| 205 | * |
| 206 | * @param {HTMLElement[]} domElements DOM elements to copy |
| 207 | * @param {HTMLDocument} [doc] Document to create the copies in; if unset, simply clone each element |
| 208 | * @return {HTMLElement[]} Copy of domElements with copies of each element |
| 209 | */ |
| 210 | ve.copyDomElements = function ( domElements, doc ) { |
| 211 | return domElements.map( ( domElement ) => doc ? doc.importNode( domElement, true ) : domElement.cloneNode( true ) ); |
| 212 | }; |
| 213 | |
| 214 | /** |
| 215 | * Check if two arrays of DOM elements are equal (according to .isEqualNode()) |
| 216 | * |
| 217 | * @param {HTMLElement[]} domElements1 First array of DOM elements |
| 218 | * @param {HTMLElement[]} domElements2 Second array of DOM elements |
| 219 | * @return {boolean} All elements are pairwise equal |
| 220 | */ |
| 221 | ve.isEqualDomElements = function ( domElements1, domElements2 ) { |
| 222 | let i = 0; |
| 223 | const len = domElements1.length; |
| 224 | if ( len !== domElements2.length ) { |
| 225 | return false; |
| 226 | } |
| 227 | for ( ; i < len; i++ ) { |
| 228 | if ( !domElements1[ i ].isEqualNode( domElements2[ i ] ) ) { |
| 229 | return false; |
| 230 | } |
| 231 | } |
| 232 | return true; |
| 233 | }; |
| 234 | |
| 235 | /** |
| 236 | * Compare two class lists, either whitespace separated strings or arrays |
| 237 | * |
| 238 | * Class lists are equivalent if they contain the same members, |
| 239 | * excluding duplicates and ignoring order. |
| 240 | * |
| 241 | * @param {string[]|string} classList1 First class list |
| 242 | * @param {string[]|string} classList2 Second class list |
| 243 | * @return {boolean} Class lists are equivalent |
| 244 | */ |
| 245 | ve.compareClassLists = function ( classList1, classList2 ) { |
| 246 | const removeEmpty = function ( c ) { |
| 247 | return c !== ''; |
| 248 | }; |
| 249 | |
| 250 | classList1 = Array.isArray( classList1 ) ? classList1 : classList1.trim().split( /\s+/ ); |
| 251 | classList2 = Array.isArray( classList2 ) ? classList2 : classList2.trim().split( /\s+/ ); |
| 252 | |
| 253 | classList1 = classList1.filter( removeEmpty ); |
| 254 | classList2 = classList2.filter( removeEmpty ); |
| 255 | |
| 256 | return ve.compare( OO.unique( classList1 ).sort(), OO.unique( classList2 ).sort() ); |
| 257 | }; |
| 258 | |
| 259 | /** |
| 260 | * Check to see if an object is a plain object (created using "{}" or "new Object"). |
| 261 | * |
| 262 | * See http://api.jquery.com/jQuery.isPlainObject/ |
| 263 | * |
| 264 | * @method |
| 265 | * @param {Object} obj The object that will be checked to see if it's a plain object |
| 266 | * @return {boolean} |
| 267 | */ |
| 268 | ve.isPlainObject = $.isPlainObject; |
| 269 | |
| 270 | /** |
| 271 | * Check to see if an object is empty (contains no properties). |
| 272 | * |
| 273 | * See http://api.jquery.com/jQuery.isEmptyObject/ |
| 274 | * |
| 275 | * @method |
| 276 | * @param {Object} obj The object that will be checked to see if it's empty |
| 277 | * @return {boolean} |
| 278 | */ |
| 279 | ve.isEmptyObject = $.isEmptyObject; |
| 280 | |
| 281 | /** |
| 282 | * Merge properties of one or more objects into another. |
| 283 | * Preserves original object's inheritance (e.g. Array, Object, whatever). |
| 284 | * In case of array or array-like objects only the indexed properties |
| 285 | * are copied over. |
| 286 | * Beware: If called with only one argument, it will consider |
| 287 | * 'target' as 'source' and 'this' as 'target'. Which means |
| 288 | * ve.extendObject( { a: 1 } ); sets ve.a = 1; |
| 289 | * |
| 290 | * See http://api.jquery.com/jQuery.extend/ |
| 291 | * |
| 292 | * @method |
| 293 | * @param {boolean} [recursive=false] |
| 294 | * @param {any} [target] Object that will receive the new properties |
| 295 | * @param {...any} [sources] Variadic list of objects containing properties |
| 296 | * to be merged into the target. |
| 297 | * @return {any} Modified version of first or second argument |
| 298 | */ |
| 299 | ve.extendObject = $.extend; |
| 300 | |
| 301 | /** |
| 302 | * Splice one array into another. |
| 303 | * |
| 304 | * This is the equivalent of arr.splice( offset, remove, d1, d2, d3, … ) except that arguments are |
| 305 | * specified as an array rather than separate parameters. |
| 306 | * |
| 307 | * This method has been proven to be faster than using slice and concat to create a new array, but |
| 308 | * performance tests should be conducted on each use of this method to verify this is true for the |
| 309 | * particular use. Also, browsers change fast, never assume anything, always test everything. |
| 310 | * |
| 311 | * Includes a replacement for broken implementations of Array.prototype.splice(). |
| 312 | * |
| 313 | * @param {Array|ve.dm.BranchNode} arr Target object (must have `splice` method, object will be modified) |
| 314 | * @param {number} offset Offset in arr to splice at. This MUST NOT be negative, unlike the |
| 315 | * 'index' parameter in Array#splice. |
| 316 | * @param {number} remove Number of elements to remove at the offset. May be zero |
| 317 | * @param {Array} data Array of items to insert at the offset. Must be non-empty if remove=0 |
| 318 | * @return {Array} Array of items removed |
| 319 | */ |
| 320 | ve.batchSplice = function ( arr, offset, remove, data ) { |
| 321 | // We need to splice insertion in in batches, because of parameter list length limits which vary |
| 322 | // cross-browser - 1024 seems to be a safe batch size on all browsers |
| 323 | let index = 0, |
| 324 | toRemove = remove, |
| 325 | removed = []; |
| 326 | const batchSize = 1024; |
| 327 | |
| 328 | if ( data.length === 0 ) { |
| 329 | // Special case: data is empty, so we're just doing a removal |
| 330 | // The code below won't handle that properly, so we do it here |
| 331 | return arr.splice( offset, remove ); |
| 332 | } |
| 333 | |
| 334 | while ( index < data.length ) { |
| 335 | // Call arr.splice( offset, remove, i0, i1, i2, …, i1023 ); |
| 336 | // Only set remove on the first call, and set it to zero on subsequent calls |
| 337 | const spliced = arr.splice( |
| 338 | index + offset, toRemove, ...data.slice( index, index + batchSize ) |
| 339 | ); |
| 340 | if ( toRemove > 0 ) { |
| 341 | removed = spliced; |
| 342 | } |
| 343 | index += batchSize; |
| 344 | toRemove = 0; |
| 345 | } |
| 346 | return removed; |
| 347 | }; |
| 348 | |
| 349 | /** |
| 350 | * Splice one array into another, replicating any holes |
| 351 | * |
| 352 | * Similar to arr.splice( offset, remove, ...data ), except holes in |
| 353 | * data remain holes in arr. Optimized for length changes that are negative, zero, or |
| 354 | * fairly small positive. |
| 355 | * |
| 356 | * @param {Array} arr Array to modify |
| 357 | * @param {number} offset Offset in arr to splice at. This MUST NOT be negative, unlike the |
| 358 | * 'index' parameter in Array#splice. |
| 359 | * @param {number} remove Number of elements to remove at the offset. May be zero |
| 360 | * @param {Array} data Array of items to insert at the offset |
| 361 | * @return {Array} Array of items removed, with holes preserved |
| 362 | */ |
| 363 | ve.sparseSplice = function ( arr, offset, remove, data ) { |
| 364 | const removed = [], |
| 365 | endOffset = offset + remove, |
| 366 | diff = data.length - remove; |
| 367 | if ( data === arr ) { |
| 368 | // Pathological case: arr and data are reference-identical |
| 369 | data = data.slice(); |
| 370 | } |
| 371 | // Remove content without adjusting length |
| 372 | arr.slice( offset, endOffset ).forEach( ( item, j ) => { |
| 373 | removed[ j ] = item; |
| 374 | delete arr[ offset + j ]; |
| 375 | } ); |
| 376 | // Adjust length |
| 377 | if ( diff > 0 ) { |
| 378 | // Grow with undefined values, then delete. (This is optimised for diff |
| 379 | // comparatively small: otherwise, it would sometimes be quicker to relocate |
| 380 | // each element of arr that lies above offset). |
| 381 | ve.batchSplice( arr, endOffset, 0, new Array( diff ) ); |
| 382 | for ( let i = endOffset + diff - 1; i >= endOffset; i-- ) { |
| 383 | delete arr[ i ]; |
| 384 | } |
| 385 | } else if ( diff < 0 ) { |
| 386 | // Shrink |
| 387 | arr.splice( offset, -diff ); |
| 388 | } |
| 389 | // Insert new content |
| 390 | data.forEach( ( item, j ) => { |
| 391 | arr[ offset + j ] = item; |
| 392 | } ); |
| 393 | // Set removed.length in case there are holes at the end |
| 394 | removed.length = remove; |
| 395 | return removed; |
| 396 | }; |
| 397 | |
| 398 | /** |
| 399 | * Insert one array into another. |
| 400 | * |
| 401 | * Shortcut for `ve.batchSplice( arr, offset, 0, src )`. |
| 402 | * |
| 403 | * @see ve.batchSplice |
| 404 | * @param {Array|ve.dm.BranchNode} arr Target object (must have `splice` method) |
| 405 | * @param {number} offset Offset in arr where items will be inserted |
| 406 | * @param {Array} src Items to insert at offset |
| 407 | */ |
| 408 | ve.insertIntoArray = function ( arr, offset, src ) { |
| 409 | ve.batchSplice( arr, offset, 0, src ); |
| 410 | }; |
| 411 | |
| 412 | /** |
| 413 | * Push one array into another. |
| 414 | * |
| 415 | * This is the equivalent of arr.push( d1, d2, d3, … ) except that arguments are |
| 416 | * specified as an array rather than separate parameters. |
| 417 | * |
| 418 | * @param {Array|ve.dm.BranchNode} arr Object supporting .push() to insert at the end of the array. Will be modified |
| 419 | * @param {Array} data Array of items to insert. |
| 420 | * @return {number} length of the new array |
| 421 | */ |
| 422 | ve.batchPush = function ( arr, data ) { |
| 423 | // We need to push insertion in batches, because of parameter list length limits which vary |
| 424 | // cross-browser - 1024 seems to be a safe batch size on all browsers |
| 425 | let index = 0; |
| 426 | const batchSize = 1024; |
| 427 | if ( batchSize >= data.length ) { |
| 428 | // Avoid slicing for small lists |
| 429 | return arr.push( ...data ); |
| 430 | } |
| 431 | let length; |
| 432 | while ( index < data.length ) { |
| 433 | // Call arr.push( i0, i1, i2, …, i1023 ); |
| 434 | length = arr.push( ...data.slice( index, index + batchSize ) ); |
| 435 | index += batchSize; |
| 436 | } |
| 437 | return length; |
| 438 | }; |
| 439 | |
| 440 | /** |
| 441 | * Log data to the console. |
| 442 | * |
| 443 | * This implementation does nothing, to add a real implementation ve.debug needs to be loaded. |
| 444 | * |
| 445 | * @param {...any} [args] Data to log |
| 446 | */ |
| 447 | ve.log = ve.log || function () { |
| 448 | // Don't do anything, this is just a stub |
| 449 | }; |
| 450 | |
| 451 | /** |
| 452 | * Log error to the console. |
| 453 | * |
| 454 | * This implementation does nothing, to add a real implementation ve.debug needs to be loaded. |
| 455 | * |
| 456 | * @param {...any} [args] Data to log |
| 457 | */ |
| 458 | ve.error = ve.error || function () { |
| 459 | // Don't do anything, this is just a stub |
| 460 | }; |
| 461 | |
| 462 | /** |
| 463 | * Log an object to the console. |
| 464 | * |
| 465 | * This implementation does nothing, to add a real implementation ve.debug needs to be loaded. |
| 466 | * |
| 467 | * @param {Object} obj |
| 468 | */ |
| 469 | ve.dir = ve.dir || function () { |
| 470 | // Don't do anything, this is just a stub |
| 471 | }; |
| 472 | |
| 473 | /** |
| 474 | * Deep freeze an object, making it immutable |
| 475 | * |
| 476 | * This implementation does nothing, to add a real implementation ve.freeze needs to be loaded. |
| 477 | * |
| 478 | * @param {Object} obj |
| 479 | * @param {boolean} onlyProperties |
| 480 | * @return {Object} |
| 481 | */ |
| 482 | ve.deepFreeze = ve.deepFreeze || function ( obj ) { |
| 483 | // Don't do anything, this is just a stub |
| 484 | return obj; |
| 485 | }; |
| 486 | |
| 487 | /** |
| 488 | * Get a localized message. |
| 489 | * |
| 490 | * @param {string} key Message key |
| 491 | * @param {...any} [params] Message parameters |
| 492 | * @return {string} Localized message |
| 493 | */ |
| 494 | ve.msg = function () { |
| 495 | // Avoid using bind because ve.init.platform doesn't exist yet. |
| 496 | // TODO: Fix dependency issues between ve.js and ve.init.platform |
| 497 | return ve.init.platform.getMessage.apply( ve.init.platform, arguments ); |
| 498 | }; |
| 499 | |
| 500 | /** |
| 501 | * Get an HTML localized message with HTML or DOM arguments. |
| 502 | * |
| 503 | * @param {string} key Message key |
| 504 | * @param {...any} [params] Message parameters |
| 505 | * @return {Node[]} Localized message |
| 506 | */ |
| 507 | ve.htmlMsg = function () { |
| 508 | // Avoid using bind because ve.init.platform doesn't exist yet. |
| 509 | // TODO: Fix dependency issues between ve.js and ve.init.platform |
| 510 | return ve.init.platform.getHtmlMessage.apply( ve.init.platform, arguments ); |
| 511 | }; |
| 512 | |
| 513 | /** |
| 514 | * Get platform config value(s) |
| 515 | * |
| 516 | * @param {string|string[]} key Config key, or list of keys |
| 517 | * @return {any|Object} Config value, or keyed object of config values if list of keys provided |
| 518 | */ |
| 519 | ve.config = function () { |
| 520 | return ve.init.platform.getConfig.apply( ve.init.platform, arguments ); |
| 521 | }; |
| 522 | |
| 523 | /** |
| 524 | * Get or set a user config value. |
| 525 | * |
| 526 | * @param {string|string[]|Object} key Config key, list of keys or object mapping keys to values |
| 527 | * @param {any} [value] Value to set, if setting and key is a string |
| 528 | * @return {any|Object|boolean} Config value, keyed object of config values if list of keys provided, |
| 529 | * or success boolean if setting. |
| 530 | */ |
| 531 | ve.userConfig = function ( key ) { |
| 532 | if ( arguments.length <= 1 && ( typeof key === 'string' || Array.isArray( key ) ) ) { |
| 533 | // get( string key ) |
| 534 | // get( Array keys ) |
| 535 | return ve.init.platform.getUserConfig.apply( ve.init.platform, arguments ); |
| 536 | } else { |
| 537 | // set( Object values ) |
| 538 | // set( key, value ) |
| 539 | return ve.init.platform.setUserConfig.apply( ve.init.platform, arguments ); |
| 540 | } |
| 541 | }; |
| 542 | |
| 543 | /** |
| 544 | * Convert a grapheme cluster offset to a byte offset. |
| 545 | * |
| 546 | * @param {string} text Text in which to calculate offset |
| 547 | * @param {number} clusterOffset Grapheme cluster offset |
| 548 | * @return {number} Byte offset |
| 549 | */ |
| 550 | ve.getByteOffset = function ( text, clusterOffset ) { |
| 551 | return unicodeJS.graphemebreak.splitClusters( text ) |
| 552 | .slice( 0, clusterOffset ) |
| 553 | .join( '' ) |
| 554 | .length; |
| 555 | }; |
| 556 | |
| 557 | /** |
| 558 | * Convert a byte offset to a grapheme cluster offset. |
| 559 | * |
| 560 | * @param {string} text Text in which to calculate offset |
| 561 | * @param {number} byteOffset Byte offset |
| 562 | * @return {number} Grapheme cluster offset |
| 563 | */ |
| 564 | ve.getClusterOffset = function ( text, byteOffset ) { |
| 565 | return unicodeJS.graphemebreak.splitClusters( text.slice( 0, byteOffset ) ).length; |
| 566 | }; |
| 567 | |
| 568 | /** |
| 569 | * Get a text substring, taking care not to split grapheme clusters. |
| 570 | * |
| 571 | * @param {string} text Text to take the substring from |
| 572 | * @param {number} start Start offset |
| 573 | * @param {number} end End offset |
| 574 | * @param {boolean} [outer=false] Include graphemes if the offset splits them |
| 575 | * @return {string} Substring of text |
| 576 | */ |
| 577 | ve.graphemeSafeSubstring = function ( text, start, end, outer ) { |
| 578 | // TODO: improve performance by incrementally inspecting characters around the offsets |
| 579 | let unicodeStart = ve.getByteOffset( text, ve.getClusterOffset( text, start ) ), |
| 580 | unicodeEnd = ve.getByteOffset( text, ve.getClusterOffset( text, end ) ); |
| 581 | |
| 582 | // If the selection collapses and we want an inner, then just return empty |
| 583 | // otherwise we'll end up crossing over start and end |
| 584 | if ( unicodeStart === unicodeEnd && !outer ) { |
| 585 | return ''; |
| 586 | } |
| 587 | |
| 588 | // The above calculations always move to the right of a multibyte grapheme. |
| 589 | // Depending on the outer flag, we may want to move to the left: |
| 590 | if ( unicodeStart > start && outer ) { |
| 591 | unicodeStart = ve.getByteOffset( text, ve.getClusterOffset( text, start ) - 1 ); |
| 592 | } |
| 593 | if ( unicodeEnd > end && !outer ) { |
| 594 | unicodeEnd = ve.getByteOffset( text, ve.getClusterOffset( text, end ) - 1 ); |
| 595 | } |
| 596 | return text.slice( unicodeStart, unicodeEnd ); |
| 597 | }; |
| 598 | |
| 599 | /** |
| 600 | * Escape non-word characters so they can be safely used as HTML attribute values. |
| 601 | * |
| 602 | * @param {string} value Attribute value to escape |
| 603 | * @return {string} Escaped attribute value |
| 604 | */ |
| 605 | ve.escapeHtml = ( function () { |
| 606 | function escape( value ) { |
| 607 | switch ( value ) { |
| 608 | case '\'': |
| 609 | return '''; |
| 610 | case '"': |
| 611 | return '"'; |
| 612 | case '<': |
| 613 | return '<'; |
| 614 | case '>': |
| 615 | return '>'; |
| 616 | case '&': |
| 617 | return '&'; |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | return function ( value ) { |
| 622 | return value.replace( /['"<>&]/g, escape ); |
| 623 | }; |
| 624 | }() ); |
| 625 | |
| 626 | /** |
| 627 | * Get the attributes of a DOM element as an object with key/value pairs. |
| 628 | * |
| 629 | * @param {HTMLElement} element |
| 630 | * @return {Object} |
| 631 | */ |
| 632 | ve.getDomAttributes = function ( element ) { |
| 633 | const result = {}; |
| 634 | for ( let i = 0; i < element.attributes.length; i++ ) { |
| 635 | result[ element.attributes[ i ].name ] = element.attributes[ i ].value; |
| 636 | } |
| 637 | return result; |
| 638 | }; |
| 639 | |
| 640 | /** |
| 641 | * Set the attributes of a DOM element as an object with key/value pairs. |
| 642 | * |
| 643 | * Use the `null` or `undefined` value to ensure an attribute's absence. |
| 644 | * |
| 645 | * @param {HTMLElement} element DOM element to apply attributes to |
| 646 | * @param {Object} attributes Attributes to apply |
| 647 | * @param {string[]} [allowedAttributes] List of attributes to exclusively allow (all lowercase names) |
| 648 | */ |
| 649 | ve.setDomAttributes = function ( element, attributes, allowedAttributes ) { |
| 650 | // Duck-typing for attribute setting |
| 651 | if ( !element.setAttribute || !element.removeAttribute ) { |
| 652 | return; |
| 653 | } |
| 654 | for ( const key in attributes ) { |
| 655 | if ( allowedAttributes && allowedAttributes.indexOf( key.toLowerCase() ) === -1 ) { |
| 656 | continue; |
| 657 | } |
| 658 | if ( attributes[ key ] === undefined || attributes[ key ] === null ) { |
| 659 | element.removeAttribute( key ); |
| 660 | } else { |
| 661 | element.setAttribute( key, attributes[ key ] ); |
| 662 | } |
| 663 | } |
| 664 | }; |
| 665 | |
| 666 | /** |
| 667 | * Get an HTML representation of a DOM element node, text node or comment node |
| 668 | * |
| 669 | * @param {Node} node The DOM node |
| 670 | * @return {string} HTML representation of the node |
| 671 | */ |
| 672 | ve.getNodeHtml = function ( node ) { |
| 673 | if ( node.nodeType === Node.ELEMENT_NODE ) { |
| 674 | return node.outerHTML; |
| 675 | } else { |
| 676 | const div = document.createElement( 'div' ); |
| 677 | div.appendChild( node.cloneNode( true ) ); |
| 678 | return div.innerHTML; |
| 679 | } |
| 680 | }; |
| 681 | |
| 682 | /** |
| 683 | * Build a summary of an HTML element. |
| 684 | * |
| 685 | * Summaries include node name, text, attributes and recursive summaries of children. |
| 686 | * Used for serializing or comparing HTML elements. |
| 687 | * |
| 688 | * @private |
| 689 | * @param {HTMLElement} element Element to summarize |
| 690 | * @param {boolean} [includeHtml=false] Include an HTML summary for element nodes |
| 691 | * @param {Function} [getAttributeSummary] Callback to modify the summary of an attribute |
| 692 | * @param {string} [getAttributeSummary.name] Name of the attribute to modify. |
| 693 | * @param {string} [getAttributeSummary.value] Value to return for the given attribute. |
| 694 | * @return {Object} Summary of element. |
| 695 | */ |
| 696 | ve.getDomElementSummary = function ( element, includeHtml, getAttributeSummary ) { |
| 697 | const summary = { |
| 698 | type: element.nodeName.toLowerCase(), |
| 699 | text: element.textContent, |
| 700 | attributes: {}, |
| 701 | children: [] |
| 702 | }; |
| 703 | |
| 704 | if ( includeHtml && element.nodeType === Node.ELEMENT_NODE ) { |
| 705 | summary.html = element.outerHTML; |
| 706 | } |
| 707 | |
| 708 | // Gather attributes |
| 709 | if ( element.attributes ) { |
| 710 | for ( let i = 0; i < element.attributes.length; i++ ) { |
| 711 | const name = element.attributes[ i ].name; |
| 712 | if ( name === 'about' ) { |
| 713 | // The about attribute is non-deterministic as we generate a new random |
| 714 | // one whenever a node is cloned (see ve.dm.Node.static.cloneElement). |
| 715 | // Exclude it from node comparisons. |
| 716 | continue; |
| 717 | } |
| 718 | const value = element.attributes[ i ].value; |
| 719 | summary.attributes[ name ] = getAttributeSummary ? getAttributeSummary( name, value ) : value; |
| 720 | } |
| 721 | } |
| 722 | // Summarize children |
| 723 | if ( element.childNodes ) { |
| 724 | for ( let i = 0; i < element.childNodes.length; i++ ) { |
| 725 | summary.children.push( ve.getDomElementSummary( element.childNodes[ i ], includeHtml ) ); |
| 726 | } |
| 727 | } |
| 728 | return summary; |
| 729 | }; |
| 730 | |
| 731 | /** |
| 732 | * Callback for #copy to convert nodes to a comparable summary. |
| 733 | * |
| 734 | * @private |
| 735 | * @param {Object} value Value in the object/array |
| 736 | * @return {Object} DOM element summary if value is a node, otherwise just the value |
| 737 | */ |
| 738 | ve.convertDomElements = function ( value ) { |
| 739 | // Use duck typing rather than instanceof Node; the latter doesn't always work correctly |
| 740 | if ( value && value.nodeType ) { |
| 741 | return ve.getDomElementSummary( value ); |
| 742 | } |
| 743 | return value; |
| 744 | }; |
| 745 | |
| 746 | ve.visibleWhitespaceCharacters = { |
| 747 | '\n': '\u21b5', // ↵ |
| 748 | '\t': '\u279e' // âžž |
| 749 | }; |
| 750 | |
| 751 | /** |
| 752 | * Check whether a given node is contentEditable |
| 753 | * |
| 754 | * Handles 'inherit', via checking isContentEditable. Knows to check for text |
| 755 | * nodes, and will return whether the text node's parent is contentEditable. |
| 756 | * |
| 757 | * @param {HTMLElement|Text} node Node to check contenteditable status of |
| 758 | * @return {boolean} Node is contenteditable |
| 759 | */ |
| 760 | ve.isContentEditable = function ( node ) { |
| 761 | return ( node.nodeType === Node.TEXT_NODE ? node.parentNode : node ).isContentEditable; |
| 762 | }; |
| 763 | |
| 764 | /** |
| 765 | * Filter out metadata elements |
| 766 | * |
| 767 | * @param {Node[]} contents DOM nodes |
| 768 | * @return {Node[]} Filtered DOM nodes |
| 769 | */ |
| 770 | ve.filterMetaElements = function ( contents ) { |
| 771 | // Filter out link and style tags for T52043 |
| 772 | // Previously filtered out meta tags, but restore these as they |
| 773 | // can be made visible with CSS. |
| 774 | // As of jQuery 3 we can't use $.not( 'tagName' ) as that doesn't |
| 775 | // match text nodes. Also we can't $.remove these elements as they |
| 776 | // aren't attached to anything. |
| 777 | contents = contents.filter( ( node ) => node.tagName !== 'LINK' && node.tagName !== 'STYLE' ); |
| 778 | // Also remove link and style tags nested inside other tags |
| 779 | $( contents ).find( 'link, style' ).remove(); |
| 780 | return contents; |
| 781 | }; |
| 782 | |
| 783 | /** |
| 784 | * Modify a set of DOM elements to resolve attributes in the context of another document. |
| 785 | * |
| 786 | * This performs node.setAttribute( 'attr', nodeInDoc[attr] ); for every node. |
| 787 | * |
| 788 | * Doesn't use jQuery to avoid document switching performance bug |
| 789 | * |
| 790 | * @param {HTMLElement|HTMLElement[]|NodeList|jQuery} elementsOrJQuery Set of DOM elements to modify. Passing a jQuery selector is deprecated. |
| 791 | * @param {HTMLDocument} doc Document to resolve against (different from $elements' .ownerDocument) |
| 792 | * @param {string[]} attrs Attributes to resolve |
| 793 | */ |
| 794 | ve.resolveAttributes = function ( elementsOrJQuery, doc, attrs ) { |
| 795 | // Convert jQuery selections to plain arrays |
| 796 | let elements = elementsOrJQuery.toArray ? elementsOrJQuery.toArray() : elementsOrJQuery; |
| 797 | |
| 798 | // Duck typing for array or NodeList :( |
| 799 | if ( elements.length === undefined ) { |
| 800 | elements = [ elements ]; |
| 801 | } |
| 802 | |
| 803 | let attr; |
| 804 | |
| 805 | /** |
| 806 | * Resolves the value of attr to the computed property value. |
| 807 | * |
| 808 | * @private |
| 809 | * @param {HTMLElement} el Element |
| 810 | */ |
| 811 | function resolveAttribute( el ) { |
| 812 | const nodeInDoc = doc.createElement( el.nodeName ); |
| 813 | nodeInDoc.setAttribute( attr, el.getAttribute( attr ) ); |
| 814 | if ( nodeInDoc[ attr ] ) { |
| 815 | el.setAttribute( attr, nodeInDoc[ attr ] ); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | for ( let i = 0, iLen = elements.length; i < iLen; i++ ) { |
| 820 | const element = elements[ i ]; |
| 821 | for ( let j = 0, jLen = attrs.length; j < jLen; j++ ) { |
| 822 | attr = attrs[ j ]; |
| 823 | if ( element.hasAttribute( attr ) ) { |
| 824 | resolveAttribute( element ); |
| 825 | } |
| 826 | Array.prototype.forEach.call( element.querySelectorAll( '[' + attr + ']' ), resolveAttribute ); |
| 827 | } |
| 828 | } |
| 829 | }; |
| 830 | |
| 831 | /** |
| 832 | * Make all links within a DOM element open in a new window |
| 833 | * |
| 834 | * @param {HTMLElement} container DOM element to search for links |
| 835 | */ |
| 836 | ve.targetLinksToNewWindow = function ( container ) { |
| 837 | // Make all links open in a new window |
| 838 | Array.prototype.forEach.call( container.querySelectorAll( 'a[href]' ), ( el ) => { |
| 839 | ve.appendToRel( el, 'noopener' ); |
| 840 | el.setAttribute( 'target', '_blank' ); |
| 841 | } ); |
| 842 | }; |
| 843 | |
| 844 | /** |
| 845 | * Add a value to an element's rel attribute if it's not already present |
| 846 | * |
| 847 | * Rel is like class: it's actually a set, represented as a string. We don't |
| 848 | * want to add the same value to the attribute if this function is called |
| 849 | * repeatedly. This is mostly a placeholder for the relList property someday |
| 850 | * becoming widely supported. |
| 851 | * |
| 852 | * @param {HTMLElement} element DOM element whose attribute should be checked |
| 853 | * @param {string} value New rel value to be added |
| 854 | */ |
| 855 | ve.appendToRel = function ( element, value ) { |
| 856 | const rel = element.getAttribute( 'rel' ); |
| 857 | if ( !rel ) { |
| 858 | // Avoid all that string-creation if it's not needed |
| 859 | element.setAttribute( 'rel', value ); |
| 860 | } else if ( ( ' ' + rel + ' ' ).indexOf( ' ' + value + ' ' ) === -1 ) { |
| 861 | element.setAttribute( 'rel', rel + ' ' + value ); |
| 862 | } |
| 863 | }; |
| 864 | |
| 865 | /** |
| 866 | * Check if a string is a valid URI component. |
| 867 | * |
| 868 | * A URI component is considered invalid if decodeURIComponent() throws an exception. |
| 869 | * |
| 870 | * @param {string} s String to test |
| 871 | * @return {boolean} decodeURIComponent( s ) did not throw an exception |
| 872 | * @see ve.safeDecodeURIComponent |
| 873 | */ |
| 874 | ve.isUriComponentValid = function ( s ) { |
| 875 | try { |
| 876 | decodeURIComponent( s ); |
| 877 | } catch ( e ) { |
| 878 | return false; |
| 879 | } |
| 880 | return true; |
| 881 | }; |
| 882 | |
| 883 | /** |
| 884 | * Safe version of decodeURIComponent() that doesn't throw exceptions. |
| 885 | * |
| 886 | * If the native decodeURIComponent() call threw an exception, the original string |
| 887 | * will be returned. |
| 888 | * |
| 889 | * @param {string} s String to decode |
| 890 | * @return {string} Decoded string, or same string if decoding failed |
| 891 | * @see ve.isUriComponentValid |
| 892 | */ |
| 893 | ve.safeDecodeURIComponent = function ( s ) { |
| 894 | try { |
| 895 | s = decodeURIComponent( s ); |
| 896 | } catch ( e ) {} |
| 897 | return s; |
| 898 | }; |
| 899 | |
| 900 | /** |
| 901 | * Find the length of the common start sequence of one or more sequences |
| 902 | * |
| 903 | * Items are tested for sameness using === . |
| 904 | * |
| 905 | * @param {Array} sequences Array of sequences (arrays, strings etc) |
| 906 | * @return {number} Common start sequence length (0 if sequences is empty) |
| 907 | */ |
| 908 | ve.getCommonStartSequenceLength = function ( sequences ) { |
| 909 | if ( sequences.length === 0 ) { |
| 910 | return 0; |
| 911 | } |
| 912 | let commonLength = 0; |
| 913 | commonLengthLoop: |
| 914 | while ( true ) { |
| 915 | if ( commonLength >= sequences[ 0 ].length ) { |
| 916 | break; |
| 917 | } |
| 918 | const val = sequences[ 0 ][ commonLength ]; |
| 919 | for ( let i = 1, len = sequences.length; i < len; i++ ) { |
| 920 | if ( |
| 921 | sequences[ i ].length <= commonLength || |
| 922 | sequences[ i ][ commonLength ] !== val |
| 923 | ) { |
| 924 | break commonLengthLoop; |
| 925 | } |
| 926 | } |
| 927 | commonLength++; |
| 928 | } |
| 929 | return commonLength; |
| 930 | }; |
| 931 | |
| 932 | /** |
| 933 | * Find the nearest common ancestor of DOM nodes |
| 934 | * |
| 935 | * @param {...Node|null} nodes DOM nodes |
| 936 | * @return {Node|null} Nearest common ancestor; or null if there is none / an argument is null |
| 937 | */ |
| 938 | ve.getCommonAncestor = function ( ...nodes ) { |
| 939 | const nodeCount = nodes.length; |
| 940 | if ( nodeCount === 0 ) { |
| 941 | return null; |
| 942 | } |
| 943 | let minHeight = null; |
| 944 | const chains = []; |
| 945 | // Build every chain |
| 946 | for ( let i = 0; i < nodeCount; i++ ) { |
| 947 | const chain = []; |
| 948 | let node = nodes[ i ]; |
| 949 | while ( node !== null ) { |
| 950 | chain.unshift( node ); |
| 951 | node = node.parentNode; |
| 952 | } |
| 953 | if ( chain.length === 0 ) { |
| 954 | // nodes[ i ] was null (so no common ancestor) |
| 955 | return null; |
| 956 | } |
| 957 | if ( i > 0 && chain[ 0 ] !== chains[ chains.length - 1 ][ 0 ] ) { |
| 958 | // No common ancestor (different documents or unattached branches) |
| 959 | return null; |
| 960 | } |
| 961 | if ( minHeight === null || minHeight > chain.length ) { |
| 962 | minHeight = chain.length; |
| 963 | } |
| 964 | chains.push( chain ); |
| 965 | } |
| 966 | |
| 967 | // Step through chains in parallel, until they differ. |
| 968 | // All chains are guaranteed to start with the common document element (or the common root |
| 969 | // of an unattached branch) |
| 970 | for ( let i = 1; i < minHeight; i++ ) { |
| 971 | const node = chains[ 0 ][ i ]; |
| 972 | for ( let j = 1; j < nodeCount; j++ ) { |
| 973 | if ( node !== chains[ j ][ i ] ) { |
| 974 | return chains[ 0 ][ i - 1 ]; |
| 975 | } |
| 976 | } |
| 977 | } |
| 978 | return chains[ 0 ][ minHeight - 1 ]; |
| 979 | }; |
| 980 | |
| 981 | /** |
| 982 | * Get the index of a node in its parentNode's childNode list |
| 983 | * |
| 984 | * @param {Node} node The node |
| 985 | * @return {number} Index in parentNode's childNode list |
| 986 | */ |
| 987 | ve.parentIndex = function ( node ) { |
| 988 | return Array.prototype.indexOf.call( node.parentNode.childNodes, node ); |
| 989 | }; |
| 990 | |
| 991 | /** |
| 992 | * Get the offset path from ancestor to offset in descendant |
| 993 | * |
| 994 | * @param {Node} ancestor The ancestor node |
| 995 | * @param {Node} node The descendant node |
| 996 | * @param {number} nodeOffset The offset in the descendant node |
| 997 | * @return {number[]} The offset path |
| 998 | */ |
| 999 | ve.getOffsetPath = function ( ancestor, node, nodeOffset ) { |
| 1000 | const path = [ nodeOffset ]; |
| 1001 | while ( node !== ancestor ) { |
| 1002 | if ( node.parentNode === null ) { |
| 1003 | ve.log( node, 'is not a descendant of', ancestor ); |
| 1004 | throw new Error( 'Not a descendant' ); |
| 1005 | } |
| 1006 | path.unshift( ve.parentIndex( node ) ); |
| 1007 | node = node.parentNode; |
| 1008 | } |
| 1009 | return path; |
| 1010 | }; |
| 1011 | |
| 1012 | /** |
| 1013 | * Compare two tuples in lexicographical order. |
| 1014 | * |
| 1015 | * This function first compares `a[0]` with `b[0]`, then `a[1]` with `b[1]`, etc. |
| 1016 | * until it encounters a pair where `a[k] != b[k]`; then returns `a[k] - b[k]`. |
| 1017 | * |
| 1018 | * If `a[k] == b[k]` for every `k`, this function returns 0. |
| 1019 | * |
| 1020 | * If a and b are of unequal length, but `a[k] == b[k]` for all `k` that exist in both a and b, then |
| 1021 | * this function returns `Infinity` (if a is longer) or `-Infinity` (if b is longer). |
| 1022 | * |
| 1023 | * @param {number[]} a First tuple |
| 1024 | * @param {number[]} b Second tuple |
| 1025 | * @return {number} `a[k] - b[k]` where k is the lowest k such that `a[k] != b[k]` |
| 1026 | */ |
| 1027 | ve.compareTuples = function ( a, b ) { |
| 1028 | for ( let i = 0, len = Math.min( a.length, b.length ); i < len; i++ ) { |
| 1029 | if ( a[ i ] !== b[ i ] ) { |
| 1030 | return a[ i ] - b[ i ]; |
| 1031 | } |
| 1032 | } |
| 1033 | if ( a.length > b.length ) { |
| 1034 | return Infinity; |
| 1035 | } |
| 1036 | if ( a.length < b.length ) { |
| 1037 | return -Infinity; |
| 1038 | } |
| 1039 | return 0; |
| 1040 | }; |
| 1041 | |
| 1042 | /** |
| 1043 | * Compare two nodes for position in document |
| 1044 | * |
| 1045 | * Return null if either position is either null or incomparable (e.g. where one of the nodes |
| 1046 | * is detached or the nodes are from different documents). |
| 1047 | * |
| 1048 | * @param {Node|null} node1 First node |
| 1049 | * @param {number|null} offset1 First offset |
| 1050 | * @param {Node|null} node2 Second node |
| 1051 | * @param {number|null} offset2 Second offset |
| 1052 | * @return {number|null} negative, zero or positive number, or null if nodes null or incomparable |
| 1053 | */ |
| 1054 | ve.compareDocumentOrder = function ( node1, offset1, node2, offset2 ) { |
| 1055 | const commonAncestor = ve.getCommonAncestor( node1, node2 ); |
| 1056 | if ( commonAncestor === null ) { |
| 1057 | // Signal no common ancestor. In theory we could disallow this case, and check |
| 1058 | // the nodes for detachedness and same-documentness before each call, but such |
| 1059 | // guard checks would duplicate (either explicitly or implicitly) much of the |
| 1060 | // branch traversal performed in this method. |
| 1061 | return null; |
| 1062 | } |
| 1063 | return ve.compareTuples( |
| 1064 | ve.getOffsetPath( commonAncestor, node1, offset1 ), |
| 1065 | ve.getOffsetPath( commonAncestor, node2, offset2 ) |
| 1066 | ); |
| 1067 | }; |
| 1068 | |
| 1069 | /** |
| 1070 | * @typedef {Object} DomPosition |
| 1071 | * @memberof ve |
| 1072 | * @property {Node|null} node The node, or null if we stepped past the root node |
| 1073 | * @property {number|null} offset The offset, or null if we stepped past the root node |
| 1074 | * @property {ve.PositionStep[]} steps Steps taken |
| 1075 | */ |
| 1076 | |
| 1077 | /** |
| 1078 | * Get the closest matching DOM position in document order (forward or reverse) |
| 1079 | * |
| 1080 | * A DOM position is represented as an object with "node" and "offset" properties. |
| 1081 | * |
| 1082 | * The noDescend option can be used to exclude the positions inside certain element nodes; it is |
| 1083 | * a jQuery selector/function ( used as a test by $node.is() - see http://api.jquery.com/is/ ); |
| 1084 | * it defaults to ve.rejectsCursor . Void elements (those matching ve.isVoidElement) are always |
| 1085 | * excluded. |
| 1086 | * |
| 1087 | * As well as the end position, an array of ve.PositionSteps (node traversals) is returned. |
| 1088 | * The "stop" option is a boolean-valued function used to test each ve.PositionStep in turn. If |
| 1089 | * If it returns true, the position arrived at is returned; else the stepping continues to the |
| 1090 | * next matching DOM position. It defaults to ve.isHardCursorStep . |
| 1091 | * |
| 1092 | * Limitation: some DOM positions cannot actually hold the cursor; e.g. the start of the interior |
| 1093 | * of a table node. Browser cursoring jumps over text node/annotation node boundaries as if they |
| 1094 | * were invisible, and skips over most grapheme clusters e.g. 'x\u0301' (though not all e.g. |
| 1095 | * '\u062D\u0627'). Also, Chromium normalizes cursor focus/offset, when they are set, to the |
| 1096 | * start-most such cursor position (Firefox does not). |
| 1097 | * |
| 1098 | * @param {Object} position Start position |
| 1099 | * @param {Node} position.node Start node |
| 1100 | * @param {number} position.offset Start offset |
| 1101 | * @param {number} direction +1 for forward, -1 for reverse |
| 1102 | * @param {Object} options |
| 1103 | * @param {Function|string} [options.noDescend] Selector or function: nodes to skip over |
| 1104 | * @param {Function} [options.stop] Boolean-valued ve.PositionStep test function |
| 1105 | * @return {ve.DomPosition} The adjacent DOM position encountered |
| 1106 | * @see ve.isHardCursorStep |
| 1107 | */ |
| 1108 | ve.adjacentDomPosition = function ( position, direction, options ) { |
| 1109 | let node = position.node, |
| 1110 | offset = position.offset; |
| 1111 | const steps = []; |
| 1112 | |
| 1113 | const noDescend = options.noDescend || ve.rejectsCursor; |
| 1114 | const stop = options.stop || ve.isHardCursorStep; |
| 1115 | |
| 1116 | direction = direction < 0 ? -1 : 1; |
| 1117 | const forward = ( direction === 1 ); |
| 1118 | |
| 1119 | while ( true ) { |
| 1120 | // If we're at the node's leading edge, move to the adjacent position in the parent node |
| 1121 | if ( offset === ( forward ? node.length || node.childNodes.length : 0 ) ) { |
| 1122 | const step = new ve.PositionStep( node, 'leave' ); |
| 1123 | steps.push( step ); |
| 1124 | if ( node.parentNode === null ) { |
| 1125 | return { |
| 1126 | node: null, |
| 1127 | offset: null, |
| 1128 | steps: steps |
| 1129 | }; |
| 1130 | } |
| 1131 | offset = ve.parentIndex( node ) + ( forward ? 1 : 0 ); |
| 1132 | node = node.parentNode; |
| 1133 | if ( stop( step ) ) { |
| 1134 | return { |
| 1135 | node: node, |
| 1136 | offset: offset, |
| 1137 | steps: steps |
| 1138 | }; |
| 1139 | } |
| 1140 | // Else take another step |
| 1141 | continue; |
| 1142 | } |
| 1143 | // Else we're in the interior of a node |
| 1144 | |
| 1145 | // If we're in a text node, move to the position in this node at the next offset |
| 1146 | if ( node.nodeType === Node.TEXT_NODE ) { |
| 1147 | const step = new ve.PositionStep( |
| 1148 | node, |
| 1149 | 'internal', |
| 1150 | offset - ( forward ? 0 : 1 ) |
| 1151 | ); |
| 1152 | steps.push( step ); |
| 1153 | offset += direction; |
| 1154 | if ( stop( step ) ) { |
| 1155 | return { |
| 1156 | node: node, |
| 1157 | offset: offset, |
| 1158 | steps: steps |
| 1159 | }; |
| 1160 | } |
| 1161 | continue; |
| 1162 | } |
| 1163 | // Else we're in the interior of an element node |
| 1164 | |
| 1165 | const childNode = node.childNodes[ forward ? offset : offset - 1 ]; |
| 1166 | |
| 1167 | // Support: Firefox |
| 1168 | // If the child is uncursorable, or is an element matching noDescend, do not |
| 1169 | // descend into it: instead, return the position just beyond it in the current node |
| 1170 | if ( |
| 1171 | childNode.nodeType === Node.ELEMENT_NODE && |
| 1172 | ( ve.isVoidElement( childNode ) || $( childNode ).is( noDescend ) ) |
| 1173 | ) { |
| 1174 | const step = new ve.PositionStep( childNode, 'cross' ); |
| 1175 | steps.push( step ); |
| 1176 | offset += forward ? 1 : -1; |
| 1177 | if ( stop( step ) ) { |
| 1178 | return { |
| 1179 | node: node, |
| 1180 | offset: offset, |
| 1181 | steps: steps |
| 1182 | }; |
| 1183 | } |
| 1184 | // Else take another step |
| 1185 | continue; |
| 1186 | } |
| 1187 | |
| 1188 | // Go to the closest offset inside the child node |
| 1189 | node = childNode; |
| 1190 | offset = forward ? 0 : node.length || node.childNodes.length; |
| 1191 | const posStep = new ve.PositionStep( node, 'enter' ); |
| 1192 | steps.push( posStep ); |
| 1193 | if ( stop( posStep ) ) { |
| 1194 | return { |
| 1195 | node: node, |
| 1196 | offset: offset, |
| 1197 | steps: steps |
| 1198 | }; |
| 1199 | } |
| 1200 | } |
| 1201 | }; |
| 1202 | |
| 1203 | /** |
| 1204 | * Test whether a cursor movement step uses up a cursor press |
| 1205 | * |
| 1206 | * Essentially, this is true unless entering/exiting a contentEditable text/annotation node. |
| 1207 | * For instance in <#text>X</#text><b><#text>y</#text></b> |
| 1208 | * a single cursor press will jump from just after X to just after Y. |
| 1209 | * |
| 1210 | * @param {ve.PositionStep} step The cursor movement step to test |
| 1211 | * @return {boolean} Whether the cursor movement step uses up a cursor press |
| 1212 | * @see ve.adjacentDomPosition |
| 1213 | */ |
| 1214 | ve.isHardCursorStep = function ( step ) { |
| 1215 | if ( step.node.nodeType === Node.TEXT_NODE ) { |
| 1216 | return step.type === 'internal'; |
| 1217 | } |
| 1218 | return ve.isBlockElement( step.node ) || ve.rejectsCursor( step.node ); |
| 1219 | }; |
| 1220 | |
| 1221 | /** |
| 1222 | * Tests whether an adjacent cursor would be prevented from entering the node |
| 1223 | * |
| 1224 | * @param {Node} [node] Element node or text node; defaults to "this" if a Node |
| 1225 | * @return {boolean} Whether an adjacent cursor would be prevented from entering |
| 1226 | */ |
| 1227 | ve.rejectsCursor = function ( node ) { |
| 1228 | if ( !node && this instanceof Node ) { |
| 1229 | node = this; |
| 1230 | } |
| 1231 | if ( node.nodeType === node.TEXT_NODE ) { |
| 1232 | return false; |
| 1233 | } |
| 1234 | if ( ve.isVoidElement( node ) ) { |
| 1235 | return true; |
| 1236 | } |
| 1237 | // We don't need to check whether the ancestor-nearest contenteditable tag is |
| 1238 | // false, because if so then there can be no adjacent cursor. |
| 1239 | return node.contentEditable === 'false'; |
| 1240 | }; |
| 1241 | |
| 1242 | /** |
| 1243 | * @typedef {Object} ChangeOffsets |
| 1244 | * @memberof ve |
| 1245 | * @return {number} start Offset from start of first changed element |
| 1246 | * @return {number} end Offset from end of last changed element (nonoverlapping with start) |
| 1247 | */ |
| 1248 | |
| 1249 | /** |
| 1250 | * Count the common elements at the start and end of two sequences |
| 1251 | * |
| 1252 | * @param {Array|string} before The original sequence |
| 1253 | * @param {Array|string} after The modified sequence |
| 1254 | * @param {Function} [equals] Two-argument comparison returning boolean (defaults to ===) |
| 1255 | * @return {ve.ChangeOffsets|null} Change offsets (valid in both sequences), or null if unchanged |
| 1256 | */ |
| 1257 | ve.countEdgeMatches = function ( before, after, equals ) { |
| 1258 | if ( !equals ) { |
| 1259 | equals = function ( x, y ) { |
| 1260 | return x === y; |
| 1261 | }; |
| 1262 | } |
| 1263 | |
| 1264 | let start, end; |
| 1265 | const len = Math.min( before.length, after.length ); |
| 1266 | // Find maximal matching left slice |
| 1267 | for ( start = 0; start < len; start++ ) { |
| 1268 | if ( !equals( before[ start ], after[ start ] ) ) { |
| 1269 | break; |
| 1270 | } |
| 1271 | } |
| 1272 | if ( start === len && before.length === after.length ) { |
| 1273 | return null; |
| 1274 | } |
| 1275 | // Find maximal matching right slice that doesn't overlap the left slice |
| 1276 | for ( end = 0; end < len - start; end++ ) { |
| 1277 | if ( !equals( |
| 1278 | before[ before.length - 1 - end ], |
| 1279 | after[ after.length - 1 - end ] |
| 1280 | ) ) { |
| 1281 | break; |
| 1282 | } |
| 1283 | } |
| 1284 | return { start: start, end: end }; |
| 1285 | }; |
| 1286 | |
| 1287 | /** |
| 1288 | * Same as Object.entries, because we don't yet presume ES2017 |
| 1289 | * |
| 1290 | * @param {Object} ob The object |
| 1291 | * @return {Array[]} Entries, in the form [string, any] |
| 1292 | */ |
| 1293 | // eslint-disable-next-line es-x/no-object-entries |
| 1294 | ve.entries = Object.entries || ( ( ob ) => Object.keys( ob ).map( ( k ) => [ k, ob[ k ] ] ) ); |