1/** 2 * @licstart The following is the entire license notice for the 3 * JavaScript code in this page 4 * 5 * Copyright 2024 Mozilla Foundation 6 * 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 * 19 * @licend The above is the entire license notice for the 20 * JavaScript code in this page 21 */ 22 23/** 24 * pdfjsVersion = 5.5.207 25 * pdfjsBuild = 527964698 26 */ 27/******/ var __webpack_modules__ = ({ 28 29/***/ 9306 30(module, __unused_webpack_exports, __webpack_require__) { 31 32 33var isCallable = __webpack_require__(4901); 34var tryToString = __webpack_require__(6823); 35 36var $TypeError = TypeError; 37 38// `Assert: IsCallable(argument) is true` 39module.exports = function (argument) { 40 if (isCallable(argument)) return argument; 41 throw new $TypeError(tryToString(argument) + ' is not a function'); 42}; 43 44 45/***/ }, 46 47/***/ 6194 48(module, __unused_webpack_exports, __webpack_require__) { 49 50 51var has = (__webpack_require__(2248).has); 52 53// Perform ? RequireInternalSlot(M, [[MapData]]) 54module.exports = function (it) { 55 has(it); 56 return it; 57}; 58 59 60/***/ }, 61 62/***/ 3506 63(module, __unused_webpack_exports, __webpack_require__) { 64 65 66var isPossiblePrototype = __webpack_require__(3925); 67 68var $String = String; 69var $TypeError = TypeError; 70 71module.exports = function (argument) { 72 if (isPossiblePrototype(argument)) return argument; 73 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype'); 74}; 75 76 77/***/ }, 78 79/***/ 7080 80(module, __unused_webpack_exports, __webpack_require__) { 81 82 83var has = (__webpack_require__(4402).has); 84 85// Perform ? RequireInternalSlot(M, [[SetData]]) 86module.exports = function (it) { 87 has(it); 88 return it; 89}; 90 91 92/***/ }, 93 94/***/ 3463 95(module) { 96 97 98var $TypeError = TypeError; 99 100module.exports = function (argument) { 101 if (typeof argument == 'string') return argument; 102 throw new $TypeError('Argument is not a string'); 103}; 104 105 106/***/ }, 107 108/***/ 4328 109(module, __unused_webpack_exports, __webpack_require__) { 110 111 112var WeakMapHelpers = __webpack_require__(4995); 113 114var weakmap = new WeakMapHelpers.WeakMap(); 115var set = WeakMapHelpers.set; 116var remove = WeakMapHelpers.remove; 117 118module.exports = function (key) { 119 set(weakmap, key, 1); 120 remove(weakmap, key); 121 return key; 122}; 123 124 125/***/ }, 126 127/***/ 6557 128(module, __unused_webpack_exports, __webpack_require__) { 129 130 131var has = (__webpack_require__(4995).has); 132 133// Perform ? RequireInternalSlot(M, [[WeakMapData]]) 134module.exports = function (it) { 135 has(it); 136 return it; 137}; 138 139 140/***/ }, 141 142/***/ 679 143(module, __unused_webpack_exports, __webpack_require__) { 144 145 146var isPrototypeOf = __webpack_require__(1625); 147 148var $TypeError = TypeError; 149 150module.exports = function (it, Prototype) { 151 if (isPrototypeOf(Prototype, it)) return it; 152 throw new $TypeError('Incorrect invocation'); 153}; 154 155 156/***/ }, 157 158/***/ 3972 159(module, __unused_webpack_exports, __webpack_require__) { 160 161 162var isObject = __webpack_require__(34); 163 164var $String = String; 165var $TypeError = TypeError; 166 167module.exports = function (argument) { 168 if (argument === undefined || isObject(argument)) return argument; 169 throw new $TypeError($String(argument) + ' is not an object or undefined'); 170}; 171 172 173/***/ }, 174 175/***/ 8551 176(module, __unused_webpack_exports, __webpack_require__) { 177 178 179var isObject = __webpack_require__(34); 180 181var $String = String; 182var $TypeError = TypeError; 183 184// `Assert: Type(argument) is Object` 185module.exports = function (argument) { 186 if (isObject(argument)) return argument; 187 throw new $TypeError($String(argument) + ' is not an object'); 188}; 189 190 191/***/ }, 192 193/***/ 4154 194(module, __unused_webpack_exports, __webpack_require__) { 195 196 197var classof = __webpack_require__(6955); 198 199var $TypeError = TypeError; 200 201// Perform ? RequireInternalSlot(argument, [[TypedArrayName]]) 202// If argument.[[TypedArrayName]] is not "Uint8Array", throw a TypeError exception 203module.exports = function (argument) { 204 if (classof(argument) === 'Uint8Array') return argument; 205 throw new $TypeError('Argument is not an Uint8Array'); 206}; 207 208 209/***/ }, 210 211/***/ 7811 212(module) { 213 214 215// eslint-disable-next-line es/no-typed-arrays -- safe 216module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined'; 217 218 219/***/ }, 220 221/***/ 7394 222(module, __unused_webpack_exports, __webpack_require__) { 223 224 225var globalThis = __webpack_require__(4576); 226var uncurryThisAccessor = __webpack_require__(6706); 227var classof = __webpack_require__(2195); 228 229var ArrayBuffer = globalThis.ArrayBuffer; 230var TypeError = globalThis.TypeError; 231 232// Includes
vendor: 5,034 bytes, lines 233-370
233// - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). 234// - If IsSharedArrayBuffer(O) is true, throw a TypeError exception. 235module.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) { 236 if (classof(O) !== 'ArrayBuffer') throw new TypeError('ArrayBuffer expected'); 237 return O.byteLength; 238}; 239 240 241/***/ }, 242 243/***/ 3238 244(module, __unused_webpack_exports, __webpack_require__) { 245 246 247var globalThis = __webpack_require__(4576); 248var NATIVE_ARRAY_BUFFER = __webpack_require__(7811); 249var arrayBufferByteLength = __webpack_require__(7394); 250 251var DataView = globalThis.DataView; 252 253module.exports = function (O) { 254 if (!NATIVE_ARRAY_BUFFER || arrayBufferByteLength(O) !== 0) return false; 255 try { 256 // eslint-disable-next-line no-new -- thrower 257 new DataView(O); 258 return false; 259 } catch (error) { 260 return true; 261 } 262}; 263 264 265/***/ }, 266 267/***/ 5169 268(module, __unused_webpack_exports, __webpack_require__) { 269 270 271var isDetached = __webpack_require__(3238); 272 273var $TypeError = TypeError; 274 275module.exports = function (it) { 276 if (isDetached(it)) throw new $TypeError('ArrayBuffer is detached'); 277 return it; 278}; 279 280 281/***/ }, 282 283/***/ 5636 284(module, __unused_webpack_exports, __webpack_require__) { 285 286 287var globalThis = __webpack_require__(4576); 288var uncurryThis = __webpack_require__(9504); 289var uncurryThisAccessor = __webpack_require__(6706); 290var toIndex = __webpack_require__(7696); 291var notDetached = __webpack_require__(5169); 292var arrayBufferByteLength = __webpack_require__(7394); 293var detachTransferable = __webpack_require__(4483); 294var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548); 295 296var structuredClone = globalThis.structuredClone; 297var ArrayBuffer = globalThis.ArrayBuffer; 298var DataView = globalThis.DataView; 299var min = Math.min; 300var ArrayBufferPrototype = ArrayBuffer.prototype; 301var DataViewPrototype = DataView.prototype; 302var slice = uncurryThis(ArrayBufferPrototype.slice); 303var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get'); 304var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get'); 305var getInt8 = uncurryThis(DataViewPrototype.getInt8); 306var setInt8 = uncurryThis(DataViewPrototype.setInt8); 307 308module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) { 309 var byteLength = arrayBufferByteLength(arrayBuffer); 310 var newByteLength = newLength === undefined ? byteLength : toIndex(newLength); 311 var fixedLength = !isResizable || !isResizable(arrayBuffer); 312 var newBuffer; 313 notDetached(arrayBuffer); 314 if (PROPER_STRUCTURED_CLONE_TRANSFER) { 315 arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] }); 316 if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer; 317 } 318 if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) { 319 newBuffer = slice(arrayBuffer, 0, newByteLength); 320 } else { 321 var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined; 322 newBuffer = new ArrayBuffer(newByteLength, options); 323 var a = new DataView(arrayBuffer); 324 var b = new DataView(newBuffer); 325 var copyLength = min(newByteLength, byteLength); 326 for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i)); 327 } 328 if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer); 329 return newBuffer; 330}; 331 332 333/***/ }, 334 335/***/ 4644 336(module, __unused_webpack_exports, __webpack_require__) { 337 338 339var NATIVE_ARRAY_BUFFER = __webpack_require__(7811); 340var DESCRIPTORS = __webpack_require__(3724); 341var globalThis = __webpack_require__(4576); 342var isCallable = __webpack_require__(4901); 343var isObject = __webpack_require__(34); 344var hasOwn = __webpack_require__(9297); 345var classof = __webpack_require__(6955); 346var tryToString = __webpack_require__(6823); 347var createNonEnumerableProperty = __webpack_require__(6699); 348var defineBuiltIn = __webpack_require__(6840); 349var defineBuiltInAccessor = __webpack_require__(2106); 350var isPrototypeOf = __webpack_require__(1625); 351var getPrototypeOf = __webpack_require__(2787); 352var setPrototypeOf = __webpack_require__(2967); 353var wellKnownSymbol = __webpack_require__(8227); 354var uid = __webpack_require__(3392); 355var InternalStateModule = __webpack_require__(1181); 356 357var enforceInternalState = InternalStateModule.enforce; 358var getInternalState = InternalStateModule.get; 359var Int8Array = globalThis.Int8Array; 360var Int8ArrayPrototype = Int8Array && Int8Array.prototype; 361var Uint8ClampedArray = globalThis.Uint8ClampedArray; 362var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; 363var TypedArray = Int8Array && getPrototypeOf(Int8Array); 364var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); 365var ObjectPrototype = Object.prototype; 366var TypeError = globalThis.TypeError; 367 368var TO_STRING_TAG = wellKnownSymbol('toStringTag'); 369var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); 370var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
vendor: 7,178 bytes, lines 371-575
371// Fixing native typed arrays in Opera Presto crashes the browser, see #595 372var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== 'Opera'; 373var TYPED_ARRAY_TAG_REQUIRED = false; 374var NAME, Constructor, Prototype; 375 376var TypedArrayConstructorsList = { 377 Int8Array: 1, 378 Uint8Array: 1, 379 Uint8ClampedArray: 1, 380 Int16Array: 2, 381 Uint16Array: 2, 382 Int32Array: 4, 383 Uint32Array: 4, 384 Float32Array: 4, 385 Float64Array: 8 386}; 387 388var BigIntArrayConstructorsList = { 389 BigInt64Array: 8, 390 BigUint64Array: 8 391}; 392 393var isView = function isView(it) { 394 if (!isObject(it)) return false; 395 var klass = classof(it); 396 return klass === 'DataView' 397 || hasOwn(TypedArrayConstructorsList, klass) 398 || hasOwn(BigIntArrayConstructorsList, klass); 399}; 400 401var getTypedArrayConstructor = function (it) { 402 var proto = getPrototypeOf(it); 403 if (!isObject(proto)) return; 404 var state = getInternalState(proto); 405 return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto); 406}; 407 408var isTypedArray = function (it) { 409 if (!isObject(it)) return false; 410 var klass = classof(it); 411 return hasOwn(TypedArrayConstructorsList, klass) 412 || hasOwn(BigIntArrayConstructorsList, klass); 413}; 414 415var aTypedArray = function (it) { 416 if (isTypedArray(it)) return it; 417 throw new TypeError('Target is not a typed array'); 418}; 419 420var aTypedArrayConstructor = function (C) { 421 if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C; 422 throw new TypeError(tryToString(C) + ' is not a typed array constructor'); 423}; 424 425var exportTypedArrayMethod = function (KEY, property, forced, options) { 426 if (!DESCRIPTORS) return; 427 if (forced) for (var ARRAY in TypedArrayConstructorsList) { 428 var TypedArrayConstructor = globalThis[ARRAY]; 429 if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try { 430 delete TypedArrayConstructor.prototype[KEY]; 431 } catch (error) { 432 // old WebKit bug - some methods are non-configurable 433 try { 434 TypedArrayConstructor.prototype[KEY] = property; 435 } catch (error2) { /* empty */ } 436 } 437 } 438 if (!TypedArrayPrototype[KEY] || forced) { 439 defineBuiltIn(TypedArrayPrototype, KEY, forced ? property 440 : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options); 441 } 442}; 443 444var exportTypedArrayStaticMethod = function (KEY, property, forced) { 445 var ARRAY, TypedArrayConstructor; 446 if (!DESCRIPTORS) return; 447 if (setPrototypeOf) { 448 if (forced) for (ARRAY in TypedArrayConstructorsList) { 449 TypedArrayConstructor = globalThis[ARRAY]; 450 if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try { 451 delete TypedArrayConstructor[KEY]; 452 } catch (error) { /* empty */ } 453 } 454 if (!TypedArray[KEY] || forced) { 455 // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable 456 try { 457 return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property); 458 } catch (error) { /* empty */ } 459 } else return; 460 } 461 for (ARRAY in TypedArrayConstructorsList) { 462 TypedArrayConstructor = globalThis[ARRAY]; 463 if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { 464 defineBuiltIn(TypedArrayConstructor, KEY, property); 465 } 466 } 467}; 468 469for (NAME in TypedArrayConstructorsList) { 470 Constructor = globalThis[NAME]; 471 Prototype = Constructor && Constructor.prototype; 472 if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; 473 else NATIVE_ARRAY_BUFFER_VIEWS = false; 474} 475 476for (NAME in BigIntArrayConstructorsList) { 477 Constructor = globalThis[NAME]; 478 Prototype = Constructor && Constructor.prototype; 479 if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; 480} 481 482// WebKit bug - typed arrays constructors prototype is Object.prototype 483if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) { 484 // eslint-disable-next-line no-shadow -- safe 485 TypedArray = function TypedArray() { 486 throw new TypeError('Incorrect invocation'); 487 }; 488 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { 489 if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray); 490 } 491} 492 493if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { 494 TypedArrayPrototype = TypedArray.prototype; 495 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { 496 if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype); 497 } 498} 499 500// WebKit bug - one more object in Uint8ClampedArray prototype chain 501if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { 502 setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); 503} 504 505if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) { 506 TYPED_ARRAY_TAG_REQUIRED = true; 507 defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, { 508 configurable: true, 509 get: function () { 510 return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; 511 } 512 }); 513 for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) { 514 createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME); 515 } 516} 517 518module.exports = { 519 NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, 520 TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG, 521 aTypedArray: aTypedArray, 522 aTypedArrayConstructor: aTypedArrayConstructor, 523 exportTypedArrayMethod: exportTypedArrayMethod, 524 exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, 525 getTypedArrayConstructor: getTypedArrayConstructor, 526 isView: isView, 527 isTypedArray: isTypedArray, 528 TypedArray: TypedArray, 529 TypedArrayPrototype: TypedArrayPrototype 530}; 531 532 533/***/ }, 534 535/***/ 5370 536(module, __unused_webpack_exports, __webpack_require__) { 537 538 539var lengthOfArrayLike = __webpack_require__(6198); 540 541module.exports = function (Constructor, list, $length) { 542 var index = 0; 543 var length = arguments.length > 2 ? $length : lengthOfArrayLike(list); 544 var result = new Constructor(length); 545 while (length > index) result[index] = list[index++]; 546 return result; 547}; 548 549 550/***/ }, 551 552/***/ 9617 553(module, __unused_webpack_exports, __webpack_require__) { 554 555 556var toIndexedObject = __webpack_require__(5397); 557var toAbsoluteIndex = __webpack_require__(5610); 558var lengthOfArrayLike = __webpack_require__(6198); 559 560// `Array.prototype.{ indexOf, includes }` methods implementation 561var createMethod = function (IS_INCLUDES) { 562 return function ($this, el, fromIndex) { 563 var O = toIndexedObject($this); 564 var length = lengthOfArrayLike(O); 565 if (length === 0) return !IS_INCLUDES && -1; 566 var index = toAbsoluteIndex(fromIndex, length); 567 var value; 568 // Array#includes uses SameValueZero equality algorithm 569 // eslint-disable-next-line no-self-compare -- NaN check 570 if (IS_INCLUDES && el !== el) while (length > index) { 571 value = O[index++]; 572 // eslint-disable-next-line no-self-compare -- NaN check 573 if (value !== value) return true; 574 // Array#indexOf ignores holes, Array#includes - not 575 } else for (;length > index; index++) {
vendor: 9,389 bytes, lines 576-950
576 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; 577 } return !IS_INCLUDES && -1; 578 }; 579}; 580 581module.exports = { 582 // `Array.prototype.includes` method 583 // https://tc39.es/ecma262/#sec-array.prototype.includes 584 includes: createMethod(true), 585 // `Array.prototype.indexOf` method 586 // https://tc39.es/ecma262/#sec-array.prototype.indexof 587 indexOf: createMethod(false) 588}; 589 590 591/***/ }, 592 593/***/ 4527 594(module, __unused_webpack_exports, __webpack_require__) { 595 596 597var DESCRIPTORS = __webpack_require__(3724); 598var isArray = __webpack_require__(4376); 599 600var $TypeError = TypeError; 601// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 602var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 603 604// Safari < 13 does not throw an error in this case 605var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () { 606 // makes no sense without proper strict mode support 607 if (this !== undefined) return true; 608 try { 609 // eslint-disable-next-line es/no-object-defineproperty -- safe 610 Object.defineProperty([], 'length', { writable: false }).length = 1; 611 } catch (error) { 612 return error instanceof TypeError; 613 } 614}(); 615 616module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) { 617 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) { 618 throw new $TypeError('Cannot set read only .length'); 619 } return O.length = length; 620} : function (O, length) { 621 return O.length = length; 622}; 623 624 625/***/ }, 626 627/***/ 7680 628(module, __unused_webpack_exports, __webpack_require__) { 629 630 631var uncurryThis = __webpack_require__(9504); 632 633module.exports = uncurryThis([].slice); 634 635 636/***/ }, 637 638/***/ 2804 639(module) { 640 641 642var commonAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 643var base64Alphabet = commonAlphabet + '+/'; 644var base64UrlAlphabet = commonAlphabet + '-_'; 645 646var inverse = function (characters) { 647 // TODO: use `Object.create(null)` in `core-js@4` 648 var result = {}; 649 var index = 0; 650 for (; index < 64; index++) result[characters.charAt(index)] = index; 651 return result; 652}; 653 654module.exports = { 655 i2c: base64Alphabet, 656 c2i: inverse(base64Alphabet), 657 i2cUrl: base64UrlAlphabet, 658 c2iUrl: inverse(base64UrlAlphabet) 659}; 660 661 662/***/ }, 663 664/***/ 6319 665(module, __unused_webpack_exports, __webpack_require__) { 666 667 668var anObject = __webpack_require__(8551); 669var iteratorClose = __webpack_require__(9539); 670 671// call something on iterator step with safe closing on error 672module.exports = function (iterator, fn, value, ENTRIES) { 673 try { 674 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); 675 } catch (error) { 676 iteratorClose(iterator, 'throw', error); 677 } 678}; 679 680 681/***/ }, 682 683/***/ 2195 684(module, __unused_webpack_exports, __webpack_require__) { 685 686 687var uncurryThis = __webpack_require__(9504); 688 689var toString = uncurryThis({}.toString); 690var stringSlice = uncurryThis(''.slice); 691 692module.exports = function (it) { 693 return stringSlice(toString(it), 8, -1); 694}; 695 696 697/***/ }, 698 699/***/ 6955 700(module, __unused_webpack_exports, __webpack_require__) { 701 702 703var TO_STRING_TAG_SUPPORT = __webpack_require__(2140); 704var isCallable = __webpack_require__(4901); 705var classofRaw = __webpack_require__(2195); 706var wellKnownSymbol = __webpack_require__(8227); 707 708var TO_STRING_TAG = wellKnownSymbol('toStringTag'); 709var $Object = Object; 710 711// ES3 wrong here 712var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments'; 713 714// fallback for IE11 Script Access Denied error 715var tryGet = function (it, key) { 716 try { 717 return it[key]; 718 } catch (error) { /* empty */ } 719}; 720 721// getting tag from ES6+ `Object.prototype.toString` 722module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { 723 var O, tag, result; 724 return it === undefined ? 'Undefined' : it === null ? 'Null' 725 // @@toStringTag case 726 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag 727 // builtinTag case 728 : CORRECT_ARGUMENTS ? classofRaw(O) 729 // ES3 arguments fallback 730 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; 731}; 732 733 734/***/ }, 735 736/***/ 7740 737(module, __unused_webpack_exports, __webpack_require__) { 738 739 740var hasOwn = __webpack_require__(9297); 741var ownKeys = __webpack_require__(5031); 742var getOwnPropertyDescriptorModule = __webpack_require__(7347); 743var definePropertyModule = __webpack_require__(4913); 744 745module.exports = function (target, source, exceptions) { 746 var keys = ownKeys(source); 747 var defineProperty = definePropertyModule.f; 748 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; 749 for (var i = 0; i < keys.length; i++) { 750 var key = keys[i]; 751 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) { 752 defineProperty(target, key, getOwnPropertyDescriptor(source, key)); 753 } 754 } 755}; 756 757 758/***/ }, 759 760/***/ 2211 761(module, __unused_webpack_exports, __webpack_require__) { 762 763 764var fails = __webpack_require__(9039); 765 766module.exports = !fails(function () { 767 function F() { /* empty */ } 768 F.prototype.constructor = null; 769 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing 770 return Object.getPrototypeOf(new F()) !== F.prototype; 771}); 772 773 774/***/ }, 775 776/***/ 2529 777(module) { 778 779 780// `CreateIterResultObject` abstract operation 781// https://tc39.es/ecma262/#sec-createiterresultobject 782module.exports = function (value, done) { 783 return { value: value, done: done }; 784}; 785 786 787/***/ }, 788 789/***/ 6699 790(module, __unused_webpack_exports, __webpack_require__) { 791 792 793var DESCRIPTORS = __webpack_require__(3724); 794var definePropertyModule = __webpack_require__(4913); 795var createPropertyDescriptor = __webpack_require__(6980); 796 797module.exports = DESCRIPTORS ? function (object, key, value) { 798 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); 799} : function (object, key, value) { 800 object[key] = value; 801 return object; 802}; 803 804 805/***/ }, 806 807/***/ 6980 808(module) { 809 810 811module.exports = function (bitmap, value) { 812 return { 813 enumerable: !(bitmap & 1), 814 configurable: !(bitmap & 2), 815 writable: !(bitmap & 4), 816 value: value 817 }; 818}; 819 820 821/***/ }, 822 823/***/ 4659 824(module, __unused_webpack_exports, __webpack_require__) { 825 826 827var DESCRIPTORS = __webpack_require__(3724); 828var definePropertyModule = __webpack_require__(4913); 829var createPropertyDescriptor = __webpack_require__(6980); 830 831module.exports = function (object, key, value) { 832 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value)); 833 else object[key] = value; 834}; 835 836 837/***/ }, 838 839/***/ 2106 840(module, __unused_webpack_exports, __webpack_require__) { 841 842 843var makeBuiltIn = __webpack_require__(283); 844var defineProperty = __webpack_require__(4913); 845 846module.exports = function (target, name, descriptor) { 847 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true }); 848 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true }); 849 return defineProperty.f(target, name, descriptor); 850}; 851 852 853/***/ }, 854 855/***/ 6840 856(module, __unused_webpack_exports, __webpack_require__) { 857 858 859var isCallable = __webpack_require__(4901); 860var definePropertyModule = __webpack_require__(4913); 861var makeBuiltIn = __webpack_require__(283); 862var defineGlobalProperty = __webpack_require__(9433); 863 864module.exports = function (O, key, value, options) { 865 if (!options) options = {}; 866 var simple = options.enumerable; 867 var name = options.name !== undefined ? options.name : key; 868 if (isCallable(value)) makeBuiltIn(value, name, options); 869 if (options.global) { 870 if (simple) O[key] = value; 871 else defineGlobalProperty(key, value); 872 } else { 873 try { 874 if (!options.unsafe) delete O[key]; 875 else if (O[key]) simple = true; 876 } catch (error) { /* empty */ } 877 if (simple) O[key] = value; 878 else definePropertyModule.f(O, key, { 879 value: value, 880 enumerable: false, 881 configurable: !options.nonConfigurable, 882 writable: !options.nonWritable 883 }); 884 } return O; 885}; 886 887 888/***/ }, 889 890/***/ 6279 891(module, __unused_webpack_exports, __webpack_require__) { 892 893 894var defineBuiltIn = __webpack_require__(6840); 895 896module.exports = function (target, src, options) { 897 for (var key in src) defineBuiltIn(target, key, src[key], options); 898 return target; 899}; 900 901 902/***/ }, 903 904/***/ 9433 905(module, __unused_webpack_exports, __webpack_require__) { 906 907 908var globalThis = __webpack_require__(4576); 909 910// eslint-disable-next-line es/no-object-defineproperty -- safe 911var defineProperty = Object.defineProperty; 912 913module.exports = function (key, value) { 914 try { 915 defineProperty(globalThis, key, { value: value, configurable: true, writable: true }); 916 } catch (error) { 917 globalThis[key] = value; 918 } return value; 919}; 920 921 922/***/ }, 923 924/***/ 3724 925(module, __unused_webpack_exports, __webpack_require__) { 926 927 928var fails = __webpack_require__(9039); 929 930// Detect IE8's incomplete defineProperty implementation 931module.exports = !fails(function () { 932 // eslint-disable-next-line es/no-object-defineproperty -- required for testing 933 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7; 934}); 935 936 937/***/ }, 938 939/***/ 4483 940(module, __unused_webpack_exports, __webpack_require__) { 941 942 943var globalThis = __webpack_require__(4576); 944var getBuiltInNodeModule = __webpack_require__(9429); 945var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548); 946 947var structuredClone = globalThis.structuredClone; 948var $ArrayBuffer = globalThis.ArrayBuffer; 949var $MessageChannel = globalThis.MessageChannel; 950var detach = false;
vendor: 2,901 bytes, lines 951-1043
951var WorkerThreads, channel, buffer, $detach; 952 953if (PROPER_STRUCTURED_CLONE_TRANSFER) { 954 detach = function (transferable) { 955 structuredClone(transferable, { transfer: [transferable] }); 956 }; 957} else if ($ArrayBuffer) try { 958 if (!$MessageChannel) { 959 WorkerThreads = getBuiltInNodeModule('worker_threads'); 960 if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel; 961 } 962 963 if ($MessageChannel) { 964 channel = new $MessageChannel(); 965 buffer = new $ArrayBuffer(2); 966 967 $detach = function (transferable) { 968 channel.port1.postMessage(null, [transferable]); 969 }; 970 971 if (buffer.byteLength === 2) { 972 $detach(buffer); 973 if (buffer.byteLength === 0) detach = $detach; 974 } 975 } 976} catch (error) { /* empty */ } 977 978module.exports = detach; 979 980 981/***/ }, 982 983/***/ 4055 984(module, __unused_webpack_exports, __webpack_require__) { 985 986 987var globalThis = __webpack_require__(4576); 988var isObject = __webpack_require__(34); 989 990var document = globalThis.document; 991// typeof document.createElement is 'object' in old IE 992var EXISTS = isObject(document) && isObject(document.createElement); 993 994module.exports = function (it) { 995 return EXISTS ? document.createElement(it) : {}; 996}; 997 998 999/***/ }, 1000 1001/***/ 6837 1002(module) { 1003 1004 1005var $TypeError = TypeError; 1006var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991 1007 1008module.exports = function (it) { 1009 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded'); 1010 return it; 1011}; 1012 1013 1014/***/ }, 1015 1016/***/ 5002 1017(module) { 1018 1019 1020module.exports = { 1021 IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 }, 1022 DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 }, 1023 HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 }, 1024 WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 }, 1025 InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 }, 1026 NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 }, 1027 NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 }, 1028 NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 }, 1029 NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 }, 1030 InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 }, 1031 InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 }, 1032 SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 }, 1033 InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 }, 1034 NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 }, 1035 InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 }, 1036 ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 }, 1037 TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 }, 1038 SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 }, 1039 NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 }, 1040 AbortError: { s: 'ABORT_ERR', c: 20, m: 1 }, 1041 URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 }, 1042 QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 }, 1043 TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
vendor: 10,070 bytes, lines 1044-1413
1044 InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 }, 1045 DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 } 1046}; 1047 1048 1049/***/ }, 1050 1051/***/ 8727 1052(module) { 1053 1054 1055// IE8- don't enum bug keys 1056module.exports = [ 1057 'constructor', 1058 'hasOwnProperty', 1059 'isPrototypeOf', 1060 'propertyIsEnumerable', 1061 'toLocaleString', 1062 'toString', 1063 'valueOf' 1064]; 1065 1066 1067/***/ }, 1068 1069/***/ 6193 1070(module, __unused_webpack_exports, __webpack_require__) { 1071 1072 1073var ENVIRONMENT = __webpack_require__(4215); 1074 1075module.exports = ENVIRONMENT === 'NODE'; 1076 1077 1078/***/ }, 1079 1080/***/ 2839 1081(module, __unused_webpack_exports, __webpack_require__) { 1082 1083 1084var globalThis = __webpack_require__(4576); 1085 1086var navigator = globalThis.navigator; 1087var userAgent = navigator && navigator.userAgent; 1088 1089module.exports = userAgent ? String(userAgent) : ''; 1090 1091 1092/***/ }, 1093 1094/***/ 9519 1095(module, __unused_webpack_exports, __webpack_require__) { 1096 1097 1098var globalThis = __webpack_require__(4576); 1099var userAgent = __webpack_require__(2839); 1100 1101var process = globalThis.process; 1102var Deno = globalThis.Deno; 1103var versions = process && process.versions || Deno && Deno.version; 1104var v8 = versions && versions.v8; 1105var match, version; 1106 1107if (v8) { 1108 match = v8.split('.'); 1109 // in old Chrome, versions of V8 isn't V8 = Chrome / 10 1110 // but their correct versions are not interesting for us 1111 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); 1112} 1113 1114// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0` 1115// so check `userAgent` even if `.v8` exists, but 0 1116if (!version && userAgent) { 1117 match = userAgent.match(/Edge\/(\d+)/); 1118 if (!match || match[1] >= 74) { 1119 match = userAgent.match(/Chrome\/(\d+)/); 1120 if (match) version = +match[1]; 1121 } 1122} 1123 1124module.exports = version; 1125 1126 1127/***/ }, 1128 1129/***/ 4215 1130(module, __unused_webpack_exports, __webpack_require__) { 1131 1132 1133/* global Bun, Deno -- detection */ 1134var globalThis = __webpack_require__(4576); 1135var userAgent = __webpack_require__(2839); 1136var classof = __webpack_require__(2195); 1137 1138var userAgentStartsWith = function (string) { 1139 return userAgent.slice(0, string.length) === string; 1140}; 1141 1142module.exports = (function () { 1143 if (userAgentStartsWith('Bun/')) return 'BUN'; 1144 if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE'; 1145 if (userAgentStartsWith('Deno/')) return 'DENO'; 1146 if (userAgentStartsWith('Node.js/')) return 'NODE'; 1147 if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN'; 1148 if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO'; 1149 if (classof(globalThis.process) === 'process') return 'NODE'; 1150 if (globalThis.window && globalThis.document) return 'BROWSER'; 1151 return 'REST'; 1152})(); 1153 1154 1155/***/ }, 1156 1157/***/ 8574 1158(module, __unused_webpack_exports, __webpack_require__) { 1159 1160 1161var uncurryThis = __webpack_require__(9504); 1162 1163var $Error = Error; 1164var replace = uncurryThis(''.replace); 1165 1166var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd'); 1167// eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe 1168var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/; 1169var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST); 1170 1171module.exports = function (stack, dropEntries) { 1172 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) { 1173 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, ''); 1174 } return stack; 1175}; 1176 1177 1178/***/ }, 1179 1180/***/ 6518 1181(module, __unused_webpack_exports, __webpack_require__) { 1182 1183 1184var globalThis = __webpack_require__(4576); 1185var getOwnPropertyDescriptor = (__webpack_require__(7347).f); 1186var createNonEnumerableProperty = __webpack_require__(6699); 1187var defineBuiltIn = __webpack_require__(6840); 1188var defineGlobalProperty = __webpack_require__(9433); 1189var copyConstructorProperties = __webpack_require__(7740); 1190var isForced = __webpack_require__(2796); 1191 1192/* 1193 options.target - name of the target object 1194 options.global - target is the global object 1195 options.stat - export as static methods of target 1196 options.proto - export as prototype methods of target 1197 options.real - real prototype method for the `pure` version 1198 options.forced - export even if the native feature is available 1199 options.bind - bind methods to the target, required for the `pure` version 1200 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version 1201 options.unsafe - use the simple assignment of property instead of delete + defineProperty 1202 options.sham - add a flag to not completely full polyfills 1203 options.enumerable - export as enumerable property 1204 options.dontCallGetSet - prevent calling a getter on target 1205 options.name - the .name of the function if it does not match the key 1206*/ 1207module.exports = function (options, source) { 1208 var TARGET = options.target; 1209 var GLOBAL = options.global; 1210 var STATIC = options.stat; 1211 var FORCED, target, key, targetProperty, sourceProperty, descriptor; 1212 if (GLOBAL) { 1213 target = globalThis; 1214 } else if (STATIC) { 1215 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {}); 1216 } else { 1217 target = globalThis[TARGET] && globalThis[TARGET].prototype; 1218 } 1219 if (target) for (key in source) { 1220 sourceProperty = source[key]; 1221 if (options.dontCallGetSet) { 1222 descriptor = getOwnPropertyDescriptor(target, key); 1223 targetProperty = descriptor && descriptor.value; 1224 } else targetProperty = target[key]; 1225 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); 1226 // contained in target 1227 if (!FORCED && targetProperty !== undefined) { 1228 if (typeof sourceProperty == typeof targetProperty) continue; 1229 copyConstructorProperties(sourceProperty, targetProperty); 1230 } 1231 // add a flag to not completely full polyfills 1232 if (options.sham || (targetProperty && targetProperty.sham)) { 1233 createNonEnumerableProperty(sourceProperty, 'sham', true); 1234 } 1235 defineBuiltIn(target, key, sourceProperty, options); 1236 } 1237}; 1238 1239 1240/***/ }, 1241 1242/***/ 9039 1243(module) { 1244 1245 1246module.exports = function (exec) { 1247 try { 1248 return !!exec(); 1249 } catch (error) { 1250 return true; 1251 } 1252}; 1253 1254 1255/***/ }, 1256 1257/***/ 8745 1258(module, __unused_webpack_exports, __webpack_require__) { 1259 1260 1261var NATIVE_BIND = __webpack_require__(616); 1262 1263var FunctionPrototype = Function.prototype; 1264var apply = FunctionPrototype.apply; 1265var call = FunctionPrototype.call; 1266 1267// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe 1268module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () { 1269 return call.apply(apply, arguments); 1270}); 1271 1272 1273/***/ }, 1274 1275/***/ 6080 1276(module, __unused_webpack_exports, __webpack_require__) { 1277 1278 1279var uncurryThis = __webpack_require__(7476); 1280var aCallable = __webpack_require__(9306); 1281var NATIVE_BIND = __webpack_require__(616); 1282 1283var bind = uncurryThis(uncurryThis.bind); 1284 1285// optional / simple context binding 1286module.exports = function (fn, that) { 1287 aCallable(fn); 1288 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) { 1289 return fn.apply(that, arguments); 1290 }; 1291}; 1292 1293 1294/***/ }, 1295 1296/***/ 616 1297(module, __unused_webpack_exports, __webpack_require__) { 1298 1299 1300var fails = __webpack_require__(9039); 1301 1302module.exports = !fails(function () { 1303 // eslint-disable-next-line es/no-function-prototype-bind -- safe 1304 var test = (function () { /* empty */ }).bind(); 1305 // eslint-disable-next-line no-prototype-builtins -- safe 1306 return typeof test != 'function' || test.hasOwnProperty('prototype'); 1307}); 1308 1309 1310/***/ }, 1311 1312/***/ 9565 1313(module, __unused_webpack_exports, __webpack_require__) { 1314 1315 1316var NATIVE_BIND = __webpack_require__(616); 1317 1318var call = Function.prototype.call; 1319// eslint-disable-next-line es/no-function-prototype-bind -- safe 1320module.exports = NATIVE_BIND ? call.bind(call) : function () { 1321 return call.apply(call, arguments); 1322}; 1323 1324 1325/***/ }, 1326 1327/***/ 350 1328(module, __unused_webpack_exports, __webpack_require__) { 1329 1330 1331var DESCRIPTORS = __webpack_require__(3724); 1332var hasOwn = __webpack_require__(9297); 1333 1334var FunctionPrototype = Function.prototype; 1335// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 1336var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; 1337 1338var EXISTS = hasOwn(FunctionPrototype, 'name'); 1339// additional protection from minified / mangled / dropped function names 1340var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something'; 1341var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable)); 1342 1343module.exports = { 1344 EXISTS: EXISTS, 1345 PROPER: PROPER, 1346 CONFIGURABLE: CONFIGURABLE 1347}; 1348 1349 1350/***/ }, 1351 1352/***/ 6706 1353(module, __unused_webpack_exports, __webpack_require__) { 1354 1355 1356var uncurryThis = __webpack_require__(9504); 1357var aCallable = __webpack_require__(9306); 1358 1359module.exports = function (object, key, method) { 1360 try { 1361 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 1362 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); 1363 } catch (error) { /* empty */ } 1364}; 1365 1366 1367/***/ }, 1368 1369/***/ 7476 1370(module, __unused_webpack_exports, __webpack_require__) { 1371 1372 1373var classofRaw = __webpack_require__(2195); 1374var uncurryThis = __webpack_require__(9504); 1375 1376module.exports = function (fn) { 1377 // Nashorn bug: 1378 // https://github.com/zloirock/core-js/issues/1128 1379 // https://github.com/zloirock/core-js/issues/1130 1380 if (classofRaw(fn) === 'Function') return uncurryThis(fn); 1381}; 1382 1383 1384/***/ }, 1385 1386/***/ 9504 1387(module, __unused_webpack_exports, __webpack_require__) { 1388 1389 1390var NATIVE_BIND = __webpack_require__(616); 1391 1392var FunctionPrototype = Function.prototype; 1393var call = FunctionPrototype.call; 1394// eslint-disable-next-line es/no-function-prototype-bind -- safe 1395var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); 1396 1397module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) { 1398 return function () { 1399 return call.apply(fn, arguments); 1400 }; 1401}; 1402 1403 1404/***/ }, 1405 1406/***/ 944 1407(module) { 1408 1409 1410var $TypeError = TypeError; 1411 1412module.exports = function (options) { 1413 var alphabet = options && options.alphabet;
vendor: 11,624 bytes, lines 1414-1883
1414 if (alphabet === undefined || alphabet === 'base64' || alphabet === 'base64url') return alphabet || 'base64'; 1415 throw new $TypeError('Incorrect `alphabet` option'); 1416}; 1417 1418 1419/***/ }, 1420 1421/***/ 9429 1422(module, __unused_webpack_exports, __webpack_require__) { 1423 1424 1425var globalThis = __webpack_require__(4576); 1426var IS_NODE = __webpack_require__(6193); 1427 1428module.exports = function (name) { 1429 if (IS_NODE) { 1430 try { 1431 return globalThis.process.getBuiltinModule(name); 1432 } catch (error) { /* empty */ } 1433 try { 1434 // eslint-disable-next-line no-new-func -- safe 1435 return Function('return require("' + name + '")')(); 1436 } catch (error) { /* empty */ } 1437 } 1438}; 1439 1440 1441/***/ }, 1442 1443/***/ 7751 1444(module, __unused_webpack_exports, __webpack_require__) { 1445 1446 1447var globalThis = __webpack_require__(4576); 1448var isCallable = __webpack_require__(4901); 1449 1450var aFunction = function (argument) { 1451 return isCallable(argument) ? argument : undefined; 1452}; 1453 1454module.exports = function (namespace, method) { 1455 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method]; 1456}; 1457 1458 1459/***/ }, 1460 1461/***/ 1767 1462(module) { 1463 1464 1465// `GetIteratorDirect(obj)` abstract operation 1466// https://tc39.es/ecma262/#sec-getiteratordirect 1467module.exports = function (obj) { 1468 return { 1469 iterator: obj, 1470 next: obj.next, 1471 done: false 1472 }; 1473}; 1474 1475 1476/***/ }, 1477 1478/***/ 8646 1479(module, __unused_webpack_exports, __webpack_require__) { 1480 1481 1482var call = __webpack_require__(9565); 1483var anObject = __webpack_require__(8551); 1484var getIteratorDirect = __webpack_require__(1767); 1485var getIteratorMethod = __webpack_require__(851); 1486 1487module.exports = function (obj, stringHandling) { 1488 if (!stringHandling || typeof obj !== 'string') anObject(obj); 1489 var method = getIteratorMethod(obj); 1490 return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj)); 1491}; 1492 1493 1494/***/ }, 1495 1496/***/ 851 1497(module, __unused_webpack_exports, __webpack_require__) { 1498 1499 1500var classof = __webpack_require__(6955); 1501var getMethod = __webpack_require__(5966); 1502var isNullOrUndefined = __webpack_require__(4117); 1503var Iterators = __webpack_require__(6269); 1504var wellKnownSymbol = __webpack_require__(8227); 1505 1506var ITERATOR = wellKnownSymbol('iterator'); 1507 1508module.exports = function (it) { 1509 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR) 1510 || getMethod(it, '@@iterator') 1511 || Iterators[classof(it)]; 1512}; 1513 1514 1515/***/ }, 1516 1517/***/ 81 1518(module, __unused_webpack_exports, __webpack_require__) { 1519 1520 1521var call = __webpack_require__(9565); 1522var aCallable = __webpack_require__(9306); 1523var anObject = __webpack_require__(8551); 1524var tryToString = __webpack_require__(6823); 1525var getIteratorMethod = __webpack_require__(851); 1526 1527var $TypeError = TypeError; 1528 1529module.exports = function (argument, usingIterator) { 1530 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator; 1531 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument)); 1532 throw new $TypeError(tryToString(argument) + ' is not iterable'); 1533}; 1534 1535 1536/***/ }, 1537 1538/***/ 5966 1539(module, __unused_webpack_exports, __webpack_require__) { 1540 1541 1542var aCallable = __webpack_require__(9306); 1543var isNullOrUndefined = __webpack_require__(4117); 1544 1545// `GetMethod` abstract operation 1546// https://tc39.es/ecma262/#sec-getmethod 1547module.exports = function (V, P) { 1548 var func = V[P]; 1549 return isNullOrUndefined(func) ? undefined : aCallable(func); 1550}; 1551 1552 1553/***/ }, 1554 1555/***/ 3789 1556(module, __unused_webpack_exports, __webpack_require__) { 1557 1558 1559var aCallable = __webpack_require__(9306); 1560var anObject = __webpack_require__(8551); 1561var call = __webpack_require__(9565); 1562var toIntegerOrInfinity = __webpack_require__(1291); 1563var getIteratorDirect = __webpack_require__(1767); 1564 1565var INVALID_SIZE = 'Invalid size'; 1566var $RangeError = RangeError; 1567var $TypeError = TypeError; 1568var max = Math.max; 1569 1570var SetRecord = function (set, intSize) { 1571 this.set = set; 1572 this.size = max(intSize, 0); 1573 this.has = aCallable(set.has); 1574 this.keys = aCallable(set.keys); 1575}; 1576 1577SetRecord.prototype = { 1578 getIterator: function () { 1579 return getIteratorDirect(anObject(call(this.keys, this.set))); 1580 }, 1581 includes: function (it) { 1582 return call(this.has, this.set, it); 1583 } 1584}; 1585 1586// `GetSetRecord` abstract operation 1587// https://tc39.es/proposal-set-methods/#sec-getsetrecord 1588module.exports = function (obj) { 1589 anObject(obj); 1590 var numSize = +obj.size; 1591 // NOTE: If size is undefined, then numSize will be NaN 1592 // eslint-disable-next-line no-self-compare -- NaN check 1593 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE); 1594 var intSize = toIntegerOrInfinity(numSize); 1595 if (intSize < 0) throw new $RangeError(INVALID_SIZE); 1596 return new SetRecord(obj, intSize); 1597}; 1598 1599 1600/***/ }, 1601 1602/***/ 4576 1603(module) { 1604 1605 1606var check = function (it) { 1607 return it && it.Math === Math && it; 1608}; 1609 1610// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 1611module.exports = 1612 // eslint-disable-next-line es/no-global-this -- safe 1613 check(typeof globalThis == 'object' && globalThis) || 1614 check(typeof window == 'object' && window) || 1615 // eslint-disable-next-line no-restricted-globals -- safe 1616 check(typeof self == 'object' && self) || 1617 check(typeof global == 'object' && global) || 1618 check(typeof this == 'object' && this) || 1619 // eslint-disable-next-line no-new-func -- fallback 1620 (function () { return this; })() || Function('return this')(); 1621 1622 1623/***/ }, 1624 1625/***/ 9297 1626(module, __unused_webpack_exports, __webpack_require__) { 1627 1628 1629var uncurryThis = __webpack_require__(9504); 1630var toObject = __webpack_require__(8981); 1631 1632var hasOwnProperty = uncurryThis({}.hasOwnProperty); 1633 1634// `HasOwnProperty` abstract operation 1635// https://tc39.es/ecma262/#sec-hasownproperty 1636// eslint-disable-next-line es/no-object-hasown -- safe 1637module.exports = Object.hasOwn || function hasOwn(it, key) { 1638 return hasOwnProperty(toObject(it), key); 1639}; 1640 1641 1642/***/ }, 1643 1644/***/ 421 1645(module) { 1646 1647 1648module.exports = {}; 1649 1650 1651/***/ }, 1652 1653/***/ 397 1654(module, __unused_webpack_exports, __webpack_require__) { 1655 1656 1657var getBuiltIn = __webpack_require__(7751); 1658 1659module.exports = getBuiltIn('document', 'documentElement'); 1660 1661 1662/***/ }, 1663 1664/***/ 5917 1665(module, __unused_webpack_exports, __webpack_require__) { 1666 1667 1668var DESCRIPTORS = __webpack_require__(3724); 1669var fails = __webpack_require__(9039); 1670var createElement = __webpack_require__(4055); 1671 1672// Thanks to IE8 for its funny defineProperty 1673module.exports = !DESCRIPTORS && !fails(function () { 1674 // eslint-disable-next-line es/no-object-defineproperty -- required for testing 1675 return Object.defineProperty(createElement('div'), 'a', { 1676 get: function () { return 7; } 1677 }).a !== 7; 1678}); 1679 1680 1681/***/ }, 1682 1683/***/ 7055 1684(module, __unused_webpack_exports, __webpack_require__) { 1685 1686 1687var uncurryThis = __webpack_require__(9504); 1688var fails = __webpack_require__(9039); 1689var classof = __webpack_require__(2195); 1690 1691var $Object = Object; 1692var split = uncurryThis(''.split); 1693 1694// fallback for non-array-like ES3 and non-enumerable old V8 strings 1695module.exports = fails(function () { 1696 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 1697 // eslint-disable-next-line no-prototype-builtins -- safe 1698 return !$Object('z').propertyIsEnumerable(0); 1699}) ? function (it) { 1700 return classof(it) === 'String' ? split(it, '') : $Object(it); 1701} : $Object; 1702 1703 1704/***/ }, 1705 1706/***/ 3167 1707(module, __unused_webpack_exports, __webpack_require__) { 1708 1709 1710var isCallable = __webpack_require__(4901); 1711var isObject = __webpack_require__(34); 1712var setPrototypeOf = __webpack_require__(2967); 1713 1714// makes subclassing work correct for wrapped built-ins 1715module.exports = function ($this, dummy, Wrapper) { 1716 var NewTarget, NewTargetPrototype; 1717 if ( 1718 // it can work only with native `setPrototypeOf` 1719 setPrototypeOf && 1720 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this 1721 isCallable(NewTarget = dummy.constructor) && 1722 NewTarget !== Wrapper && 1723 isObject(NewTargetPrototype = NewTarget.prototype) && 1724 NewTargetPrototype !== Wrapper.prototype 1725 ) setPrototypeOf($this, NewTargetPrototype); 1726 return $this; 1727}; 1728 1729 1730/***/ }, 1731 1732/***/ 3706 1733(module, __unused_webpack_exports, __webpack_require__) { 1734 1735 1736var uncurryThis = __webpack_require__(9504); 1737var isCallable = __webpack_require__(4901); 1738var store = __webpack_require__(7629); 1739 1740var functionToString = uncurryThis(Function.toString); 1741 1742// this helper broken in `[email protected]`, so we can't use `shared` helper 1743if (!isCallable(store.inspectSource)) { 1744 store.inspectSource = function (it) { 1745 return functionToString(it); 1746 }; 1747} 1748 1749module.exports = store.inspectSource; 1750 1751 1752/***/ }, 1753 1754/***/ 1181 1755(module, __unused_webpack_exports, __webpack_require__) { 1756 1757 1758var NATIVE_WEAK_MAP = __webpack_require__(8622); 1759var globalThis = __webpack_require__(4576); 1760var isObject = __webpack_require__(34); 1761var createNonEnumerableProperty = __webpack_require__(6699); 1762var hasOwn = __webpack_require__(9297); 1763var shared = __webpack_require__(7629); 1764var sharedKey = __webpack_require__(6119); 1765var hiddenKeys = __webpack_require__(421); 1766 1767var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; 1768var TypeError = globalThis.TypeError; 1769var WeakMap = globalThis.WeakMap; 1770var set, get, has; 1771 1772var enforce = function (it) { 1773 return has(it) ? get(it) : set(it, {}); 1774}; 1775 1776var getterFor = function (TYPE) { 1777 return function (it) { 1778 var state; 1779 if (!isObject(it) || (state = get(it)).type !== TYPE) { 1780 throw new TypeError('Incompatible receiver, ' + TYPE + ' required'); 1781 } return state; 1782 }; 1783}; 1784 1785if (NATIVE_WEAK_MAP || shared.state) { 1786 var store = shared.state || (shared.state = new WeakMap()); 1787 /* eslint-disable no-self-assign -- prototype methods protection */ 1788 store.get = store.get; 1789 store.has = store.has; 1790 store.set = store.set; 1791 /* eslint-enable no-self-assign -- prototype methods protection */ 1792 set = function (it, metadata) { 1793 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); 1794 metadata.facade = it; 1795 store.set(it, metadata); 1796 return metadata; 1797 }; 1798 get = function (it) { 1799 return store.get(it) || {}; 1800 }; 1801 has = function (it) { 1802 return store.has(it); 1803 }; 1804} else { 1805 var STATE = sharedKey('state'); 1806 hiddenKeys[STATE] = true; 1807 set = function (it, metadata) { 1808 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); 1809 metadata.facade = it; 1810 createNonEnumerableProperty(it, STATE, metadata); 1811 return metadata; 1812 }; 1813 get = function (it) { 1814 return hasOwn(it, STATE) ? it[STATE] : {}; 1815 }; 1816 has = function (it) { 1817 return hasOwn(it, STATE); 1818 }; 1819} 1820 1821module.exports = { 1822 set: set, 1823 get: get, 1824 has: has, 1825 enforce: enforce, 1826 getterFor: getterFor 1827}; 1828 1829 1830/***/ }, 1831 1832/***/ 4209 1833(module, __unused_webpack_exports, __webpack_require__) { 1834 1835 1836var wellKnownSymbol = __webpack_require__(8227); 1837var Iterators = __webpack_require__(6269); 1838 1839var ITERATOR = wellKnownSymbol('iterator'); 1840var ArrayPrototype = Array.prototype; 1841 1842// check on default Array iterator 1843module.exports = function (it) { 1844 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); 1845}; 1846 1847 1848/***/ }, 1849 1850/***/ 4376 1851(module, __unused_webpack_exports, __webpack_require__) { 1852 1853 1854var classof = __webpack_require__(2195); 1855 1856// `IsArray` abstract operation 1857// https://tc39.es/ecma262/#sec-isarray 1858// eslint-disable-next-line es/no-array-isarray -- safe 1859module.exports = Array.isArray || function isArray(argument) { 1860 return classof(argument) === 'Array'; 1861}; 1862 1863 1864/***/ }, 1865 1866/***/ 1108 1867(module, __unused_webpack_exports, __webpack_require__) { 1868 1869 1870var classof = __webpack_require__(6955); 1871 1872module.exports = function (it) { 1873 var klass = classof(it); 1874 return klass === 'BigInt64Array' || klass === 'BigUint64Array'; 1875}; 1876 1877 1878/***/ }, 1879 1880/***/ 4901 1881(module) { 1882 1883
vendor: 4,675 bytes, lines 1884-2075
1884// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot 1885var documentAll = typeof document == 'object' && document.all; 1886 1887// `IsCallable` abstract operation 1888// https://tc39.es/ecma262/#sec-iscallable 1889// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing 1890module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) { 1891 return typeof argument == 'function' || argument === documentAll; 1892} : function (argument) { 1893 return typeof argument == 'function'; 1894}; 1895 1896 1897/***/ }, 1898 1899/***/ 2796 1900(module, __unused_webpack_exports, __webpack_require__) { 1901 1902 1903var fails = __webpack_require__(9039); 1904var isCallable = __webpack_require__(4901); 1905 1906var replacement = /#|\.prototype\./; 1907 1908var isForced = function (feature, detection) { 1909 var value = data[normalize(feature)]; 1910 return value === POLYFILL ? true 1911 : value === NATIVE ? false 1912 : isCallable(detection) ? fails(detection) 1913 : !!detection; 1914}; 1915 1916var normalize = isForced.normalize = function (string) { 1917 return String(string).replace(replacement, '.').toLowerCase(); 1918}; 1919 1920var data = isForced.data = {}; 1921var NATIVE = isForced.NATIVE = 'N'; 1922var POLYFILL = isForced.POLYFILL = 'P'; 1923 1924module.exports = isForced; 1925 1926 1927/***/ }, 1928 1929/***/ 4117 1930(module) { 1931 1932 1933// we can't use just `it == null` since of `document.all` special case 1934// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec 1935module.exports = function (it) { 1936 return it === null || it === undefined; 1937}; 1938 1939 1940/***/ }, 1941 1942/***/ 34 1943(module, __unused_webpack_exports, __webpack_require__) { 1944 1945 1946var isCallable = __webpack_require__(4901); 1947 1948module.exports = function (it) { 1949 return typeof it == 'object' ? it !== null : isCallable(it); 1950}; 1951 1952 1953/***/ }, 1954 1955/***/ 3925 1956(module, __unused_webpack_exports, __webpack_require__) { 1957 1958 1959var isObject = __webpack_require__(34); 1960 1961module.exports = function (argument) { 1962 return isObject(argument) || argument === null; 1963}; 1964 1965 1966/***/ }, 1967 1968/***/ 6395 1969(module) { 1970 1971 1972module.exports = false; 1973 1974 1975/***/ }, 1976 1977/***/ 5810 1978(module, __unused_webpack_exports, __webpack_require__) { 1979 1980 1981var isObject = __webpack_require__(34); 1982var getInternalState = (__webpack_require__(1181).get); 1983 1984module.exports = function isRawJSON(O) { 1985 if (!isObject(O)) return false; 1986 var state = getInternalState(O); 1987 return !!state && state.type === 'RawJSON'; 1988}; 1989 1990 1991/***/ }, 1992 1993/***/ 757 1994(module, __unused_webpack_exports, __webpack_require__) { 1995 1996 1997var getBuiltIn = __webpack_require__(7751); 1998var isCallable = __webpack_require__(4901); 1999var isPrototypeOf = __webpack_require__(1625); 2000var USE_SYMBOL_AS_UID = __webpack_require__(7040); 2001 2002var $Object = Object; 2003 2004module.exports = USE_SYMBOL_AS_UID ? function (it) { 2005 return typeof it == 'symbol'; 2006} : function (it) { 2007 var $Symbol = getBuiltIn('Symbol'); 2008 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); 2009}; 2010 2011 2012/***/ }, 2013 2014/***/ 507 2015(module, __unused_webpack_exports, __webpack_require__) { 2016 2017 2018var call = __webpack_require__(9565); 2019 2020module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) { 2021 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator; 2022 var next = record.next; 2023 var step, result; 2024 while (!(step = call(next, iterator)).done) { 2025 result = fn(step.value); 2026 if (result !== undefined) return result; 2027 } 2028}; 2029 2030 2031/***/ }, 2032 2033/***/ 2652 2034(module, __unused_webpack_exports, __webpack_require__) { 2035 2036 2037var bind = __webpack_require__(6080); 2038var call = __webpack_require__(9565); 2039var anObject = __webpack_require__(8551); 2040var tryToString = __webpack_require__(6823); 2041var isArrayIteratorMethod = __webpack_require__(4209); 2042var lengthOfArrayLike = __webpack_require__(6198); 2043var isPrototypeOf = __webpack_require__(1625); 2044var getIterator = __webpack_require__(81); 2045var getIteratorMethod = __webpack_require__(851); 2046var iteratorClose = __webpack_require__(9539); 2047 2048var $TypeError = TypeError; 2049 2050var Result = function (stopped, result) { 2051 this.stopped = stopped; 2052 this.result = result; 2053}; 2054 2055var ResultPrototype = Result.prototype; 2056 2057module.exports = function (iterable, unboundFunction, options) { 2058 var that = options && options.that; 2059 var AS_ENTRIES = !!(options && options.AS_ENTRIES); 2060 var IS_RECORD = !!(options && options.IS_RECORD); 2061 var IS_ITERATOR = !!(options && options.IS_ITERATOR); 2062 var INTERRUPTED = !!(options && options.INTERRUPTED); 2063 var fn = bind(unboundFunction, that); 2064 var iterator, iterFn, index, length, result, next, step; 2065 2066 var stop = function (condition) { 2067 if (iterator) iteratorClose(iterator, 'normal'); 2068 return new Result(true, condition); 2069 }; 2070 2071 var callFn = function (value) { 2072 if (AS_ENTRIES) { 2073 anObject(value); 2074 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); 2075 }
vendor: 3,725 bytes, lines 2075-2196
2075 return INTERRUPTED ? fn(value, stop) : fn(value); 2076 }; 2077 2078 if (IS_RECORD) { 2079 iterator = iterable.iterator; 2080 } else if (IS_ITERATOR) { 2081 iterator = iterable; 2082 } else { 2083 iterFn = getIteratorMethod(iterable); 2084 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable'); 2085 // optimisation for array iterators 2086 if (isArrayIteratorMethod(iterFn)) { 2087 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) { 2088 result = callFn(iterable[index]); 2089 if (result && isPrototypeOf(ResultPrototype, result)) return result; 2090 } return new Result(false); 2091 } 2092 iterator = getIterator(iterable, iterFn); 2093 } 2094 2095 next = IS_RECORD ? iterable.next : iterator.next; 2096 while (!(step = call(next, iterator)).done) { 2097 try { 2098 result = callFn(step.value); 2099 } catch (error) { 2100 iteratorClose(iterator, 'throw', error); 2101 } 2102 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result; 2103 } return new Result(false); 2104}; 2105 2106 2107/***/ }, 2108 2109/***/ 1385 2110(module, __unused_webpack_exports, __webpack_require__) { 2111 2112 2113var iteratorClose = __webpack_require__(9539); 2114 2115module.exports = function (iters, kind, value) { 2116 for (var i = iters.length - 1; i >= 0; i--) { 2117 if (iters[i] === undefined) continue; 2118 try { 2119 value = iteratorClose(iters[i].iterator, kind, value); 2120 } catch (error) { 2121 kind = 'throw'; 2122 value = error; 2123 } 2124 } 2125 if (kind === 'throw') throw value; 2126 return value; 2127}; 2128 2129 2130/***/ }, 2131 2132/***/ 9539 2133(module, __unused_webpack_exports, __webpack_require__) { 2134 2135 2136var call = __webpack_require__(9565); 2137var anObject = __webpack_require__(8551); 2138var getMethod = __webpack_require__(5966); 2139 2140module.exports = function (iterator, kind, value) { 2141 var innerResult, innerError; 2142 anObject(iterator); 2143 try { 2144 innerResult = getMethod(iterator, 'return'); 2145 if (!innerResult) { 2146 if (kind === 'throw') throw value; 2147 return value; 2148 } 2149 innerResult = call(innerResult, iterator); 2150 } catch (error) { 2151 innerError = true; 2152 innerResult = error; 2153 } 2154 if (kind === 'throw') throw value; 2155 if (innerError) throw innerResult; 2156 anObject(innerResult); 2157 return value; 2158}; 2159 2160 2161/***/ }, 2162 2163/***/ 9462 2164(module, __unused_webpack_exports, __webpack_require__) { 2165 2166 2167var call = __webpack_require__(9565); 2168var create = __webpack_require__(2360); 2169var createNonEnumerableProperty = __webpack_require__(6699); 2170var defineBuiltIns = __webpack_require__(6279); 2171var wellKnownSymbol = __webpack_require__(8227); 2172var InternalStateModule = __webpack_require__(1181); 2173var getMethod = __webpack_require__(5966); 2174var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype); 2175var createIterResultObject = __webpack_require__(2529); 2176var iteratorClose = __webpack_require__(9539); 2177var iteratorCloseAll = __webpack_require__(1385); 2178 2179var TO_STRING_TAG = wellKnownSymbol('toStringTag'); 2180var ITERATOR_HELPER = 'IteratorHelper'; 2181var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator'; 2182var NORMAL = 'normal'; 2183var THROW = 'throw'; 2184var setInternalState = InternalStateModule.set; 2185 2186var createIteratorProxyPrototype = function (IS_ITERATOR) { 2187 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER); 2188 2189 return defineBuiltIns(create(IteratorPrototype), { 2190 next: function next() { 2191 var state = getInternalState(this); 2192 // for simplification: 2193 // for `%WrapForValidIteratorPrototype%.next` or with `state.returnHandlerResult` our `nextHandler` returns `IterResultObject` 2194 // for `%IteratorHelperPrototype%.next` - just a value 2195 if (IS_ITERATOR) return state.nextHandler(); 2196 if (state.done) return createIterResultObject(undefined, true);
vendor: 4,981 bytes, lines 2197-2373
2197 try { 2198 var result = state.nextHandler(); 2199 return state.returnHandlerResult ? result : createIterResultObject(result, state.done); 2200 } catch (error) { 2201 state.done = true; 2202 throw error; 2203 } 2204 }, 2205 'return': function () { 2206 var state = getInternalState(this); 2207 var iterator = state.iterator; 2208 state.done = true; 2209 if (IS_ITERATOR) { 2210 var returnMethod = getMethod(iterator, 'return'); 2211 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true); 2212 } 2213 if (state.inner) try { 2214 iteratorClose(state.inner.iterator, NORMAL); 2215 } catch (error) { 2216 return iteratorClose(iterator, THROW, error); 2217 } 2218 if (state.openIters) try { 2219 iteratorCloseAll(state.openIters, NORMAL); 2220 } catch (error) { 2221 return iteratorClose(iterator, THROW, error); 2222 } 2223 if (iterator) iteratorClose(iterator, NORMAL); 2224 return createIterResultObject(undefined, true); 2225 } 2226 }); 2227}; 2228 2229var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true); 2230var IteratorHelperPrototype = createIteratorProxyPrototype(false); 2231 2232createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper'); 2233 2234module.exports = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) { 2235 var IteratorProxy = function Iterator(record, state) { 2236 if (state) { 2237 state.iterator = record.iterator; 2238 state.next = record.next; 2239 } else state = record; 2240 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER; 2241 state.returnHandlerResult = !!RETURN_HANDLER_RESULT; 2242 state.nextHandler = nextHandler; 2243 state.counter = 0; 2244 state.done = false; 2245 setInternalState(this, state); 2246 }; 2247 2248 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype; 2249 2250 return IteratorProxy; 2251}; 2252 2253 2254/***/ }, 2255 2256/***/ 684 2257(module) { 2258 2259 2260// Should throw an error on invalid iterator 2261// https://issues.chromium.org/issues/336839115 2262module.exports = function (methodName, argument) { 2263 // eslint-disable-next-line es/no-iterator -- required for testing 2264 var method = typeof Iterator == 'function' && Iterator.prototype[methodName]; 2265 if (method) try { 2266 method.call({ next: null }, argument).next(); 2267 } catch (error) { 2268 return true; 2269 } 2270}; 2271 2272 2273/***/ }, 2274 2275/***/ 4549 2276(module, __unused_webpack_exports, __webpack_require__) { 2277 2278 2279var globalThis = __webpack_require__(4576); 2280 2281// https://github.com/tc39/ecma262/pull/3467 2282module.exports = function (METHOD_NAME, ExpectedError) { 2283 var Iterator = globalThis.Iterator; 2284 var IteratorPrototype = Iterator && Iterator.prototype; 2285 var method = IteratorPrototype && IteratorPrototype[METHOD_NAME]; 2286 2287 var CLOSED = false; 2288 2289 if (method) try { 2290 method.call({ 2291 next: function () { return { done: true }; }, 2292 'return': function () { CLOSED = true; } 2293 }, -1); 2294 } catch (error) { 2295 // https://bugs.webkit.org/show_bug.cgi?id=291195 2296 if (!(error instanceof ExpectedError)) CLOSED = false; 2297 } 2298 2299 if (!CLOSED) return method; 2300}; 2301 2302 2303/***/ }, 2304 2305/***/ 7657 2306(module, __unused_webpack_exports, __webpack_require__) { 2307 2308 2309var fails = __webpack_require__(9039); 2310var isCallable = __webpack_require__(4901); 2311var isObject = __webpack_require__(34); 2312var create = __webpack_require__(2360); 2313var getPrototypeOf = __webpack_require__(2787); 2314var defineBuiltIn = __webpack_require__(6840); 2315var wellKnownSymbol = __webpack_require__(8227); 2316var IS_PURE = __webpack_require__(6395); 2317 2318var ITERATOR = wellKnownSymbol('iterator'); 2319var BUGGY_SAFARI_ITERATORS = false; 2320 2321// `%IteratorPrototype%` object 2322// https://tc39.es/ecma262/#sec-%iteratorprototype%-object 2323var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; 2324 2325/* eslint-disable es/no-array-prototype-keys -- safe */ 2326if ([].keys) { 2327 arrayIterator = [].keys(); 2328 // Safari 8 has buggy iterators w/o `next` 2329 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; 2330 else { 2331 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); 2332 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; 2333 } 2334} 2335 2336var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () { 2337 var test = {}; 2338 // FF44- legacy iterators case 2339 return IteratorPrototype[ITERATOR].call(test) !== test; 2340}); 2341 2342if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {}; 2343else if (IS_PURE) IteratorPrototype = create(IteratorPrototype); 2344 2345// `%IteratorPrototype%[@@iterator]()` method 2346// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator 2347if (!isCallable(IteratorPrototype[ITERATOR])) { 2348 defineBuiltIn(IteratorPrototype, ITERATOR, function () { 2349 return this; 2350 }); 2351} 2352 2353module.exports = { 2354 IteratorPrototype: IteratorPrototype, 2355 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS 2356}; 2357 2358 2359/***/ }, 2360 2361/***/ 6269 2362(module) { 2363 2364 2365module.exports = {}; 2366 2367 2368/***/ }, 2369 2370/***/ 6198 2371(module, __unused_webpack_exports, __webpack_require__) { 2372 2373
vendor: 5,234 bytes, lines 2374-2555
2374var toLength = __webpack_require__(8014); 2375 2376// `LengthOfArrayLike` abstract operation 2377// https://tc39.es/ecma262/#sec-lengthofarraylike 2378module.exports = function (obj) { 2379 return toLength(obj.length); 2380}; 2381 2382 2383/***/ }, 2384 2385/***/ 283 2386(module, __unused_webpack_exports, __webpack_require__) { 2387 2388 2389var uncurryThis = __webpack_require__(9504); 2390var fails = __webpack_require__(9039); 2391var isCallable = __webpack_require__(4901); 2392var hasOwn = __webpack_require__(9297); 2393var DESCRIPTORS = __webpack_require__(3724); 2394var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(350).CONFIGURABLE); 2395var inspectSource = __webpack_require__(3706); 2396var InternalStateModule = __webpack_require__(1181); 2397 2398var enforceInternalState = InternalStateModule.enforce; 2399var getInternalState = InternalStateModule.get; 2400var $String = String; 2401// eslint-disable-next-line es/no-object-defineproperty -- safe 2402var defineProperty = Object.defineProperty; 2403var stringSlice = uncurryThis(''.slice); 2404var replace = uncurryThis(''.replace); 2405var join = uncurryThis([].join); 2406 2407var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () { 2408 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8; 2409}); 2410 2411var TEMPLATE = String(String).split('String'); 2412 2413var makeBuiltIn = module.exports = function (value, name, options) { 2414 if (stringSlice($String(name), 0, 7) === 'Symbol(') { 2415 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']'; 2416 } 2417 if (options && options.getter) name = 'get ' + name; 2418 if (options && options.setter) name = 'set ' + name; 2419 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) { 2420 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true }); 2421 else value.name = name; 2422 } 2423 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) { 2424 defineProperty(value, 'length', { value: options.arity }); 2425 } 2426 try { 2427 if (options && hasOwn(options, 'constructor') && options.constructor) { 2428 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false }); 2429 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable 2430 } else if (value.prototype) value.prototype = undefined; 2431 } catch (error) { /* empty */ } 2432 var state = enforceInternalState(value); 2433 if (!hasOwn(state, 'source')) { 2434 state.source = join(TEMPLATE, typeof name == 'string' ? name : ''); 2435 } return value; 2436}; 2437 2438// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative 2439// eslint-disable-next-line no-extend-native -- required 2440Function.prototype.toString = makeBuiltIn(function toString() { 2441 return isCallable(this) && getInternalState(this).source || inspectSource(this); 2442}, 'toString'); 2443 2444 2445/***/ }, 2446 2447/***/ 2248 2448(module, __unused_webpack_exports, __webpack_require__) { 2449 2450 2451var uncurryThis = __webpack_require__(9504); 2452 2453// eslint-disable-next-line es/no-map -- safe 2454var MapPrototype = Map.prototype; 2455 2456module.exports = { 2457 // eslint-disable-next-line es/no-map -- safe 2458 Map: Map, 2459 set: uncurryThis(MapPrototype.set), 2460 get: uncurryThis(MapPrototype.get), 2461 has: uncurryThis(MapPrototype.has), 2462 remove: uncurryThis(MapPrototype['delete']), 2463 proto: MapPrototype 2464}; 2465 2466 2467/***/ }, 2468 2469/***/ 741 2470(module) { 2471 2472 2473var ceil = Math.ceil; 2474var floor = Math.floor; 2475 2476// `Math.trunc` method 2477// https://tc39.es/ecma262/#sec-math.trunc 2478// eslint-disable-next-line es/no-math-trunc -- safe 2479module.exports = Math.trunc || function trunc(x) { 2480 var n = +x; 2481 return (n > 0 ? floor : ceil)(n); 2482}; 2483 2484 2485/***/ }, 2486 2487/***/ 7819 2488(module, __unused_webpack_exports, __webpack_require__) { 2489 2490 2491/* eslint-disable es/no-json -- safe */ 2492var fails = __webpack_require__(9039); 2493 2494module.exports = !fails(function () { 2495 var unsafeInt = '9007199254740993'; 2496 // eslint-disable-next-line es/no-json-rawjson -- feature detection 2497 var raw = JSON.rawJSON(unsafeInt); 2498 // eslint-disable-next-line es/no-json-israwjson -- feature detection 2499 return !JSON.isRawJSON(raw) || JSON.stringify(raw) !== unsafeInt; 2500}); 2501 2502 2503/***/ }, 2504 2505/***/ 6043 2506(module, __unused_webpack_exports, __webpack_require__) { 2507 2508 2509var aCallable = __webpack_require__(9306); 2510 2511var $TypeError = TypeError; 2512 2513var PromiseCapability = function (C) { 2514 var resolve, reject; 2515 this.promise = new C(function ($$resolve, $$reject) { 2516 if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor'); 2517 resolve = $$resolve; 2518 reject = $$reject; 2519 }); 2520 this.resolve = aCallable(resolve); 2521 this.reject = aCallable(reject); 2522}; 2523 2524// `NewPromiseCapability` abstract operation 2525// https://tc39.es/ecma262/#sec-newpromisecapability 2526module.exports.f = function (C) { 2527 return new PromiseCapability(C); 2528}; 2529 2530 2531/***/ }, 2532 2533/***/ 2603 2534(module, __unused_webpack_exports, __webpack_require__) { 2535 2536 2537var toString = __webpack_require__(655); 2538 2539module.exports = function (argument, $default) { 2540 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument); 2541}; 2542 2543 2544/***/ }, 2545 2546/***/ 4149 2547(module) { 2548 2549 2550var $RangeError = RangeError; 2551 2552module.exports = function (it) { 2553 // eslint-disable-next-line no-self-compare -- NaN check 2554 if (it === it) return it; 2555 throw new $RangeError('NaN is not allowed'
vendor: 11,767 bytes, lines 2555-2933
2555); 2556}; 2557 2558 2559/***/ }, 2560 2561/***/ 2360 2562(module, __unused_webpack_exports, __webpack_require__) { 2563 2564 2565/* global ActiveXObject -- old IE, WSH */ 2566var anObject = __webpack_require__(8551); 2567var definePropertiesModule = __webpack_require__(6801); 2568var enumBugKeys = __webpack_require__(8727); 2569var hiddenKeys = __webpack_require__(421); 2570var html = __webpack_require__(397); 2571var documentCreateElement = __webpack_require__(4055); 2572var sharedKey = __webpack_require__(6119); 2573 2574var GT = '>'; 2575var LT = '<'; 2576var PROTOTYPE = 'prototype'; 2577var SCRIPT = 'script'; 2578var IE_PROTO = sharedKey('IE_PROTO'); 2579 2580var EmptyConstructor = function () { /* empty */ }; 2581 2582var scriptTag = function (content) { 2583 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; 2584}; 2585 2586// Create object with fake `null` prototype: use ActiveX Object with cleared prototype 2587var NullProtoObjectViaActiveX = function (activeXDocument) { 2588 activeXDocument.write(scriptTag('')); 2589 activeXDocument.close(); 2590 var temp = activeXDocument.parentWindow.Object; 2591 // eslint-disable-next-line no-useless-assignment -- avoid memory leak 2592 activeXDocument = null; 2593 return temp; 2594}; 2595 2596// Create object with fake `null` prototype: use iframe Object with cleared prototype 2597var NullProtoObjectViaIFrame = function () { 2598 // Thrash, waste and sodomy: IE GC bug 2599 var iframe = documentCreateElement('iframe'); 2600 var JS = 'java' + SCRIPT + ':'; 2601 var iframeDocument; 2602 iframe.style.display = 'none'; 2603 html.appendChild(iframe); 2604 // https://github.com/zloirock/core-js/issues/475 2605 iframe.src = String(JS); 2606 iframeDocument = iframe.contentWindow.document; 2607 iframeDocument.open(); 2608 iframeDocument.write(scriptTag('document.F=Object')); 2609 iframeDocument.close(); 2610 return iframeDocument.F; 2611}; 2612 2613// Check for document.domain and active x support 2614// No need to use active x approach when document.domain is not set 2615// see https://github.com/es-shims/es5-shim/issues/150 2616// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 2617// avoid IE GC bug 2618var activeXDocument; 2619var NullProtoObject = function () { 2620 try { 2621 activeXDocument = new ActiveXObject('htmlfile'); 2622 } catch (error) { /* ignore */ } 2623 NullProtoObject = typeof document != 'undefined' 2624 ? document.domain && activeXDocument 2625 ? NullProtoObjectViaActiveX(activeXDocument) // old IE 2626 : NullProtoObjectViaIFrame() 2627 : NullProtoObjectViaActiveX(activeXDocument); // WSH 2628 var length = enumBugKeys.length; 2629 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; 2630 return NullProtoObject(); 2631}; 2632 2633hiddenKeys[IE_PROTO] = true; 2634 2635// `Object.create` method 2636// https://tc39.es/ecma262/#sec-object.create 2637// eslint-disable-next-line es/no-object-create -- safe 2638module.exports = Object.create || function create(O, Properties) { 2639 var result; 2640 if (O !== null) { 2641 EmptyConstructor[PROTOTYPE] = anObject(O); 2642 result = new EmptyConstructor(); 2643 EmptyConstructor[PROTOTYPE] = null; 2644 // add "__proto__" for Object.getPrototypeOf polyfill 2645 result[IE_PROTO] = O; 2646 } else result = NullProtoObject(); 2647 return Properties === undefined ? result : definePropertiesModule.f(result, Properties); 2648}; 2649 2650 2651/***/ }, 2652 2653/***/ 6801 2654(__unused_webpack_module, exports, __webpack_require__) { 2655 2656 2657var DESCRIPTORS = __webpack_require__(3724); 2658var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686); 2659var definePropertyModule = __webpack_require__(4913); 2660var anObject = __webpack_require__(8551); 2661var toIndexedObject = __webpack_require__(5397); 2662var objectKeys = __webpack_require__(1072); 2663 2664// `Object.defineProperties` method 2665// https://tc39.es/ecma262/#sec-object.defineproperties 2666// eslint-disable-next-line es/no-object-defineproperties -- safe 2667exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) { 2668 anObject(O); 2669 var props = toIndexedObject(Properties); 2670 var keys = objectKeys(Properties); 2671 var length = keys.length; 2672 var index = 0; 2673 var key; 2674 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]); 2675 return O; 2676}; 2677 2678 2679/***/ }, 2680 2681/***/ 4913 2682(__unused_webpack_module, exports, __webpack_require__) { 2683 2684 2685var DESCRIPTORS = __webpack_require__(3724); 2686var IE8_DOM_DEFINE = __webpack_require__(5917); 2687var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686); 2688var anObject = __webpack_require__(8551); 2689var toPropertyKey = __webpack_require__(6969); 2690 2691var $TypeError = TypeError; 2692// eslint-disable-next-line es/no-object-defineproperty -- safe 2693var $defineProperty = Object.defineProperty; 2694// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 2695var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 2696var ENUMERABLE = 'enumerable'; 2697var CONFIGURABLE = 'configurable'; 2698var WRITABLE = 'writable'; 2699 2700// `Object.defineProperty` method 2701// https://tc39.es/ecma262/#sec-object.defineproperty 2702exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { 2703 anObject(O); 2704 P = toPropertyKey(P); 2705 anObject(Attributes); 2706 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { 2707 var current = $getOwnPropertyDescriptor(O, P); 2708 if (current && current[WRITABLE]) { 2709 O[P] = Attributes.value; 2710 Attributes = { 2711 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], 2712 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], 2713 writable: false 2714 }; 2715 } 2716 } return $defineProperty(O, P, Attributes); 2717} : $defineProperty : function defineProperty(O, P, Attributes) { 2718 anObject(O); 2719 P = toPropertyKey(P); 2720 anObject(Attributes); 2721 if (IE8_DOM_DEFINE) try { 2722 return $defineProperty(O, P, Attributes); 2723 } catch (error) { /* empty */ } 2724 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported'); 2725 if ('value' in Attributes) O[P] = Attributes.value; 2726 return O; 2727}; 2728 2729 2730/***/ }, 2731 2732/***/ 7347 2733(__unused_webpack_module, exports, __webpack_require__) { 2734 2735 2736var DESCRIPTORS = __webpack_require__(3724); 2737var call = __webpack_require__(9565); 2738var propertyIsEnumerableModule = __webpack_require__(8773); 2739var createPropertyDescriptor = __webpack_require__(6980); 2740var toIndexedObject = __webpack_require__(5397); 2741var toPropertyKey = __webpack_require__(6969); 2742var hasOwn = __webpack_require__(9297); 2743var IE8_DOM_DEFINE = __webpack_require__(5917); 2744 2745// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 2746var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 2747 2748// `Object.getOwnPropertyDescriptor` method 2749// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor 2750exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { 2751 O = toIndexedObject(O); 2752 P = toPropertyKey(P); 2753 if (IE8_DOM_DEFINE) try { 2754 return $getOwnPropertyDescriptor(O, P); 2755 } catch (error) { /* empty */ } 2756 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); 2757}; 2758 2759 2760/***/ }, 2761 2762/***/ 8480 2763(__unused_webpack_module, exports, __webpack_require__) { 2764 2765 2766var internalObjectKeys = __webpack_require__(1828); 2767var enumBugKeys = __webpack_require__(8727); 2768 2769var hiddenKeys = enumBugKeys.concat('length', 'prototype'); 2770 2771// `Object.getOwnPropertyNames` method 2772// https://tc39.es/ecma262/#sec-object.getownpropertynames 2773// eslint-disable-next-line es/no-object-getownpropertynames -- safe 2774exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { 2775 return internalObjectKeys(O, hiddenKeys); 2776}; 2777 2778 2779/***/ }, 2780 2781/***/ 3717 2782(__unused_webpack_module, exports) { 2783 2784 2785// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe 2786exports.f = Object.getOwnPropertySymbols; 2787 2788 2789/***/ }, 2790 2791/***/ 2787 2792(module, __unused_webpack_exports, __webpack_require__) { 2793 2794 2795var hasOwn = __webpack_require__(9297); 2796var isCallable = __webpack_require__(4901); 2797var toObject = __webpack_require__(8981); 2798var sharedKey = __webpack_require__(6119); 2799var CORRECT_PROTOTYPE_GETTER = __webpack_require__(2211); 2800 2801var IE_PROTO = sharedKey('IE_PROTO'); 2802var $Object = Object; 2803var ObjectPrototype = $Object.prototype; 2804 2805// `Object.getPrototypeOf` method 2806// https://tc39.es/ecma262/#sec-object.getprototypeof 2807// eslint-disable-next-line es/no-object-getprototypeof -- safe 2808module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) { 2809 var object = toObject(O); 2810 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO]; 2811 var constructor = object.constructor; 2812 if (isCallable(constructor) && object instanceof constructor) { 2813 return constructor.prototype; 2814 } return object instanceof $Object ? ObjectPrototype : null; 2815}; 2816 2817 2818/***/ }, 2819 2820/***/ 1625 2821(module, __unused_webpack_exports, __webpack_require__) { 2822 2823 2824var uncurryThis = __webpack_require__(9504); 2825 2826module.exports = uncurryThis({}.isPrototypeOf); 2827 2828 2829/***/ }, 2830 2831/***/ 1828 2832(module, __unused_webpack_exports, __webpack_require__) { 2833 2834 2835var uncurryThis = __webpack_require__(9504); 2836var hasOwn = __webpack_require__(9297); 2837var toIndexedObject = __webpack_require__(5397); 2838var indexOf = (__webpack_require__(9617).indexOf); 2839var hiddenKeys = __webpack_require__(421); 2840 2841var push = uncurryThis([].push); 2842 2843module.exports = function (object, names) { 2844 var O = toIndexedObject(object); 2845 var i = 0; 2846 var result = []; 2847 var key; 2848 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key); 2849 // Don't enum bug & hidden keys 2850 while (names.length > i) if (hasOwn(O, key = names[i++])) { 2851 ~indexOf(result, key) || push(result, key); 2852 } 2853 return result; 2854}; 2855 2856 2857/***/ }, 2858 2859/***/ 1072 2860(module, __unused_webpack_exports, __webpack_require__) { 2861 2862 2863var internalObjectKeys = __webpack_require__(1828); 2864var enumBugKeys = __webpack_require__(8727); 2865 2866// `Object.keys` method 2867// https://tc39.es/ecma262/#sec-object.keys 2868// eslint-disable-next-line es/no-object-keys -- safe 2869module.exports = Object.keys || function keys(O) { 2870 return internalObjectKeys(O, enumBugKeys); 2871}; 2872 2873 2874/***/ }, 2875 2876/***/ 8773 2877(__unused_webpack_module, exports) { 2878 2879 2880var $propertyIsEnumerable = {}.propertyIsEnumerable; 2881// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 2882var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 2883 2884// Nashorn ~ JDK8 bug 2885var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1); 2886 2887// `Object.prototype.propertyIsEnumerable` method implementation 2888// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable 2889exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { 2890 var descriptor = getOwnPropertyDescriptor(this, V); 2891 return !!descriptor && descriptor.enumerable; 2892} : $propertyIsEnumerable; 2893 2894 2895/***/ }, 2896 2897/***/ 2967 2898(module, __unused_webpack_exports, __webpack_require__) { 2899 2900 2901/* eslint-disable no-proto -- safe */ 2902var uncurryThisAccessor = __webpack_require__(6706); 2903var isObject = __webpack_require__(34); 2904var requireObjectCoercible = __webpack_require__(7750); 2905var aPossiblePrototype = __webpack_require__(3506); 2906 2907// `Object.setPrototypeOf` method 2908// https://tc39.es/ecma262/#sec-object.setprototypeof 2909// Works with __proto__ only. Old v8 can't work with null proto objects. 2910// eslint-disable-next-line es/no-object-setprototypeof -- safe 2911module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { 2912 var CORRECT_SETTER = false; 2913 var test = {}; 2914 var setter; 2915 try { 2916 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); 2917 setter(test, []); 2918 CORRECT_SETTER = test instanceof Array; 2919 } catch (error) { /* empty */ } 2920 return function setPrototypeOf(O, proto) { 2921 requireObjectCoercible(O); 2922 aPossiblePrototype(proto); 2923 if (!isObject(O)) return O; 2924 if (CORRECT_SETTER) setter(O, proto); 2925 else O.__proto__ = proto; 2926 return O; 2927 }; 2928}() : undefined); 2929 2930 2931/***/ }, 2932 2933/***/
29334270 2934(module, __unused_webpack_exports, __webpack_require__) { 2935 2936 2937var call = __webpack_require__(9565); 2938var isCallable = __webpack_require__(4901); 2939var isObject = __webpack_require__(34); 2940 2941var $TypeError = TypeError; 2942 2943// `OrdinaryToPrimitive` abstract operation 2944// https://tc39.es/ecma262/#sec-ordinarytoprimitive 2945module.exports = function (input, pref) { 2946 var fn, val; 2947 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; 2948 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val; 2949 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; 2950 throw new $TypeError("Can't convert object to primitive value"); 2951}; 2952 2953 2954/***/ }, 2955 2956/***/ 5031 2957(module, __unused_webpack_exports, __webpack_require__) { 2958 2959 2960var getBuiltIn = __webpack_require__(7751); 2961var uncurryThis = __webpack_require__(9504); 2962var getOwnPropertyNamesModule = __webpack_require__(8480); 2963var getOwnPropertySymbolsModule = __webpack_require__(3717); 2964var anObject = __webpack_require__(8551); 2965
vendor: 6,000 bytes, lines 2966-3205
2966var concat = uncurryThis([].concat); 2967 2968// all object keys, includes non-enumerable and symbols 2969module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { 2970 var keys = getOwnPropertyNamesModule.f(anObject(it)); 2971 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; 2972 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys; 2973}; 2974 2975 2976/***/ }, 2977 2978/***/ 8235 2979(module, __unused_webpack_exports, __webpack_require__) { 2980 2981 2982var uncurryThis = __webpack_require__(9504); 2983var hasOwn = __webpack_require__(9297); 2984 2985var $SyntaxError = SyntaxError; 2986var $parseInt = parseInt; 2987var fromCharCode = String.fromCharCode; 2988var at = uncurryThis(''.charAt); 2989var slice = uncurryThis(''.slice); 2990var exec = uncurryThis(/./.exec); 2991 2992var codePoints = { 2993 '\\"': '"', 2994 '\\\\': '\\', 2995 '\\/': '/', 2996 '\\b': '\b', 2997 '\\f': '\f', 2998 '\\n': '\n', 2999 '\\r': '\r', 3000 '\\t': '\t' 3001}; 3002 3003var IS_4_HEX_DIGITS = /^[\da-f]{4}$/i; 3004// eslint-disable-next-line regexp/no-control-character -- safe 3005var IS_C0_CONTROL_CODE = /^[\u0000-\u001F]$/; 3006 3007module.exports = function (source, i) { 3008 var unterminated = true; 3009 var value = ''; 3010 while (i < source.length) { 3011 var chr = at(source, i); 3012 if (chr === '\\') { 3013 var twoChars = slice(source, i, i + 2); 3014 if (hasOwn(codePoints, twoChars)) { 3015 value += codePoints[twoChars]; 3016 i += 2; 3017 } else if (twoChars === '\\u') { 3018 i += 2; 3019 var fourHexDigits = slice(source, i, i + 4); 3020 if (!exec(IS_4_HEX_DIGITS, fourHexDigits)) throw new $SyntaxError('Bad Unicode escape at: ' + i); 3021 value += fromCharCode($parseInt(fourHexDigits, 16)); 3022 i += 4; 3023 } else throw new $SyntaxError('Unknown escape sequence: "' + twoChars + '"'); 3024 } else if (chr === '"') { 3025 unterminated = false; 3026 i++; 3027 break; 3028 } else { 3029 if (exec(IS_C0_CONTROL_CODE, chr)) throw new $SyntaxError('Bad control character in string literal at: ' + i); 3030 value += chr; 3031 i++; 3032 } 3033 } 3034 if (unterminated) throw new $SyntaxError('Unterminated string at: ' + i); 3035 return { value: value, end: i }; 3036}; 3037 3038 3039/***/ }, 3040 3041/***/ 1103 3042(module) { 3043 3044 3045module.exports = function (exec) { 3046 try { 3047 return { error: false, value: exec() }; 3048 } catch (error) { 3049 return { error: true, value: error }; 3050 } 3051}; 3052 3053 3054/***/ }, 3055 3056/***/ 7750 3057(module, __unused_webpack_exports, __webpack_require__) { 3058 3059 3060var isNullOrUndefined = __webpack_require__(4117); 3061 3062var $TypeError = TypeError; 3063 3064// `RequireObjectCoercible` abstract operation 3065// https://tc39.es/ecma262/#sec-requireobjectcoercible 3066module.exports = function (it) { 3067 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it); 3068 return it; 3069}; 3070 3071 3072/***/ }, 3073 3074/***/ 9286 3075(module, __unused_webpack_exports, __webpack_require__) { 3076 3077 3078var SetHelpers = __webpack_require__(4402); 3079var iterate = __webpack_require__(8469); 3080 3081var Set = SetHelpers.Set; 3082var add = SetHelpers.add; 3083 3084module.exports = function (set) { 3085 var result = new Set(); 3086 iterate(set, function (it) { 3087 add(result, it); 3088 }); 3089 return result; 3090}; 3091 3092 3093/***/ }, 3094 3095/***/ 3440 3096(module, __unused_webpack_exports, __webpack_require__) { 3097 3098 3099var aSet = __webpack_require__(7080); 3100var SetHelpers = __webpack_require__(4402); 3101var clone = __webpack_require__(9286); 3102var size = __webpack_require__(5170); 3103var getSetRecord = __webpack_require__(3789); 3104var iterateSet = __webpack_require__(8469); 3105var iterateSimple = __webpack_require__(507); 3106 3107var has = SetHelpers.has; 3108var remove = SetHelpers.remove; 3109 3110// `Set.prototype.difference` method 3111// https://tc39.es/ecma262/#sec-set.prototype.difference 3112module.exports = function difference(other) { 3113 var O = aSet(this); 3114 var otherRec = getSetRecord(other); 3115 var result = clone(O); 3116 if (size(O) <= otherRec.size) iterateSet(O, function (e) { 3117 if (otherRec.includes(e)) remove(result, e); 3118 }); 3119 else iterateSimple(otherRec.getIterator(), function (e) { 3120 if (has(result, e)) remove(result, e); 3121 }); 3122 return result; 3123}; 3124 3125 3126/***/ }, 3127 3128/***/ 4402 3129(module, __unused_webpack_exports, __webpack_require__) { 3130 3131 3132var uncurryThis = __webpack_require__(9504); 3133 3134// eslint-disable-next-line es/no-set -- safe 3135var SetPrototype = Set.prototype; 3136 3137module.exports = { 3138 // eslint-disable-next-line es/no-set -- safe 3139 Set: Set, 3140 add: uncurryThis(SetPrototype.add), 3141 has: uncurryThis(SetPrototype.has), 3142 remove: uncurryThis(SetPrototype['delete']), 3143 proto: SetPrototype 3144}; 3145 3146 3147/***/ }, 3148 3149/***/ 8750 3150(module, __unused_webpack_exports, __webpack_require__) { 3151 3152 3153var aSet = __webpack_require__(7080); 3154var SetHelpers = __webpack_require__(4402); 3155var size = __webpack_require__(5170); 3156var getSetRecord = __webpack_require__(3789); 3157var iterateSet = __webpack_require__(8469); 3158var iterateSimple = __webpack_require__(507); 3159 3160var Set = SetHelpers.Set; 3161var add = SetHelpers.add; 3162var has = SetHelpers.has; 3163 3164// `Set.prototype.intersection` method 3165// https://tc39.es/ecma262/#sec-set.prototype.intersection 3166module.exports = function intersection(other) { 3167 var O = aSet(this); 3168 var otherRec = getSetRecord(other); 3169 var result = new Set(); 3170 3171 if (size(O) > otherRec.size) { 3172 iterateSimple(otherRec.getIterator(), function (e) { 3173 if (has(O, e)) add(result, e); 3174 }); 3175 } else { 3176 iterateSet(O, function (e) { 3177 if (otherRec.includes(e)) add(result, e); 3178 }); 3179 } 3180 3181 return result; 3182}; 3183 3184 3185/***/ }, 3186 3187/***/ 4449 3188(module, __unused_webpack_exports, __webpack_require__) { 3189 3190 3191var aSet = __webpack_require__(7080); 3192var has = (__webpack_require__(4402).has); 3193var size = __webpack_require__(5170); 3194var getSetRecord = __webpack_require__(3789); 3195var iterateSet = __webpack_require__(8469); 3196var iterateSimple = __webpack_require__(507); 3197var iteratorClose = __webpack_require__(9539); 3198 3199// `Set.prototype.isDisjointFrom` method 3200// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom 3201module.exports = function isDisjointFrom(other) { 3202 var O = aSet(this); 3203 var otherRec = getSetRecord(other); 3204 if (size(O) <= otherRec.size) return iterateSet(O, function (e) { 3205 if (otherRec.includes(e)) return false;
vendor: 4,477 bytes, lines 3206-3381
3206 }, true) !== false; 3207 var iterator = otherRec.getIterator(); 3208 return iterateSimple(iterator, function (e) { 3209 if (has(O, e)) return iteratorClose(iterator, 'normal', false); 3210 }) !== false; 3211}; 3212 3213 3214/***/ }, 3215 3216/***/ 3838 3217(module, __unused_webpack_exports, __webpack_require__) { 3218 3219 3220var aSet = __webpack_require__(7080); 3221var size = __webpack_require__(5170); 3222var iterate = __webpack_require__(8469); 3223var getSetRecord = __webpack_require__(3789); 3224 3225// `Set.prototype.isSubsetOf` method 3226// https://tc39.es/ecma262/#sec-set.prototype.issubsetof 3227module.exports = function isSubsetOf(other) { 3228 var O = aSet(this); 3229 var otherRec = getSetRecord(other); 3230 if (size(O) > otherRec.size) return false; 3231 return iterate(O, function (e) { 3232 if (!otherRec.includes(e)) return false; 3233 }, true) !== false; 3234}; 3235 3236 3237/***/ }, 3238 3239/***/ 8527 3240(module, __unused_webpack_exports, __webpack_require__) { 3241 3242 3243var aSet = __webpack_require__(7080); 3244var has = (__webpack_require__(4402).has); 3245var size = __webpack_require__(5170); 3246var getSetRecord = __webpack_require__(3789); 3247var iterateSimple = __webpack_require__(507); 3248var iteratorClose = __webpack_require__(9539); 3249 3250// `Set.prototype.isSupersetOf` method 3251// https://tc39.es/ecma262/#sec-set.prototype.issupersetof 3252module.exports = function isSupersetOf(other) { 3253 var O = aSet(this); 3254 var otherRec = getSetRecord(other); 3255 if (size(O) < otherRec.size) return false; 3256 var iterator = otherRec.getIterator(); 3257 return iterateSimple(iterator, function (e) { 3258 if (!has(O, e)) return iteratorClose(iterator, 'normal', false); 3259 }) !== false; 3260}; 3261 3262 3263/***/ }, 3264 3265/***/ 8469 3266(module, __unused_webpack_exports, __webpack_require__) { 3267 3268 3269var uncurryThis = __webpack_require__(9504); 3270var iterateSimple = __webpack_require__(507); 3271var SetHelpers = __webpack_require__(4402); 3272 3273var Set = SetHelpers.Set; 3274var SetPrototype = SetHelpers.proto; 3275var forEach = uncurryThis(SetPrototype.forEach); 3276var keys = uncurryThis(SetPrototype.keys); 3277var next = keys(new Set()).next; 3278 3279module.exports = function (set, fn, interruptible) { 3280 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn); 3281}; 3282 3283 3284/***/ }, 3285 3286/***/ 4916 3287(module, __unused_webpack_exports, __webpack_require__) { 3288 3289 3290var getBuiltIn = __webpack_require__(7751); 3291 3292var createSetLike = function (size) { 3293 return { 3294 size: size, 3295 has: function () { 3296 return false; 3297 }, 3298 keys: function () { 3299 return { 3300 next: function () { 3301 return { done: true }; 3302 } 3303 }; 3304 } 3305 }; 3306}; 3307 3308var createSetLikeWithInfinitySize = function (size) { 3309 return { 3310 size: size, 3311 has: function () { 3312 return true; 3313 }, 3314 keys: function () { 3315 throw new Error('e'); 3316 } 3317 }; 3318}; 3319 3320module.exports = function (name, callback) { 3321 var Set = getBuiltIn('Set'); 3322 try { 3323 new Set()[name](createSetLike(0)); 3324 try { 3325 // late spec change, early WebKit ~ Safari 17 implementation does not pass it 3326 // https://github.com/tc39/proposal-set-methods/pull/88 3327 // also covered engines with 3328 // https://bugs.webkit.org/show_bug.cgi?id=272679 3329 new Set()[name](createSetLike(-1)); 3330 return false; 3331 } catch (error2) { 3332 if (!callback) return true; 3333 // early V8 implementation bug 3334 // https://issues.chromium.org/issues/351332634 3335 try { 3336 new Set()[name](createSetLikeWithInfinitySize(-Infinity)); 3337 return false; 3338 } catch (error) { 3339 var set = new Set([1, 2]); 3340 return callback(set[name](createSetLikeWithInfinitySize(Infinity))); 3341 } 3342 } 3343 } catch (error) { 3344 return false; 3345 } 3346}; 3347 3348 3349/***/ }, 3350 3351/***/ 9835 3352(module) { 3353 3354 3355// Should get iterator record of a set-like object before cloning this 3356// https://bugs.webkit.org/show_bug.cgi?id=289430 3357module.exports = function (METHOD_NAME) { 3358 try { 3359 // eslint-disable-next-line es/no-set -- needed for test 3360 var baseSet = new Set(); 3361 var setLike = { 3362 size: 0, 3363 has: function () { return true; }, 3364 keys: function () { 3365 // eslint-disable-next-line es/no-object-defineproperty -- needed for test 3366 return Object.defineProperty({}, 'next', { 3367 get: function () { 3368 baseSet.clear(); 3369 baseSet.add(4); 3370 return function () { 3371 return { done: true }; 3372 }; 3373 } 3374 }); 3375 } 3376 }; 3377 var result = baseSet[METHOD_NAME](setLike); 3378 3379 return result.size === 1 && result.values().next().value === 4; 3380 } catch (error) { 3381 return false;
vendor: 4,239 bytes, lines 3382-3545
3382 } 3383}; 3384 3385 3386/***/ }, 3387 3388/***/ 5170 3389(module, __unused_webpack_exports, __webpack_require__) { 3390 3391 3392var uncurryThisAccessor = __webpack_require__(6706); 3393var SetHelpers = __webpack_require__(4402); 3394 3395module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) { 3396 return set.size; 3397}; 3398 3399 3400/***/ }, 3401 3402/***/ 3650 3403(module, __unused_webpack_exports, __webpack_require__) { 3404 3405 3406var aSet = __webpack_require__(7080); 3407var SetHelpers = __webpack_require__(4402); 3408var clone = __webpack_require__(9286); 3409var getSetRecord = __webpack_require__(3789); 3410var iterateSimple = __webpack_require__(507); 3411 3412var add = SetHelpers.add; 3413var has = SetHelpers.has; 3414var remove = SetHelpers.remove; 3415 3416// `Set.prototype.symmetricDifference` method 3417// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference 3418module.exports = function symmetricDifference(other) { 3419 var O = aSet(this); 3420 var keysIter = getSetRecord(other).getIterator(); 3421 var result = clone(O); 3422 iterateSimple(keysIter, function (e) { 3423 if (has(O, e)) remove(result, e); 3424 else add(result, e); 3425 }); 3426 return result; 3427}; 3428 3429 3430/***/ }, 3431 3432/***/ 4204 3433(module, __unused_webpack_exports, __webpack_require__) { 3434 3435 3436var aSet = __webpack_require__(7080); 3437var add = (__webpack_require__(4402).add); 3438var clone = __webpack_require__(9286); 3439var getSetRecord = __webpack_require__(3789); 3440var iterateSimple = __webpack_require__(507); 3441 3442// `Set.prototype.union` method 3443// https://tc39.es/ecma262/#sec-set.prototype.union 3444module.exports = function union(other) { 3445 var O = aSet(this); 3446 var keysIter = getSetRecord(other).getIterator(); 3447 var result = clone(O); 3448 iterateSimple(keysIter, function (it) { 3449 add(result, it); 3450 }); 3451 return result; 3452}; 3453 3454 3455/***/ }, 3456 3457/***/ 6119 3458(module, __unused_webpack_exports, __webpack_require__) { 3459 3460 3461var shared = __webpack_require__(5745); 3462var uid = __webpack_require__(3392); 3463 3464var keys = shared('keys'); 3465 3466module.exports = function (key) { 3467 return keys[key] || (keys[key] = uid(key)); 3468}; 3469 3470 3471/***/ }, 3472 3473/***/ 7629 3474(module, __unused_webpack_exports, __webpack_require__) { 3475 3476 3477var IS_PURE = __webpack_require__(6395); 3478var globalThis = __webpack_require__(4576); 3479var defineGlobalProperty = __webpack_require__(9433); 3480 3481var SHARED = '__core-js_shared__'; 3482var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {}); 3483 3484(store.versions || (store.versions = [])).push({ 3485 version: '3.48.0', 3486 mode: IS_PURE ? 'pure' : 'global', 3487 copyright: '© 2013â2025 Denis Pushkarev (zloirock.ru), 2025â2026 CoreJS Company (core-js.io). All rights reserved.', 3488 license: 'https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE', 3489 source: 'https://github.com/zloirock/core-js' 3490}); 3491 3492 3493/***/ }, 3494 3495/***/ 5745 3496(module, __unused_webpack_exports, __webpack_require__) { 3497 3498 3499var store = __webpack_require__(7629); 3500 3501module.exports = function (key, value) { 3502 return store[key] || (store[key] = value || {}); 3503}; 3504 3505 3506/***/ }, 3507 3508/***/ 1548 3509(module, __unused_webpack_exports, __webpack_require__) { 3510 3511 3512var globalThis = __webpack_require__(4576); 3513var fails = __webpack_require__(9039); 3514var V8 = __webpack_require__(9519); 3515var ENVIRONMENT = __webpack_require__(4215); 3516 3517var structuredClone = globalThis.structuredClone; 3518 3519module.exports = !!structuredClone && !fails(function () { 3520 // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation 3521 // https://github.com/zloirock/core-js/issues/679 3522 if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false; 3523 var buffer = new ArrayBuffer(8); 3524 var clone = structuredClone(buffer, { transfer: [buffer] }); 3525 return buffer.byteLength !== 0 || clone.byteLength !== 8; 3526}); 3527 3528 3529/***/ }, 3530 3531/***/ 4495 3532(module, __unused_webpack_exports, __webpack_require__) { 3533 3534 3535/* eslint-disable es/no-symbol -- required for testing */ 3536var V8_VERSION = __webpack_require__(9519); 3537var fails = __webpack_require__(9039); 3538var globalThis = __webpack_require__(4576); 3539 3540var $String = globalThis.String; 3541 3542// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing 3543module.exports = !!Object.getOwnPropertySymbols && !fails(function () { 3544 var symbol = Symbol('symbol detection'); 3545 // Chrome 38 Symbol has incorrect toString conversion
vendor: 7,346 bytes, lines 3546-3847
3546 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances 3547 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will, 3548 // of course, fail. 3549 return !$String(symbol) || !(Object(symbol) instanceof Symbol) || 3550 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances 3551 !Symbol.sham && V8_VERSION && V8_VERSION < 41; 3552}); 3553 3554 3555/***/ }, 3556 3557/***/ 5610 3558(module, __unused_webpack_exports, __webpack_require__) { 3559 3560 3561var toIntegerOrInfinity = __webpack_require__(1291); 3562 3563var max = Math.max; 3564var min = Math.min; 3565 3566// Helper for a popular repeating case of the spec: 3567// Let integer be ? ToInteger(index). 3568// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). 3569module.exports = function (index, length) { 3570 var integer = toIntegerOrInfinity(index); 3571 return integer < 0 ? max(integer + length, 0) : min(integer, length); 3572}; 3573 3574 3575/***/ }, 3576 3577/***/ 5854 3578(module, __unused_webpack_exports, __webpack_require__) { 3579 3580 3581var toPrimitive = __webpack_require__(2777); 3582 3583var $TypeError = TypeError; 3584 3585// `ToBigInt` abstract operation 3586// https://tc39.es/ecma262/#sec-tobigint 3587module.exports = function (argument) { 3588 var prim = toPrimitive(argument, 'number'); 3589 if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint"); 3590 // eslint-disable-next-line es/no-bigint -- safe 3591 return BigInt(prim); 3592}; 3593 3594 3595/***/ }, 3596 3597/***/ 7696 3598(module, __unused_webpack_exports, __webpack_require__) { 3599 3600 3601var toIntegerOrInfinity = __webpack_require__(1291); 3602var toLength = __webpack_require__(8014); 3603 3604var $RangeError = RangeError; 3605 3606// `ToIndex` abstract operation 3607// https://tc39.es/ecma262/#sec-toindex 3608module.exports = function (it) { 3609 if (it === undefined) return 0; 3610 var number = toIntegerOrInfinity(it); 3611 var length = toLength(number); 3612 if (number !== length) throw new $RangeError('Wrong length or index'); 3613 return length; 3614}; 3615 3616 3617/***/ }, 3618 3619/***/ 5397 3620(module, __unused_webpack_exports, __webpack_require__) { 3621 3622 3623// toObject with fallback for non-array-like ES3 strings 3624var IndexedObject = __webpack_require__(7055); 3625var requireObjectCoercible = __webpack_require__(7750); 3626 3627module.exports = function (it) { 3628 return IndexedObject(requireObjectCoercible(it)); 3629}; 3630 3631 3632/***/ }, 3633 3634/***/ 1291 3635(module, __unused_webpack_exports, __webpack_require__) { 3636 3637 3638var trunc = __webpack_require__(741); 3639 3640// `ToIntegerOrInfinity` abstract operation 3641// https://tc39.es/ecma262/#sec-tointegerorinfinity 3642module.exports = function (argument) { 3643 var number = +argument; 3644 // eslint-disable-next-line no-self-compare -- NaN check 3645 return number !== number || number === 0 ? 0 : trunc(number); 3646}; 3647 3648 3649/***/ }, 3650 3651/***/ 8014 3652(module, __unused_webpack_exports, __webpack_require__) { 3653 3654 3655var toIntegerOrInfinity = __webpack_require__(1291); 3656 3657var min = Math.min; 3658 3659// `ToLength` abstract operation 3660// https://tc39.es/ecma262/#sec-tolength 3661module.exports = function (argument) { 3662 var len = toIntegerOrInfinity(argument); 3663 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 3664}; 3665 3666 3667/***/ }, 3668 3669/***/ 8981 3670(module, __unused_webpack_exports, __webpack_require__) { 3671 3672 3673var requireObjectCoercible = __webpack_require__(7750); 3674 3675var $Object = Object; 3676 3677// `ToObject` abstract operation 3678// https://tc39.es/ecma262/#sec-toobject 3679module.exports = function (argument) { 3680 return $Object(requireObjectCoercible(argument)); 3681}; 3682 3683 3684/***/ }, 3685 3686/***/ 9590 3687(module, __unused_webpack_exports, __webpack_require__) { 3688 3689 3690var toIntegerOrInfinity = __webpack_require__(1291); 3691 3692var $RangeError = RangeError; 3693 3694module.exports = function (it) { 3695 var result = toIntegerOrInfinity(it); 3696 if (result < 0) throw new $RangeError("The argument can't be less than 0"); 3697 return result; 3698}; 3699 3700 3701/***/ }, 3702 3703/***/ 2777 3704(module, __unused_webpack_exports, __webpack_require__) { 3705 3706 3707var call = __webpack_require__(9565); 3708var isObject = __webpack_require__(34); 3709var isSymbol = __webpack_require__(757); 3710var getMethod = __webpack_require__(5966); 3711var ordinaryToPrimitive = __webpack_require__(4270); 3712var wellKnownSymbol = __webpack_require__(8227); 3713 3714var $TypeError = TypeError; 3715var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); 3716 3717// `ToPrimitive` abstract operation 3718// https://tc39.es/ecma262/#sec-toprimitive 3719module.exports = function (input, pref) { 3720 if (!isObject(input) || isSymbol(input)) return input; 3721 var exoticToPrim = getMethod(input, TO_PRIMITIVE); 3722 var result; 3723 if (exoticToPrim) { 3724 if (pref === undefined) pref = 'default'; 3725 result = call(exoticToPrim, input, pref); 3726 if (!isObject(result) || isSymbol(result)) return result; 3727 throw new $TypeError("Can't convert object to primitive value"); 3728 } 3729 if (pref === undefined) pref = 'number'; 3730 return ordinaryToPrimitive(input, pref); 3731}; 3732 3733 3734/***/ }, 3735 3736/***/ 6969 3737(module, __unused_webpack_exports, __webpack_require__) { 3738 3739 3740var toPrimitive = __webpack_require__(2777); 3741var isSymbol = __webpack_require__(757); 3742 3743// `ToPropertyKey` abstract operation 3744// https://tc39.es/ecma262/#sec-topropertykey 3745module.exports = function (argument) { 3746 var key = toPrimitive(argument, 'string'); 3747 return isSymbol(key) ? key : key + ''; 3748}; 3749 3750 3751/***/ }, 3752 3753/***/ 2140 3754(module, __unused_webpack_exports, __webpack_require__) { 3755 3756 3757var wellKnownSymbol = __webpack_require__(8227); 3758 3759var TO_STRING_TAG = wellKnownSymbol('toStringTag'); 3760var test = {}; 3761// eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation 3762test[TO_STRING_TAG] = 'z'; 3763 3764module.exports = String(test) === '[object z]'; 3765 3766 3767/***/ }, 3768 3769/***/ 655 3770(module, __unused_webpack_exports, __webpack_require__) { 3771 3772 3773var classof = __webpack_require__(6955); 3774 3775var $String = String; 3776 3777module.exports = function (argument) { 3778 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string'); 3779 return $String(argument); 3780}; 3781 3782 3783/***/ }, 3784 3785/***/ 6823 3786(module) { 3787 3788 3789var $String = String; 3790 3791module.exports = function (argument) { 3792 try { 3793 return $String(argument); 3794 } catch (error) { 3795 return 'Object'; 3796 } 3797}; 3798 3799 3800/***/ }, 3801 3802/***/ 3392 3803(module, __unused_webpack_exports, __webpack_require__) { 3804 3805 3806var uncurryThis = __webpack_require__(9504); 3807 3808var id = 0; 3809var postfix = Math.random(); 3810var toString = uncurryThis(1.1.toString); 3811 3812module.exports = function (key) { 3813 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36); 3814}; 3815 3816 3817/***/ }, 3818 3819/***/ 9143 3820(module, __unused_webpack_exports, __webpack_require__) { 3821 3822 3823var globalThis = __webpack_require__(4576); 3824var uncurryThis = __webpack_require__(9504); 3825var anObjectOrUndefined = __webpack_require__(3972); 3826var aString = __webpack_require__(3463); 3827var hasOwn = __webpack_require__(9297); 3828var base64Map = __webpack_require__(2804); 3829var getAlphabetOption = __webpack_require__(944); 3830var notDetached = __webpack_require__(5169); 3831 3832var base64Alphabet = base64Map.c2i; 3833var base64UrlAlphabet = base64Map.c2iUrl; 3834 3835var SyntaxError = globalThis.SyntaxError; 3836var TypeError = globalThis.TypeError; 3837var at = uncurryThis(''.charAt); 3838 3839var skipAsciiWhitespace = function (string, index) { 3840 var length = string.length; 3841 for (;index < length; index++) { 3842 var chr = at(string, index); 3843 if (chr !== ' ' && chr !== '\t' && chr !== '\n' && chr !== '\f' && chr !== '\r') break; 3844 } return index; 3845}; 3846 3847var decodeBase64Chunk = function (chunk, alphabet, throwOnExtraBits) {
vendor: 5,550 bytes, lines 3848-4033
3848 var chunkLength = chunk.length; 3849 3850 if (chunkLength < 4) { 3851 chunk += chunkLength === 2 ? 'AA' : 'A'; 3852 } 3853 3854 var triplet = (alphabet[at(chunk, 0)] << 18) 3855 + (alphabet[at(chunk, 1)] << 12) 3856 + (alphabet[at(chunk, 2)] << 6) 3857 + alphabet[at(chunk, 3)]; 3858 3859 var chunkBytes = [ 3860 (triplet >> 16) & 255, 3861 (triplet >> 8) & 255, 3862 triplet & 255 3863 ]; 3864 3865 if (chunkLength === 2) { 3866 if (throwOnExtraBits && chunkBytes[1] !== 0) { 3867 throw new SyntaxError('Extra bits'); 3868 } 3869 return [chunkBytes[0]]; 3870 } 3871 3872 if (chunkLength === 3) { 3873 if (throwOnExtraBits && chunkBytes[2] !== 0) { 3874 throw new SyntaxError('Extra bits'); 3875 } 3876 return [chunkBytes[0], chunkBytes[1]]; 3877 } 3878 3879 return chunkBytes; 3880}; 3881 3882var writeBytes = function (bytes, elements, written) { 3883 var elementsLength = elements.length; 3884 for (var index = 0; index < elementsLength; index++) { 3885 bytes[written + index] = elements[index]; 3886 } 3887 return written + elementsLength; 3888}; 3889 3890/* eslint-disable max-statements, max-depth -- TODO */ 3891module.exports = function (string, options, into, maxLength) { 3892 aString(string); 3893 anObjectOrUndefined(options); 3894 var alphabet = getAlphabetOption(options) === 'base64' ? base64Alphabet : base64UrlAlphabet; 3895 var lastChunkHandling = options ? options.lastChunkHandling : undefined; 3896 3897 if (lastChunkHandling === undefined) lastChunkHandling = 'loose'; 3898 3899 if (lastChunkHandling !== 'loose' && lastChunkHandling !== 'strict' && lastChunkHandling !== 'stop-before-partial') { 3900 throw new TypeError('Incorrect `lastChunkHandling` option'); 3901 } 3902 3903 if (into) notDetached(into.buffer); 3904 3905 var stringLength = string.length; 3906 var bytes = into || []; 3907 var written = 0; 3908 var read = 0; 3909 var chunk = ''; 3910 var index = 0; 3911 3912 if (maxLength) while (true) { 3913 index = skipAsciiWhitespace(string, index); 3914 if (index === stringLength) { 3915 if (chunk.length > 0) { 3916 if (lastChunkHandling === 'stop-before-partial') { 3917 break; 3918 } 3919 if (lastChunkHandling === 'loose') { 3920 if (chunk.length === 1) { 3921 throw new SyntaxError('Malformed padding: exactly one additional character'); 3922 } 3923 written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written); 3924 } else { 3925 throw new SyntaxError('Missing padding'); 3926 } 3927 } 3928 read = stringLength; 3929 break; 3930 } 3931 var chr = at(string, index); 3932 ++index; 3933 if (chr === '=') { 3934 if (chunk.length < 2) { 3935 throw new SyntaxError('Padding is too early'); 3936 } 3937 index = skipAsciiWhitespace(string, index); 3938 if (chunk.length === 2) { 3939 if (index === stringLength) { 3940 if (lastChunkHandling === 'stop-before-partial') { 3941 break; 3942 } 3943 throw new SyntaxError('Malformed padding: only one ='); 3944 } 3945 if (at(string, index) === '=') { 3946 ++index; 3947 index = skipAsciiWhitespace(string, index); 3948 } 3949 } 3950 if (index < stringLength) { 3951 throw new SyntaxError('Unexpected character after padding'); 3952 } 3953 written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, lastChunkHandling === 'strict'), written); 3954 read = stringLength; 3955 break; 3956 } 3957 if (!hasOwn(alphabet, chr)) { 3958 throw new SyntaxError('Unexpected character'); 3959 } 3960 var remainingBytes = maxLength - written; 3961 if (remainingBytes === 1 && chunk.length === 2 || remainingBytes === 2 && chunk.length === 3) { 3962 // special case: we can fit exactly the number of bytes currently represented by chunk, so we were just checking for `=` 3963 break; 3964 } 3965 3966 chunk += chr; 3967 if (chunk.length === 4) { 3968 written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written); 3969 chunk = ''; 3970 read = index; 3971 if (written === maxLength) { 3972 break; 3973 } 3974 } 3975 } 3976 3977 return { bytes: bytes, read: read, written: written }; 3978}; 3979 3980 3981/***/ }, 3982 3983/***/ 2303 3984(module, __unused_webpack_exports, __webpack_require__) { 3985 3986 3987var globalThis = __webpack_require__(4576); 3988var uncurryThis = __webpack_require__(9504); 3989 3990var Uint8Array = globalThis.Uint8Array; 3991var SyntaxError = globalThis.SyntaxError; 3992var parseInt = globalThis.parseInt; 3993var min = Math.min; 3994var NOT_HEX = /[^\da-f]/i; 3995var exec = uncurryThis(NOT_HEX.exec); 3996var stringSlice = uncurryThis(''.slice); 3997 3998module.exports = function (string, into) { 3999 var stringLength = string.length; 4000 if (stringLength % 2 !== 0) throw new SyntaxError('String should be an even number of characters'); 4001 var maxLength = into ? min(into.length, stringLength / 2) : stringLength / 2; 4002 var bytes = into || new Uint8Array(maxLength); 4003 var read = 0; 4004 var written = 0; 4005 while (written < maxLength) { 4006 var hexits = stringSlice(string, read, read += 2); 4007 if (exec(NOT_HEX, hexits)) throw new SyntaxError('String should only contain hex characters'); 4008 bytes[written++] = parseInt(hexits, 16); 4009 } 4010 return { bytes: bytes, read: read }; 4011}; 4012 4013 4014/***/ }, 4015 4016/***/ 7416 4017(module, __unused_webpack_exports, __webpack_require__) { 4018 4019 4020var fails = __webpack_require__(9039); 4021var wellKnownSymbol = __webpack_require__(8227); 4022var DESCRIPTORS = __webpack_require__(3724); 4023var IS_PURE = __webpack_require__(6395); 4024 4025var ITERATOR = wellKnownSymbol('iterator'); 4026 4027module.exports = !fails(function () { 4028 // eslint-disable-next-line unicorn/relative-url-style -- required for testing 4029 var url = new URL('b?a=1&b=2&c=3', 'https://a'); 4030 var params = url.searchParams; 4031 var params2 = new URLSearchParams('a=1&a=2&b=3'); 4032 var result = ''; 4033 url.pathname = 'c%20d';
vendor: 4,451 bytes, lines 4034-4204
4034 params.forEach(function (value, key) { 4035 params['delete']('b'); 4036 result += key + value; 4037 }); 4038 params2['delete']('a', 2); 4039 // `undefined` case is a Chromium 117 bug 4040 // https://bugs.chromium.org/p/v8/issues/detail?id=14222 4041 params2['delete']('b', undefined); 4042 return (IS_PURE && (!url.toJSON || !params2.has('a', 1) || params2.has('a', 2) || !params2.has('a', undefined) || params2.has('b'))) 4043 || (!params.size && (IS_PURE || !DESCRIPTORS)) 4044 || !params.sort 4045 || url.href !== 'https://a/c%20d?a=1&c=3' 4046 || params.get('c') !== '3' 4047 || String(new URLSearchParams('?a=1')) !== 'a=1' 4048 || !params[ITERATOR] 4049 // throws in Edge 4050 || new URL('https://a@b').username !== 'a' 4051 || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' 4052 // not punycoded in Edge 4053 || new URL('https://ÑеÑÑ').host !== 'xn--e1aybc' 4054 // not escaped in Chrome 62- 4055 || new URL('https://a#б').hash !== '#%D0%B1' 4056 // fails in Chrome 66- 4057 || result !== 'a1c3' 4058 // throws in Safari 4059 || new URL('https://x', undefined).host !== 'x'; 4060}); 4061 4062 4063/***/ }, 4064 4065/***/ 7040 4066(module, __unused_webpack_exports, __webpack_require__) { 4067 4068 4069/* eslint-disable es/no-symbol -- required for testing */ 4070var NATIVE_SYMBOL = __webpack_require__(4495); 4071 4072module.exports = NATIVE_SYMBOL && 4073 !Symbol.sham && 4074 typeof Symbol.iterator == 'symbol'; 4075 4076 4077/***/ }, 4078 4079/***/ 8686 4080(module, __unused_webpack_exports, __webpack_require__) { 4081 4082 4083var DESCRIPTORS = __webpack_require__(3724); 4084var fails = __webpack_require__(9039); 4085 4086// V8 ~ Chrome 36- 4087// https://bugs.chromium.org/p/v8/issues/detail?id=3334 4088module.exports = DESCRIPTORS && fails(function () { 4089 // eslint-disable-next-line es/no-object-defineproperty -- required for testing 4090 return Object.defineProperty(function () { /* empty */ }, 'prototype', { 4091 value: 42, 4092 writable: false 4093 }).prototype !== 42; 4094}); 4095 4096 4097/***/ }, 4098 4099/***/ 2812 4100(module) { 4101 4102 4103var $TypeError = TypeError; 4104 4105module.exports = function (passed, required) { 4106 if (passed < required) throw new $TypeError('Not enough arguments'); 4107 return passed; 4108}; 4109 4110 4111/***/ }, 4112 4113/***/ 8622 4114(module, __unused_webpack_exports, __webpack_require__) { 4115 4116 4117var globalThis = __webpack_require__(4576); 4118var isCallable = __webpack_require__(4901); 4119 4120var WeakMap = globalThis.WeakMap; 4121 4122module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap)); 4123 4124 4125/***/ }, 4126 4127/***/ 4995 4128(module, __unused_webpack_exports, __webpack_require__) { 4129 4130 4131var uncurryThis = __webpack_require__(9504); 4132 4133// eslint-disable-next-line es/no-weak-map -- safe 4134var WeakMapPrototype = WeakMap.prototype; 4135 4136module.exports = { 4137 // eslint-disable-next-line es/no-weak-map -- safe 4138 WeakMap: WeakMap, 4139 set: uncurryThis(WeakMapPrototype.set), 4140 get: uncurryThis(WeakMapPrototype.get), 4141 has: uncurryThis(WeakMapPrototype.has), 4142 remove: uncurryThis(WeakMapPrototype['delete']) 4143}; 4144 4145 4146/***/ }, 4147 4148/***/ 8227 4149(module, __unused_webpack_exports, __webpack_require__) { 4150 4151 4152var globalThis = __webpack_require__(4576); 4153var shared = __webpack_require__(5745); 4154var hasOwn = __webpack_require__(9297); 4155var uid = __webpack_require__(3392); 4156var NATIVE_SYMBOL = __webpack_require__(4495); 4157var USE_SYMBOL_AS_UID = __webpack_require__(7040); 4158 4159var Symbol = globalThis.Symbol; 4160var WellKnownSymbolsStore = shared('wks'); 4161var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid; 4162 4163module.exports = function (name) { 4164 if (!hasOwn(WellKnownSymbolsStore, name)) { 4165 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name) 4166 ? Symbol[name] 4167 : createWellKnownSymbol('Symbol.' + name); 4168 } return WellKnownSymbolsStore[name]; 4169}; 4170 4171 4172/***/ }, 4173 4174/***/ 6573 4175(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4176 4177 4178var DESCRIPTORS = __webpack_require__(3724); 4179var defineBuiltInAccessor = __webpack_require__(2106); 4180var isDetached = __webpack_require__(3238); 4181 4182var ArrayBufferPrototype = ArrayBuffer.prototype; 4183 4184// `ArrayBuffer.prototype.detached` getter 4185// https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.detached 4186if (DESCRIPTORS && !('detached' in ArrayBufferPrototype)) { 4187 defineBuiltInAccessor(ArrayBufferPrototype, 'detached', { 4188 configurable: true, 4189 get: function detached() { 4190 return isDetached(this); 4191 } 4192 }); 4193} 4194 4195 4196/***/ }, 4197 4198/***/ 7936 4199(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4200 4201 4202var $ = __webpack_require__(6518); 4203var $transfer = __webpack_require__(5636); 4204
vendor: 5,196 bytes, lines 4205-4366
4205// `ArrayBuffer.prototype.transferToFixedLength` method 4206// https://tc39.es/ecma262/#sec-arraybuffer.prototype.transfertofixedlength 4207if ($transfer) $({ target: 'ArrayBuffer', proto: true }, { 4208 transferToFixedLength: function transferToFixedLength() { 4209 return $transfer(this, arguments.length ? arguments[0] : undefined, false); 4210 } 4211}); 4212 4213 4214/***/ }, 4215 4216/***/ 8100 4217(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4218 4219 4220var $ = __webpack_require__(6518); 4221var $transfer = __webpack_require__(5636); 4222 4223// `ArrayBuffer.prototype.transfer` method 4224// https://tc39.es/ecma262/#sec-arraybuffer.prototype.transfer 4225if ($transfer) $({ target: 'ArrayBuffer', proto: true }, { 4226 transfer: function transfer() { 4227 return $transfer(this, arguments.length ? arguments[0] : undefined, true); 4228 } 4229}); 4230 4231 4232/***/ }, 4233 4234/***/ 4114 4235(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4236 4237 4238var $ = __webpack_require__(6518); 4239var toObject = __webpack_require__(8981); 4240var lengthOfArrayLike = __webpack_require__(6198); 4241var setArrayLength = __webpack_require__(4527); 4242var doesNotExceedSafeInteger = __webpack_require__(6837); 4243var fails = __webpack_require__(9039); 4244 4245var INCORRECT_TO_LENGTH = fails(function () { 4246 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297; 4247}); 4248 4249// V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError 4250// https://bugs.chromium.org/p/v8/issues/detail?id=12681 4251var properErrorOnNonWritableLength = function () { 4252 try { 4253 // eslint-disable-next-line es/no-object-defineproperty -- safe 4254 Object.defineProperty([], 'length', { writable: false }).push(); 4255 } catch (error) { 4256 return error instanceof TypeError; 4257 } 4258}; 4259 4260var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength(); 4261 4262// `Array.prototype.push` method 4263// https://tc39.es/ecma262/#sec-array.prototype.push 4264$({ target: 'Array', proto: true, arity: 1, forced: FORCED }, { 4265 // eslint-disable-next-line no-unused-vars -- required for `.length` 4266 push: function push(item) { 4267 var O = toObject(this); 4268 var len = lengthOfArrayLike(O); 4269 var argCount = arguments.length; 4270 doesNotExceedSafeInteger(len + argCount); 4271 for (var i = 0; i < argCount; i++) { 4272 O[len] = arguments[i]; 4273 len++; 4274 } 4275 setArrayLength(O, len); 4276 return len; 4277 } 4278}); 4279 4280 4281/***/ }, 4282 4283/***/ 8111 4284(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4285 4286 4287var $ = __webpack_require__(6518); 4288var globalThis = __webpack_require__(4576); 4289var anInstance = __webpack_require__(679); 4290var anObject = __webpack_require__(8551); 4291var isCallable = __webpack_require__(4901); 4292var getPrototypeOf = __webpack_require__(2787); 4293var defineBuiltInAccessor = __webpack_require__(2106); 4294var createProperty = __webpack_require__(4659); 4295var fails = __webpack_require__(9039); 4296var hasOwn = __webpack_require__(9297); 4297var wellKnownSymbol = __webpack_require__(8227); 4298var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype); 4299var DESCRIPTORS = __webpack_require__(3724); 4300var IS_PURE = __webpack_require__(6395); 4301 4302var CONSTRUCTOR = 'constructor'; 4303var ITERATOR = 'Iterator'; 4304var TO_STRING_TAG = wellKnownSymbol('toStringTag'); 4305 4306var $TypeError = TypeError; 4307var NativeIterator = globalThis[ITERATOR]; 4308 4309// FF56- have non-standard global helper `Iterator` 4310var FORCED = IS_PURE 4311 || !isCallable(NativeIterator) 4312 || NativeIterator.prototype !== IteratorPrototype 4313 // FF44- non-standard `Iterator` passes previous tests 4314 || !fails(function () { NativeIterator({}); }); 4315 4316var IteratorConstructor = function Iterator() { 4317 anInstance(this, IteratorPrototype); 4318 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable'); 4319}; 4320 4321var defineIteratorPrototypeAccessor = function (key, value) { 4322 if (DESCRIPTORS) { 4323 defineBuiltInAccessor(IteratorPrototype, key, { 4324 configurable: true, 4325 get: function () { 4326 return value; 4327 }, 4328 set: function (replacement) { 4329 anObject(this); 4330 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property"); 4331 if (hasOwn(this, key)) this[key] = replacement; 4332 else createProperty(this, key, replacement); 4333 } 4334 }); 4335 } else IteratorPrototype[key] = value; 4336}; 4337 4338if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR); 4339 4340if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) { 4341 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor); 4342} 4343 4344IteratorConstructor.prototype = IteratorPrototype; 4345 4346// `Iterator` constructor 4347// https://tc39.es/ecma262/#sec-iterator 4348$({ global: true, constructor: true, forced: FORCED }, { 4349 Iterator: IteratorConstructor 4350}); 4351 4352 4353/***/ }, 4354 4355/***/ 9314 4356(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4357 4358 4359var $ = __webpack_require__(6518); 4360var call = __webpack_require__(9565); 4361var anObject = __webpack_require__(8551); 4362var getIteratorDirect = __webpack_require__(1767); 4363var notANaN = __webpack_require__(4149); 4364var toPositiveInteger = __webpack_require__(9590); 4365var iteratorClose = __webpack_require__(9539); 4366var createIteratorProxy = __webpack_require__(9462);
vendor: 5,929 bytes, lines 4367-4541
4367var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684); 4368var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4369var IS_PURE = __webpack_require__(6395); 4370 4371var DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('drop', 0); 4372var dropWithoutClosingOnEarlyError = !IS_PURE && !DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR 4373 && iteratorHelperWithoutClosingOnEarlyError('drop', RangeError); 4374 4375var FORCED = IS_PURE || DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR || dropWithoutClosingOnEarlyError; 4376 4377var IteratorProxy = createIteratorProxy(function () { 4378 var iterator = this.iterator; 4379 var next = this.next; 4380 var result, done; 4381 while (this.remaining) { 4382 this.remaining--; 4383 result = anObject(call(next, iterator)); 4384 done = this.done = !!result.done; 4385 if (done) return; 4386 } 4387 result = anObject(call(next, iterator)); 4388 done = this.done = !!result.done; 4389 if (!done) return result.value; 4390}); 4391 4392// `Iterator.prototype.drop` method 4393// https://tc39.es/ecma262/#sec-iterator.prototype.drop 4394$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { 4395 drop: function drop(limit) { 4396 anObject(this); 4397 var remaining; 4398 try { 4399 remaining = toPositiveInteger(notANaN(+limit)); 4400 } catch (error) { 4401 iteratorClose(this, 'throw', error); 4402 } 4403 4404 if (dropWithoutClosingOnEarlyError) return call(dropWithoutClosingOnEarlyError, this, remaining); 4405 4406 return new IteratorProxy(getIteratorDirect(this), { 4407 remaining: remaining 4408 }); 4409 } 4410}); 4411 4412 4413/***/ }, 4414 4415/***/ 1148 4416(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4417 4418 4419var $ = __webpack_require__(6518); 4420var call = __webpack_require__(9565); 4421var iterate = __webpack_require__(2652); 4422var aCallable = __webpack_require__(9306); 4423var anObject = __webpack_require__(8551); 4424var getIteratorDirect = __webpack_require__(1767); 4425var iteratorClose = __webpack_require__(9539); 4426var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4427 4428var everyWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('every', TypeError); 4429 4430// `Iterator.prototype.every` method 4431// https://tc39.es/ecma262/#sec-iterator.prototype.every 4432$({ target: 'Iterator', proto: true, real: true, forced: everyWithoutClosingOnEarlyError }, { 4433 every: function every(predicate) { 4434 anObject(this); 4435 try { 4436 aCallable(predicate); 4437 } catch (error) { 4438 iteratorClose(this, 'throw', error); 4439 } 4440 4441 if (everyWithoutClosingOnEarlyError) return call(everyWithoutClosingOnEarlyError, this, predicate); 4442 4443 var record = getIteratorDirect(this); 4444 var counter = 0; 4445 return !iterate(record, function (value, stop) { 4446 if (!predicate(value, counter++)) return stop(); 4447 }, { IS_RECORD: true, INTERRUPTED: true }).stopped; 4448 } 4449}); 4450 4451 4452/***/ }, 4453 4454/***/ 2489 4455(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4456 4457 4458var $ = __webpack_require__(6518); 4459var call = __webpack_require__(9565); 4460var aCallable = __webpack_require__(9306); 4461var anObject = __webpack_require__(8551); 4462var getIteratorDirect = __webpack_require__(1767); 4463var createIteratorProxy = __webpack_require__(9462); 4464var callWithSafeIterationClosing = __webpack_require__(6319); 4465var IS_PURE = __webpack_require__(6395); 4466var iteratorClose = __webpack_require__(9539); 4467var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684); 4468var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4469 4470var FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('filter', function () { /* empty */ }); 4471var filterWithoutClosingOnEarlyError = !IS_PURE && !FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR 4472 && iteratorHelperWithoutClosingOnEarlyError('filter', TypeError); 4473 4474var FORCED = IS_PURE || FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR || filterWithoutClosingOnEarlyError; 4475 4476var IteratorProxy = createIteratorProxy(function () { 4477 var iterator = this.iterator; 4478 var predicate = this.predicate; 4479 var next = this.next; 4480 var result, done, value; 4481 while (true) { 4482 result = anObject(call(next, iterator)); 4483 done = this.done = !!result.done; 4484 if (done) return; 4485 value = result.value; 4486 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value; 4487 } 4488}); 4489 4490// `Iterator.prototype.filter` method 4491// https://tc39.es/ecma262/#sec-iterator.prototype.filter 4492$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { 4493 filter: function filter(predicate) { 4494 anObject(this); 4495 try { 4496 aCallable(predicate); 4497 } catch (error) { 4498 iteratorClose(this, 'throw', error); 4499 } 4500 4501 if (filterWithoutClosingOnEarlyError) return call(filterWithoutClosingOnEarlyError, this, predicate); 4502 4503 return new IteratorProxy(getIteratorDirect(this), { 4504 predicate: predicate 4505 }); 4506 } 4507}); 4508 4509 4510/***/ }, 4511 4512/***/ 116 4513(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4514 4515 4516var $ = __webpack_require__(6518); 4517var call = __webpack_require__(9565); 4518var iterate = __webpack_require__(2652); 4519var aCallable = __webpack_require__(9306); 4520var anObject = __webpack_require__(8551); 4521var getIteratorDirect = __webpack_require__(1767); 4522var iteratorClose = __webpack_require__(9539); 4523var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4524 4525var findWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('find', TypeError); 4526 4527// `Iterator.prototype.find` method 4528// https://tc39.es/ecma262/#sec-iterator.prototype.find 4529$({ target: 'Iterator', proto: true, real: true, forced: findWithoutClosingOnEarlyError }, { 4530 find: function find(predicate) { 4531 anObject(this); 4532 try { 4533 aCallable(predicate); 4534 } catch (error) { 4535 iteratorClose(this, 'throw', error); 4536 } 4537 4538 if (findWithoutClosingOnEarlyError) return call(findWithoutClosingOnEarlyError, this, predicate); 4539 4540 var record = getIteratorDirect(this); 4541 var counter = 0;
vendor: 4,642 bytes, lines 4542-4683
4542 return iterate(record, function (value, stop) { 4543 if (predicate(value, counter++)) return stop(value); 4544 }, { IS_RECORD: true, INTERRUPTED: true }).result; 4545 } 4546}); 4547 4548 4549/***/ }, 4550 4551/***/ 531 4552(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4553 4554 4555var $ = __webpack_require__(6518); 4556var call = __webpack_require__(9565); 4557var aCallable = __webpack_require__(9306); 4558var anObject = __webpack_require__(8551); 4559var getIteratorDirect = __webpack_require__(1767); 4560var getIteratorFlattenable = __webpack_require__(8646); 4561var createIteratorProxy = __webpack_require__(9462); 4562var iteratorClose = __webpack_require__(9539); 4563var IS_PURE = __webpack_require__(6395); 4564var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684); 4565var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4566 4567// Should not throw an error for an iterator without `return` method. Fixed in Safari 26.2 4568// https://bugs.webkit.org/show_bug.cgi?id=297532 4569function throwsOnIteratorWithoutReturn() { 4570 try { 4571 // eslint-disable-next-line es/no-map, es/no-iterator, es/no-iterator-prototype-flatmap -- required for testing 4572 var it = Iterator.prototype.flatMap.call(new Map([[4, 5]]).entries(), function (v) { return v; }); 4573 it.next(); 4574 it['return'](); 4575 } catch (error) { 4576 return true; 4577 } 4578} 4579 4580var FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE 4581 && !iteratorHelperThrowsOnInvalidIterator('flatMap', function () { /* empty */ }); 4582var flatMapWithoutClosingOnEarlyError = !IS_PURE && !FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR 4583 && iteratorHelperWithoutClosingOnEarlyError('flatMap', TypeError); 4584 4585var FORCED = IS_PURE || FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || flatMapWithoutClosingOnEarlyError 4586 || throwsOnIteratorWithoutReturn(); 4587 4588var IteratorProxy = createIteratorProxy(function () { 4589 var iterator = this.iterator; 4590 var mapper = this.mapper; 4591 var result, inner; 4592 4593 while (true) { 4594 if (inner = this.inner) try { 4595 result = anObject(call(inner.next, inner.iterator)); 4596 if (!result.done) return result.value; 4597 this.inner = null; 4598 } catch (error) { iteratorClose(iterator, 'throw', error); } 4599 4600 result = anObject(call(this.next, iterator)); 4601 4602 if (this.done = !!result.done) return; 4603 4604 try { 4605 this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false); 4606 } catch (error) { iteratorClose(iterator, 'throw', error); } 4607 } 4608}); 4609 4610// `Iterator.prototype.flatMap` method 4611// https://tc39.es/ecma262/#sec-iterator.prototype.flatmap 4612$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { 4613 flatMap: function flatMap(mapper) { 4614 anObject(this); 4615 try { 4616 aCallable(mapper); 4617 } catch (error) { 4618 iteratorClose(this, 'throw', error); 4619 } 4620 4621 if (flatMapWithoutClosingOnEarlyError) return call(flatMapWithoutClosingOnEarlyError, this, mapper); 4622 4623 return new IteratorProxy(getIteratorDirect(this), { 4624 mapper: mapper, 4625 inner: null 4626 }); 4627 } 4628}); 4629 4630 4631/***/ }, 4632 4633/***/ 7588 4634(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4635 4636 4637var $ = __webpack_require__(6518); 4638var call = __webpack_require__(9565); 4639var iterate = __webpack_require__(2652); 4640var aCallable = __webpack_require__(9306); 4641var anObject = __webpack_require__(8551); 4642var getIteratorDirect = __webpack_require__(1767); 4643var iteratorClose = __webpack_require__(9539); 4644var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4645 4646var forEachWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('forEach', TypeError); 4647 4648// `Iterator.prototype.forEach` method 4649// https://tc39.es/ecma262/#sec-iterator.prototype.foreach 4650$({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosingOnEarlyError }, { 4651 forEach: function forEach(fn) { 4652 anObject(this); 4653 try { 4654 aCallable(fn); 4655 } catch (error) { 4656 iteratorClose(this, 'throw', error); 4657 } 4658 4659 if (forEachWithoutClosingOnEarlyError) return call(forEachWithoutClosingOnEarlyError, this, fn); 4660 4661 var record = getIteratorDirect(this); 4662 var counter = 0; 4663 iterate(record, function (value) { 4664 fn(value, counter++); 4665 }, { IS_RECORD: true }); 4666 } 4667}); 4668 4669 4670/***/ }, 4671 4672/***/ 1701 4673(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4674 4675 4676var $ = __webpack_require__(6518); 4677var call = __webpack_require__(9565); 4678var aCallable = __webpack_require__(9306); 4679var anObject = __webpack_require__(8551); 4680var getIteratorDirect = __webpack_require__(1767); 4681var createIteratorProxy = __webpack_require__(9462); 4682var callWithSafeIterationClosing = __webpack_require__(6319); 4683var iteratorClose = __webpack_require__(9539);
vendor: 10,758 bytes, lines 4684-5004
4684var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684); 4685var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4686var IS_PURE = __webpack_require__(6395); 4687 4688var MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('map', function () { /* empty */ }); 4689var mapWithoutClosingOnEarlyError = !IS_PURE && !MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR 4690 && iteratorHelperWithoutClosingOnEarlyError('map', TypeError); 4691 4692var FORCED = IS_PURE || MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || mapWithoutClosingOnEarlyError; 4693 4694var IteratorProxy = createIteratorProxy(function () { 4695 var iterator = this.iterator; 4696 var result = anObject(call(this.next, iterator)); 4697 var done = this.done = !!result.done; 4698 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true); 4699}); 4700 4701// `Iterator.prototype.map` method 4702// https://tc39.es/ecma262/#sec-iterator.prototype.map 4703$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { 4704 map: function map(mapper) { 4705 anObject(this); 4706 try { 4707 aCallable(mapper); 4708 } catch (error) { 4709 iteratorClose(this, 'throw', error); 4710 } 4711 4712 if (mapWithoutClosingOnEarlyError) return call(mapWithoutClosingOnEarlyError, this, mapper); 4713 4714 return new IteratorProxy(getIteratorDirect(this), { 4715 mapper: mapper 4716 }); 4717 } 4718}); 4719 4720 4721/***/ }, 4722 4723/***/ 8237 4724(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4725 4726 4727var $ = __webpack_require__(6518); 4728var iterate = __webpack_require__(2652); 4729var aCallable = __webpack_require__(9306); 4730var anObject = __webpack_require__(8551); 4731var getIteratorDirect = __webpack_require__(1767); 4732var iteratorClose = __webpack_require__(9539); 4733var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4734var apply = __webpack_require__(8745); 4735var fails = __webpack_require__(9039); 4736 4737var $TypeError = TypeError; 4738 4739// https://bugs.webkit.org/show_bug.cgi?id=291651 4740var FAILS_ON_INITIAL_UNDEFINED = fails(function () { 4741 // eslint-disable-next-line es/no-iterator-prototype-reduce, es/no-array-prototype-keys, array-callback-return -- required for testing 4742 [].keys().reduce(function () { /* empty */ }, undefined); 4743}); 4744 4745var reduceWithoutClosingOnEarlyError = !FAILS_ON_INITIAL_UNDEFINED && iteratorHelperWithoutClosingOnEarlyError('reduce', $TypeError); 4746 4747// `Iterator.prototype.reduce` method 4748// https://tc39.es/ecma262/#sec-iterator.prototype.reduce 4749$({ target: 'Iterator', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFINED || reduceWithoutClosingOnEarlyError }, { 4750 reduce: function reduce(reducer /* , initialValue */) { 4751 anObject(this); 4752 try { 4753 aCallable(reducer); 4754 } catch (error) { 4755 iteratorClose(this, 'throw', error); 4756 } 4757 4758 var noInitial = arguments.length < 2; 4759 var accumulator = noInitial ? undefined : arguments[1]; 4760 if (reduceWithoutClosingOnEarlyError) { 4761 return apply(reduceWithoutClosingOnEarlyError, this, noInitial ? [reducer] : [reducer, accumulator]); 4762 } 4763 var record = getIteratorDirect(this); 4764 var counter = 0; 4765 iterate(record, function (value) { 4766 if (noInitial) { 4767 noInitial = false; 4768 accumulator = value; 4769 } else { 4770 accumulator = reducer(accumulator, value, counter); 4771 } 4772 counter++; 4773 }, { IS_RECORD: true }); 4774 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value'); 4775 return accumulator; 4776 } 4777}); 4778 4779 4780/***/ }, 4781 4782/***/ 3579 4783(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4784 4785 4786var $ = __webpack_require__(6518); 4787var call = __webpack_require__(9565); 4788var iterate = __webpack_require__(2652); 4789var aCallable = __webpack_require__(9306); 4790var anObject = __webpack_require__(8551); 4791var getIteratorDirect = __webpack_require__(1767); 4792var iteratorClose = __webpack_require__(9539); 4793var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4794 4795var someWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('some', TypeError); 4796 4797// `Iterator.prototype.some` method 4798// https://tc39.es/ecma262/#sec-iterator.prototype.some 4799$({ target: 'Iterator', proto: true, real: true, forced: someWithoutClosingOnEarlyError }, { 4800 some: function some(predicate) { 4801 anObject(this); 4802 try { 4803 aCallable(predicate); 4804 } catch (error) { 4805 iteratorClose(this, 'throw', error); 4806 } 4807 4808 if (someWithoutClosingOnEarlyError) return call(someWithoutClosingOnEarlyError, this, predicate); 4809 4810 var record = getIteratorDirect(this); 4811 var counter = 0; 4812 return iterate(record, function (value, stop) { 4813 if (predicate(value, counter++)) return stop(); 4814 }, { IS_RECORD: true, INTERRUPTED: true }).stopped; 4815 } 4816}); 4817 4818 4819/***/ }, 4820 4821/***/ 4972 4822(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4823 4824 4825var $ = __webpack_require__(6518); 4826var call = __webpack_require__(9565); 4827var anObject = __webpack_require__(8551); 4828var getIteratorDirect = __webpack_require__(1767); 4829var notANaN = __webpack_require__(4149); 4830var toPositiveInteger = __webpack_require__(9590); 4831var createIteratorProxy = __webpack_require__(9462); 4832var iteratorClose = __webpack_require__(9539); 4833var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549); 4834var IS_PURE = __webpack_require__(6395); 4835 4836var takeWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('take', RangeError); 4837 4838var IteratorProxy = createIteratorProxy(function () { 4839 var iterator = this.iterator; 4840 if (!this.remaining--) { 4841 this.done = true; 4842 return iteratorClose(iterator, 'normal', undefined); 4843 } 4844 var result = anObject(call(this.next, iterator)); 4845 var done = this.done = !!result.done; 4846 if (!done) return result.value; 4847}); 4848 4849// `Iterator.prototype.take` method 4850// https://tc39.es/ecma262/#sec-iterator.prototype.take 4851$({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || takeWithoutClosingOnEarlyError }, { 4852 take: function take(limit) { 4853 anObject(this); 4854 var remaining; 4855 try { 4856 remaining = toPositiveInteger(notANaN(+limit)); 4857 } catch (error) { 4858 iteratorClose(this, 'throw', error); 4859 } 4860 4861 if (takeWithoutClosingOnEarlyError) return call(takeWithoutClosingOnEarlyError, this, remaining); 4862 4863 return new IteratorProxy(getIteratorDirect(this), { 4864 remaining: remaining 4865 }); 4866 } 4867}); 4868 4869 4870/***/ }, 4871 4872/***/ 9112 4873(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 4874 4875 4876var $ = __webpack_require__(6518); 4877var DESCRIPTORS = __webpack_require__(3724); 4878var globalThis = __webpack_require__(4576); 4879var getBuiltIn = __webpack_require__(7751); 4880var uncurryThis = __webpack_require__(9504); 4881var call = __webpack_require__(9565); 4882var isCallable = __webpack_require__(4901); 4883var isObject = __webpack_require__(34); 4884var isArray = __webpack_require__(4376); 4885var hasOwn = __webpack_require__(9297); 4886var toString = __webpack_require__(655); 4887var lengthOfArrayLike = __webpack_require__(6198); 4888var createProperty = __webpack_require__(4659); 4889var fails = __webpack_require__(9039); 4890var parseJSONString = __webpack_require__(8235); 4891var NATIVE_SYMBOL = __webpack_require__(4495); 4892 4893var JSON = globalThis.JSON; 4894var Number = globalThis.Number; 4895var SyntaxError = globalThis.SyntaxError; 4896var nativeParse = JSON && JSON.parse; 4897var enumerableOwnProperties = getBuiltIn('Object', 'keys'); 4898// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 4899var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 4900var at = uncurryThis(''.charAt); 4901var slice = uncurryThis(''.slice); 4902var exec = uncurryThis(/./.exec); 4903var push = uncurryThis([].push); 4904 4905var IS_DIGIT = /^\d$/; 4906var IS_NON_ZERO_DIGIT = /^[1-9]$/; 4907var IS_NUMBER_START = /^[\d-]$/; 4908var IS_WHITESPACE = /^[\t\n\r ]$/; 4909 4910var PRIMITIVE = 0; 4911var OBJECT = 1; 4912 4913var $parse = function (source, reviver) { 4914 source = toString(source); 4915 var context = new Context(source, 0, ''); 4916 var root = context.parse(); 4917 var value = root.value; 4918 var endIndex = context.skip(IS_WHITESPACE, root.end); 4919 if (endIndex < source.length) { 4920 throw new SyntaxError('Unexpected extra character: "' + at(source, endIndex) + '" after the parsed data at: ' + endIndex); 4921 } 4922 return isCallable(reviver) ? internalize({ '': value }, '', reviver, root) : value; 4923}; 4924 4925var internalize = function (holder, name, reviver, node) { 4926 var val = holder[name]; 4927 var unmodified = node && val === node.value; 4928 var context = unmodified && typeof node.source == 'string' ? { source: node.source } : {}; 4929 var elementRecordsLen, keys, len, i, P; 4930 if (isObject(val)) { 4931 var nodeIsArray = isArray(val); 4932 var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {}; 4933 if (nodeIsArray) { 4934 elementRecordsLen = nodes.length; 4935 len = lengthOfArrayLike(val); 4936 for (i = 0; i < len; i++) { 4937 internalizeProperty(val, i, internalize(val, '' + i, reviver, i < elementRecordsLen ? nodes[i] : undefined)); 4938 } 4939 } else { 4940 keys = enumerableOwnProperties(val); 4941 len = lengthOfArrayLike(keys); 4942 for (i = 0; i < len; i++) { 4943 P = keys[i]; 4944 internalizeProperty(val, P, internalize(val, P, reviver, hasOwn(nodes, P) ? nodes[P] : undefined)); 4945 } 4946 } 4947 } 4948 return call(reviver, holder, name, val, context); 4949}; 4950 4951var internalizeProperty = function (object, key, value) { 4952 if (DESCRIPTORS) { 4953 var descriptor = getOwnPropertyDescriptor(object, key); 4954 if (descriptor && !descriptor.configurable) return; 4955 } 4956 if (value === undefined) delete object[key]; 4957 else createProperty(object, key, value); 4958}; 4959 4960var Node = function (value, end, source, nodes) { 4961 this.value = value; 4962 this.end = end; 4963 this.source = source; 4964 this.nodes = nodes; 4965}; 4966 4967var Context = function (source, index) { 4968 this.source = source; 4969 this.index = index; 4970}; 4971 4972// https://www.json.org/json-en.html 4973Context.prototype = { 4974 fork: function (nextIndex) { 4975 return new Context(this.source, nextIndex); 4976 }, 4977 parse: function () { 4978 var source = this.source; 4979 var i = this.skip(IS_WHITESPACE, this.index); 4980 var fork = this.fork(i); 4981 var chr = at(source, i); 4982 if (exec(IS_NUMBER_START, chr)) return fork.number(); 4983 switch (chr) { 4984 case '{': 4985 return fork.object(); 4986 case '[': 4987 return fork.array(); 4988 case '"': 4989 return fork.string(); 4990 case 't': 4991 return fork.keyword(true); 4992 case 'f': 4993 return fork.keyword(false); 4994 case 'n': 4995 return fork.keyword(null); 4996 } throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i); 4997 }, 4998 node: function (type, value, start, end, nodes) { 4999 return new Node(value, end, type ? null : slice(this.source, start, end), nodes); 5000 }, 5001 object: function () { 5002 var source = this.source; 5003 var i = this.index + 1; 5004 var expectKeypair = false;
vendor: 4,885 bytes, lines 5005-5155
5005 var object = {}; 5006 var nodes = {}; 5007 while (i < source.length) { 5008 i = this.until(['"', '}'], i); 5009 if (at(source, i) === '}' && !expectKeypair) { 5010 i++; 5011 break; 5012 } 5013 // Parsing the key 5014 var result = this.fork(i).string(); 5015 var key = result.value; 5016 i = result.end; 5017 i = this.until([':'], i) + 1; 5018 // Parsing value 5019 i = this.skip(IS_WHITESPACE, i); 5020 result = this.fork(i).parse(); 5021 createProperty(nodes, key, result); 5022 createProperty(object, key, result.value); 5023 i = this.until([',', '}'], result.end); 5024 var chr = at(source, i); 5025 if (chr === ',') { 5026 expectKeypair = true; 5027 i++; 5028 } else if (chr === '}') { 5029 i++; 5030 break; 5031 } 5032 } 5033 return this.node(OBJECT, object, this.index, i, nodes); 5034 }, 5035 array: function () { 5036 var source = this.source; 5037 var i = this.index + 1; 5038 var expectElement = false; 5039 var array = []; 5040 var nodes = []; 5041 while (i < source.length) { 5042 i = this.skip(IS_WHITESPACE, i); 5043 if (at(source, i) === ']' && !expectElement) { 5044 i++; 5045 break; 5046 } 5047 var result = this.fork(i).parse(); 5048 push(nodes, result); 5049 push(array, result.value); 5050 i = this.until([',', ']'], result.end); 5051 if (at(source, i) === ',') { 5052 expectElement = true; 5053 i++; 5054 } else if (at(source, i) === ']') { 5055 i++; 5056 break; 5057 } 5058 } 5059 return this.node(OBJECT, array, this.index, i, nodes); 5060 }, 5061 string: function () { 5062 var index = this.index; 5063 var parsed = parseJSONString(this.source, this.index + 1); 5064 return this.node(PRIMITIVE, parsed.value, index, parsed.end); 5065 }, 5066 number: function () { 5067 var source = this.source; 5068 var startIndex = this.index; 5069 var i = startIndex; 5070 if (at(source, i) === '-') i++; 5071 if (at(source, i) === '0') i++; 5072 else if (exec(IS_NON_ZERO_DIGIT, at(source, i))) i = this.skip(IS_DIGIT, i + 1); 5073 else throw new SyntaxError('Failed to parse number at: ' + i); 5074 if (at(source, i) === '.') i = this.skip(IS_DIGIT, i + 1); 5075 if (at(source, i) === 'e' || at(source, i) === 'E') { 5076 i++; 5077 if (at(source, i) === '+' || at(source, i) === '-') i++; 5078 var exponentStartIndex = i; 5079 i = this.skip(IS_DIGIT, i); 5080 if (exponentStartIndex === i) throw new SyntaxError("Failed to parse number's exponent value at: " + i); 5081 } 5082 return this.node(PRIMITIVE, Number(slice(source, startIndex, i)), startIndex, i); 5083 }, 5084 keyword: function (value) { 5085 var keyword = '' + value; 5086 var index = this.index; 5087 var endIndex = index + keyword.length; 5088 if (slice(this.source, index, endIndex) !== keyword) throw new SyntaxError('Failed to parse value at: ' + index); 5089 return this.node(PRIMITIVE, value, index, endIndex); 5090 }, 5091 skip: function (regex, i) { 5092 var source = this.source; 5093 for (; i < source.length; i++) if (!exec(regex, at(source, i))) break; 5094 return i; 5095 }, 5096 until: function (array, i) { 5097 i = this.skip(IS_WHITESPACE, i); 5098 var chr = at(this.source, i); 5099 for (var j = 0; j < array.length; j++) if (array[j] === chr) return i; 5100 throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i); 5101 } 5102}; 5103 5104var NO_SOURCE_SUPPORT = fails(function () { 5105 var unsafeInt = '9007199254740993'; 5106 var source; 5107 nativeParse(unsafeInt, function (key, value, context) { 5108 source = context.source; 5109 }); 5110 return source !== unsafeInt; 5111}); 5112 5113var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails(function () { 5114 // Safari 9 bug 5115 return 1 / nativeParse('-0 \t') !== -Infinity; 5116}); 5117 5118// `JSON.parse` method 5119// https://tc39.es/ecma262/#sec-json.parse 5120// https://github.com/tc39/proposal-json-parse-with-source 5121$({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, { 5122 parse: function parse(text, reviver) { 5123 return PROPER_BASE_PARSE && !isCallable(reviver) ? nativeParse(text) : $parse(text, reviver); 5124 } 5125}); 5126 5127 5128/***/ }, 5129 5130/***/ 3110 5131(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5132 5133 5134var $ = __webpack_require__(6518); 5135var getBuiltIn = __webpack_require__(7751); 5136var apply = __webpack_require__(8745); 5137var call = __webpack_require__(9565); 5138var uncurryThis = __webpack_require__(9504); 5139var fails = __webpack_require__(9039); 5140var isArray = __webpack_require__(4376); 5141var isCallable = __webpack_require__(4901); 5142var isRawJSON = __webpack_require__(5810); 5143var isSymbol = __webpack_require__(757); 5144var classof = __webpack_require__(2195); 5145var toString = __webpack_require__(655); 5146var arraySlice = __webpack_require__(7680); 5147var parseJSONString = __webpack_require__(8235); 5148var uid = __webpack_require__(3392); 5149var NATIVE_SYMBOL = __webpack_require__(4495); 5150var NATIVE_RAW_JSON = __webpack_require__(7819); 5151 5152var $String = String; 5153var $stringify = getBuiltIn('JSON', 'stringify'); 5154var exec = uncurryThis(/./.exec); 5155var charAt = uncurryThis(''.charAt);
vendor: 6,800 bytes, lines 5156-5365
5156var charCodeAt = uncurryThis(''.charCodeAt); 5157var replace = uncurryThis(''.replace); 5158var slice = uncurryThis(''.slice); 5159var push = uncurryThis([].push); 5160var numberToString = uncurryThis(1.1.toString); 5161 5162var surrogates = /[\uD800-\uDFFF]/g; 5163var lowSurrogates = /^[\uD800-\uDBFF]$/; 5164var hiSurrogates = /^[\uDC00-\uDFFF]$/; 5165 5166var MARK = uid(); 5167var MARK_LENGTH = MARK.length; 5168 5169var WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails(function () { 5170 var symbol = getBuiltIn('Symbol')('stringify detection'); 5171 // MS Edge converts symbol values to JSON as {} 5172 return $stringify([symbol]) !== '[null]' 5173 // WebKit converts symbol values to JSON as null 5174 || $stringify({ a: symbol }) !== '{}' 5175 // V8 throws on boxed symbols 5176 || $stringify(Object(symbol)) !== '{}'; 5177}); 5178 5179// https://github.com/tc39/proposal-well-formed-stringify 5180var ILL_FORMED_UNICODE = fails(function () { 5181 return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"' 5182 || $stringify('\uDEAD') !== '"\\udead"'; 5183}); 5184 5185var stringifyWithProperSymbolsConversion = WRONG_SYMBOLS_CONVERSION ? function (it, replacer) { 5186 var args = arraySlice(arguments); 5187 var $replacer = getReplacerFunction(replacer); 5188 if (!isCallable($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined 5189 args[1] = function (key, value) { 5190 // some old implementations (like WebKit) could pass numbers as keys 5191 if (isCallable($replacer)) value = call($replacer, this, $String(key), value); 5192 if (!isSymbol(value)) return value; 5193 }; 5194 return apply($stringify, null, args); 5195} : $stringify; 5196 5197var fixIllFormedJSON = function (match, offset, string) { 5198 var prev = charAt(string, offset - 1); 5199 var next = charAt(string, offset + 1); 5200 if ((exec(lowSurrogates, match) && !exec(hiSurrogates, next)) || (exec(hiSurrogates, match) && !exec(lowSurrogates, prev))) { 5201 return '\\u' + numberToString(charCodeAt(match, 0), 16); 5202 } return match; 5203}; 5204 5205var getReplacerFunction = function (replacer) { 5206 if (isCallable(replacer)) return replacer; 5207 if (!isArray(replacer)) return; 5208 var rawLength = replacer.length; 5209 var keys = []; 5210 for (var i = 0; i < rawLength; i++) { 5211 var element = replacer[i]; 5212 if (typeof element == 'string') push(keys, element); 5213 else if (typeof element == 'number' || classof(element) === 'Number' || classof(element) === 'String') push(keys, toString(element)); 5214 } 5215 var keysLength = keys.length; 5216 var root = true; 5217 return function (key, value) { 5218 if (root) { 5219 root = false; 5220 return value; 5221 } 5222 if (isArray(this)) return value; 5223 for (var j = 0; j < keysLength; j++) if (keys[j] === key) return value; 5224 }; 5225}; 5226 5227// `JSON.stringify` method 5228// https://tc39.es/ecma262/#sec-json.stringify 5229// https://github.com/tc39/proposal-json-parse-with-source 5230if ($stringify) $({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE || !NATIVE_RAW_JSON }, { 5231 stringify: function stringify(text, replacer, space) { 5232 var replacerFunction = getReplacerFunction(replacer); 5233 var rawStrings = []; 5234 5235 var json = stringifyWithProperSymbolsConversion(text, function (key, value) { 5236 // some old implementations (like WebKit) could pass numbers as keys 5237 var v = isCallable(replacerFunction) ? call(replacerFunction, this, $String(key), value) : value; 5238 return !NATIVE_RAW_JSON && isRawJSON(v) ? MARK + (push(rawStrings, v.rawJSON) - 1) : v; 5239 }, space); 5240 5241 if (typeof json != 'string') return json; 5242 5243 if (ILL_FORMED_UNICODE) json = replace(json, surrogates, fixIllFormedJSON); 5244 5245 if (NATIVE_RAW_JSON) return json; 5246 5247 var result = ''; 5248 var length = json.length; 5249 5250 for (var i = 0; i < length; i++) { 5251 var chr = charAt(json, i); 5252 if (chr === '"') { 5253 var end = parseJSONString(json, ++i).end - 1; 5254 var string = slice(json, i, end); 5255 result += slice(string, 0, MARK_LENGTH) === MARK 5256 ? rawStrings[slice(string, MARK_LENGTH)] 5257 : '"' + string + '"'; 5258 i = end; 5259 } else result += chr; 5260 } 5261 5262 return result; 5263 } 5264}); 5265 5266 5267/***/ }, 5268 5269/***/ 2731 5270(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5271 5272 5273var $ = __webpack_require__(6518); 5274var aCallable = __webpack_require__(9306); 5275var aMap = __webpack_require__(6194); 5276var MapHelpers = __webpack_require__(2248); 5277var IS_PURE = __webpack_require__(6395); 5278 5279var get = MapHelpers.get; 5280var has = MapHelpers.has; 5281var set = MapHelpers.set; 5282 5283// `Map.prototype.getOrInsertComputed` method 5284// https://github.com/tc39/proposal-upsert 5285$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { 5286 getOrInsertComputed: function getOrInsertComputed(key, callbackfn) { 5287 aMap(this); 5288 aCallable(callbackfn); 5289 if (has(this, key)) return get(this, key); 5290 // CanonicalizeKeyedCollectionKey 5291 if (key === 0 && 1 / key === -Infinity) key = 0; 5292 var value = callbackfn(key); 5293 set(this, key, value); 5294 return value; 5295 } 5296}); 5297 5298 5299/***/ }, 5300 5301/***/ 5367 5302(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5303 5304 5305var $ = __webpack_require__(6518); 5306var aMap = __webpack_require__(6194); 5307var MapHelpers = __webpack_require__(2248); 5308var IS_PURE = __webpack_require__(6395); 5309 5310var get = MapHelpers.get; 5311var has = MapHelpers.has; 5312var set = MapHelpers.set; 5313 5314// `Map.prototype.getOrInsert` method 5315// https://github.com/tc39/proposal-upsert 5316$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { 5317 getOrInsert: function getOrInsert(key, value) { 5318 if (has(aMap(this), key)) return get(this, key); 5319 set(this, key, value); 5320 return value; 5321 } 5322}); 5323 5324 5325/***/ }, 5326 5327/***/ 3068 5328(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5329 5330 5331// based on Shewchuk's algorithm for exactly floating point addition 5332// adapted from https://github.com/tc39/proposal-math-sum/blob/3513d58323a1ae25560e8700aa5294500c6c9287/polyfill/polyfill.mjs 5333var $ = __webpack_require__(6518); 5334var uncurryThis = __webpack_require__(9504); 5335var iterate = __webpack_require__(2652); 5336 5337var $RangeError = RangeError; 5338var $TypeError = TypeError; 5339var $Infinity = Infinity; 5340var $NaN = NaN; 5341var abs = Math.abs; 5342var pow = Math.pow; 5343var push = uncurryThis([].push); 5344 5345var POW_2_1023 = pow(2, 1023); 5346var MAX_SAFE_INTEGER = pow(2, 53) - 1; // 2 ** 53 - 1 === 9007199254740992 5347var MAX_DOUBLE = Number.MAX_VALUE; // 2 ** 1024 - 2 ** (1023 - 52) === 1.79769313486231570815e+308 5348var MAX_ULP = pow(2, 971); // 2 ** (1023 - 52) === 1.99584030953471981166e+292 5349 5350var NOT_A_NUMBER = {}; 5351var MINUS_INFINITY = {}; 5352var PLUS_INFINITY = {}; 5353var MINUS_ZERO = {}; 5354var FINITE = {}; 5355 5356// prerequisite: abs(x) >= abs(y) 5357var twosum = function (x, y) { 5358 var hi = x + y; 5359 var lo = y - (hi - x); 5360 return { hi: hi, lo: lo }; 5361}; 5362 5363// `Math.sumPrecise` method 5364// https://github.com/tc39/proposal-math-sum 5365$({ target: 'Math', stat: true }, {
vendor: 5,164 bytes, lines 5366-5534
5366 // eslint-disable-next-line max-statements -- ok 5367 sumPrecise: function sumPrecise(items) { 5368 var numbers = []; 5369 var count = 0; 5370 var state = MINUS_ZERO; 5371 5372 iterate(items, function (n) { 5373 if (++count >= MAX_SAFE_INTEGER) throw new $RangeError('Maximum allowed index exceeded'); 5374 if (typeof n != 'number') throw new $TypeError('Value is not a number'); 5375 if (state !== NOT_A_NUMBER) { 5376 // eslint-disable-next-line no-self-compare -- NaN check 5377 if (n !== n) state = NOT_A_NUMBER; 5378 else if (n === $Infinity) state = state === MINUS_INFINITY ? NOT_A_NUMBER : PLUS_INFINITY; 5379 else if (n === -$Infinity) state = state === PLUS_INFINITY ? NOT_A_NUMBER : MINUS_INFINITY; 5380 else if ((n !== 0 || (1 / n) === $Infinity) && (state === MINUS_ZERO || state === FINITE)) { 5381 state = FINITE; 5382 push(numbers, n); 5383 } 5384 } 5385 }); 5386 5387 switch (state) { 5388 case NOT_A_NUMBER: return $NaN; 5389 case MINUS_INFINITY: return -$Infinity; 5390 case PLUS_INFINITY: return $Infinity; 5391 case MINUS_ZERO: return -0; 5392 } 5393 5394 var partials = []; 5395 var overflow = 0; // conceptually 2 ** 1024 times this value; the final partial is biased by this amount 5396 var x, y, sum, hi, lo, tmp; 5397 5398 for (var i = 0; i < numbers.length; i++) { 5399 x = numbers[i]; 5400 var actuallyUsedPartials = 0; 5401 for (var j = 0; j < partials.length; j++) { 5402 y = partials[j]; 5403 if (abs(x) < abs(y)) { 5404 tmp = x; 5405 x = y; 5406 y = tmp; 5407 } 5408 sum = twosum(x, y); 5409 hi = sum.hi; 5410 lo = sum.lo; 5411 if (abs(hi) === $Infinity) { 5412 var sign = hi === $Infinity ? 1 : -1; 5413 overflow += sign; 5414 5415 x = (x - (sign * POW_2_1023)) - (sign * POW_2_1023); 5416 if (abs(x) < abs(y)) { 5417 tmp = x; 5418 x = y; 5419 y = tmp; 5420 } 5421 sum = twosum(x, y); 5422 hi = sum.hi; 5423 lo = sum.lo; 5424 } 5425 if (lo !== 0) partials[actuallyUsedPartials++] = lo; 5426 x = hi; 5427 } 5428 partials.length = actuallyUsedPartials; 5429 if (x !== 0) push(partials, x); 5430 } 5431 5432 // compute the exact sum of partials, stopping once we lose precision 5433 var n = partials.length - 1; 5434 hi = 0; 5435 lo = 0; 5436 5437 if (overflow !== 0) { 5438 var next = n >= 0 ? partials[n] : 0; 5439 n--; 5440 if (abs(overflow) > 1 || (overflow > 0 && next > 0) || (overflow < 0 && next < 0)) { 5441 return overflow > 0 ? $Infinity : -$Infinity; 5442 } 5443 // here we actually have to do the arithmetic 5444 // drop a factor of 2 so we can do it without overflow 5445 // assert(abs(overflow) === 1) 5446 sum = twosum(overflow * POW_2_1023, next / 2); 5447 hi = sum.hi; 5448 lo = sum.lo; 5449 lo *= 2; 5450 if (abs(2 * hi) === $Infinity) { 5451 // rounding to the maximum value 5452 if (hi > 0) { 5453 return (hi === POW_2_1023 && lo === -(MAX_ULP / 2) && n >= 0 && partials[n] < 0) ? MAX_DOUBLE : $Infinity; 5454 } return (hi === -POW_2_1023 && lo === (MAX_ULP / 2) && n >= 0 && partials[n] > 0) ? -MAX_DOUBLE : -$Infinity; 5455 } 5456 5457 if (lo !== 0) { 5458 partials[++n] = lo; 5459 lo = 0; 5460 } 5461 5462 hi *= 2; 5463 } 5464 5465 while (n >= 0) { 5466 sum = twosum(hi, partials[n--]); 5467 hi = sum.hi; 5468 lo = sum.lo; 5469 if (lo !== 0) break; 5470 } 5471 5472 if (n >= 0 && ((lo < 0 && partials[n] < 0) || (lo > 0 && partials[n] > 0))) { 5473 y = lo * 2; 5474 x = hi + y; 5475 if (y === x - hi) hi = x; 5476 } 5477 5478 return hi; 5479 } 5480}); 5481 5482 5483/***/ }, 5484 5485/***/ 1689 5486(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5487 5488 5489var $ = __webpack_require__(6518); 5490var globalThis = __webpack_require__(4576); 5491var apply = __webpack_require__(8745); 5492var slice = __webpack_require__(7680); 5493var newPromiseCapabilityModule = __webpack_require__(6043); 5494var aCallable = __webpack_require__(9306); 5495var perform = __webpack_require__(1103); 5496 5497var Promise = globalThis.Promise; 5498 5499var ACCEPT_ARGUMENTS = false; 5500// Avoiding the use of polyfills of the previous iteration of this proposal 5501// that does not accept arguments of the callback 5502var FORCED = !Promise || !Promise['try'] || perform(function () { 5503 Promise['try'](function (argument) { 5504 ACCEPT_ARGUMENTS = argument === 8; 5505 }, 8); 5506}).error || !ACCEPT_ARGUMENTS; 5507 5508// `Promise.try` method 5509// https://tc39.es/ecma262/#sec-promise.try 5510$({ target: 'Promise', stat: true, forced: FORCED }, { 5511 'try': function (callbackfn /* , ...args */) { 5512 var args = arguments.length > 1 ? slice(arguments, 1) : []; 5513 var promiseCapability = newPromiseCapabilityModule.f(this); 5514 var result = perform(function () { 5515 return apply(aCallable(callbackfn), undefined, args); 5516 }); 5517 (result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value); 5518 return promiseCapability.promise; 5519 } 5520}); 5521 5522 5523/***/ }, 5524 5525/***/ 4628 5526(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5527 5528 5529var $ = __webpack_require__(6518); 5530var newPromiseCapabilityModule = __webpack_require__(6043); 5531 5532// `Promise.withResolvers` method 5533// https://tc39.es/ecma262/#sec-promise.withResolvers 5534$({ target: 'Promise', stat: true }, {
vendor: 5,874 bytes, lines 5535-5738
5535 withResolvers: function withResolvers() { 5536 var promiseCapability = newPromiseCapabilityModule.f(this); 5537 return { 5538 promise: promiseCapability.promise, 5539 resolve: promiseCapability.resolve, 5540 reject: promiseCapability.reject 5541 }; 5542 } 5543}); 5544 5545 5546/***/ }, 5547 5548/***/ 7642 5549(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5550 5551 5552var $ = __webpack_require__(6518); 5553var difference = __webpack_require__(3440); 5554var fails = __webpack_require__(9039); 5555var setMethodAcceptSetLike = __webpack_require__(4916); 5556 5557var SET_LIKE_INCORRECT_BEHAVIOR = !setMethodAcceptSetLike('difference', function (result) { 5558 return result.size === 0; 5559}); 5560 5561var FORCED = SET_LIKE_INCORRECT_BEHAVIOR || fails(function () { 5562 // https://bugs.webkit.org/show_bug.cgi?id=288595 5563 var setLike = { 5564 size: 1, 5565 has: function () { return true; }, 5566 keys: function () { 5567 var index = 0; 5568 return { 5569 next: function () { 5570 var done = index++ > 1; 5571 if (baseSet.has(1)) baseSet.clear(); 5572 return { done: done, value: 2 }; 5573 } 5574 }; 5575 } 5576 }; 5577 // eslint-disable-next-line es/no-set -- testing 5578 var baseSet = new Set([1, 2, 3, 4]); 5579 // eslint-disable-next-line es/no-set-prototype-difference -- testing 5580 return baseSet.difference(setLike).size !== 3; 5581}); 5582 5583// `Set.prototype.difference` method 5584// https://tc39.es/ecma262/#sec-set.prototype.difference 5585$({ target: 'Set', proto: true, real: true, forced: FORCED }, { 5586 difference: difference 5587}); 5588 5589 5590/***/ }, 5591 5592/***/ 8004 5593(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5594 5595 5596var $ = __webpack_require__(6518); 5597var fails = __webpack_require__(9039); 5598var intersection = __webpack_require__(8750); 5599var setMethodAcceptSetLike = __webpack_require__(4916); 5600 5601var INCORRECT = !setMethodAcceptSetLike('intersection', function (result) { 5602 return result.size === 2 && result.has(1) && result.has(2); 5603}) || fails(function () { 5604 // eslint-disable-next-line es/no-array-from, es/no-set, es/no-set-prototype-intersection -- testing 5605 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2'; 5606}); 5607 5608// `Set.prototype.intersection` method 5609// https://tc39.es/ecma262/#sec-set.prototype.intersection 5610$({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { 5611 intersection: intersection 5612}); 5613 5614 5615/***/ }, 5616 5617/***/ 3853 5618(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5619 5620 5621var $ = __webpack_require__(6518); 5622var isDisjointFrom = __webpack_require__(4449); 5623var setMethodAcceptSetLike = __webpack_require__(4916); 5624 5625var INCORRECT = !setMethodAcceptSetLike('isDisjointFrom', function (result) { 5626 return !result; 5627}); 5628 5629// `Set.prototype.isDisjointFrom` method 5630// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom 5631$({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { 5632 isDisjointFrom: isDisjointFrom 5633}); 5634 5635 5636/***/ }, 5637 5638/***/ 5876 5639(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5640 5641 5642var $ = __webpack_require__(6518); 5643var isSubsetOf = __webpack_require__(3838); 5644var setMethodAcceptSetLike = __webpack_require__(4916); 5645 5646var INCORRECT = !setMethodAcceptSetLike('isSubsetOf', function (result) { 5647 return result; 5648}); 5649 5650// `Set.prototype.isSubsetOf` method 5651// https://tc39.es/ecma262/#sec-set.prototype.issubsetof 5652$({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { 5653 isSubsetOf: isSubsetOf 5654}); 5655 5656 5657/***/ }, 5658 5659/***/ 2475 5660(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5661 5662 5663var $ = __webpack_require__(6518); 5664var isSupersetOf = __webpack_require__(8527); 5665var setMethodAcceptSetLike = __webpack_require__(4916); 5666 5667var INCORRECT = !setMethodAcceptSetLike('isSupersetOf', function (result) { 5668 return !result; 5669}); 5670 5671// `Set.prototype.isSupersetOf` method 5672// https://tc39.es/ecma262/#sec-set.prototype.issupersetof 5673$({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { 5674 isSupersetOf: isSupersetOf 5675}); 5676 5677 5678/***/ }, 5679 5680/***/ 5024 5681(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5682 5683 5684var $ = __webpack_require__(6518); 5685var symmetricDifference = __webpack_require__(3650); 5686var setMethodGetKeysBeforeCloning = __webpack_require__(9835); 5687var setMethodAcceptSetLike = __webpack_require__(4916); 5688 5689var FORCED = !setMethodAcceptSetLike('symmetricDifference') || !setMethodGetKeysBeforeCloning('symmetricDifference'); 5690 5691// `Set.prototype.symmetricDifference` method 5692// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference 5693$({ target: 'Set', proto: true, real: true, forced: FORCED }, { 5694 symmetricDifference: symmetricDifference 5695}); 5696 5697 5698/***/ }, 5699 5700/***/ 1698 5701(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5702 5703 5704var $ = __webpack_require__(6518); 5705var union = __webpack_require__(4204); 5706var setMethodGetKeysBeforeCloning = __webpack_require__(9835); 5707var setMethodAcceptSetLike = __webpack_require__(4916); 5708 5709var FORCED = !setMethodAcceptSetLike('union') || !setMethodGetKeysBeforeCloning('union'); 5710 5711// `Set.prototype.union` method 5712// https://tc39.es/ecma262/#sec-set.prototype.union 5713$({ target: 'Set', proto: true, real: true, forced: FORCED }, { 5714 union: union 5715}); 5716 5717 5718/***/ }, 5719 5720/***/ 9577 5721(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5722 5723 5724var ArrayBufferViewCore = __webpack_require__(4644); 5725var isBigIntArray = __webpack_require__(1108); 5726var lengthOfArrayLike = __webpack_require__(6198); 5727var toIntegerOrInfinity = __webpack_require__(1291); 5728var toBigInt = __webpack_require__(5854); 5729 5730var aTypedArray = ArrayBufferViewCore.aTypedArray; 5731var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; 5732var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; 5733 5734var $RangeError = RangeError; 5735 5736var PROPER_ORDER = function () { 5737 try { 5738 // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing
vendor: 7,883 bytes, lines 5739-5980
5739 new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } }); 5740 } catch (error) { 5741 // some early implementations, like WebKit, does not follow the final semantic 5742 // https://github.com/tc39/proposal-change-array-by-copy/pull/86 5743 return error === 8; 5744 } 5745}(); 5746 5747// Bug in WebKit. It should truncate a negative fractional index to zero, but instead throws an error 5748var THROW_ON_NEGATIVE_FRACTIONAL_INDEX = PROPER_ORDER && function () { 5749 try { 5750 // eslint-disable-next-line es/no-typed-arrays, es/no-array-prototype-with -- required for testing 5751 new Int8Array(1)['with'](-0.5, 1); 5752 } catch (error) { 5753 return true; 5754 } 5755}(); 5756 5757// `%TypedArray%.prototype.with` method 5758// https://tc39.es/ecma262/#sec-%typedarray%.prototype.with 5759exportTypedArrayMethod('with', { 'with': function (index, value) { 5760 var O = aTypedArray(this); 5761 var len = lengthOfArrayLike(O); 5762 var relativeIndex = toIntegerOrInfinity(index); 5763 var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex; 5764 var numericValue = isBigIntArray(O) ? toBigInt(value) : +value; 5765 if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index'); 5766 var A = new (getTypedArrayConstructor(O))(len); 5767 var k = 0; 5768 for (; k < len; k++) A[k] = k === actualIndex ? numericValue : O[k]; 5769 return A; 5770} }['with'], !PROPER_ORDER || THROW_ON_NEGATIVE_FRACTIONAL_INDEX); 5771 5772 5773/***/ }, 5774 5775/***/ 5213 5776(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5777 5778 5779var $ = __webpack_require__(6518); 5780var globalThis = __webpack_require__(4576); 5781var arrayFromConstructorAndList = __webpack_require__(5370); 5782var $fromBase64 = __webpack_require__(9143); 5783 5784var Uint8Array = globalThis.Uint8Array; 5785 5786var INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.fromBase64 || !function () { 5787 // Webkit not throw an error on odd length string 5788 try { 5789 Uint8Array.fromBase64('a'); 5790 return; 5791 } catch (error) { /* empty */ } 5792 try { 5793 Uint8Array.fromBase64('', null); 5794 } catch (error) { 5795 return true; 5796 } 5797}(); 5798 5799// `Uint8Array.fromBase64` method 5800// https://github.com/tc39/proposal-arraybuffer-base64 5801if (Uint8Array) $({ target: 'Uint8Array', stat: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, { 5802 fromBase64: function fromBase64(string /* , options */) { 5803 var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, null, 0x1FFFFFFFFFFFFF); 5804 return arrayFromConstructorAndList(Uint8Array, result.bytes); 5805 } 5806}); 5807 5808 5809/***/ }, 5810 5811/***/ 6632 5812(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5813 5814 5815var $ = __webpack_require__(6518); 5816var globalThis = __webpack_require__(4576); 5817var $fromBase64 = __webpack_require__(9143); 5818var anUint8Array = __webpack_require__(4154); 5819 5820var Uint8Array = globalThis.Uint8Array; 5821 5822var INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.setFromBase64 || !function () { 5823 var target = new Uint8Array([255, 255, 255, 255, 255]); 5824 try { 5825 target.setFromBase64('', null); 5826 return; 5827 } catch (error) { /* empty */ } 5828 // Webkit not throw an error on odd length string 5829 try { 5830 target.setFromBase64('a'); 5831 return; 5832 } catch (error) { /* empty */ } 5833 try { 5834 target.setFromBase64('MjYyZg==='); 5835 } catch (error) { 5836 return target[0] === 50 && target[1] === 54 && target[2] === 50 && target[3] === 255 && target[4] === 255; 5837 } 5838}(); 5839 5840// `Uint8Array.prototype.setFromBase64` method 5841// https://github.com/tc39/proposal-arraybuffer-base64 5842if (Uint8Array) $({ target: 'Uint8Array', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, { 5843 setFromBase64: function setFromBase64(string /* , options */) { 5844 anUint8Array(this); 5845 5846 var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, this, this.length); 5847 5848 return { read: result.read, written: result.written }; 5849 } 5850}); 5851 5852 5853/***/ }, 5854 5855/***/ 4226 5856(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5857 5858 5859var $ = __webpack_require__(6518); 5860var globalThis = __webpack_require__(4576); 5861var aString = __webpack_require__(3463); 5862var anUint8Array = __webpack_require__(4154); 5863var notDetached = __webpack_require__(5169); 5864var $fromHex = __webpack_require__(2303); 5865 5866// Should not throw an error on length-tracking views over ResizableArrayBuffer 5867// https://issues.chromium.org/issues/454630441 5868function throwsOnLengthTrackingView() { 5869 try { 5870 // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- required for testing 5871 var rab = new ArrayBuffer(16, { maxByteLength: 1024 }); 5872 // eslint-disable-next-line es/no-uint8array-prototype-setfromhex, es/no-typed-arrays -- required for testing 5873 new Uint8Array(rab).setFromHex('cafed00d'); 5874 } catch (error) { 5875 return true; 5876 } 5877} 5878 5879// `Uint8Array.prototype.setFromHex` method 5880// https://github.com/tc39/proposal-arraybuffer-base64 5881if (globalThis.Uint8Array) $({ target: 'Uint8Array', proto: true, forced: throwsOnLengthTrackingView() }, { 5882 setFromHex: function setFromHex(string) { 5883 anUint8Array(this); 5884 aString(string); 5885 notDetached(this.buffer); 5886 var read = $fromHex(string, this).read; 5887 return { read: read, written: read / 2 }; 5888 } 5889}); 5890 5891 5892/***/ }, 5893 5894/***/ 9486 5895(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5896 5897 5898var $ = __webpack_require__(6518); 5899var globalThis = __webpack_require__(4576); 5900var uncurryThis = __webpack_require__(9504); 5901var anObjectOrUndefined = __webpack_require__(3972); 5902var anUint8Array = __webpack_require__(4154); 5903var notDetached = __webpack_require__(5169); 5904var base64Map = __webpack_require__(2804); 5905var getAlphabetOption = __webpack_require__(944); 5906 5907var base64Alphabet = base64Map.i2c; 5908var base64UrlAlphabet = base64Map.i2cUrl; 5909 5910var charAt = uncurryThis(''.charAt); 5911 5912var Uint8Array = globalThis.Uint8Array; 5913 5914var INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.toBase64 || !function () { 5915 try { 5916 var target = new Uint8Array(); 5917 target.toBase64(null); 5918 } catch (error) { 5919 return true; 5920 } 5921}(); 5922 5923// `Uint8Array.prototype.toBase64` method 5924// https://github.com/tc39/proposal-arraybuffer-base64 5925if (Uint8Array) $({ target: 'Uint8Array', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, { 5926 toBase64: function toBase64(/* options */) { 5927 var array = anUint8Array(this); 5928 var options = arguments.length ? anObjectOrUndefined(arguments[0]) : undefined; 5929 var alphabet = getAlphabetOption(options) === 'base64' ? base64Alphabet : base64UrlAlphabet; 5930 var omitPadding = !!options && !!options.omitPadding; 5931 notDetached(this.buffer); 5932 5933 var result = ''; 5934 var i = 0; 5935 var length = array.length; 5936 var triplet; 5937 5938 var at = function (shift) { 5939 return charAt(alphabet, (triplet >> (6 * shift)) & 63); 5940 }; 5941 5942 for (; i + 2 < length; i += 3) { 5943 triplet = (array[i] << 16) + (array[i + 1] << 8) + array[i + 2]; 5944 result += at(3) + at(2) + at(1) + at(0); 5945 } 5946 if (i + 2 === length) { 5947 triplet = (array[i] << 16) + (array[i + 1] << 8); 5948 result += at(3) + at(2) + at(1) + (omitPadding ? '' : '='); 5949 } else if (i + 1 === length) { 5950 triplet = array[i] << 16; 5951 result += at(3) + at(2) + (omitPadding ? '' : '=='); 5952 } 5953 5954 return result; 5955 } 5956}); 5957 5958 5959/***/ }, 5960 5961/***/ 456 5962(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 5963 5964 5965var $ = __webpack_require__(6518); 5966var globalThis = __webpack_require__(4576); 5967var uncurryThis = __webpack_require__(9504); 5968var anUint8Array = __webpack_require__(4154); 5969var notDetached = __webpack_require__(5169); 5970 5971var numberToString = uncurryThis(1.1.toString); 5972 5973var Uint8Array = globalThis.Uint8Array; 5974 5975var INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.toHex || !(function () { 5976 try { 5977 var target = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]); 5978 return target.toHex() === 'ffffffffffffffff'; 5979 } catch (error) { 5980 return false;
vendor: 4,802 bytes, lines 5981-6122
5981 } 5982})(); 5983 5984// `Uint8Array.prototype.toHex` method 5985// https://github.com/tc39/proposal-arraybuffer-base64 5986if (Uint8Array) $({ target: 'Uint8Array', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, { 5987 toHex: function toHex() { 5988 anUint8Array(this); 5989 notDetached(this.buffer); 5990 var result = ''; 5991 for (var i = 0, length = this.length; i < length; i++) { 5992 var hex = numberToString(this[i], 16); 5993 result += hex.length === 1 ? '0' + hex : hex; 5994 } 5995 return result; 5996 } 5997}); 5998 5999 6000/***/ }, 6001 6002/***/ 9452 6003(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6004 6005 6006var $ = __webpack_require__(6518); 6007var aCallable = __webpack_require__(9306); 6008var aWeakMap = __webpack_require__(6557); 6009var aWeakKey = __webpack_require__(4328); 6010var WeakMapHelpers = __webpack_require__(4995); 6011var IS_PURE = __webpack_require__(6395); 6012 6013var get = WeakMapHelpers.get; 6014var has = WeakMapHelpers.has; 6015var set = WeakMapHelpers.set; 6016 6017var FORCED = IS_PURE || !function () { 6018 try { 6019 // eslint-disable-next-line es/no-weak-map, no-throw-literal -- testing 6020 if (WeakMap.prototype.getOrInsertComputed) new WeakMap().getOrInsertComputed(1, function () { throw 1; }); 6021 } catch (error) { 6022 // FF144 Nightly - Beta 3 bug 6023 // https://bugzilla.mozilla.org/show_bug.cgi?id=1988369 6024 return error instanceof TypeError; 6025 } 6026}(); 6027 6028// `WeakMap.prototype.getOrInsertComputed` method 6029// https://github.com/tc39/proposal-upsert 6030$({ target: 'WeakMap', proto: true, real: true, forced: FORCED }, { 6031 getOrInsertComputed: function getOrInsertComputed(key, callbackfn) { 6032 aWeakMap(this); 6033 aWeakKey(key); 6034 aCallable(callbackfn); 6035 if (has(this, key)) return get(this, key); 6036 var value = callbackfn(key); 6037 set(this, key, value); 6038 return value; 6039 } 6040}); 6041 6042 6043/***/ }, 6044 6045/***/ 8454 6046(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6047 6048 6049var $ = __webpack_require__(6518); 6050var aWeakMap = __webpack_require__(6557); 6051var WeakMapHelpers = __webpack_require__(4995); 6052var IS_PURE = __webpack_require__(6395); 6053 6054var get = WeakMapHelpers.get; 6055var has = WeakMapHelpers.has; 6056var set = WeakMapHelpers.set; 6057 6058// `WeakMap.prototype.getOrInsert` method 6059// https://github.com/tc39/proposal-upsert 6060$({ target: 'WeakMap', proto: true, real: true, forced: IS_PURE }, { 6061 getOrInsert: function getOrInsert(key, value) { 6062 if (has(aWeakMap(this), key)) return get(this, key); 6063 set(this, key, value); 6064 return value; 6065 } 6066}); 6067 6068 6069/***/ }, 6070 6071/***/ 4979 6072(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6073 6074 6075var $ = __webpack_require__(6518); 6076var globalThis = __webpack_require__(4576); 6077var getBuiltIn = __webpack_require__(7751); 6078var createPropertyDescriptor = __webpack_require__(6980); 6079var defineProperty = (__webpack_require__(4913).f); 6080var hasOwn = __webpack_require__(9297); 6081var anInstance = __webpack_require__(679); 6082var inheritIfRequired = __webpack_require__(3167); 6083var normalizeStringArgument = __webpack_require__(2603); 6084var DOMExceptionConstants = __webpack_require__(5002); 6085var clearErrorStack = __webpack_require__(8574); 6086var DESCRIPTORS = __webpack_require__(3724); 6087var IS_PURE = __webpack_require__(6395); 6088 6089var DOM_EXCEPTION = 'DOMException'; 6090var Error = getBuiltIn('Error'); 6091var NativeDOMException = getBuiltIn(DOM_EXCEPTION); 6092 6093var $DOMException = function DOMException() { 6094 anInstance(this, DOMExceptionPrototype); 6095 var argumentsLength = arguments.length; 6096 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]); 6097 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error'); 6098 var that = new NativeDOMException(message, name); 6099 var error = new Error(message); 6100 error.name = DOM_EXCEPTION; 6101 defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1))); 6102 inheritIfRequired(that, this, $DOMException); 6103 return that; 6104}; 6105 6106var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype; 6107 6108var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION); 6109var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2); 6110 6111// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe 6112var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION); 6113 6114// Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it 6115// https://github.com/Jarred-Sumner/bun/issues/399 6116var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable); 6117 6118var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK; 6119 6120// `DOMException` constructor patch for `.stack` where it's required 6121// https://webidl.spec.whatwg.org/#es-DOMException-specialness 6122$({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }
vendor: 13,100 bytes, lines 6122-6580
6122, { // TODO: fix export logic 6123 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException 6124}); 6125 6126var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION); 6127var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype; 6128 6129if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) { 6130 if (!IS_PURE) { 6131 defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException)); 6132 } 6133 6134 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) { 6135 var constant = DOMExceptionConstants[key]; 6136 var constantName = constant.s; 6137 if (!hasOwn(PolyfilledDOMException, constantName)) { 6138 defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c)); 6139 } 6140 } 6141} 6142 6143 6144/***/ }, 6145 6146/***/ 4603 6147(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6148 6149 6150var defineBuiltIn = __webpack_require__(6840); 6151var uncurryThis = __webpack_require__(9504); 6152var toString = __webpack_require__(655); 6153var validateArgumentsLength = __webpack_require__(2812); 6154 6155var $URLSearchParams = URLSearchParams; 6156var URLSearchParamsPrototype = $URLSearchParams.prototype; 6157var append = uncurryThis(URLSearchParamsPrototype.append); 6158var $delete = uncurryThis(URLSearchParamsPrototype['delete']); 6159var forEach = uncurryThis(URLSearchParamsPrototype.forEach); 6160var push = uncurryThis([].push); 6161var params = new $URLSearchParams('a=1&a=2&b=3'); 6162 6163params['delete']('a', 1); 6164// `undefined` case is a Chromium 117 bug 6165// https://bugs.chromium.org/p/v8/issues/detail?id=14222 6166params['delete']('b', undefined); 6167 6168if (params + '' !== 'a=2') { 6169 defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) { 6170 var length = arguments.length; 6171 var $value = length < 2 ? undefined : arguments[1]; 6172 if (length && $value === undefined) return $delete(this, name); 6173 var entries = []; 6174 forEach(this, function (v, k) { // also validates `this` 6175 push(entries, { key: k, value: v }); 6176 }); 6177 validateArgumentsLength(length, 1); 6178 var key = toString(name); 6179 var value = toString($value); 6180 var index = 0; 6181 var dindex = 0; 6182 var found = false; 6183 var entriesLength = entries.length; 6184 var entry; 6185 while (index < entriesLength) { 6186 entry = entries[index++]; 6187 if (found || entry.key === key) { 6188 found = true; 6189 $delete(this, entry.key); 6190 } else dindex++; 6191 } 6192 while (dindex < entriesLength) { 6193 entry = entries[dindex++]; 6194 if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value); 6195 } 6196 }, { enumerable: true, unsafe: true }); 6197} 6198 6199 6200/***/ }, 6201 6202/***/ 7566 6203(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6204 6205 6206var defineBuiltIn = __webpack_require__(6840); 6207var uncurryThis = __webpack_require__(9504); 6208var toString = __webpack_require__(655); 6209var validateArgumentsLength = __webpack_require__(2812); 6210 6211var $URLSearchParams = URLSearchParams; 6212var URLSearchParamsPrototype = $URLSearchParams.prototype; 6213var getAll = uncurryThis(URLSearchParamsPrototype.getAll); 6214var $has = uncurryThis(URLSearchParamsPrototype.has); 6215var params = new $URLSearchParams('a=1'); 6216 6217// `undefined` case is a Chromium 117 bug 6218// https://bugs.chromium.org/p/v8/issues/detail?id=14222 6219if (params.has('a', 2) || !params.has('a', undefined)) { 6220 defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) { 6221 var length = arguments.length; 6222 var $value = length < 2 ? undefined : arguments[1]; 6223 if (length && $value === undefined) return $has(this, name); 6224 var values = getAll(this, name); // also validates `this` 6225 validateArgumentsLength(length, 1); 6226 var value = toString($value); 6227 var index = 0; 6228 while (index < values.length) { 6229 if (values[index++] === value) return true; 6230 } return false; 6231 }, { enumerable: true, unsafe: true }); 6232} 6233 6234 6235/***/ }, 6236 6237/***/ 8721 6238(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6239 6240 6241var DESCRIPTORS = __webpack_require__(3724); 6242var uncurryThis = __webpack_require__(9504); 6243var defineBuiltInAccessor = __webpack_require__(2106); 6244 6245var URLSearchParamsPrototype = URLSearchParams.prototype; 6246var forEach = uncurryThis(URLSearchParamsPrototype.forEach); 6247 6248// `URLSearchParams.prototype.size` getter 6249// https://github.com/whatwg/url/pull/734 6250if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) { 6251 defineBuiltInAccessor(URLSearchParamsPrototype, 'size', { 6252 get: function size() { 6253 var count = 0; 6254 forEach(this, function () { count++; }); 6255 return count; 6256 }, 6257 configurable: true, 6258 enumerable: true 6259 }); 6260} 6261 6262 6263/***/ }, 6264 6265/***/ 5781 6266(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { 6267 6268 6269var $ = __webpack_require__(6518); 6270var getBuiltIn = __webpack_require__(7751); 6271var validateArgumentsLength = __webpack_require__(2812); 6272var toString = __webpack_require__(655); 6273var USE_NATIVE_URL = __webpack_require__(7416); 6274 6275var URL = getBuiltIn('URL'); 6276 6277// `URL.parse` method 6278// https://url.spec.whatwg.org/#dom-url-canparse 6279$({ target: 'URL', stat: true, forced: !USE_NATIVE_URL }, { 6280 parse: function parse(url) { 6281 var length = validateArgumentsLength(arguments.length, 1); 6282 var urlString = toString(url); 6283 var base = length < 2 || arguments[1] === undefined ? undefined : toString(arguments[1]); 6284 try { 6285 return new URL(urlString, base); 6286 } catch (error) { 6287 return null; 6288 } 6289 } 6290}); 6291 6292 6293/***/ } 6294 6295/******/ }); 6296/************************************************************************/ 6297/******/ // The module cache 6298/******/ var __webpack_module_cache__ = {}; 6299/******/ 6300/******/ // The require function 6301/******/ function __webpack_require__(moduleId) { 6302/******/ // Check if module is in cache 6303/******/ var cachedModule = __webpack_module_cache__[moduleId]; 6304/******/ if (cachedModule !== undefined) { 6305/******/ return cachedModule.exports; 6306/******/ } 6307/******/ // Create a new module (and put it into the cache) 6308/******/ var module = __webpack_module_cache__[moduleId] = { 6309/******/ // no module.id needed 6310/******/ // no module.loaded needed 6311/******/ exports: {} 6312/******/ }; 6313/******/ 6314/******/ // Execute the module function 6315/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); 6316/******/ 6317/******/ // Return the exports of the module 6318/******/ return module.exports; 6319/******/ } 6320/******/ 6321/************************************************************************/ 6322/******/ /* webpack/runtime/define property getters */ 6323/******/ (() => { 6324/******/ // define getter functions for harmony exports 6325/******/ __webpack_require__.d = (exports, definition) => { 6326/******/ for(var key in definition) { 6327/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { 6328/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); 6329/******/ } 6330/******/ } 6331/******/ }; 6332/******/ })(); 6333/******/ 6334/******/ /* webpack/runtime/hasOwnProperty shorthand */ 6335/******/ (() => { 6336/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) 6337/******/ })(); 6338/******/ 6339/************************************************************************/ 6340var __webpack_exports__ = {}; 6341 6342// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array.push.js 6343var es_array_push = __webpack_require__(4114); 6344// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.detached.js 6345var es_array_buffer_detached = __webpack_require__(6573); 6346// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer.js 6347var es_array_buffer_transfer = __webpack_require__(8100); 6348// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer-to-fixed-length.js 6349var es_array_buffer_transfer_to_fixed_length = __webpack_require__(7936); 6350// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.constructor.js 6351var es_iterator_constructor = __webpack_require__(8111); 6352// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.reduce.js 6353var es_iterator_reduce = __webpack_require__(8237); 6354// EXTERNAL MODULE: ./node_modules/core-js/modules/es.map.get-or-insert.js 6355var es_map_get_or_insert = __webpack_require__(5367); 6356// EXTERNAL MODULE: ./node_modules/core-js/modules/es.map.get-or-insert-computed.js 6357var es_map_get_or_insert_computed = __webpack_require__(2731); 6358// EXTERNAL MODULE: ./node_modules/core-js/modules/es.math.sum-precise.js 6359var es_math_sum_precise = __webpack_require__(3068); 6360// EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.with.js 6361var es_typed_array_with = __webpack_require__(9577); 6362// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.set-from-base64.js 6363var es_uint8_array_set_from_base64 = __webpack_require__(6632); 6364// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.set-from-hex.js 6365var es_uint8_array_set_from_hex = __webpack_require__(4226); 6366// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.to-base64.js 6367var es_uint8_array_to_base64 = __webpack_require__(9486); 6368// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.to-hex.js 6369var es_uint8_array_to_hex = __webpack_require__(456); 6370// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url.parse.js 6371var web_url_parse = __webpack_require__(5781); 6372;// ./src/shared/util.js 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); 6389const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; 6390const LINE_FACTOR = 1.35; 6391const LINE_DESCENT_FACTOR = 0.35; 6392const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; 6393const RenderingIntentFlag = { 6394 ANY: 0x01, 6395 DISPLAY: 0x02, 6396 PRINT: 0x04, 6397 SAVE: 0x08, 6398 ANNOTATIONS_FORMS: 0x10, 6399 ANNOTATIONS_STORAGE: 0x20, 6400 ANNOTATIONS_DISABLE: 0x40, 6401 IS_EDITING: 0x80, 6402 OPLIST: 0x100 6403}; 6404const AnnotationMode = { 6405 DISABLE: 0, 6406 ENABLE: 1, 6407 ENABLE_FORMS: 2, 6408 ENABLE_STORAGE: 3 6409}; 6410const AnnotationEditorPrefix = "pdfjs_internal_editor_"; 6411const AnnotationEditorType = { 6412 DISABLE: -1, 6413 NONE: 0, 6414 FREETEXT: 3, 6415 HIGHLIGHT: 9, 6416 STAMP: 13, 6417 INK: 15, 6418 POPUP: 16, 6419 SIGNATURE: 101, 6420 COMMENT: 102 6421}; 6422const AnnotationEditorParamsType = { 6423 RESIZE: 1, 6424 CREATE: 2, 6425 FREETEXT_SIZE: 11, 6426 FREETEXT_COLOR: 12, 6427 FREETEXT_OPACITY: 13, 6428 INK_COLOR: 21, 6429 INK_THICKNESS: 22, 6430 INK_OPACITY: 23, 6431 HIGHLIGHT_COLOR: 31, 6432 HIGHLIGHT_THICKNESS: 32, 6433 HIGHLIGHT_FREE: 33, 6434 HIGHLIGHT_SHOW_ALL: 34, 6435 DRAW_STEP: 41 6436}; 6437const PermissionFlag = { 6438 PRINT: 0x04, 6439 MODIFY_CONTENTS: 0x08, 6440 COPY: 0x10, 6441 MODIFY_ANNOTATIONS: 0x20, 6442 FILL_INTERACTIVE_FORMS: 0x100, 6443 COPY_FOR_ACCESSIBILITY: 0x200, 6444 ASSEMBLE: 0x400, 6445 PRINT_HIGH_QUALITY: 0x800 6446}; 6447const MeshFigureType = { 6448 TRIANGLES: 1, 6449 LATTICE: 2, 6450 PATCH: 3 6451}; 6452const TextRenderingMode = { 6453 FILL: 0, 6454 STROKE: 1, 6455 FILL_STROKE: 2, 6456 INVISIBLE: 3, 6457 FILL_ADD_TO_PATH: 4, 6458 STROKE_ADD_TO_PATH: 5, 6459 FILL_STROKE_ADD_TO_PATH: 6, 6460 ADD_TO_PATH: 7, 6461 FILL_STROKE_MASK: 3, 6462 ADD_TO_PATH_FLAG: 4 6463}; 6464const ImageKind = { 6465 GRAYSCALE_1BPP: 1, 6466 RGB_24BPP: 2, 6467 RGBA_32BPP: 3 6468}; 6469const AnnotationType = { 6470 TEXT: 1, 6471 LINK: 2, 6472 FREETEXT: 3, 6473 LINE: 4, 6474 SQUARE: 5, 6475 CIRCLE: 6, 6476 POLYGON: 7, 6477 POLYLINE: 8, 6478 HIGHLIGHT: 9, 6479 UNDERLINE: 10, 6480 SQUIGGLY: 11, 6481 STRIKEOUT: 12, 6482 STAMP: 13, 6483 CARET: 14, 6484 INK: 15, 6485 POPUP: 16, 6486 FILEATTACHMENT: 17, 6487 SOUND: 18, 6488 MOVIE: 19, 6489 WIDGET: 20, 6490 SCREEN: 21, 6491 PRINTERMARK: 22, 6492 TRAPNET: 23, 6493 WATERMARK: 24, 6494 THREED: 25, 6495 REDACT: 26 6496}; 6497const AnnotationReplyType = { 6498 GROUP: "Group", 6499 REPLY: "R" 6500}; 6501const AnnotationFlag = { 6502 INVISIBLE: 0x01, 6503 HIDDEN: 0x02, 6504 PRINT: 0x04, 6505 NOZOOM: 0x08, 6506 NOROTATE: 0x10, 6507 NOVIEW: 0x20, 6508 READONLY: 0x40, 6509 LOCKED: 0x80, 6510 TOGGLENOVIEW: 0x100, 6511 LOCKEDCONTENTS: 0x200 6512}; 6513const AnnotationFieldFlag = { 6514 READONLY: 0x0000001, 6515 REQUIRED: 0x0000002, 6516 NOEXPORT: 0x0000004, 6517 MULTILINE: 0x0001000, 6518 PASSWORD: 0x0002000, 6519 NOTOGGLETOOFF: 0x0004000, 6520 RADIO: 0x0008000, 6521 PUSHBUTTON: 0x0010000, 6522 COMBO: 0x0020000, 6523 EDIT: 0x0040000, 6524 SORT: 0x0080000, 6525 FILESELECT: 0x0100000, 6526 MULTISELECT: 0x0200000, 6527 DONOTSPELLCHECK: 0x0400000, 6528 DONOTSCROLL: 0x0800000, 6529 COMB: 0x1000000, 6530 RICHTEXT: 0x2000000, 6531 RADIOSINUNISON: 0x2000000, 6532 COMMITONSELCHANGE: 0x4000000 6533}; 6534const AnnotationBorderStyleType = { 6535 SOLID: 1, 6536 DASHED: 2, 6537 BEVELED: 3, 6538 INSET: 4, 6539 UNDERLINE: 5 6540}; 6541const AnnotationActionEventType = { 6542 E: "Mouse Enter", 6543 X: "Mouse Exit", 6544 D: "Mouse Down", 6545 U: "Mouse Up", 6546 Fo: "Focus", 6547 Bl: "Blur", 6548 PO: "PageOpen", 6549 PC: "PageClose", 6550 PV: "PageVisible", 6551 PI: "PageInvisible", 6552 K: "Keystroke", 6553 F: "Format", 6554 V: "Validate", 6555 C: "Calculate" 6556}; 6557const DocumentActionEventType = { 6558 WC: "WillClose", 6559 WS: "WillSave", 6560 DS: "DidSave", 6561 WP: "WillPrint", 6562 DP: "DidPrint" 6563}; 6564const PageActionEventType = { 6565 O: "PageOpen", 6566 C: "PageClose" 6567}; 6568const VerbosityLevel = { 6569 ERRORS: 0, 6570 WARNINGS: 1, 6571 INFOS: 5 6572}; 6573const OPS = { 6574 dependency: 1, 6575 setLineWidth: 2, 6576 setLineCap: 3, 6577 setLineJoin: 4, 6578 setMiterLimit: 5, 6579 setDash: 6, 6580 setRenderingIntent: 7,
vendor: 5,802 bytes, lines 6581-6826
6581 setFlatness: 8, 6582 setGState: 9, 6583 save: 10, 6584 restore: 11, 6585 transform: 12, 6586 moveTo: 13, 6587 lineTo: 14, 6588 curveTo: 15, 6589 curveTo2: 16, 6590 curveTo3: 17, 6591 closePath: 18, 6592 rectangle: 19, 6593 stroke: 20, 6594 closeStroke: 21, 6595 fill: 22, 6596 eoFill: 23, 6597 fillStroke: 24, 6598 eoFillStroke: 25, 6599 closeFillStroke: 26, 6600 closeEOFillStroke: 27, 6601 endPath: 28, 6602 clip: 29, 6603 eoClip: 30, 6604 beginText: 31, 6605 endText: 32, 6606 setCharSpacing: 33, 6607 setWordSpacing: 34, 6608 setHScale: 35, 6609 setLeading: 36, 6610 setFont: 37, 6611 setTextRenderingMode: 38, 6612 setTextRise: 39, 6613 moveText: 40, 6614 setLeadingMoveText: 41, 6615 setTextMatrix: 42, 6616 nextLine: 43, 6617 showText: 44, 6618 showSpacedText: 45, 6619 nextLineShowText: 46, 6620 nextLineSetSpacingShowText: 47, 6621 setCharWidth: 48, 6622 setCharWidthAndBounds: 49, 6623 setStrokeColorSpace: 50, 6624 setFillColorSpace: 51, 6625 setStrokeColor: 52, 6626 setStrokeColorN: 53, 6627 setFillColor: 54, 6628 setFillColorN: 55, 6629 setStrokeGray: 56, 6630 setFillGray: 57, 6631 setStrokeRGBColor: 58, 6632 setFillRGBColor: 59, 6633 setStrokeCMYKColor: 60, 6634 setFillCMYKColor: 61, 6635 shadingFill: 62, 6636 beginInlineImage: 63, 6637 beginImageData: 64, 6638 endInlineImage: 65, 6639 paintXObject: 66, 6640 markPoint: 67, 6641 markPointProps: 68, 6642 beginMarkedContent: 69, 6643 beginMarkedContentProps: 70, 6644 endMarkedContent: 71, 6645 beginCompat: 72, 6646 endCompat: 73, 6647 paintFormXObjectBegin: 74, 6648 paintFormXObjectEnd: 75, 6649 beginGroup: 76, 6650 endGroup: 77, 6651 beginAnnotation: 80, 6652 endAnnotation: 81, 6653 paintImageMaskXObject: 83, 6654 paintImageMaskXObjectGroup: 84, 6655 paintImageXObject: 85, 6656 paintInlineImageXObject: 86, 6657 paintInlineImageXObjectGroup: 87, 6658 paintImageXObjectRepeat: 88, 6659 paintImageMaskXObjectRepeat: 89, 6660 paintSolidColorImageMask: 90, 6661 constructPath: 91, 6662 setStrokeTransparent: 92, 6663 setFillTransparent: 93, 6664 rawFillPath: 94 6665}; 6666const DrawOPS = { 6667 moveTo: 0, 6668 lineTo: 1, 6669 curveTo: 2, 6670 quadraticCurveTo: 3, 6671 closePath: 4 6672}; 6673const PasswordResponses = { 6674 NEED_PASSWORD: 1, 6675 INCORRECT_PASSWORD: 2 6676}; 6677let verbosity = VerbosityLevel.WARNINGS; 6678function setVerbosityLevel(level) { 6679 if (Number.isInteger(level)) { 6680 verbosity = level; 6681 } 6682} 6683function getVerbosityLevel() { 6684 return verbosity; 6685} 6686function info(msg) { 6687 if (verbosity >= VerbosityLevel.INFOS) { 6688 console.info(`Info: ${msg}`); 6689 } 6690} 6691function warn(msg) { 6692 if (verbosity >= VerbosityLevel.WARNINGS) { 6693 console.warn(`Warning: ${msg}`); 6694 } 6695} 6696function unreachable(msg) { 6697 throw new Error(msg); 6698} 6699function assert(cond, msg) { 6700 if (!cond) { 6701 unreachable(msg); 6702 } 6703} 6704function _isValidProtocol(url) { 6705 switch (url?.protocol) { 6706 case "http:": 6707 case "https:": 6708 case "ftp:": 6709 case "mailto:": 6710 case "tel:": 6711 return true; 6712 default: 6713 return false; 6714 } 6715} 6716function createValidAbsoluteUrl(url, baseUrl = null, options = null) { 6717 if (!url) { 6718 return null; 6719 } 6720 if (options && typeof url === "string") { 6721 if (options.addDefaultProtocol && url.startsWith("www.")) { 6722 const dots = url.match(/\./g); 6723 if (dots?.length >= 2) { 6724 url = `http://${url}`; 6725 } 6726 } 6727 if (options.tryConvertEncoding) { 6728 try { 6729 url = stringToUTF8String(url); 6730 } catch {} 6731 } 6732 } 6733 const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); 6734 return _isValidProtocol(absoluteUrl) ? absoluteUrl : null; 6735} 6736function updateUrlHash(url, hash, allowRel = false) { 6737 const res = URL.parse(url); 6738 if (res) { 6739 res.hash = hash; 6740 return res.href; 6741 } 6742 if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) { 6743 return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`; 6744 } 6745 return ""; 6746} 6747function stripPath(str) { 6748 return str.substring(str.lastIndexOf("/") + 1); 6749} 6750function shadow(obj, prop, value, nonSerializable = false) { 6751 Object.defineProperty(obj, prop, { 6752 value, 6753 enumerable: !nonSerializable, 6754 configurable: true, 6755 writable: false 6756 }); 6757 return value; 6758} 6759const BaseException = function BaseExceptionClosure() { 6760 function BaseException(message, name) { 6761 this.message = message; 6762 this.name = name; 6763 } 6764 BaseException.prototype = new Error(); 6765 BaseException.constructor = BaseException; 6766 return BaseException; 6767}(); 6768class PasswordException extends BaseException { 6769 constructor(msg, code) { 6770 super(msg, "PasswordException"); 6771 this.code = code; 6772 } 6773} 6774class UnknownErrorException extends BaseException { 6775 constructor(msg, details) { 6776 super(msg, "UnknownErrorException"); 6777 this.details = details; 6778 } 6779} 6780class InvalidPDFException extends BaseException { 6781 constructor(msg) { 6782 super(msg, "InvalidPDFException"); 6783 } 6784} 6785class ResponseException extends BaseException { 6786 constructor(msg, status, missing) { 6787 super(msg, "ResponseException"); 6788 this.status = status; 6789 this.missing = missing; 6790 } 6791} 6792class FormatError extends BaseException { 6793 constructor(msg) { 6794 super(msg, "FormatError"); 6795 } 6796} 6797class AbortException extends BaseException { 6798 constructor(msg) { 6799 super(msg, "AbortException"); 6800 } 6801} 6802function bytesToString(bytes) { 6803 if (typeof bytes !== "object" || bytes?.length === undefined) { 6804 unreachable("Invalid argument for bytesToString"); 6805 } 6806 const length = bytes.length; 6807 const MAX_ARGUMENT_COUNT = 8192; 6808 if (length < MAX_ARGUMENT_COUNT) { 6809 return String.fromCharCode.apply(null, bytes); 6810 } 6811 const strBuf = []; 6812 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) { 6813 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); 6814 const chunk = bytes.subarray(i, chunkEnd); 6815 strBuf.push(String.fromCharCode.apply(null, chunk)); 6816 } 6817 return strBuf.join(""); 6818} 6819function stringToBytes(str) { 6820 if (typeof str !== "string") { 6821 unreachable("Invalid argument for stringToBytes"); 6822 } 6823 const length = str.length; 6824 const bytes = new Uint8Array(length); 6825 for (let i = 0; i < length; ++i) { 6826 bytes[i] = str.charCodeAt(i) & 0xff;
vendor: 10,306 bytes, lines 6827-7119
6827 } 6828 return bytes; 6829} 6830function string32(value) { 6831 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); 6832} 6833function objectSize(obj) { 6834 return Object.keys(obj).length; 6835} 6836function isLittleEndian() { 6837 const buffer8 = new Uint8Array(4); 6838 buffer8[0] = 1; 6839 const view32 = new Uint32Array(buffer8.buffer, 0, 1); 6840 return view32[0] === 1; 6841} 6842function isEvalSupported() { 6843 try { 6844 new Function(""); 6845 return true; 6846 } catch { 6847 return false; 6848 } 6849} 6850class FeatureTest { 6851 static get isLittleEndian() { 6852 return shadow(this, "isLittleEndian", isLittleEndian()); 6853 } 6854 static get isEvalSupported() { 6855 return shadow(this, "isEvalSupported", isEvalSupported()); 6856 } 6857 static get isOffscreenCanvasSupported() { 6858 return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); 6859 } 6860 static get isImageDecoderSupported() { 6861 return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined"); 6862 } 6863 static get isFloat16ArraySupported() { 6864 return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined"); 6865 } 6866 static get isSanitizerSupported() { 6867 return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined"); 6868 } 6869 static get platform() { 6870 const { 6871 platform, 6872 userAgent 6873 } = navigator; 6874 return shadow(this, "platform", { 6875 isAndroid: userAgent.includes("Android"), 6876 isLinux: platform.includes("Linux"), 6877 isMac: platform.includes("Mac"), 6878 isWindows: platform.includes("Win"), 6879 isFirefox: userAgent.includes("Firefox") 6880 }); 6881 } 6882 static get isCSSRoundSupported() { 6883 return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); 6884 } 6885} 6886const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0")); 6887class Util { 6888 static makeHexColor(r, g, b) { 6889 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`; 6890 } 6891 static domMatrixToTransform(dm) { 6892 return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f]; 6893 } 6894 static scaleMinMax(transform, minMax) { 6895 let temp; 6896 if (transform[0]) { 6897 if (transform[0] < 0) { 6898 temp = minMax[0]; 6899 minMax[0] = minMax[2]; 6900 minMax[2] = temp; 6901 } 6902 minMax[0] *= transform[0]; 6903 minMax[2] *= transform[0]; 6904 if (transform[3] < 0) { 6905 temp = minMax[1]; 6906 minMax[1] = minMax[3]; 6907 minMax[3] = temp; 6908 } 6909 minMax[1] *= transform[3]; 6910 minMax[3] *= transform[3]; 6911 } else { 6912 temp = minMax[0]; 6913 minMax[0] = minMax[1]; 6914 minMax[1] = temp; 6915 temp = minMax[2]; 6916 minMax[2] = minMax[3]; 6917 minMax[3] = temp; 6918 if (transform[1] < 0) { 6919 temp = minMax[1]; 6920 minMax[1] = minMax[3]; 6921 minMax[3] = temp; 6922 } 6923 minMax[1] *= transform[1]; 6924 minMax[3] *= transform[1]; 6925 if (transform[2] < 0) { 6926 temp = minMax[0]; 6927 minMax[0] = minMax[2]; 6928 minMax[2] = temp; 6929 } 6930 minMax[0] *= transform[2]; 6931 minMax[2] *= transform[2]; 6932 } 6933 minMax[0] += transform[4]; 6934 minMax[1] += transform[5]; 6935 minMax[2] += transform[4]; 6936 minMax[3] += transform[5]; 6937 } 6938 static transform(m1, m2) { 6939 return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; 6940 } 6941 static multiplyByDOMMatrix(m, md) { 6942 return [m[0] * md.a + m[2] * md.b, m[1] * md.a + m[3] * md.b, m[0] * md.c + m[2] * md.d, m[1] * md.c + m[3] * md.d, m[0] * md.e + m[2] * md.f + m[4], m[1] * md.e + m[3] * md.f + m[5]]; 6943 } 6944 static applyTransform(p, m, pos = 0) { 6945 const p0 = p[pos]; 6946 const p1 = p[pos + 1]; 6947 p[pos] = p0 * m[0] + p1 * m[2] + m[4]; 6948 p[pos + 1] = p0 * m[1] + p1 * m[3] + m[5]; 6949 } 6950 static applyTransformToBezier(p, transform, pos = 0) { 6951 const m0 = transform[0]; 6952 const m1 = transform[1]; 6953 const m2 = transform[2]; 6954 const m3 = transform[3]; 6955 const m4 = transform[4]; 6956 const m5 = transform[5]; 6957 for (let i = 0; i < 6; i += 2) { 6958 const pI = p[pos + i]; 6959 const pI1 = p[pos + i + 1]; 6960 p[pos + i] = pI * m0 + pI1 * m2 + m4; 6961 p[pos + i + 1] = pI * m1 + pI1 * m3 + m5; 6962 } 6963 } 6964 static applyInverseTransform(p, m) { 6965 const p0 = p[0]; 6966 const p1 = p[1]; 6967 const d = m[0] * m[3] - m[1] * m[2]; 6968 p[0] = (p0 * m[3] - p1 * m[2] + m[2] * m[5] - m[4] * m[3]) / d; 6969 p[1] = (-p0 * m[1] + p1 * m[0] + m[4] * m[1] - m[5] * m[0]) / d; 6970 } 6971 static axialAlignedBoundingBox(rect, transform, output) { 6972 const m0 = transform[0]; 6973 const m1 = transform[1]; 6974 const m2 = transform[2]; 6975 const m3 = transform[3]; 6976 const m4 = transform[4]; 6977 const m5 = transform[5]; 6978 const r0 = rect[0]; 6979 const r1 = rect[1]; 6980 const r2 = rect[2]; 6981 const r3 = rect[3]; 6982 let a0 = m0 * r0 + m4; 6983 let a2 = a0; 6984 let a1 = m0 * r2 + m4; 6985 let a3 = a1; 6986 let b0 = m3 * r1 + m5; 6987 let b2 = b0; 6988 let b1 = m3 * r3 + m5; 6989 let b3 = b1; 6990 if (m1 !== 0 || m2 !== 0) { 6991 const m1r0 = m1 * r0; 6992 const m1r2 = m1 * r2; 6993 const m2r1 = m2 * r1; 6994 const m2r3 = m2 * r3; 6995 a0 += m2r1; 6996 a3 += m2r1; 6997 a1 += m2r3; 6998 a2 += m2r3; 6999 b0 += m1r0; 7000 b3 += m1r0; 7001 b1 += m1r2; 7002 b2 += m1r2; 7003 } 7004 output[0] = Math.min(output[0], a0, a1, a2, a3); 7005 output[1] = Math.min(output[1], b0, b1, b2, b3); 7006 output[2] = Math.max(output[2], a0, a1, a2, a3); 7007 output[3] = Math.max(output[3], b0, b1, b2, b3); 7008 } 7009 static inverseTransform(m) { 7010 const d = m[0] * m[3] - m[1] * m[2]; 7011 return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; 7012 } 7013 static singularValueDecompose2dScale(matrix, output) { 7014 const m0 = matrix[0]; 7015 const m1 = matrix[1]; 7016 const m2 = matrix[2]; 7017 const m3 = matrix[3]; 7018 const a = m0 ** 2 + m1 ** 2; 7019 const b = m0 * m2 + m1 * m3; 7020 const c = m2 ** 2 + m3 ** 2; 7021 const first = (a + c) / 2; 7022 const second = Math.sqrt(first ** 2 - (a * c - b ** 2)); 7023 output[0] = Math.sqrt(first + second || 1); 7024 output[1] = Math.sqrt(first - second || 1); 7025 } 7026 static normalizeRect(rect) { 7027 const r = rect.slice(0); 7028 if (rect[0] > rect[2]) { 7029 r[0] = rect[2]; 7030 r[2] = rect[0]; 7031 } 7032 if (rect[1] > rect[3]) { 7033 r[1] = rect[3]; 7034 r[3] = rect[1]; 7035 } 7036 return r; 7037 } 7038 static intersect(rect1, rect2) { 7039 const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2])); 7040 const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2])); 7041 if (xLow > xHigh) { 7042 return null; 7043 } 7044 const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3])); 7045 const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3])); 7046 if (yLow > yHigh) { 7047 return null; 7048 } 7049 return [xLow, yLow, xHigh, yHigh]; 7050 } 7051 static pointBoundingBox(x, y, minMax) { 7052 minMax[0] = Math.min(minMax[0], x); 7053 minMax[1] = Math.min(minMax[1], y); 7054 minMax[2] = Math.max(minMax[2], x); 7055 minMax[3] = Math.max(minMax[3], y); 7056 } 7057 static rectBoundingBox(x0, y0, x1, y1, minMax) { 7058 minMax[0] = Math.min(minMax[0], x0, x1); 7059 minMax[1] = Math.min(minMax[1], y0, y1); 7060 minMax[2] = Math.max(minMax[2], x0, x1); 7061 minMax[3] = Math.max(minMax[3], y0, y1); 7062 } 7063 static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) { 7064 if (t <= 0 || t >= 1) { 7065 return; 7066 } 7067 const mt = 1 - t; 7068 const tt = t * t; 7069 const ttt = tt * t; 7070 const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3; 7071 const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3; 7072 minMax[0] = Math.min(minMax[0], x); 7073 minMax[1] = Math.min(minMax[1], y); 7074 minMax[2] = Math.max(minMax[2], x); 7075 minMax[3] = Math.max(minMax[3], y); 7076 } 7077 static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) { 7078 if (Math.abs(a) < 1e-12) { 7079 if (Math.abs(b) >= 1e-12) { 7080 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax); 7081 } 7082 return; 7083 } 7084 const delta = b ** 2 - 4 * c * a; 7085 if (delta < 0) { 7086 return; 7087 } 7088 const sqrtDelta = Math.sqrt(delta); 7089 const a2 = 2 * a; 7090 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax); 7091 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax); 7092 } 7093 static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) { 7094 minMax[0] = Math.min(minMax[0], x0, x3); 7095 minMax[1] = Math.min(minMax[1], y0, y3); 7096 minMax[2] = Math.max(minMax[2], x0, x3); 7097 minMax[3] = Math.max(minMax[3], y0, y3); 7098 this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax); 7099 this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax); 7100 } 7101} 7102const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac])); 7103function stringToPDFString(str, keepEscapeSequence = false) { 7104 if (str[0] >= "\xEF") { 7105 let encoding; 7106 if (str[0] === "\xFE" && str[1] === "\xFF") { 7107 encoding = "utf-16be"; 7108 if (str.length % 2 === 1) { 7109 str = str.slice(0, -1); 7110 } 7111 } else if (str[0] === "\xFF" && str[1] === "\xFE") { 7112 encoding = "utf-16le"; 7113 if (str.length % 2 === 1) { 7114 str = str.slice(0, -1); 7115 } 7116 } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") { 7117 encoding = "utf-8"; 7118 } 7119 if (encoding) {
vendor: 12,299 bytes, lines 7120-7532
7120 try { 7121 const decoder = new TextDecoder(encoding, { 7122 fatal: true 7123 }); 7124 const buffer = stringToBytes(str); 7125 const decoded = decoder.decode(buffer); 7126 if (keepEscapeSequence || !decoded.includes("\x1b")) { 7127 return decoded; 7128 } 7129 return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, ""); 7130 } catch (ex) { 7131 warn(`stringToPDFString: "${ex}".`); 7132 } 7133 } 7134 } 7135 const strBuf = []; 7136 for (let i = 0, ii = str.length; i < ii; i++) { 7137 const charCode = str.charCodeAt(i); 7138 if (!keepEscapeSequence && charCode === 0x1b) { 7139 while (++i < ii && str.charCodeAt(i) !== 0x1b) {} 7140 continue; 7141 } 7142 const code = PDFStringTranslateTable[charCode]; 7143 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); 7144 } 7145 return strBuf.join(""); 7146} 7147function stringToUTF8String(str) { 7148 return decodeURIComponent(escape(str)); 7149} 7150function utf8StringToString(str) { 7151 return unescape(encodeURIComponent(str)); 7152} 7153function isArrayEqual(arr1, arr2) { 7154 if (arr1.length !== arr2.length) { 7155 return false; 7156 } 7157 for (let i = 0, ii = arr1.length; i < ii; i++) { 7158 if (arr1[i] !== arr2[i]) { 7159 return false; 7160 } 7161 } 7162 return true; 7163} 7164function getModificationDate(date = new Date()) { 7165 if (!(date instanceof Date)) { 7166 date = new Date(date); 7167 } 7168 const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")]; 7169 return buffer.join(""); 7170} 7171let NormalizeRegex = null; 7172let NormalizationMap = null; 7173function normalizeUnicode(str) { 7174 if (!NormalizeRegex) { 7175 NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu; 7176 NormalizationMap = new Map([["ï¬ ", "Å¿t"]]); 7177 } 7178 return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2)); 7179} 7180function getUuid() { 7181 if (typeof crypto.randomUUID === "function") { 7182 return crypto.randomUUID(); 7183 } 7184 const buf = new Uint8Array(32); 7185 crypto.getRandomValues(buf); 7186 return bytesToString(buf); 7187} 7188const AnnotationPrefix = "pdfjs_internal_id_"; 7189function _isValidExplicitDest(validRef, validName, dest) { 7190 if (!Array.isArray(dest) || dest.length < 2) { 7191 return false; 7192 } 7193 const [page, zoom, ...args] = dest; 7194 if (!validRef(page) && !Number.isInteger(page)) { 7195 return false; 7196 } 7197 if (!validName(zoom)) { 7198 return false; 7199 } 7200 const argsLen = args.length; 7201 let allowNull = true; 7202 switch (zoom.name) { 7203 case "XYZ": 7204 if (argsLen < 2 || argsLen > 3) { 7205 return false; 7206 } 7207 break; 7208 case "Fit": 7209 case "FitB": 7210 return argsLen === 0; 7211 case "FitH": 7212 case "FitBH": 7213 case "FitV": 7214 case "FitBV": 7215 if (argsLen > 1) { 7216 return false; 7217 } 7218 break; 7219 case "FitR": 7220 if (argsLen !== 4) { 7221 return false; 7222 } 7223 allowNull = false; 7224 break; 7225 default: 7226 return false; 7227 } 7228 for (const arg of args) { 7229 if (typeof arg === "number" || allowNull && arg === null) { 7230 continue; 7231 } 7232 return false; 7233 } 7234 return true; 7235} 7236const makeArr = () => []; 7237const makeMap = () => new Map(); 7238const makeObj = () => Object.create(null); 7239function MathClamp(v, min, max) { 7240 return Math.min(Math.max(v, min), max); 7241} 7242if (typeof Response.prototype.bytes !== "function") { 7243 Response.prototype.bytes = async function () { 7244 return new Uint8Array(await this.arrayBuffer()); 7245 }; 7246} 7247if (typeof AbortSignal.any !== "function") { 7248 AbortSignal.any = function (iterable) { 7249 const ac = new AbortController(); 7250 const { 7251 signal 7252 } = ac; 7253 for (const s of iterable) { 7254 if (s.aborted) { 7255 ac.abort(s.reason); 7256 return signal; 7257 } 7258 } 7259 for (const s of iterable) { 7260 s.addEventListener("abort", () => { 7261 ac.abort(s.reason); 7262 }, { 7263 signal 7264 }); 7265 } 7266 return signal; 7267 }; 7268} 7269 7270// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.every.js 7271var es_iterator_every = __webpack_require__(1148); 7272// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.map.js 7273var es_iterator_map = __webpack_require__(1701); 7274// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.delete.js 7275var web_url_search_params_delete = __webpack_require__(4603); 7276// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.has.js 7277var web_url_search_params_has = __webpack_require__(7566); 7278// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.size.js 7279var web_url_search_params_size = __webpack_require__(8721); 7280;// ./src/display/xfa_text.js 7281 7282class XfaText { 7283 static textContent(xfa) { 7284 const items = []; 7285 const output = { 7286 items, 7287 styles: Object.create(null) 7288 }; 7289 function walk(node) { 7290 if (!node) { 7291 return; 7292 } 7293 let str = null; 7294 const name = node.name; 7295 if (name === "#text") { 7296 str = node.value; 7297 } else if (!XfaText.shouldBuildText(name)) { 7298 return; 7299 } else if (node?.attributes?.textContent) { 7300 str = node.attributes.textContent; 7301 } else if (node.value) { 7302 str = node.value; 7303 } 7304 if (str !== null) { 7305 items.push({ 7306 str 7307 }); 7308 } 7309 if (!node.children) { 7310 return; 7311 } 7312 for (const child of node.children) { 7313 walk(child); 7314 } 7315 } 7316 walk(xfa); 7317 return output; 7318 } 7319 static shouldBuildText(name) { 7320 return !(name === "textarea" || name === "input" || name === "option" || name === "select"); 7321 } 7322} 7323 7324;// ./src/display/xfa_layer.js 7325 7326 7327class XfaLayer { 7328 static setupStorage(html, id, element, storage, intent) { 7329 const storedData = storage.getValue(id, { 7330 value: null 7331 }); 7332 switch (element.name) { 7333 case "textarea": 7334 if (storedData.value !== null) { 7335 html.textContent = storedData.value; 7336 } 7337 if (intent === "print") { 7338 break; 7339 } 7340 html.addEventListener("input", event => { 7341 storage.setValue(id, { 7342 value: event.target.value 7343 }); 7344 }); 7345 break; 7346 case "input": 7347 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { 7348 if (storedData.value === element.attributes.xfaOn) { 7349 html.setAttribute("checked", true); 7350 } else if (storedData.value === element.attributes.xfaOff) { 7351 html.removeAttribute("checked"); 7352 } 7353 if (intent === "print") { 7354 break; 7355 } 7356 html.addEventListener("change", event => { 7357 storage.setValue(id, { 7358 value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") 7359 }); 7360 }); 7361 } else { 7362 if (storedData.value !== null) { 7363 html.setAttribute("value", storedData.value); 7364 } 7365 if (intent === "print") { 7366 break; 7367 } 7368 html.addEventListener("input", event => { 7369 storage.setValue(id, { 7370 value: event.target.value 7371 }); 7372 }); 7373 } 7374 break; 7375 case "select": 7376 if (storedData.value !== null) { 7377 html.setAttribute("value", storedData.value); 7378 for (const option of element.children) { 7379 if (option.attributes.value === storedData.value) { 7380 option.attributes.selected = true; 7381 } else if (option.attributes.hasOwnProperty("selected")) { 7382 delete option.attributes.selected; 7383 } 7384 } 7385 } 7386 html.addEventListener("input", event => { 7387 const options = event.target.options; 7388 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; 7389 storage.setValue(id, { 7390 value 7391 }); 7392 }); 7393 break; 7394 } 7395 } 7396 static setAttributes({ 7397 html, 7398 element, 7399 storage = null, 7400 intent, 7401 linkService 7402 }) { 7403 const { 7404 attributes 7405 } = element; 7406 const isHTMLAnchorElement = html instanceof HTMLAnchorElement; 7407 if (attributes.type === "radio") { 7408 attributes.name = `${attributes.name}-${intent}`; 7409 } 7410 for (const [key, value] of Object.entries(attributes)) { 7411 if (value === null || value === undefined) { 7412 continue; 7413 } 7414 switch (key) { 7415 case "class": 7416 if (value.length) { 7417 html.setAttribute(key, value.join(" ")); 7418 } 7419 break; 7420 case "dataId": 7421 break; 7422 case "id": 7423 html.setAttribute("data-element-id", value); 7424 break; 7425 case "style": 7426 Object.assign(html.style, value); 7427 break; 7428 case "textContent": 7429 html.textContent = value; 7430 break; 7431 default: 7432 if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") { 7433 html.setAttribute(key, value); 7434 } 7435 } 7436 } 7437 if (isHTMLAnchorElement) { 7438 linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); 7439 } 7440 if (storage && attributes.dataId) { 7441 this.setupStorage(html, attributes.dataId, element, storage); 7442 } 7443 } 7444 static render(parameters) { 7445 const storage = parameters.annotationStorage; 7446 const linkService = parameters.linkService; 7447 const root = parameters.xfaHtml; 7448 const intent = parameters.intent || "display"; 7449 const rootHtml = document.createElement(root.name); 7450 if (root.attributes) { 7451 this.setAttributes({ 7452 html: rootHtml, 7453 element: root, 7454 intent, 7455 linkService 7456 }); 7457 } 7458 const isNotForRichText = intent !== "richText"; 7459 const rootDiv = parameters.div; 7460 rootDiv.append(rootHtml); 7461 if (parameters.viewport) { 7462 const transform = `matrix(${parameters.viewport.transform.join(",")})`; 7463 rootDiv.style.transform = transform; 7464 } 7465 if (isNotForRichText) { 7466 rootDiv.setAttribute("class", "xfaLayer xfaFont"); 7467 } 7468 const textDivs = []; 7469 if (root.children.length === 0) { 7470 if (root.value) { 7471 const node = document.createTextNode(root.value); 7472 rootHtml.append(node); 7473 if (isNotForRichText && XfaText.shouldBuildText(root.name)) { 7474 textDivs.push(node); 7475 } 7476 } 7477 return { 7478 textDivs 7479 }; 7480 } 7481 const stack = [[root, -1, rootHtml]]; 7482 while (stack.length > 0) { 7483 const [parent, i, html] = stack.at(-1); 7484 if (i + 1 === parent.children.length) { 7485 stack.pop(); 7486 continue; 7487 } 7488 const child = parent.children[++stack.at(-1)[1]]; 7489 if (child === null) { 7490 continue; 7491 } 7492 const { 7493 name 7494 } = child; 7495 if (name === "#text") { 7496 const node = document.createTextNode(child.value); 7497 textDivs.push(node); 7498 html.append(node); 7499 continue; 7500 } 7501 const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); 7502 html.append(childHtml); 7503 if (child.attributes) { 7504 this.setAttributes({ 7505 html: childHtml, 7506 element: child, 7507 storage, 7508 intent, 7509 linkService 7510 }); 7511 } 7512 if (child.children?.length > 0) { 7513 stack.push([child, -1, childHtml]); 7514 } else if (child.value) { 7515 const node = document.createTextNode(child.value); 7516 if (isNotForRichText && XfaText.shouldBuildText(name)) { 7517 textDivs.push(node); 7518 } 7519 childHtml.append(node); 7520 } 7521 } 7522 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { 7523 el.setAttribute("readOnly", true); 7524 } 7525 return { 7526 textDivs 7527 }; 7528 } 7529 static update(parameters) { 7530 const transform = `matrix(${parameters.viewport.transform.join(",")})`; 7531 parameters.div.style.transform = transform; 7532 parameters.div.hidden = false;
vendor: 5,530 bytes, lines 7533-7754
7533 } 7534} 7535 7536;// ./src/display/display_utils.js 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557const SVG_NS = "http://www.w3.org/2000/svg"; 7558class PixelsPerInch { 7559 static CSS = 96.0; 7560 static PDF = 72.0; 7561 static PDF_TO_CSS_UNITS = this.CSS / this.PDF; 7562} 7563async function fetchData(url, type = "text") { 7564 if (isValidFetchUrl(url, document.baseURI)) { 7565 const response = await fetch(url); 7566 if (!response.ok) { 7567 throw new Error(response.statusText); 7568 } 7569 switch (type) { 7570 case "blob": 7571 return response.blob(); 7572 case "bytes": 7573 return response.bytes(); 7574 case "json": 7575 return response.json(); 7576 } 7577 return response.text(); 7578 } 7579 return new Promise((resolve, reject) => { 7580 const request = new XMLHttpRequest(); 7581 request.open("GET", url, true); 7582 request.responseType = type === "bytes" ? "arraybuffer" : type; 7583 request.onreadystatechange = () => { 7584 if (request.readyState !== XMLHttpRequest.DONE) { 7585 return; 7586 } 7587 if (request.status === 200 || request.status === 0) { 7588 switch (type) { 7589 case "bytes": 7590 resolve(new Uint8Array(request.response)); 7591 return; 7592 case "blob": 7593 case "json": 7594 resolve(request.response); 7595 return; 7596 } 7597 resolve(request.responseText); 7598 return; 7599 } 7600 reject(new Error(request.statusText)); 7601 }; 7602 request.send(null); 7603 }); 7604} 7605class PageViewport { 7606 constructor({ 7607 viewBox, 7608 userUnit, 7609 scale, 7610 rotation, 7611 offsetX = 0, 7612 offsetY = 0, 7613 dontFlip = false 7614 }) { 7615 this.viewBox = viewBox; 7616 this.userUnit = userUnit; 7617 this.scale = scale; 7618 this.rotation = rotation; 7619 this.offsetX = offsetX; 7620 this.offsetY = offsetY; 7621 scale *= userUnit; 7622 const centerX = (viewBox[2] + viewBox[0]) / 2; 7623 const centerY = (viewBox[3] + viewBox[1]) / 2; 7624 let rotateA, rotateB, rotateC, rotateD; 7625 rotation %= 360; 7626 if (rotation < 0) { 7627 rotation += 360; 7628 } 7629 switch (rotation) { 7630 case 180: 7631 rotateA = -1; 7632 rotateB = 0; 7633 rotateC = 0; 7634 rotateD = 1; 7635 break; 7636 case 90: 7637 rotateA = 0; 7638 rotateB = 1; 7639 rotateC = 1; 7640 rotateD = 0; 7641 break; 7642 case 270: 7643 rotateA = 0; 7644 rotateB = -1; 7645 rotateC = -1; 7646 rotateD = 0; 7647 break; 7648 case 0: 7649 rotateA = 1; 7650 rotateB = 0; 7651 rotateC = 0; 7652 rotateD = -1; 7653 break; 7654 default: 7655 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); 7656 } 7657 if (dontFlip) { 7658 rotateC = -rotateC; 7659 rotateD = -rotateD; 7660 } 7661 let offsetCanvasX, offsetCanvasY; 7662 let width, height; 7663 if (rotateA === 0) { 7664 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; 7665 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; 7666 width = (viewBox[3] - viewBox[1]) * scale; 7667 height = (viewBox[2] - viewBox[0]) * scale; 7668 } else { 7669 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; 7670 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; 7671 width = (viewBox[2] - viewBox[0]) * scale; 7672 height = (viewBox[3] - viewBox[1]) * scale; 7673 } 7674 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; 7675 this.width = width; 7676 this.height = height; 7677 } 7678 get rawDims() { 7679 const dims = this.viewBox; 7680 return shadow(this, "rawDims", { 7681 pageWidth: dims[2] - dims[0], 7682 pageHeight: dims[3] - dims[1], 7683 pageX: dims[0], 7684 pageY: dims[1] 7685 }); 7686 } 7687 clone({ 7688 scale = this.scale, 7689 rotation = this.rotation, 7690 offsetX = this.offsetX, 7691 offsetY = this.offsetY, 7692 dontFlip = false 7693 } = {}) { 7694 return new PageViewport({ 7695 viewBox: this.viewBox.slice(), 7696 userUnit: this.userUnit, 7697 scale, 7698 rotation, 7699 offsetX, 7700 offsetY, 7701 dontFlip 7702 }); 7703 } 7704 convertToViewportPoint(x, y) { 7705 const p = [x, y]; 7706 Util.applyTransform(p, this.transform); 7707 return p; 7708 } 7709 convertToViewportRectangle(rect) { 7710 const topLeft = [rect[0], rect[1]]; 7711 Util.applyTransform(topLeft, this.transform); 7712 const bottomRight = [rect[2], rect[3]]; 7713 Util.applyTransform(bottomRight, this.transform); 7714 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; 7715 } 7716 convertToPdfPoint(x, y) { 7717 const p = [x, y]; 7718 Util.applyInverseTransform(p, this.transform); 7719 return p; 7720 } 7721} 7722class RenderingCancelledException extends BaseException { 7723 constructor(msg, extraDelay = 0) { 7724 super(msg, "RenderingCancelledException"); 7725 this.extraDelay = extraDelay; 7726 } 7727} 7728function isDataScheme(url) { 7729 const ii = url.length; 7730 let i = 0; 7731 while (i < ii && url[i].trim() === "") { 7732 i++; 7733 } 7734 return url.substring(i, i + 5).toLowerCase() === "data:"; 7735} 7736function isPdfFile(filename) { 7737 return typeof filename === "string" && /\.pdf$/i.test(filename); 7738} 7739function getFilenameFromUrl(url) { 7740 [url] = url.split(/[#?]/, 1); 7741 return stripPath(url); 7742} 7743function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { 7744 if (typeof url !== "string") { 7745 return defaultFilename; 7746 } 7747 if (isDataScheme(url)) { 7748 warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); 7749 return defaultFilename; 7750 } 7751 const getURL = urlString => { 7752 try { 7753 return new URL(urlString); 7754 } catch {
7755 try { 7756 return new URL(decodeURIComponent(urlString)); 7757 } catch { 7758 try { 7759 return new URL(urlString, "https://foo.bar"); 7760 } catch { 7761 try { 7762 return new URL(decodeURIComponent(urlString), "https://foo.bar"); 7763 } catch { 7764 return null; 7765 } 7766 } 7767 } 7768 } 7769 }; 7770 const newURL = getURL(url); 7771 if (!newURL) { 7772 return defaultFilename; 7773 } 7774 const decode = name => { 7775 try { 7776 let decoded = decodeURIComponent(name); 7777 if (decoded.includes("/")) { 7778 decoded = stripPath(decoded); 7779 if (/^\.pdf$/i.test(decoded)) { 7780 return name; 7781 } 7782 } 7783 return decoded; 7784 } catch { 7785 return name; 7786 } 7787 }; 7788 const pdfRegex = /\.pdf$/i; 7789 const filename = stripPath(newURL.pathname); 7790 if (pdfRegex.test(filename)) { 7791 return decode(filename); 7792 } 7793 if (newURL.searchParams.size > 0) { 7794 const getLast = iterator => [...iterator].findLast(v => pdfRegex.test(v)); 7795 const name = getLast(newURL.searchParams.values()) ?? getLast(newURL.searchParams.keys()); 7796 if (name) { 7797 return decode(name); 7798 } 7799 } 7800 if (newURL.hash) { 7801 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; 7802 const hashFilename = reFilename.exec(newURL.hash); 7803 if (hashFilename) { 7804 return decode(hashFilename[0]); 7805 } 7806 } 7807 return defaultFilename; 7808} 7809class StatTimer { 7810 started = Object.create(null); 7811 times = []; 7812 time(name) { 7813 if (name in this.started) { 7814 warn(`Timer is already running for ${name}`); 7815 } 7816 this.started[name] = Date.now(); 7817 } 7818 timeEnd(name) { 7819 if (!(name in this.started)) { 7820 warn(`Timer has not been started for ${name}`); 7821 } 7822 this.times.push({ 7823 name, 7824 start: this.started[name], 7825 end: Date.now() 7826 }); 7827 delete this.started[name]; 7828 } 7829 toString() { 7830 const outBuf = []; 7831 let longest = 0; 7832 for (const { 7833 name 7834 } of this.times) { 7835 longest = Math.max(name.length, longest); 7836 } 7837 for (const { 7838 name, 7839 start, 7840 end 7841 } of this.times) { 7842 outBuf.push(`${name.padEnd(longest)} ${end - start}
7842ms\n`); 7843 } 7844 return outBuf.join(""); 7845 } 7846} 7847function isValidFetchUrl(url, baseUrl) { 7848 const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); 7849 return /https?:/.test(res?.protocol ?? ""); 7850} 7851function noContextMenu(e) { 7852 e.preventDefault(); 7853} 7854function stopEvent(e) { 7855 e.preventDefault(); 7856 e.stopPropagation(); 7857} 7858function deprecated(details) { 7859 console.log("Deprecated API usage: " + details); 7860} 7861class PDFDateString { 7862 static #regex; 7863 static toDateObject(input) { 7864 if (input instanceof Date) { 7865 return input; 7866 } 7867 if (!input || typeof input !== "string") { 7868 return null; 7869 } 7870 this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); 7871 const matches = this.#regex.exec(input); 7872 if (!matches) { 7873 return null; 7874 } 7875 const year = parseInt(matches[1], 10); 7876 let month = parseInt(matches[2], 10); 7877 month = month >= 1 && month <= 12 ? month - 1 : 0; 7878 let day = parseInt(matches[3], 10); 7879 day = day >= 1 && day <= 31 ? day : 1; 7880 let hour = parseInt(matches[4], 10); 7881 hour = hour >= 0 && hour <= 23 ? hour : 0; 7882 let minute = parseInt(matches[5], 10); 7883 minute = minute >= 0 && minute <= 59 ? minute : 0; 7884 let second = parseInt(matches[6], 10); 7885 second = second >= 0 && second <= 59 ? second : 0; 7886 const universalTimeRelation = matches[7] || "Z"; 7887 let offsetHour = parseInt(matches[8], 10); 7888 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; 7889 let offsetMinute = parseInt(matches[9], 10) || 0; 7890 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; 7891 if (universalTimeRelation === "-") { 7892 hour += offsetHour; 7893 minute += offsetMinute; 7894 } else if (universalTimeRelation === "+") { 7895 hour -= offsetHour; 7896 minute -= offsetMinute; 7897 } 7898 return new Date(Date.UTC(year, month, day, hour, minute, second)); 7899 } 7900} 7901function getXfaPageViewport(xfaPage, { 7902 scale = 1, 7903 rotation = 0 7904}) { 7905 const { 7906 width, 7907 height 7908 } = xfaPage.attributes.style; 7909 const viewBox = [0, 0, parseInt(width), parseInt(height)]; 7910 return new PageViewport({ 7911 viewBox, 7912 userUnit: 1, 7913 scale, 7914 rotation 7915 }); 7916} 7917function getRGB(color) { 7918 if (color.startsWith("#")) { 7919 const colorRGB = parseInt(color.slice(1), 16); 7920 return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff]; 7921 } 7922 if (color.startsWith("rgb(")) { 7923 return color.slice(4, -1).split(",").map(x => parseInt(x)); 7924 } 7925 if (color.startsWith("rgba(")) { 7926 return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3); 7927 } 7928 warn(`Not a valid color format: "${color}"`); 7929 return [0, 0, 0]; 7930} 7931function getColorValues(colors) { 7932 const span = document.createElement("span"); 7933 span.style.visibility = "hidden"; 7934 span.style.colorScheme = "only light"; 7935 document.body.append(span); 7936 for (const name of colors.keys()) { 7937 span.style.color = name; 7938 const computedColor = window.getComputedStyle(span).color; 7939 colors.set(name, getRGB(computedColor)); 7940 } 7941 span.remove(); 7942} 7943function getCurrentTransform(ctx) { 7944 const { 7945 a, 7946 b, 7947 c, 7948 d, 7949 e, 7950 f 7951 } = ctx.getTransform(); 7952 return [a, b, c, d, e, f]; 7953} 7954function getCurrentTransformInverse(ctx) { 7955 const { 7956 a, 7957 b, 7958 c, 7959 d, 7960 e, 7961 f 7962 } = ctx.getTransform().invertSelf(); 7963 return [a, b, c, d, e, f]; 7964} 7965function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { 7966 if (viewport instanceof PageViewport) { 7967 const { 7968 pageWidth, 7969 pageHeight 7970 } = viewport.rawDims; 7971 const { 7972 style 7973 } = div; 7974 const useRound = FeatureTest.isCSSRoundSupported; 7975 const w = `var(--total-scale-factor) * ${pageWidth}px`, 7976 h = `var(--total-scale-factor) * ${pageHeight}px`; 7977 const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`, 7978 heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`; 7979 if (!mustFlip || viewport.rotation % 180 === 0) { 7980 style.width = widthStr; 7981 style.height = heightStr; 7982 } else { 7983 style.width = heightStr; 7984 style.height = widthStr; 7985 } 7986 } 7987 if (mustRotate) { 7988 div.setAttribute("data-main-rotation", viewport.rotation); 7989 } 7990} 7991class OutputScale { 7992 constructor() { 7993 const { 7994 pixelRatio 7995 } = OutputScale; 7996 this.sx = pixelRatio; 7997 this.sy = pixelRatio; 7998 } 7999 get scaled() { 8000 return this.sx !== 1 || this.sy !== 1; 8001 } 8002 get symmetric() { 8003 return this.sx === this.sy; 8004 } 8005 limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) { 8006 let maxAreaScale = Infinity, 8007 maxWidthScale = Infinity, 8008 maxHeightScale = Infinity; 8009 maxPixels = OutputScale.capPixels(maxPixels, capAreaFactor); 8010 if (maxPixels > 0) { 8011 maxAreaScale = Math.sqrt(maxPixels / (width * height)); 8012 } 8013 if (maxDim !== -1) { 8014 maxWidthScale = maxDim / width; 8015 maxHeightScale = maxDim / height; 8016 } 8017 const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale); 8018 if (this.sx > maxScale || this.sy > maxScale) { 8019 this.sx = maxScale; 8020 this.sy = maxScale; 8021 return true; 8022 } 8023 return false;
vendor: 6,339 bytes, lines 8024-8235
8024 } 8025 static get pixelRatio() { 8026 return globalThis.devicePixelRatio || 1; 8027 } 8028 static capPixels(maxPixels, capAreaFactor) { 8029 if (capAreaFactor >= 0) { 8030 const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)); 8031 return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels; 8032 } 8033 return maxPixels; 8034 } 8035} 8036const SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"]; 8037class ColorScheme { 8038 static get isDarkMode() { 8039 return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches); 8040 } 8041} 8042class CSSConstants { 8043 static get commentForegroundColor() { 8044 const element = document.createElement("span"); 8045 element.classList.add("comment", "sidebar"); 8046 const { 8047 style 8048 } = element; 8049 style.width = style.height = "0"; 8050 style.display = "none"; 8051 style.color = "var(--comment-fg-color)"; 8052 document.body.append(element); 8053 const { 8054 color 8055 } = window.getComputedStyle(element); 8056 element.remove(); 8057 return shadow(this, "commentForegroundColor", getRGB(color)); 8058 } 8059} 8060function applyOpacity(r, g, b, opacity) { 8061 opacity = MathClamp(opacity ?? 1, 0, 1); 8062 const white = 255 * (1 - opacity); 8063 r = Math.round(r * opacity + white); 8064 g = Math.round(g * opacity + white); 8065 b = Math.round(b * opacity + white); 8066 return [r, g, b]; 8067} 8068function RGBToHSL(rgb, output) { 8069 const r = rgb[0] / 255; 8070 const g = rgb[1] / 255; 8071 const b = rgb[2] / 255; 8072 const max = Math.max(r, g, b); 8073 const min = Math.min(r, g, b); 8074 const l = (max + min) / 2; 8075 if (max === min) { 8076 output[0] = output[1] = 0; 8077 } else { 8078 const d = max - min; 8079 output[1] = l < 0.5 ? d / (max + min) : d / (2 - max - min); 8080 switch (max) { 8081 case r: 8082 output[0] = ((g - b) / d + (g < b ? 6 : 0)) * 60; 8083 break; 8084 case g: 8085 output[0] = ((b - r) / d + 2) * 60; 8086 break; 8087 case b: 8088 output[0] = ((r - g) / d + 4) * 60; 8089 break; 8090 } 8091 } 8092 output[2] = l; 8093} 8094function HSLToRGB(hsl, output) { 8095 const h = hsl[0]; 8096 const s = hsl[1]; 8097 const l = hsl[2]; 8098 const c = (1 - Math.abs(2 * l - 1)) * s; 8099 const x = c * (1 - Math.abs(h / 60 % 2 - 1)); 8100 const m = l - c / 2; 8101 switch (Math.floor(h / 60)) { 8102 case 0: 8103 output[0] = c + m; 8104 output[1] = x + m; 8105 output[2] = m; 8106 break; 8107 case 1: 8108 output[0] = x + m; 8109 output[1] = c + m; 8110 output[2] = m; 8111 break; 8112 case 2: 8113 output[0] = m; 8114 output[1] = c + m; 8115 output[2] = x + m; 8116 break; 8117 case 3: 8118 output[0] = m; 8119 output[1] = x + m; 8120 output[2] = c + m; 8121 break; 8122 case 4: 8123 output[0] = x + m; 8124 output[1] = m; 8125 output[2] = c + m; 8126 break; 8127 case 5: 8128 case 6: 8129 output[0] = c + m; 8130 output[1] = m; 8131 output[2] = x + m; 8132 break; 8133 } 8134} 8135function computeLuminance(x) { 8136 return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; 8137} 8138function contrastRatio(hsl1, hsl2, output) { 8139 HSLToRGB(hsl1, output); 8140 output.map(computeLuminance); 8141 const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; 8142 HSLToRGB(hsl2, output); 8143 output.map(computeLuminance); 8144 const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; 8145 return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05); 8146} 8147const contrastCache = new Map(); 8148function findContrastColor(baseColor, fixedColor) { 8149 const key = baseColor[0] + baseColor[1] * 0x100 + baseColor[2] * 0x10000 + fixedColor[0] * 0x1000000 + fixedColor[1] * 0x100000000 + fixedColor[2] * 0x10000000000; 8150 let cachedValue = contrastCache.get(key); 8151 if (cachedValue) { 8152 return cachedValue; 8153 } 8154 const array = new Float32Array(9); 8155 const output = array.subarray(0, 3); 8156 const baseHSL = array.subarray(3, 6); 8157 RGBToHSL(baseColor, baseHSL); 8158 const fixedHSL = array.subarray(6, 9); 8159 RGBToHSL(fixedColor, fixedHSL); 8160 const isFixedColorDark = fixedHSL[2] < 0.5; 8161 const minContrast = isFixedColorDark ? 12 : 4.5; 8162 baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]); 8163 if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) { 8164 let start, end; 8165 if (isFixedColorDark) { 8166 start = baseHSL[2]; 8167 end = 1; 8168 } else { 8169 start = 0; 8170 end = baseHSL[2]; 8171 } 8172 const PRECISION = 0.005; 8173 while (end - start > PRECISION) { 8174 const mid = baseHSL[2] = (start + end) / 2; 8175 if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) { 8176 start = mid; 8177 } else { 8178 end = mid; 8179 } 8180 } 8181 baseHSL[2] = isFixedColorDark ? end : start; 8182 } 8183 HSLToRGB(baseHSL, output); 8184 cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255)); 8185 contrastCache.set(key, cachedValue); 8186 return cachedValue; 8187} 8188function renderRichText({ 8189 html, 8190 dir, 8191 className 8192}, container) { 8193 const fragment = document.createDocumentFragment(); 8194 if (typeof html === "string") { 8195 const p = document.createElement("p"); 8196 p.dir = dir || "auto"; 8197 const lines = html.split(/(?:\r\n?|\n)/); 8198 for (let i = 0, ii = lines.length; i < ii; ++i) { 8199 const line = lines[i]; 8200 p.append(document.createTextNode(line)); 8201 if (i < ii - 1) { 8202 p.append(document.createElement("br")); 8203 } 8204 } 8205 fragment.append(p); 8206 } else { 8207 XfaLayer.render({ 8208 xfaHtml: html, 8209 div: fragment, 8210 intent: "richText" 8211 }); 8212 } 8213 fragment.firstElementChild.classList.add("richText", className); 8214 container.append(fragment); 8215} 8216function makePathFromDrawOPS(data) { 8217 const path = new Path2D(); 8218 if (!data) { 8219 return path; 8220 } 8221 for (let i = 0, ii = data.length; i < ii;) { 8222 switch (data[i++]) { 8223 case DrawOPS.moveTo: 8224 path.moveTo(data[i++], data[i++]); 8225 break; 8226 case DrawOPS.lineTo: 8227 path.lineTo(data[i++], data[i++]); 8228 break; 8229 case DrawOPS.curveTo: 8230 path.bezierCurveTo(data[i++], data[i++], data[i++], data[i++], data[i++], data[i++]); 8231 break; 8232 case DrawOPS.quadraticCurveTo: 8233 path.quadraticCurveTo(data[i++], data[i++], data[i++], data[i++]); 8234 break; 8235 case DrawOPS.closePath:
8236 path.closePath(); 8237 break; 8238 default: 8239 warn(`Unrecognized drawing path operator: ${data[i - 1]}`); 8240 break; 8241 } 8242 } 8243 return path; 8244} 8245class PagesMapper { 8246 #idToPageNumber = null; 8247 #pageNumberToId = null; 8248 #prevPageNumbers = null; 8249 #pagesNumber = 0; 8250 #listeners = []; 8251 #copiedPageIds = null; 8252 #copiedPageNumbers = null; 8253 get pagesNumber() { 8254 return this.#pagesNumber; 8255 } 8256 set pagesNumber(n) { 8257 if (this.#pagesNumber === n) { 8258 return; 8259 } 8260 this.#pagesNumber = n; 8261 this.#reset(); 8262 } 8263 #reset() { 8264 this.#pageNumberToId = null; 8265 this.#idToPageNumber = null; 8266 } 8267 addListener(listener) { 8268 this.#listeners.push(listener); 8269 } 8270 removeListener(listener) { 8271 const index = this.#listeners.indexOf(listener); 8272 if (index >= 0) { 8273 this.#listeners.splice(index, 1); 8274 } 8275 } 8276 #updateListeners(data) { 8277 for (const listener of this.#listeners) { 8278 listener(data); 8279 } 8280 } 8281 #init(mustInit) { 8282 if (this.#pageNumberToId) { 8283 return; 8284 } 8285 const n = this.#pagesNumber; 8286 const pageNumberToId = this.#pageNumberToId = new Uint32Array(n); 8287 this.#prevPageNumbers = new Int32Array(pageNumberToId); 8288 const idToPageNumber = this.#idToPageNumber = new Map(); 8289 if (mustInit) { 8290 for (let i = 1; i <= n; i++) { 8291 pageNumberToId[i - 1] = i; 8292 idToPageNumber.set(i, [i]); 8293 } 8294 } 8295 } 8296 #updateIdToPageNumber() { 8297 const idToPageNumber = this.#idToPageNumber; 8298 const pageNumberToId = this.#pageNumberToId; 8299 idToPageNumber.clear(); 8300 for (let i = 0, ii = this.#pagesNumber; i < ii; i++) { 8301 const id = pageNumberToId[i]; 8302 const pageNumbers = idToPageNumber.get(id); 8303 if (pageNumbers) { 8304 pageNumbers.push(i + 1); 8305 } else { 8306 idToPageNumber.set(id, [i + 1]); 8307 } 8308 } 8309 } 8310 movePages(selectedPages, pagesToMove, index) { 8311 this.#init(true); 8312 const pageNumberToId = this.#pageNumberToId; 8313 const idToPageNumber = this.#idToPageNumber; 8314 const movedCount = pagesToMove.length; 8315 const mappedPagesToMove = new Uint32Array(movedCount); 8316 let removedBeforeTarget = 0; 8317 for (let i = 0; i < movedCount; i++) { 8318 const pageIndex = pagesToMove[i] - 1; 8319 mappedPagesToMove[i] = pageNumberToId[pageIndex]; 8320 if (pageIndex < index) { 8321 removedBeforeTarget += 1; 8322 } 8323 } 8324 const pagesNumber = this.#pagesNumber; 8325 let adjustedTarget = index - removedBeforeTarget; 8326 const remainingLen = pagesNumber - movedCount; 8327 adjustedTarget = MathClamp(adjustedTarget, 0, remainingLen); 8328 for (let i = 0, r = 0; i < pagesNumber; i++) { 8329 if (!selectedPages.has(i + 1)) { 8330 pageNumberToId[r++] = pageNumberToId[i]; 8331 } 8332 } 8333 pageNumberToId.copyWithin(adjustedTarget + movedCount, adjustedTarget, remainingLen); 8334 pageNumberToId.set(mappedPagesToMove, adjustedTarget); 8335 this.#setPrevPageNumbers(idToPageNumber, null); 8336 this.#updateIdToPageNumber(); 8337 this.#updateListeners({ 8338 type: "move" 8339 }); 8340 if (pageNumberToId.every((id, i) => id === i + 1)) { 8341 this.#reset(); 8342 } 8343 } 8344 deletePages(pagesToDelete) { 8345 this.#init(true); 8346 const pageNumberToId = this.#pageNumberToId; 8347 const prevIdToPageNumber = this.#idToPageNumber; 8348 this.pagesNumber -= pagesToDelete.length; 8349 this.#init(false); 8350 const newPageNumberToId = this.#pageNumberToId; 8351 let sourceIndex = 0; 8352 let destIndex = 0; 8353 for (const pageNumber of pagesToDelete) { 8354 const pageIndex = pageNumber - 1; 8355 if (pageIndex !== sourceIndex) { 8356 newPageNumberToId.set(pageNumberToId.subarray(sourceIndex, pageIndex), destIndex); 8357 destIndex += pageIndex - sourceIndex; 8358 } 8359 sourceIndex = pageIndex + 1; 8360 } 8361 if (sourceIndex < pageNumberToId.length) { 8362 newPageNumberToId.set(pageNumberToId.subarray(sourceIndex), destIndex); 8363 } 8364 this.#setPrevPageNumbers(prevIdToPageNumber, null); 8365 this.#updateIdToPageNumber(); 8366 this.#updateListeners({ 8367 type: "delete", 8368 pageNumbers: pagesToDelete 8369 }); 8370 } 8371 copyPages(pagesToCopy) { 8372 this.#init(true); 8373 this.#copiedPageNumbers = pagesToCopy; 8374 this.#copiedPageIds = pagesToCopy.map(pageNumber => this.#pageNumberToId[pageNumber - 1]); 8375 this.#updateListeners({ 8376 type: "copy", 8377 pageNumbers: pagesToCopy 8378 }); 8379 } 8380 pastePages(index) { 8381 this.#init(true); 8382 const pageNumberToId = this.#pageNumberToId; 8383 const prevIdToPageNumber = this.#idToPageNumber; 8384 const copiedPageNumbers = this.#copiedPageNumbers; 8385 const copiedPageMapping = new Map(); 8386 let base = index; 8387 for (const pageNumber of copiedPageNumbers) { 8388 copiedPageMapping.set(++base, pageNumber); 8389 } 8390 this.pagesNumber += copiedPageNumbers.length; 8391 this.#init(false); 8392 const newPageNumberToId = this.#pageNumberToId; 8393 newPageNumberToId.set(pageNumberToId.subarray(0, index), 0); 8394 newPageNumberToId.set(this.#copiedPageIds, index); 8395 newPageNumberToId.set(pageNumberToId.subarray(index), index + copiedPageNumbers.length);
vendor: 19,459 bytes, lines 8396-9053
8396 this.#setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping); 8397 this.#updateIdToPageNumber(); 8398 this.#updateListeners({ 8399 type: "paste" 8400 }); 8401 this.#copiedPageIds = null; 8402 } 8403 #setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping) { 8404 const prevPageNumbers = this.#prevPageNumbers; 8405 const newPageNumberToId = this.#pageNumberToId; 8406 const idsIndices = new Map(); 8407 for (let i = 0, ii = this.#pagesNumber; i < ii; i++) { 8408 const oldPageNumber = copiedPageMapping?.get(i + 1); 8409 if (oldPageNumber) { 8410 prevPageNumbers[i] = -oldPageNumber; 8411 continue; 8412 } 8413 const id = newPageNumberToId[i]; 8414 const j = idsIndices.get(id) || 0; 8415 prevPageNumbers[i] = prevIdToPageNumber.get(id)?.[j]; 8416 idsIndices.set(id, j + 1); 8417 } 8418 } 8419 hasBeenAltered() { 8420 return this.#pageNumberToId !== null; 8421 } 8422 getPageMappingForSaving() { 8423 const idToPageNumber = this.#idToPageNumber; 8424 let nCopy = 0; 8425 for (const pageNumbers of idToPageNumber.values()) { 8426 nCopy = Math.max(nCopy, pageNumbers.length); 8427 } 8428 const extractParams = new Array(nCopy); 8429 for (let i = 0; i < nCopy; i++) { 8430 extractParams[i] = { 8431 document: null, 8432 pageIndices: [], 8433 includePages: [] 8434 }; 8435 } 8436 for (const [id, pageNumbers] of idToPageNumber) { 8437 for (let i = 0, ii = pageNumbers.length; i < ii; i++) { 8438 extractParams[i].includePages.push([id - 1, pageNumbers[i] - 1]); 8439 } 8440 } 8441 for (const { 8442 includePages, 8443 pageIndices 8444 } of extractParams) { 8445 includePages.sort((a, b) => a[0] - b[0]); 8446 for (let i = 0, ii = includePages.length; i < ii; i++) { 8447 pageIndices.push(includePages[i][1]); 8448 includePages[i] = includePages[i][0]; 8449 } 8450 } 8451 return extractParams; 8452 } 8453 getPrevPageNumber(pageNumber) { 8454 return this.#prevPageNumbers[pageNumber - 1] ?? 0; 8455 } 8456 getPageNumber(id) { 8457 return this.#idToPageNumber ? this.#idToPageNumber.get(id)?.[0] ?? 0 : id; 8458 } 8459 getPageId(pageNumber) { 8460 return this.#pageNumberToId?.[pageNumber - 1] ?? pageNumber; 8461 } 8462 getMapping() { 8463 return this.#pageNumberToId.subarray(0, this.pagesNumber); 8464 } 8465} 8466 8467// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.take.js 8468var es_iterator_take = __webpack_require__(4972); 8469// EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.with-resolvers.js 8470var es_promise_with_resolvers = __webpack_require__(4628); 8471// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.difference.v2.js 8472var es_set_difference_v2 = __webpack_require__(7642); 8473// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.intersection.v2.js 8474var es_set_intersection_v2 = __webpack_require__(8004); 8475// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-disjoint-from.v2.js 8476var es_set_is_disjoint_from_v2 = __webpack_require__(3853); 8477// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-subset-of.v2.js 8478var es_set_is_subset_of_v2 = __webpack_require__(5876); 8479// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-superset-of.v2.js 8480var es_set_is_superset_of_v2 = __webpack_require__(2475); 8481// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.symmetric-difference.v2.js 8482var es_set_symmetric_difference_v2 = __webpack_require__(5024); 8483// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.union.v2.js 8484var es_set_union_v2 = __webpack_require__(1698); 8485// EXTERNAL MODULE: ./node_modules/core-js/modules/es.weak-map.get-or-insert.js 8486var es_weak_map_get_or_insert = __webpack_require__(8454); 8487// EXTERNAL MODULE: ./node_modules/core-js/modules/es.weak-map.get-or-insert-computed.js 8488var es_weak_map_get_or_insert_computed = __webpack_require__(9452); 8489// EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom-exception.stack.js 8490var web_dom_exception_stack = __webpack_require__(4979); 8491// EXTERNAL MODULE: ./node_modules/core-js/modules/es.json.stringify.js 8492var es_json_stringify = __webpack_require__(3110); 8493// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.drop.js 8494var es_iterator_drop = __webpack_require__(9314); 8495// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.some.js 8496var es_iterator_some = __webpack_require__(3579); 8497// EXTERNAL MODULE: ./node_modules/core-js/modules/es.json.parse.js 8498var es_json_parse = __webpack_require__(9112); 8499;// ./src/display/editor/toolbar.js 8500 8501class EditorToolbar { 8502 #toolbar = null; 8503 #colorPicker = null; 8504 #editor; 8505 #buttons = null; 8506 #altText = null; 8507 #comment = null; 8508 #commentButtonDivider = null; 8509 #signatureDescriptionButton = null; 8510 static #l10nRemove = null; 8511 constructor(editor) { 8512 this.#editor = editor; 8513 EditorToolbar.#l10nRemove ||= Object.freeze({ 8514 freetext: "pdfjs-editor-remove-freetext-button", 8515 highlight: "pdfjs-editor-remove-highlight-button", 8516 ink: "pdfjs-editor-remove-ink-button", 8517 stamp: "pdfjs-editor-remove-stamp-button", 8518 signature: "pdfjs-editor-remove-signature-button" 8519 }); 8520 } 8521 render() { 8522 const editToolbar = this.#toolbar = document.createElement("div"); 8523 editToolbar.classList.add("editToolbar", "hidden"); 8524 editToolbar.setAttribute("role", "toolbar"); 8525 const signal = this.#editor._uiManager._signal; 8526 if (signal instanceof AbortSignal && !signal.aborted) { 8527 editToolbar.addEventListener("contextmenu", noContextMenu, { 8528 signal 8529 }); 8530 editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, { 8531 signal 8532 }); 8533 } 8534 const buttons = this.#buttons = document.createElement("div"); 8535 buttons.className = "buttons"; 8536 editToolbar.append(buttons); 8537 const position = this.#editor.toolbarPosition; 8538 if (position) { 8539 const { 8540 style 8541 } = editToolbar; 8542 const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0]; 8543 style.insetInlineEnd = `${100 * x}%`; 8544 style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`; 8545 } 8546 return editToolbar; 8547 } 8548 get div() { 8549 return this.#toolbar; 8550 } 8551 static #pointerDown(e) { 8552 e.stopPropagation(); 8553 } 8554 #focusIn(e) { 8555 this.#editor._focusEventsAllowed = false; 8556 stopEvent(e); 8557 } 8558 #focusOut(e) { 8559 this.#editor._focusEventsAllowed = true; 8560 stopEvent(e); 8561 } 8562 #addListenersToElement(element) { 8563 const signal = this.#editor._uiManager._signal; 8564 if (!(signal instanceof AbortSignal) || signal.aborted) { 8565 return false; 8566 } 8567 element.addEventListener("focusin", this.#focusIn.bind(this), { 8568 capture: true, 8569 signal 8570 }); 8571 element.addEventListener("focusout", this.#focusOut.bind(this), { 8572 capture: true, 8573 signal 8574 }); 8575 element.addEventListener("contextmenu", noContextMenu, { 8576 signal 8577 }); 8578 return true; 8579 } 8580 hide() { 8581 this.#toolbar.classList.add("hidden"); 8582 this.#colorPicker?.hideDropdown(); 8583 } 8584 show() { 8585 this.#toolbar.classList.remove("hidden"); 8586 this.#altText?.shown(); 8587 this.#comment?.shown(); 8588 } 8589 addDeleteButton() { 8590 const { 8591 editorType, 8592 _uiManager 8593 } = this.#editor; 8594 const button = document.createElement("button"); 8595 button.classList.add("basic", "deleteButton"); 8596 button.tabIndex = 0; 8597 button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]); 8598 if (this.#addListenersToElement(button)) { 8599 button.addEventListener("click", e => { 8600 _uiManager.delete(); 8601 }, { 8602 signal: _uiManager._signal 8603 }); 8604 } 8605 this.#buttons.append(button); 8606 } 8607 get #divider() { 8608 const divider = document.createElement("div"); 8609 divider.className = "divider"; 8610 return divider; 8611 } 8612 async addAltText(altText) { 8613 const button = await altText.render(); 8614 this.#addListenersToElement(button); 8615 this.#buttons.append(button, this.#divider); 8616 this.#altText = altText; 8617 } 8618 addComment(comment, beforeElement = null) { 8619 if (this.#comment) { 8620 return; 8621 } 8622 const button = comment.renderForToolbar(); 8623 if (!button) { 8624 return; 8625 } 8626 this.#addListenersToElement(button); 8627 const divider = this.#commentButtonDivider = this.#divider; 8628 if (!beforeElement) { 8629 this.#buttons.append(button, divider); 8630 } else { 8631 this.#buttons.insertBefore(button, beforeElement); 8632 this.#buttons.insertBefore(divider, beforeElement); 8633 } 8634 this.#comment = comment; 8635 comment.toolbar = this; 8636 } 8637 addColorPicker(colorPicker) { 8638 if (this.#colorPicker) { 8639 return; 8640 } 8641 this.#colorPicker = colorPicker; 8642 const button = colorPicker.renderButton(); 8643 this.#addListenersToElement(button); 8644 this.#buttons.append(button, this.#divider); 8645 } 8646 async addEditSignatureButton(signatureManager) { 8647 const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor); 8648 this.#addListenersToElement(button); 8649 this.#buttons.append(button, this.#divider); 8650 } 8651 removeButton(name) { 8652 switch (name) { 8653 case "comment": 8654 this.#comment?.removeToolbarCommentButton(); 8655 this.#comment = null; 8656 this.#commentButtonDivider?.remove(); 8657 this.#commentButtonDivider = null; 8658 break; 8659 } 8660 } 8661 async addButton(name, tool) { 8662 switch (name) { 8663 case "colorPicker": 8664 if (tool) { 8665 this.addColorPicker(tool); 8666 } 8667 break; 8668 case "altText": 8669 if (tool) { 8670 await this.addAltText(tool); 8671 } 8672 break; 8673 case "editSignature": 8674 if (tool) { 8675 await this.addEditSignatureButton(tool); 8676 } 8677 break; 8678 case "delete": 8679 this.addDeleteButton(); 8680 break; 8681 case "comment": 8682 if (tool) { 8683 this.addComment(tool); 8684 } 8685 break; 8686 } 8687 } 8688 async addButtonBefore(name, tool, beforeSelector) { 8689 if (!tool && name === "comment") { 8690 return; 8691 } 8692 const beforeElement = this.#buttons.querySelector(beforeSelector); 8693 if (!beforeElement) { 8694 return; 8695 } 8696 if (name === "comment") { 8697 this.addComment(tool, beforeElement); 8698 } 8699 } 8700 updateEditSignatureButton(description) { 8701 if (this.#signatureDescriptionButton) { 8702 this.#signatureDescriptionButton.title = description; 8703 } 8704 } 8705 remove() { 8706 this.#toolbar.remove(); 8707 this.#colorPicker?.destroy(); 8708 this.#colorPicker = null; 8709 } 8710} 8711class FloatingToolbar { 8712 #buttons = null; 8713 #toolbar = null; 8714 #uiManager; 8715 constructor(uiManager) { 8716 this.#uiManager = uiManager; 8717 } 8718 #render() { 8719 const editToolbar = this.#toolbar = document.createElement("div"); 8720 editToolbar.className = "editToolbar"; 8721 editToolbar.setAttribute("role", "toolbar"); 8722 const signal = this.#uiManager._signal; 8723 if (signal instanceof AbortSignal && !signal.aborted) { 8724 editToolbar.addEventListener("contextmenu", noContextMenu, { 8725 signal 8726 }); 8727 } 8728 const buttons = this.#buttons = document.createElement("div"); 8729 buttons.className = "buttons"; 8730 editToolbar.append(buttons); 8731 if (this.#uiManager.hasCommentManager()) { 8732 this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => { 8733 this.#uiManager.commentSelection("floating_button"); 8734 }); 8735 } 8736 this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => { 8737 this.#uiManager.highlightSelection("floating_button"); 8738 }); 8739 return editToolbar; 8740 } 8741 #getLastPoint(boxes, isLTR) { 8742 let lastY = 0; 8743 let lastX = 0; 8744 for (const box of boxes) { 8745 const y = box.y + box.height; 8746 if (y < lastY) { 8747 continue; 8748 } 8749 const x = box.x + (isLTR ? box.width : 0); 8750 if (y > lastY) { 8751 lastX = x; 8752 lastY = y; 8753 continue; 8754 } 8755 if (isLTR) { 8756 if (x > lastX) { 8757 lastX = x; 8758 } 8759 } else if (x < lastX) { 8760 lastX = x; 8761 } 8762 } 8763 return [isLTR ? 1 - lastX : lastX, lastY]; 8764 } 8765 show(parent, boxes, isLTR) { 8766 const [x, y] = this.#getLastPoint(boxes, isLTR); 8767 const { 8768 style 8769 } = this.#toolbar ||= this.#render(); 8770 parent.append(this.#toolbar); 8771 style.insetInlineEnd = `${100 * x}%`; 8772 style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`; 8773 } 8774 hide() { 8775 this.#toolbar.remove(); 8776 } 8777 #makeButton(buttonClass, l10nId, labelL10nId, clickHandler) { 8778 const button = document.createElement("button"); 8779 button.classList.add("basic", buttonClass); 8780 button.tabIndex = 0; 8781 button.setAttribute("data-l10n-id", l10nId); 8782 const span = document.createElement("span"); 8783 button.append(span); 8784 span.className = "visuallyHidden"; 8785 span.setAttribute("data-l10n-id", labelL10nId); 8786 const signal = this.#uiManager._signal; 8787 if (signal instanceof AbortSignal && !signal.aborted) { 8788 button.addEventListener("contextmenu", noContextMenu, { 8789 signal 8790 }); 8791 button.addEventListener("click", clickHandler, { 8792 signal 8793 }); 8794 } 8795 this.#buttons.append(button); 8796 } 8797} 8798 8799;// ./src/display/editor/tools.js 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825function bindEvents(obj, element, names) { 8826 for (const name of names) { 8827 element.addEventListener(name, obj[name].bind(obj)); 8828 } 8829} 8830class CurrentPointers { 8831 static #pointerId = NaN; 8832 static #pointerIds = null; 8833 static #moveTimestamp = NaN; 8834 static #pointerType = null; 8835 static initializeAndAddPointerId(pointerId) { 8836 (CurrentPointers.#pointerIds ||= new Set()).add(pointerId); 8837 } 8838 static setPointer(pointerType, pointerId) { 8839 CurrentPointers.#pointerId ||= pointerId; 8840 CurrentPointers.#pointerType ??= pointerType; 8841 } 8842 static setTimeStamp(timeStamp) { 8843 CurrentPointers.#moveTimestamp = timeStamp; 8844 } 8845 static isSamePointerId(pointerId) { 8846 return CurrentPointers.#pointerId === pointerId; 8847 } 8848 static isSamePointerIdOrRemove(pointerId) { 8849 if (CurrentPointers.#pointerId === pointerId) { 8850 return true; 8851 } 8852 CurrentPointers.#pointerIds?.delete(pointerId); 8853 return false; 8854 } 8855 static isSamePointerType(pointerType) { 8856 return CurrentPointers.#pointerType === pointerType; 8857 } 8858 static isInitializedAndDifferentPointerType(pointerType) { 8859 return CurrentPointers.#pointerType !== null && !CurrentPointers.isSamePointerType(pointerType); 8860 } 8861 static isSameTimeStamp(timeStamp) { 8862 return CurrentPointers.#moveTimestamp === timeStamp; 8863 } 8864 static isUsingMultiplePointers() { 8865 return CurrentPointers.#pointerIds?.size >= 1; 8866 } 8867 static clearPointerType() { 8868 CurrentPointers.#pointerType = null; 8869 } 8870 static clearPointerIds() { 8871 CurrentPointers.#pointerId = NaN; 8872 CurrentPointers.#pointerIds = null; 8873 } 8874 static clearTimeStamp() { 8875 CurrentPointers.#moveTimestamp = NaN; 8876 } 8877} 8878class IdManager { 8879 #id = 0; 8880 get id() { 8881 return `${AnnotationEditorPrefix}${this.#id++}`; 8882 } 8883} 8884class ImageManager { 8885 #baseId = getUuid(); 8886 #id = 0; 8887 #cache = null; 8888 static get _isSVGFittingCanvas() { 8889 const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`; 8890 const canvas = new OffscreenCanvas(1, 3); 8891 const ctx = canvas.getContext("2d", { 8892 willReadFrequently: true 8893 }); 8894 const image = new Image(); 8895 image.src = svg; 8896 const promise = image.decode().then(() => { 8897 ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3); 8898 return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0; 8899 }); 8900 return shadow(this, "_isSVGFittingCanvas", promise); 8901 } 8902 async #get(key, rawData) { 8903 this.#cache ||= new Map(); 8904 let data = this.#cache.get(key); 8905 if (data === null) { 8906 return null; 8907 } 8908 if (data?.bitmap) { 8909 data.refCounter += 1; 8910 return data; 8911 } 8912 try { 8913 data ||= { 8914 bitmap: null, 8915 id: `image_${this.#baseId}_${this.#id++}`, 8916 refCounter: 0, 8917 isSvg: false 8918 }; 8919 let image; 8920 if (typeof rawData === "string") { 8921 data.url = rawData; 8922 image = await fetchData(rawData, "blob"); 8923 } else if (rawData instanceof File) { 8924 image = data.file = rawData; 8925 } else if (rawData instanceof Blob) { 8926 image = rawData; 8927 } 8928 if (image.type === "image/svg+xml") { 8929 const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas; 8930 const fileReader = new FileReader(); 8931 const imageElement = new Image(); 8932 const imagePromise = new Promise((resolve, reject) => { 8933 imageElement.onload = () => { 8934 data.bitmap = imageElement; 8935 data.isSvg = true; 8936 resolve(); 8937 }; 8938 fileReader.onload = async () => { 8939 const url = data.svgUrl = fileReader.result; 8940 imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url; 8941 }; 8942 imageElement.onerror = fileReader.onerror = reject; 8943 }); 8944 fileReader.readAsDataURL(image); 8945 await imagePromise; 8946 } else { 8947 data.bitmap = await createImageBitmap(image); 8948 } 8949 data.refCounter = 1; 8950 } catch (e) { 8951 warn(e); 8952 data = null; 8953 } 8954 this.#cache.set(key, data); 8955 if (data) { 8956 this.#cache.set(data.id, data); 8957 } 8958 return data; 8959 } 8960 async getFromFile(file) { 8961 const { 8962 lastModified, 8963 name, 8964 size, 8965 type 8966 } = file; 8967 return this.#get(`${lastModified}_${name}_${size}_${type}`, file); 8968 } 8969 async getFromUrl(url) { 8970 return this.#get(url, url); 8971 } 8972 async getFromBlob(id, blobPromise) { 8973 const blob = await blobPromise; 8974 return this.#get(id, blob); 8975 } 8976 async getFromId(id) { 8977 this.#cache ||= new Map(); 8978 const data = this.#cache.get(id); 8979 if (!data) { 8980 return null; 8981 } 8982 if (data.bitmap) { 8983 data.refCounter += 1; 8984 return data; 8985 } 8986 if (data.file) { 8987 return this.getFromFile(data.file); 8988 } 8989 if (data.blobPromise) { 8990 const { 8991 blobPromise 8992 } = data; 8993 delete data.blobPromise; 8994 return this.getFromBlob(data.id, blobPromise); 8995 } 8996 return this.getFromUrl(data.url); 8997 } 8998 getFromCanvas(id, canvas) { 8999 this.#cache ||= new Map(); 9000 let data = this.#cache.get(id); 9001 if (data?.bitmap) { 9002 data.refCounter += 1; 9003 return data; 9004 } 9005 const offscreen = new OffscreenCanvas(canvas.width, canvas.height); 9006 const ctx = offscreen.getContext("2d"); 9007 ctx.drawImage(canvas, 0, 0); 9008 data = { 9009 bitmap: offscreen.transferToImageBitmap(), 9010 id: `image_${this.#baseId}_${this.#id++}`, 9011 refCounter: 1, 9012 isSvg: false 9013 }; 9014 this.#cache.set(id, data); 9015 this.#cache.set(data.id, data); 9016 return data; 9017 } 9018 getSvgUrl(id) { 9019 const data = this.#cache.get(id); 9020 if (!data?.isSvg) { 9021 return null; 9022 } 9023 return data.svgUrl; 9024 } 9025 deleteId(id) { 9026 this.#cache ||= new Map(); 9027 const data = this.#cache.get(id); 9028 if (!data) { 9029 return; 9030 } 9031 data.refCounter -= 1; 9032 if (data.refCounter !== 0) { 9033 return; 9034 } 9035 const { 9036 bitmap 9037 } = data; 9038 if (!data.url && !data.file) { 9039 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); 9040 const ctx = canvas.getContext("bitmaprenderer"); 9041 ctx.transferFromImageBitmap(bitmap); 9042 data.blobPromise = canvas.convertToBlob(); 9043 } 9044 bitmap.close?.(); 9045 data.bitmap = null; 9046 } 9047 isValidId(id) { 9048 return id.startsWith(`image_${this.#baseId}_`); 9049 } 9050} 9051class CommandManager { 9052 #commands = []; 9053 #locked = false;
vendor: 10,207 bytes, lines 9054-9402
9054 #maxSize; 9055 #position = -1; 9056 constructor(maxSize = 128) { 9057 this.#maxSize = maxSize; 9058 } 9059 add({ 9060 cmd, 9061 undo, 9062 post, 9063 mustExec, 9064 type = NaN, 9065 overwriteIfSameType = false, 9066 keepUndo = false 9067 }) { 9068 if (mustExec) { 9069 cmd(); 9070 } 9071 if (this.#locked) { 9072 return; 9073 } 9074 const save = { 9075 cmd, 9076 undo, 9077 post, 9078 type 9079 }; 9080 if (this.#position === -1) { 9081 if (this.#commands.length > 0) { 9082 this.#commands.length = 0; 9083 } 9084 this.#position = 0; 9085 this.#commands.push(save); 9086 return; 9087 } 9088 if (overwriteIfSameType && this.#commands[this.#position].type === type) { 9089 if (keepUndo) { 9090 save.undo = this.#commands[this.#position].undo; 9091 } 9092 this.#commands[this.#position] = save; 9093 return; 9094 } 9095 const next = this.#position + 1; 9096 if (next === this.#maxSize) { 9097 this.#commands.splice(0, 1); 9098 } else { 9099 this.#position = next; 9100 if (next < this.#commands.length) { 9101 this.#commands.splice(next); 9102 } 9103 } 9104 this.#commands.push(save); 9105 } 9106 undo() { 9107 if (this.#position === -1) { 9108 return; 9109 } 9110 this.#locked = true; 9111 const { 9112 undo, 9113 post 9114 } = this.#commands[this.#position]; 9115 undo(); 9116 post?.(); 9117 this.#locked = false; 9118 this.#position -= 1; 9119 } 9120 redo() { 9121 if (this.#position < this.#commands.length - 1) { 9122 this.#position += 1; 9123 this.#locked = true; 9124 const { 9125 cmd, 9126 post 9127 } = this.#commands[this.#position]; 9128 cmd(); 9129 post?.(); 9130 this.#locked = false; 9131 } 9132 } 9133 hasSomethingToUndo() { 9134 return this.#position !== -1; 9135 } 9136 hasSomethingToRedo() { 9137 return this.#position < this.#commands.length - 1; 9138 } 9139 cleanType(type) { 9140 if (this.#position === -1) { 9141 return; 9142 } 9143 for (let i = this.#position; i >= 0; i--) { 9144 if (this.#commands[i].type !== type) { 9145 this.#commands.splice(i + 1, this.#position - i); 9146 this.#position = i; 9147 return; 9148 } 9149 } 9150 this.#commands.length = 0; 9151 this.#position = -1; 9152 } 9153 destroy() { 9154 this.#commands = null; 9155 } 9156} 9157class KeyboardManager { 9158 constructor(callbacks) { 9159 this.buffer = []; 9160 this.callbacks = new Map(); 9161 this.allKeys = new Set(); 9162 const { 9163 isMac 9164 } = FeatureTest.platform; 9165 for (const [keys, callback, options = {}] of callbacks) { 9166 for (const key of keys) { 9167 const isMacKey = key.startsWith("mac+"); 9168 if (isMac && isMacKey) { 9169 this.callbacks.set(key.slice(4), { 9170 callback, 9171 options 9172 }); 9173 this.allKeys.add(key.split("+").at(-1)); 9174 } else if (!isMac && !isMacKey) { 9175 this.callbacks.set(key, { 9176 callback, 9177 options 9178 }); 9179 this.allKeys.add(key.split("+").at(-1)); 9180 } 9181 } 9182 } 9183 } 9184 #serialize(event) { 9185 if (event.altKey) { 9186 this.buffer.push("alt"); 9187 } 9188 if (event.ctrlKey) { 9189 this.buffer.push("ctrl"); 9190 } 9191 if (event.metaKey) { 9192 this.buffer.push("meta"); 9193 } 9194 if (event.shiftKey) { 9195 this.buffer.push("shift"); 9196 } 9197 this.buffer.push(event.key); 9198 const str = this.buffer.join("+"); 9199 this.buffer.length = 0; 9200 return str; 9201 } 9202 exec(self, event) { 9203 if (!this.allKeys.has(event.key)) { 9204 return; 9205 } 9206 const info = this.callbacks.get(this.#serialize(event)); 9207 if (!info) { 9208 return; 9209 } 9210 const { 9211 callback, 9212 options: { 9213 bubbles = false, 9214 args = [], 9215 checker = null 9216 } 9217 } = info; 9218 if (checker && !checker(self, event)) { 9219 return; 9220 } 9221 callback.bind(self, ...args, event)(); 9222 if (!bubbles) { 9223 stopEvent(event); 9224 } 9225 } 9226} 9227class ColorManager { 9228 static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); 9229 get _colors() { 9230 const colors = new Map([["CanvasText", null], ["Canvas", null]]); 9231 getColorValues(colors); 9232 return shadow(this, "_colors", colors); 9233 } 9234 convert(color) { 9235 const rgb = getRGB(color); 9236 if (!window.matchMedia("(forced-colors: active)").matches) { 9237 return rgb; 9238 } 9239 for (const [name, RGB] of this._colors) { 9240 if (RGB.every((x, i) => x === rgb[i])) { 9241 return ColorManager._colorsMapping.get(name); 9242 } 9243 } 9244 return rgb; 9245 } 9246 getHexCode(name) { 9247 const rgb = this._colors.get(name); 9248 if (!rgb) { 9249 return name; 9250 } 9251 return Util.makeHexColor(...rgb); 9252 } 9253} 9254class AnnotationEditorUIManager { 9255 #abortController = new AbortController(); 9256 #activeEditor = null; 9257 #allEditableAnnotations = null; 9258 #allEditors = new Map(); 9259 #allLayers = new Map(); 9260 #altTextManager = null; 9261 #annotationStorage = null; 9262 #changedExistingAnnotations = null; 9263 #commandManager = new CommandManager(); 9264 #commentManager = null; 9265 #copyPasteAC = null; 9266 #currentDrawingSession = null; 9267 #currentPageIndex = 0; 9268 #deletedAnnotationsElementIds = new Set(); 9269 #draggingEditors = null; 9270 #editorTypes = null; 9271 #editorsToRescale = new Set(); 9272 _editorUndoBar = null; 9273 #enableHighlightFloatingButton = false; 9274 #enableUpdatedAddImage = false; 9275 #enableNewAltTextWhenAddingImage = false; 9276 #filterFactory = null; 9277 #focusMainContainerTimeoutId = null; 9278 #focusManagerAC = null; 9279 #highlightColors = null; 9280 #highlightWhenShiftUp = false; 9281 #floatingToolbar = null; 9282 #idManager = new IdManager(); 9283 #isEnabled = false; 9284 #isPointerDown = false; 9285 #isWaiting = false; 9286 #keyboardManagerAC = null; 9287 #lastActiveElement = null; 9288 #mainHighlightColorPicker = null; 9289 #missingCanvases = null; 9290 #mlManager = null; 9291 #mode = AnnotationEditorType.NONE; 9292 #selectedEditors = new Set(); 9293 #selectedTextNode = null; 9294 #signatureManager = null; 9295 #pageColors = null; 9296 #showAllStates = null; 9297 #pdfDocument = null; 9298 #previousStates = { 9299 isEditing: false, 9300 isEmpty: true, 9301 hasSomethingToUndo: false, 9302 hasSomethingToRedo: false, 9303 hasSelectedEditor: false, 9304 hasSelectedText: false 9305 }; 9306 #translation = [0, 0]; 9307 #translationTimeoutId = null; 9308 #container = null; 9309 #viewer = null; 9310 #viewerAlert = null; 9311 #updateModeCapability = null; 9312 static TRANSLATE_SMALL = 1; 9313 static TRANSLATE_BIG = 10; 9314 static get _keyboardManager() { 9315 const proto = AnnotationEditorUIManager.prototype; 9316 const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl(); 9317 const textInputChecker = (_self, { 9318 target: el 9319 }) => { 9320 if (el instanceof HTMLInputElement) { 9321 const { 9322 type 9323 } = el; 9324 return type !== "text" && type !== "number"; 9325 } 9326 return true; 9327 }; 9328 const small = this.TRANSLATE_SMALL; 9329 const big = this.TRANSLATE_BIG; 9330 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, { 9331 checker: textInputChecker 9332 }], [["ctrl+z", "mac+meta+z"], proto.undo, { 9333 checker: textInputChecker 9334 }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, { 9335 checker: textInputChecker 9336 }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, { 9337 checker: textInputChecker 9338 }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, { 9339 checker: (self, { 9340 target: el 9341 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled 9342 }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, { 9343 checker: (self, { 9344 target: el 9345 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement) 9346 }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { 9347 args: [-small, 0], 9348 checker: arrowChecker 9349 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, { 9350 args: [-big, 0], 9351 checker: arrowChecker 9352 }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, { 9353 args: [small, 0], 9354 checker: arrowChecker 9355 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, { 9356 args: [big, 0], 9357 checker: arrowChecker 9358 }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, { 9359 args: [0, -small], 9360 checker: arrowChecker 9361 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, { 9362 args: [0, -big], 9363 checker: arrowChecker 9364 }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, { 9365 args: [0, small], 9366 checker: arrowChecker 9367 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, { 9368 args: [0, big], 9369 checker: arrowChecker 9370 }]])); 9371 } 9372 constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) { 9373 const signal = this._signal = this.#abortController.signal; 9374 this.#container = container; 9375 this.#viewer = viewer; 9376 this.#viewerAlert = viewerAlert; 9377 this.#altTextManager = altTextManager; 9378 this.#commentManager = commentManager; 9379 this.#signatureManager = signatureManager; 9380 this.#pdfDocument = pdfDocument; 9381 this._eventBus = eventBus; 9382 eventBus._on("editingaction", this.onEditingAction.bind(this), { 9383 signal 9384 }); 9385 eventBus._on("pagechanging", this.onPageChanging.bind(this), { 9386 signal 9387 }); 9388 eventBus._on("scalechanging", this.onScaleChanging.bind(this), { 9389 signal 9390 }); 9391 eventBus._on("rotationchanging", this.onRotationChanging.bind(this), { 9392 signal 9393 }); 9394 eventBus._on("setpreference", this.onSetPreference.bind(this), { 9395 signal 9396 }); 9397 eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), { 9398 signal 9399 }); 9400 window.addEventListener("pointerdown", () => { 9401 this.#isPointerDown = true; 9402 }, {
vendor: 10,372 bytes, lines 9403-9767
9403 capture: true, 9404 signal 9405 }); 9406 window.addEventListener("pointerup", () => { 9407 this.#isPointerDown = false; 9408 }, { 9409 capture: true, 9410 signal 9411 }); 9412 window.addEventListener("beforeunload", this.#beforeUnload.bind(this), { 9413 capture: true, 9414 signal 9415 }); 9416 this.#addSelectionListener(); 9417 this.#addDragAndDropListeners(); 9418 this.#addKeyboardManager(); 9419 this.#annotationStorage = pdfDocument.annotationStorage; 9420 this.#filterFactory = pdfDocument.filterFactory; 9421 this.#pageColors = pageColors; 9422 this.#highlightColors = highlightColors || null; 9423 this.#enableHighlightFloatingButton = enableHighlightFloatingButton; 9424 this.#enableUpdatedAddImage = enableUpdatedAddImage; 9425 this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage; 9426 this.#mlManager = mlManager || null; 9427 this.viewParameters = { 9428 realScale: PixelsPerInch.PDF_TO_CSS_UNITS, 9429 rotation: 0 9430 }; 9431 this.isShiftKeyDown = false; 9432 this._editorUndoBar = editorUndoBar || null; 9433 this._supportsPinchToZoom = supportsPinchToZoom !== false; 9434 commentManager?.setSidebarUiManager(this); 9435 } 9436 destroy() { 9437 this.#updateModeCapability?.resolve(); 9438 this.#updateModeCapability = null; 9439 this.#abortController?.abort(); 9440 this.#abortController = null; 9441 this._signal = null; 9442 for (const layer of this.#allLayers.values()) { 9443 layer.destroy(); 9444 } 9445 this.#allLayers.clear(); 9446 this.#allEditors.clear(); 9447 this.#editorsToRescale.clear(); 9448 this.#missingCanvases?.clear(); 9449 this.#activeEditor = null; 9450 this.#selectedEditors.clear(); 9451 this.#commandManager.destroy(); 9452 this.#altTextManager?.destroy(); 9453 this.#commentManager?.destroy(); 9454 this.#signatureManager?.destroy(); 9455 this.#floatingToolbar?.hide(); 9456 this.#floatingToolbar = null; 9457 this.#mainHighlightColorPicker?.destroy(); 9458 this.#mainHighlightColorPicker = null; 9459 this.#allEditableAnnotations = null; 9460 if (this.#focusMainContainerTimeoutId) { 9461 clearTimeout(this.#focusMainContainerTimeoutId); 9462 this.#focusMainContainerTimeoutId = null; 9463 } 9464 if (this.#translationTimeoutId) { 9465 clearTimeout(this.#translationTimeoutId); 9466 this.#translationTimeoutId = null; 9467 } 9468 this._editorUndoBar?.destroy(); 9469 this.#pdfDocument = null; 9470 } 9471 combinedSignal(ac) { 9472 return AbortSignal.any([this._signal, ac.signal]); 9473 } 9474 get mlManager() { 9475 return this.#mlManager; 9476 } 9477 get useNewAltTextFlow() { 9478 return this.#enableUpdatedAddImage; 9479 } 9480 get useNewAltTextWhenAddingImage() { 9481 return this.#enableNewAltTextWhenAddingImage; 9482 } 9483 get hcmFilter() { 9484 return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); 9485 } 9486 get direction() { 9487 return shadow(this, "direction", getComputedStyle(this.#container).direction); 9488 } 9489 get _highlightColors() { 9490 return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => { 9491 pair = pair.split("=").map(x => x.trim()); 9492 pair[1] = pair[1].toUpperCase(); 9493 return pair; 9494 })) : null); 9495 } 9496 get highlightColors() { 9497 const { 9498 _highlightColors 9499 } = this; 9500 if (!_highlightColors) { 9501 return shadow(this, "highlightColors", null); 9502 } 9503 const map = new Map(); 9504 const hasHCM = !!this.#pageColors; 9505 for (const [name, color] of _highlightColors) { 9506 const isNameForHCM = name.endsWith("_HCM"); 9507 if (hasHCM && isNameForHCM) { 9508 map.set(name.replace("_HCM", ""), color); 9509 continue; 9510 } 9511 if (!hasHCM && !isNameForHCM) { 9512 map.set(name, color); 9513 } 9514 } 9515 return shadow(this, "highlightColors", map); 9516 } 9517 get highlightColorNames() { 9518 return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null); 9519 } 9520 getNonHCMColor(color) { 9521 if (!this._highlightColors) { 9522 return color; 9523 } 9524 const colorName = this.highlightColorNames.get(color); 9525 return this._highlightColors.get(colorName) || color; 9526 } 9527 getNonHCMColorName(color) { 9528 return this.highlightColorNames.get(color) || color; 9529 } 9530 setCurrentDrawingSession(layer) { 9531 if (layer) { 9532 this.unselectAll(); 9533 this.disableUserSelect(true); 9534 } else { 9535 this.disableUserSelect(false); 9536 } 9537 this.#currentDrawingSession = layer; 9538 } 9539 setMainHighlightColorPicker(colorPicker) { 9540 this.#mainHighlightColorPicker = colorPicker; 9541 } 9542 editAltText(editor, firstTime = false) { 9543 this.#altTextManager?.editAltText(this, editor, firstTime); 9544 } 9545 hasCommentManager() { 9546 return !!this.#commentManager; 9547 } 9548 editComment(editor, posX, posY, options) { 9549 this.#commentManager?.showDialog(this, editor, posX, posY, options); 9550 } 9551 selectComment(pageIndex, uid) { 9552 const layer = this.#allLayers.get(pageIndex); 9553 const editor = layer?.getEditorByUID(uid); 9554 editor?.toggleComment(true, true); 9555 } 9556 updateComment(editor) { 9557 this.#commentManager?.updateComment(editor.getData()); 9558 } 9559 updatePopupColor(editor) { 9560 this.#commentManager?.updatePopupColor(editor); 9561 } 9562 removeComment(editor) { 9563 this.#commentManager?.removeComments([editor.uid]); 9564 } 9565 deleteComment(editor, savedData) { 9566 const undo = () => { 9567 editor.comment = savedData; 9568 }; 9569 const cmd = () => { 9570 this._editorUndoBar?.show(undo, "comment"); 9571 this.toggleComment(null); 9572 editor.comment = null; 9573 }; 9574 this.addCommands({ 9575 cmd, 9576 undo, 9577 mustExec: true 9578 }); 9579 } 9580 toggleComment(editor, isSelected, visibility = undefined) { 9581 this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility); 9582 } 9583 makeCommentColor(color, opacity) { 9584 return color && this.#commentManager?.makeCommentColor(color, opacity) || null; 9585 } 9586 getCommentDialogElement() { 9587 return this.#commentManager?.dialogElement || null; 9588 } 9589 async waitForEditorsRendered(pageNumber) { 9590 if (this.#allLayers.has(pageNumber - 1)) { 9591 return; 9592 } 9593 const { 9594 resolve, 9595 promise 9596 } = Promise.withResolvers(); 9597 const onEditorsRendered = evt => { 9598 if (evt.pageNumber === pageNumber) { 9599 this._eventBus._off("editorsrendered", onEditorsRendered); 9600 resolve(); 9601 } 9602 }; 9603 this._eventBus.on("editorsrendered", onEditorsRendered); 9604 await promise; 9605 } 9606 getSignature(editor) { 9607 this.#signatureManager?.getSignature({ 9608 uiManager: this, 9609 editor 9610 }); 9611 } 9612 get signatureManager() { 9613 return this.#signatureManager; 9614 } 9615 switchToMode(mode, callback) { 9616 this._eventBus.on("annotationeditormodechanged", callback, { 9617 once: true, 9618 signal: this._signal 9619 }); 9620 this._eventBus.dispatch("showannotationeditorui", { 9621 source: this, 9622 mode 9623 }); 9624 } 9625 setPreference(name, value) { 9626 this._eventBus.dispatch("setpreference", { 9627 source: this, 9628 name, 9629 value 9630 }); 9631 } 9632 onSetPreference({ 9633 name, 9634 value 9635 }) { 9636 switch (name) { 9637 case "enableNewAltTextWhenAddingImage": 9638 this.#enableNewAltTextWhenAddingImage = value; 9639 break; 9640 } 9641 } 9642 onPageChanging({ 9643 pageNumber 9644 }) { 9645 this.#currentPageIndex = pageNumber - 1; 9646 } 9647 deletePage(id) { 9648 for (const editor of this.getEditors(id)) { 9649 editor.remove(); 9650 } 9651 this.#allLayers.delete(id); 9652 if (this.#currentPageIndex === id) { 9653 this.#currentPageIndex = 0; 9654 } 9655 } 9656 focusMainContainer() { 9657 this.#container.focus(); 9658 } 9659 findParent(x, y) { 9660 for (const layer of this.#allLayers.values()) { 9661 const { 9662 x: layerX, 9663 y: layerY, 9664 width, 9665 height 9666 } = layer.div.getBoundingClientRect(); 9667 if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) { 9668 return layer; 9669 } 9670 } 9671 return null; 9672 } 9673 disableUserSelect(value = false) { 9674 this.#viewer.classList.toggle("noUserSelect", value); 9675 } 9676 addShouldRescale(editor) { 9677 this.#editorsToRescale.add(editor); 9678 } 9679 removeShouldRescale(editor) { 9680 this.#editorsToRescale.delete(editor); 9681 } 9682 onScaleChanging({ 9683 scale 9684 }) { 9685 this.commitOrRemove(); 9686 this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; 9687 for (const editor of this.#editorsToRescale) { 9688 editor.onScaleChanging(); 9689 } 9690 this.#currentDrawingSession?.onScaleChanging(); 9691 } 9692 onRotationChanging({ 9693 pagesRotation 9694 }) { 9695 this.commitOrRemove(); 9696 this.viewParameters.rotation = pagesRotation; 9697 } 9698 #getAnchorElementForSelection({ 9699 anchorNode 9700 }) { 9701 return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode; 9702 } 9703 #getLayerForTextLayer(textLayer) { 9704 const { 9705 currentLayer 9706 } = this; 9707 if (currentLayer.hasTextLayer(textLayer)) { 9708 return currentLayer; 9709 } 9710 for (const layer of this.#allLayers.values()) { 9711 if (layer.hasTextLayer(textLayer)) { 9712 return layer; 9713 } 9714 } 9715 return null; 9716 } 9717 highlightSelection(methodOfCreation = "", comment = false) { 9718 const selection = document.getSelection(); 9719 if (!selection || selection.isCollapsed) { 9720 return; 9721 } 9722 const { 9723 anchorNode, 9724 anchorOffset, 9725 focusNode, 9726 focusOffset 9727 } = selection; 9728 const text = selection.toString(); 9729 const anchorElement = this.#getAnchorElementForSelection(selection); 9730 const textLayer = anchorElement.closest(".textLayer"); 9731 const boxes = this.getSelectionBoxes(textLayer); 9732 if (!boxes) { 9733 return; 9734 } 9735 selection.empty(); 9736 const layer = this.#getLayerForTextLayer(textLayer); 9737 const isNoneMode = this.#mode === AnnotationEditorType.NONE; 9738 const callback = () => { 9739 const editor = layer?.createAndAddNewEditor({ 9740 x: 0, 9741 y: 0 9742 }, false, { 9743 methodOfCreation, 9744 boxes, 9745 anchorNode, 9746 anchorOffset, 9747 focusNode, 9748 focusOffset, 9749 text 9750 }); 9751 if (isNoneMode) { 9752 this.showAllEditors("highlight", true, true); 9753 } 9754 if (comment) { 9755 editor?.editComment(); 9756 } 9757 }; 9758 if (isNoneMode) { 9759 this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback); 9760 return; 9761 } 9762 callback(); 9763 } 9764 commentSelection(methodOfCreation = "") { 9765 this.highlightSelection(methodOfCreation, true); 9766 } 9767 #beforeUnload(e
vendor: 10,279 bytes, lines 9767-10138
9767) { 9768 this.commitOrRemove(); 9769 this.currentLayer?.endDrawingSession(false); 9770 } 9771 #displayFloatingToolbar() { 9772 const selection = document.getSelection(); 9773 if (!selection || selection.isCollapsed) { 9774 return; 9775 } 9776 const anchorElement = this.#getAnchorElementForSelection(selection); 9777 const textLayer = anchorElement.closest(".textLayer"); 9778 const boxes = this.getSelectionBoxes(textLayer); 9779 if (!boxes) { 9780 return; 9781 } 9782 this.#floatingToolbar ||= new FloatingToolbar(this); 9783 this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr"); 9784 } 9785 getAndRemoveDataFromAnnotationStorage(annotationId) { 9786 if (!this.#annotationStorage) { 9787 return null; 9788 } 9789 const key = `${AnnotationEditorPrefix}${annotationId}`; 9790 const storedValue = this.#annotationStorage.getRawValue(key); 9791 if (storedValue) { 9792 this.#annotationStorage.remove(key); 9793 } 9794 return storedValue; 9795 } 9796 addToAnnotationStorage(editor) { 9797 if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) { 9798 this.#annotationStorage.setValue(editor.id, editor); 9799 } 9800 } 9801 a11yAlert(messageId, args = null) { 9802 const viewerAlert = this.#viewerAlert; 9803 if (!viewerAlert) { 9804 return; 9805 } 9806 viewerAlert.setAttribute("data-l10n-id", messageId); 9807 if (args) { 9808 viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args)); 9809 } else { 9810 viewerAlert.removeAttribute("data-l10n-args"); 9811 } 9812 } 9813 #selectionChange() { 9814 const selection = document.getSelection(); 9815 if (!selection || selection.isCollapsed) { 9816 if (this.#selectedTextNode) { 9817 this.#floatingToolbar?.hide(); 9818 this.#selectedTextNode = null; 9819 this.#dispatchUpdateStates({ 9820 hasSelectedText: false 9821 }); 9822 } 9823 return; 9824 } 9825 const { 9826 anchorNode 9827 } = selection; 9828 if (anchorNode === this.#selectedTextNode) { 9829 return; 9830 } 9831 const anchorElement = this.#getAnchorElementForSelection(selection); 9832 const textLayer = anchorElement.closest(".textLayer"); 9833 if (!textLayer) { 9834 if (this.#selectedTextNode) { 9835 this.#floatingToolbar?.hide(); 9836 this.#selectedTextNode = null; 9837 this.#dispatchUpdateStates({ 9838 hasSelectedText: false 9839 }); 9840 } 9841 return; 9842 } 9843 this.#floatingToolbar?.hide(); 9844 this.#selectedTextNode = anchorNode; 9845 this.#dispatchUpdateStates({ 9846 hasSelectedText: true 9847 }); 9848 if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) { 9849 return; 9850 } 9851 if (this.#mode === AnnotationEditorType.HIGHLIGHT) { 9852 this.showAllEditors("highlight", true, true); 9853 } 9854 this.#highlightWhenShiftUp = this.isShiftKeyDown; 9855 if (!this.isShiftKeyDown) { 9856 const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null; 9857 activeLayer?.toggleDrawing(); 9858 if (this.#isPointerDown) { 9859 const ac = new AbortController(); 9860 const signal = this.combinedSignal(ac); 9861 const pointerup = e => { 9862 if (e.type === "pointerup" && e.button !== 0) { 9863 return; 9864 } 9865 ac.abort(); 9866 activeLayer?.toggleDrawing(true); 9867 if (e.type === "pointerup") { 9868 this.#onSelectEnd("main_toolbar"); 9869 } 9870 }; 9871 window.addEventListener("pointerup", pointerup, { 9872 signal 9873 }); 9874 window.addEventListener("blur", pointerup, { 9875 signal 9876 }); 9877 } else { 9878 activeLayer?.toggleDrawing(true); 9879 this.#onSelectEnd("main_toolbar"); 9880 } 9881 } 9882 } 9883 #onSelectEnd(methodOfCreation = "") { 9884 if (this.#mode === AnnotationEditorType.HIGHLIGHT) { 9885 this.highlightSelection(methodOfCreation); 9886 } else if (this.#enableHighlightFloatingButton) { 9887 this.#displayFloatingToolbar(); 9888 } 9889 } 9890 #addSelectionListener() { 9891 document.addEventListener("selectionchange", this.#selectionChange.bind(this), { 9892 signal: this._signal 9893 }); 9894 } 9895 #addFocusManager() { 9896 if (this.#focusManagerAC) { 9897 return; 9898 } 9899 this.#focusManagerAC = new AbortController(); 9900 const signal = this.combinedSignal(this.#focusManagerAC); 9901 window.addEventListener("focus", this.focus.bind(this), { 9902 signal 9903 }); 9904 window.addEventListener("blur", this.blur.bind(this), { 9905 signal 9906 }); 9907 } 9908 #removeFocusManager() { 9909 this.#focusManagerAC?.abort(); 9910 this.#focusManagerAC = null; 9911 } 9912 blur() { 9913 this.isShiftKeyDown = false; 9914 if (this.#highlightWhenShiftUp) { 9915 this.#highlightWhenShiftUp = false; 9916 this.#onSelectEnd("main_toolbar"); 9917 } 9918 if (!this.hasSelection) { 9919 return; 9920 } 9921 const { 9922 activeElement 9923 } = document; 9924 for (const editor of this.#selectedEditors) { 9925 if (editor.div.contains(activeElement)) { 9926 this.#lastActiveElement = [editor, activeElement]; 9927 editor._focusEventsAllowed = false; 9928 break; 9929 } 9930 } 9931 } 9932 focus() { 9933 if (!this.#lastActiveElement) { 9934 return; 9935 } 9936 const [lastEditor, lastActiveElement] = this.#lastActiveElement; 9937 this.#lastActiveElement = null; 9938 lastActiveElement.addEventListener("focusin", () => { 9939 lastEditor._focusEventsAllowed = true; 9940 }, { 9941 once: true, 9942 signal: this._signal 9943 }); 9944 lastActiveElement.focus(); 9945 } 9946 #addKeyboardManager() { 9947 if (this.#keyboardManagerAC) { 9948 return; 9949 } 9950 this.#keyboardManagerAC = new AbortController(); 9951 const signal = this.combinedSignal(this.#keyboardManagerAC); 9952 window.addEventListener("keydown", this.keydown.bind(this), { 9953 signal 9954 }); 9955 window.addEventListener("keyup", this.keyup.bind(this), { 9956 signal 9957 }); 9958 } 9959 #removeKeyboardManager() { 9960 this.#keyboardManagerAC?.abort(); 9961 this.#keyboardManagerAC = null; 9962 } 9963 #addCopyPasteListeners() { 9964 if (this.#copyPasteAC) { 9965 return; 9966 } 9967 this.#copyPasteAC = new AbortController(); 9968 const signal = this.combinedSignal(this.#copyPasteAC); 9969 document.addEventListener("copy", this.copy.bind(this), { 9970 signal 9971 }); 9972 document.addEventListener("cut", this.cut.bind(this), { 9973 signal 9974 }); 9975 document.addEventListener("paste", this.paste.bind(this), { 9976 signal 9977 }); 9978 } 9979 #removeCopyPasteListeners() { 9980 this.#copyPasteAC?.abort(); 9981 this.#copyPasteAC = null; 9982 } 9983 #addDragAndDropListeners() { 9984 const signal = this._signal; 9985 document.addEventListener("dragover", this.dragOver.bind(this), { 9986 signal 9987 }); 9988 document.addEventListener("drop", this.drop.bind(this), { 9989 signal 9990 }); 9991 } 9992 addEditListeners() { 9993 this.#addKeyboardManager(); 9994 this.setEditingState(true); 9995 } 9996 removeEditListeners() { 9997 this.#removeKeyboardManager(); 9998 this.setEditingState(false); 9999 } 10000 dragOver(event) { 10001 for (const { 10002 type 10003 } of event.dataTransfer.items) { 10004 for (const editorType of this.#editorTypes) { 10005 if (editorType.isHandlingMimeForPasting(type)) { 10006 event.dataTransfer.dropEffect = "copy"; 10007 event.preventDefault(); 10008 return; 10009 } 10010 } 10011 } 10012 } 10013 drop(event) { 10014 for (const item of event.dataTransfer.items) { 10015 for (const editorType of this.#editorTypes) { 10016 if (editorType.isHandlingMimeForPasting(item.type)) { 10017 editorType.paste(item, this.currentLayer); 10018 event.preventDefault(); 10019 return; 10020 } 10021 } 10022 } 10023 } 10024 copy(event) { 10025 event.preventDefault(); 10026 this.#activeEditor?.commitOrRemove(); 10027 if (!this.hasSelection) { 10028 return; 10029 } 10030 const editors = []; 10031 for (const editor of this.#selectedEditors) { 10032 const serialized = editor.serialize(true); 10033 if (serialized) { 10034 editors.push(serialized); 10035 } 10036 } 10037 if (editors.length === 0) { 10038 return; 10039 } 10040 event.clipboardData.setData("application/pdfjs", JSON.stringify(editors)); 10041 } 10042 cut(event) { 10043 this.copy(event); 10044 this.delete(); 10045 } 10046 async paste(event) { 10047 event.preventDefault(); 10048 const { 10049 clipboardData 10050 } = event; 10051 for (const item of clipboardData.items) { 10052 for (const editorType of this.#editorTypes) { 10053 if (editorType.isHandlingMimeForPasting(item.type)) { 10054 editorType.paste(item, this.currentLayer); 10055 return; 10056 } 10057 } 10058 } 10059 let data = clipboardData.getData("application/pdfjs"); 10060 if (!data) { 10061 return; 10062 } 10063 try { 10064 data = JSON.parse(data); 10065 } catch (ex) { 10066 warn(`paste: "${ex.message}".`); 10067 return; 10068 } 10069 if (!Array.isArray(data)) { 10070 return; 10071 } 10072 this.unselectAll(); 10073 const layer = this.currentLayer; 10074 try { 10075 const newEditors = []; 10076 for (const editor of data) { 10077 const deserializedEditor = await layer.deserialize(editor); 10078 if (!deserializedEditor) { 10079 return; 10080 } 10081 newEditors.push(deserializedEditor); 10082 } 10083 const cmd = () => { 10084 for (const editor of newEditors) { 10085 this.#addEditorToLayer(editor); 10086 } 10087 this.#selectEditors(newEditors); 10088 }; 10089 const undo = () => { 10090 for (const editor of newEditors) { 10091 editor.remove(); 10092 } 10093 }; 10094 this.addCommands({ 10095 cmd, 10096 undo, 10097 mustExec: true 10098 }); 10099 } catch (ex) { 10100 warn(`paste: "${ex.message}".`); 10101 } 10102 } 10103 keydown(event) { 10104 if (!this.isShiftKeyDown && event.key === "Shift") { 10105 this.isShiftKeyDown = true; 10106 } 10107 if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { 10108 AnnotationEditorUIManager._keyboardManager.exec(this, event); 10109 } 10110 } 10111 keyup(event) { 10112 if (this.isShiftKeyDown && event.key === "Shift") { 10113 this.isShiftKeyDown = false; 10114 if (this.#highlightWhenShiftUp) { 10115 this.#highlightWhenShiftUp = false; 10116 this.#onSelectEnd("main_toolbar"); 10117 } 10118 } 10119 } 10120 onEditingAction({ 10121 name 10122 }) { 10123 switch (name) { 10124 case "undo": 10125 case "redo": 10126 case "delete": 10127 case "selectAll": 10128 this[name](); 10129 break; 10130 case "highlightSelection": 10131 this.highlightSelection("context_menu"); 10132 break; 10133 case "commentSelection": 10134 this.commentSelection("context_menu"); 10135 break; 10136 } 10137 } 10138
vendor: 7,533 bytes, lines 10138-10391
10138#dispatchUpdateStates(details) { 10139 const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value); 10140 if (hasChanged) { 10141 this._eventBus.dispatch("annotationeditorstateschanged", { 10142 source: this, 10143 details: Object.assign(this.#previousStates, details) 10144 }); 10145 if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { 10146 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); 10147 } 10148 } 10149 } 10150 #dispatchUpdateUI(details) { 10151 this._eventBus.dispatch("annotationeditorparamschanged", { 10152 source: this, 10153 details 10154 }); 10155 } 10156 setEditingState(isEditing) { 10157 if (isEditing) { 10158 this.#addFocusManager(); 10159 this.#addCopyPasteListeners(); 10160 this.#dispatchUpdateStates({ 10161 isEditing: this.#mode !== AnnotationEditorType.NONE, 10162 isEmpty: this.#isEmpty(), 10163 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), 10164 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), 10165 hasSelectedEditor: false 10166 }); 10167 } else { 10168 this.#removeFocusManager(); 10169 this.#removeCopyPasteListeners(); 10170 this.#dispatchUpdateStates({ 10171 isEditing: false 10172 }); 10173 this.disableUserSelect(false); 10174 } 10175 } 10176 registerEditorTypes(types) { 10177 if (this.#editorTypes) { 10178 return; 10179 } 10180 this.#editorTypes = types; 10181 for (const editorType of this.#editorTypes) { 10182 this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); 10183 } 10184 } 10185 getId() { 10186 return this.#idManager.id; 10187 } 10188 get currentLayer() { 10189 return this.#allLayers.get(this.#currentPageIndex); 10190 } 10191 getLayer(pageIndex) { 10192 return this.#allLayers.get(pageIndex); 10193 } 10194 get currentPageIndex() { 10195 return this.#currentPageIndex; 10196 } 10197 addLayer(layer) { 10198 this.#allLayers.set(layer.pageIndex, layer); 10199 if (this.#isEnabled) { 10200 layer.enable(); 10201 } else { 10202 layer.disable(); 10203 } 10204 } 10205 removeLayer(layer) { 10206 this.#allLayers.delete(layer.pageIndex); 10207 } 10208 async updateMode(mode, editId = null, isFromUser = false, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) { 10209 if (this.#mode === mode) { 10210 return; 10211 } 10212 if (this.#updateModeCapability) { 10213 await this.#updateModeCapability.promise; 10214 if (!this.#updateModeCapability) { 10215 return; 10216 } 10217 } 10218 this.#updateModeCapability = Promise.withResolvers(); 10219 this.#currentDrawingSession?.commitOrRemove(); 10220 if (this.#mode === AnnotationEditorType.POPUP) { 10221 this.#commentManager?.hideSidebar(); 10222 } 10223 this.#commentManager?.destroyPopup(); 10224 this.#mode = mode; 10225 if (mode === AnnotationEditorType.NONE) { 10226 this.setEditingState(false); 10227 this.#disableAll(); 10228 for (const editor of this.#allEditors.values()) { 10229 editor.hideStandaloneCommentButton(); 10230 } 10231 this._editorUndoBar?.hide(); 10232 this.toggleComment(null); 10233 this.#updateModeCapability.resolve(); 10234 return; 10235 } 10236 for (const editor of this.#allEditors.values()) { 10237 editor.addStandaloneCommentButton(); 10238 } 10239 if (mode === AnnotationEditorType.SIGNATURE) { 10240 await this.#signatureManager?.loadSignatures(); 10241 } 10242 if (isFromUser) { 10243 CurrentPointers.clearPointerType(); 10244 } 10245 this.setEditingState(true); 10246 await this.#enableAll(); 10247 this.unselectAll(); 10248 for (const layer of this.#allLayers.values()) { 10249 layer.updateMode(mode); 10250 } 10251 if (mode === AnnotationEditorType.POPUP) { 10252 this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map(editorClass => editorClass._editorType))); 10253 const elementIds = new Set(); 10254 const allComments = []; 10255 for (const editor of this.#allEditors.values()) { 10256 const { 10257 annotationElementId, 10258 hasComment, 10259 deleted 10260 } = editor; 10261 if (annotationElementId) { 10262 elementIds.add(annotationElementId); 10263 } 10264 if (hasComment && !deleted) { 10265 allComments.push(editor.getData()); 10266 } 10267 } 10268 for (const annotation of this.#allEditableAnnotations) { 10269 const { 10270 id, 10271 popupRef, 10272 contentsObj 10273 } = annotation; 10274 if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) { 10275 allComments.push(annotation); 10276 } 10277 } 10278 this.#commentManager?.showSidebar(allComments); 10279 } 10280 if (!editId) { 10281 if (isFromKeyboard) { 10282 this.addNewEditorFromKeyboard(); 10283 } 10284 this.#updateModeCapability.resolve(); 10285 return; 10286 } 10287 for (const editor of this.#allEditors.values()) { 10288 if (editor.uid === editId) { 10289 this.setSelected(editor); 10290 if (editComment) { 10291 editor.editComment(); 10292 } else if (mustEnterInEditMode) { 10293 editor.enterInEditMode(); 10294 } else { 10295 editor.focus(); 10296 } 10297 } else { 10298 editor.unselect(); 10299 } 10300 } 10301 this.#updateModeCapability.resolve(); 10302 } 10303 addNewEditorFromKeyboard() { 10304 if (this.currentLayer.canCreateNewEmptyEditor()) { 10305 this.currentLayer.addNewEditor(); 10306 } 10307 } 10308 updateToolbar(options) { 10309 if (options.mode === this.#mode) { 10310 return; 10311 } 10312 this._eventBus.dispatch("switchannotationeditormode", { 10313 source: this, 10314 ...options 10315 }); 10316 } 10317 updateParams(type, value) { 10318 if (!this.#editorTypes) { 10319 return; 10320 } 10321 switch (type) { 10322 case AnnotationEditorParamsType.CREATE: 10323 this.currentLayer.addNewEditor(value); 10324 return; 10325 case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: 10326 this._eventBus.dispatch("reporttelemetry", { 10327 source: this, 10328 details: { 10329 type: "editing", 10330 data: { 10331 type: "highlight", 10332 action: "toggle_visibility" 10333 } 10334 } 10335 }); 10336 (this.#showAllStates ||= new Map()).set(type, value); 10337 this.showAllEditors("highlight", value); 10338 break; 10339 } 10340 if (this.hasSelection) { 10341 for (const editor of this.#selectedEditors) { 10342 editor.updateParams(type, value); 10343 } 10344 } else { 10345 for (const editorType of this.#editorTypes) { 10346 editorType.updateDefaultParams(type, value); 10347 } 10348 } 10349 } 10350 showAllEditors(type, visible, updateButton = false) { 10351 for (const editor of this.#allEditors.values()) { 10352 if (editor.editorType === type) { 10353 editor.show(visible); 10354 } 10355 } 10356 const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true; 10357 if (state !== visible) { 10358 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]); 10359 } 10360 } 10361 enableWaiting(mustWait = false) { 10362 if (this.#isWaiting === mustWait) { 10363 return; 10364 } 10365 this.#isWaiting = mustWait; 10366 for (const layer of this.#allLayers.values()) { 10367 if (mustWait) { 10368 layer.disableClick(); 10369 } else { 10370 layer.enableClick(); 10371 } 10372 layer.div.classList.toggle("waiting", mustWait); 10373 } 10374 } 10375 async #enableAll() { 10376 if (!this.#isEnabled) { 10377 this.#isEnabled = true; 10378 const promises = []; 10379 for (const layer of this.#allLayers.values()) { 10380 promises.push(layer.enable()); 10381 } 10382 await Promise.all(promises); 10383 for (const editor of this.#allEditors.values()) { 10384 editor.enable(); 10385 } 10386 } 10387 } 10388 #disableAll() { 10389 this.unselectAll(); 10390 if (this.#isEnabled) { 10391 this.#isEnabled = false;
vendor: 4,951 bytes, lines 10392-10567
10392 for (const layer of this.#allLayers.values()) { 10393 layer.disable(); 10394 } 10395 for (const editor of this.#allEditors.values()) { 10396 editor.disable(); 10397 } 10398 } 10399 } 10400 *getEditors(pageIndex) { 10401 for (const editor of this.#allEditors.values()) { 10402 if (editor.pageIndex === pageIndex) { 10403 yield editor; 10404 } 10405 } 10406 } 10407 getEditor(id) { 10408 return this.#allEditors.get(id); 10409 } 10410 addEditor(editor) { 10411 this.#allEditors.set(editor.id, editor); 10412 } 10413 removeEditor(editor) { 10414 if (editor.div.contains(document.activeElement)) { 10415 if (this.#focusMainContainerTimeoutId) { 10416 clearTimeout(this.#focusMainContainerTimeoutId); 10417 } 10418 this.#focusMainContainerTimeoutId = setTimeout(() => { 10419 this.focusMainContainer(); 10420 this.#focusMainContainerTimeoutId = null; 10421 }, 0); 10422 } 10423 this.#allEditors.delete(editor.id); 10424 if (editor.annotationElementId) { 10425 this.#missingCanvases?.delete(editor.annotationElementId); 10426 } 10427 this.unselect(editor); 10428 if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) { 10429 this.#annotationStorage?.remove(editor.id); 10430 } 10431 } 10432 addDeletedAnnotationElement(editor) { 10433 this.#deletedAnnotationsElementIds.add(editor.annotationElementId); 10434 this.addChangedExistingAnnotation(editor); 10435 editor.deleted = true; 10436 } 10437 isDeletedAnnotationElement(annotationElementId) { 10438 return this.#deletedAnnotationsElementIds.has(annotationElementId); 10439 } 10440 removeDeletedAnnotationElement(editor) { 10441 this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); 10442 this.removeChangedExistingAnnotation(editor); 10443 editor.deleted = false; 10444 } 10445 #addEditorToLayer(editor) { 10446 const layer = this.#allLayers.get(editor.pageIndex); 10447 if (layer) { 10448 layer.addOrRebuild(editor); 10449 } else { 10450 this.addEditor(editor); 10451 this.addToAnnotationStorage(editor); 10452 } 10453 } 10454 setActiveEditor(editor) { 10455 if (this.#activeEditor === editor) { 10456 return; 10457 } 10458 this.#activeEditor = editor; 10459 if (editor) { 10460 this.#dispatchUpdateUI(editor.propertiesToUpdate); 10461 } 10462 } 10463 get #lastSelectedEditor() { 10464 let ed = null; 10465 for (ed of this.#selectedEditors) {} 10466 return ed; 10467 } 10468 updateUI(editor) { 10469 if (this.#lastSelectedEditor === editor) { 10470 this.#dispatchUpdateUI(editor.propertiesToUpdate); 10471 } 10472 } 10473 updateUIForDefaultProperties(editorType) { 10474 this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); 10475 } 10476 toggleSelected(editor) { 10477 if (this.#selectedEditors.has(editor)) { 10478 this.#selectedEditors.delete(editor); 10479 editor.unselect(); 10480 this.#dispatchUpdateStates({ 10481 hasSelectedEditor: this.hasSelection 10482 }); 10483 return; 10484 } 10485 this.#selectedEditors.add(editor); 10486 editor.select(); 10487 this.#dispatchUpdateUI(editor.propertiesToUpdate); 10488 this.#dispatchUpdateStates({ 10489 hasSelectedEditor: true 10490 }); 10491 } 10492 setSelected(editor) { 10493 this.updateToolbar({ 10494 mode: editor.mode, 10495 editId: editor.uid 10496 }); 10497 this.#currentDrawingSession?.commitOrRemove(); 10498 for (const ed of this.#selectedEditors) { 10499 if (ed !== editor) { 10500 ed.unselect(); 10501 } 10502 } 10503 this.#selectedEditors.clear(); 10504 this.#selectedEditors.add(editor); 10505 editor.select(); 10506 this.#dispatchUpdateUI(editor.propertiesToUpdate); 10507 this.#dispatchUpdateStates({ 10508 hasSelectedEditor: true 10509 }); 10510 } 10511 isSelected(editor) { 10512 return this.#selectedEditors.has(editor); 10513 } 10514 get firstSelectedEditor() { 10515 return this.#selectedEditors.values().next().value; 10516 } 10517 unselect(editor) { 10518 editor.unselect(); 10519 this.#selectedEditors.delete(editor); 10520 this.#dispatchUpdateStates({ 10521 hasSelectedEditor: this.hasSelection 10522 }); 10523 } 10524 get hasSelection() { 10525 return this.#selectedEditors.size !== 0; 10526 } 10527 get isEnterHandled() { 10528 return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; 10529 } 10530 undo() { 10531 this.#commandManager.undo(); 10532 this.#dispatchUpdateStates({ 10533 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), 10534 hasSomethingToRedo: true, 10535 isEmpty: this.#isEmpty() 10536 }); 10537 this._editorUndoBar?.hide(); 10538 } 10539 redo() { 10540 this.#commandManager.redo(); 10541 this.#dispatchUpdateStates({ 10542 hasSomethingToUndo: true, 10543 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), 10544 isEmpty: this.#isEmpty() 10545 }); 10546 } 10547 addCommands(params) { 10548 this.#commandManager.add(params); 10549 this.#dispatchUpdateStates({ 10550 hasSomethingToUndo: true, 10551 hasSomethingToRedo: false, 10552 isEmpty: this.#isEmpty() 10553 }); 10554 } 10555 cleanUndoStack(type) { 10556 this.#commandManager.cleanType(type); 10557 } 10558 #isEmpty() { 10559 if (this.#allEditors.size === 0) { 10560 return true; 10561 } 10562 if (this.#allEditors.size === 1) { 10563 for (const editor of this.#allEditors.values()) { 10564 return editor.isEmpty(); 10565 } 10566 } 10567 return false;
vendor: 1,612 bytes, lines 10568-10630
10568 } 10569 delete() { 10570 this.commitOrRemove(); 10571 const drawingEditor = this.currentLayer?.endDrawingSession(true); 10572 if (!this.hasSelection && !drawingEditor) { 10573 return; 10574 } 10575 const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors]; 10576 const cmd = () => { 10577 this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length); 10578 for (const editor of editors) { 10579 editor.remove(); 10580 } 10581 }; 10582 const undo = () => { 10583 for (const editor of editors) { 10584 this.#addEditorToLayer(editor); 10585 } 10586 }; 10587 this.addCommands({ 10588 cmd, 10589 undo, 10590 mustExec: true 10591 }); 10592 } 10593 commitOrRemove() { 10594 this.#activeEditor?.commitOrRemove(); 10595 } 10596 hasSomethingToControl() { 10597 return this.#activeEditor || this.hasSelection; 10598 } 10599 #selectEditors(editors) { 10600 for (const editor of this.#selectedEditors) { 10601 editor.unselect(); 10602 } 10603 this.#selectedEditors.clear(); 10604 for (const editor of editors) { 10605 if (editor.isEmpty()) { 10606 continue; 10607 } 10608 this.#selectedEditors.add(editor); 10609 editor.select(); 10610 } 10611 this.#dispatchUpdateStates({ 10612 hasSelectedEditor: this.hasSelection 10613 }); 10614 } 10615 selectAll() { 10616 for (const editor of this.#selectedEditors) { 10617 editor.commit(); 10618 } 10619 this.#selectEditors(this.#allEditors.values()); 10620 } 10621 unselectAll() { 10622 if (this.#activeEditor) { 10623 this.#activeEditor.commitOrRemove(); 10624 if (this.#mode !== AnnotationEditorType.NONE) { 10625 return; 10626 } 10627 } 10628 if (this.#currentDrawingSession?.commitOrRemove()) { 10629 return; 10630 }
vendor: 10,497 bytes, lines 10630-11001
10630 10631 if (!this.hasSelection) { 10632 return; 10633 } 10634 for (const editor of this.#selectedEditors) { 10635 editor.unselect(); 10636 } 10637 this.#selectedEditors.clear(); 10638 this.#dispatchUpdateStates({ 10639 hasSelectedEditor: false 10640 }); 10641 } 10642 translateSelectedEditors(x, y, noCommit = false) { 10643 if (!noCommit) { 10644 this.commitOrRemove(); 10645 } 10646 if (!this.hasSelection) { 10647 return; 10648 } 10649 this.#translation[0] += x; 10650 this.#translation[1] += y; 10651 const [totalX, totalY] = this.#translation; 10652 const editors = [...this.#selectedEditors]; 10653 const TIME_TO_WAIT = 1000; 10654 if (this.#translationTimeoutId) { 10655 clearTimeout(this.#translationTimeoutId); 10656 } 10657 this.#translationTimeoutId = setTimeout(() => { 10658 this.#translationTimeoutId = null; 10659 this.#translation[0] = this.#translation[1] = 0; 10660 this.addCommands({ 10661 cmd: () => { 10662 for (const editor of editors) { 10663 if (this.#allEditors.has(editor.id)) { 10664 editor.translateInPage(totalX, totalY); 10665 editor.translationDone(); 10666 } 10667 } 10668 }, 10669 undo: () => { 10670 for (const editor of editors) { 10671 if (this.#allEditors.has(editor.id)) { 10672 editor.translateInPage(-totalX, -totalY); 10673 editor.translationDone(); 10674 } 10675 } 10676 }, 10677 mustExec: false 10678 }); 10679 }, TIME_TO_WAIT); 10680 for (const editor of editors) { 10681 editor.translateInPage(x, y); 10682 editor.translationDone(); 10683 } 10684 } 10685 setUpDragSession() { 10686 if (!this.hasSelection) { 10687 return; 10688 } 10689 this.disableUserSelect(true); 10690 this.#draggingEditors = new Map(); 10691 for (const editor of this.#selectedEditors) { 10692 this.#draggingEditors.set(editor, { 10693 savedX: editor.x, 10694 savedY: editor.y, 10695 savedPageIndex: editor.pageIndex, 10696 newX: 0, 10697 newY: 0, 10698 newPageIndex: -1 10699 }); 10700 } 10701 } 10702 endDragSession() { 10703 if (!this.#draggingEditors) { 10704 return false; 10705 } 10706 this.disableUserSelect(false); 10707 const map = this.#draggingEditors; 10708 this.#draggingEditors = null; 10709 let mustBeAddedInUndoStack = false; 10710 for (const [{ 10711 x, 10712 y, 10713 pageIndex 10714 }, value] of map) { 10715 value.newX = x; 10716 value.newY = y; 10717 value.newPageIndex = pageIndex; 10718 mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex; 10719 } 10720 if (!mustBeAddedInUndoStack) { 10721 return false; 10722 } 10723 const move = (editor, x, y, pageIndex) => { 10724 if (this.#allEditors.has(editor.id)) { 10725 const parent = this.#allLayers.get(pageIndex); 10726 if (parent) { 10727 editor._setParentAndPosition(parent, x, y); 10728 } else { 10729 editor.pageIndex = pageIndex; 10730 editor.x = x; 10731 editor.y = y; 10732 } 10733 } 10734 }; 10735 this.addCommands({ 10736 cmd: () => { 10737 for (const [editor, { 10738 newX, 10739 newY, 10740 newPageIndex 10741 }] of map) { 10742 move(editor, newX, newY, newPageIndex); 10743 } 10744 }, 10745 undo: () => { 10746 for (const [editor, { 10747 savedX, 10748 savedY, 10749 savedPageIndex 10750 }] of map) { 10751 move(editor, savedX, savedY, savedPageIndex); 10752 } 10753 }, 10754 mustExec: true 10755 }); 10756 return true; 10757 } 10758 dragSelectedEditors(tx, ty) { 10759 if (!this.#draggingEditors) { 10760 return; 10761 } 10762 for (const editor of this.#draggingEditors.keys()) { 10763 editor.drag(tx, ty); 10764 } 10765 } 10766 rebuild(editor) { 10767 if (editor.parent === null) { 10768 const parent = this.getLayer(editor.pageIndex); 10769 if (parent) { 10770 parent.changeParent(editor); 10771 parent.addOrRebuild(editor); 10772 } else { 10773 this.addEditor(editor); 10774 this.addToAnnotationStorage(editor); 10775 editor.rebuild(); 10776 } 10777 } else { 10778 editor.parent.addOrRebuild(editor); 10779 } 10780 } 10781 get isEditorHandlingKeyboard() { 10782 return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); 10783 } 10784 isActive(editor) { 10785 return this.#activeEditor === editor; 10786 } 10787 getActive() { 10788 return this.#activeEditor; 10789 } 10790 getMode() { 10791 return this.#mode; 10792 } 10793 isEditingMode() { 10794 return this.#mode !== AnnotationEditorType.NONE; 10795 } 10796 get imageManager() { 10797 return shadow(this, "imageManager", new ImageManager()); 10798 } 10799 getSelectionBoxes(textLayer) { 10800 if (!textLayer) { 10801 return null; 10802 } 10803 const selection = document.getSelection(); 10804 for (let i = 0, ii = selection.rangeCount; i < ii; i++) { 10805 if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) { 10806 return null; 10807 } 10808 } 10809 const { 10810 x: layerX, 10811 y: layerY, 10812 width: parentWidth, 10813 height: parentHeight 10814 } = textLayer.getBoundingClientRect(); 10815 let rotator; 10816 switch (textLayer.getAttribute("data-main-rotation")) { 10817 case "90": 10818 rotator = (x, y, w, h) => ({ 10819 x: (y - layerY) / parentHeight, 10820 y: 1 - (x + w - layerX) / parentWidth, 10821 width: h / parentHeight, 10822 height: w / parentWidth 10823 }); 10824 break; 10825 case "180": 10826 rotator = (x, y, w, h) => ({ 10827 x: 1 - (x + w - layerX) / parentWidth, 10828 y: 1 - (y + h - layerY) / parentHeight, 10829 width: w / parentWidth, 10830 height: h / parentHeight 10831 }); 10832 break; 10833 case "270": 10834 rotator = (x, y, w, h) => ({ 10835 x: 1 - (y + h - layerY) / parentHeight, 10836 y: (x - layerX) / parentWidth, 10837 width: h / parentHeight, 10838 height: w / parentWidth 10839 }); 10840 break; 10841 default: 10842 rotator = (x, y, w, h) => ({ 10843 x: (x - layerX) / parentWidth, 10844 y: (y - layerY) / parentHeight, 10845 width: w / parentWidth, 10846 height: h / parentHeight 10847 }); 10848 break; 10849 } 10850 const boxes = []; 10851 for (let i = 0, ii = selection.rangeCount; i < ii; i++) { 10852 const range = selection.getRangeAt(i); 10853 if (range.collapsed) { 10854 continue; 10855 } 10856 for (const { 10857 x, 10858 y, 10859 width, 10860 height 10861 } of range.getClientRects()) { 10862 if (width === 0 || height === 0) { 10863 continue; 10864 } 10865 boxes.push(rotator(x, y, width, height)); 10866 } 10867 } 10868 return boxes.length === 0 ? null : boxes; 10869 } 10870 addChangedExistingAnnotation({ 10871 annotationElementId, 10872 id 10873 }) { 10874 (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id); 10875 } 10876 removeChangedExistingAnnotation({ 10877 annotationElementId 10878 }) { 10879 this.#changedExistingAnnotations?.delete(annotationElementId); 10880 } 10881 renderAnnotationElement(annotation) { 10882 const editorId = this.#changedExistingAnnotations?.get(annotation.data.id); 10883 if (!editorId) { 10884 return; 10885 } 10886 const editor = this.#annotationStorage.getRawValue(editorId); 10887 if (!editor) { 10888 return; 10889 } 10890 if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) { 10891 return; 10892 } 10893 editor.renderAnnotationElement(annotation); 10894 } 10895 setMissingCanvas(annotationId, annotationElementId, canvas) { 10896 const editor = this.#missingCanvases?.get(annotationId); 10897 if (!editor) { 10898 return; 10899 } 10900 editor.setCanvas(annotationElementId, canvas); 10901 this.#missingCanvases.delete(annotationId); 10902 } 10903 addMissingCanvas(annotationId, editor) { 10904 (this.#missingCanvases ||= new Map()).set(annotationId, editor); 10905 } 10906} 10907 10908;// ./src/display/editor/alt_text.js 10909 10910class AltText { 10911 #altText = null; 10912 #altTextDecorative = false; 10913 #altTextButton = null; 10914 #altTextButtonLabel = null; 10915 #altTextTooltip = null; 10916 #altTextTooltipTimeout = null; 10917 #altTextWasFromKeyBoard = false; 10918 #badge = null; 10919 #editor = null; 10920 #guessedText = null; 10921 #textWithDisclaimer = null; 10922 #useNewAltTextFlow = false; 10923 static #l10nNewButton = null; 10924 static _l10n = null; 10925 constructor(editor) { 10926 this.#editor = editor; 10927 this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; 10928 AltText.#l10nNewButton ||= Object.freeze({ 10929 added: "pdfjs-editor-new-alt-text-added-button", 10930 "added-label": "pdfjs-editor-new-alt-text-added-button-label", 10931 missing: "pdfjs-editor-new-alt-text-missing-button", 10932 "missing-label": "pdfjs-editor-new-alt-text-missing-button-label", 10933 review: "pdfjs-editor-new-alt-text-to-review-button", 10934 "review-label": "pdfjs-editor-new-alt-text-to-review-button-label" 10935 }); 10936 } 10937 static initialize(l10n) { 10938 AltText._l10n ??= l10n; 10939 } 10940 async render() { 10941 const altText = this.#altTextButton = document.createElement("button"); 10942 altText.className = "altText"; 10943 altText.tabIndex = "0"; 10944 const label = this.#altTextButtonLabel = document.createElement("span"); 10945 altText.append(label); 10946 if (this.#useNewAltTextFlow) { 10947 altText.classList.add("new"); 10948 altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing); 10949 label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]); 10950 } else { 10951 altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button"); 10952 label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label"); 10953 } 10954 const signal = this.#editor._uiManager._signal; 10955 altText.addEventListener("contextmenu", noContextMenu, { 10956 signal 10957 }); 10958 altText.addEventListener("pointerdown", event => event.stopPropagation(), { 10959 signal 10960 }); 10961 const onClick = event => { 10962 event.preventDefault(); 10963 this.#editor._uiManager.editAltText(this.#editor); 10964 if (this.#useNewAltTextFlow) { 10965 this.#editor._reportTelemetry({ 10966 action: "pdfjs.image.alt_text.image_status_label_clicked", 10967 data: { 10968 label: this.#label 10969 } 10970 }); 10971 } 10972 }; 10973 altText.addEventListener("click", onClick, { 10974 capture: true, 10975 signal 10976 }); 10977 altText.addEventListener("keydown", event => { 10978 if (event.target === altText && event.key === "Enter") { 10979 this.#altTextWasFromKeyBoard = true; 10980 onClick(event); 10981 } 10982 }, { 10983 signal 10984 }); 10985 await this.#setState(); 10986 return altText; 10987 } 10988 get #label() { 10989 return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing"; 10990 } 10991 finish() { 10992 if (!this.#altTextButton) { 10993 return; 10994 } 10995 this.#altTextButton.focus({ 10996 focusVisible: this.#altTextWasFromKeyBoard 10997 }); 10998 this.#altTextWasFromKeyBoard = false; 10999 } 11000 isEmpty() { 11001
11001if (this.#useNewAltTextFlow) { 11002 return this.#altText === null; 11003 } 11004 return !this.#altText && !this.#altTextDecorative; 11005 } 11006 hasData() { 11007 if (this.#useNewAltTextFlow) { 11008 return this.#altText !== null || !!this.#guessedText; 11009 } 11010 return
vendor: 12,118 bytes, lines 11010-11446
11010 this.isEmpty(); 11011 } 11012 get guessedText() { 11013 return this.#guessedText; 11014 } 11015 async setGuessedText(guessedText) { 11016 if (this.#altText !== null) { 11017 return; 11018 } 11019 this.#guessedText = guessedText; 11020 this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", { 11021 generatedAltText: guessedText 11022 }); 11023 this.#setState(); 11024 } 11025 toggleAltTextBadge(visibility = false) { 11026 if (!this.#useNewAltTextFlow || this.#altText) { 11027 this.#badge?.remove(); 11028 this.#badge = null; 11029 return; 11030 } 11031 if (!this.#badge) { 11032 const badge = this.#badge = document.createElement("div"); 11033 badge.className = "noAltTextBadge"; 11034 this.#editor.div.append(badge); 11035 } 11036 this.#badge.classList.toggle("hidden", !visibility); 11037 } 11038 serialize(isForCopying) { 11039 let altText = this.#altText; 11040 if (!isForCopying && this.#guessedText === altText) { 11041 altText = this.#textWithDisclaimer; 11042 } 11043 return { 11044 altText, 11045 decorative: this.#altTextDecorative, 11046 guessedText: this.#guessedText, 11047 textWithDisclaimer: this.#textWithDisclaimer 11048 }; 11049 } 11050 get data() { 11051 return { 11052 altText: this.#altText, 11053 decorative: this.#altTextDecorative 11054 }; 11055 } 11056 set data({ 11057 altText, 11058 decorative, 11059 guessedText, 11060 textWithDisclaimer, 11061 cancel = false 11062 }) { 11063 if (guessedText) { 11064 this.#guessedText = guessedText; 11065 this.#textWithDisclaimer = textWithDisclaimer; 11066 } 11067 if (this.#altText === altText && this.#altTextDecorative === decorative) { 11068 return; 11069 } 11070 if (!cancel) { 11071 this.#altText = altText; 11072 this.#altTextDecorative = decorative; 11073 } 11074 this.#setState(); 11075 } 11076 toggle(enabled = false) { 11077 if (!this.#altTextButton) { 11078 return; 11079 } 11080 if (!enabled && this.#altTextTooltipTimeout) { 11081 clearTimeout(this.#altTextTooltipTimeout); 11082 this.#altTextTooltipTimeout = null; 11083 } 11084 this.#altTextButton.disabled = !enabled; 11085 } 11086 shown() { 11087 this.#editor._reportTelemetry({ 11088 action: "pdfjs.image.alt_text.image_status_label_displayed", 11089 data: { 11090 label: this.#label 11091 } 11092 }); 11093 } 11094 destroy() { 11095 this.#altTextButton?.remove(); 11096 this.#altTextButton = null; 11097 this.#altTextButtonLabel = null; 11098 this.#altTextTooltip = null; 11099 this.#badge?.remove(); 11100 this.#badge = null; 11101 } 11102 async #setState() { 11103 const button = this.#altTextButton; 11104 if (!button) { 11105 return; 11106 } 11107 if (this.#useNewAltTextFlow) { 11108 button.classList.toggle("done", !!this.#altText); 11109 button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]); 11110 this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]); 11111 if (!this.#altText) { 11112 this.#altTextTooltip?.remove(); 11113 return; 11114 } 11115 } else { 11116 if (!this.#altText && !this.#altTextDecorative) { 11117 button.classList.remove("done"); 11118 this.#altTextTooltip?.remove(); 11119 return; 11120 } 11121 button.classList.add("done"); 11122 button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button"); 11123 } 11124 let tooltip = this.#altTextTooltip; 11125 if (!tooltip) { 11126 this.#altTextTooltip = tooltip = document.createElement("span"); 11127 tooltip.className = "tooltip"; 11128 tooltip.setAttribute("role", "tooltip"); 11129 tooltip.id = `alt-text-tooltip-${this.#editor.id}`; 11130 const DELAY_TO_SHOW_TOOLTIP = 100; 11131 const signal = this.#editor._uiManager._signal; 11132 signal.addEventListener("abort", () => { 11133 clearTimeout(this.#altTextTooltipTimeout); 11134 this.#altTextTooltipTimeout = null; 11135 }, { 11136 once: true 11137 }); 11138 button.addEventListener("mouseenter", () => { 11139 this.#altTextTooltipTimeout = setTimeout(() => { 11140 this.#altTextTooltipTimeout = null; 11141 this.#altTextTooltip.classList.add("show"); 11142 this.#editor._reportTelemetry({ 11143 action: "alt_text_tooltip" 11144 }); 11145 }, DELAY_TO_SHOW_TOOLTIP); 11146 }, { 11147 signal 11148 }); 11149 button.addEventListener("mouseleave", () => { 11150 if (this.#altTextTooltipTimeout) { 11151 clearTimeout(this.#altTextTooltipTimeout); 11152 this.#altTextTooltipTimeout = null; 11153 } 11154 this.#altTextTooltip?.classList.remove("show"); 11155 }, { 11156 signal 11157 }); 11158 } 11159 if (this.#altTextDecorative) { 11160 tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip"); 11161 } else { 11162 tooltip.removeAttribute("data-l10n-id"); 11163 tooltip.textContent = this.#altText; 11164 } 11165 if (!tooltip.parentNode) { 11166 button.append(tooltip); 11167 } 11168 const element = this.#editor.getElementForAltText(); 11169 element?.setAttribute("aria-describedby", tooltip.id); 11170 } 11171} 11172 11173;// ./src/display/editor/comment.js 11174 11175class Comment { 11176 #commentStandaloneButton = null; 11177 #commentToolbarButton = null; 11178 #commentWasFromKeyBoard = false; 11179 #editor = null; 11180 #initialText = null; 11181 #richText = null; 11182 #text = null; 11183 #date = null; 11184 #deleted = false; 11185 #popupPosition = null; 11186 constructor(editor) { 11187 this.#editor = editor; 11188 } 11189 renderForToolbar() { 11190 const button = this.#commentToolbarButton = document.createElement("button"); 11191 button.className = "comment"; 11192 return this.#render(button, false); 11193 } 11194 renderForStandalone() { 11195 const button = this.#commentStandaloneButton = document.createElement("button"); 11196 button.className = "annotationCommentButton"; 11197 const position = this.#editor.commentButtonPosition; 11198 if (position) { 11199 const { 11200 style 11201 } = button; 11202 style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`; 11203 style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`; 11204 const color = this.#editor.commentButtonColor; 11205 if (color) { 11206 style.backgroundColor = color; 11207 } 11208 } 11209 return this.#render(button, true); 11210 } 11211 focusButton() { 11212 setTimeout(() => { 11213 (this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus(); 11214 }, 0); 11215 } 11216 onUpdatedColor() { 11217 if (!this.#commentStandaloneButton) { 11218 return; 11219 } 11220 const color = this.#editor.commentButtonColor; 11221 if (color) { 11222 this.#commentStandaloneButton.style.backgroundColor = color; 11223 } 11224 this.#editor._uiManager.updatePopupColor(this.#editor); 11225 } 11226 get commentButtonWidth() { 11227 return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width; 11228 } 11229 get commentPopupPositionInLayer() { 11230 if (this.#popupPosition) { 11231 return this.#popupPosition; 11232 } 11233 if (!this.#commentStandaloneButton) { 11234 return null; 11235 } 11236 const { 11237 x, 11238 y, 11239 height 11240 } = this.#commentStandaloneButton.getBoundingClientRect(); 11241 const { 11242 x: parentX, 11243 y: parentY, 11244 width: parentWidth, 11245 height: parentHeight 11246 } = this.#editor.parent.boundingClientRect; 11247 return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight]; 11248 } 11249 set commentPopupPositionInLayer(pos) { 11250 this.#popupPosition = pos; 11251 } 11252 hasDefaultPopupPosition() { 11253 return this.#popupPosition === null; 11254 } 11255 removeStandaloneCommentButton() { 11256 this.#commentStandaloneButton?.remove(); 11257 this.#commentStandaloneButton = null; 11258 } 11259 removeToolbarCommentButton() { 11260 this.#commentToolbarButton?.remove(); 11261 this.#commentToolbarButton = null; 11262 } 11263 setCommentButtonStates({ 11264 selected, 11265 hasPopup 11266 }) { 11267 if (!this.#commentStandaloneButton) { 11268 return; 11269 } 11270 this.#commentStandaloneButton.classList.toggle("selected", selected); 11271 this.#commentStandaloneButton.ariaExpanded = hasPopup; 11272 } 11273 #render(comment, isStandalone) { 11274 if (!this.#editor._uiManager.hasCommentManager()) { 11275 return null; 11276 } 11277 comment.tabIndex = "0"; 11278 comment.ariaHasPopup = "dialog"; 11279 if (isStandalone) { 11280 comment.ariaControls = "commentPopup"; 11281 comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); 11282 } else { 11283 comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()]; 11284 comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button"); 11285 } 11286 const signal = this.#editor._uiManager._signal; 11287 if (!(signal instanceof AbortSignal) || signal.aborted) { 11288 return comment; 11289 } 11290 comment.addEventListener("contextmenu", noContextMenu, { 11291 signal 11292 }); 11293 if (isStandalone) { 11294 comment.addEventListener("focusin", e => { 11295 this.#editor._focusEventsAllowed = false; 11296 stopEvent(e); 11297 }, { 11298 capture: true, 11299 signal 11300 }); 11301 comment.addEventListener("focusout", e => { 11302 this.#editor._focusEventsAllowed = true; 11303 stopEvent(e); 11304 }, { 11305 capture: true, 11306 signal 11307 }); 11308 } 11309 comment.addEventListener("pointerdown", event => event.stopPropagation(), { 11310 signal 11311 }); 11312 const onClick = event => { 11313 event.preventDefault(); 11314 if (comment === this.#commentToolbarButton) { 11315 this.edit(); 11316 } else { 11317 this.#editor.toggleComment(true); 11318 } 11319 }; 11320 comment.addEventListener("click", onClick, { 11321 capture: true, 11322 signal 11323 }); 11324 comment.addEventListener("keydown", event => { 11325 if (event.target === comment && event.key === "Enter") { 11326 this.#commentWasFromKeyBoard = true; 11327 onClick(event); 11328 } 11329 }, { 11330 signal 11331 }); 11332 comment.addEventListener("pointerenter", () => { 11333 this.#editor.toggleComment(false, true); 11334 }, { 11335 signal 11336 }); 11337 comment.addEventListener("pointerleave", () => { 11338 this.#editor.toggleComment(false, false); 11339 }, { 11340 signal 11341 }); 11342 return comment; 11343 } 11344 edit(options) { 11345 const position = this.commentPopupPositionInLayer; 11346 let posX, posY; 11347 if (position) { 11348 [posX, posY] = position; 11349 } else { 11350 [posX, posY] = this.#editor.commentButtonPosition; 11351 const { 11352 width, 11353 height, 11354 x, 11355 y 11356 } = this.#editor; 11357 posX = x + posX * width; 11358 posY = y + posY * height; 11359 } 11360 const parentDimensions = this.#editor.parent.boundingClientRect; 11361 const { 11362 x: parentX, 11363 y: parentY, 11364 width: parentWidth, 11365 height: parentHeight 11366 } = parentDimensions; 11367 this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, { 11368 ...options, 11369 parentDimensions 11370 }); 11371 } 11372 finish() { 11373 if (!this.#commentToolbarButton) { 11374 return; 11375 } 11376 this.#commentToolbarButton.focus({ 11377 focusVisible: this.#commentWasFromKeyBoard 11378 }); 11379 this.#commentWasFromKeyBoard = false; 11380 } 11381 isDeleted() { 11382 return this.#deleted || this.#text === ""; 11383 } 11384 isEmpty() { 11385 return this.#text === null; 11386 } 11387 hasBeenEdited() { 11388 return this.isDeleted() || this.#text !== this.#initialText; 11389 } 11390 serialize() { 11391 return this.data; 11392 } 11393 get data() { 11394 return { 11395 text: this.#text, 11396 richText: this.#richText, 11397 date: this.#date, 11398 deleted: this.isDeleted() 11399 }; 11400 } 11401 set data(text) { 11402 if (text !== this.#text) { 11403 this.#richText = null; 11404 } 11405 if (text === null) { 11406 this.#text = ""; 11407 this.#deleted = true; 11408 return; 11409 } 11410 this.#text = text; 11411 this.#date = new Date(); 11412 this.#deleted = false; 11413 } 11414 restoreData({ 11415 text, 11416 richText, 11417 date 11418 }) { 11419 this.#text = text; 11420 this.#richText = richText; 11421 this.#date = date; 11422 this.#deleted = false; 11423 } 11424 setInitialText(text, richText = null) { 11425 this.#initialText = text; 11426 this.data = text; 11427 this.#date = null; 11428 this.#richText = richText; 11429 } 11430 shown() {} 11431 destroy() { 11432 this.#commentToolbarButton?.remove(); 11433 this.#commentToolbarButton = null; 11434 this.#commentStandaloneButton?.remove(); 11435 this.#commentStandaloneButton = null; 11436 this.#text = ""; 11437 this.#richText = null; 11438 this.#date = null; 11439 this.#editor = null; 11440 this.#commentWasFromKeyBoard = false; 11441 this.#deleted = false; 11442 } 11443} 11444 11445;// ./src/display/touch_manager.js 11446
vendor: 8,490 bytes, lines 11447-11726
11447class TouchManager { 11448 #container; 11449 #isPinching = false; 11450 #isPinchingStopped = null; 11451 #isPinchingDisabled; 11452 #onPinchStart; 11453 #onPinching; 11454 #onPinchEnd; 11455 #pointerDownAC = null; 11456 #signal; 11457 #touchInfo = null; 11458 #touchManagerAC; 11459 #touchMoveAC = null; 11460 constructor({ 11461 container, 11462 isPinchingDisabled = null, 11463 isPinchingStopped = null, 11464 onPinchStart = null, 11465 onPinching = null, 11466 onPinchEnd = null, 11467 signal 11468 }) { 11469 this.#container = container; 11470 this.#isPinchingStopped = isPinchingStopped; 11471 this.#isPinchingDisabled = isPinchingDisabled; 11472 this.#onPinchStart = onPinchStart; 11473 this.#onPinching = onPinching; 11474 this.#onPinchEnd = onPinchEnd; 11475 this.#touchManagerAC = new AbortController(); 11476 this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]); 11477 container.addEventListener("touchstart", this.#onTouchStart.bind(this), { 11478 passive: false, 11479 signal: this.#signal 11480 }); 11481 } 11482 get MIN_TOUCH_DISTANCE_TO_PINCH() { 11483 return 35 / OutputScale.pixelRatio; 11484 } 11485 #onTouchStart(evt) { 11486 if (this.#isPinchingDisabled?.()) { 11487 return; 11488 } 11489 if (evt.touches.length === 1) { 11490 if (this.#pointerDownAC) { 11491 return; 11492 } 11493 const pointerDownAC = this.#pointerDownAC = new AbortController(); 11494 const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]); 11495 const container = this.#container; 11496 const opts = { 11497 capture: true, 11498 signal, 11499 passive: false 11500 }; 11501 const cancelPointerDown = e => { 11502 if (e.pointerType === "touch") { 11503 this.#pointerDownAC?.abort(); 11504 this.#pointerDownAC = null; 11505 } 11506 }; 11507 container.addEventListener("pointerdown", e => { 11508 if (e.pointerType === "touch") { 11509 stopEvent(e); 11510 cancelPointerDown(e); 11511 } 11512 }, opts); 11513 container.addEventListener("pointerup", cancelPointerDown, opts); 11514 container.addEventListener("pointercancel", cancelPointerDown, opts); 11515 return; 11516 } 11517 if (!this.#touchMoveAC) { 11518 this.#touchMoveAC = new AbortController(); 11519 const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]); 11520 const container = this.#container; 11521 const opt = { 11522 signal, 11523 capture: false, 11524 passive: false 11525 }; 11526 container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt); 11527 const onTouchEnd = this.#onTouchEnd.bind(this); 11528 container.addEventListener("touchend", onTouchEnd, opt); 11529 container.addEventListener("touchcancel", onTouchEnd, opt); 11530 opt.capture = true; 11531 container.addEventListener("pointerdown", stopEvent, opt); 11532 container.addEventListener("pointermove", stopEvent, opt); 11533 container.addEventListener("pointercancel", stopEvent, opt); 11534 container.addEventListener("pointerup", stopEvent, opt); 11535 this.#onPinchStart?.(); 11536 } 11537 stopEvent(evt); 11538 if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) { 11539 this.#touchInfo = null; 11540 return; 11541 } 11542 let [touch0, touch1] = evt.touches; 11543 if (touch0.identifier > touch1.identifier) { 11544 [touch0, touch1] = [touch1, touch0]; 11545 } 11546 this.#touchInfo = { 11547 touch0X: touch0.screenX, 11548 touch0Y: touch0.screenY, 11549 touch1X: touch1.screenX, 11550 touch1Y: touch1.screenY 11551 }; 11552 } 11553 #onTouchMove(evt) { 11554 if (!this.#touchInfo || evt.touches.length !== 2) { 11555 return; 11556 } 11557 stopEvent(evt); 11558 let [touch0, touch1] = evt.touches; 11559 if (touch0.identifier > touch1.identifier) { 11560 [touch0, touch1] = [touch1, touch0]; 11561 } 11562 const { 11563 screenX: screen0X, 11564 screenY: screen0Y 11565 } = touch0; 11566 const { 11567 screenX: screen1X, 11568 screenY: screen1Y 11569 } = touch1; 11570 const touchInfo = this.#touchInfo; 11571 const { 11572 touch0X: pTouch0X, 11573 touch0Y: pTouch0Y, 11574 touch1X: pTouch1X, 11575 touch1Y: pTouch1Y 11576 } = touchInfo; 11577 const prevGapX = pTouch1X - pTouch0X; 11578 const prevGapY = pTouch1Y - pTouch0Y; 11579 const currGapX = screen1X - screen0X; 11580 const currGapY = screen1Y - screen0Y; 11581 const distance = Math.hypot(currGapX, currGapY) || 1; 11582 const pDistance = Math.hypot(prevGapX, prevGapY) || 1; 11583 if (!this.#isPinching && Math.abs(pDistance - distance) <= TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) { 11584 return; 11585 } 11586 touchInfo.touch0X = screen0X; 11587 touchInfo.touch0Y = screen0Y; 11588 touchInfo.touch1X = screen1X; 11589 touchInfo.touch1Y = screen1Y; 11590 if (!this.#isPinching) { 11591 this.#isPinching = true; 11592 return; 11593 } 11594 const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2]; 11595 this.#onPinching?.(origin, pDistance, distance); 11596 } 11597 #onTouchEnd(evt) { 11598 if (evt.touches.length >= 2) { 11599 return; 11600 } 11601 if (this.#touchMoveAC) { 11602 this.#touchMoveAC.abort(); 11603 this.#touchMoveAC = null; 11604 this.#onPinchEnd?.(); 11605 } 11606 if (!this.#touchInfo) { 11607 return; 11608 } 11609 stopEvent(evt); 11610 this.#touchInfo = null; 11611 this.#isPinching = false; 11612 } 11613 destroy() { 11614 this.#touchManagerAC?.abort(); 11615 this.#touchManagerAC = null; 11616 this.#pointerDownAC?.abort(); 11617 this.#pointerDownAC = null; 11618 } 11619} 11620 11621;// ./src/display/editor/editor.js 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631class AnnotationEditor { 11632 #accessibilityData = null; 11633 #allResizerDivs = null; 11634 #altText = null; 11635 #comment = null; 11636 #commentStandaloneButton = null; 11637 #disabled = false; 11638 #dragPointerId = null; 11639 #dragPointerType = ""; 11640 #resizersDiv = null; 11641 #lastPointerCoords = null; 11642 #savedDimensions = null; 11643 #fakeAnnotation = null; 11644 #focusAC = null; 11645 #focusedResizerName = ""; 11646 #hasBeenClicked = false; 11647 #initialRect = null; 11648 #isEditing = false; 11649 #isInEditMode = false; 11650 #isResizerEnabledForKeyboard = false; 11651 #moveInDOMTimeout = null; 11652 #prevDragX = 0; 11653 #prevDragY = 0; 11654 #telemetryTimeouts = null; 11655 #touchManager = null; 11656 isSelected = false; 11657 _isCopy = false; 11658 _editToolbar = null; 11659 _initialOptions = Object.create(null); 11660 _initialData = null; 11661 _isVisible = true; 11662 _uiManager = null; 11663 _focusEventsAllowed = true; 11664 static _l10n = null; 11665 static _l10nResizer = null; 11666 #isDraggable = false; 11667 #zIndex = AnnotationEditor._zIndex++; 11668 static _borderLineWidth = -1; 11669 static _colorManager = new ColorManager(); 11670 static _zIndex = 1; 11671 static _telemetryTimeout = 1000; 11672 static get _resizerKeyboardManager() { 11673 const resize = AnnotationEditor.prototype._resizeWithKeyboard; 11674 const small = AnnotationEditorUIManager.TRANSLATE_SMALL; 11675 const big = AnnotationEditorUIManager.TRANSLATE_BIG; 11676 return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, { 11677 args: [-small, 0] 11678 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, { 11679 args: [-big, 0] 11680 }], [["ArrowRight", "mac+ArrowRight"], resize, { 11681 args: [small, 0] 11682 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, { 11683 args: [big, 0] 11684 }], [["ArrowUp", "mac+ArrowUp"], resize, { 11685 args: [0, -small] 11686 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, { 11687 args: [0, -big] 11688 }], [["ArrowDown", "mac+ArrowDown"], resize, { 11689 args: [0, small] 11690 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, { 11691 args: [0, big] 11692 }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]])); 11693 } 11694 constructor(parameters) { 11695 this.parent = parameters.parent; 11696 this.id = parameters.id; 11697 this.width = this.height = null; 11698 this.pageIndex = parameters.parent.pageIndex; 11699 this.name = parameters.name; 11700 this.div = null; 11701 this._uiManager = parameters.uiManager; 11702 this.annotationElementId = null; 11703 this._willKeepAspectRatio = false; 11704 this._initialOptions.isCentered = parameters.isCentered; 11705 this._structTreeParentId = null; 11706 this.annotationElementId = parameters.annotationElementId || null; 11707 this.creationDate = parameters.creationDate || new Date(); 11708 this.modificationDate = parameters.modificationDate || null; 11709 this.canAddComment = true; 11710 const { 11711 rotation, 11712 rawDims: { 11713 pageWidth, 11714 pageHeight, 11715 pageX, 11716 pageY 11717 } 11718 } = this.parent.viewport; 11719 this.rotation = rotation; 11720 this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; 11721 this.pageDimensions = [pageWidth, pageHeight]; 11722 this.pageTranslation = [pageX, pageY]; 11723 const [width, height] = this.parentDimensions; 11724 this.x = parameters.x / width; 11725 this.y = parameters.y / height; 11726 this.isAttachedToDOM = false;
vendor: 6,125 bytes, lines 11727-11950
11727 this.deleted = false; 11728 } 11729 updatePageIndex(newPageIndex) { 11730 this.pageIndex = newPageIndex; 11731 } 11732 get editorType() { 11733 return Object.getPrototypeOf(this).constructor._type; 11734 } 11735 get mode() { 11736 return Object.getPrototypeOf(this).constructor._editorType; 11737 } 11738 static get isDrawer() { 11739 return false; 11740 } 11741 static get _defaultLineColor() { 11742 return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); 11743 } 11744 static deleteAnnotationElement(editor) { 11745 const fakeEditor = new FakeEditor({ 11746 id: editor.parent.getNextId(), 11747 parent: editor.parent, 11748 uiManager: editor._uiManager 11749 }); 11750 fakeEditor.annotationElementId = editor.annotationElementId; 11751 fakeEditor.deleted = true; 11752 fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); 11753 } 11754 static initialize(l10n, _uiManager) { 11755 AnnotationEditor._l10n ??= l10n; 11756 AnnotationEditor._l10nResizer ||= Object.freeze({ 11757 topLeft: "pdfjs-editor-resizer-top-left", 11758 topMiddle: "pdfjs-editor-resizer-top-middle", 11759 topRight: "pdfjs-editor-resizer-top-right", 11760 middleRight: "pdfjs-editor-resizer-middle-right", 11761 bottomRight: "pdfjs-editor-resizer-bottom-right", 11762 bottomMiddle: "pdfjs-editor-resizer-bottom-middle", 11763 bottomLeft: "pdfjs-editor-resizer-bottom-left", 11764 middleLeft: "pdfjs-editor-resizer-middle-left" 11765 }); 11766 if (AnnotationEditor._borderLineWidth !== -1) { 11767 return; 11768 } 11769 const style = getComputedStyle(document.documentElement); 11770 AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; 11771 } 11772 static updateDefaultParams(_type, _value) {} 11773 static get defaultPropertiesToUpdate() { 11774 return []; 11775 } 11776 static isHandlingMimeForPasting(mime) { 11777 return false; 11778 } 11779 static paste(item, parent) { 11780 unreachable("Not implemented"); 11781 } 11782 get propertiesToUpdate() { 11783 return []; 11784 } 11785 get _isDraggable() { 11786 return this.#isDraggable; 11787 } 11788 set _isDraggable(value) { 11789 this.#isDraggable = value; 11790 this.div?.classList.toggle("draggable", value); 11791 } 11792 get uid() { 11793 return this.annotationElementId || this.id; 11794 } 11795 get isEnterHandled() { 11796 return true; 11797 } 11798 center() { 11799 const [pageWidth, pageHeight] = this.pageDimensions; 11800 switch (this.parentRotation) { 11801 case 90: 11802 this.x -= this.height * pageHeight / (pageWidth * 2); 11803 this.y += this.width * pageWidth / (pageHeight * 2); 11804 break; 11805 case 180: 11806 this.x += this.width / 2; 11807 this.y += this.height / 2; 11808 break; 11809 case 270: 11810 this.x += this.height * pageHeight / (pageWidth * 2); 11811 this.y -= this.width * pageWidth / (pageHeight * 2); 11812 break; 11813 default: 11814 this.x -= this.width / 2; 11815 this.y -= this.height / 2; 11816 break; 11817 } 11818 this.fixAndSetPosition(); 11819 } 11820 addCommands(params) { 11821 this._uiManager.addCommands(params); 11822 } 11823 get currentLayer() { 11824 return this._uiManager.currentLayer; 11825 } 11826 setInBackground() { 11827 this.div.style.zIndex = 0; 11828 } 11829 setInForeground() { 11830 this.div.style.zIndex = this.#zIndex; 11831 } 11832 setParent(parent) { 11833 if (parent !== null) { 11834 this.pageIndex = parent.pageIndex; 11835 this.pageDimensions = parent.pageDimensions; 11836 } else { 11837 this.#stopResizing(); 11838 this.#fakeAnnotation?.remove(); 11839 this.#fakeAnnotation = null; 11840 } 11841 this.parent = parent; 11842 } 11843 focusin(event) { 11844 if (!this._focusEventsAllowed) { 11845 return; 11846 } 11847 if (!this.#hasBeenClicked) { 11848 this.parent.setSelected(this); 11849 } else { 11850 this.#hasBeenClicked = false; 11851 } 11852 } 11853 focusout(event) { 11854 if (!this._focusEventsAllowed) { 11855 return; 11856 } 11857 if (!this.isAttachedToDOM) { 11858 return; 11859 } 11860 const target = event.relatedTarget; 11861 if (target?.closest(`#${this.id}`)) { 11862 return; 11863 } 11864 event.preventDefault(); 11865 if (!this.parent?.isMultipleSelection) { 11866 this.commitOrRemove(); 11867 } 11868 } 11869 commitOrRemove() { 11870 if (this.isEmpty()) { 11871 this.remove(); 11872 } else { 11873 this.commit(); 11874 } 11875 } 11876 commit() { 11877 if (!this.isInEditMode()) { 11878 return; 11879 } 11880 this.addToAnnotationStorage(); 11881 } 11882 addToAnnotationStorage() { 11883 this._uiManager.addToAnnotationStorage(this); 11884 } 11885 setAt(x, y, tx, ty) { 11886 const [width, height] = this.parentDimensions; 11887 [tx, ty] = this.screenToPageTranslation(tx, ty); 11888 this.x = (x + tx) / width; 11889 this.y = (y + ty) / height; 11890 this.fixAndSetPosition(); 11891 } 11892 _moveAfterPaste(baseX, baseY) { 11893 const [parentWidth, parentHeight] = this.parentDimensions; 11894 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); 11895 this._onTranslated(); 11896 } 11897 #translate([width, height], x, y) { 11898 [x, y] = this.screenToPageTranslation(x, y); 11899 this.x += x / width; 11900 this.y += y / height; 11901 this._onTranslating(this.x, this.y); 11902 this.fixAndSetPosition(); 11903 } 11904 translate(x, y) { 11905 this.#translate(this.parentDimensions, x, y); 11906 } 11907 translateInPage(x, y) { 11908 this.#initialRect ||= [this.x, this.y, this.width, this.height]; 11909 this.#translate(this.pageDimensions, x, y); 11910 this.div.scrollIntoView({ 11911 block: "nearest" 11912 }); 11913 } 11914 translationDone() { 11915 this._onTranslated(this.x, this.y); 11916 } 11917 drag(tx, ty) { 11918 this.#initialRect ||= [this.x, this.y, this.width, this.height]; 11919 const { 11920 div, 11921 parentDimensions: [parentWidth, parentHeight] 11922 } = this; 11923 this.x += tx / parentWidth; 11924 this.y += ty / parentHeight; 11925 if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { 11926 const { 11927 x, 11928 y 11929 } = this.div.getBoundingClientRect(); 11930 if (this.parent.findNewParent(this, x, y)) { 11931 this.x -= Math.floor(this.x); 11932 this.y -= Math.floor(this.y); 11933 } 11934 } 11935 let { 11936 x, 11937 y 11938 } = this; 11939 const [bx, by] = this.getBaseTranslation(); 11940 x += bx; 11941 y += by; 11942 const { 11943 style 11944 } = div; 11945 style.left = `${(100 * x).toFixed(2)}%`; 11946 style.top = `${(100 * y).toFixed(2)}%`; 11947 this._onTranslating(x, y); 11948 div.scrollIntoView({ 11949 block: "nearest" 11950 }
vendor: 17,821 bytes, lines 11950-12545
11950); 11951 } 11952 _onTranslating(x, y) {} 11953 _onTranslated(x, y) {} 11954 get _hasBeenMoved() { 11955 return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y); 11956 } 11957 get _hasBeenResized() { 11958 return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height); 11959 } 11960 getBaseTranslation() { 11961 const [parentWidth, parentHeight] = this.parentDimensions; 11962 const { 11963 _borderLineWidth 11964 } = AnnotationEditor; 11965 const x = _borderLineWidth / parentWidth; 11966 const y = _borderLineWidth / parentHeight; 11967 switch (this.rotation) { 11968 case 90: 11969 return [-x, y]; 11970 case 180: 11971 return [x, y]; 11972 case 270: 11973 return [x, -y]; 11974 default: 11975 return [-x, -y]; 11976 } 11977 } 11978 get _mustFixPosition() { 11979 return true; 11980 } 11981 fixAndSetPosition(rotation = this.rotation) { 11982 const { 11983 div: { 11984 style 11985 }, 11986 pageDimensions: [pageWidth, pageHeight] 11987 } = this; 11988 let { 11989 x, 11990 y, 11991 width, 11992 height 11993 } = this; 11994 width *= pageWidth; 11995 height *= pageHeight; 11996 x *= pageWidth; 11997 y *= pageHeight; 11998 if (this._mustFixPosition) { 11999 switch (rotation) { 12000 case 0: 12001 x = MathClamp(x, 0, pageWidth - width); 12002 y = MathClamp(y, 0, pageHeight - height); 12003 break; 12004 case 90: 12005 x = MathClamp(x, 0, pageWidth - height); 12006 y = MathClamp(y, width, pageHeight); 12007 break; 12008 case 180: 12009 x = MathClamp(x, width, pageWidth); 12010 y = MathClamp(y, height, pageHeight); 12011 break; 12012 case 270: 12013 x = MathClamp(x, height, pageWidth); 12014 y = MathClamp(y, 0, pageHeight - width); 12015 break; 12016 } 12017 } 12018 this.x = x /= pageWidth; 12019 this.y = y /= pageHeight; 12020 const [bx, by] = this.getBaseTranslation(); 12021 x += bx; 12022 y += by; 12023 style.left = `${(100 * x).toFixed(2)}%`; 12024 style.top = `${(100 * y).toFixed(2)}%`; 12025 this.moveInDOM(); 12026 } 12027 static #rotatePoint(x, y, angle) { 12028 switch (angle) { 12029 case 90: 12030 return [y, -x]; 12031 case 180: 12032 return [-x, -y]; 12033 case 270: 12034 return [-y, x]; 12035 default: 12036 return [x, y]; 12037 } 12038 } 12039 screenToPageTranslation(x, y) { 12040 return AnnotationEditor.#rotatePoint(x, y, this.parentRotation); 12041 } 12042 pageTranslationToScreen(x, y) { 12043 return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation); 12044 } 12045 #getRotationMatrix(rotation) { 12046 switch (rotation) { 12047 case 90: 12048 { 12049 const [pageWidth, pageHeight] = this.pageDimensions; 12050 return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; 12051 } 12052 case 180: 12053 return [-1, 0, 0, -1]; 12054 case 270: 12055 { 12056 const [pageWidth, pageHeight] = this.pageDimensions; 12057 return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; 12058 } 12059 default: 12060 return [1, 0, 0, 1]; 12061 } 12062 } 12063 get parentScale() { 12064 return this._uiManager.viewParameters.realScale; 12065 } 12066 get parentRotation() { 12067 return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; 12068 } 12069 get parentDimensions() { 12070 const { 12071 parentScale, 12072 pageDimensions: [pageWidth, pageHeight] 12073 } = this; 12074 return [pageWidth * parentScale, pageHeight * parentScale]; 12075 } 12076 setDims() { 12077 const { 12078 div: { 12079 style 12080 }, 12081 width, 12082 height 12083 } = this; 12084 style.width = `${(100 * width).toFixed(2)}%`; 12085 style.height = `${(100 * height).toFixed(2)}%`; 12086 } 12087 getInitialTranslation() { 12088 return [0, 0]; 12089 } 12090 #createResizers() { 12091 if (this.#resizersDiv) { 12092 return; 12093 } 12094 this.#resizersDiv = document.createElement("div"); 12095 this.#resizersDiv.classList.add("resizers"); 12096 const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"]; 12097 const signal = this._uiManager._signal; 12098 for (const name of classes) { 12099 const div = document.createElement("div"); 12100 this.#resizersDiv.append(div); 12101 div.classList.add("resizer", name); 12102 div.setAttribute("data-resizer-name", name); 12103 div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), { 12104 signal 12105 }); 12106 div.addEventListener("contextmenu", noContextMenu, { 12107 signal 12108 }); 12109 div.tabIndex = -1; 12110 } 12111 this.div.prepend(this.#resizersDiv); 12112 } 12113 #resizerPointerdown(name, event) { 12114 event.preventDefault(); 12115 const { 12116 isMac 12117 } = FeatureTest.platform; 12118 if (event.button !== 0 || event.ctrlKey && isMac) { 12119 return; 12120 } 12121 this.#altText?.toggle(false); 12122 const savedDraggable = this._isDraggable; 12123 this._isDraggable = false; 12124 this.#lastPointerCoords = [event.screenX, event.screenY]; 12125 const ac = new AbortController(); 12126 const signal = this._uiManager.combinedSignal(ac); 12127 this.parent.togglePointerEvents(false); 12128 window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), { 12129 passive: true, 12130 capture: true, 12131 signal 12132 }); 12133 window.addEventListener("touchmove", stopEvent, { 12134 passive: false, 12135 signal 12136 }); 12137 window.addEventListener("contextmenu", noContextMenu, { 12138 signal 12139 }); 12140 this.#savedDimensions = { 12141 savedX: this.x, 12142 savedY: this.y, 12143 savedWidth: this.width, 12144 savedHeight: this.height 12145 }; 12146 const savedParentCursor = this.parent.div.style.cursor; 12147 const savedCursor = this.div.style.cursor; 12148 this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; 12149 const pointerUpCallback = () => { 12150 ac.abort(); 12151 this.parent.togglePointerEvents(true); 12152 this.#altText?.toggle(true); 12153 this._isDraggable = savedDraggable; 12154 this.parent.div.style.cursor = savedParentCursor; 12155 this.div.style.cursor = savedCursor; 12156 this.#addResizeToUndoStack(); 12157 }; 12158 window.addEventListener("pointerup", pointerUpCallback, { 12159 signal 12160 }); 12161 window.addEventListener("blur", pointerUpCallback, { 12162 signal 12163 }); 12164 } 12165 #resize(x, y, width, height) { 12166 this.width = width; 12167 this.height = height; 12168 this.x = x; 12169 this.y = y; 12170 this.setDims(); 12171 this.fixAndSetPosition(); 12172 this._onResized(); 12173 } 12174 _onResized() {} 12175 #addResizeToUndoStack() { 12176 if (!this.#savedDimensions) { 12177 return; 12178 } 12179 const { 12180 savedX, 12181 savedY, 12182 savedWidth, 12183 savedHeight 12184 } = this.#savedDimensions; 12185 this.#savedDimensions = null; 12186 const newX = this.x; 12187 const newY = this.y; 12188 const newWidth = this.width; 12189 const newHeight = this.height; 12190 if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { 12191 return; 12192 } 12193 this.addCommands({ 12194 cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight), 12195 undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight), 12196 mustExec: true 12197 }); 12198 } 12199 static _round(x) { 12200 return Math.round(x * 10000) / 10000; 12201 } 12202 #resizerPointermove(name, event) { 12203 const [parentWidth, parentHeight] = this.parentDimensions; 12204 const savedX = this.x; 12205 const savedY = this.y; 12206 const savedWidth = this.width; 12207 const savedHeight = this.height; 12208 const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; 12209 const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; 12210 const rotationMatrix = this.#getRotationMatrix(this.rotation); 12211 const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; 12212 const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); 12213 const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y]; 12214 let getPoint; 12215 let getOpposite; 12216 let isDiagonal = false; 12217 let isHorizontal = false; 12218 switch (name) { 12219 case "topLeft": 12220 isDiagonal = true; 12221 getPoint = (w, h) => [0, 0]; 12222 getOpposite = (w, h) => [w, h]; 12223 break; 12224 case "topMiddle": 12225 getPoint = (w, h) => [w / 2, 0]; 12226 getOpposite = (w, h) => [w / 2, h]; 12227 break; 12228 case "topRight": 12229 isDiagonal = true; 12230 getPoint = (w, h) => [w, 0]; 12231 getOpposite = (w, h) => [0, h]; 12232 break; 12233 case "middleRight": 12234 isHorizontal = true; 12235 getPoint = (w, h) => [w, h / 2]; 12236 getOpposite = (w, h) => [0, h / 2]; 12237 break; 12238 case "bottomRight": 12239 isDiagonal = true; 12240 getPoint = (w, h) => [w, h]; 12241 getOpposite = (w, h) => [0, 0]; 12242 break; 12243 case "bottomMiddle": 12244 getPoint = (w, h) => [w / 2, h]; 12245 getOpposite = (w, h) => [w / 2, 0]; 12246 break; 12247 case "bottomLeft": 12248 isDiagonal = true; 12249 getPoint = (w, h) => [0, h]; 12250 getOpposite = (w, h) => [w, 0]; 12251 break; 12252 case "middleLeft": 12253 isHorizontal = true; 12254 getPoint = (w, h) => [0, h / 2]; 12255 getOpposite = (w, h) => [w, h / 2]; 12256 break; 12257 } 12258 const point = getPoint(savedWidth, savedHeight); 12259 const oppositePoint = getOpposite(savedWidth, savedHeight); 12260 let transfOppositePoint = transf(...oppositePoint); 12261 const oppositeX = AnnotationEditor._round(savedX + transfOppositePoint[0]); 12262 const oppositeY = AnnotationEditor._round(savedY + transfOppositePoint[1]); 12263 let ratioX = 1; 12264 let ratioY = 1; 12265 let deltaX, deltaY; 12266 if (!event.fromKeyboard) { 12267 const { 12268 screenX, 12269 screenY 12270 } = event; 12271 const [lastScreenX, lastScreenY] = this.#lastPointerCoords; 12272 [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY); 12273 this.#lastPointerCoords[0] = screenX; 12274 this.#lastPointerCoords[1] = screenY; 12275 } else { 12276 ({ 12277 deltaX, 12278 deltaY 12279 } = event); 12280 } 12281 [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); 12282 if (isDiagonal) { 12283 const oldDiag = Math.hypot(savedWidth, savedHeight); 12284 ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); 12285 } else if (isHorizontal) { 12286 ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth; 12287 } else { 12288 ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight; 12289 } 12290 const newWidth = AnnotationEditor._round(savedWidth * ratioX); 12291 const newHeight = AnnotationEditor._round(savedHeight * ratioY); 12292 transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); 12293 const newX = oppositeX - transfOppositePoint[0]; 12294 const newY = oppositeY - transfOppositePoint[1]; 12295 this.#initialRect ||= [this.x, this.y, this.width, this.height]; 12296 this.width = newWidth; 12297 this.height = newHeight; 12298 this.x = newX; 12299 this.y = newY; 12300 this.setDims(); 12301 this.fixAndSetPosition(); 12302 this._onResizing(); 12303 } 12304 _onResizing() {} 12305 altTextFinish() { 12306 this.#altText?.finish(); 12307 } 12308 get toolbarButtons() { 12309 return null; 12310 } 12311 async addEditToolbar() { 12312 if (this._editToolbar || this.#isInEditMode) { 12313 return this._editToolbar; 12314 } 12315 this._editToolbar = new EditorToolbar(this); 12316 this.div.append(this._editToolbar.render()); 12317 const { 12318 toolbarButtons 12319 } = this; 12320 if (toolbarButtons) { 12321 for (const [name, tool] of toolbarButtons) { 12322 await this._editToolbar.addButton(name, tool); 12323 } 12324 } 12325 if (!this.hasComment) { 12326 this._editToolbar.addButton("comment", this.addCommentButton()); 12327 } 12328 this._editToolbar.addButton("delete"); 12329 return this._editToolbar; 12330 } 12331 addCommentButtonInToolbar() { 12332 this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton"); 12333 } 12334 removeCommentButtonFromToolbar() { 12335 this._editToolbar?.removeButton("comment"); 12336 } 12337 removeEditToolbar() { 12338 this._editToolbar?.remove(); 12339 this._editToolbar = null; 12340 this.#altText?.destroy(); 12341 } 12342 addContainer(container) { 12343 const editToolbarDiv = this._editToolbar?.div; 12344 if (editToolbarDiv) { 12345 editToolbarDiv.before(container); 12346 } else { 12347 this.div.append(container); 12348 } 12349 } 12350 getClientDimensions() { 12351 return this.div.getBoundingClientRect(); 12352 } 12353 createAltText() { 12354 if (!this.#altText) { 12355 AltText.initialize(AnnotationEditor._l10n); 12356 this.#altText = new AltText(this); 12357 if (this.#accessibilityData) { 12358 this.#altText.data = this.#accessibilityData; 12359 this.#accessibilityData = null; 12360 } 12361 } 12362 return this.#altText; 12363 } 12364 get altTextData() { 12365 return this.#altText?.data; 12366 } 12367 set altTextData(data) { 12368 if (!this.#altText) { 12369 return; 12370 } 12371 this.#altText.data = data; 12372 } 12373 get guessedAltText() { 12374 return this.#altText?.guessedText; 12375 } 12376 async setGuessedAltText(text) { 12377 await this.#altText?.setGuessedText(text); 12378 } 12379 serializeAltText(isForCopying) { 12380 return this.#altText?.serialize(isForCopying); 12381 } 12382 hasAltText() { 12383 return !!this.#altText && !this.#altText.isEmpty(); 12384 } 12385 hasAltTextData() { 12386 return this.#altText?.hasData() ?? false; 12387 } 12388 focusCommentButton() { 12389 this.#comment?.focusButton(); 12390 } 12391 addCommentButton() { 12392 return this.canAddComment ? this.#comment ||= new Comment(this) : null; 12393 } 12394 addStandaloneCommentButton() { 12395 if (!this._uiManager.hasCommentManager()) { 12396 return; 12397 } 12398 if (this.#commentStandaloneButton) { 12399 if (this._uiManager.isEditingMode()) { 12400 this.#commentStandaloneButton.classList.remove("hidden"); 12401 } 12402 return; 12403 } 12404 if (!this.hasComment) { 12405 return; 12406 } 12407 this.#commentStandaloneButton = this.#comment.renderForStandalone(); 12408 this.div.append(this.#commentStandaloneButton); 12409 } 12410 removeStandaloneCommentButton() { 12411 this.#comment.removeStandaloneCommentButton(); 12412 this.#commentStandaloneButton = null; 12413 } 12414 hideStandaloneCommentButton() { 12415 this.#commentStandaloneButton?.classList.add("hidden"); 12416 } 12417 get comment() { 12418 if (!this.#comment) { 12419 return null; 12420 } 12421 const { 12422 data: { 12423 richText, 12424 text, 12425 date, 12426 deleted 12427 } 12428 } = this.#comment; 12429 return { 12430 text, 12431 richText, 12432 date, 12433 deleted, 12434 color: this.getNonHCMColor(), 12435 opacity: this.opacity ?? 1 12436 }; 12437 } 12438 set comment(value) { 12439 this.#comment ||= new Comment(this); 12440 if (typeof value === "object" && value !== null) { 12441 this.#comment.restoreData(value); 12442 } else { 12443 this.#comment.data = value; 12444 } 12445 if (this.hasComment) { 12446 this.removeCommentButtonFromToolbar(); 12447 this.addStandaloneCommentButton(); 12448 this._uiManager.updateComment(this); 12449 } else { 12450 this.addCommentButtonInToolbar(); 12451 this.removeStandaloneCommentButton(); 12452 this._uiManager.removeComment(this); 12453 } 12454 } 12455 setCommentData({ 12456 comment, 12457 popupRef, 12458 richText 12459 }) { 12460 if (!popupRef) { 12461 return; 12462 } 12463 this.#comment ||= new Comment(this); 12464 this.#comment.setInitialText(comment, richText); 12465 if (!this.annotationElementId) { 12466 return; 12467 } 12468 const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId); 12469 if (storedData) { 12470 this.updateFromAnnotationLayer(storedData); 12471 } 12472 } 12473 get hasEditedComment() { 12474 return this.#comment?.hasBeenEdited(); 12475 } 12476 get hasDeletedComment() { 12477 return this.#comment?.isDeleted(); 12478 } 12479 get hasComment() { 12480 return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted(); 12481 } 12482 async editComment(options) { 12483 this.#comment ||= new Comment(this); 12484 this.#comment.edit(options); 12485 } 12486 toggleComment(isSelected, visibility = undefined) { 12487 if (this.hasComment) { 12488 this._uiManager.toggleComment(this, isSelected, visibility); 12489 } 12490 } 12491 setSelectedCommentButton(selected) { 12492 this.#comment.setSelectedButton(selected); 12493 } 12494 addComment(serialized) { 12495 if (this.hasEditedComment) { 12496 const DEFAULT_POPUP_WIDTH = 180; 12497 const DEFAULT_POPUP_HEIGHT = 100; 12498 const [,,, trY] = serialized.rect; 12499 const [pageWidth] = this.pageDimensions; 12500 const [pageX] = this.pageTranslation; 12501 const blX = pageX + pageWidth + 1; 12502 const blY = trY - DEFAULT_POPUP_HEIGHT; 12503 const trX = blX + DEFAULT_POPUP_WIDTH; 12504 serialized.popup = { 12505 contents: this.comment.text, 12506 deleted: this.comment.deleted, 12507 rect: [blX, blY, trX, trY] 12508 }; 12509 } 12510 } 12511 updateFromAnnotationLayer({ 12512 popup: { 12513 contents, 12514 deleted 12515 } 12516 }) { 12517 this.#comment.data = deleted ? null : contents; 12518 } 12519 get parentBoundingClientRect() { 12520 return this.parent.boundingClientRect; 12521 } 12522 render() { 12523 const div = this.div = document.createElement("div"); 12524 div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); 12525 div.className = this.name; 12526 div.setAttribute("id", this.id); 12527 div.tabIndex = this.#disabled ? -1 : 0; 12528 div.setAttribute("role", "application"); 12529 if (this.defaultL10nId) { 12530 div.setAttribute("data-l10n-id", this.defaultL10nId); 12531 } 12532 if (!this._isVisible) { 12533 div.classList.add("hidden"); 12534 } 12535 this.setInForeground(); 12536 this.#addFocusListeners(); 12537 const [parentWidth, parentHeight] = this.parentDimensions; 12538 if (this.parentRotation % 180 !== 0) { 12539 div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; 12540 div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; 12541 } 12542 const [tx, ty] = this.getInitialTranslation(); 12543 this.translate(tx, ty); 12544 bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]); 12545
vendor: 3,341 bytes, lines 12545-12638
12545if (this.isResizable && this._uiManager._supportsPinchToZoom) { 12546 this.#touchManager ||= new TouchManager({ 12547 container: div, 12548 isPinchingDisabled: () => !this.isSelected, 12549 onPinchStart: this.#touchPinchStartCallback.bind(this), 12550 onPinching: this.#touchPinchCallback.bind(this), 12551 onPinchEnd: this.#touchPinchEndCallback.bind(this), 12552 signal: this._uiManager._signal 12553 }); 12554 } 12555 this.addStandaloneCommentButton(); 12556 this._uiManager._editorUndoBar?.hide(); 12557 return div; 12558 } 12559 #touchPinchStartCallback() { 12560 this.#savedDimensions = { 12561 savedX: this.x, 12562 savedY: this.y, 12563 savedWidth: this.width, 12564 savedHeight: this.height 12565 }; 12566 this.#altText?.toggle(false); 12567 this.parent.togglePointerEvents(false); 12568 } 12569 #touchPinchCallback(_origin, prevDistance, distance) { 12570 const slowDownFactor = 0.7; 12571 let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor; 12572 if (factor === 1) { 12573 return; 12574 } 12575 const rotationMatrix = this.#getRotationMatrix(this.rotation); 12576 const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; 12577 const [parentWidth, parentHeight] = this.parentDimensions; 12578 const savedX = this.x; 12579 const savedY = this.y; 12580 const savedWidth = this.width; 12581 const savedHeight = this.height; 12582 const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; 12583 const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; 12584 factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); 12585 const newWidth = AnnotationEditor._round(savedWidth * factor); 12586 const newHeight = AnnotationEditor._round(savedHeight * factor); 12587 if (newWidth === savedWidth && newHeight === savedHeight) { 12588 return; 12589 } 12590 this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight]; 12591 const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2); 12592 const centerX = AnnotationEditor._round(savedX + transfCenterPoint[0]); 12593 const centerY = AnnotationEditor._round(savedY + transfCenterPoint[1]); 12594 const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2); 12595 this.x = centerX - newTransfCenterPoint[0]; 12596 this.y = centerY - newTransfCenterPoint[1]; 12597 this.width = newWidth; 12598 this.height = newHeight; 12599 this.setDims(); 12600 this.fixAndSetPosition(); 12601 this._onResizing(); 12602 } 12603 #touchPinchEndCallback() { 12604 this.#altText?.toggle(true); 12605 this.parent.togglePointerEvents(true); 12606 this.#addResizeToUndoStack(); 12607 } 12608 pointerdown(event) { 12609 const { 12610 isMac 12611 } = FeatureTest.platform; 12612 if (event.button !== 0 || event.ctrlKey && isMac) { 12613 event.preventDefault(); 12614 return; 12615 } 12616 this.#hasBeenClicked = true; 12617 if (this._isDraggable) { 12618 this.#setUpDragSession(event); 12619 return; 12620 } 12621 this.#selectOnPointerEvent(event); 12622 } 12623 #selectOnPointerEvent(event) { 12624 const { 12625 isMac 12626 } = FeatureTest.platform; 12627 if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { 12628 this.parent.toggleSelected(this); 12629 } else { 12630 this.parent.setSelected(this); 12631 } 12632 } 12633 #setUpDragSession(event) { 12634 const { 12635 isSelected 12636 } = this; 12637 this._uiManager.setUpDragSession(); 12638 let hasDraggingStarted = false;
vendor: 8,205 bytes, lines 12639-12930
12639 const ac = new AbortController(); 12640 const signal = this._uiManager.combinedSignal(ac); 12641 const opts = { 12642 capture: true, 12643 passive: false, 12644 signal 12645 }; 12646 const cancelDrag = e => { 12647 ac.abort(); 12648 this.#dragPointerId = null; 12649 this.#hasBeenClicked = false; 12650 if (!this._uiManager.endDragSession()) { 12651 this.#selectOnPointerEvent(e); 12652 } 12653 if (hasDraggingStarted) { 12654 this._onStopDragging(); 12655 } 12656 }; 12657 if (isSelected) { 12658 this.#prevDragX = event.clientX; 12659 this.#prevDragY = event.clientY; 12660 this.#dragPointerId = event.pointerId; 12661 this.#dragPointerType = event.pointerType; 12662 window.addEventListener("pointermove", e => { 12663 if (!hasDraggingStarted) { 12664 hasDraggingStarted = true; 12665 this._uiManager.toggleComment(this, true, false); 12666 this._onStartDragging(); 12667 } 12668 const { 12669 clientX: x, 12670 clientY: y, 12671 pointerId 12672 } = e; 12673 if (pointerId !== this.#dragPointerId) { 12674 stopEvent(e); 12675 return; 12676 } 12677 const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY); 12678 this.#prevDragX = x; 12679 this.#prevDragY = y; 12680 this._uiManager.dragSelectedEditors(tx, ty); 12681 }, opts); 12682 window.addEventListener("touchmove", stopEvent, opts); 12683 window.addEventListener("pointerdown", e => { 12684 if (e.pointerType === this.#dragPointerType) { 12685 if (this.#touchManager || e.isPrimary) { 12686 cancelDrag(e); 12687 } 12688 } 12689 stopEvent(e); 12690 }, opts); 12691 } 12692 const pointerUpCallback = e => { 12693 if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) { 12694 cancelDrag(e); 12695 return; 12696 } 12697 stopEvent(e); 12698 }; 12699 window.addEventListener("pointerup", pointerUpCallback, { 12700 signal 12701 }); 12702 window.addEventListener("blur", pointerUpCallback, { 12703 signal 12704 }); 12705 } 12706 _onStartDragging() {} 12707 _onStopDragging() {} 12708 moveInDOM() { 12709 if (this.#moveInDOMTimeout) { 12710 clearTimeout(this.#moveInDOMTimeout); 12711 } 12712 this.#moveInDOMTimeout = setTimeout(() => { 12713 this.#moveInDOMTimeout = null; 12714 this.parent?.moveEditorInDOM(this); 12715 }, 0); 12716 } 12717 _setParentAndPosition(parent, x, y) { 12718 parent.changeParent(this); 12719 this.x = x; 12720 this.y = y; 12721 this.fixAndSetPosition(); 12722 this._onTranslated(); 12723 } 12724 getRect(tx, ty, rotation = this.rotation) { 12725 const scale = this.parentScale; 12726 const [pageWidth, pageHeight] = this.pageDimensions; 12727 const [pageX, pageY] = this.pageTranslation; 12728 const shiftX = tx / scale; 12729 const shiftY = ty / scale; 12730 const x = this.x * pageWidth; 12731 const y = this.y * pageHeight; 12732 const width = this.width * pageWidth; 12733 const height = this.height * pageHeight; 12734 switch (rotation) { 12735 case 0: 12736 return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY]; 12737 case 90: 12738 return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY]; 12739 case 180: 12740 return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY]; 12741 case 270: 12742 return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY]; 12743 default: 12744 throw new Error("Invalid rotation"); 12745 } 12746 } 12747 getRectInCurrentCoords(rect, pageHeight) { 12748 const [x1, y1, x2, y2] = rect; 12749 const width = x2 - x1; 12750 const height = y2 - y1; 12751 switch (this.rotation) { 12752 case 0: 12753 return [x1, pageHeight - y2, width, height]; 12754 case 90: 12755 return [x1, pageHeight - y1, height, width]; 12756 case 180: 12757 return [x2, pageHeight - y1, width, height]; 12758 case 270: 12759 return [x2, pageHeight - y2, height, width]; 12760 default: 12761 throw new Error("Invalid rotation"); 12762 } 12763 } 12764 getPDFRect() { 12765 return this.getRect(0, 0); 12766 } 12767 getNonHCMColor() { 12768 return this.color && AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); 12769 } 12770 onUpdatedColor() { 12771 this.#comment?.onUpdatedColor(); 12772 } 12773 getData() { 12774 const { 12775 comment: { 12776 text: str, 12777 color, 12778 date, 12779 opacity, 12780 deleted, 12781 richText 12782 }, 12783 uid: id, 12784 pageIndex, 12785 creationDate, 12786 modificationDate 12787 } = this; 12788 return { 12789 id, 12790 pageIndex, 12791 rect: this.getPDFRect(), 12792 richText, 12793 contentsObj: { 12794 str 12795 }, 12796 creationDate, 12797 modificationDate: date || modificationDate, 12798 popupRef: !deleted, 12799 color, 12800 opacity 12801 }; 12802 } 12803 onceAdded(focus) {} 12804 isEmpty() { 12805 return false; 12806 } 12807 enableEditMode() { 12808 if (this.isInEditMode()) { 12809 return false; 12810 } 12811 this.parent.setEditingState(false); 12812 this.#isInEditMode = true; 12813 return true; 12814 } 12815 disableEditMode() { 12816 if (!this.isInEditMode()) { 12817 return false; 12818 } 12819 this.parent.setEditingState(true); 12820 this.#isInEditMode = false; 12821 return true; 12822 } 12823 isInEditMode() { 12824 return this.#isInEditMode; 12825 } 12826 shouldGetKeyboardEvents() { 12827 return this.#isResizerEnabledForKeyboard; 12828 } 12829 needsToBeRebuilt() { 12830 return this.div && !this.isAttachedToDOM; 12831 } 12832 get isOnScreen() { 12833 const { 12834 top, 12835 left, 12836 bottom, 12837 right 12838 } = this.getClientDimensions(); 12839 const { 12840 innerHeight, 12841 innerWidth 12842 } = window; 12843 return left < innerWidth && right > 0 && top < innerHeight && bottom > 0; 12844 } 12845 #addFocusListeners() { 12846 if (this.#focusAC || !this.div) { 12847 return; 12848 } 12849 this.#focusAC = new AbortController(); 12850 const signal = this._uiManager.combinedSignal(this.#focusAC); 12851 this.div.addEventListener("focusin", this.focusin.bind(this), { 12852 signal 12853 }); 12854 this.div.addEventListener("focusout", this.focusout.bind(this), { 12855 signal 12856 }); 12857 } 12858 rebuild() { 12859 this.#addFocusListeners(); 12860 } 12861 rotate(_angle) {} 12862 resize() {} 12863 serializeDeleted() { 12864 return { 12865 id: this.annotationElementId, 12866 deleted: true, 12867 pageIndex: this.pageIndex, 12868 popupRef: this._initialData?.popupRef || "" 12869 }; 12870 } 12871 serialize(isForCopying = false, context = null) { 12872 return { 12873 annotationType: this.mode, 12874 pageIndex: this.pageIndex, 12875 rect: this.getPDFRect(), 12876 rotation: this.rotation, 12877 structTreeParentId: this._structTreeParentId, 12878 popupRef: this._initialData?.popupRef || "" 12879 }; 12880 } 12881 static async deserialize(data, parent, uiManager) { 12882 const editor = new this.prototype.constructor({ 12883 parent, 12884 id: parent.getNextId(), 12885 uiManager, 12886 annotationElementId: data.annotationElementId, 12887 creationDate: data.creationDate, 12888 modificationDate: data.modificationDate 12889 }); 12890 editor.rotation = data.rotation; 12891 editor.#accessibilityData = data.accessibilityData; 12892 editor._isCopy = data.isCopy || false; 12893 const [pageWidth, pageHeight] = editor.pageDimensions; 12894 const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); 12895 editor.x = x / pageWidth; 12896 editor.y = y / pageHeight; 12897 editor.width = width / pageWidth; 12898 editor.height = height / pageHeight; 12899 return editor; 12900 } 12901 get hasBeenModified() { 12902 return !!this.annotationElementId && (this.deleted || this.serialize() !== null); 12903 } 12904 remove() { 12905 this.#focusAC?.abort(); 12906 this.#focusAC = null; 12907 if (!this.isEmpty()) { 12908 this.commit(); 12909 } 12910 if (this.parent) { 12911 this.parent.remove(this); 12912 } else { 12913 this._uiManager.removeEditor(this); 12914 } 12915 this.hideCommentPopup(); 12916 if (this.#moveInDOMTimeout) { 12917 clearTimeout(this.#moveInDOMTimeout); 12918 this.#moveInDOMTimeout = null; 12919 } 12920 this.#stopResizing(); 12921 this.removeEditToolbar(); 12922 if (this.#telemetryTimeouts) { 12923 for (const timeout of this.#telemetryTimeouts.values()) { 12924 clearTimeout(timeout); 12925 } 12926 this.#telemetryTimeouts = null; 12927 } 12928 this.parent = null; 12929 this.#touchManager?.destroy(); 12930 this.#touchManager
vendor: 9,812 bytes, lines 12930-13286
12930 = null; 12931 this.#fakeAnnotation?.remove(); 12932 this.#fakeAnnotation = null; 12933 } 12934 get isResizable() { 12935 return false; 12936 } 12937 makeResizable() { 12938 if (this.isResizable) { 12939 this.#createResizers(); 12940 this.#resizersDiv.classList.remove("hidden"); 12941 } 12942 } 12943 get toolbarPosition() { 12944 return null; 12945 } 12946 get commentButtonPosition() { 12947 return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0]; 12948 } 12949 get commentButtonPositionInPage() { 12950 const { 12951 commentButtonPosition: [posX, posY] 12952 } = this; 12953 const [blX, blY, trX, trY] = this.getPDFRect(); 12954 return [AnnotationEditor._round(blX + (trX - blX) * posX), AnnotationEditor._round(blY + (trY - blY) * (1 - posY))]; 12955 } 12956 get commentButtonColor() { 12957 return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity); 12958 } 12959 get commentPopupPosition() { 12960 return this.#comment.commentPopupPositionInLayer; 12961 } 12962 set commentPopupPosition(pos) { 12963 this.#comment.commentPopupPositionInLayer = pos; 12964 } 12965 hasDefaultPopupPosition() { 12966 return this.#comment.hasDefaultPopupPosition(); 12967 } 12968 get commentButtonWidth() { 12969 return this.#comment.commentButtonWidth; 12970 } 12971 get elementBeforePopup() { 12972 return this.div; 12973 } 12974 setCommentButtonStates(options) { 12975 this.#comment?.setCommentButtonStates(options); 12976 } 12977 keydown(event) { 12978 if (!this.isResizable || event.target !== this.div || event.key !== "Enter") { 12979 return; 12980 } 12981 this._uiManager.setSelected(this); 12982 this.#savedDimensions = { 12983 savedX: this.x, 12984 savedY: this.y, 12985 savedWidth: this.width, 12986 savedHeight: this.height 12987 }; 12988 const children = this.#resizersDiv.children; 12989 if (!this.#allResizerDivs) { 12990 this.#allResizerDivs = Array.from(children); 12991 const boundResizerKeydown = this.#resizerKeydown.bind(this); 12992 const boundResizerBlur = this.#resizerBlur.bind(this); 12993 const signal = this._uiManager._signal; 12994 for (const div of this.#allResizerDivs) { 12995 const name = div.getAttribute("data-resizer-name"); 12996 div.setAttribute("role", "spinbutton"); 12997 div.addEventListener("keydown", boundResizerKeydown, { 12998 signal 12999 }); 13000 div.addEventListener("blur", boundResizerBlur, { 13001 signal 13002 }); 13003 div.addEventListener("focus", this.#resizerFocus.bind(this, name), { 13004 signal 13005 }); 13006 div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); 13007 } 13008 } 13009 const first = this.#allResizerDivs[0]; 13010 let firstPosition = 0; 13011 for (const div of children) { 13012 if (div === first) { 13013 break; 13014 } 13015 firstPosition++; 13016 } 13017 const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4); 13018 if (nextFirstPosition !== firstPosition) { 13019 if (nextFirstPosition < firstPosition) { 13020 for (let i = 0; i < firstPosition - nextFirstPosition; i++) { 13021 this.#resizersDiv.append(this.#resizersDiv.firstElementChild); 13022 } 13023 } else if (nextFirstPosition > firstPosition) { 13024 for (let i = 0; i < nextFirstPosition - firstPosition; i++) { 13025 this.#resizersDiv.firstElementChild.before(this.#resizersDiv.lastElementChild); 13026 } 13027 } 13028 let i = 0; 13029 for (const child of children) { 13030 const div = this.#allResizerDivs[i++]; 13031 const name = div.getAttribute("data-resizer-name"); 13032 child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); 13033 } 13034 } 13035 this.#setResizerTabIndex(0); 13036 this.#isResizerEnabledForKeyboard = true; 13037 this.#resizersDiv.firstElementChild.focus({ 13038 focusVisible: true 13039 }); 13040 event.preventDefault(); 13041 event.stopImmediatePropagation(); 13042 } 13043 #resizerKeydown(event) { 13044 AnnotationEditor._resizerKeyboardManager.exec(this, event); 13045 } 13046 #resizerBlur(event) { 13047 if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) { 13048 this.#stopResizing(); 13049 } 13050 } 13051 #resizerFocus(name) { 13052 this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : ""; 13053 } 13054 #setResizerTabIndex(value) { 13055 if (!this.#allResizerDivs) { 13056 return; 13057 } 13058 for (const div of this.#allResizerDivs) { 13059 div.tabIndex = value; 13060 } 13061 } 13062 _resizeWithKeyboard(x, y) { 13063 if (!this.#isResizerEnabledForKeyboard) { 13064 return; 13065 } 13066 this.#resizerPointermove(this.#focusedResizerName, { 13067 deltaX: x, 13068 deltaY: y, 13069 fromKeyboard: true 13070 }); 13071 } 13072 #stopResizing() { 13073 this.#isResizerEnabledForKeyboard = false; 13074 this.#setResizerTabIndex(-1); 13075 this.#addResizeToUndoStack(); 13076 } 13077 _stopResizingWithKeyboard() { 13078 this.#stopResizing(); 13079 this.div.focus(); 13080 } 13081 select() { 13082 if (this.isSelected && this._editToolbar) { 13083 this._editToolbar.show(); 13084 return; 13085 } 13086 this.isSelected = true; 13087 this.makeResizable(); 13088 this.div?.classList.add("selectedEditor"); 13089 if (!this._editToolbar) { 13090 this.addEditToolbar().then(() => { 13091 if (this.div?.classList.contains("selectedEditor")) { 13092 this._editToolbar?.show(); 13093 } 13094 }); 13095 return; 13096 } 13097 this._editToolbar?.show(); 13098 this.#altText?.toggleAltTextBadge(false); 13099 } 13100 focus() { 13101 if (this.div && !this.div.contains(document.activeElement)) { 13102 setTimeout(() => this.div?.focus({ 13103 preventScroll: true 13104 }), 0); 13105 } 13106 } 13107 unselect() { 13108 if (!this.isSelected) { 13109 return; 13110 } 13111 this.isSelected = false; 13112 this.#resizersDiv?.classList.add("hidden"); 13113 this.div?.classList.remove("selectedEditor"); 13114 if (this.div?.contains(document.activeElement)) { 13115 this._uiManager.currentLayer.div.focus({ 13116 preventScroll: true 13117 }); 13118 } 13119 this._editToolbar?.hide(); 13120 this.#altText?.toggleAltTextBadge(true); 13121 this.hideCommentPopup(); 13122 } 13123 hideCommentPopup() { 13124 if (this.hasComment) { 13125 this._uiManager.toggleComment(null); 13126 } 13127 } 13128 updateParams(type, value) {} 13129 disableEditing() {} 13130 enableEditing() {} 13131 get canChangeContent() { 13132 return false; 13133 } 13134 enterInEditMode() { 13135 if (!this.canChangeContent) { 13136 return; 13137 } 13138 this.enableEditMode(); 13139 this.div.focus(); 13140 } 13141 dblclick(event) { 13142 if (event.target.nodeName === "BUTTON") { 13143 return; 13144 } 13145 this.enterInEditMode(); 13146 this.parent.updateToolbar({ 13147 mode: this.constructor._editorType, 13148 editId: this.uid 13149 }); 13150 } 13151 getElementForAltText() { 13152 return this.div; 13153 } 13154 get contentDiv() { 13155 return this.div; 13156 } 13157 get isEditing() { 13158 return this.#isEditing; 13159 } 13160 set isEditing(value) { 13161 this.#isEditing = value; 13162 if (!this.parent) { 13163 return; 13164 } 13165 if (value) { 13166 this.parent.setSelected(this); 13167 this.parent.setActiveEditor(this); 13168 } else { 13169 this.parent.setActiveEditor(null); 13170 } 13171 } 13172 static get MIN_SIZE() { 13173 return 16; 13174 } 13175 static canCreateNewEmptyEditor() { 13176 return true; 13177 } 13178 get telemetryInitialData() { 13179 return { 13180 action: "added" 13181 }; 13182 } 13183 get telemetryFinalData() { 13184 return null; 13185 } 13186 _reportTelemetry(data, mustWait = false) { 13187 if (mustWait) { 13188 this.#telemetryTimeouts ||= new Map(); 13189 const { 13190 action 13191 } = data; 13192 let timeout = this.#telemetryTimeouts.get(action); 13193 if (timeout) { 13194 clearTimeout(timeout); 13195 } 13196 timeout = setTimeout(() => { 13197 this._reportTelemetry(data); 13198 this.#telemetryTimeouts.delete(action); 13199 if (this.#telemetryTimeouts.size === 0) { 13200 this.#telemetryTimeouts = null; 13201 } 13202 }, AnnotationEditor._telemetryTimeout); 13203 this.#telemetryTimeouts.set(action, timeout); 13204 return; 13205 } 13206 data.type ||= this.editorType; 13207 this._uiManager._eventBus.dispatch("reporttelemetry", { 13208 source: this, 13209 details: { 13210 type: "editing", 13211 data 13212 } 13213 }); 13214 } 13215 show(visible = this._isVisible) { 13216 this.div.classList.toggle("hidden", !visible); 13217 this._isVisible = visible; 13218 } 13219 enable() { 13220 if (this.div) { 13221 this.div.tabIndex = 0; 13222 } 13223 this.#disabled = false; 13224 } 13225 disable() { 13226 if (this.div) { 13227 this.div.tabIndex = -1; 13228 } 13229 this.#disabled = true; 13230 } 13231 updateFakeAnnotationElement(annotationLayer) { 13232 if (!this.#fakeAnnotation && !this.deleted) { 13233 this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this); 13234 return; 13235 } 13236 if (this.deleted) { 13237 this.#fakeAnnotation.remove(); 13238 this.#fakeAnnotation = null; 13239 return; 13240 } 13241 if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) { 13242 this.#fakeAnnotation.updateEdited({ 13243 rect: this.getPDFRect(), 13244 popup: this.comment 13245 }); 13246 } 13247 } 13248 renderAnnotationElement(annotation) { 13249 if (this.deleted) { 13250 annotation.hide(); 13251 return null; 13252 } 13253 let content = annotation.container.querySelector(".annotationContent"); 13254 if (!content) { 13255 content = document.createElement("div"); 13256 content.classList.add("annotationContent", this.editorType); 13257 annotation.container.prepend(content); 13258 } else if (content.nodeName === "CANVAS") { 13259 const canvas = content; 13260 content = document.createElement("div"); 13261 content.classList.add("annotationContent", this.editorType); 13262 canvas.before(content); 13263 } 13264 return content; 13265 } 13266 resetAnnotationElement(annotation) { 13267 const { 13268 firstElementChild 13269 } = annotation.container; 13270 if (firstElementChild?.nodeName === "DIV" && firstElementChild.classList.contains("annotationContent")) { 13271 firstElementChild.remove(); 13272 } 13273 } 13274} 13275class FakeEditor extends AnnotationEditor { 13276 constructor(params) { 13277 super(params); 13278 this.annotationElementId = params.annotationElementId; 13279 this.deleted = true; 13280 } 13281 serialize() { 13282 return this.serializeDeleted(); 13283 } 13284} 13285 13286;// ./src/shared/murmurhash3.js
vendor: 3,062 bytes, lines 13287-13411
13287 13288 13289 13290 13291 13292 13293 13294 13295const SEED = 0xc3d2e1f0; 13296const MASK_HIGH = 0xffff0000; 13297const MASK_LOW = 0xffff; 13298class MurmurHash3_64 { 13299 constructor(seed) { 13300 this.h1 = seed ? seed & 0xffffffff : SEED; 13301 this.h2 = seed ? seed & 0xffffffff : SEED; 13302 } 13303 update(input) { 13304 let data, length; 13305 if (typeof input === "string") { 13306 data = new Uint8Array(input.length * 2); 13307 length = 0; 13308 for (let i = 0, ii = input.length; i < ii; i++) { 13309 const code = input.charCodeAt(i); 13310 if (code <= 0xff) { 13311 data[length++] = code; 13312 } else { 13313 data[length++] = code >>> 8; 13314 data[length++] = code & 0xff; 13315 } 13316 } 13317 } else if (ArrayBuffer.isView(input)) { 13318 data = input.slice(); 13319 length = data.byteLength; 13320 } else { 13321 throw new Error("Invalid data format, must be a string or TypedArray."); 13322 } 13323 const blockCounts = length >> 2; 13324 const tailLength = length - blockCounts * 4; 13325 const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts); 13326 let k1 = 0, 13327 k2 = 0; 13328 let h1 = this.h1, 13329 h2 = this.h2; 13330 const C1 = 0xcc9e2d51, 13331 C2 = 0x1b873593; 13332 const C1_LOW = C1 & MASK_LOW, 13333 C2_LOW = C2 & MASK_LOW; 13334 for (let i = 0; i < blockCounts; i++) { 13335 if (i & 1) { 13336 k1 = dataUint32[i]; 13337 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; 13338 k1 = k1 << 15 | k1 >>> 17; 13339 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; 13340 h1 ^= k1; 13341 h1 = h1 << 13 | h1 >>> 19; 13342 h1 = h1 * 5 + 0xe6546b64; 13343 } else { 13344 k2 = dataUint32[i]; 13345 k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW; 13346 k2 = k2 << 15 | k2 >>> 17; 13347 k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW; 13348 h2 ^= k2; 13349 h2 = h2 << 13 | h2 >>> 19; 13350 h2 = h2 * 5 + 0xe6546b64; 13351 } 13352 } 13353 k1 = 0; 13354 switch (tailLength) { 13355 case 3: 13356 k1 ^= data[blockCounts * 4 + 2] << 16; 13357 case 2: 13358 k1 ^= data[blockCounts * 4 + 1] << 8; 13359 case 1: 13360 k1 ^= data[blockCounts * 4]; 13361 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; 13362 k1 = k1 << 15 | k1 >>> 17; 13363 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; 13364 if (blockCounts & 1) { 13365 h1 ^= k1; 13366 } else { 13367 h2 ^= k1; 13368 } 13369 } 13370 this.h1 = h1; 13371 this.h2 = h2; 13372 } 13373 hexdigest() { 13374 let h1 = this.h1, 13375 h2 = this.h2; 13376 h1 ^= h2 >>> 1; 13377 h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW; 13378 h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16; 13379 h1 ^= h2 >>> 1; 13380 h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW; 13381 h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16; 13382 h1 ^= h2 >>> 1; 13383 return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); 13384 } 13385} 13386 13387;// ./src/display/annotation_storage.js 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405const SerializableEmpty = Object.freeze({ 13406 map: null, 13407 hash: "", 13408 transfer: undefined 13409}); 13410class AnnotationStorage { 13411 #modified = false;
vendor: 4,101 bytes, lines 13412-13564
13412 #modifiedIds = null; 13413 #editorsMap = null; 13414 #storage = new Map(); 13415 onSetModified = null; 13416 onResetModified = null; 13417 onAnnotationEditor = null; 13418 getValue(key, defaultValue) { 13419 const value = this.#storage.get(key); 13420 if (value === undefined) { 13421 return defaultValue; 13422 } 13423 return Object.assign(defaultValue, value); 13424 } 13425 getRawValue(key) { 13426 return this.#storage.get(key); 13427 } 13428 remove(key) { 13429 const storedValue = this.#storage.get(key); 13430 if (storedValue === undefined) { 13431 return; 13432 } 13433 if (storedValue instanceof AnnotationEditor) { 13434 this.#editorsMap.delete(storedValue.annotationElementId); 13435 } 13436 this.#storage.delete(key); 13437 if (this.#storage.size === 0) { 13438 this.resetModified(); 13439 } 13440 if (typeof this.onAnnotationEditor === "function") { 13441 for (const value of this.#storage.values()) { 13442 if (value instanceof AnnotationEditor) { 13443 return; 13444 } 13445 } 13446 this.onAnnotationEditor(null); 13447 } 13448 } 13449 setValue(key, value) { 13450 const obj = this.#storage.get(key); 13451 let modified = false; 13452 if (obj !== undefined) { 13453 for (const [entry, val] of Object.entries(value)) { 13454 if (obj[entry] !== val) { 13455 modified = true; 13456 obj[entry] = val; 13457 } 13458 } 13459 } else { 13460 modified = true; 13461 this.#storage.set(key, value); 13462 } 13463 if (modified) { 13464 this.#setModified(); 13465 } 13466 if (value instanceof AnnotationEditor) { 13467 (this.#editorsMap ||= new Map()).set(value.annotationElementId, value); 13468 if (typeof this.onAnnotationEditor === "function") { 13469 this.onAnnotationEditor(value.constructor._type); 13470 } 13471 } 13472 } 13473 has(key) { 13474 return this.#storage.has(key); 13475 } 13476 get size() { 13477 return this.#storage.size; 13478 } 13479 #setModified() { 13480 if (!this.#modified) { 13481 this.#modified = true; 13482 if (typeof this.onSetModified === "function") { 13483 this.onSetModified(); 13484 } 13485 } 13486 } 13487 resetModified() { 13488 if (this.#modified) { 13489 this.#modified = false; 13490 if (typeof this.onResetModified === "function") { 13491 this.onResetModified(); 13492 } 13493 } 13494 } 13495 get print() { 13496 return new PrintAnnotationStorage(this); 13497 } 13498 get serializable() { 13499 if (this.#storage.size === 0) { 13500 return SerializableEmpty; 13501 } 13502 const map = new Map(), 13503 hash = new MurmurHash3_64(), 13504 transfer = []; 13505 const context = Object.create(null); 13506 let hasBitmap = false; 13507 for (const [key, val] of this.#storage) { 13508 const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val; 13509 if (val.page) { 13510 val.pageIndex = val.page._pageIndex; 13511 delete val.page; 13512 } 13513 if (serialized) { 13514 map.set(key, serialized); 13515 hash.update(`${key}:${JSON.stringify(serialized)}`); 13516 hasBitmap ||= !!serialized.bitmap; 13517 } 13518 } 13519 if (hasBitmap) { 13520 for (const value of map.values()) { 13521 if (value.bitmap) { 13522 transfer.push(value.bitmap); 13523 } 13524 } 13525 } 13526 return map.size > 0 ? { 13527 map, 13528 hash: hash.hexdigest(), 13529 transfer 13530 } : SerializableEmpty; 13531 } 13532 get editorStats() { 13533 let stats = null; 13534 const typeToEditor = new Map(); 13535 let numberOfEditedComments = 0; 13536 let numberOfDeletedComments = 0; 13537 for (const value of this.#storage.values()) { 13538 if (!(value instanceof AnnotationEditor)) { 13539 if (value.popup) { 13540 if (value.popup.deleted) { 13541 numberOfDeletedComments += 1; 13542 } else { 13543 numberOfEditedComments += 1; 13544 } 13545 } 13546 continue; 13547 } 13548 if (value.isCommentDeleted) { 13549 numberOfDeletedComments += 1; 13550 } else if (value.hasEditedComment) { 13551 numberOfEditedComments += 1; 13552 } 13553 const editorStats = value.telemetryFinalData; 13554 if (!editorStats) { 13555 continue; 13556 } 13557 const { 13558 type 13559 } = editorStats; 13560 if (!typeToEditor.has(type)) { 13561 typeToEditor.set(type, Object.getPrototypeOf(value).constructor); 13562 } 13563 stats ||= Object.create(null); 13564 const map = stats[type] ||= new Map();
vendor: 8,152 bytes, lines 13565-13810
13565 for (const [key, val] of Object.entries(editorStats)) { 13566 if (key === "type") { 13567 continue; 13568 } 13569 const counters = map.getOrInsertComputed(key, makeMap); 13570 counters.set(val, (counters.get(val) ?? 0) + 1); 13571 } 13572 } 13573 if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) { 13574 stats ||= Object.create(null); 13575 stats.comments = { 13576 deleted: numberOfDeletedComments, 13577 edited: numberOfEditedComments 13578 }; 13579 } 13580 if (!stats) { 13581 return null; 13582 } 13583 for (const [type, editor] of typeToEditor) { 13584 stats[type] = editor.computeTelemetryFinalData(stats[type]); 13585 } 13586 return stats; 13587 } 13588 resetModifiedIds() { 13589 this.#modifiedIds = null; 13590 } 13591 updateEditor(annotationId, data) { 13592 const value = this.#editorsMap?.get(annotationId); 13593 if (value) { 13594 value.updateFromAnnotationLayer(data); 13595 return true; 13596 } 13597 return false; 13598 } 13599 getEditor(annotationId) { 13600 return this.#editorsMap?.get(annotationId) || null; 13601 } 13602 get modifiedIds() { 13603 if (this.#modifiedIds) { 13604 return this.#modifiedIds; 13605 } 13606 const ids = []; 13607 if (this.#editorsMap) { 13608 for (const value of this.#editorsMap.values()) { 13609 if (!value.serialize()) { 13610 continue; 13611 } 13612 ids.push(value.annotationElementId); 13613 } 13614 } 13615 return this.#modifiedIds = { 13616 ids: new Set(ids), 13617 hash: ids.join(",") 13618 }; 13619 } 13620 [Symbol.iterator]() { 13621 return this.#storage.entries(); 13622 } 13623} 13624class PrintAnnotationStorage extends AnnotationStorage { 13625 #serializable = SerializableEmpty; 13626 constructor(parent) { 13627 super(); 13628 const { 13629 serializable 13630 } = parent; 13631 if (serializable === SerializableEmpty) { 13632 return; 13633 } 13634 const { 13635 map, 13636 hash, 13637 transfer 13638 } = serializable; 13639 const clone = structuredClone(map, transfer ? { 13640 transfer 13641 } : null); 13642 this.#serializable = { 13643 map: clone, 13644 hash, 13645 transfer: [] 13646 }; 13647 } 13648 get print() { 13649 unreachable("Should not call PrintAnnotationStorage.print"); 13650 } 13651 get serializable() { 13652 return this.#serializable; 13653 } 13654 get modifiedIds() { 13655 return shadow(this, "modifiedIds", { 13656 ids: new Set(), 13657 hash: "" 13658 }); 13659 } 13660} 13661 13662;// ./src/display/font_loader.js 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674class FontLoader { 13675 #systemFonts = new Set(); 13676 constructor({ 13677 ownerDocument = globalThis.document, 13678 styleElement = null 13679 }) { 13680 this._document = ownerDocument; 13681 this.nativeFontFaces = new Set(); 13682 this.styleElement = null; 13683 this.loadingRequests = []; 13684 this.loadTestFontId = 0; 13685 } 13686 addNativeFontFace(nativeFontFace) { 13687 this.nativeFontFaces.add(nativeFontFace); 13688 this._document.fonts.add(nativeFontFace); 13689 } 13690 removeNativeFontFace(nativeFontFace) { 13691 this.nativeFontFaces.delete(nativeFontFace); 13692 this._document.fonts.delete(nativeFontFace); 13693 } 13694 insertRule(rule) { 13695 if (!this.styleElement) { 13696 this.styleElement = this._document.createElement("style"); 13697 this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement); 13698 } 13699 const styleSheet = this.styleElement.sheet; 13700 styleSheet.insertRule(rule, styleSheet.cssRules.length); 13701 } 13702 clear() { 13703 for (const nativeFontFace of this.nativeFontFaces) { 13704 this._document.fonts.delete(nativeFontFace); 13705 } 13706 this.nativeFontFaces.clear(); 13707 this.#systemFonts.clear(); 13708 if (this.styleElement) { 13709 this.styleElement.remove(); 13710 this.styleElement = null; 13711 } 13712 } 13713 async loadSystemFont({ 13714 systemFontInfo: info, 13715 disableFontFace, 13716 _inspectFont 13717 }) { 13718 if (!info || this.#systemFonts.has(info.loadedName)) { 13719 return; 13720 } 13721 assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); 13722 if (this.isFontLoadingAPISupported) { 13723 const { 13724 loadedName, 13725 src, 13726 style 13727 } = info; 13728 const fontFace = new FontFace(loadedName, src, style); 13729 this.addNativeFontFace(fontFace); 13730 try { 13731 await fontFace.load(); 13732 this.#systemFonts.add(loadedName); 13733 _inspectFont?.(info); 13734 } catch { 13735 warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); 13736 this.removeNativeFontFace(fontFace); 13737 } 13738 return; 13739 } 13740 unreachable("Not implemented: loadSystemFont without the Font Loading API."); 13741 } 13742 async bind(font) { 13743 if (font.attached || font.missingFile && !font.systemFontInfo) { 13744 return; 13745 } 13746 font.attached = true; 13747 if (font.systemFontInfo) { 13748 await this.loadSystemFont(font); 13749 return; 13750 } 13751 if (this.isFontLoadingAPISupported) { 13752 const nativeFontFace = font.createNativeFontFace(); 13753 if (nativeFontFace) { 13754 this.addNativeFontFace(nativeFontFace); 13755 try { 13756 await nativeFontFace.loaded; 13757 } catch (ex) { 13758 warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); 13759 font.disableFontFace = true; 13760 throw ex; 13761 } 13762 } 13763 return; 13764 } 13765 const rule = font.createFontFaceRule(); 13766 if (rule) { 13767 this.insertRule(rule); 13768 if (this.isSyncFontLoadingSupported) { 13769 return; 13770 } 13771 await new Promise(resolve => { 13772 const request = this._queueLoadingCallback(resolve); 13773 this._prepareFontLoadEvent(font, request); 13774 }); 13775 } 13776 } 13777 get isFontLoadingAPISupported() { 13778 const hasFonts = !!this._document?.fonts; 13779 return shadow(this, "isFontLoadingAPISupported", hasFonts); 13780 } 13781 get isSyncFontLoadingSupported() { 13782 return shadow(this, "isSyncFontLoadingSupported", isNodeJS || FeatureTest.platform.isFirefox); 13783 } 13784 _queueLoadingCallback(callback) { 13785 function completeRequest() { 13786 assert(!request.done, "completeRequest() cannot be called twice."); 13787 request.done = true; 13788 while (loadingRequests.length > 0 && loadingRequests[0].done) { 13789 const otherRequest = loadingRequests.shift(); 13790 setTimeout(otherRequest.callback, 0); 13791 } 13792 } 13793 const { 13794 loadingRequests 13795 } = this; 13796 const request = { 13797 done: false, 13798 complete: completeRequest, 13799 callback 13800 }; 13801 loadingRequests.push(request); 13802 return request; 13803 } 13804 get _loadTestFont() { 13805 const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="); 13806 return shadow(this, "_loadTestFont", testFont); 13807 } 13808 _prepareFontLoadEvent(font, request) { 13809 function int32(data, offset) { 13810 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
vendor: 6,420 bytes, lines 13811-14042
13811 } 13812 function spliceString(s, offset, remove, insert) { 13813 const chunk1 = s.substring(0, offset); 13814 const chunk2 = s.substring(offset + remove); 13815 return chunk1 + insert + chunk2; 13816 } 13817 let i, ii; 13818 const canvas = this._document.createElement("canvas"); 13819 canvas.width = 1; 13820 canvas.height = 1; 13821 const ctx = canvas.getContext("2d"); 13822 let called = 0; 13823 function isFontReady(name, callback) { 13824 if (++called > 30) { 13825 warn("Load test font never loaded."); 13826 callback(); 13827 return; 13828 } 13829 ctx.font = "30px " + name; 13830 ctx.fillText(".", 0, 20); 13831 const imageData = ctx.getImageData(0, 0, 1, 1); 13832 if (imageData.data[3] > 0) { 13833 callback(); 13834 return; 13835 } 13836 setTimeout(isFontReady.bind(null, name, callback)); 13837 } 13838 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; 13839 let data = this._loadTestFont; 13840 const COMMENT_OFFSET = 976; 13841 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); 13842 const CFF_CHECKSUM_OFFSET = 16; 13843 const XXXX_VALUE = 0x58585858; 13844 let checksum = int32(data, CFF_CHECKSUM_OFFSET); 13845 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { 13846 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; 13847 } 13848 if (i < loadTestFontId.length) { 13849 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; 13850 } 13851 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); 13852 const url = `url(data:font/opentype;base64,${btoa(data)});`; 13853 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; 13854 this.insertRule(rule); 13855 const div = this._document.createElement("div"); 13856 div.style.visibility = "hidden"; 13857 div.style.width = div.style.height = "10px"; 13858 div.style.position = "absolute"; 13859 div.style.top = div.style.left = "0px"; 13860 for (const name of [font.loadedName, loadTestFontId]) { 13861 const span = this._document.createElement("span"); 13862 span.textContent = "Hi"; 13863 span.style.fontFamily = name; 13864 div.append(span); 13865 } 13866 this._document.body.append(div); 13867 isFontReady(loadTestFontId, () => { 13868 div.remove(); 13869 request.complete(); 13870 }); 13871 } 13872} 13873class FontFaceObject { 13874 #fontData; 13875 constructor(translatedData, inspectFont = null, extra, charProcOperatorList) { 13876 this.compiledGlyphs = Object.create(null); 13877 this.#fontData = translatedData; 13878 this._inspectFont = inspectFont; 13879 if (extra) { 13880 Object.assign(this, extra); 13881 } 13882 if (charProcOperatorList) { 13883 this.charProcOperatorList = charProcOperatorList; 13884 } 13885 } 13886 createNativeFontFace() { 13887 if (!this.data || this.disableFontFace) { 13888 return null; 13889 } 13890 let nativeFontFace; 13891 if (!this.cssFontInfo) { 13892 nativeFontFace = new FontFace(this.loadedName, this.data, {}); 13893 } else { 13894 const css = { 13895 weight: this.cssFontInfo.fontWeight 13896 }; 13897 if (this.cssFontInfo.italicAngle) { 13898 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`; 13899 } 13900 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css); 13901 } 13902 this._inspectFont?.(this); 13903 return nativeFontFace; 13904 } 13905 createFontFaceRule() { 13906 if (!this.data || this.disableFontFace) { 13907 return null; 13908 } 13909 const url = `url(data:${this.mimetype};base64,${this.data.toBase64()});`; 13910 let rule; 13911 if (!this.cssFontInfo) { 13912 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; 13913 } else { 13914 let css = `font-weight: ${this.cssFontInfo.fontWeight};`; 13915 if (this.cssFontInfo.italicAngle) { 13916 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; 13917 } 13918 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`; 13919 } 13920 this._inspectFont?.(this, url); 13921 return rule; 13922 } 13923 getPathGenerator(objs, character) { 13924 if (this.compiledGlyphs[character] !== undefined) { 13925 return this.compiledGlyphs[character]; 13926 } 13927 const objId = this.loadedName + "_path_" + character; 13928 let cmds; 13929 try { 13930 cmds = objs.get(objId); 13931 } catch (ex) { 13932 warn(`getPathGenerator - ignoring character: "${ex}".`); 13933 } 13934 const path = makePathFromDrawOPS(cmds?.path); 13935 if (!this.fontExtraProperties) { 13936 objs.delete(objId); 13937 } 13938 return this.compiledGlyphs[character] = path; 13939 } 13940 get black() { 13941 return this.#fontData.black; 13942 } 13943 get bold() { 13944 return this.#fontData.bold; 13945 } 13946 get disableFontFace() { 13947 return this.#fontData.disableFontFace ?? false; 13948 } 13949 set disableFontFace(value) { 13950 shadow(this, "disableFontFace", !!value); 13951 } 13952 get fontExtraProperties() { 13953 return this.#fontData.fontExtraProperties ?? false; 13954 } 13955 get isInvalidPDFjsFont() { 13956 return this.#fontData.isInvalidPDFjsFont; 13957 } 13958 get isType3Font() { 13959 return this.#fontData.isType3Font; 13960 } 13961 get italic() { 13962 return this.#fontData.italic; 13963 } 13964 get missingFile() { 13965 return this.#fontData.missingFile; 13966 } 13967 get remeasure() { 13968 return this.#fontData.remeasure; 13969 } 13970 get vertical() { 13971 return this.#fontData.vertical; 13972 } 13973 get ascent() { 13974 return this.#fontData.ascent; 13975 } 13976 get defaultWidth() { 13977 return this.#fontData.defaultWidth; 13978 } 13979 get descent() { 13980 return this.#fontData.descent; 13981 } 13982 get bbox() { 13983 return this.#fontData.bbox; 13984 } 13985 set bbox(bbox) { 13986 shadow(this, "bbox", bbox); 13987 } 13988 get fontMatrix() { 13989 return this.#fontData.fontMatrix; 13990 } 13991 get fallbackName() { 13992 return this.#fontData.fallbackName; 13993 } 13994 get loadedName() { 13995 return this.#fontData.loadedName; 13996 } 13997 get mimetype() { 13998 return this.#fontData.mimetype; 13999 } 14000 get name() { 14001 return this.#fontData.name; 14002 } 14003 get data() { 14004 return this.#fontData.data; 14005 } 14006 clearData() { 14007 this.#fontData.clearData(); 14008 } 14009 get cssFontInfo() { 14010 return this.#fontData.cssFontInfo; 14011 } 14012 get systemFontInfo() { 14013 return this.#fontData.systemFontInfo; 14014 } 14015 get defaultVMetrics() { 14016 return this.#fontData.defaultVMetrics; 14017 } 14018} 14019 14020;// ./src/shared/obj-bin-transform.js 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031class CssFontInfo { 14032 #buffer; 14033 #view; 14034 #decoder; 14035 static strings = ["fontFamily", "fontWeight", "italicAngle"]; 14036 static write(info) { 14037 const encoder = new TextEncoder(); 14038 const encodedStrings = {}; 14039 let stringsLength = 0; 14040 for (const prop of CssFontInfo.strings) { 14041 const encoded = encoder.encode(info[prop]); 14042 encodedStrings[prop] = encoded;
vendor: 10,728 bytes, lines 14043-14375
14043 stringsLength += 4 + encoded.length; 14044 } 14045 const buffer = new ArrayBuffer(stringsLength); 14046 const data = new Uint8Array(buffer); 14047 const view = new DataView(buffer); 14048 let offset = 0; 14049 for (const prop of CssFontInfo.strings) { 14050 const encoded = encodedStrings[prop]; 14051 const length = encoded.length; 14052 view.setUint32(offset, length); 14053 data.set(encoded, offset + 4); 14054 offset += 4 + length; 14055 } 14056 assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow"); 14057 return buffer; 14058 } 14059 constructor(buffer) { 14060 this.#buffer = buffer; 14061 this.#view = new DataView(this.#buffer); 14062 this.#decoder = new TextDecoder(); 14063 } 14064 #readString(index) { 14065 assert(index < CssFontInfo.strings.length, "Invalid string index"); 14066 let offset = 0; 14067 for (let i = 0; i < index; i++) { 14068 offset += this.#view.getUint32(offset) + 4; 14069 } 14070 const length = this.#view.getUint32(offset); 14071 return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); 14072 } 14073 get fontFamily() { 14074 return this.#readString(0); 14075 } 14076 get fontWeight() { 14077 return this.#readString(1); 14078 } 14079 get italicAngle() { 14080 return this.#readString(2); 14081 } 14082} 14083class SystemFontInfo { 14084 #buffer; 14085 #view; 14086 #decoder; 14087 static strings = ["css", "loadedName", "baseFontName", "src"]; 14088 static write(info) { 14089 const encoder = new TextEncoder(); 14090 const encodedStrings = {}; 14091 let stringsLength = 0; 14092 for (const prop of SystemFontInfo.strings) { 14093 const encoded = encoder.encode(info[prop]); 14094 encodedStrings[prop] = encoded; 14095 stringsLength += 4 + encoded.length; 14096 } 14097 stringsLength += 4; 14098 let encodedStyleStyle, 14099 encodedStyleWeight, 14100 lengthEstimate = 1 + stringsLength; 14101 if (info.style) { 14102 encodedStyleStyle = encoder.encode(info.style.style); 14103 encodedStyleWeight = encoder.encode(info.style.weight); 14104 lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length; 14105 } 14106 const buffer = new ArrayBuffer(lengthEstimate); 14107 const data = new Uint8Array(buffer); 14108 const view = new DataView(buffer); 14109 let offset = 0; 14110 view.setUint8(offset++, info.guessFallback ? 1 : 0); 14111 view.setUint32(offset, 0); 14112 offset += 4; 14113 stringsLength = 0; 14114 for (const prop of SystemFontInfo.strings) { 14115 const encoded = encodedStrings[prop]; 14116 const length = encoded.length; 14117 stringsLength += 4 + length; 14118 view.setUint32(offset, length); 14119 data.set(encoded, offset + 4); 14120 offset += 4 + length; 14121 } 14122 view.setUint32(offset - stringsLength - 4, stringsLength); 14123 if (info.style) { 14124 view.setUint32(offset, encodedStyleStyle.length); 14125 data.set(encodedStyleStyle, offset + 4); 14126 offset += 4 + encodedStyleStyle.length; 14127 view.setUint32(offset, encodedStyleWeight.length); 14128 data.set(encodedStyleWeight, offset + 4); 14129 offset += 4 + encodedStyleWeight.length; 14130 } 14131 assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow"); 14132 return buffer.transferToFixedLength(offset); 14133 } 14134 constructor(buffer) { 14135 this.#buffer = buffer; 14136 this.#view = new DataView(this.#buffer); 14137 this.#decoder = new TextDecoder(); 14138 } 14139 get guessFallback() { 14140 return this.#view.getUint8(0) !== 0; 14141 } 14142 #readString(index) { 14143 assert(index < SystemFontInfo.strings.length, "Invalid string index"); 14144 let offset = 5; 14145 for (let i = 0; i < index; i++) { 14146 offset += this.#view.getUint32(offset) + 4; 14147 } 14148 const length = this.#view.getUint32(offset); 14149 return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); 14150 } 14151 get css() { 14152 return this.#readString(0); 14153 } 14154 get loadedName() { 14155 return this.#readString(1); 14156 } 14157 get baseFontName() { 14158 return this.#readString(2); 14159 } 14160 get src() { 14161 return this.#readString(3); 14162 } 14163 get style() { 14164 let offset = 1; 14165 offset += 4 + this.#view.getUint32(offset); 14166 const styleLength = this.#view.getUint32(offset); 14167 const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength)); 14168 offset += 4 + styleLength; 14169 const weightLength = this.#view.getUint32(offset); 14170 const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength)); 14171 return { 14172 style, 14173 weight 14174 }; 14175 } 14176} 14177class FontInfo { 14178 static bools = ["black", "bold", "disableFontFace", "fontExtraProperties", "isInvalidPDFjsFont", "isType3Font", "italic", "missingFile", "remeasure", "vertical"]; 14179 static numbers = ["ascent", "defaultWidth", "descent"]; 14180 static strings = ["fallbackName", "loadedName", "mimetype", "name"]; 14181 static #OFFSET_NUMBERS = Math.ceil(this.bools.length * 2 / 8); 14182 static #OFFSET_BBOX = this.#OFFSET_NUMBERS + this.numbers.length * 8; 14183 static #OFFSET_FONT_MATRIX = this.#OFFSET_BBOX + 1 + 2 * 4; 14184 static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6; 14185 static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3; 14186 #buffer; 14187 #decoder; 14188 #view; 14189 constructor({ 14190 data, 14191 extra 14192 }) { 14193 this.#buffer = data; 14194 this.#decoder = new TextDecoder(); 14195 this.#view = new DataView(this.#buffer); 14196 if (extra) { 14197 Object.assign(this, extra); 14198 } 14199 } 14200 #readBoolean(index) { 14201 assert(index < FontInfo.bools.length, "Invalid boolean index"); 14202 const byteOffset = Math.floor(index / 4); 14203 const bitOffset = index * 2 % 8; 14204 const value = this.#view.getUint8(byteOffset) >> bitOffset & 0x03; 14205 return value === 0x00 ? undefined : value === 0x02; 14206 } 14207 get black() { 14208 return this.#readBoolean(0); 14209 } 14210 get bold() { 14211 return this.#readBoolean(1); 14212 } 14213 get disableFontFace() { 14214 return this.#readBoolean(2); 14215 } 14216 get fontExtraProperties() { 14217 return this.#readBoolean(3); 14218 } 14219 get isInvalidPDFjsFont() { 14220 return this.#readBoolean(4); 14221 } 14222 get isType3Font() { 14223 return this.#readBoolean(5); 14224 } 14225 get italic() { 14226 return this.#readBoolean(6); 14227 } 14228 get missingFile() { 14229 return this.#readBoolean(7); 14230 } 14231 get remeasure() { 14232 return this.#readBoolean(8); 14233 } 14234 get vertical() { 14235 return this.#readBoolean(9); 14236 } 14237 #readNumber(index) { 14238 assert(index < FontInfo.numbers.length, "Invalid number index"); 14239 return this.#view.getFloat64(FontInfo.#OFFSET_NUMBERS + index * 8); 14240 } 14241 get ascent() { 14242 return this.#readNumber(0); 14243 } 14244 get defaultWidth() { 14245 return this.#readNumber(1); 14246 } 14247 get descent() { 14248 return this.#readNumber(2); 14249 } 14250 get bbox() { 14251 let offset = FontInfo.#OFFSET_BBOX; 14252 const numCoords = this.#view.getUint8(offset); 14253 if (numCoords === 0) { 14254 return undefined; 14255 } 14256 offset += 1; 14257 const bbox = []; 14258 for (let i = 0; i < 4; i++) { 14259 bbox.push(this.#view.getInt16(offset, true)); 14260 offset += 2; 14261 } 14262 return bbox; 14263 } 14264 get fontMatrix() { 14265 let offset = FontInfo.#OFFSET_FONT_MATRIX; 14266 const numPoints = this.#view.getUint8(offset); 14267 if (numPoints === 0) { 14268 return undefined; 14269 } 14270 offset += 1; 14271 const fontMatrix = []; 14272 for (let i = 0; i < 6; i++) { 14273 fontMatrix.push(this.#view.getFloat64(offset, true)); 14274 offset += 8; 14275 } 14276 return fontMatrix; 14277 } 14278 get defaultVMetrics() { 14279 let offset = FontInfo.#OFFSET_DEFAULT_VMETRICS; 14280 const numMetrics = this.#view.getUint8(offset); 14281 if (numMetrics === 0) { 14282 return undefined; 14283 } 14284 offset += 1; 14285 const defaultVMetrics = []; 14286 for (let i = 0; i < 3; i++) { 14287 defaultVMetrics.push(this.#view.getInt16(offset, true)); 14288 offset += 2; 14289 } 14290 return defaultVMetrics; 14291 } 14292 #readString(index) { 14293 assert(index < FontInfo.strings.length, "Invalid string index"); 14294 let offset = FontInfo.#OFFSET_STRINGS + 4; 14295 for (let i = 0; i < index; i++) { 14296 offset += this.#view.getUint32(offset) + 4; 14297 } 14298 const length = this.#view.getUint32(offset); 14299 const stringData = new Uint8Array(length); 14300 stringData.set(new Uint8Array(this.#buffer, offset + 4, length)); 14301 return this.#decoder.decode(stringData); 14302 } 14303 get fallbackName() { 14304 return this.#readString(0); 14305 } 14306 get loadedName() { 14307 return this.#readString(1); 14308 } 14309 get mimetype() { 14310 return this.#readString(2); 14311 } 14312 get name() { 14313 return this.#readString(3); 14314 } 14315 get data() { 14316 let offset = FontInfo.#OFFSET_STRINGS; 14317 const stringsLength = this.#view.getUint32(offset); 14318 offset += 4 + stringsLength; 14319 const systemFontInfoLength = this.#view.getUint32(offset); 14320 offset += 4 + systemFontInfoLength; 14321 const cssFontInfoLength = this.#view.getUint32(offset); 14322 offset += 4 + cssFontInfoLength; 14323 const length = this.#view.getUint32(offset); 14324 if (length === 0) { 14325 return undefined; 14326 } 14327 return new Uint8Array(this.#buffer, offset + 4, length); 14328 } 14329 clearData() { 14330 let offset = FontInfo.#OFFSET_STRINGS; 14331 const stringsLength = this.#view.getUint32(offset); 14332 offset += 4 + stringsLength; 14333 const systemFontInfoLength = this.#view.getUint32(offset); 14334 offset += 4 + systemFontInfoLength; 14335 const cssFontInfoLength = this.#view.getUint32(offset); 14336 offset += 4 + cssFontInfoLength; 14337 const length = this.#view.getUint32(offset); 14338 const data = new Uint8Array(this.#buffer, offset + 4, length); 14339 data.fill(0); 14340 this.#view.setUint32(offset, 0); 14341 } 14342 get cssFontInfo() { 14343 let offset = FontInfo.#OFFSET_STRINGS; 14344 const stringsLength = this.#view.getUint32(offset); 14345 offset += 4 + stringsLength; 14346 const systemFontInfoLength = this.#view.getUint32(offset); 14347 offset += 4 + systemFontInfoLength; 14348 const cssFontInfoLength = this.#view.getUint32(offset); 14349 if (cssFontInfoLength === 0) { 14350 return null; 14351 } 14352 const cssFontInfoData = new Uint8Array(cssFontInfoLength); 14353 cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength)); 14354 return new CssFontInfo(cssFontInfoData.buffer); 14355 } 14356 get systemFontInfo() { 14357 let offset = FontInfo.#OFFSET_STRINGS; 14358 const stringsLength = this.#view.getUint32(offset); 14359 offset += 4 + stringsLength; 14360 const systemFontInfoLength = this.#view.getUint32(offset); 14361 if (systemFontInfoLength === 0) { 14362 return null; 14363 } 14364 const systemFontInfoData = new Uint8Array(systemFontInfoLength); 14365 systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength)); 14366 return new SystemFontInfo(systemFontInfoData.buffer); 14367 } 14368 static write(font) { 14369 const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null; 14370 const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null; 14371 const encoder = new TextEncoder(); 14372 const encodedStrings = {}; 14373 let stringsLength = 0; 14374 for (const prop of FontInfo.strings) { 14375 encodedStrings[prop] = encoder.encode(font[prop]);
vendor: 5,233 bytes, lines 14376-14529
14376 stringsLength += 4 + encodedStrings[prop].length; 14377 } 14378 const lengthEstimate = FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0); 14379 const buffer = new ArrayBuffer(lengthEstimate); 14380 const data = new Uint8Array(buffer); 14381 const view = new DataView(buffer); 14382 let offset = 0; 14383 const numBools = FontInfo.bools.length; 14384 let boolByte = 0, 14385 boolBit = 0; 14386 for (let i = 0; i < numBools; i++) { 14387 const value = font[FontInfo.bools[i]]; 14388 const bits = value === undefined ? 0x00 : value ? 0x02 : 0x01; 14389 boolByte |= bits << boolBit; 14390 boolBit += 2; 14391 if (boolBit === 8 || i === numBools - 1) { 14392 view.setUint8(offset++, boolByte); 14393 boolByte = 0; 14394 boolBit = 0; 14395 } 14396 } 14397 assert(offset === FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch"); 14398 for (const prop of FontInfo.numbers) { 14399 view.setFloat64(offset, font[prop]); 14400 offset += 8; 14401 } 14402 assert(offset === FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch"); 14403 if (font.bbox) { 14404 view.setUint8(offset++, 4); 14405 for (const coord of font.bbox) { 14406 view.setInt16(offset, coord, true); 14407 offset += 2; 14408 } 14409 } else { 14410 view.setUint8(offset++, 0); 14411 offset += 2 * 4; 14412 } 14413 assert(offset === FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch"); 14414 if (font.fontMatrix) { 14415 view.setUint8(offset++, 6); 14416 for (const point of font.fontMatrix) { 14417 view.setFloat64(offset, point, true); 14418 offset += 8; 14419 } 14420 } else { 14421 view.setUint8(offset++, 0); 14422 offset += 8 * 6; 14423 } 14424 assert(offset === FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch"); 14425 if (font.defaultVMetrics) { 14426 view.setUint8(offset++, 1); 14427 for (const metric of font.defaultVMetrics) { 14428 view.setInt16(offset, metric, true); 14429 offset += 2; 14430 } 14431 } else { 14432 view.setUint8(offset++, 0); 14433 offset += 3 * 2; 14434 } 14435 assert(offset === FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch"); 14436 view.setUint32(FontInfo.#OFFSET_STRINGS, 0); 14437 offset += 4; 14438 for (const prop of FontInfo.strings) { 14439 const encoded = encodedStrings[prop]; 14440 const length = encoded.length; 14441 view.setUint32(offset, length); 14442 data.set(encoded, offset + 4); 14443 offset += 4 + length; 14444 } 14445 view.setUint32(FontInfo.#OFFSET_STRINGS, offset - FontInfo.#OFFSET_STRINGS - 4); 14446 if (!systemFontInfoBuffer) { 14447 view.setUint32(offset, 0); 14448 offset += 4; 14449 } else { 14450 const length = systemFontInfoBuffer.byteLength; 14451 view.setUint32(offset, length); 14452 assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo"); 14453 data.set(new Uint8Array(systemFontInfoBuffer), offset + 4); 14454 offset += 4 + length; 14455 } 14456 if (!cssFontInfoBuffer) { 14457 view.setUint32(offset, 0); 14458 offset += 4; 14459 } else { 14460 const length = cssFontInfoBuffer.byteLength; 14461 view.setUint32(offset, length); 14462 assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo"); 14463 data.set(new Uint8Array(cssFontInfoBuffer), offset + 4); 14464 offset += 4 + length; 14465 } 14466 if (font.data === undefined) { 14467 view.setUint32(offset, 0); 14468 offset += 4; 14469 } else { 14470 view.setUint32(offset, font.data.length); 14471 data.set(font.data, offset + 4); 14472 offset += 4 + font.data.length; 14473 } 14474 assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow"); 14475 return buffer.transferToFixedLength(offset); 14476 } 14477} 14478class PatternInfo { 14479 static #KIND = 0; 14480 static #HAS_BBOX = 1; 14481 static #HAS_BACKGROUND = 2; 14482 static #SHADING_TYPE = 3; 14483 static #N_COORD = 4; 14484 static #N_COLOR = 8; 14485 static #N_STOP = 12; 14486 static #N_FIGURES = 16; 14487 constructor(buffer) { 14488 this.buffer = buffer; 14489 this.view = new DataView(buffer); 14490 this.data = new Uint8Array(buffer); 14491 } 14492 static write(ir) { 14493 let kind, 14494 bbox = null, 14495 coords = [], 14496 colors = [], 14497 colorStops = [], 14498 figures = [], 14499 shadingType = null, 14500 background = null; 14501 switch (ir[0]) { 14502 case "RadialAxial": 14503 kind = ir[1] === "axial" ? 1 : 2; 14504 bbox = ir[2]; 14505 colorStops = ir[3]; 14506 if (kind === 1) { 14507 coords.push(...ir[4], ...ir[5]); 14508 } else { 14509 coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]); 14510 } 14511 break; 14512 case "Mesh": 14513 kind = 3; 14514 shadingType = ir[1]; 14515 coords = ir[2]; 14516 colors = ir[3]; 14517 figures = ir[4] || []; 14518 bbox = ir[6]; 14519 background = ir[7]; 14520 break; 14521 default: 14522 throw new Error(`Unsupported pattern type: ${ir[0]}`); 14523 } 14524 const nCoord = Math.floor(coords.length / 2); 14525 const nColor = Math.floor(colors.length / 3); 14526 const nStop = colorStops.length; 14527 const nFigures = figures.length; 14528 let figuresSize = 0; 14529 for (const figure of figures) {
14530 figuresSize += 1; 14531 figuresSize = Math.ceil(figuresSize / 4) * 4; 14532 figuresSize += 4 + figure.coords.length * 4; 14533 figuresSize += 4 + figure.colors.length * 4; 14534 if (figure.verticesPerRow !== undefined) { 14535 figuresSize += 4; 14536 } 14537 } 14538 const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize; 14539 const buffer = new ArrayBuffer(byteLen); 14540 const dataView = new DataView(buffer); 14541 const u8data = new Uint8Array(buffer); 14542 dataView.setUint8(PatternInfo.#KIND, kind); 14543 dataView.setUint8(PatternInfo.#HAS_BBOX, bbox ? 1 : 0); 14544 dataView.setUint8(PatternInfo.#HAS_BACKGROUND, background ? 1 : 0); 14545 dataView.setUint8(PatternInfo.#SHADING_TYPE, shadingType); 14546 dataView.setUint32(PatternInfo.#N_COORD, nCoord, true); 14547 dataView.setUint32(PatternInfo.#N_COLOR, nColor, true); 14548 dataView.setUint32(PatternInfo.#N_STOP, nStop, true); 14549 dataView.setUint32(PatternInfo.#N_FIGURES, nFigures, true); 14550 let offset = 20; 14551 const coordsView = new Float32Array(buffer, offset, nCoord * 2); 14552 coordsView.set(coords); 14553 offset += nCoord * 8; 14554 u8data.set(colors, offset); 14555 offset += nColor * 3; 14556 for (const [pos, hex] of colorStops) { 14557 dataView.setFloat32(offset, pos, true); 14558 offset += 4; 14559 dataView.setUint32(offset, parseInt(hex.slice(1), 16), true); 14560 offset += 4; 14561 } 14562 if (bbox) { 14563 for (const v of bbox) { 14564 dataView.setFloat32(offset, v, true); 14565 offset += 4; 14566 } 14567 } 14568 if (background) { 14569 u8data.set(background, offset); 14570 offset += 3; 14571 } 14572 for (let i = 0; i < figures.length; i++) { 14573 const figure = figures[i]; 14574 dataView.setUint8(offset, figure.type); 14575 offset += 1; 14576 offset = Math.ceil(offset / 4) * 4; 14577 dataView.setUint32(offset, figure.coords.length, true); 14578 offset += 4; 14579 const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length); 14580 figureCoordsView.set(figure.coords); 14581 offset += figure.coords.length * 4; 14582 dataView.setUint32(offset, figure.colors.length, true); 14583 offset += 4; 14584 const colorsView = new Int32Array(buffer, offset, figure.colors.length); 14585 colorsView.set(figure.colors); 14586 offset += figure.colors.length * 4; 14587 if (figure.verticesPerRow !== undefined) { 14588 dataView.setUint32(offset, figure.verticesPerRow, true); 14589 offset += 4; 14590 } 14591 } 14592 return buffer; 14593 } 14594 getIR() { 14595 const dataView = this.view; 14596 const kind = this.data[PatternInfo.#KIND]; 14597 const hasBBox = !!this.data[PatternInfo.#HAS_BBOX]; 14598 const hasBackground = !!this.data[PatternInfo.#HAS_BACKGROUND]; 14599 const nCoord = dataView.getUint32(PatternInfo.#N_COORD, true); 14600 const nColor = dataView.getUint32(PatternInfo.#N_COLOR, true); 14601 const nStop = dataView.getUint32(PatternInfo.#N_STOP, true); 14602 const nFigures = dataView.getUint32(PatternInfo.#N_FIGURES, true); 14603 let offset = 20; 14604 const coords = new Float32Array(this.buffer, offset, nCoord * 2); 14605 offset += nCoord * 8; 14606 const colors = new Uint8Array(this.buffer, offset, nColor * 3); 14607 offset += nColor * 3; 14608 const stops = []; 14609 for (let i = 0; i < nStop; ++i) { 14610 const p = dataView.getFloat32(offset, true); 14611 offset += 4; 14612 const rgb = dataView.getUint32(offset, true); 14613 offset += 4; 14614 stops.push([p, `#${rgb.toString(16).padStart(6, "0")}`]); 14615 } 14616 let bbox = null; 14617 if (hasBBox) { 14618 bbox = []; 14619 for (let i = 0; i < 4; ++i) { 14620 bbox.push(dataView.getFloat32(offset, true)); 14621 offset += 4; 14622 } 14623 } 14624 let background = null; 14625 if (hasBackground) { 14626 background = new Uint8Array(this.buffer, offset, 3); 14627 offset += 3; 14628 } 14629 const figures = []; 14630 for (let i = 0; i < nFigures; ++i) { 14631 const type = dataView.getUint8(offset); 14632 offset += 1; 14633 offset = Math.ceil(offset / 4) * 4; 14634 const coordsLength = dataView.getUint32(offset, true); 14635 offset += 4; 14636 const figureCoords = new Int32Array(this.buffer, offset, coordsLength); 14637 offset += coordsLength * 4; 14638 const colorsLength = dataView.getUint32(offset, true); 14639 offset += 4; 14640 const figureColors = new Int32Array(this.buffer, offset, colorsLength); 14641 offset += colorsLength * 4; 14642 const figure = { 14643 type, 14644 coords: figureCoords, 14645 colors: figureColors 14646 }; 14647 if (type === MeshFigureType.LATTICE) { 14648 figure.verticesPerRow = dataView.getUint32(offset, true); 14649 offset += 4; 14650 } 14651 figures.push(figure); 14652 } 14653 if (kind === 1) { 14654 return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null]; 14655 } 14656 if (kind === 2) { 14657 return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], c
vendor: 16,746 bytes, lines 14657-15225
14657oords[4]], coords[2], coords[5]]; 14658 } 14659 if (kind === 3) { 14660 const shadingType = this.data[PatternInfo.#SHADING_TYPE]; 14661 let bounds = null; 14662 if (coords.length > 0) { 14663 let minX = coords[0], 14664 maxX = coords[0]; 14665 let minY = coords[1], 14666 maxY = coords[1]; 14667 for (let i = 0; i < coords.length; i += 2) { 14668 const x = coords[i], 14669 y = coords[i + 1]; 14670 minX = minX > x ? x : minX; 14671 minY = minY > y ? y : minY; 14672 maxX = maxX < x ? x : maxX; 14673 maxY = maxY < y ? y : maxY; 14674 } 14675 bounds = [minX, minY, maxX, maxY]; 14676 } 14677 return ["Mesh", shadingType, coords, colors, figures, bounds, bbox, background]; 14678 } 14679 throw new Error(`Unsupported pattern kind: ${kind}`); 14680 } 14681} 14682class FontPathInfo { 14683 static write(path) { 14684 let data; 14685 let buffer; 14686 if (FeatureTest.isFloat16ArraySupported) { 14687 buffer = new ArrayBuffer(path.length * 2); 14688 data = new Float16Array(buffer); 14689 } else { 14690 buffer = new ArrayBuffer(path.length * 4); 14691 data = new Float32Array(buffer); 14692 } 14693 data.set(path); 14694 return buffer; 14695 } 14696 #buffer; 14697 constructor(buffer) { 14698 this.#buffer = buffer; 14699 } 14700 get path() { 14701 if (FeatureTest.isFloat16ArraySupported) { 14702 return new Float16Array(this.#buffer); 14703 } 14704 return new Float32Array(this.#buffer); 14705 } 14706} 14707 14708;// ./src/display/api_utils.js 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725function getUrlProp(val) { 14726 if (val instanceof URL) { 14727 return val; 14728 } 14729 if (typeof val === "string") { 14730 if (isNodeJS) { 14731 if (/^[a-z][a-z0-9\-+.]+:/i.test(val)) { 14732 return new URL(val); 14733 } 14734 const url = process.getBuiltinModule("url"); 14735 return new URL(url.pathToFileURL(val)); 14736 } 14737 const url = URL.parse(val, window.location); 14738 if (url) { 14739 return url; 14740 } 14741 } 14742 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); 14743} 14744function getDataProp(val) { 14745 if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) { 14746 throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); 14747 } 14748 if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) { 14749 return val; 14750 } 14751 if (typeof val === "string") { 14752 return stringToBytes(val); 14753 } 14754 if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) { 14755 return new Uint8Array(val); 14756 } 14757 throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property."); 14758} 14759function getFactoryUrlProp(val) { 14760 if (typeof val !== "string") { 14761 return null; 14762 } 14763 if (val.endsWith("/")) { 14764 return val; 14765 } 14766 throw new Error(`Invalid factory url: "${val}" must include trailing slash.`); 14767} 14768const isRefProxy = v => typeof v === "object" && Number.isInteger(v?.num) && v.num >= 0 && Number.isInteger(v?.gen) && v.gen >= 0; 14769const isNameProxy = v => typeof v === "object" && typeof v?.name === "string"; 14770const isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy); 14771class LoopbackPort { 14772 #listeners = new Map(); 14773 #deferred = Promise.resolve(); 14774 postMessage(obj, transfer) { 14775 const event = { 14776 data: structuredClone(obj, transfer ? { 14777 transfer 14778 } : null) 14779 }; 14780 this.#deferred.then(() => { 14781 for (const [listener] of this.#listeners) { 14782 listener.call(this, event); 14783 } 14784 }); 14785 } 14786 addEventListener(name, listener, options = null) { 14787 let rmAbort = null; 14788 if (options?.signal instanceof AbortSignal) { 14789 const { 14790 signal 14791 } = options; 14792 if (signal.aborted) { 14793 warn("LoopbackPort - cannot use an `aborted` signal."); 14794 return; 14795 } 14796 const onAbort = () => this.removeEventListener(name, listener); 14797 rmAbort = () => signal.removeEventListener("abort", onAbort); 14798 signal.addEventListener("abort", onAbort); 14799 } 14800 this.#listeners.set(listener, rmAbort); 14801 } 14802 removeEventListener(name, listener) { 14803 const rmAbort = this.#listeners.get(listener); 14804 rmAbort?.(); 14805 this.#listeners.delete(listener); 14806 } 14807 terminate() { 14808 for (const [, rmAbort] of this.#listeners) { 14809 rmAbort?.(); 14810 } 14811 this.#listeners.clear(); 14812 } 14813} 14814 14815// EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.try.js 14816var es_promise_try = __webpack_require__(1689); 14817;// ./src/shared/message_handler.js 14818 14819 14820 14821const CallbackKind = { 14822 DATA: 1, 14823 ERROR: 2 14824}; 14825const StreamKind = { 14826 CANCEL: 1, 14827 CANCEL_COMPLETE: 2, 14828 CLOSE: 3, 14829 ENQUEUE: 4, 14830 ERROR: 5, 14831 PULL: 6, 14832 PULL_COMPLETE: 7, 14833 START_COMPLETE: 8 14834}; 14835function onFn() {} 14836function wrapReason(ex) { 14837 if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) { 14838 return ex; 14839 } 14840 if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) { 14841 unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); 14842 } 14843 switch (ex.name) { 14844 case "AbortException": 14845 return new AbortException(ex.message); 14846 case "InvalidPDFException": 14847 return new InvalidPDFException(ex.message); 14848 case "PasswordException": 14849 return new PasswordException(ex.message, ex.code); 14850 case "ResponseException": 14851 return new ResponseException(ex.message, ex.status, ex.missing); 14852 case "UnknownErrorException": 14853 return new UnknownErrorException(ex.message, ex.details); 14854 } 14855 return new UnknownErrorException(ex.message, ex.toString()); 14856} 14857class MessageHandler { 14858 #messageAC = new AbortController(); 14859 constructor(sourceName, targetName, comObj) { 14860 this.sourceName = sourceName; 14861 this.targetName = targetName; 14862 this.comObj = comObj; 14863 this.callbackId = 1; 14864 this.streamId = 1; 14865 this.streamSinks = Object.create(null); 14866 this.streamControllers = Object.create(null); 14867 this.callbackCapabilities = Object.create(null); 14868 this.actionHandler = Object.create(null); 14869 comObj.addEventListener("message", this.#onMessage.bind(this), { 14870 signal: this.#messageAC.signal 14871 }); 14872 } 14873 #onMessage({ 14874 data 14875 }) { 14876 if (data.targetName !== this.sourceName) { 14877 return; 14878 } 14879 if (data.stream) { 14880 this.#processStreamMessage(data); 14881 return; 14882 } 14883 if (data.callback) { 14884 const callbackId = data.callbackId; 14885 const capability = this.callbackCapabilities[callbackId]; 14886 if (!capability) { 14887 throw new Error(`Cannot resolve callback ${callbackId}`); 14888 } 14889 delete this.callbackCapabilities[callbackId]; 14890 if (data.callback === CallbackKind.DATA) { 14891 capability.resolve(data.data); 14892 } else if (data.callback === CallbackKind.ERROR) { 14893 capability.reject(wrapReason(data.reason)); 14894 } else { 14895 throw new Error("Unexpected callback case"); 14896 } 14897 return; 14898 } 14899 const action = this.actionHandler[data.action]; 14900 if (!action) { 14901 throw new Error(`Unknown action from worker: ${data.action}`); 14902 } 14903 if (data.callbackId) { 14904 const sourceName = this.sourceName, 14905 targetName = data.sourceName, 14906 comObj = this.comObj; 14907 Promise.try(action, data.data).then(function (result) { 14908 comObj.postMessage({ 14909 sourceName, 14910 targetName, 14911 callback: CallbackKind.DATA, 14912 callbackId: data.callbackId, 14913 data: result 14914 }); 14915 }, function (reason) { 14916 comObj.postMessage({ 14917 sourceName, 14918 targetName, 14919 callback: CallbackKind.ERROR, 14920 callbackId: data.callbackId, 14921 reason: wrapReason(reason) 14922 }); 14923 }); 14924 return; 14925 } 14926 if (data.streamId) { 14927 this.#createStreamSink(data); 14928 return; 14929 } 14930 action(data.data); 14931 } 14932 on(actionName, handler) { 14933 const ah = this.actionHandler; 14934 if (ah[actionName]) { 14935 throw new Error(`There is already an actionName called "${actionName}"`); 14936 } 14937 ah[actionName] = handler; 14938 } 14939 send(actionName, data, transfers) { 14940 this.comObj.postMessage({ 14941 sourceName: this.sourceName, 14942 targetName: this.targetName, 14943 action: actionName, 14944 data 14945 }, transfers); 14946 } 14947 sendWithPromise(actionName, data, transfers) { 14948 const callbackId = this.callbackId++; 14949 const capability = Promise.withResolvers(); 14950 this.callbackCapabilities[callbackId] = capability; 14951 try { 14952 this.comObj.postMessage({ 14953 sourceName: this.sourceName, 14954 targetName: this.targetName, 14955 action: actionName, 14956 callbackId, 14957 data 14958 }, transfers); 14959 } catch (ex) { 14960 capability.reject(ex); 14961 } 14962 return capability.promise; 14963 } 14964 sendWithStream(actionName, data, queueingStrategy, transfers) { 14965 const streamId = this.streamId++, 14966 sourceName = this.sourceName, 14967 targetName = this.targetName, 14968 comObj = this.comObj; 14969 return new ReadableStream({ 14970 start: controller => { 14971 const startCapability = Promise.withResolvers(); 14972 this.streamControllers[streamId] = { 14973 controller, 14974 startCall: startCapability, 14975 pullCall: null, 14976 cancelCall: null, 14977 isClosed: false 14978 }; 14979 comObj.postMessage({ 14980 sourceName, 14981 targetName, 14982 action: actionName, 14983 streamId, 14984 data, 14985 desiredSize: controller.desiredSize 14986 }, transfers); 14987 return startCapability.promise; 14988 }, 14989 pull: controller => { 14990 const pullCapability = Promise.withResolvers(); 14991 this.streamControllers[streamId].pullCall = pullCapability; 14992 comObj.postMessage({ 14993 sourceName, 14994 targetName, 14995 stream: StreamKind.PULL, 14996 streamId, 14997 desiredSize: controller.desiredSize 14998 }); 14999 return pullCapability.promise; 15000 }, 15001 cancel: reason => { 15002 assert(reason instanceof Error, "cancel must have a valid reason"); 15003 const cancelCapability = Promise.withResolvers(); 15004 this.streamControllers[streamId].cancelCall = cancelCapability; 15005 this.streamControllers[streamId].isClosed = true; 15006 comObj.postMessage({ 15007 sourceName, 15008 targetName, 15009 stream: StreamKind.CANCEL, 15010 streamId, 15011 reason: wrapReason(reason) 15012 }); 15013 return cancelCapability.promise; 15014 } 15015 }, queueingStrategy); 15016 } 15017 #createStreamSink(data) { 15018 const streamId = data.streamId, 15019 sourceName = this.sourceName, 15020 targetName = data.sourceName, 15021 comObj = this.comObj; 15022 const self = this, 15023 action = this.actionHandler[data.action]; 15024 const streamSink = { 15025 enqueue(chunk, size = 1, transfers) { 15026 if (this.isCancelled) { 15027 return; 15028 } 15029 const lastDesiredSize = this.desiredSize; 15030 this.desiredSize -= size; 15031 if (lastDesiredSize > 0 && this.desiredSize <= 0) { 15032 this.sinkCapability = Promise.withResolvers(); 15033 this.ready = this.sinkCapability.promise; 15034 } 15035 comObj.postMessage({ 15036 sourceName, 15037 targetName, 15038 stream: StreamKind.ENQUEUE, 15039 streamId, 15040 chunk 15041 }, transfers); 15042 }, 15043 close() { 15044 if (this.isCancelled) { 15045 return; 15046 } 15047 this.isCancelled = true; 15048 comObj.postMessage({ 15049 sourceName, 15050 targetName, 15051 stream: StreamKind.CLOSE, 15052 streamId 15053 }); 15054 delete self.streamSinks[streamId]; 15055 }, 15056 error(reason) { 15057 assert(reason instanceof Error, "error must have a valid reason"); 15058 if (this.isCancelled) { 15059 return; 15060 } 15061 this.isCancelled = true; 15062 comObj.postMessage({ 15063 sourceName, 15064 targetName, 15065 stream: StreamKind.ERROR, 15066 streamId, 15067 reason: wrapReason(reason) 15068 }); 15069 }, 15070 sinkCapability: Promise.withResolvers(), 15071 onPull: null, 15072 onCancel: null, 15073 isCancelled: false, 15074 desiredSize: data.desiredSize, 15075 ready: null 15076 }; 15077 streamSink.sinkCapability.resolve(); 15078 streamSink.ready = streamSink.sinkCapability.promise; 15079 this.streamSinks[streamId] = streamSink; 15080 Promise.try(action, data.data, streamSink).then(function () { 15081 comObj.postMessage({ 15082 sourceName, 15083 targetName, 15084 stream: StreamKind.START_COMPLETE, 15085 streamId, 15086 success: true 15087 }); 15088 }, function (reason) { 15089 comObj.postMessage({ 15090 sourceName, 15091 targetName, 15092 stream: StreamKind.START_COMPLETE, 15093 streamId, 15094 reason: wrapReason(reason) 15095 }); 15096 }); 15097 } 15098 #processStreamMessage(data) { 15099 const streamId = data.streamId, 15100 sourceName = this.sourceName, 15101 targetName = data.sourceName, 15102 comObj = this.comObj; 15103 const streamController = this.streamControllers[streamId], 15104 streamSink = this.streamSinks[streamId]; 15105 switch (data.stream) { 15106 case StreamKind.START_COMPLETE: 15107 if (data.success) { 15108 streamController.startCall.resolve(); 15109 } else { 15110 streamController.startCall.reject(wrapReason(data.reason)); 15111 } 15112 break; 15113 case StreamKind.PULL_COMPLETE: 15114 if (data.success) { 15115 streamController.pullCall.resolve(); 15116 } else { 15117 streamController.pullCall.reject(wrapReason(data.reason)); 15118 } 15119 break; 15120 case StreamKind.PULL: 15121 if (!streamSink) { 15122 comObj.postMessage({ 15123 sourceName, 15124 targetName, 15125 stream: StreamKind.PULL_COMPLETE, 15126 streamId, 15127 success: true 15128 }); 15129 break; 15130 } 15131 if (streamSink.desiredSize <= 0 && data.desiredSize > 0) { 15132 streamSink.sinkCapability.resolve(); 15133 } 15134 streamSink.desiredSize = data.desiredSize; 15135 Promise.try(streamSink.onPull || onFn).then(function () { 15136 comObj.postMessage({ 15137 sourceName, 15138 targetName, 15139 stream: StreamKind.PULL_COMPLETE, 15140 streamId, 15141 success: true 15142 }); 15143 }, function (reason) { 15144 comObj.postMessage({ 15145 sourceName, 15146 targetName, 15147 stream: StreamKind.PULL_COMPLETE, 15148 streamId, 15149 reason: wrapReason(reason) 15150 }); 15151 }); 15152 break; 15153 case StreamKind.ENQUEUE: 15154 assert(streamController, "enqueue should have stream controller"); 15155 if (streamController.isClosed) { 15156 break; 15157 } 15158 streamController.controller.enqueue(data.chunk); 15159 break; 15160 case StreamKind.CLOSE: 15161 assert(streamController, "close should have stream controller"); 15162 if (streamController.isClosed) { 15163 break; 15164 } 15165 streamController.isClosed = true; 15166 streamController.controller.close(); 15167 this.#deleteStreamController(streamController, streamId); 15168 break; 15169 case StreamKind.ERROR: 15170 assert(streamController, "error should have stream controller"); 15171 streamController.controller.error(wrapReason(data.reason)); 15172 this.#deleteStreamController(streamController, streamId); 15173 break; 15174 case StreamKind.CANCEL_COMPLETE: 15175 if (data.success) { 15176 streamController.cancelCall.resolve(); 15177 } else { 15178 streamController.cancelCall.reject(wrapReason(data.reason)); 15179 } 15180 this.#deleteStreamController(streamController, streamId); 15181 break; 15182 case StreamKind.CANCEL: 15183 if (!streamSink) { 15184 break; 15185 } 15186 const dataReason = wrapReason(data.reason); 15187 Promise.try(streamSink.onCancel || onFn, dataReason).then(function () { 15188 comObj.postMessage({ 15189 sourceName, 15190 targetName, 15191 stream: StreamKind.CANCEL_COMPLETE, 15192 streamId, 15193 success: true 15194 }); 15195 }, function (reason) { 15196 comObj.postMessage({ 15197 sourceName, 15198 targetName, 15199 stream: StreamKind.CANCEL_COMPLETE, 15200 streamId, 15201 reason: wrapReason(reason) 15202 }); 15203 }); 15204 streamSink.sinkCapability.reject(dataReason); 15205 streamSink.isCancelled = true; 15206 delete this.streamSinks[streamId]; 15207 break; 15208 default: 15209 throw new Error("Unexpected stream case"); 15210 } 15211 } 15212 async #deleteStreamController(streamController, streamId) { 15213 await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]); 15214 delete this.streamControllers[streamId]; 15215 } 15216 destroy() { 15217 this.#messageAC?.abort(); 15218 this.#messageAC = null; 15219 } 15220} 15221 15222;// ./src/display/canvas_factory.js 15223 15224class BaseCanvasFactory { 15225 #enableHWA = false;
vendor: 35,769 bytes, lines 15226-16427
15226 constructor({ 15227 enableHWA = false 15228 }) { 15229 this.#enableHWA = enableHWA; 15230 } 15231 create(width, height) { 15232 if (width <= 0 || height <= 0) { 15233 throw new Error("Invalid canvas size"); 15234 } 15235 const canvas = this._createCanvas(width, height); 15236 return { 15237 canvas, 15238 context: canvas.getContext("2d", { 15239 willReadFrequently: !this.#enableHWA 15240 }) 15241 }; 15242 } 15243 reset(canvasAndContext, width, height) { 15244 if (!canvasAndContext.canvas) { 15245 throw new Error("Canvas is not specified"); 15246 } 15247 if (width <= 0 || height <= 0) { 15248 throw new Error("Invalid canvas size"); 15249 } 15250 canvasAndContext.canvas.width = width; 15251 canvasAndContext.canvas.height = height; 15252 } 15253 destroy(canvasAndContext) { 15254 if (!canvasAndContext.canvas) { 15255 throw new Error("Canvas is not specified"); 15256 } 15257 canvasAndContext.canvas.width = 0; 15258 canvasAndContext.canvas.height = 0; 15259 canvasAndContext.canvas = null; 15260 canvasAndContext.context = null; 15261 } 15262 _createCanvas(width, height) { 15263 unreachable("Abstract method `_createCanvas` called."); 15264 } 15265} 15266class DOMCanvasFactory extends BaseCanvasFactory { 15267 constructor({ 15268 ownerDocument = globalThis.document, 15269 enableHWA = false 15270 }) { 15271 super({ 15272 enableHWA 15273 }); 15274 this._document = ownerDocument; 15275 } 15276 _createCanvas(width, height) { 15277 const canvas = this._document.createElement("canvas"); 15278 canvas.width = width; 15279 canvas.height = height; 15280 return canvas; 15281 } 15282} 15283 15284;// ./src/display/cmap_reader_factory.js 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295class BaseCMapReaderFactory { 15296 constructor({ 15297 baseUrl = null, 15298 isCompressed = true 15299 }) { 15300 this.baseUrl = baseUrl; 15301 this.isCompressed = isCompressed; 15302 } 15303 async fetch({ 15304 name 15305 }) { 15306 if (!this.baseUrl) { 15307 throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."); 15308 } 15309 if (!name) { 15310 throw new Error("CMap name must be specified."); 15311 } 15312 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); 15313 return this._fetch(url).then(cMapData => ({ 15314 cMapData, 15315 isCompressed: this.isCompressed 15316 })).catch(reason => { 15317 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); 15318 }); 15319 } 15320 async _fetch(url) { 15321 unreachable("Abstract method `_fetch` called."); 15322 } 15323} 15324class DOMCMapReaderFactory extends BaseCMapReaderFactory { 15325 async _fetch(url) { 15326 const data = await fetchData(url, this.isCompressed ? "bytes" : "text"); 15327 return data instanceof Uint8Array ? data : stringToBytes(data); 15328 } 15329} 15330 15331// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.filter.js 15332var es_iterator_filter = __webpack_require__(2489); 15333;// ./src/display/filter_factory.js 15334 15335 15336 15337 15338 15339 15340class BaseFilterFactory { 15341 addFilter(maps) { 15342 return "none"; 15343 } 15344 addHCMFilter(fgColor, bgColor) { 15345 return "none"; 15346 } 15347 addAlphaFilter(map) { 15348 return "none"; 15349 } 15350 addLuminosityFilter(map) { 15351 return "none"; 15352 } 15353 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { 15354 return "none"; 15355 } 15356 destroy(keepHCM = false) {} 15357} 15358class DOMFilterFactory extends BaseFilterFactory { 15359 #baseUrl; 15360 #_cache; 15361 #_defs; 15362 #docId; 15363 #document; 15364 #_hcmCache; 15365 #id = 0; 15366 constructor({ 15367 docId, 15368 ownerDocument = globalThis.document 15369 }) { 15370 super(); 15371 this.#docId = docId; 15372 this.#document = ownerDocument; 15373 } 15374 get #cache() { 15375 return this.#_cache ||= new Map(); 15376 } 15377 get #hcmCache() { 15378 return this.#_hcmCache ||= new Map(); 15379 } 15380 get #defs() { 15381 if (!this.#_defs) { 15382 const div = this.#document.createElement("div"); 15383 const { 15384 style 15385 } = div; 15386 style.visibility = "hidden"; 15387 style.contain = "strict"; 15388 style.width = style.height = 0; 15389 style.position = "absolute"; 15390 style.top = style.left = 0; 15391 style.zIndex = -1; 15392 const svg = this.#document.createElementNS(SVG_NS, "svg"); 15393 svg.setAttribute("width", 0); 15394 svg.setAttribute("height", 0); 15395 this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); 15396 div.append(svg); 15397 svg.append(this.#_defs); 15398 this.#document.body.append(div); 15399 } 15400 return this.#_defs; 15401 } 15402 #createTables(maps) { 15403 if (maps.length === 1) { 15404 const mapR = maps[0]; 15405 const buffer = new Array(256); 15406 for (let i = 0; i < 256; i++) { 15407 buffer[i] = mapR[i] / 255; 15408 } 15409 const table = buffer.join(","); 15410 return [table, table, table]; 15411 } 15412 const [mapR, mapG, mapB] = maps; 15413 const bufferR = new Array(256); 15414 const bufferG = new Array(256); 15415 const bufferB = new Array(256); 15416 for (let i = 0; i < 256; i++) { 15417 bufferR[i] = mapR[i] / 255; 15418 bufferG[i] = mapG[i] / 255; 15419 bufferB[i] = mapB[i] / 255; 15420 } 15421 return [bufferR.join(","), bufferG.join(","), bufferB.join(",")]; 15422 } 15423 #createUrl(id) { 15424 if (this.#baseUrl === undefined) { 15425 this.#baseUrl = ""; 15426 const url = this.#document.URL; 15427 if (url !== this.#document.baseURI) { 15428 if (isDataScheme(url)) { 15429 warn('#createUrl: ignore "data:"-URL for performance reasons.'); 15430 } else { 15431 this.#baseUrl = updateUrlHash(url, ""); 15432 } 15433 } 15434 } 15435 return `url(${this.#baseUrl}#${id})`; 15436 } 15437 addFilter(maps) { 15438 if (!maps) { 15439 return "none"; 15440 } 15441 let value = this.#cache.get(maps); 15442 if (value) { 15443 return value; 15444 } 15445 const [tableR, tableG, tableB] = this.#createTables(maps); 15446 const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`; 15447 value = this.#cache.get(key); 15448 if (value) { 15449 this.#cache.set(maps, value); 15450 return value; 15451 } 15452 const id = `g_${this.#docId}_transfer_map_${this.#id++}`; 15453 const url = this.#createUrl(id); 15454 this.#cache.set(maps, url); 15455 this.#cache.set(key, url); 15456 const filter = this.#createFilter(id); 15457 this.#addTransferMapConversion(tableR, tableG, tableB, filter); 15458 return url; 15459 } 15460 addHCMFilter(fgColor, bgColor) { 15461 const key = `${fgColor}-${bgColor}`; 15462 const filterName = "base"; 15463 let info = this.#hcmCache.get(filterName); 15464 if (info?.key === key) { 15465 return info.url; 15466 } 15467 if (info) { 15468 info.filter?.remove(); 15469 info.key = key; 15470 info.url = "none"; 15471 info.filter = null; 15472 } else { 15473 info = { 15474 key, 15475 url: "none", 15476 filter: null 15477 }; 15478 this.#hcmCache.set(filterName, info); 15479 } 15480 if (!fgColor || !bgColor) { 15481 return info.url; 15482 } 15483 const fgRGB = this.#getRGB(fgColor); 15484 fgColor = Util.makeHexColor(...fgRGB); 15485 const bgRGB = this.#getRGB(bgColor); 15486 bgColor = Util.makeHexColor(...bgRGB); 15487 this.#defs.style.color = ""; 15488 if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { 15489 return info.url; 15490 } 15491 const map = new Array(256); 15492 for (let i = 0; i <= 255; i++) { 15493 const x = i / 255; 15494 map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; 15495 } 15496 const table = map.join(","); 15497 const id = `g_${this.#docId}_hcm_filter`; 15498 const filter = info.filter = this.#createFilter(id); 15499 this.#addTransferMapConversion(table, table, table, filter); 15500 this.#addGrayConversion(filter); 15501 const getSteps = (c, n) => { 15502 const start = fgRGB[c] / 255; 15503 const end = bgRGB[c] / 255; 15504 const arr = new Array(n + 1); 15505 for (let i = 0; i <= n; i++) { 15506 arr[i] = start + i / n * (end - start); 15507 } 15508 return arr.join(","); 15509 }; 15510 this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); 15511 info.url = this.#createUrl(id); 15512 return info.url; 15513 } 15514 addAlphaFilter(map) { 15515 let value = this.#cache.get(map); 15516 if (value) { 15517 return value; 15518 } 15519 const [tableA] = this.#createTables([map]); 15520 const key = `alpha_${tableA}`; 15521 value = this.#cache.get(key); 15522 if (value) { 15523 this.#cache.set(map, value); 15524 return value; 15525 } 15526 const id = `g_${this.#docId}_alpha_map_${this.#id++}`; 15527 const url = this.#createUrl(id); 15528 this.#cache.set(map, url); 15529 this.#cache.set(key, url); 15530 const filter = this.#createFilter(id); 15531 this.#addTransferMapAlphaConversion(tableA, filter); 15532 return url; 15533 } 15534 addLuminosityFilter(map) { 15535 let value = this.#cache.get(map || "luminosity"); 15536 if (value) { 15537 return value; 15538 } 15539 let tableA, key; 15540 if (map) { 15541 [tableA] = this.#createTables([map]); 15542 key = `luminosity_${tableA}`; 15543 } else { 15544 key = "luminosity"; 15545 } 15546 value = this.#cache.get(key); 15547 if (value) { 15548 this.#cache.set(map, value); 15549 return value; 15550 } 15551 const id = `g_${this.#docId}_luminosity_map_${this.#id++}`; 15552 const url = this.#createUrl(id); 15553 this.#cache.set(map, url); 15554 this.#cache.set(key, url); 15555 const filter = this.#createFilter(id); 15556 this.#addLuminosityConversion(filter); 15557 if (map) { 15558 this.#addTransferMapAlphaConversion(tableA, filter); 15559 } 15560 return url; 15561 } 15562 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { 15563 const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; 15564 let info = this.#hcmCache.get(filterName); 15565 if (info?.key === key) { 15566 return info.url; 15567 } 15568 if (info) { 15569 info.filter?.remove(); 15570 info.key = key; 15571 info.url = "none"; 15572 info.filter = null; 15573 } else { 15574 info = { 15575 key, 15576 url: "none", 15577 filter: null 15578 }; 15579 this.#hcmCache.set(filterName, info); 15580 } 15581 if (!fgColor || !bgColor) { 15582 return info.url; 15583 } 15584 const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); 15585 let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); 15586 let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); 15587 let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); 15588 if (bgGray < fgGray) { 15589 [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; 15590 } 15591 this.#defs.style.color = ""; 15592 const getSteps = (fg, bg, n) => { 15593 const arr = new Array(256); 15594 const step = (bgGray - fgGray) / n; 15595 const newStart = fg / 255; 15596 const newStep = (bg - fg) / (255 * n); 15597 let prev = 0; 15598 for (let i = 0; i <= n; i++) { 15599 const k = Math.round(fgGray + i * step); 15600 const value = newStart + i * newStep; 15601 for (let j = prev; j <= k; j++) { 15602 arr[j] = value; 15603 } 15604 prev = k + 1; 15605 } 15606 for (let i = prev; i < 256; i++) { 15607 arr[i] = arr[prev - 1]; 15608 } 15609 return arr.join(","); 15610 }; 15611 const id = `g_${this.#docId}_hcm_${filterName}_filter`; 15612 const filter = info.filter = this.#createFilter(id); 15613 this.#addGrayConversion(filter); 15614 this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter); 15615 info.url = this.#createUrl(id); 15616 return info.url; 15617 } 15618 destroy(keepHCM = false) { 15619 if (keepHCM && this.#_hcmCache?.size) { 15620 return; 15621 } 15622 this.#_defs?.parentNode.parentNode.remove(); 15623 this.#_defs = null; 15624 this.#_cache?.clear(); 15625 this.#_cache = null; 15626 this.#_hcmCache?.clear(); 15627 this.#_hcmCache = null; 15628 this.#id = 0; 15629 } 15630 #addLuminosityConversion(filter) { 15631 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); 15632 feColorMatrix.setAttribute("type", "matrix"); 15633 feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"); 15634 filter.append(feColorMatrix); 15635 } 15636 #addGrayConversion(filter) { 15637 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); 15638 feColorMatrix.setAttribute("type", "matrix"); 15639 feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"); 15640 filter.append(feColorMatrix); 15641 } 15642 #createFilter(id) { 15643 const filter = this.#document.createElementNS(SVG_NS, "filter"); 15644 filter.setAttribute("color-interpolation-filters", "sRGB"); 15645 filter.setAttribute("id", id); 15646 this.#defs.append(filter); 15647 return filter; 15648 } 15649 #appendFeFunc(feComponentTransfer, func, table) { 15650 const feFunc = this.#document.createElementNS(SVG_NS, func); 15651 feFunc.setAttribute("type", "discrete"); 15652 feFunc.setAttribute("tableValues", table); 15653 feComponentTransfer.append(feFunc); 15654 } 15655 #addTransferMapConversion(rTable, gTable, bTable, filter) { 15656 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); 15657 filter.append(feComponentTransfer); 15658 this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); 15659 this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); 15660 this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); 15661 } 15662 #addTransferMapAlphaConversion(aTable, filter) { 15663 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); 15664 filter.append(feComponentTransfer); 15665 this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); 15666 } 15667 #getRGB(color) { 15668 this.#defs.style.color = color; 15669 return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); 15670 } 15671} 15672 15673;// ./src/display/standard_fontdata_factory.js 15674 15675 15676class BaseStandardFontDataFactory { 15677 constructor({ 15678 baseUrl = null 15679 }) { 15680 this.baseUrl = baseUrl; 15681 } 15682 async fetch({ 15683 filename 15684 }) { 15685 if (!this.baseUrl) { 15686 throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided."); 15687 } 15688 if (!filename) { 15689 throw new Error("Font filename must be specified."); 15690 } 15691 const url = `${this.baseUrl}${filename}`; 15692 return this._fetch(url).catch(reason => { 15693 throw new Error(`Unable to load font data at: ${url}`); 15694 }); 15695 } 15696 async _fetch(url) { 15697 unreachable("Abstract method `_fetch` called."); 15698 } 15699} 15700class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { 15701 async _fetch(url) { 15702 return fetchData(url, "bytes"); 15703 } 15704} 15705 15706;// ./src/display/wasm_factory.js 15707 15708 15709class BaseWasmFactory { 15710 constructor({ 15711 baseUrl = null 15712 }) { 15713 this.baseUrl = baseUrl; 15714 } 15715 async fetch({ 15716 filename 15717 }) { 15718 if (!this.baseUrl) { 15719 throw new Error("Ensure that the `wasmUrl` API parameter is provided."); 15720 } 15721 if (!filename) { 15722 throw new Error("Wasm filename must be specified."); 15723 } 15724 const url = `${this.baseUrl}${filename}`; 15725 return this._fetch(url).catch(reason => { 15726 throw new Error(`Unable to load wasm data at: ${url}`); 15727 }); 15728 } 15729 async _fetch(url) { 15730 unreachable("Abstract method `_fetch` called."); 15731 } 15732} 15733class DOMWasmFactory extends BaseWasmFactory { 15734 async _fetch(url) { 15735 return fetchData(url, "bytes"); 15736 } 15737} 15738 15739;// ./src/display/node_utils.js 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754if (isNodeJS) { 15755 let canvas; 15756 try { 15757 const require = process.getBuiltinModule("module").createRequire(import.meta.url); 15758 try { 15759 canvas = require("@napi-rs/canvas"); 15760 } catch (ex) { 15761 warn(`Cannot load "@napi-rs/canvas" package: "${ex}".`); 15762 } 15763 } catch (ex) { 15764 warn(`Cannot access the \`require\` function: "${ex}".`); 15765 } 15766 if (!globalThis.DOMMatrix) { 15767 if (canvas?.DOMMatrix) { 15768 globalThis.DOMMatrix = canvas.DOMMatrix; 15769 } else { 15770 warn("Cannot polyfill `DOMMatrix`, rendering may be broken."); 15771 } 15772 } 15773 if (!globalThis.ImageData) { 15774 if (canvas?.ImageData) { 15775 globalThis.ImageData = canvas.ImageData; 15776 } else { 15777 warn("Cannot polyfill `ImageData`, rendering may be broken."); 15778 } 15779 } 15780 if (!globalThis.Path2D) { 15781 if (canvas?.Path2D) { 15782 globalThis.Path2D = canvas.Path2D; 15783 } else { 15784 warn("Cannot polyfill `Path2D`, rendering may be broken."); 15785 } 15786 } 15787 if (!globalThis.navigator?.language) { 15788 globalThis.navigator = { 15789 language: "en-US", 15790 platform: "", 15791 userAgent: "" 15792 }; 15793 } 15794} 15795async function node_utils_fetchData(url) { 15796 const fs = process.getBuiltinModule("fs"); 15797 const data = await fs.promises.readFile(url); 15798 return new Uint8Array(data); 15799} 15800class NodeFilterFactory extends BaseFilterFactory {} 15801class NodeCanvasFactory extends BaseCanvasFactory { 15802 _createCanvas(width, height) { 15803 const require = process.getBuiltinModule("module").createRequire(import.meta.url); 15804 const canvas = require("@napi-rs/canvas"); 15805 return canvas.createCanvas(width, height); 15806 } 15807} 15808class NodeCMapReaderFactory extends BaseCMapReaderFactory { 15809 async _fetch(url) { 15810 return node_utils_fetchData(url); 15811 } 15812} 15813class NodeStandardFontDataFactory extends BaseStandardFontDataFactory { 15814 async _fetch(url) { 15815 return node_utils_fetchData(url); 15816 } 15817} 15818class NodeWasmFactory extends BaseWasmFactory { 15819 async _fetch(url) { 15820 return node_utils_fetchData(url); 15821 } 15822} 15823 15824// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.for-each.js 15825var es_iterator_for_each = __webpack_require__(7588); 15826;// ./src/display/canvas_dependency_tracker.js 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848const FORCED_DEPENDENCY_LABEL = "__forcedDependency"; 15849const { 15850 floor, 15851 ceil 15852} = Math; 15853function expandBBox(array, index, minX, minY, maxX, maxY) { 15854 array[index * 4 + 0] = Math.min(array[index * 4 + 0], minX); 15855 array[index * 4 + 1] = Math.min(array[index * 4 + 1], minY); 15856 array[index * 4 + 2] = Math.max(array[index * 4 + 2], maxX); 15857 array[index * 4 + 3] = Math.max(array[index * 4 + 3], maxY); 15858} 15859const EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0]; 15860class BBoxReader { 15861 #bboxes; 15862 #coords; 15863 constructor(bboxes, coords) { 15864 this.#bboxes = bboxes; 15865 this.#coords = coords; 15866 } 15867 get length() { 15868 return this.#bboxes.length; 15869 } 15870 isEmpty(i) { 15871 return this.#bboxes[i] === EMPTY_BBOX; 15872 } 15873 minX(i) { 15874 return this.#coords[i * 4 + 0] / 256; 15875 } 15876 minY(i) { 15877 return this.#coords[i * 4 + 1] / 256; 15878 } 15879 maxX(i) { 15880 return (this.#coords[i * 4 + 2] + 1) / 256; 15881 } 15882 maxY(i) { 15883 return (this.#coords[i * 4 + 3] + 1) / 256; 15884 } 15885} 15886const ensureDebugMetadata = (map, key) => map?.getOrInsertComputed(key, () => ({ 15887 dependencies: new Set(), 15888 isRenderingOperation: false 15889})); 15890class CanvasDependencyTracker { 15891 #simple = { 15892 __proto__: null 15893 }; 15894 #incremental = { 15895 __proto__: null, 15896 transform: [], 15897 moveText: [], 15898 sameLineText: [], 15899 [FORCED_DEPENDENCY_LABEL]: [] 15900 }; 15901 #namedDependencies = new Map(); 15902 #savesStack = []; 15903 #markedContentStack = []; 15904 #baseTransformStack = [[1, 0, 0, 1, 0, 0]]; 15905 #clipBox = [-Infinity, -Infinity, Infinity, Infinity]; 15906 #pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]); 15907 #pendingBBoxIdx = -1; 15908 #pendingDependencies = new Set(); 15909 #operations = new Map(); 15910 #fontBBoxTrustworthy = new Map(); 15911 #canvasWidth; 15912 #canvasHeight; 15913 #bboxesCoords; 15914 #bboxes; 15915 #debugMetadata; 15916 constructor(canvas, operationsCount, recordDebugMetadata = false) { 15917 this.#canvasWidth = canvas.width; 15918 this.#canvasHeight = canvas.height; 15919 this.#initializeBBoxes(operationsCount); 15920 if (recordDebugMetadata) { 15921 this.#debugMetadata = new Map(); 15922 } 15923 } 15924 growOperationsCount(operationsCount) { 15925 if (operationsCount >= this.#bboxes.length) { 15926 this.#initializeBBoxes(operationsCount, this.#bboxes); 15927 } 15928 } 15929 #initializeBBoxes(operationsCount, oldBBoxes) { 15930 const buffer = new ArrayBuffer(operationsCount * 4); 15931 this.#bboxesCoords = new Uint8ClampedArray(buffer); 15932 this.#bboxes = new Uint32Array(buffer); 15933 if (oldBBoxes && oldBBoxes.length > 0) { 15934 this.#bboxes.set(oldBBoxes); 15935 this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length); 15936 } else { 15937 this.#bboxes.fill(EMPTY_BBOX); 15938 } 15939 } 15940 save(opIdx) { 15941 this.#simple = { 15942 __proto__: this.#simple 15943 }; 15944 this.#incremental = { 15945 __proto__: this.#incremental, 15946 transform: { 15947 __proto__: this.#incremental.transform 15948 }, 15949 moveText: { 15950 __proto__: this.#incremental.moveText 15951 }, 15952 sameLineText: { 15953 __proto__: this.#incremental.sameLineText 15954 }, 15955 [FORCED_DEPENDENCY_LABEL]: { 15956 __proto__: this.#incremental[FORCED_DEPENDENCY_LABEL] 15957 } 15958 }; 15959 this.#clipBox = { 15960 __proto__: this.#clipBox 15961 }; 15962 this.#savesStack.push(opIdx); 15963 return this; 15964 } 15965 restore(opIdx) { 15966 const previous = Object.getPrototypeOf(this.#simple); 15967 if (previous === null) { 15968 return this; 15969 } 15970 this.#simple = previous; 15971 this.#incremental = Object.getPrototypeOf(this.#incremental); 15972 this.#clipBox = Object.getPrototypeOf(this.#clipBox); 15973 const lastSave = this.#savesStack.pop(); 15974 if (lastSave !== undefined) { 15975 ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); 15976 this.#bboxes[opIdx] = this.#bboxes[lastSave]; 15977 } 15978 return this; 15979 } 15980 recordOpenMarker(idx) { 15981 this.#savesStack.push(idx); 15982 return this; 15983 } 15984 getOpenMarker() { 15985 if (this.#savesStack.length === 0) { 15986 return null; 15987 } 15988 return this.#savesStack.at(-1); 15989 } 15990 recordCloseMarker(opIdx) { 15991 const lastSave = this.#savesStack.pop(); 15992 if (lastSave !== undefined) { 15993 ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); 15994 this.#bboxes[opIdx] = this.#bboxes[lastSave]; 15995 } 15996 return this; 15997 } 15998 beginMarkedContent(opIdx) { 15999 this.#markedContentStack.push(opIdx); 16000 return this; 16001 } 16002 endMarkedContent(opIdx) { 16003 const lastSave = this.#markedContentStack.pop(); 16004 if (lastSave !== undefined) { 16005 ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); 16006 this.#bboxes[opIdx] = this.#bboxes[lastSave]; 16007 } 16008 return this; 16009 } 16010 pushBaseTransform(ctx) { 16011 this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform())); 16012 return this; 16013 } 16014 popBaseTransform() { 16015 if (this.#baseTransformStack.length > 1) { 16016 this.#baseTransformStack.pop(); 16017 } 16018 return this; 16019 } 16020 recordSimpleData(name, idx) { 16021 this.#simple[name] = idx; 16022 return this; 16023 } 16024 recordIncrementalData(name, idx) { 16025 this.#incremental[name].push(idx); 16026 return this; 16027 } 16028 resetIncrementalData(name, idx) { 16029 this.#incremental[name].length = 0; 16030 return this; 16031 } 16032 recordNamedData(name, idx) { 16033 this.#namedDependencies.set(name, idx); 16034 return this; 16035 } 16036 recordSimpleDataFromNamed(name, depName, fallbackIdx) { 16037 this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx; 16038 } 16039 recordFutureForcedDependency(name, idx) { 16040 this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx); 16041 return this; 16042 } 16043 inheritSimpleDataAsFutureForcedDependencies(names) { 16044 for (const name of names) { 16045 if (name in this.#simple) { 16046 this.recordFutureForcedDependency(name, this.#simple[name]); 16047 } 16048 } 16049 return this; 16050 } 16051 inheritPendingDependenciesAsFutureForcedDependencies() { 16052 for (const dep of this.#pendingDependencies) { 16053 this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep); 16054 } 16055 return this; 16056 } 16057 resetBBox(idx) { 16058 if (this.#pendingBBoxIdx !== idx) { 16059 this.#pendingBBoxIdx = idx; 16060 this.#pendingBBox[0] = Infinity; 16061 this.#pendingBBox[1] = Infinity; 16062 this.#pendingBBox[2] = -Infinity; 16063 this.#pendingBBox[3] = -Infinity; 16064 } 16065 return this; 16066 } 16067 recordClipBox(idx, ctx, minX, maxX, minY, maxY) { 16068 const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); 16069 const clipBox = [Infinity, Infinity, -Infinity, -Infinity]; 16070 Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox); 16071 const intersection = Util.intersect(this.#clipBox, clipBox); 16072 if (intersection) { 16073 this.#clipBox[0] = intersection[0]; 16074 this.#clipBox[1] = intersection[1]; 16075 this.#clipBox[2] = intersection[2]; 16076 this.#clipBox[3] = intersection[3]; 16077 } else { 16078 this.#clipBox[0] = this.#clipBox[1] = Infinity; 16079 this.#clipBox[2] = this.#clipBox[3] = -Infinity; 16080 } 16081 return this; 16082 } 16083 recordBBox(idx, ctx, minX, maxX, minY, maxY) { 16084 const clipBox = this.#clipBox; 16085 if (clipBox[0] === Infinity) { 16086 return this; 16087 } 16088 const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); 16089 if (clipBox[0] === -Infinity) { 16090 Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox); 16091 return this; 16092 } 16093 const bbox = [Infinity, Infinity, -Infinity, -Infinity]; 16094 Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox); 16095 this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0])); 16096 this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1])); 16097 this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2])); 16098 this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3])); 16099 return this; 16100 } 16101 recordCharacterBBox(idx, ctx, font, scale = 1, x = 0, y = 0, getMeasure) { 16102 const fontBBox = font.bbox; 16103 let isBBoxTrustworthy; 16104 let computedBBox; 16105 if (fontBBox) { 16106 isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font); 16107 if (isBBoxTrustworthy !== false) { 16108 computedBBox = [0, 0, 0, 0]; 16109 Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox); 16110 if (scale !== 1 || x !== 0 || y !== 0) { 16111 Util.scaleMinMax([scale, 0, 0, -scale, x, y], computedBBox); 16112 } 16113 if (isBBoxTrustworthy) { 16114 return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); 16115 } 16116 } 16117 } 16118 if (!getMeasure) { 16119 return this.recordFullPageBBox(idx); 16120 } 16121 const measure = getMeasure(); 16122 if (fontBBox && computedBBox && isBBoxTrustworthy === undefined) { 16123 isBBoxTrustworthy = computedBBox[0] <= x - measure.actualBoundingBoxLeft && computedBBox[2] >= x + measure.actualBoundingBoxRight && computedBBox[1] <= y - measure.actualBoundingBoxAscent && computedBBox[3] >= y + measure.actualBoundingBoxDescent; 16124 this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy); 16125 if (isBBoxTrustworthy) { 16126 return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); 16127 } 16128 } 16129 return this.recordBBox(idx, ctx, x - measure.actualBoundingBoxLeft, x + measure.actualBoundingBoxRight, y - measure.actualBoundingBoxAscent, y + measure.actualBoundingBoxDescent); 16130 } 16131 recordFullPageBBox(idx) { 16132 this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]); 16133 this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]); 16134 this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]); 16135 this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]); 16136 return this; 16137 } 16138 getSimpleIndex(dependencyName) { 16139 return this.#simple[dependencyName]; 16140 } 16141 recordDependencies(idx, dependencyNames) { 16142 const pendingDependencies = this.#pendingDependencies; 16143 const simple = this.#simple; 16144 const incremental = this.#incremental; 16145 for (const name of dependencyNames) { 16146 if (name in this.#simple) { 16147 pendingDependencies.add(simple[name]); 16148 } else if (name in incremental) { 16149 incremental[name].forEach(pendingDependencies.add, pendingDependencies); 16150 } 16151 } 16152 return this; 16153 } 16154 recordNamedDependency(idx, name) { 16155 if (this.#namedDependencies.has(name)) { 16156 this.#pendingDependencies.add(this.#namedDependencies.get(name)); 16157 } 16158 return this; 16159 } 16160 recordOperation(idx, preserve = false) { 16161 this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]); 16162 if (this.#debugMetadata) { 16163 const metadata = ensureDebugMetadata(this.#debugMetadata, idx); 16164 const { 16165 dependencies 16166 } = metadata; 16167 this.#pendingDependencies.forEach(dependencies.add, dependencies); 16168 this.#savesStack.forEach(dependencies.add, dependencies); 16169 this.#markedContentStack.forEach(dependencies.add, dependencies); 16170 dependencies.delete(idx); 16171 metadata.isRenderingOperation = true; 16172 } 16173 if (this.#pendingBBoxIdx === idx) { 16174 const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth); 16175 const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight); 16176 const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth); 16177 const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight); 16178 expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY); 16179 for (const depIdx of this.#pendingDependencies) { 16180 if (depIdx !== idx) { 16181 expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY); 16182 } 16183 } 16184 for (const saveIdx of this.#savesStack) { 16185 if (saveIdx !== idx) { 16186 expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); 16187 } 16188 } 16189 for (const saveIdx of this.#markedContentStack) { 16190 if (saveIdx !== idx) { 16191 expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); 16192 } 16193 } 16194 if (!preserve) { 16195 this.#pendingDependencies.clear(); 16196 this.#pendingBBoxIdx = -1; 16197 } 16198 } 16199 return this; 16200 } 16201 recordShowTextOperation(idx, preserve = false) { 16202 const deps = Array.from(this.#pendingDependencies); 16203 this.recordOperation(idx, preserve); 16204 this.recordIncrementalData("sameLineText", idx); 16205 for (const dep of deps) { 16206 this.recordIncrementalData("sameLineText", dep); 16207 } 16208 return this; 16209 } 16210 bboxToClipBoxDropOperation(idx, preserve = false) { 16211 if (this.#pendingBBoxIdx === idx) { 16212 this.#pendingBBoxIdx = -1; 16213 this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]); 16214 this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]); 16215 this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]); 16216 this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]); 16217 if (!preserve) { 16218 this.#pendingDependencies.clear(); 16219 } 16220 } 16221 return this; 16222 } 16223 _takePendingDependencies() { 16224 const pendingDependencies = this.#pendingDependencies; 16225 this.#pendingDependencies = new Set(); 16226 return pendingDependencies; 16227 } 16228 _extractOperation(idx) { 16229 const operation = this.#operations.get(idx); 16230 this.#operations.delete(idx); 16231 return operation; 16232 } 16233 _pushPendingDependencies(dependencies) { 16234 for (const dep of dependencies) { 16235 this.#pendingDependencies.add(dep); 16236 } 16237 } 16238 take() { 16239 this.#fontBBoxTrustworthy.clear(); 16240 return new BBoxReader(this.#bboxes, this.#bboxesCoords); 16241 } 16242 takeDebugMetadata() { 16243 return this.#debugMetadata; 16244 } 16245} 16246class CanvasNestedDependencyTracker { 16247 #dependencyTracker; 16248 #opIdx; 16249 #ignoreBBoxes; 16250 #nestingLevel = 0; 16251 #savesLevel = 0; 16252 constructor(dependencyTracker, opIdx, ignoreBBoxes) { 16253 if (dependencyTracker instanceof CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) { 16254 return dependencyTracker; 16255 } 16256 this.#dependencyTracker = dependencyTracker; 16257 this.#opIdx = opIdx; 16258 this.#ignoreBBoxes = !!ignoreBBoxes; 16259 } 16260 growOperationsCount() { 16261 throw new Error("Unreachable"); 16262 } 16263 save(opIdx) { 16264 this.#savesLevel++; 16265 this.#dependencyTracker.save(this.#opIdx); 16266 return this; 16267 } 16268 restore(opIdx) { 16269 if (this.#savesLevel > 0) { 16270 this.#dependencyTracker.restore(this.#opIdx); 16271 this.#savesLevel--; 16272 } 16273 return this; 16274 } 16275 recordOpenMarker(idx) { 16276 this.#nestingLevel++; 16277 return this; 16278 } 16279 getOpenMarker() { 16280 return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker(); 16281 } 16282 recordCloseMarker(idx) { 16283 this.#nestingLevel--; 16284 return this; 16285 } 16286 beginMarkedContent(opIdx) { 16287 return this; 16288 } 16289 endMarkedContent(opIdx) { 16290 return this; 16291 } 16292 pushBaseTransform(ctx) { 16293 this.#dependencyTracker.pushBaseTransform(ctx); 16294 return this; 16295 } 16296 popBaseTransform() { 16297 this.#dependencyTracker.popBaseTransform(); 16298 return this; 16299 } 16300 recordSimpleData(name, idx) { 16301 this.#dependencyTracker.recordSimpleData(name, this.#opIdx); 16302 return this; 16303 } 16304 recordIncrementalData(name, idx) { 16305 this.#dependencyTracker.recordIncrementalData(name, this.#opIdx); 16306 return this; 16307 } 16308 resetIncrementalData(name, idx) { 16309 this.#dependencyTracker.resetIncrementalData(name, this.#opIdx); 16310 return this; 16311 } 16312 recordNamedData(name, idx) { 16313 return this; 16314 } 16315 recordSimpleDataFromNamed(name, depName, fallbackIdx) { 16316 this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx); 16317 return this; 16318 } 16319 recordFutureForcedDependency(name, idx) { 16320 this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx); 16321 return this; 16322 } 16323 inheritSimpleDataAsFutureForcedDependencies(names) { 16324 this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names); 16325 return this; 16326 } 16327 inheritPendingDependenciesAsFutureForcedDependencies() { 16328 this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies(); 16329 return this; 16330 } 16331 resetBBox(idx) { 16332 if (!this.#ignoreBBoxes) { 16333 this.#dependencyTracker.resetBBox(this.#opIdx); 16334 } 16335 return this; 16336 } 16337 recordClipBox(idx, ctx, minX, maxX, minY, maxY) { 16338 if (!this.#ignoreBBoxes) { 16339 this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY); 16340 } 16341 return this; 16342 } 16343 recordBBox(idx, ctx, minX, maxX, minY, maxY) { 16344 if (!this.#ignoreBBoxes) { 16345 this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY); 16346 } 16347 return this; 16348 } 16349 recordCharacterBBox(idx, ctx, font, scale, x, y, getMeasure) { 16350 if (!this.#ignoreBBoxes) { 16351 this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x, y, getMeasure); 16352 } 16353 return this; 16354 } 16355 recordFullPageBBox(idx) { 16356 if (!this.#ignoreBBoxes) { 16357 this.#dependencyTracker.recordFullPageBBox(this.#opIdx); 16358 } 16359 return this; 16360 } 16361 getSimpleIndex(dependencyName) { 16362 return this.#dependencyTracker.getSimpleIndex(dependencyName); 16363 } 16364 recordDependencies(idx, dependencyNames) { 16365 this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames); 16366 return this; 16367 } 16368 recordNamedDependency(idx, name) { 16369 this.#dependencyTracker.recordNamedDependency(this.#opIdx, name); 16370 return this; 16371 } 16372 recordOperation(idx) { 16373 this.#dependencyTracker.recordOperation(this.#opIdx, true); 16374 return this; 16375 } 16376 recordShowTextOperation(idx) { 16377 this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true); 16378 return this; 16379 } 16380 bboxToClipBoxDropOperation(idx) { 16381 if (!this.#ignoreBBoxes) { 16382 this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true); 16383 } 16384 return this; 16385 } 16386 take() { 16387 throw new Error("Unreachable"); 16388 } 16389 takeDebugMetadata() { 16390 throw new Error("Unreachable"); 16391 } 16392} 16393const Dependencies = { 16394 stroke: ["path", "transform", "filter", "strokeColor", "strokeAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "dash"], 16395 fill: ["path", "transform", "filter", "fillColor", "fillAlpha", "globalCompositeOperation", "SMask"], 16396 imageXObject: ["transform", "SMask", "filter", "fillAlpha", "strokeAlpha", "globalCompositeOperation"], 16397 rawFillPath: ["filter", "fillColor", "fillAlpha"], 16398 showText: ["transform", "leading", "charSpacing", "wordSpacing", "hScale", "textRise", "moveText", "textMatrix", "font", "fontObj", "filter", "fillColor", "textRenderingMode", "SMask", "fillAlpha", "strokeAlpha", "globalCompositeOperation", "sameLineText"], 16399 transform: ["transform"], 16400 transformAndFill: ["transform", "fillColor"] 16401}; 16402 16403;// ./src/display/pattern_helper.js 16404 16405 16406 16407 16408 16409 16410const PathType = { 16411 FILL: "Fill", 16412 STROKE: "Stroke", 16413 SHADING: "Shading" 16414}; 16415function applyBoundingBox(ctx, bbox) { 16416 if (!bbox) { 16417 return; 16418 } 16419 const width = bbox[2] - bbox[0]; 16420 const height = bbox[3] - bbox[1]; 16421 const region = new Path2D(); 16422 region.rect(bbox[0], bbox[1], width, height); 16423 ctx.clip(region); 16424} 16425class BaseShadingPattern { 16426 isModifyingCurrentTransform() { 16427 return false;
vendor: 4,978 bytes, lines 16428-16581
16428 } 16429 getPattern() { 16430 unreachable("Abstract method `getPattern` called."); 16431 } 16432} 16433class RadialAxialShadingPattern extends BaseShadingPattern { 16434 constructor(IR) { 16435 super(); 16436 this._type = IR[1]; 16437 this._bbox = IR[2]; 16438 this._colorStops = IR[3]; 16439 this._p0 = IR[4]; 16440 this._p1 = IR[5]; 16441 this._r0 = IR[6]; 16442 this._r1 = IR[7]; 16443 this.matrix = null; 16444 } 16445 isOriginBased() { 16446 return this._p0[0] === 0 && this._p0[1] === 0 && (!this.isRadial() || this._p1[0] === 0 && this._p1[1] === 0); 16447 } 16448 isRadial() { 16449 return this._type === "radial"; 16450 } 16451 _createGradient(ctx, transform = null) { 16452 let grad; 16453 let firstPoint = this._p0; 16454 let secondPoint = this._p1; 16455 if (transform) { 16456 firstPoint = firstPoint.slice(); 16457 secondPoint = secondPoint.slice(); 16458 Util.applyTransform(firstPoint, transform); 16459 Util.applyTransform(secondPoint, transform); 16460 } 16461 if (this._type === "axial") { 16462 grad = ctx.createLinearGradient(firstPoint[0], firstPoint[1], secondPoint[0], secondPoint[1]); 16463 } else if (this._type === "radial") { 16464 let r0 = this._r0; 16465 let r1 = this._r1; 16466 if (transform) { 16467 const scale = new Float32Array(2); 16468 Util.singularValueDecompose2dScale(transform, scale); 16469 r0 *= scale[0]; 16470 r1 *= scale[0]; 16471 } 16472 grad = ctx.createRadialGradient(firstPoint[0], firstPoint[1], r0, secondPoint[0], secondPoint[1], r1); 16473 } 16474 for (const colorStop of this._colorStops) { 16475 grad.addColorStop(colorStop[0], colorStop[1]); 16476 } 16477 return grad; 16478 } 16479 getPattern(ctx, owner, inverse, pathType) { 16480 let pattern; 16481 if (pathType === PathType.STROKE || pathType === PathType.FILL) { 16482 if (this.isOriginBased()) { 16483 let transf = Util.transform(inverse, owner.baseTransform); 16484 if (this.matrix) { 16485 transf = Util.transform(transf, this.matrix); 16486 } 16487 const precision = 1e-3; 16488 const n1 = Math.hypot(transf[0], transf[1]); 16489 const n2 = Math.hypot(transf[2], transf[3]); 16490 const ps = (transf[0] * transf[2] + transf[1] * transf[3]) / (n1 * n2); 16491 if (Math.abs(ps) < precision) { 16492 if (this.isRadial()) { 16493 if (Math.abs(n1 - n2) < precision) { 16494 return this._createGradient(ctx, transf); 16495 } 16496 } else { 16497 return this._createGradient(ctx, transf); 16498 } 16499 } 16500 } 16501 const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0]; 16502 const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1; 16503 const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1; 16504 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height); 16505 const tmpCtx = tmpCanvas.context; 16506 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); 16507 tmpCtx.beginPath(); 16508 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); 16509 tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]); 16510 inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); 16511 tmpCtx.transform(...owner.baseTransform); 16512 if (this.matrix) { 16513 tmpCtx.transform(...this.matrix); 16514 } 16515 applyBoundingBox(tmpCtx, this._bbox); 16516 tmpCtx.fillStyle = this._createGradient(tmpCtx); 16517 tmpCtx.fill(); 16518 pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat"); 16519 const domMatrix = new DOMMatrix(inverse); 16520 pattern.setTransform(domMatrix); 16521 } else { 16522 applyBoundingBox(ctx, this._bbox); 16523 pattern = this._createGradient(ctx); 16524 } 16525 return pattern; 16526 } 16527} 16528function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { 16529 const coords = context.coords, 16530 colors = context.colors; 16531 const bytes = data.data, 16532 rowSize = data.width * 4; 16533 let tmp; 16534 if (coords[p1 + 1] > coords[p2 + 1]) { 16535 tmp = p1; 16536 p1 = p2; 16537 p2 = tmp; 16538 tmp = c1; 16539 c1 = c2; 16540 c2 = tmp; 16541 } 16542 if (coords[p2 + 1] > coords[p3 + 1]) { 16543 tmp = p2; 16544 p2 = p3; 16545 p3 = tmp; 16546 tmp = c2; 16547 c2 = c3; 16548 c3 = tmp; 16549 } 16550 if (coords[p1 + 1] > coords[p2 + 1]) { 16551 tmp = p1; 16552 p1 = p2; 16553 p2 = tmp; 16554 tmp = c1; 16555 c1 = c2; 16556 c2 = tmp; 16557 } 16558 const x1 = (coords[p1] + context.offsetX) * context.scaleX; 16559 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; 16560 const x2 = (coords[p2] + context.offsetX) * context.scaleX; 16561 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; 16562 const x3 = (coords[p3] + context.offsetX) * context.scaleX; 16563 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; 16564 if (y1 >= y3) { 16565 return; 16566 } 16567 const c1r = colors[c1], 16568 c1g = colors[c1 + 1], 16569 c1b = colors[c1 + 2]; 16570 const c2r = colors[c2], 16571 c2g = colors[c2 + 1], 16572 c2b = colors[c2 + 2]; 16573 const c3r = colors[c3], 16574 c3g = colors[c3 + 1], 16575 c3b = colors[c3 + 2]; 16576 const minY = Math.round(y1), 16577 maxY = Math.round(y3); 16578 let xa, car, cag, cab; 16579 let xb, cbr, cbg, cbb; 16580 for (let y = minY; y <= maxY; y++) { 16581 if (y < y2) {
vendor: 8,643 bytes, lines 16582-16838
16582 const k = y < y1 ? 0 : (y1 - y) / (y1 - y2); 16583 xa = x1 - (x1 - x2) * k; 16584 car = c1r - (c1r - c2r) * k; 16585 cag = c1g - (c1g - c2g) * k; 16586 cab = c1b - (c1b - c2b) * k; 16587 } else { 16588 let k; 16589 if (y > y3) { 16590 k = 1; 16591 } else if (y2 === y3) { 16592 k = 0; 16593 } else { 16594 k = (y2 - y) / (y2 - y3); 16595 } 16596 xa = x2 - (x2 - x3) * k; 16597 car = c2r - (c2r - c3r) * k; 16598 cag = c2g - (c2g - c3g) * k; 16599 cab = c2b - (c2b - c3b) * k; 16600 } 16601 let k; 16602 if (y < y1) { 16603 k = 0; 16604 } else if (y > y3) { 16605 k = 1; 16606 } else { 16607 k = (y1 - y) / (y1 - y3); 16608 } 16609 xb = x1 - (x1 - x3) * k; 16610 cbr = c1r - (c1r - c3r) * k; 16611 cbg = c1g - (c1g - c3g) * k; 16612 cbb = c1b - (c1b - c3b) * k; 16613 const x1_ = Math.round(Math.min(xa, xb)); 16614 const x2_ = Math.round(Math.max(xa, xb)); 16615 let j = rowSize * y + x1_ * 4; 16616 for (let x = x1_; x <= x2_; x++) { 16617 k = (xa - x) / (xa - xb); 16618 if (k < 0) { 16619 k = 0; 16620 } else if (k > 1) { 16621 k = 1; 16622 } 16623 bytes[j++] = car - (car - cbr) * k | 0; 16624 bytes[j++] = cag - (cag - cbg) * k | 0; 16625 bytes[j++] = cab - (cab - cbb) * k | 0; 16626 bytes[j++] = 255; 16627 } 16628 } 16629} 16630function drawFigure(data, figure, context) { 16631 const ps = figure.coords; 16632 const cs = figure.colors; 16633 let i, ii; 16634 switch (figure.type) { 16635 case MeshFigureType.LATTICE: 16636 const verticesPerRow = figure.verticesPerRow; 16637 const rows = Math.floor(ps.length / verticesPerRow) - 1; 16638 const cols = verticesPerRow - 1; 16639 for (i = 0; i < rows; i++) { 16640 let q = i * verticesPerRow; 16641 for (let j = 0; j < cols; j++, q++) { 16642 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); 16643 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); 16644 } 16645 } 16646 break; 16647 case MeshFigureType.TRIANGLES: 16648 for (i = 0, ii = ps.length; i < ii; i += 3) { 16649 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); 16650 } 16651 break; 16652 default: 16653 throw new Error("illegal figure"); 16654 } 16655} 16656class MeshShadingPattern extends BaseShadingPattern { 16657 constructor(IR) { 16658 super(); 16659 this._coords = IR[2]; 16660 this._colors = IR[3]; 16661 this._figures = IR[4]; 16662 this._bounds = IR[5]; 16663 this._bbox = IR[6]; 16664 this._background = IR[7]; 16665 this.matrix = null; 16666 } 16667 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { 16668 const EXPECTED_SCALE = 1.1; 16669 const MAX_PATTERN_SIZE = 3000; 16670 const BORDER_SIZE = 2; 16671 const offsetX = Math.floor(this._bounds[0]); 16672 const offsetY = Math.floor(this._bounds[1]); 16673 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX; 16674 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; 16675 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); 16676 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); 16677 const scaleX = boundsWidth / width; 16678 const scaleY = boundsHeight / height; 16679 const context = { 16680 coords: this._coords, 16681 colors: this._colors, 16682 offsetX: -offsetX, 16683 offsetY: -offsetY, 16684 scaleX: 1 / scaleX, 16685 scaleY: 1 / scaleY 16686 }; 16687 const paddedWidth = width + BORDER_SIZE * 2; 16688 const paddedHeight = height + BORDER_SIZE * 2; 16689 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight); 16690 const tmpCtx = tmpCanvas.context; 16691 const data = tmpCtx.createImageData(width, height); 16692 if (backgroundColor) { 16693 const bytes = data.data; 16694 for (let i = 0, ii = bytes.length; i < ii; i += 4) { 16695 bytes[i] = backgroundColor[0]; 16696 bytes[i + 1] = backgroundColor[1]; 16697 bytes[i + 2] = backgroundColor[2]; 16698 bytes[i + 3] = 255; 16699 } 16700 } 16701 for (const figure of this._figures) { 16702 drawFigure(data, figure, context); 16703 } 16704 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); 16705 const canvas = tmpCanvas.canvas; 16706 return { 16707 canvas, 16708 offsetX: offsetX - BORDER_SIZE * scaleX, 16709 offsetY: offsetY - BORDER_SIZE * scaleY, 16710 scaleX, 16711 scaleY 16712 }; 16713 } 16714 isModifyingCurrentTransform() { 16715 return true; 16716 } 16717 getPattern(ctx, owner, inverse, pathType) { 16718 applyBoundingBox(ctx, this._bbox); 16719 const scale = new Float32Array(2); 16720 if (pathType === PathType.SHADING) { 16721 Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale); 16722 } else if (this.matrix) { 16723 Util.singularValueDecompose2dScale(this.matrix, scale); 16724 const [matrixScaleX, matrixScaleY] = scale; 16725 Util.singularValueDecompose2dScale(owner.baseTransform, scale); 16726 scale[0] *= matrixScaleX; 16727 scale[1] *= matrixScaleY; 16728 } else { 16729 Util.singularValueDecompose2dScale(owner.baseTransform, scale); 16730 } 16731 const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases); 16732 if (pathType !== PathType.SHADING) { 16733 ctx.setTransform(...owner.baseTransform); 16734 if (this.matrix) { 16735 ctx.transform(...this.matrix); 16736 } 16737 } 16738 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); 16739 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); 16740 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); 16741 } 16742} 16743class DummyShadingPattern extends BaseShadingPattern { 16744 getPattern() { 16745 return "hotpink"; 16746 } 16747} 16748function getShadingPattern(IR) { 16749 switch (IR[0]) { 16750 case "RadialAxial": 16751 return new RadialAxialShadingPattern(IR); 16752 case "Mesh": 16753 return new MeshShadingPattern(IR); 16754 case "Dummy": 16755 return new DummyShadingPattern(); 16756 } 16757 throw new Error(`Unknown IR type: ${IR[0]}`); 16758} 16759const PaintType = { 16760 COLORED: 1, 16761 UNCOLORED: 2 16762}; 16763class TilingPattern { 16764 static MAX_PATTERN_SIZE = 3000; 16765 constructor(IR, ctx, canvasGraphicsFactory, baseTransform) { 16766 this.color = IR[1]; 16767 this.operatorList = IR[2]; 16768 this.matrix = IR[3]; 16769 this.bbox = IR[4]; 16770 this.xstep = IR[5]; 16771 this.ystep = IR[6]; 16772 this.paintType = IR[7]; 16773 this.tilingType = IR[8]; 16774 this.ctx = ctx; 16775 this.canvasGraphicsFactory = canvasGraphicsFactory; 16776 this.baseTransform = baseTransform; 16777 } 16778 createPatternCanvas(owner, opIdx) { 16779 const { 16780 bbox, 16781 operatorList, 16782 paintType, 16783 tilingType, 16784 color, 16785 canvasGraphicsFactory 16786 } = this; 16787 let { 16788 xstep, 16789 ystep 16790 } = this; 16791 xstep = Math.abs(xstep); 16792 ystep = Math.abs(ystep); 16793 info("TilingType: " + tilingType); 16794 const x0 = bbox[0], 16795 y0 = bbox[1], 16796 x1 = bbox[2], 16797 y1 = bbox[3]; 16798 const width = x1 - x0; 16799 const height = y1 - y0; 16800 const scale = new Float32Array(2); 16801 Util.singularValueDecompose2dScale(this.matrix, scale); 16802 const [matrixScaleX, matrixScaleY] = scale; 16803 Util.singularValueDecompose2dScale(this.baseTransform, scale); 16804 const combinedScaleX = matrixScaleX * scale[0]; 16805 const combinedScaleY = matrixScaleY * scale[1]; 16806 let canvasWidth = width, 16807 canvasHeight = height, 16808 redrawHorizontally = false, 16809 redrawVertically = false; 16810 const xScaledStep = Math.ceil(xstep * combinedScaleX); 16811 const yScaledStep = Math.ceil(ystep * combinedScaleY); 16812 const xScaledWidth = Math.ceil(width * combinedScaleX); 16813 const yScaledHeight = Math.ceil(height * combinedScaleY); 16814 if (xScaledStep >= xScaledWidth) { 16815 canvasWidth = xstep; 16816 } else { 16817 redrawHorizontally = true; 16818 } 16819 if (yScaledStep >= yScaledHeight) { 16820 canvasHeight = ystep; 16821 } else { 16822 redrawVertically = true; 16823 } 16824 const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); 16825 const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); 16826 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size); 16827 const tmpCtx = tmpCanvas.context; 16828 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx); 16829 graphics.groupLevel = owner.groupLevel; 16830 this.setFillAndStrokeStyleToContext(graphics, paintType, color); 16831 tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0); 16832 graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0); 16833 tmpCtx.save(); 16834 graphics.dependencyTracker?.save(); 16835 this.clipBbox(graphics, x0, y0, x1, y1); 16836 graphics.baseTransform = getCurrentTransform(graphics.ctx); 16837 graphics.executeOperatorList(operatorList); 16838 graphics.endDrawing();
vendor: 6,476 bytes, lines 16839-17032
16839 graphics.dependencyTracker?.restore(); 16840 tmpCtx.restore(); 16841 if (redrawHorizontally || redrawVertically) { 16842 const image = tmpCanvas.canvas; 16843 if (redrawHorizontally) { 16844 canvasWidth = xstep; 16845 } 16846 if (redrawVertically) { 16847 canvasHeight = ystep; 16848 } 16849 const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); 16850 const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); 16851 const xSize = dimx2.size; 16852 const ySize = dimy2.size; 16853 const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize); 16854 const tmpCtx2 = tmpCanvas2.context; 16855 const ii = redrawHorizontally ? Math.floor(width / xstep) : 0; 16856 const jj = redrawVertically ? Math.floor(height / ystep) : 0; 16857 for (let i = 0; i <= ii; i++) { 16858 for (let j = 0; j <= jj; j++) { 16859 tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize); 16860 } 16861 } 16862 return { 16863 canvas: tmpCanvas2.canvas, 16864 scaleX: dimx2.scale, 16865 scaleY: dimy2.scale, 16866 offsetX: x0, 16867 offsetY: y0 16868 }; 16869 } 16870 return { 16871 canvas: tmpCanvas.canvas, 16872 scaleX: dimx.scale, 16873 scaleY: dimy.scale, 16874 offsetX: x0, 16875 offsetY: y0 16876 }; 16877 } 16878 getSizeAndScale(step, realOutputSize, scale) { 16879 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize); 16880 let size = Math.ceil(step * scale); 16881 if (size >= maxSize) { 16882 size = maxSize; 16883 } else { 16884 scale = size / step; 16885 } 16886 return { 16887 scale, 16888 size 16889 }; 16890 } 16891 clipBbox(graphics, x0, y0, x1, y1) { 16892 const bboxWidth = x1 - x0; 16893 const bboxHeight = y1 - y0; 16894 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); 16895 Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax); 16896 graphics.clip(); 16897 graphics.endPath(); 16898 } 16899 setFillAndStrokeStyleToContext(graphics, paintType, color) { 16900 const context = graphics.ctx, 16901 current = graphics.current; 16902 switch (paintType) { 16903 case PaintType.COLORED: 16904 const { 16905 fillStyle, 16906 strokeStyle 16907 } = this.ctx; 16908 context.fillStyle = current.fillColor = fillStyle; 16909 context.strokeStyle = current.strokeColor = strokeStyle; 16910 break; 16911 case PaintType.UNCOLORED: 16912 context.fillStyle = context.strokeStyle = color; 16913 current.fillColor = current.strokeColor = color; 16914 break; 16915 default: 16916 throw new FormatError(`Unsupported paint type: ${paintType}`); 16917 } 16918 } 16919 isModifyingCurrentTransform() { 16920 return false; 16921 } 16922 getPattern(ctx, owner, inverse, pathType, opIdx) { 16923 let matrix = inverse; 16924 if (pathType !== PathType.SHADING) { 16925 matrix = Util.transform(matrix, owner.baseTransform); 16926 if (this.matrix) { 16927 matrix = Util.transform(matrix, this.matrix); 16928 } 16929 } 16930 const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx); 16931 let domMatrix = new DOMMatrix(matrix); 16932 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); 16933 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); 16934 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); 16935 pattern.setTransform(domMatrix); 16936 return pattern; 16937 } 16938} 16939 16940;// ./src/shared/image_utils.js 16941/* unused harmony import specifier */ var image_utils_ImageKind; 16942/* unused harmony import specifier */ var image_utils_FeatureTest; 16943 16944 16945 16946 16947 16948function convertToRGBA(params) { 16949 switch (params.kind) { 16950 case image_utils_ImageKind.GRAYSCALE_1BPP: 16951 return convertBlackAndWhiteToRGBA(params); 16952 case image_utils_ImageKind.RGB_24BPP: 16953 return convertRGBToRGBA(params); 16954 } 16955 return null; 16956} 16957function convertBlackAndWhiteToRGBA({ 16958 src, 16959 srcPos = 0, 16960 dest, 16961 width, 16962 height, 16963 nonBlackColor = 0xffffffff, 16964 inverseDecode = false 16965}) { 16966 const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; 16967 const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; 16968 const widthInSource = width >> 3; 16969 const widthRemainder = width & 7; 16970 const xorMask = zeroMapping ^ oneMapping; 16971 const srcLength = src.length; 16972 dest = new Uint32Array(dest.buffer); 16973 let destPos = 0; 16974 for (let i = 0; i < height; ++i) { 16975 for (const max = srcPos + widthInSource; srcPos < max; ++srcPos, destPos += 8) { 16976 const elem = src[srcPos]; 16977 dest[destPos] = zeroMapping ^ -(elem >> 7 & 1) & xorMask; 16978 dest[destPos + 1] = zeroMapping ^ -(elem >> 6 & 1) & xorMask; 16979 dest[destPos + 2] = zeroMapping ^ -(elem >> 5 & 1) & xorMask; 16980 dest[destPos + 3] = zeroMapping ^ -(elem >> 4 & 1) & xorMask; 16981 dest[destPos + 4] = zeroMapping ^ -(elem >> 3 & 1) & xorMask; 16982 dest[destPos + 5] = zeroMapping ^ -(elem >> 2 & 1) & xorMask; 16983 dest[destPos + 6] = zeroMapping ^ -(elem >> 1 & 1) & xorMask; 16984 dest[destPos + 7] = zeroMapping ^ -(elem & 1) & xorMask; 16985 } 16986 if (widthRemainder === 0) { 16987 continue; 16988 } 16989 const elem = srcPos < srcLength ? src[srcPos++] : 255; 16990 for (let j = 0; j < widthRemainder; ++j, ++destPos) { 16991 dest[destPos] = zeroMapping ^ -(elem >> 7 - j & 1) & xorMask; 16992 } 16993 } 16994 return { 16995 srcPos, 16996 destPos 16997 }; 16998} 16999function convertRGBToRGBA({ 17000 src, 17001 srcPos = 0, 17002 dest, 17003 destPos = 0, 17004 width, 17005 height 17006}) { 17007 let i = 0; 17008 const len = width * height * 3; 17009 const len32 = len >> 2; 17010 const src32 = new Uint32Array(src.buffer, srcPos, len32); 17011 const alphaMask = image_utils_FeatureTest.isLittleEndian ? 0xff000000 : 0xff; 17012 if (image_utils_FeatureTest.isLittleEndian) { 17013 for (; i < len32 - 2; i += 3, destPos += 4) { 17014 const s1 = src32[i], 17015 s2 = src32[i + 1], 17016 s3 = src32[i + 2]; 17017 dest[destPos] = s1 | alphaMask; 17018 dest[destPos + 1] = s1 >>> 24 | s2 << 8 | alphaMask; 17019 dest[destPos + 2] = s2 >>> 16 | s3 << 16 | alphaMask; 17020 dest[destPos + 3] = s3 >>> 8 | alphaMask; 17021 } 17022 for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { 17023 dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | alphaMask; 17024 } 17025 } else { 17026 for (; i < len32 - 2; i += 3, destPos += 4) { 17027 const s1 = src32[i], 17028 s2 = src32[i + 1], 17029 s3 = src32[i + 2]; 17030 dest[destPos] = s1 | alphaMask; 17031 dest[destPos + 1] = s1 << 24 | s2 >>> 8 | alphaMask; 17032 dest[destPos + 2] = s2 << 16 | s3 >>> 16 | alphaMask;
17033 dest[destPos + 3] = s3 << 8 | alphaMask; 17034 } 17035 for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { 17036 dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | alphaMask; 17037 } 17038 } 17039 return { 17040 srcPos: srcPos + len, 17041 destPos 17042 }; 17043} 17044function grayToRGBA(src, dest) { 17045 if (image_utils_FeatureTest.isLittleEndian) { 17046 for (let i = 0, ii = src.length; i < ii; i++) { 17047 dest[i] = src[i] * 0x10101 | 0xff000000; 17048 } 17049 } else { 17050 for (let i = 0, ii = src.length; i < ii; i++) { 17051 dest[i] = src[i] * 0x1010100 | 0x000000ff; 17052 } 17053 } 17054} 17055 17056;// ./src/display/canvas.js 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073const MIN_FONT_SIZE = 16; 17074const MAX_FONT_SIZE = 100; 17075const EXECUTION_TIME = 15; 17076const EXECUTION_STEPS = 10; 17077const FULL_CHUNK_HEIGHT = 16; 17078const SCALE_MATRIX = new DOMMatrix(); 17079const XY = new Float32Array(2); 17080const MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); 17081function mirrorContextOperations(ctx, destCtx) { 17082 if (ctx._removeMirroring) { 17083 throw new Error("Context is already forwarding operations."); 17084 } 17085 ctx.__originalSave = ctx.save; 17086 ctx.__originalRestore = ctx.restore; 17087 ctx.__originalRotate = ctx.rotate; 17088 ctx.__originalScale = ctx.scale; 17089 ctx.__originalTranslate = ctx.translate; 17090 ctx.__originalTransform = ctx.transform; 17091 ctx.__originalSetTransform = ctx.setTransform; 17092 ctx.__originalResetTransform = ctx.resetTransform; 17093 ctx.__originalClip = ctx.clip; 17094 ctx.__originalMoveTo = ctx.moveTo; 17095 ctx.__originalLineTo = ctx.lineTo; 17096 ctx.__originalBezierCurveTo = ctx.bezierCurveTo; 17097 ctx.__originalRect = ctx.rect; 17098 ctx.__originalClosePath = ctx.closePath; 17099 ctx.__originalBeginPath = ctx.beginPath; 17100 ctx._removeMirroring = () => { 17101 ctx.save = ctx.__originalSave; 17102 ctx.restore = ctx.__originalRestore; 17103 ctx.rotate = ctx.__originalRotate; 17104 ctx.scale = ctx.__originalScale; 17105 ctx.translate = ctx.__originalTranslate; 17106 ctx.transform = ctx.__originalTransform; 17107 ctx.setTransform = ctx.__originalSetTransform; 17108 ctx.resetTransform = ctx.__originalResetTransform; 17109 ctx.clip = ctx.__originalClip; 17110 ctx.moveTo = ctx.__originalMoveTo; 17111 ctx.lineTo = ctx.__originalLineTo; 17112 ctx.bezierCurveTo = ctx.__originalBezierCurveTo; 17113 ctx.rect = ctx.__originalRect; 17114 ctx.closePath = ctx.__originalClosePath; 17115 ctx.beginPath = ctx.__originalBeginPath; 17116 delete ctx._removeMirroring; 17117 }; 17118 ctx.save = function () { 17119 destCtx.save(); 17120 this.__originalSave(); 17121 }; 17122 ctx.restore = function () { 17123 destCtx.restore(); 17124 this.__originalRestore(); 17125 }; 17126 ctx.translate = function (x, y) { 17127 destCtx.translate(x, y); 17128 this.__originalTranslate(x, y); 17129 }; 17130 ctx.scale = function (x, y) { 17131 destCtx.scale(x, y); 17132 this.__originalScale(x, y); 17133 }; 17134 ctx.transform = function (a, b, c, d, e, f) { 17135 destCtx.transform(a, b, c, d, e, f); 17136 this.__originalTransform(a, b, c, d, e, f); 17137 }; 17138 ctx.setTransform = function (a, b, c, d, e, f) { 17139 destCtx.setTransform(a, b, c, d, e, f); 17140 this.__originalSetTransform(a, b, c, d, e, f); 17141 }; 17142 ctx.resetTransform = function () { 17143 destCtx.resetTransform(); 17144 this.__originalResetTransform(); 17145 }; 17146 ctx.rotate = function (angle) { 17147 destCtx.rotate(angle); 17148 this.__originalRotate(angle); 17149 }; 17150 ctx.clip = function (rule) { 17151 destCtx.clip(rule); 17152 this.__originalClip(rule); 17153 }; 17154 ctx.moveTo = function (x, y) { 17155 destCtx.moveTo(x, y); 17156 this.__originalMoveTo(x, y); 17157 }; 17158 ctx.lineTo = function (x, y) { 17159 destCtx.lineTo(x, y); 17160 this.__originalLineTo(x, y); 17161 }; 17162 ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { 17163 destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); 17164 this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); 17165 }; 17166 ctx.rect = function (x, y, width, height) { 17167 destCtx.rect(x, y, width, height); 17168 this.__originalRect(x, y, width, height); 17169 }; 17170 ctx.closePath = function () { 17171 destCtx.closePath(); 17172 this.__originalClosePath(); 17173 }; 17174 ctx.beginPath = function () { 17175 destCtx.beginPath(); 17176 this.__originalBeginPath(); 17177 }; 17178} 17179class CachedCanvases { 17180 constructor(canvasFactory) { 17181 this.canvasFactory = canvasFactory; 17182 this.cache = Object.create(null); 17183 } 17184 getCanvas(id, width, height) {
vendor: 36,580 bytes, lines 17185-18209
17185 let canvasEntry; 17186 if (this.cache[id] !== undefined) { 17187 canvasEntry = this.cache[id]; 17188 this.canvasFactory.reset(canvasEntry, width, height); 17189 } else { 17190 canvasEntry = this.canvasFactory.create(width, height); 17191 this.cache[id] = canvasEntry; 17192 } 17193 return canvasEntry; 17194 } 17195 delete(id) { 17196 delete this.cache[id]; 17197 } 17198 clear() { 17199 for (const id in this.cache) { 17200 const canvasEntry = this.cache[id]; 17201 this.canvasFactory.destroy(canvasEntry); 17202 delete this.cache[id]; 17203 } 17204 } 17205} 17206function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { 17207 const [a, b, c, d, tx, ty] = getCurrentTransform(ctx); 17208 if (b === 0 && c === 0) { 17209 const tlX = destX * a + tx; 17210 const rTlX = Math.round(tlX); 17211 const tlY = destY * d + ty; 17212 const rTlY = Math.round(tlY); 17213 const brX = (destX + destW) * a + tx; 17214 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; 17215 const brY = (destY + destH) * d + ty; 17216 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; 17217 ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY); 17218 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); 17219 ctx.setTransform(a, b, c, d, tx, ty); 17220 return [rWidth, rHeight]; 17221 } 17222 if (a === 0 && d === 0) { 17223 const tlX = destY * c + tx; 17224 const rTlX = Math.round(tlX); 17225 const tlY = destX * b + ty; 17226 const rTlY = Math.round(tlY); 17227 const brX = (destY + destH) * c + tx; 17228 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; 17229 const brY = (destX + destW) * b + ty; 17230 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; 17231 ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY); 17232 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); 17233 ctx.setTransform(a, b, c, d, tx, ty); 17234 return [rHeight, rWidth]; 17235 } 17236 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); 17237 const scaleX = Math.hypot(a, b); 17238 const scaleY = Math.hypot(c, d); 17239 return [scaleX * destW, scaleY * destH]; 17240} 17241class CanvasExtraState { 17242 alphaIsShape = false; 17243 fontSize = 0; 17244 fontSizeScale = 1; 17245 textMatrix = null; 17246 textMatrixScale = 1; 17247 fontMatrix = FONT_IDENTITY_MATRIX; 17248 leading = 0; 17249 x = 0; 17250 y = 0; 17251 lineX = 0; 17252 lineY = 0; 17253 charSpacing = 0; 17254 wordSpacing = 0; 17255 textHScale = 1; 17256 textRenderingMode = TextRenderingMode.FILL; 17257 textRise = 0; 17258 fillColor = "#000000"; 17259 strokeColor = "#000000"; 17260 patternFill = false; 17261 patternStroke = false; 17262 fillAlpha = 1; 17263 strokeAlpha = 1; 17264 lineWidth = 1; 17265 activeSMask = null; 17266 transferMaps = "none"; 17267 constructor(width, height, preInit) { 17268 preInit?.(this); 17269 this.clipBox = new Float32Array([0, 0, width, height]); 17270 this.minMax = MIN_MAX_INIT.slice(); 17271 } 17272 clone() { 17273 const clone = Object.create(this); 17274 clone.clipBox = this.clipBox.slice(); 17275 clone.minMax = this.minMax.slice(); 17276 return clone; 17277 } 17278 getPathBoundingBox(pathType = PathType.FILL, transform = null) { 17279 const box = this.minMax.slice(); 17280 if (pathType === PathType.STROKE) { 17281 if (!transform) { 17282 unreachable("Stroke bounding box must include transform."); 17283 } 17284 Util.singularValueDecompose2dScale(transform, XY); 17285 const xStrokePad = XY[0] * this.lineWidth / 2; 17286 const yStrokePad = XY[1] * this.lineWidth / 2; 17287 box[0] -= xStrokePad; 17288 box[1] -= yStrokePad; 17289 box[2] += xStrokePad; 17290 box[3] += yStrokePad; 17291 } 17292 return box; 17293 } 17294 updateClipFromPath() { 17295 const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox()); 17296 this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); 17297 } 17298 isEmptyClip() { 17299 return this.minMax[0] === Infinity; 17300 } 17301 startNewPathAndClipBox(box) { 17302 this.clipBox.set(box, 0); 17303 this.minMax.set(MIN_MAX_INIT, 0); 17304 } 17305 getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) { 17306 return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); 17307 } 17308} 17309function putBinaryImageData(ctx, imgData) { 17310 if (imgData instanceof ImageData) { 17311 ctx.putImageData(imgData, 0, 0); 17312 return; 17313 } 17314 const height = imgData.height, 17315 width = imgData.width; 17316 const partialChunkHeight = height % FULL_CHUNK_HEIGHT; 17317 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; 17318 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; 17319 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); 17320 let srcPos = 0, 17321 destPos; 17322 const src = imgData.data; 17323 const dest = chunkImgData.data; 17324 let i, j, thisChunkHeight, elemsInThisChunk; 17325 if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { 17326 const srcLength = src.byteLength; 17327 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); 17328 const dest32DataLength = dest32.length; 17329 const fullSrcDiff = width + 7 >> 3; 17330 const white = 0xffffffff; 17331 const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; 17332 for (i = 0; i < totalChunks; i++) { 17333 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; 17334 destPos = 0; 17335 for (j = 0; j < thisChunkHeight; j++) { 17336 const srcDiff = srcLength - srcPos; 17337 let k = 0; 17338 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; 17339 const kEndUnrolled = kEnd & ~7; 17340 let mask = 0; 17341 let srcByte = 0; 17342 for (; k < kEndUnrolled; k += 8) { 17343 srcByte = src[srcPos++]; 17344 dest32[destPos++] = srcByte & 128 ? white : black; 17345 dest32[destPos++] = srcByte & 64 ? white : black; 17346 dest32[destPos++] = srcByte & 32 ? white : black; 17347 dest32[destPos++] = srcByte & 16 ? white : black; 17348 dest32[destPos++] = srcByte & 8 ? white : black; 17349 dest32[destPos++] = srcByte & 4 ? white : black; 17350 dest32[destPos++] = srcByte & 2 ? white : black; 17351 dest32[destPos++] = srcByte & 1 ? white : black; 17352 } 17353 for (; k < kEnd; k++) { 17354 if (mask === 0) { 17355 srcByte = src[srcPos++]; 17356 mask = 128; 17357 } 17358 dest32[destPos++] = srcByte & mask ? white : black; 17359 mask >>= 1; 17360 } 17361 } 17362 while (destPos < dest32DataLength) { 17363 dest32[destPos++] = 0; 17364 } 17365 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 17366 } 17367 } else if (imgData.kind === ImageKind.RGBA_32BPP) { 17368 j = 0; 17369 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; 17370 for (i = 0; i < fullChunks; i++) { 17371 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); 17372 srcPos += elemsInThisChunk; 17373 ctx.putImageData(chunkImgData, 0, j); 17374 j += FULL_CHUNK_HEIGHT; 17375 } 17376 if (i < totalChunks) { 17377 elemsInThisChunk = width * partialChunkHeight * 4; 17378 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); 17379 ctx.putImageData(chunkImgData, 0, j); 17380 } 17381 } else if (imgData.kind === ImageKind.RGB_24BPP) { 17382 thisChunkHeight = FULL_CHUNK_HEIGHT; 17383 elemsInThisChunk = width * thisChunkHeight; 17384 for (i = 0; i < totalChunks; i++) { 17385 if (i >= fullChunks) { 17386 thisChunkHeight = partialChunkHeight; 17387 elemsInThisChunk = width * thisChunkHeight; 17388 } 17389 destPos = 0; 17390 for (j = elemsInThisChunk; j--;) { 17391 dest[destPos++] = src[srcPos++]; 17392 dest[destPos++] = src[srcPos++]; 17393 dest[destPos++] = src[srcPos++]; 17394 dest[destPos++] = 255; 17395 } 17396 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 17397 } 17398 } else { 17399 throw new Error(`bad image kind: ${imgData.kind}`); 17400 } 17401} 17402function putBinaryImageMask(ctx, imgData) { 17403 if (imgData.bitmap) { 17404 ctx.drawImage(imgData.bitmap, 0, 0); 17405 return; 17406 } 17407 const height = imgData.height, 17408 width = imgData.width; 17409 const partialChunkHeight = height % FULL_CHUNK_HEIGHT; 17410 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; 17411 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; 17412 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); 17413 let srcPos = 0; 17414 const src = imgData.data; 17415 const dest = chunkImgData.data; 17416 for (let i = 0; i < totalChunks; i++) { 17417 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; 17418 ({ 17419 srcPos 17420 } = convertBlackAndWhiteToRGBA({ 17421 src, 17422 srcPos, 17423 dest, 17424 width, 17425 height: thisChunkHeight, 17426 nonBlackColor: 0 17427 })); 17428 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 17429 } 17430} 17431function copyCtxState(sourceCtx, destCtx) { 17432 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; 17433 for (const property of properties) { 17434 if (sourceCtx[property] !== undefined) { 17435 destCtx[property] = sourceCtx[property]; 17436 } 17437 } 17438 if (sourceCtx.setLineDash !== undefined) { 17439 destCtx.setLineDash(sourceCtx.getLineDash()); 17440 destCtx.lineDashOffset = sourceCtx.lineDashOffset; 17441 } 17442} 17443function resetCtxToDefault(ctx) { 17444 ctx.strokeStyle = ctx.fillStyle = "#000000"; 17445 ctx.fillRule = "nonzero"; 17446 ctx.globalAlpha = 1; 17447 ctx.lineWidth = 1; 17448 ctx.lineCap = "butt"; 17449 ctx.lineJoin = "miter"; 17450 ctx.miterLimit = 10; 17451 ctx.globalCompositeOperation = "source-over"; 17452 ctx.font = "10px sans-serif"; 17453 if (ctx.setLineDash !== undefined) { 17454 ctx.setLineDash([]); 17455 ctx.lineDashOffset = 0; 17456 } 17457 const { 17458 filter 17459 } = ctx; 17460 if (filter !== "none" && filter !== "") { 17461 ctx.filter = "none"; 17462 } 17463} 17464function getImageSmoothingEnabled(transform, interpolate) { 17465 if (interpolate) { 17466 return true; 17467 } 17468 Util.singularValueDecompose2dScale(transform, XY); 17469 const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS); 17470 return XY[0] <= actualScale && XY[1] <= actualScale; 17471} 17472const LINE_CAP_STYLES = ["butt", "round", "square"]; 17473const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; 17474const NORMAL_CLIP = {}; 17475const EO_CLIP = {}; 17476class CanvasGraphics { 17477 constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { 17478 optionalContentConfig, 17479 markedContentStack = null 17480 }, annotationCanvasMap, pageColors, dependencyTracker) { 17481 this.ctx = canvasCtx; 17482 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); 17483 this.stateStack = []; 17484 this.pendingClip = null; 17485 this.pendingEOFill = false; 17486 this.commonObjs = commonObjs; 17487 this.objs = objs; 17488 this.canvasFactory = canvasFactory; 17489 this.filterFactory = filterFactory; 17490 this.groupStack = []; 17491 this.baseTransform = null; 17492 this.baseTransformStack = []; 17493 this.groupLevel = 0; 17494 this.smaskStack = []; 17495 this.smaskCounter = 0; 17496 this.tempSMask = null; 17497 this.suspendedCtx = null; 17498 this.contentVisible = true; 17499 this.markedContentStack = markedContentStack || []; 17500 this.optionalContentConfig = optionalContentConfig; 17501 this.cachedCanvases = new CachedCanvases(this.canvasFactory); 17502 this.cachedPatterns = new Map(); 17503 this.annotationCanvasMap = annotationCanvasMap; 17504 this.viewportScale = 1; 17505 this.outputScaleX = 1; 17506 this.outputScaleY = 1; 17507 this.pageColors = pageColors; 17508 this._cachedScaleForStroking = [-1, 0]; 17509 this._cachedGetSinglePixelWidth = null; 17510 this._cachedBitmapsMap = new Map(); 17511 this.dependencyTracker = dependencyTracker ?? null; 17512 } 17513 getObject(opIdx, data, fallback = null) { 17514 if (typeof data === "string") { 17515 this.dependencyTracker?.recordNamedDependency(opIdx, data); 17516 return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); 17517 } 17518 return fallback; 17519 } 17520 beginDrawing({ 17521 transform, 17522 viewport, 17523 transparency = false, 17524 background = null 17525 }) { 17526 const width = this.ctx.canvas.width; 17527 const height = this.ctx.canvas.height; 17528 const savedFillStyle = this.ctx.fillStyle; 17529 this.ctx.fillStyle = background || "#ffffff"; 17530 this.ctx.fillRect(0, 0, width, height); 17531 this.ctx.fillStyle = savedFillStyle; 17532 if (transparency) { 17533 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); 17534 this.compositeCtx = this.ctx; 17535 this.transparentCanvas = transparentCanvas.canvas; 17536 this.ctx = transparentCanvas.context; 17537 this.ctx.save(); 17538 this.ctx.transform(...getCurrentTransform(this.compositeCtx)); 17539 } 17540 this.ctx.save(); 17541 resetCtxToDefault(this.ctx); 17542 if (transform) { 17543 this.ctx.transform(...transform); 17544 this.outputScaleX = transform[0]; 17545 this.outputScaleY = transform[0]; 17546 } 17547 this.ctx.transform(...viewport.transform); 17548 this.viewportScale = viewport.scale; 17549 this.baseTransform = getCurrentTransform(this.ctx); 17550 } 17551 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) { 17552 const argsArray = operatorList.argsArray; 17553 const fnArray = operatorList.fnArray; 17554 let i = executionStartIdx || 0; 17555 const argsArrayLen = argsArray.length; 17556 if (argsArrayLen === i) { 17557 return i; 17558 } 17559 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; 17560 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; 17561 let steps = 0; 17562 const commonObjs = this.commonObjs; 17563 const objs = this.objs; 17564 let fnId, fnArgs; 17565 while (true) { 17566 if (stepper !== undefined && i === stepper.nextBreakPoint) { 17567 stepper.breakIt(i, continueCallback); 17568 return i; 17569 } 17570 if (!operationsFilter || operationsFilter(i)) { 17571 fnId = fnArray[i]; 17572 fnArgs = argsArray[i] ?? null; 17573 if (fnId !== OPS.dependency) { 17574 if (fnArgs === null) { 17575 this[fnId](i); 17576 } else { 17577 this[fnId](i, ...fnArgs); 17578 } 17579 } else { 17580 for (const depObjId of fnArgs) { 17581 this.dependencyTracker?.recordNamedData(depObjId, i); 17582 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; 17583 if (!objsPool.has(depObjId)) { 17584 objsPool.get(depObjId, continueCallback); 17585 return i; 17586 } 17587 } 17588 } 17589 } 17590 i++; 17591 if (i === argsArrayLen) { 17592 return i; 17593 } 17594 if (chunkOperations && ++steps > EXECUTION_STEPS) { 17595 if (Date.now() > endTime) { 17596 continueCallback(); 17597 return i; 17598 } 17599 steps = 0; 17600 } 17601 } 17602 } 17603 #restoreInitialState() { 17604 while (this.stateStack.length || this.inSMaskMode) { 17605 this.restore(); 17606 } 17607 this.current.activeSMask = null; 17608 this.ctx.restore(); 17609 if (this.transparentCanvas) { 17610 this.ctx = this.compositeCtx; 17611 this.ctx.save(); 17612 this.ctx.setTransform(1, 0, 0, 1, 0, 0); 17613 this.ctx.drawImage(this.transparentCanvas, 0, 0); 17614 this.ctx.restore(); 17615 this.transparentCanvas = null; 17616 } 17617 } 17618 endDrawing() { 17619 this.#restoreInitialState(); 17620 this.cachedCanvases.clear(); 17621 this.cachedPatterns.clear(); 17622 for (const cache of this._cachedBitmapsMap.values()) { 17623 for (const canvas of cache.values()) { 17624 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { 17625 canvas.width = canvas.height = 0; 17626 } 17627 } 17628 cache.clear(); 17629 } 17630 this._cachedBitmapsMap.clear(); 17631 this.#drawFilter(); 17632 } 17633 #drawFilter() { 17634 if (this.pageColors) { 17635 const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); 17636 if (hcmFilterId !== "none") { 17637 const savedFilter = this.ctx.filter; 17638 this.ctx.filter = hcmFilterId; 17639 this.ctx.drawImage(this.ctx.canvas, 0, 0); 17640 this.ctx.filter = savedFilter; 17641 } 17642 } 17643 } 17644 _scaleImage(img, inverseTransform) { 17645 const width = img.width ?? img.displayWidth; 17646 const height = img.height ?? img.displayHeight; 17647 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); 17648 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); 17649 let paintWidth = width, 17650 paintHeight = height; 17651 let tmpCanvasId = "prescale1"; 17652 let tmpCanvas, tmpCtx; 17653 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { 17654 let newWidth = paintWidth, 17655 newHeight = paintHeight; 17656 if (widthScale > 2 && paintWidth > 1) { 17657 newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); 17658 widthScale /= paintWidth / newWidth; 17659 } 17660 if (heightScale > 2 && paintHeight > 1) { 17661 newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; 17662 heightScale /= paintHeight / newHeight; 17663 } 17664 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); 17665 tmpCtx = tmpCanvas.context; 17666 tmpCtx.clearRect(0, 0, newWidth, newHeight); 17667 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); 17668 img = tmpCanvas.canvas; 17669 paintWidth = newWidth; 17670 paintHeight = newHeight; 17671 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; 17672 } 17673 return { 17674 img, 17675 paintWidth, 17676 paintHeight 17677 }; 17678 } 17679 _createMaskCanvas(opIdx, img) { 17680 const ctx = this.ctx; 17681 const { 17682 width, 17683 height 17684 } = img; 17685 const fillColor = this.current.fillColor; 17686 const isPatternFill = this.current.patternFill; 17687 const currentTransform = getCurrentTransform(ctx); 17688 let cache, cacheKey, scaled, maskCanvas; 17689 if ((img.bitmap || img.data) && img.count > 1) { 17690 const mainKey = img.bitmap || img.data.buffer; 17691 cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); 17692 cache = this._cachedBitmapsMap.getOrInsertComputed(mainKey, makeMap); 17693 const cachedImage = cache.get(cacheKey); 17694 if (cachedImage && !isPatternFill) { 17695 const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); 17696 const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); 17697 this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); 17698 return { 17699 canvas: cachedImage, 17700 offsetX, 17701 offsetY 17702 }; 17703 } 17704 scaled = cachedImage; 17705 } 17706 if (!scaled) { 17707 maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); 17708 putBinaryImageMask(maskCanvas.context, img); 17709 } 17710 let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); 17711 maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); 17712 const minMax = MIN_MAX_INIT.slice(); 17713 Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax); 17714 const [minX, minY, maxX, maxY] = minMax; 17715 const drawnWidth = Math.round(maxX - minX) || 1; 17716 const drawnHeight = Math.round(maxY - minY) || 1; 17717 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); 17718 const fillCtx = fillCanvas.context; 17719 const offsetX = minX; 17720 const offsetY = minY; 17721 fillCtx.translate(-offsetX, -offsetY); 17722 fillCtx.transform(...maskToCanvas); 17723 if (!scaled) { 17724 scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx)); 17725 scaled = scaled.img; 17726 if (cache && isPatternFill) { 17727 cache.set(cacheKey, scaled); 17728 } 17729 } 17730 fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate); 17731 drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); 17732 fillCtx.globalCompositeOperation = "source-in"; 17733 const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); 17734 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor; 17735 fillCtx.fillRect(0, 0, width, height); 17736 if (cache && !isPatternFill) { 17737 this.cachedCanvases.delete("fillCanvas"); 17738 cache.set(cacheKey, fillCanvas.canvas); 17739 } 17740 this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); 17741 return { 17742 canvas: fillCanvas.canvas, 17743 offsetX: Math.round(offsetX), 17744 offsetY: Math.round(offsetY) 17745 }; 17746 } 17747 setLineWidth(opIdx, width) { 17748 this.dependencyTracker?.recordSimpleData("lineWidth", opIdx); 17749 if (width !== this.current.lineWidth) { 17750 this._cachedScaleForStroking[0] = -1; 17751 } 17752 this.current.lineWidth = width; 17753 this.ctx.lineWidth = width; 17754 } 17755 setLineCap(opIdx, style) { 17756 this.dependencyTracker?.recordSimpleData("lineCap", opIdx); 17757 this.ctx.lineCap = LINE_CAP_STYLES[style]; 17758 } 17759 setLineJoin(opIdx, style) { 17760 this.dependencyTracker?.recordSimpleData("lineJoin", opIdx); 17761 this.ctx.lineJoin = LINE_JOIN_STYLES[style]; 17762 } 17763 setMiterLimit(opIdx, limit) { 17764 this.dependencyTracker?.recordSimpleData("miterLimit", opIdx); 17765 this.ctx.miterLimit = limit; 17766 } 17767 setDash(opIdx, dashArray, dashPhase) { 17768 this.dependencyTracker?.recordSimpleData("dash", opIdx); 17769 const ctx = this.ctx; 17770 if (ctx.setLineDash !== undefined) { 17771 ctx.setLineDash(dashArray); 17772 ctx.lineDashOffset = dashPhase; 17773 } 17774 } 17775 setRenderingIntent(opIdx, intent) {} 17776 setFlatness(opIdx, flatness) {} 17777 setGState(opIdx, states) { 17778 for (const [key, value] of states) { 17779 switch (key) { 17780 case "LW": 17781 this.setLineWidth(opIdx, value); 17782 break; 17783 case "LC": 17784 this.setLineCap(opIdx, value); 17785 break; 17786 case "LJ": 17787 this.setLineJoin(opIdx, value); 17788 break; 17789 case "ML": 17790 this.setMiterLimit(opIdx, value); 17791 break; 17792 case "D": 17793 this.setDash(opIdx, value[0], value[1]); 17794 break; 17795 case "RI": 17796 this.setRenderingIntent(opIdx, value); 17797 break; 17798 case "FL": 17799 this.setFlatness(opIdx, value); 17800 break; 17801 case "Font": 17802 this.setFont(opIdx, value[0], value[1]); 17803 break; 17804 case "CA": 17805 this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx); 17806 this.current.strokeAlpha = value; 17807 break; 17808 case "ca": 17809 this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx); 17810 this.ctx.globalAlpha = this.current.fillAlpha = value; 17811 break; 17812 case "BM": 17813 this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx); 17814 this.ctx.globalCompositeOperation = value; 17815 break; 17816 case "SMask": 17817 this.dependencyTracker?.recordSimpleData("SMask", opIdx); 17818 this.current.activeSMask = value ? this.tempSMask : null; 17819 this.tempSMask = null; 17820 this.checkSMaskState(); 17821 break; 17822 case "TR": 17823 this.dependencyTracker?.recordSimpleData("filter", opIdx); 17824 this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); 17825 break; 17826 } 17827 } 17828 } 17829 get inSMaskMode() { 17830 return !!this.suspendedCtx; 17831 } 17832 checkSMaskState() { 17833 const inSMaskMode = this.inSMaskMode; 17834 if (this.current.activeSMask && !inSMaskMode) { 17835 this.beginSMaskMode(); 17836 } else if (!this.current.activeSMask && inSMaskMode) { 17837 this.endSMaskMode(); 17838 } 17839 } 17840 beginSMaskMode(opIdx) { 17841 if (this.inSMaskMode) { 17842 throw new Error("beginSMaskMode called while already in smask mode"); 17843 } 17844 const drawnWidth = this.ctx.canvas.width; 17845 const drawnHeight = this.ctx.canvas.height; 17846 const cacheId = "smaskGroupAt" + this.groupLevel; 17847 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); 17848 this.suspendedCtx = this.ctx; 17849 const ctx = this.ctx = scratchCanvas.context; 17850 ctx.setTransform(this.suspendedCtx.getTransform()); 17851 copyCtxState(this.suspendedCtx, ctx); 17852 mirrorContextOperations(ctx, this.suspendedCtx); 17853 this.setGState(opIdx, [["BM", "source-over"]]); 17854 } 17855 endSMaskMode() { 17856 if (!this.inSMaskMode) { 17857 throw new Error("endSMaskMode called while not in smask mode"); 17858 } 17859 this.ctx._removeMirroring(); 17860 copyCtxState(this.ctx, this.suspendedCtx); 17861 this.ctx = this.suspendedCtx; 17862 this.suspendedCtx = null; 17863 } 17864 compose(dirtyBox) { 17865 if (!this.current.activeSMask) { 17866 return; 17867 } 17868 if (!dirtyBox) { 17869 dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; 17870 } else { 17871 dirtyBox[0] = Math.floor(dirtyBox[0]); 17872 dirtyBox[1] = Math.floor(dirtyBox[1]); 17873 dirtyBox[2] = Math.ceil(dirtyBox[2]); 17874 dirtyBox[3] = Math.ceil(dirtyBox[3]); 17875 } 17876 const smask = this.current.activeSMask; 17877 const suspendedCtx = this.suspendedCtx; 17878 this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); 17879 this.ctx.save(); 17880 this.ctx.setTransform(1, 0, 0, 1, 0, 0); 17881 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); 17882 this.ctx.restore(); 17883 } 17884 composeSMask(ctx, smask, layerCtx, layerBox) { 17885 const layerOffsetX = layerBox[0]; 17886 const layerOffsetY = layerBox[1]; 17887 const layerWidth = layerBox[2] - layerOffsetX; 17888 const layerHeight = layerBox[3] - layerOffsetY; 17889 if (layerWidth === 0 || layerHeight === 0) { 17890 return; 17891 } 17892 this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); 17893 ctx.save(); 17894 ctx.globalAlpha = 1; 17895 ctx.globalCompositeOperation = "source-over"; 17896 ctx.setTransform(1, 0, 0, 1, 0, 0); 17897 ctx.drawImage(layerCtx.canvas, 0, 0); 17898 ctx.restore(); 17899 } 17900 genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { 17901 let maskCanvas = maskCtx.canvas; 17902 let maskX = layerOffsetX - maskOffsetX; 17903 let maskY = layerOffsetY - maskOffsetY; 17904 if (backdrop) { 17905 if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) { 17906 const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height); 17907 const ctx = canvas.context; 17908 ctx.drawImage(maskCanvas, -maskX, -maskY); 17909 ctx.globalCompositeOperation = "destination-atop"; 17910 ctx.fillStyle = backdrop; 17911 ctx.fillRect(0, 0, width, height); 17912 ctx.globalCompositeOperation = "source-over"; 17913 maskCanvas = canvas.canvas; 17914 maskX = maskY = 0; 17915 } else { 17916 maskCtx.save(); 17917 maskCtx.globalAlpha = 1; 17918 maskCtx.setTransform(1, 0, 0, 1, 0, 0); 17919 const clip = new Path2D(); 17920 clip.rect(maskX, maskY, width, height); 17921 maskCtx.clip(clip); 17922 maskCtx.globalCompositeOperation = "destination-atop"; 17923 maskCtx.fillStyle = backdrop; 17924 maskCtx.fillRect(maskX, maskY, width, height); 17925 maskCtx.restore(); 17926 } 17927 } 17928 layerCtx.save(); 17929 layerCtx.globalAlpha = 1; 17930 layerCtx.setTransform(1, 0, 0, 1, 0, 0); 17931 if (subtype === "Alpha" && transferMap) { 17932 layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap); 17933 } else if (subtype === "Luminosity") { 17934 layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap); 17935 } 17936 const clip = new Path2D(); 17937 clip.rect(layerOffsetX, layerOffsetY, width, height); 17938 layerCtx.clip(clip); 17939 layerCtx.globalCompositeOperation = "destination-in"; 17940 layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height); 17941 layerCtx.restore(); 17942 } 17943 save(opIdx) { 17944 if (this.inSMaskMode) { 17945 copyCtxState(this.ctx, this.suspendedCtx); 17946 } 17947 this.ctx.save(); 17948 const old = this.current; 17949 this.stateStack.push(old); 17950 this.current = old.clone(); 17951 this.dependencyTracker?.save(opIdx); 17952 } 17953 restore(opIdx) { 17954 this.dependencyTracker?.restore(opIdx); 17955 if (this.stateStack.length === 0) { 17956 if (this.inSMaskMode) { 17957 this.endSMaskMode(); 17958 } 17959 return; 17960 } 17961 this.current = this.stateStack.pop(); 17962 this.ctx.restore(); 17963 if (this.inSMaskMode) { 17964 copyCtxState(this.suspendedCtx, this.ctx); 17965 } 17966 this.checkSMaskState(); 17967 this.pendingClip = null; 17968 this._cachedScaleForStroking[0] = -1; 17969 this._cachedGetSinglePixelWidth = null; 17970 } 17971 transform(opIdx, a, b, c, d, e, f) { 17972 this.dependencyTracker?.recordIncrementalData("transform", opIdx); 17973 this.ctx.transform(a, b, c, d, e, f); 17974 this._cachedScaleForStroking[0] = -1; 17975 this._cachedGetSinglePixelWidth = null; 17976 } 17977 constructPath(opIdx, op, data, minMax) { 17978 let [path] = data; 17979 if (!minMax) { 17980 path ||= data[0] = new Path2D(); 17981 this[op](opIdx, path); 17982 return; 17983 } 17984 if (this.dependencyTracker !== null) { 17985 const outerExtraSize = op === OPS.stroke ? this.current.lineWidth / 2 : 0; 17986 this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]); 17987 } 17988 if (!(path instanceof Path2D)) { 17989 path = data[0] = makePathFromDrawOPS(path); 17990 } 17991 Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax); 17992 this[op](opIdx, path); 17993 this._pathStartIdx = opIdx; 17994 } 17995 closePath(opIdx) { 17996 this.ctx.closePath(); 17997 } 17998 stroke(opIdx, path, consumePath = true) { 17999 const ctx = this.ctx; 18000 const strokeColor = this.current.strokeColor; 18001 ctx.globalAlpha = this.current.strokeAlpha; 18002 if (this.contentVisible) { 18003 if (typeof strokeColor === "object" && strokeColor?.getPattern) { 18004 const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; 18005 ctx.save(); 18006 ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); 18007 if (baseTransform) { 18008 const newPath = new Path2D(); 18009 newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); 18010 path = newPath; 18011 } 18012 this.rescaleAndStroke(path, false); 18013 ctx.restore(); 18014 } else { 18015 this.rescaleAndStroke(path, true); 18016 } 18017 } 18018 this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke); 18019 if (consumePath) { 18020 this.consumePath(opIdx, path, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx))); 18021 } 18022 ctx.globalAlpha = this.current.fillAlpha; 18023 } 18024 closeStroke(opIdx, path) { 18025 this.stroke(opIdx, path); 18026 } 18027 fill(opIdx, path, consumePath = true) { 18028 const ctx = this.ctx; 18029 const fillColor = this.current.fillColor; 18030 const isPatternFill = this.current.patternFill; 18031 let needRestore = false; 18032 if (isPatternFill) { 18033 const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; 18034 this.dependencyTracker?.save(opIdx); 18035 ctx.save(); 18036 ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); 18037 if (baseTransform) { 18038 const newPath = new Path2D(); 18039 newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); 18040 path = newPath; 18041 } 18042 needRestore = true; 18043 } 18044 const intersect = this.current.getClippedPathBoundingBox(); 18045 if (this.contentVisible && intersect !== null) { 18046 if (this.pendingEOFill) { 18047 ctx.fill(path, "evenodd"); 18048 this.pendingEOFill = false; 18049 } else { 18050 ctx.fill(path); 18051 } 18052 } 18053 this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill); 18054 if (needRestore) { 18055 ctx.restore(); 18056 this.dependencyTracker?.restore(opIdx); 18057 } 18058 if (consumePath) { 18059 this.consumePath(opIdx, path, intersect); 18060 } 18061 } 18062 eoFill(opIdx, path) { 18063 this.pendingEOFill = true; 18064 this.fill(opIdx, path); 18065 } 18066 fillStroke(opIdx, path) { 18067 this.fill(opIdx, path, false); 18068 this.stroke(opIdx, path, false); 18069 this.consumePath(opIdx, path); 18070 } 18071 eoFillStroke(opIdx, path) { 18072 this.pendingEOFill = true; 18073 this.fillStroke(opIdx, path); 18074 } 18075 closeFillStroke(opIdx, path) { 18076 this.fillStroke(opIdx, path); 18077 } 18078 closeEOFillStroke(opIdx, path) { 18079 this.pendingEOFill = true; 18080 this.fillStroke(opIdx, path); 18081 } 18082 endPath(opIdx, path) { 18083 this.consumePath(opIdx, path); 18084 } 18085 rawFillPath(opIdx, path) { 18086 this.ctx.fill(path); 18087 this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx); 18088 } 18089 clip(opIdx) { 18090 this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); 18091 this.pendingClip = NORMAL_CLIP; 18092 } 18093 eoClip(opIdx) { 18094 this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); 18095 this.pendingClip = EO_CLIP; 18096 } 18097 beginText(opIdx) { 18098 this.current.textMatrix = null; 18099 this.current.textMatrixScale = 1; 18100 this.current.x = this.current.lineX = 0; 18101 this.current.y = this.current.lineY = 0; 18102 this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx); 18103 } 18104 endText(opIdx) { 18105 const paths = this.pendingTextPaths; 18106 const ctx = this.ctx; 18107 if (this.dependencyTracker) { 18108 const { 18109 dependencyTracker 18110 } = this; 18111 if (paths !== undefined) { 18112 dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx); 18113 } 18114 dependencyTracker.recordCloseMarker(opIdx); 18115 } 18116 if (paths !== undefined) { 18117 const newPath = new Path2D(); 18118 const invTransf = ctx.getTransform().invertSelf(); 18119 for (const { 18120 transform, 18121 x, 18122 y, 18123 fontSize, 18124 path 18125 } of paths) { 18126 if (!path) { 18127 continue; 18128 } 18129 newPath.addPath(path, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize)); 18130 } 18131 ctx.clip(newPath); 18132 } 18133 delete this.pendingTextPaths; 18134 } 18135 setCharSpacing(opIdx, spacing) { 18136 this.dependencyTracker?.recordSimpleData("charSpacing", opIdx); 18137 this.current.charSpacing = spacing; 18138 } 18139 setWordSpacing(opIdx, spacing) { 18140 this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx); 18141 this.current.wordSpacing = spacing; 18142 } 18143 setHScale(opIdx, scale) { 18144 this.dependencyTracker?.recordSimpleData("hScale", opIdx); 18145 this.current.textHScale = scale / 100; 18146 } 18147 setLeading(opIdx, leading) { 18148 this.dependencyTracker?.recordSimpleData("leading", opIdx); 18149 this.current.leading = -leading; 18150 } 18151 setFont(opIdx, fontRefName, size) { 18152 this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx); 18153 const fontObj = this.commonObjs.get(fontRefName); 18154 const current = this.current; 18155 if (!fontObj) { 18156 throw new Error(`Can't find font for ${fontRefName}`); 18157 } 18158 current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX; 18159 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { 18160 warn("Invalid font matrix for font " + fontRefName); 18161 } 18162 if (size < 0) { 18163 size = -size; 18164 current.fontDirection = -1; 18165 } else { 18166 current.fontDirection = 1; 18167 } 18168 this.current.font = fontObj; 18169 this.current.fontSize = size; 18170 if (fontObj.isType3Font) { 18171 return; 18172 } 18173 const name = fontObj.loadedName || "sans-serif"; 18174 const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; 18175 let bold = "normal"; 18176 if (fontObj.black) { 18177 bold = "900"; 18178 } else if (fontObj.bold) { 18179 bold = "bold"; 18180 } 18181 const italic = fontObj.italic ? "italic" : "normal"; 18182 let browserFontSize = size; 18183 if (size < MIN_FONT_SIZE) { 18184 browserFontSize = MIN_FONT_SIZE; 18185 } else if (size > MAX_FONT_SIZE) { 18186 browserFontSize = MAX_FONT_SIZE; 18187 } 18188 this.current.fontSizeScale = size / browserFontSize; 18189 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; 18190 } 18191 setTextRenderingMode(opIdx, mode) { 18192 this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx); 18193 this.current.textRenderingMode = mode; 18194 } 18195 setTextRise(opIdx, rise) { 18196 this.dependencyTracker?.recordSimpleData("textRise", opIdx); 18197 this.current.textRise = rise; 18198 } 18199 moveText(opIdx, x, y) { 18200 this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx); 18201 this.current.x = this.current.lineX += x; 18202 this.current.y = this.current.lineY += y; 18203 } 18204 setLeadingMoveText(opIdx, x, y) { 18205 this.setLeading(opIdx, -y); 18206 this.moveText(opIdx, x, y); 18207 } 18208 setTextMatrix(opIdx, matrix) { 18209 this.dependencyTracker?.resetIncrementalData("sameLineText")
vendor: 5,039 bytes, lines 18209-18330
18209.recordSimpleData("textMatrix", opIdx); 18210 const { 18211 current 18212 } = this; 18213 current.textMatrix = matrix; 18214 current.textMatrixScale = Math.hypot(matrix[0], matrix[1]); 18215 current.x = current.lineX = 0; 18216 current.y = current.lineY = 0; 18217 } 18218 nextLine(opIdx) { 18219 this.moveText(opIdx, 0, this.current.leading); 18220 this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx); 18221 } 18222 #getScaledPath(path, currentTransform, transform) { 18223 const newPath = new Path2D(); 18224 newPath.addPath(path, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform)); 18225 return newPath; 18226 } 18227 paintChar(opIdx, character, x, y, patternFillTransform, patternStrokeTransform) { 18228 const ctx = this.ctx; 18229 const current = this.current; 18230 const font = current.font; 18231 const textRenderingMode = current.textRenderingMode; 18232 const fontSize = current.fontSize / current.fontSizeScale; 18233 const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; 18234 const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); 18235 const patternFill = current.patternFill && !font.missingFile; 18236 const patternStroke = current.patternStroke && !font.missingFile; 18237 let path; 18238 if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) { 18239 path = font.getPathGenerator(this.commonObjs, character); 18240 } 18241 if (path && (font.disableFontFace || patternFill || patternStroke)) { 18242 ctx.save(); 18243 ctx.translate(x, y); 18244 ctx.scale(fontSize, -fontSize); 18245 this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font); 18246 let currentTransform; 18247 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { 18248 if (patternFillTransform) { 18249 currentTransform = ctx.getTransform(); 18250 ctx.setTransform(...patternFillTransform); 18251 const scaledPath = this.#getScaledPath(path, currentTransform, patternFillTransform); 18252 ctx.fill(scaledPath); 18253 } else { 18254 ctx.fill(path); 18255 } 18256 } 18257 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { 18258 if (patternStrokeTransform) { 18259 currentTransform ||= ctx.getTransform(); 18260 ctx.setTransform(...patternStrokeTransform); 18261 const { 18262 a, 18263 b, 18264 c, 18265 d 18266 } = currentTransform; 18267 const invPatternTransform = Util.inverseTransform(patternStrokeTransform); 18268 const transf = Util.transform([a, b, c, d, 0, 0], invPatternTransform); 18269 Util.singularValueDecompose2dScale(transf, XY); 18270 ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize; 18271 ctx.stroke(this.#getScaledPath(path, currentTransform, patternStrokeTransform)); 18272 } else { 18273 ctx.lineWidth /= fontSize; 18274 ctx.stroke(path); 18275 } 18276 } 18277 ctx.restore(); 18278 } else { 18279 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { 18280 ctx.fillText(character, x, y); 18281 this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character)); 18282 } 18283 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { 18284 if (this.dependencyTracker) { 18285 this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke); 18286 } 18287 ctx.strokeText(character, x, y); 18288 } 18289 } 18290 if (isAddToPathSet) { 18291 const paths = this.pendingTextPaths ||= []; 18292 paths.push({ 18293 transform: getCurrentTransform(ctx), 18294 x, 18295 y, 18296 fontSize, 18297 path 18298 }); 18299 this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y); 18300 } 18301 } 18302 get isFontSubpixelAAEnabled() { 18303 const { 18304 context: ctx 18305 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); 18306 ctx.scale(1.5, 1); 18307 ctx.fillText("I", 0, 10); 18308 const data = ctx.getImageData(0, 0, 10, 10).data; 18309 let enabled = false; 18310 for (let i = 3; i < data.length; i += 4) { 18311 if (data[i] > 0 && data[i] < 255) { 18312 enabled = true; 18313 break; 18314 } 18315 } 18316 return shadow(this, "isFontSubpixelAAEnabled", enabled); 18317 } 18318 showText(opIdx, glyphs) { 18319 if (this.dependencyTracker) { 18320 this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx); 18321 if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) { 18322 this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies(); 18323 } 18324 } 18325 const current = this.current; 18326 const font = current.font; 18327 if (font.isType3Font) { 18328 this.showType3Text(opIdx, glyphs); 18329 this.dependencyTracker?.recordShowTextOperation(opIdx); 18330 return
vendor: 7,185 bytes, lines 18330-18507
18330undefined; 18331 } 18332 const fontSize = current.fontSize; 18333 if (fontSize === 0) { 18334 this.dependencyTracker?.recordOperation(opIdx); 18335 return undefined; 18336 } 18337 const ctx = this.ctx; 18338 const fontSizeScale = current.fontSizeScale; 18339 const charSpacing = current.charSpacing; 18340 const wordSpacing = current.wordSpacing; 18341 const fontDirection = current.fontDirection; 18342 const textHScale = current.textHScale * fontDirection; 18343 const glyphsLength = glyphs.length; 18344 const vertical = font.vertical; 18345 const spacingDir = vertical ? 1 : -1; 18346 const defaultVMetrics = font.defaultVMetrics; 18347 const widthAdvanceScale = fontSize * current.fontMatrix[0]; 18348 const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; 18349 ctx.save(); 18350 if (current.textMatrix) { 18351 ctx.transform(...current.textMatrix); 18352 } 18353 ctx.translate(current.x, current.y + current.textRise); 18354 if (fontDirection > 0) { 18355 ctx.scale(textHScale, -1); 18356 } else { 18357 ctx.scale(textHScale, 1); 18358 } 18359 let patternFillTransform, patternStrokeTransform; 18360 const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; 18361 const needsFill = fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE; 18362 const needsStroke = fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE; 18363 if (needsFill && current.patternFill) { 18364 ctx.save(); 18365 const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); 18366 patternFillTransform = getCurrentTransform(ctx); 18367 ctx.restore(); 18368 ctx.fillStyle = pattern; 18369 } 18370 if (needsStroke && current.patternStroke) { 18371 ctx.save(); 18372 const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); 18373 patternStrokeTransform = getCurrentTransform(ctx); 18374 ctx.restore(); 18375 ctx.strokeStyle = pattern; 18376 } 18377 let lineWidth = current.lineWidth; 18378 const scale = current.textMatrixScale; 18379 if (scale === 0 || lineWidth === 0) { 18380 if (needsStroke) { 18381 lineWidth = this.getSinglePixelWidth(); 18382 } 18383 } else { 18384 lineWidth /= scale; 18385 } 18386 if (fontSizeScale !== 1.0) { 18387 ctx.scale(fontSizeScale, fontSizeScale); 18388 lineWidth /= fontSizeScale; 18389 } 18390 ctx.lineWidth = lineWidth; 18391 if (font.isInvalidPDFjsFont) { 18392 const chars = []; 18393 let width = 0; 18394 for (const glyph of glyphs) { 18395 chars.push(glyph.unicode); 18396 width += glyph.width; 18397 } 18398 const joinedChars = chars.join(""); 18399 ctx.fillText(joinedChars, 0, 0); 18400 if (this.dependencyTracker !== null) { 18401 const measure = ctx.measureText(joinedChars); 18402 this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx); 18403 } 18404 current.x += width * widthAdvanceScale * textHScale; 18405 ctx.restore(); 18406 this.compose(); 18407 return undefined; 18408 } 18409 let x = 0, 18410 i; 18411 for (i = 0; i < glyphsLength; ++i) { 18412 const glyph = glyphs[i]; 18413 if (typeof glyph === "number") { 18414 x += spacingDir * glyph * fontSize / 1000; 18415 continue; 18416 } 18417 let restoreNeeded = false; 18418 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; 18419 const character = glyph.fontChar; 18420 const accent = glyph.accent; 18421 let scaledX, scaledY; 18422 let width = glyph.width; 18423 if (vertical) { 18424 const vmetric = glyph.vmetric || defaultVMetrics; 18425 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; 18426 const vy = vmetric[2] * widthAdvanceScale; 18427 width = vmetric ? -vmetric[0] : width; 18428 scaledX = vx / fontSizeScale; 18429 scaledY = (x + vy) / fontSizeScale; 18430 } else { 18431 scaledX = x / fontSizeScale; 18432 scaledY = 0; 18433 } 18434 let measure; 18435 if (font.remeasure && width > 0) { 18436 measure = ctx.measureText(character); 18437 const measuredWidth = measure.width * 1000 / fontSize * fontSizeScale; 18438 if (width < measuredWidth && this.isFontSubpixelAAEnabled) { 18439 const characterScaleX = width / measuredWidth; 18440 restoreNeeded = true; 18441 ctx.save(); 18442 ctx.scale(characterScaleX, 1); 18443 scaledX /= characterScaleX; 18444 } else if (width !== measuredWidth) { 18445 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; 18446 } 18447 } 18448 if (this.contentVisible && (glyph.isInFont || font.missingFile)) { 18449 if (simpleFillText && !accent) { 18450 ctx.fillText(character, scaledX, scaledY); 18451 this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? { 18452 bbox: null 18453 } : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character)); 18454 } else { 18455 this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform); 18456 if (accent) { 18457 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; 18458 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; 18459 this.paintChar(opIdx, accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform); 18460 } 18461 } 18462 } 18463 const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; 18464 x += charWidth; 18465 if (restoreNeeded) { 18466 ctx.restore(); 18467 } 18468 } 18469 if (vertical) { 18470 current.y -= x; 18471 } else { 18472 current.x += x * textHScale; 18473 } 18474 ctx.restore(); 18475 this.compose(); 18476 this.dependencyTracker?.recordShowTextOperation(opIdx); 18477 return undefined; 18478 } 18479 showType3Text(opIdx, glyphs) { 18480 const ctx = this.ctx; 18481 const current = this.current; 18482 const font = current.font; 18483 const fontSize = current.fontSize; 18484 const fontDirection = current.fontDirection; 18485 const spacingDir = font.vertical ? 1 : -1; 18486 const charSpacing = current.charSpacing; 18487 const wordSpacing = current.wordSpacing; 18488 const textHScale = current.textHScale * fontDirection; 18489 const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; 18490 const glyphsLength = glyphs.length; 18491 const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; 18492 let i, glyph, width, spacingLength; 18493 if (isTextInvisible || fontSize === 0) { 18494 return; 18495 } 18496 this._cachedScaleForStroking[0] = -1; 18497 this._cachedGetSinglePixelWidth = null; 18498 ctx.save(); 18499 if (current.textMatrix) { 18500 ctx.transform(...current.textMatrix); 18501 } 18502 ctx.translate(current.x, current.y + current.textRise); 18503 ctx.scale(textHScale, fontDirection); 18504 const dependencyTracker = this.dependencyTracker; 18505 this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null; 18506 for (i = 0; i < glyphsLength; ++i) { 18507 glyph = glyphs[i];
vendor: 1,863 bytes, lines 18508-18552
18508 if (typeof glyph === "number") { 18509 spacingLength = spacingDir * glyph * fontSize / 1000; 18510 this.ctx.translate(spacingLength, 0); 18511 current.x += spacingLength * textHScale; 18512 continue; 18513 } 18514 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; 18515 const operatorList = font.charProcOperatorList[glyph.operatorListId]; 18516 if (!operatorList) { 18517 warn(`Type3 character "${glyph.operatorListId}" is not available.`); 18518 } else if (this.contentVisible) { 18519 this.save(); 18520 ctx.scale(fontSize, fontSize); 18521 ctx.transform(...fontMatrix); 18522 this.executeOperatorList(operatorList); 18523 this.restore(); 18524 } 18525 const p = [glyph.width, 0]; 18526 Util.applyTransform(p, fontMatrix); 18527 width = p[0] * fontSize + spacing; 18528 ctx.translate(width, 0); 18529 current.x += width * textHScale; 18530 } 18531 ctx.restore(); 18532 if (dependencyTracker) { 18533 this.dependencyTracker = dependencyTracker; 18534 } 18535 } 18536 setCharWidth(opIdx, xWidth, yWidth) {} 18537 setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) { 18538 const clip = new Path2D(); 18539 clip.rect(llx, lly, urx - llx, ury - lly); 18540 this.ctx.clip(clip); 18541 this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury); 18542 this.endPath(opIdx); 18543 } 18544 getColorN_Pattern(opIdx, IR) { 18545 let pattern; 18546 if (IR[0] === "TilingPattern") { 18547 const baseTransform = this.baseTransform || getCurrentTransform(this.ctx); 18548 const canvasGraphicsFactory = { 18549 createCanvasGraphics: (ctx, renderingOpIdx) => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { 18550 optionalContentConfig: this.optionalContentConfig, 18551 markedContentStack: this.markedContentStack 18552 }, undefined, undefined
vendor: 6,488 bytes, lines 18552-18730
18552, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null) 18553 }; 18554 pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform); 18555 } else { 18556 pattern = this._getPattern(opIdx, IR[1], IR[2]); 18557 } 18558 return pattern; 18559 } 18560 setStrokeColorN(opIdx, ...args) { 18561 this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); 18562 this.current.strokeColor = this.getColorN_Pattern(opIdx, args); 18563 this.current.patternStroke = true; 18564 } 18565 setFillColorN(opIdx, ...args) { 18566 this.dependencyTracker?.recordSimpleData("fillColor", opIdx); 18567 this.current.fillColor = this.getColorN_Pattern(opIdx, args); 18568 this.current.patternFill = true; 18569 } 18570 setStrokeRGBColor(opIdx, color) { 18571 this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); 18572 this.ctx.strokeStyle = this.current.strokeColor = color; 18573 this.current.patternStroke = false; 18574 } 18575 setStrokeTransparent(opIdx) { 18576 this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); 18577 this.ctx.strokeStyle = this.current.strokeColor = "transparent"; 18578 this.current.patternStroke = false; 18579 } 18580 setFillRGBColor(opIdx, color) { 18581 this.dependencyTracker?.recordSimpleData("fillColor", opIdx); 18582 this.ctx.fillStyle = this.current.fillColor = color; 18583 this.current.patternFill = false; 18584 } 18585 setFillTransparent(opIdx) { 18586 this.dependencyTracker?.recordSimpleData("fillColor", opIdx); 18587 this.ctx.fillStyle = this.current.fillColor = "transparent"; 18588 this.current.patternFill = false; 18589 } 18590 _getPattern(opIdx, objId, matrix = null) { 18591 let pattern; 18592 if (this.cachedPatterns.has(objId)) { 18593 pattern = this.cachedPatterns.get(objId); 18594 } else { 18595 pattern = getShadingPattern(this.getObject(opIdx, objId)); 18596 this.cachedPatterns.set(objId, pattern); 18597 } 18598 if (matrix) { 18599 pattern.matrix = matrix; 18600 } 18601 return pattern; 18602 } 18603 shadingFill(opIdx, objId) { 18604 if (!this.contentVisible) { 18605 return; 18606 } 18607 const ctx = this.ctx; 18608 this.save(opIdx); 18609 const pattern = this._getPattern(opIdx, objId); 18610 ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx); 18611 const inv = getCurrentTransformInverse(ctx); 18612 if (inv) { 18613 const { 18614 width, 18615 height 18616 } = ctx.canvas; 18617 const minMax = MIN_MAX_INIT.slice(); 18618 Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax); 18619 const [x0, y0, x1, y1] = minMax; 18620 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); 18621 } else { 18622 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); 18623 } 18624 this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); 18625 this.compose(this.current.getClippedPathBoundingBox()); 18626 this.restore(opIdx); 18627 } 18628 beginInlineImage() { 18629 unreachable("Should not call beginInlineImage"); 18630 } 18631 beginImageData() { 18632 unreachable("Should not call beginImageData"); 18633 } 18634 paintFormXObjectBegin(opIdx, matrix, bbox) { 18635 if (!this.contentVisible) { 18636 return; 18637 } 18638 this.save(opIdx); 18639 this.baseTransformStack.push(this.baseTransform); 18640 if (matrix) { 18641 this.transform(opIdx, ...matrix); 18642 } 18643 this.baseTransform = getCurrentTransform(this.ctx); 18644 if (bbox) { 18645 Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax); 18646 const [x0, y0, x1, y1] = bbox; 18647 const clip = new Path2D(); 18648 clip.rect(x0, y0, x1 - x0, y1 - y0); 18649 this.ctx.clip(clip); 18650 this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1); 18651 this.endPath(opIdx); 18652 } 18653 } 18654 paintFormXObjectEnd(opIdx) { 18655 if (!this.contentVisible) { 18656 return; 18657 } 18658 this.restore(opIdx); 18659 this.baseTransform = this.baseTransformStack.pop(); 18660 } 18661 beginGroup(opIdx, group) { 18662 if (!this.contentVisible) { 18663 return; 18664 } 18665 this.save(opIdx); 18666 if (this.inSMaskMode) { 18667 this.endSMaskMode(); 18668 this.current.activeSMask = null; 18669 } 18670 const currentCtx = this.ctx; 18671 if (!group.isolated) { 18672 info("TODO: Support non-isolated groups."); 18673 } 18674 if (group.knockout) { 18675 warn("Knockout groups not supported."); 18676 } 18677 const currentTransform = getCurrentTransform(currentCtx); 18678 if (group.matrix) { 18679 currentCtx.transform(...group.matrix); 18680 } 18681 if (!group.bbox) { 18682 throw new Error("Bounding box is required."); 18683 } 18684 let bounds = MIN_MAX_INIT.slice(); 18685 Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds); 18686 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; 18687 bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; 18688 const offsetX = Math.floor(bounds[0]); 18689 const offsetY = Math.floor(bounds[1]); 18690 const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); 18691 const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); 18692 this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); 18693 let cacheId = "groupAt" + this.groupLevel; 18694 if (group.smask) { 18695 cacheId += "_smask_" + this.smaskCounter++ % 2; 18696 } 18697 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); 18698 const groupCtx = scratchCanvas.context; 18699 groupCtx.translate(-offsetX, -offsetY); 18700 groupCtx.transform(...currentTransform); 18701 let clip = new Path2D(); 18702 const [x0, y0, x1, y1] = group.bbox; 18703 clip.rect(x0, y0, x1 - x0, y1 - y0); 18704 if (group.matrix) { 18705 const path = new Path2D(); 18706 path.addPath(clip, new DOMMatrix(group.matrix)); 18707 clip = path; 18708 } 18709 groupCtx.clip(clip); 18710 if (group.smask) { 18711 this.smaskStack.push({ 18712 canvas: scratchCanvas.canvas, 18713 context: groupCtx, 18714 offsetX, 18715 offsetY, 18716 subtype: group.smask.subtype, 18717 backdrop: group.smask.backdrop, 18718 transferMap: group.smask.transferMap || null, 18719 startTransformInverse: null 18720 }); 18721 } 18722 if (!group.smask || this.dependencyTracker) { 18723 currentCtx.setTransform(1, 0, 0, 1, 0, 0); 18724 currentCtx.translate(offsetX, offsetY); 18725 currentCtx.save(); 18726 } 18727 copyCtxState(currentCtx, groupCtx); 18728 this.ctx = groupCtx; 18729 this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx); 18730 this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1]
18730, ["TR", null
vendor: 10,222 bytes, lines 18730-19019
18730]]); 18731 this.groupStack.push(currentCtx); 18732 this.groupLevel++; 18733 } 18734 endGroup(opIdx, group) { 18735 if (!this.contentVisible) { 18736 return; 18737 } 18738 this.groupLevel--; 18739 const groupCtx = this.ctx; 18740 const ctx = this.groupStack.pop(); 18741 this.ctx = ctx; 18742 this.ctx.imageSmoothingEnabled = false; 18743 this.dependencyTracker?.popBaseTransform(); 18744 if (group.smask) { 18745 this.tempSMask = this.smaskStack.pop(); 18746 this.restore(opIdx); 18747 if (this.dependencyTracker) { 18748 this.ctx.restore(); 18749 } 18750 } else { 18751 this.ctx.restore(); 18752 const currentMtx = getCurrentTransform(this.ctx); 18753 this.restore(opIdx); 18754 this.ctx.save(); 18755 this.ctx.setTransform(...currentMtx); 18756 const dirtyBox = MIN_MAX_INIT.slice(); 18757 Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox); 18758 this.ctx.drawImage(groupCtx.canvas, 0, 0); 18759 this.ctx.restore(); 18760 this.compose(dirtyBox); 18761 } 18762 } 18763 beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) { 18764 this.#restoreInitialState(); 18765 resetCtxToDefault(this.ctx); 18766 this.ctx.save(); 18767 this.save(opIdx); 18768 if (this.baseTransform) { 18769 this.ctx.setTransform(...this.baseTransform); 18770 } 18771 if (rect) { 18772 const width = rect[2] - rect[0]; 18773 const height = rect[3] - rect[1]; 18774 if (hasOwnCanvas && this.annotationCanvasMap) { 18775 transform = transform.slice(); 18776 transform[4] -= rect[0]; 18777 transform[5] -= rect[1]; 18778 rect = rect.slice(); 18779 rect[0] = rect[1] = 0; 18780 rect[2] = width; 18781 rect[3] = height; 18782 Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY); 18783 const { 18784 viewportScale 18785 } = this; 18786 const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); 18787 const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); 18788 this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); 18789 const { 18790 canvas, 18791 context 18792 } = this.annotationCanvas; 18793 this.annotationCanvasMap.set(id, canvas); 18794 this.annotationCanvas.savedCtx = this.ctx; 18795 this.ctx = context; 18796 this.ctx.save(); 18797 this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]); 18798 resetCtxToDefault(this.ctx); 18799 } else { 18800 resetCtxToDefault(this.ctx); 18801 this.endPath(opIdx); 18802 const clip = new Path2D(); 18803 clip.rect(rect[0], rect[1], width, height); 18804 this.ctx.clip(clip); 18805 } 18806 } 18807 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); 18808 this.transform(opIdx, ...transform); 18809 this.transform(opIdx, ...matrix); 18810 } 18811 endAnnotation(opIdx) { 18812 if (this.annotationCanvas) { 18813 this.ctx.restore(); 18814 this.#drawFilter(); 18815 this.ctx = this.annotationCanvas.savedCtx; 18816 delete this.annotationCanvas.savedCtx; 18817 delete this.annotationCanvas; 18818 } 18819 } 18820 paintImageMaskXObject(opIdx, img) { 18821 if (!this.contentVisible) { 18822 return; 18823 } 18824 const count = img.count; 18825 img = this.getObject(opIdx, img.data, img); 18826 img.count = count; 18827 const ctx = this.ctx; 18828 const mask = this._createMaskCanvas(opIdx, img); 18829 const maskCanvas = mask.canvas; 18830 ctx.save(); 18831 ctx.setTransform(1, 0, 0, 1, 0, 0); 18832 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); 18833 this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx); 18834 ctx.restore(); 18835 this.compose(); 18836 } 18837 paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions) { 18838 if (!this.contentVisible) { 18839 return; 18840 } 18841 img = this.getObject(opIdx, img.data, img); 18842 const ctx = this.ctx; 18843 ctx.save(); 18844 const currentTransform = getCurrentTransform(ctx); 18845 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); 18846 const mask = this._createMaskCanvas(opIdx, img); 18847 ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); 18848 this.dependencyTracker?.resetBBox(opIdx); 18849 for (let i = 0, ii = positions.length; i < ii; i += 2) { 18850 const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); 18851 ctx.drawImage(mask.canvas, trans[4], trans[5]); 18852 this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height); 18853 } 18854 ctx.restore(); 18855 this.compose(); 18856 this.dependencyTracker?.recordOperation(opIdx); 18857 } 18858 paintImageMaskXObjectGroup(opIdx, images) { 18859 if (!this.contentVisible) { 18860 return; 18861 } 18862 const ctx = this.ctx; 18863 const fillColor = this.current.fillColor; 18864 const isPatternFill = this.current.patternFill; 18865 this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill); 18866 for (const image of images) { 18867 const { 18868 data, 18869 width, 18870 height, 18871 transform 18872 } = image; 18873 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); 18874 const maskCtx = maskCanvas.context; 18875 maskCtx.save(); 18876 const img = this.getObject(opIdx, data, image); 18877 putBinaryImageMask(maskCtx, img); 18878 maskCtx.globalCompositeOperation = "source-in"; 18879 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor; 18880 maskCtx.fillRect(0, 0, width, height); 18881 maskCtx.restore(); 18882 ctx.save(); 18883 ctx.transform(...transform); 18884 ctx.scale(1, -1); 18885 drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); 18886 this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height); 18887 ctx.restore(); 18888 } 18889 this.compose(); 18890 this.dependencyTracker?.recordOperation(opIdx); 18891 } 18892 paintImageXObject(opIdx, objId) { 18893 if (!this.contentVisible) { 18894 return; 18895 } 18896 const imgData = this.getObject(opIdx, objId); 18897 if (!imgData) { 18898 warn("Dependent image isn't ready yet"); 18899 return; 18900 } 18901 this.paintInlineImageXObject(opIdx, imgData); 18902 } 18903 paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions) { 18904 if (!this.contentVisible) { 18905 return; 18906 } 18907 const imgData = this.getObject(opIdx, objId); 18908 if (!imgData) { 18909 warn("Dependent image isn't ready yet"); 18910 return; 18911 } 18912 const width = imgData.width; 18913 const height = imgData.height; 18914 const map = []; 18915 for (let i = 0, ii = positions.length; i < ii; i += 2) { 18916 map.push({ 18917 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], 18918 x: 0, 18919 y: 0, 18920 w: width, 18921 h: height 18922 }); 18923 } 18924 this.paintInlineImageXObjectGroup(opIdx, imgData, map); 18925 } 18926 applyTransferMapsToCanvas(ctx) { 18927 if (this.current.transferMaps !== "none") { 18928 ctx.filter = this.current.transferMaps; 18929 ctx.drawImage(ctx.canvas, 0, 0); 18930 ctx.filter = "none"; 18931 } 18932 return ctx.canvas; 18933 } 18934 applyTransferMapsToBitmap(imgData) { 18935 if (this.current.transferMaps === "none") { 18936 return imgData.bitmap; 18937 } 18938 const { 18939 bitmap, 18940 width, 18941 height 18942 } = imgData; 18943 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); 18944 const tmpCtx = tmpCanvas.context; 18945 tmpCtx.filter = this.current.transferMaps; 18946 tmpCtx.drawImage(bitmap, 0, 0); 18947 tmpCtx.filter = "none"; 18948 return tmpCanvas.canvas; 18949 } 18950 paintInlineImageXObject(opIdx, imgData) { 18951 if (!this.contentVisible) { 18952 return; 18953 } 18954 const width = imgData.width; 18955 const height = imgData.height; 18956 const ctx = this.ctx; 18957 this.save(opIdx); 18958 const { 18959 filter 18960 } = ctx; 18961 if (filter !== "none" && filter !== "") { 18962 ctx.filter = "none"; 18963 } 18964 ctx.scale(1 / width, -1 / height); 18965 let imgToPaint; 18966 if (imgData.bitmap) { 18967 imgToPaint = this.applyTransferMapsToBitmap(imgData); 18968 } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { 18969 imgToPaint = imgData; 18970 } else { 18971 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); 18972 const tmpCtx = tmpCanvas.context; 18973 putBinaryImageData(tmpCtx, imgData); 18974 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); 18975 } 18976 const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx)); 18977 ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate); 18978 this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx); 18979 drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); 18980 this.compose(); 18981 this.restore(opIdx); 18982 } 18983 paintInlineImageXObjectGroup(opIdx, imgData, map) { 18984 if (!this.contentVisible) { 18985 return; 18986 } 18987 const ctx = this.ctx; 18988 let imgToPaint; 18989 if (imgData.bitmap) { 18990 imgToPaint = imgData.bitmap; 18991 } else { 18992 const w = imgData.width; 18993 const h = imgData.height; 18994 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); 18995 const tmpCtx = tmpCanvas.context; 18996 putBinaryImageData(tmpCtx, imgData); 18997 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); 18998 } 18999 this.dependencyTracker?.resetBBox(opIdx); 19000 for (const entry of map) { 19001 ctx.save(); 19002 ctx.transform(...entry.transform); 19003 ctx.scale(1, -1); 19004 drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); 19005 this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0); 19006 ctx.restore(); 19007 } 19008 this.dependencyTracker?.recordOperation(opIdx); 19009 this.compose(); 19010 } 19011 paintSolidColorImageMask(opIdx) { 19012 if (!this.contentVisible) { 19013 return; 19014 } 19015 this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); 19016 this.ctx.fillRect(0, 0, 1, 1); 19017 this.compose(); 19018 } 19019 markPoint(opIdx, tag) {
vendor: 29,817 bytes, lines 19019-20147
19019} 19020 markPointProps(opIdx, tag, properties) {} 19021 beginMarkedContent(opIdx, tag) { 19022 this.dependencyTracker?.beginMarkedContent(opIdx); 19023 this.markedContentStack.push({ 19024 visible: true 19025 }); 19026 } 19027 beginMarkedContentProps(opIdx, tag, properties) { 19028 this.dependencyTracker?.beginMarkedContent(opIdx); 19029 if (tag === "OC") { 19030 this.markedContentStack.push({ 19031 visible: this.optionalContentConfig.isVisible(properties) 19032 }); 19033 } else { 19034 this.markedContentStack.push({ 19035 visible: true 19036 }); 19037 } 19038 this.contentVisible = this.isContentVisible(); 19039 } 19040 endMarkedContent(opIdx) { 19041 this.dependencyTracker?.endMarkedContent(opIdx); 19042 this.markedContentStack.pop(); 19043 this.contentVisible = this.isContentVisible(); 19044 } 19045 beginCompat(opIdx) {} 19046 endCompat(opIdx) {} 19047 consumePath(opIdx, path, clipBox) { 19048 const isEmpty = this.current.isEmptyClip(); 19049 if (this.pendingClip) { 19050 this.current.updateClipFromPath(); 19051 } 19052 if (!this.pendingClip) { 19053 this.compose(clipBox); 19054 } 19055 const ctx = this.ctx; 19056 if (this.pendingClip) { 19057 if (!isEmpty) { 19058 if (this.pendingClip === EO_CLIP) { 19059 ctx.clip(path, "evenodd"); 19060 } else { 19061 ctx.clip(path); 19062 } 19063 } 19064 this.pendingClip = null; 19065 this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx); 19066 } else { 19067 this.dependencyTracker?.recordOperation(opIdx); 19068 } 19069 this.current.startNewPathAndClipBox(this.current.clipBox); 19070 } 19071 getSinglePixelWidth() { 19072 if (!this._cachedGetSinglePixelWidth) { 19073 const m = getCurrentTransform(this.ctx); 19074 if (m[1] === 0 && m[2] === 0) { 19075 this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3])); 19076 } else { 19077 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); 19078 const normX = Math.hypot(m[0], m[2]); 19079 const normY = Math.hypot(m[1], m[3]); 19080 this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; 19081 } 19082 } 19083 return this._cachedGetSinglePixelWidth; 19084 } 19085 getScaleForStroking() { 19086 if (this._cachedScaleForStroking[0] === -1) { 19087 const { 19088 lineWidth 19089 } = this.current; 19090 const { 19091 a, 19092 b, 19093 c, 19094 d 19095 } = this.ctx.getTransform(); 19096 let scaleX, scaleY; 19097 if (b === 0 && c === 0) { 19098 const normX = Math.abs(a); 19099 const normY = Math.abs(d); 19100 if (normX === normY) { 19101 if (lineWidth === 0) { 19102 scaleX = scaleY = 1 / normX; 19103 } else { 19104 const scaledLineWidth = normX * lineWidth; 19105 scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; 19106 } 19107 } else if (lineWidth === 0) { 19108 scaleX = 1 / normX; 19109 scaleY = 1 / normY; 19110 } else { 19111 const scaledXLineWidth = normX * lineWidth; 19112 const scaledYLineWidth = normY * lineWidth; 19113 scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; 19114 scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; 19115 } 19116 } else { 19117 const absDet = Math.abs(a * d - b * c); 19118 const normX = Math.hypot(a, b); 19119 const normY = Math.hypot(c, d); 19120 if (lineWidth === 0) { 19121 scaleX = normY / absDet; 19122 scaleY = normX / absDet; 19123 } else { 19124 const baseArea = lineWidth * absDet; 19125 scaleX = normY > baseArea ? normY / baseArea : 1; 19126 scaleY = normX > baseArea ? normX / baseArea : 1; 19127 } 19128 } 19129 this._cachedScaleForStroking[0] = scaleX; 19130 this._cachedScaleForStroking[1] = scaleY; 19131 } 19132 return this._cachedScaleForStroking; 19133 } 19134 rescaleAndStroke(path, saveRestore) { 19135 const { 19136 ctx, 19137 current: { 19138 lineWidth 19139 } 19140 } = this; 19141 const [scaleX, scaleY] = this.getScaleForStroking(); 19142 if (scaleX === scaleY) { 19143 ctx.lineWidth = (lineWidth || 1) * scaleX; 19144 ctx.stroke(path); 19145 return; 19146 } 19147 const dashes = ctx.getLineDash(); 19148 if (saveRestore) { 19149 ctx.save(); 19150 } 19151 ctx.scale(scaleX, scaleY); 19152 SCALE_MATRIX.a = 1 / scaleX; 19153 SCALE_MATRIX.d = 1 / scaleY; 19154 const newPath = new Path2D(); 19155 newPath.addPath(path, SCALE_MATRIX); 19156 if (dashes.length > 0) { 19157 const scale = Math.max(scaleX, scaleY); 19158 ctx.setLineDash(dashes.map(x => x / scale)); 19159 ctx.lineDashOffset /= scale; 19160 } 19161 ctx.lineWidth = lineWidth || 1; 19162 ctx.stroke(newPath); 19163 if (saveRestore) { 19164 ctx.restore(); 19165 } 19166 } 19167 isContentVisible() { 19168 for (let i = this.markedContentStack.length - 1; i >= 0; i--) { 19169 if (!this.markedContentStack[i].visible) { 19170 return false; 19171 } 19172 } 19173 return true; 19174 } 19175} 19176for (const op in OPS) { 19177 if (CanvasGraphics.prototype[op] !== undefined) { 19178 CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; 19179 } 19180} 19181 19182;// ./src/display/worker_options.js 19183class GlobalWorkerOptions { 19184 static #port = null; 19185 static #src = ""; 19186 static get workerPort() { 19187 return this.#port; 19188 } 19189 static set workerPort(val) { 19190 if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) { 19191 throw new Error("Invalid `workerPort` type."); 19192 } 19193 this.#port = val; 19194 } 19195 static get workerSrc() { 19196 return this.#src; 19197 } 19198 static set workerSrc(val) { 19199 if (typeof val !== "string") { 19200 throw new Error("Invalid `workerSrc` type."); 19201 } 19202 this.#src = val; 19203 } 19204} 19205 19206;// ./src/display/metadata.js 19207class Metadata { 19208 #map; 19209 #data; 19210 constructor({ 19211 parsedData, 19212 rawData 19213 }) { 19214 this.#map = parsedData; 19215 this.#data = rawData; 19216 } 19217 getRaw() { 19218 return this.#data; 19219 } 19220 get(name) { 19221 return this.#map.get(name) ?? null; 19222 } 19223 [Symbol.iterator]() { 19224 return this.#map.entries(); 19225 } 19226} 19227 19228;// ./src/display/optional_content_config.js 19229 19230 19231 19232 19233const INTERNAL = Symbol("INTERNAL"); 19234class OptionalContentGroup { 19235 #isDisplay = false; 19236 #isPrint = false; 19237 #userSet = false; 19238 #visible = true; 19239 constructor(renderingIntent, { 19240 name, 19241 intent, 19242 usage, 19243 rbGroups 19244 }) { 19245 this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY); 19246 this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); 19247 this.name = name; 19248 this.intent = intent; 19249 this.usage = usage; 19250 this.rbGroups = rbGroups; 19251 } 19252 get visible() { 19253 if (this.#userSet) { 19254 return this.#visible; 19255 } 19256 if (!this.#visible) { 19257 return false; 19258 } 19259 const { 19260 print, 19261 view 19262 } = this.usage; 19263 if (this.#isDisplay) { 19264 return view?.viewState !== "OFF"; 19265 } else if (this.#isPrint) { 19266 return print?.printState !== "OFF"; 19267 } 19268 return true; 19269 } 19270 _setVisible(internal, visible, userSet = false) { 19271 if (internal !== INTERNAL) { 19272 unreachable("Internal method `_setVisible` called."); 19273 } 19274 this.#userSet = userSet; 19275 this.#visible = visible; 19276 } 19277} 19278class OptionalContentConfig { 19279 #cachedGetHash = null; 19280 #groups = new Map(); 19281 #initialHash = null; 19282 #order = null; 19283 constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { 19284 this.renderingIntent = renderingIntent; 19285 this.name = null; 19286 this.creator = null; 19287 if (data === null) { 19288 return; 19289 } 19290 this.name = data.name; 19291 this.creator = data.creator; 19292 this.#order = data.order; 19293 for (const group of data.groups) { 19294 this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); 19295 } 19296 if (data.baseState === "OFF") { 19297 for (const group of this.#groups.values()) { 19298 group._setVisible(INTERNAL, false); 19299 } 19300 } 19301 for (const on of data.on) { 19302 this.#groups.get(on)._setVisible(INTERNAL, true); 19303 } 19304 for (const off of data.off) { 19305 this.#groups.get(off)._setVisible(INTERNAL, false); 19306 } 19307 this.#initialHash = this.getHash(); 19308 } 19309 #evaluateVisibilityExpression(array) { 19310 const length = array.length; 19311 if (length < 2) { 19312 return true; 19313 } 19314 const operator = array[0]; 19315 for (let i = 1; i < length; i++) { 19316 const element = array[i]; 19317 let state; 19318 if (Array.isArray(element)) { 19319 state = this.#evaluateVisibilityExpression(element); 19320 } else if (this.#groups.has(element)) { 19321 state = this.#groups.get(element).visible; 19322 } else { 19323 warn(`Optional content group not found: ${element}`); 19324 return true; 19325 } 19326 switch (operator) { 19327 case "And": 19328 if (!state) { 19329 return false; 19330 } 19331 break; 19332 case "Or": 19333 if (state) { 19334 return true; 19335 } 19336 break; 19337 case "Not": 19338 return !state; 19339 default: 19340 return true; 19341 } 19342 } 19343 return operator === "And"; 19344 } 19345 isVisible(group) { 19346 if (this.#groups.size === 0) { 19347 return true; 19348 } 19349 if (!group) { 19350 info("Optional content group not defined."); 19351 return true; 19352 } 19353 if (group.type === "OCG") { 19354 if (!this.#groups.has(group.id)) { 19355 warn(`Optional content group not found: ${group.id}`); 19356 return true; 19357 } 19358 return this.#groups.get(group.id).visible; 19359 } else if (group.type === "OCMD") { 19360 if (group.expression) { 19361 return this.#evaluateVisibilityExpression(group.expression); 19362 } 19363 if (!group.policy || group.policy === "AnyOn") { 19364 for (const id of group.ids) { 19365 if (!this.#groups.has(id)) { 19366 warn(`Optional content group not found: ${id}`); 19367 return true; 19368 } 19369 if (this.#groups.get(id).visible) { 19370 return true; 19371 } 19372 } 19373 return false; 19374 } else if (group.policy === "AllOn") { 19375 for (const id of group.ids) { 19376 if (!this.#groups.has(id)) { 19377 warn(`Optional content group not found: ${id}`); 19378 return true; 19379 } 19380 if (!this.#groups.get(id).visible) { 19381 return false; 19382 } 19383 } 19384 return true; 19385 } else if (group.policy === "AnyOff") { 19386 for (const id of group.ids) { 19387 if (!this.#groups.has(id)) { 19388 warn(`Optional content group not found: ${id}`); 19389 return true; 19390 } 19391 if (!this.#groups.get(id).visible) { 19392 return true; 19393 } 19394 } 19395 return false; 19396 } else if (group.policy === "AllOff") { 19397 for (const id of group.ids) { 19398 if (!this.#groups.has(id)) { 19399 warn(`Optional content group not found: ${id}`); 19400 return true; 19401 } 19402 if (this.#groups.get(id).visible) { 19403 return false; 19404 } 19405 } 19406 return true; 19407 } 19408 warn(`Unknown optional content policy ${group.policy}.`); 19409 return true; 19410 } 19411 warn(`Unknown group type ${group.type}.`); 19412 return true; 19413 } 19414 setVisibility(id, visible = true, preserveRB = true) { 19415 const group = this.#groups.get(id); 19416 if (!group) { 19417 warn(`Optional content group not found: ${id}`); 19418 return; 19419 } 19420 if (preserveRB && visible && group.rbGroups.length) { 19421 for (const rbGroup of group.rbGroups) { 19422 for (const otherId of rbGroup) { 19423 if (otherId !== id) { 19424 this.#groups.get(otherId)?._setVisible(INTERNAL, false, true); 19425 } 19426 } 19427 } 19428 } 19429 group._setVisible(INTERNAL, !!visible, true); 19430 this.#cachedGetHash = null; 19431 } 19432 setOCGState({ 19433 state, 19434 preserveRB 19435 }) { 19436 let operator; 19437 for (const elem of state) { 19438 switch (elem) { 19439 case "ON": 19440 case "OFF": 19441 case "Toggle": 19442 operator = elem; 19443 continue; 19444 } 19445 const group = this.#groups.get(elem); 19446 if (!group) { 19447 continue; 19448 } 19449 switch (operator) { 19450 case "ON": 19451 this.setVisibility(elem, true, preserveRB); 19452 break; 19453 case "OFF": 19454 this.setVisibility(elem, false, preserveRB); 19455 break; 19456 case "Toggle": 19457 this.setVisibility(elem, !group.visible, preserveRB); 19458 break; 19459 } 19460 } 19461 this.#cachedGetHash = null; 19462 } 19463 get hasInitialVisibility() { 19464 return this.#initialHash === null || this.getHash() === this.#initialHash; 19465 } 19466 getOrder() { 19467 if (!this.#groups.size) { 19468 return null; 19469 } 19470 if (this.#order) { 19471 return this.#order.slice(); 19472 } 19473 return [...this.#groups.keys()]; 19474 } 19475 getGroup(id) { 19476 return this.#groups.get(id) || null; 19477 } 19478 getHash() { 19479 if (this.#cachedGetHash !== null) { 19480 return this.#cachedGetHash; 19481 } 19482 const hash = new MurmurHash3_64(); 19483 for (const [id, group] of this.#groups) { 19484 hash.update(`${id}:${group.visible}`); 19485 } 19486 return this.#cachedGetHash = hash.hexdigest(); 19487 } 19488 [Symbol.iterator]() { 19489 return this.#groups.entries(); 19490 } 19491} 19492 19493// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.find.js 19494var es_iterator_find = __webpack_require__(116); 19495;// ./src/shared/base_pdf_stream.js 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505class BasePDFStream { 19506 #PDFStreamReader = null; 19507 #PDFStreamRangeReader = null; 19508 _fullReader = null; 19509 _rangeReaders = new Set(); 19510 _source = null; 19511 constructor(source, PDFStreamReader, PDFStreamRangeReader) { 19512 this._source = source; 19513 this.#PDFStreamReader = PDFStreamReader; 19514 this.#PDFStreamRangeReader = PDFStreamRangeReader; 19515 } 19516 get _progressiveDataLength() { 19517 return this._fullReader?._loaded ?? 0; 19518 } 19519 getFullReader() { 19520 assert(!this._fullReader, "BasePDFStream.getFullReader can only be called once."); 19521 return this._fullReader = new this.#PDFStreamReader(this); 19522 } 19523 getRangeReader(begin, end) { 19524 if (end <= this._progressiveDataLength) { 19525 return null; 19526 } 19527 const reader = new this.#PDFStreamRangeReader(this, begin, end); 19528 this._rangeReaders.add(reader); 19529 return reader; 19530 } 19531 cancelAllRequests(reason) { 19532 this._fullReader?.cancel(reason); 19533 for (const reader of new Set(this._rangeReaders)) { 19534 reader.cancel(reason); 19535 } 19536 } 19537} 19538class BasePDFStreamReader { 19539 onProgress = null; 19540 _contentLength = 0; 19541 _filename = null; 19542 _headersCapability = Promise.withResolvers(); 19543 _isRangeSupported = false; 19544 _isStreamingSupported = false; 19545 _loaded = 0; 19546 _stream = null; 19547 constructor(stream) { 19548 this._stream = stream; 19549 } 19550 _callOnProgress() { 19551 this.onProgress?.({ 19552 loaded: this._loaded, 19553 total: this._contentLength 19554 }); 19555 } 19556 get headersReady() { 19557 return this._headersCapability.promise; 19558 } 19559 get filename() { 19560 return this._filename; 19561 } 19562 get contentLength() { 19563 return this._contentLength; 19564 } 19565 get isRangeSupported() { 19566 return this._isRangeSupported; 19567 } 19568 get isStreamingSupported() { 19569 return this._isStreamingSupported; 19570 } 19571 async read() { 19572 unreachable("Abstract method `read` called"); 19573 } 19574 cancel(reason) { 19575 unreachable("Abstract method `cancel` called"); 19576 } 19577} 19578class BasePDFStreamRangeReader { 19579 _stream = null; 19580 constructor(stream, begin, end) { 19581 this._stream = stream; 19582 } 19583 async read() { 19584 unreachable("Abstract method `read` called"); 19585 } 19586 cancel(reason) { 19587 unreachable("Abstract method `cancel` called"); 19588 } 19589} 19590 19591;// ./src/display/transport_stream.js 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607function getArrayBuffer(val) { 19608 return val instanceof Uint8Array && val.byteLength === val.buffer.byteLength ? val.buffer : new Uint8Array(val).buffer; 19609} 19610function endRequests() { 19611 for (const capability of this._requests) { 19612 capability.resolve({ 19613 value: undefined, 19614 done: true 19615 }); 19616 } 19617 this._requests.length = 0; 19618} 19619class PDFDataTransportStream extends BasePDFStream { 19620 _progressiveDone = false; 19621 _queuedChunks = []; 19622 constructor(source) { 19623 super(source, PDFDataTransportStreamReader, PDFDataTransportStreamRangeReader); 19624 const { 19625 pdfDataRangeTransport 19626 } = source; 19627 const { 19628 initialData, 19629 progressiveDone 19630 } = pdfDataRangeTransport; 19631 if (initialData?.length > 0) { 19632 const buffer = getArrayBuffer(initialData); 19633 this._queuedChunks.push(buffer); 19634 } 19635 this._progressiveDone = progressiveDone; 19636 pdfDataRangeTransport.addRangeListener((begin, chunk) => { 19637 this.#onReceiveData(begin, chunk); 19638 }); 19639 pdfDataRangeTransport.addProgressiveReadListener(chunk => { 19640 this.#onReceiveData(undefined, chunk); 19641 }); 19642 pdfDataRangeTransport.addProgressiveDoneListener(() => { 19643 this._fullReader?.progressiveDone(); 19644 this._progressiveDone = true; 19645 }); 19646 pdfDataRangeTransport.transportReady(); 19647 } 19648 #onReceiveData(begin, chunk) { 19649 const buffer = getArrayBuffer(chunk); 19650 if (begin === undefined) { 19651 if (this._fullReader) { 19652 this._fullReader._enqueue(buffer); 19653 } else { 19654 this._queuedChunks.push(buffer); 19655 } 19656 } else { 19657 const rangeReader = this._rangeReaders.keys().find(r => r._begin === begin); 19658 assert(rangeReader, "#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); 19659 rangeReader._enqueue(buffer); 19660 } 19661 } 19662 getFullReader() { 19663 const reader = super.getFullReader(); 19664 this._queuedChunks = null; 19665 return reader; 19666 } 19667 getRangeReader(begin, end) { 19668 const reader = super.getRangeReader(begin, end); 19669 if (reader) { 19670 reader.onDone = () => this._rangeReaders.delete(reader); 19671 this._source.pdfDataRangeTransport.requestDataRange(begin, end); 19672 } 19673 return reader; 19674 } 19675 cancelAllRequests(reason) { 19676 super.cancelAllRequests(reason); 19677 this._source.pdfDataRangeTransport.abort(); 19678 } 19679} 19680class PDFDataTransportStreamReader extends BasePDFStreamReader { 19681 #endRequests = endRequests.bind(this); 19682 _done = false; 19683 _queuedChunks = null; 19684 _requests = []; 19685 constructor(stream) { 19686 super(stream); 19687 const { 19688 pdfDataRangeTransport, 19689 disableRange, 19690 disableStream 19691 } = stream._source; 19692 const { 19693 length, 19694 contentDispositionFilename 19695 } = pdfDataRangeTransport; 19696 this._queuedChunks = stream._queuedChunks || []; 19697 for (const chunk of this._queuedChunks) { 19698 this._loaded += chunk.byteLength; 19699 } 19700 this._done = stream._progressiveDone; 19701 this._contentLength = length; 19702 this._isStreamingSupported = !disableStream; 19703 this._isRangeSupported = !disableRange; 19704 if (isPdfFile(contentDispositionFilename)) { 19705 this._filename = contentDispositionFilename; 19706 } 19707 this._headersCapability.resolve(); 19708 const loaded = this._loaded; 19709 Promise.resolve().then(() => { 19710 if (loaded > 0 && this._loaded === loaded) { 19711 this._callOnProgress(); 19712 } 19713 }); 19714 } 19715 _enqueue(chunk) { 19716 if (this._done) { 19717 return; 19718 } 19719 if (this._requests.length > 0) { 19720 const capability = this._requests.shift(); 19721 capability.resolve({ 19722 value: chunk, 19723 done: false 19724 }); 19725 } else { 19726 this._queuedChunks.push(chunk); 19727 } 19728 this._loaded += chunk.byteLength; 19729 this._callOnProgress(); 19730 } 19731 async read() { 19732 if (this._queuedChunks.length > 0) { 19733 const chunk = this._queuedChunks.shift(); 19734 return { 19735 value: chunk, 19736 done: false 19737 }; 19738 } 19739 if (this._done) { 19740 return { 19741 value: undefined, 19742 done: true 19743 }; 19744 } 19745 const capability = Promise.withResolvers(); 19746 this._requests.push(capability); 19747 return capability.promise; 19748 } 19749 cancel(reason) { 19750 this._done = true; 19751 this.#endRequests(); 19752 } 19753 progressiveDone() { 19754 this._done ||= true; 19755 if (this._queuedChunks.length === 0) { 19756 this.#endRequests(); 19757 } 19758 } 19759} 19760class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader { 19761 #endRequests = endRequests.bind(this); 19762 onDone = null; 19763 _begin = -1; 19764 _done = false; 19765 _queuedChunk = null; 19766 _requests = []; 19767 constructor(stream, begin, end) { 19768 super(stream, begin, end); 19769 this._begin = begin; 19770 } 19771 _enqueue(chunk) { 19772 if (this._done) { 19773 return; 19774 } 19775 if (this._requests.length === 0) { 19776 this._queuedChunk = chunk; 19777 } else { 19778 const capability = this._requests.shift(); 19779 capability.resolve({ 19780 value: chunk, 19781 done: false 19782 }); 19783 this.#endRequests(); 19784 } 19785 this._done = true; 19786 this.onDone?.(); 19787 } 19788 async read() { 19789 if (this._queuedChunk) { 19790 const chunk = this._queuedChunk; 19791 this._queuedChunk = null; 19792 return { 19793 value: chunk, 19794 done: false 19795 }; 19796 } 19797 if (this._done) { 19798 return { 19799 value: undefined, 19800 done: true 19801 }; 19802 } 19803 const capability = Promise.withResolvers(); 19804 this._requests.push(capability); 19805 return capability.promise; 19806 } 19807 cancel(reason) { 19808 this._done = true; 19809 this.#endRequests(); 19810 this.onDone?.(); 19811 } 19812} 19813 19814;// ./src/display/content_disposition.js 19815 19816 19817 19818function getFilenameFromContentDispositionHeader(contentDisposition) { 19819 let needsEncodingFixup = true; 19820 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); 19821 if (tmp) { 19822 tmp = tmp[1]; 19823 let filename = rfc2616unquote(tmp); 19824 filename = unescape(filename); 19825 filename = rfc5987decode(filename); 19826 filename = rfc2047decode(filename); 19827 return fixupEncoding(filename); 19828 } 19829 tmp = rfc2231getparam(contentDisposition); 19830 if (tmp) { 19831 const filename = rfc2047decode(tmp); 19832 return fixupEncoding(filename); 19833 } 19834 tmp = toParamRegExp("filename", "i").exec(contentDisposition); 19835 if (tmp) { 19836 tmp = tmp[1]; 19837 let filename = rfc2616unquote(tmp); 19838 filename = rfc2047decode(filename); 19839 return fixupEncoding(filename); 19840 } 19841 function toParamRegExp(attributePattern, flags) { 19842 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags); 19843 } 19844 function textdecode(encoding, value) { 19845 if (encoding) { 19846 if (!/^[\x00-\xFF]+$/.test(value)) { 19847 return value; 19848 } 19849 try { 19850 const decoder = new TextDecoder(encoding, { 19851 fatal: true 19852 }); 19853 const buffer = stringToBytes(value); 19854 value = decoder.decode(buffer); 19855 needsEncodingFixup = false; 19856 } catch {} 19857 } 19858 return value; 19859 } 19860 function fixupEncoding(value) { 19861 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { 19862 value = textdecode("utf-8", value); 19863 if (needsEncodingFixup) { 19864 value = textdecode("iso-8859-1", value); 19865 } 19866 } 19867 return value; 19868 } 19869 function rfc2231getparam(contentDispositionStr) { 19870 const matches = []; 19871 let match; 19872 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); 19873 while ((match = iter.exec(contentDispositionStr)) !== null) { 19874 let [, n, quot, part] = match; 19875 n = parseInt(n, 10); 19876 if (n in matches) { 19877 if (n === 0) { 19878 break; 19879 } 19880 continue; 19881 } 19882 matches[n] = [quot, part]; 19883 } 19884 const parts = []; 19885 for (let n = 0; n < matches.length; ++n) { 19886 if (!(n in matches)) { 19887 break; 19888 } 19889 let [quot, part] = matches[n]; 19890 part = rfc2616unquote(part); 19891 if (quot) { 19892 part = unescape(part); 19893 if (n === 0) { 19894 part = rfc5987decode(part); 19895 } 19896 } 19897 parts.push(part); 19898 } 19899 return parts.join(""); 19900 } 19901 function rfc2616unquote(value) { 19902 if (value.startsWith('"')) { 19903 const parts = value.slice(1).split('\\"'); 19904 for (let i = 0; i < parts.length; ++i) { 19905 const quotindex = parts[i].indexOf('"'); 19906 if (quotindex !== -1) { 19907 parts[i] = parts[i].slice(0, quotindex); 19908 parts.length = i + 1; 19909 } 19910 parts[i] = parts[i].replaceAll(/\\(.)/g, "$1"); 19911 } 19912 value = parts.join('"'); 19913 } 19914 return value; 19915 } 19916 function rfc5987decode(extvalue) { 19917 const encodingend = extvalue.indexOf("'"); 19918 if (encodingend === -1) { 19919 return extvalue; 19920 } 19921 const encoding = extvalue.slice(0, encodingend); 19922 const langvalue = extvalue.slice(encodingend + 1); 19923 const value = langvalue.replace(/^[^']*'/, ""); 19924 return textdecode(encoding, value); 19925 } 19926 function rfc2047decode(value) { 19927 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { 19928 return value; 19929 } 19930 return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) { 19931 if (encoding === "q" || encoding === "Q") { 19932 text = text.replaceAll("_", " "); 19933 text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) { 19934 return String.fromCharCode(parseInt(hex, 16)); 19935 }); 19936 return textdecode(charset, text); 19937 } 19938 try { 19939 text = atob(text); 19940 } catch {} 19941 return textdecode(charset, text); 19942 }); 19943 } 19944 return ""; 19945} 19946 19947;// ./src/display/network_utils.js 19948 19949 19950 19951 19952function createHeaders(isHttp, httpHeaders) { 19953 const headers = new Headers(); 19954 if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") { 19955 return headers; 19956 } 19957 for (const key in httpHeaders) { 19958 const val = httpHeaders[key]; 19959 if (val !== undefined) { 19960 headers.append(key, val); 19961 } 19962 } 19963 return headers; 19964} 19965function getResponseOrigin(url) { 19966 return URL.parse(url)?.origin ?? null; 19967} 19968function validateRangeRequestCapabilities({ 19969 responseHeaders, 19970 isHttp, 19971 rangeChunkSize, 19972 disableRange 19973}) { 19974 const returnValues = { 19975 allowRangeRequests: false, 19976 suggestedLength: undefined 19977 }; 19978 const length = parseInt(responseHeaders.get("Content-Length"), 10); 19979 if (!Number.isInteger(length)) { 19980 return returnValues; 19981 } 19982 returnValues.suggestedLength = length; 19983 if (length <= 2 * rangeChunkSize) { 19984 return returnValues; 19985 } 19986 if (disableRange || !isHttp) { 19987 return returnValues; 19988 } 19989 if (responseHeaders.get("Accept-Ranges") !== "bytes") { 19990 return returnValues; 19991 } 19992 const contentEncoding = responseHeaders.get("Content-Encoding") || "identity"; 19993 if (contentEncoding !== "identity") { 19994 return returnValues; 19995 } 19996 returnValues.allowRangeRequests = true; 19997 return returnValues; 19998} 19999function extractFilenameFromHeader(responseHeaders) { 20000 const contentDisposition = responseHeaders.get("Content-Disposition"); 20001 if (contentDisposition) { 20002 let filename = getFilenameFromContentDispositionHeader(contentDisposition); 20003 if (filename.includes("%")) { 20004 try { 20005 filename = decodeURIComponent(filename); 20006 } catch {} 20007 } 20008 if (isPdfFile(filename)) { 20009 return filename; 20010 } 20011 } 20012 return null; 20013} 20014function createResponseError(status, url) { 20015 return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url.href}".`, status, status === 404 || status === 0 && url.protocol === "file:"); 20016} 20017function ensureResponseOrigin(rangeOrigin, origin) { 20018 if (rangeOrigin !== origin) { 20019 throw new Error(`Expected range response-origin "${rangeOrigin}" to match "${origin}".`); 20020 } 20021} 20022 20023;// ./src/display/fetch_stream.js 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036function fetchUrl(url, headers, withCredentials, abortController) { 20037 return fetch(url, { 20038 method: "GET", 20039 headers, 20040 signal: abortController.signal, 20041 mode: "cors", 20042 credentials: withCredentials ? "include" : "same-origin", 20043 redirect: "follow" 20044 }); 20045} 20046function ensureResponseStatus(status, url) { 20047 if (status !== 200 && status !== 206) { 20048 throw createResponseError(status, url); 20049 } 20050} 20051function fetch_stream_getArrayBuffer(val) { 20052 if (val instanceof Uint8Array) { 20053 return val.buffer; 20054 } 20055 if (val instanceof ArrayBuffer) { 20056 return val; 20057 } 20058 throw new Error(`getArrayBuffer - unexpected data: ${val}`); 20059} 20060class PDFFetchStream extends BasePDFStream { 20061 _responseOrigin = null; 20062 constructor(source) { 20063 super(source, PDFFetchStreamReader, PDFFetchStreamRangeReader); 20064 const { 20065 httpHeaders, 20066 url 20067 } = source; 20068 assert(/https?:/.test(url.protocol), "PDFFetchStream only supports http(s):// URLs."); 20069 this.headers = createHeaders(true, httpHeaders); 20070 } 20071} 20072class PDFFetchStreamReader extends BasePDFStreamReader { 20073 _abortController = new AbortController(); 20074 _reader = null; 20075 constructor(stream) { 20076 super(stream); 20077 const { 20078 disableRange, 20079 disableStream, 20080 length, 20081 rangeChunkSize, 20082 url, 20083 withCredentials 20084 } = stream._source; 20085 this._contentLength = length; 20086 this._isStreamingSupported = !disableStream; 20087 this._isRangeSupported = !disableRange; 20088 const headers = new Headers(stream.headers); 20089 fetchUrl(url, headers, withCredentials, this._abortController).then(response => { 20090 stream._responseOrigin = getResponseOrigin(response.url); 20091 ensureResponseStatus(response.status, url); 20092 this._reader = response.body.getReader(); 20093 const responseHeaders = response.headers; 20094 const { 20095 allowRangeRequests, 20096 suggestedLength 20097 } = validateRangeRequestCapabilities({ 20098 responseHeaders, 20099 isHttp: true, 20100 rangeChunkSize, 20101 disableRange 20102 }); 20103 this._isRangeSupported = allowRangeRequests; 20104 this._contentLength = suggestedLength || this._contentLength; 20105 this._filename = extractFilenameFromHeader(responseHeaders); 20106 if (!this._isStreamingSupported && this._isRangeSupported) { 20107 this.cancel(new AbortException("Streaming is disabled.")); 20108 } 20109 this._headersCapability.resolve(); 20110 }).catch(this._headersCapability.reject); 20111 } 20112 async read() { 20113 await this._headersCapability.promise; 20114 const { 20115 value, 20116 done 20117 } = await this._reader.read(); 20118 if (done) { 20119 return { 20120 value, 20121 done 20122 }; 20123 } 20124 this._loaded += value.byteLength; 20125 this._callOnProgress(); 20126 return { 20127 value: fetch_stream_getArrayBuffer(value), 20128 done: false 20129 }; 20130 } 20131 cancel(reason) { 20132 this._reader?.cancel(reason); 20133 this._abortController.abort(); 20134 } 20135} 20136class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader { 20137 _abortController = new AbortController(); 20138 _readCapability = Promise.withResolvers(); 20139 _reader = null; 20140 constructor(stream, begin, end) { 20141 super(stream, begin, end); 20142 const { 20143 url, 20144 withCredentials 20145 } = stream._source; 20146 const headers = new Headers(stream.headers); 20147 headers.append("Range", `bytes=${begin}
20147-${end - 1}`); 20148 fetchUrl(url, headers, withCredentials, this._abortController).then(response => { 20149 const responseOrigin = getResponseOrigin(response.url); 20150 ensureResponseOrigin(responseOrigin, stream._responseOrigin); 20151 ensureResponseStatus(response.status, url); 20152 this._reader = response.body.getReader(); 20153 this._readCapability.resolve(); 20154 }).catch(this._readCapability.reject); 20155 } 20156 async read() { 20157 await this._readCapability.promise; 20158 const { 20159 value, 20160 done 20161 } = await this._reader.read(); 20162 if (done) { 20163 return { 20164 value, 20165 done 20166 }; 20167 } 20168 return { 20169 value: fetch_stream_getArrayBuffer(value), 20170 done: false 20171 }; 20172 } 20173 cancel(reason) { 20174 this._reader?.cancel(reason); 20175 this._abortController.abort(); 20176 } 20177} 20178 20179;// ./src/display/network.js 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190const OK_RESPONSE = 200; 20191const PARTIAL_CONTENT_RESPONSE = 206; 20192function network_getArrayBuffer(val) { 20193 return typeof val !== "string" ? val : stringToBytes(val).buffer; 20194} 20195class PDFNetworkStream extends BasePDFStream { 20196 #pendingRequests = new WeakMap(); 20197 _responseOrigin = null; 20198 constructor(source) { 20199 super(source, PDFNetworkStreamReader, PDFNetworkStreamRangeReader); 20200 const { 20201 httpHeaders, 20202 url 20203 } = source; 20204 this.url = url; 20205 this.isHttp = /https?:/.test(url.protocol); 20206 this.headers = createHeaders(this.isHttp, httpHeaders); 20207 } 20208 _request(args) { 20209 const xhr = new XMLHttpRequest(); 20210 const pendingRequest = { 20211 validateStatus: null, 20212 onHeadersReceived: args.onHeadersReceived, 20213 onDone: args.onDone, 20214 onError: args.onError, 20215 onProgress: args.onProgress 20216 }; 20217 this.#pendingRequests.set(xhr, pendingRequest); 20218 xhr.open("GET", this.url); 20219 xhr.withCredentials = this._source.withCredentials; 20220 for (const [key, val] of this.headers) { 20221 xhr.setRequestHeader(key, val); 20222 } 20223 if (this.isHttp && "begin" in args && "end" in args) { 20224 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); 20225 pendingRequest.validateStatus = status => status === PARTIAL_CONTENT_RESPONSE || status === OK_RESPONSE; 20226 } else { 20227 pendingRequest.validateStatus = status => status === OK_RESPONSE; 20228 } 20229 xhr.responseType = "arraybuffer"; 20230 assert(args.onError, "Expected `onError` callback to be provided."); 20231 xhr.onerror = () => args.onError(xhr.status); 20232 xhr.onreadystatechange = this.#onStateChange.bind(this, xhr); 20233 xhr.onprogress = this.#onProgress.bind(this, xhr); 20234 xhr.send(null); 20235 return xhr; 20236 } 20237 #onProgress(xhr, evt) { 20238 const pendingRequest = this.#pendingRequests.get(xhr); 20239 pendingRequest?.onProgress?.(evt); 20240 } 20241 #onStateChange(xhr, evt) { 20242 const pendingRequest = this.#pendingRequests.get(xhr); 20243 if (!pendingRequest) { 20244 return; 20245 } 20246 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { 20247 pendingRequest.onHeadersReceived(); 20248 delete pendingRequest.onHeadersReceived; 20249 } 20250 if (xhr.readyState !== 4) { 20251 return; 20252 } 20253 if (!this.#pendingRequests.has(xhr)) { 20254 return; 20255 } 20256 this.#pendingRequests.delete(xhr); 20257 if (xhr.status === 0 && this.isHttp) { 20258 pendingRequest.onError(xhr.status); 20259 return; 20260 } 20261 const xhrStatus = xhr.status || OK_RESPONSE; 20262 if (!pendingRequest.validateStatus(xhrStatus)) { 20263 pendingRequest.onError(xhr.status); 20264 return; 20265 } 20266 const chunk = network_getArrayBuffer(xhr.response); 20267 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { 20268 const rangeHeader = xhr.getResponseHeader("Content-Range"); 20269 if (/bytes (\d+)-(\d+)\/(\d+)/.test(rangeHeader)) { 20270 pendingRequest.onDone(chunk); 20271 } else { 20272 warn(`Missing or invalid "Content-Range" header.`); 20273 pendingRequest.onError(0); 20274 } 20275 } else if (chunk) { 20276 pendingRequest.onDone(chunk); 20277 } else { 20278 pendingRequest.onError(xhr.status); 20279 } 20280 } 20281 _abortRequest(xhr) { 20282 if (this.#pendingRequests.has(xhr)) { 20283 this.#pendingRequests.delete(xhr); 20284 xhr.abort(); 20285 } 20286 } 20287 getRangeReader(begin, end) { 20288 const reader = super.getRangeReader(begin, end); 20289 if (reader) { 20290 reader.onClosed = () => this._rangeReaders.delete(reader); 20291 } 20292 return reader; 20293 } 20294} 20295class PDFNetworkStreamReader extends BasePDFStreamReader { 20296 #endRequests = endRequests.bind(this); 20297 _cachedChunks = []; 20298 _done = false;
vendor: 20,530 bytes, lines 20299-21036
20299 _requests = []; 20300 _storedError = null; 20301 constructor(stream) { 20302 super(stream); 20303 const { 20304 length 20305 } = stream._source; 20306 this._contentLength = length; 20307 this._fullRequestXhr = stream._request({ 20308 onHeadersReceived: this.#onHeadersReceived.bind(this), 20309 onDone: this.#onDone.bind(this), 20310 onError: this.#onError.bind(this), 20311 onProgress: this.#onProgress.bind(this) 20312 }); 20313 } 20314 #onHeadersReceived() { 20315 const stream = this._stream; 20316 const { 20317 disableRange, 20318 rangeChunkSize 20319 } = stream._source; 20320 const fullRequestXhr = this._fullRequestXhr; 20321 stream._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL); 20322 const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders(); 20323 const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map(x => { 20324 const [key, ...val] = x.split(": "); 20325 return [key, val.join(": ")]; 20326 }) : []); 20327 const { 20328 allowRangeRequests, 20329 suggestedLength 20330 } = validateRangeRequestCapabilities({ 20331 responseHeaders, 20332 isHttp: stream.isHttp, 20333 rangeChunkSize, 20334 disableRange 20335 }); 20336 if (allowRangeRequests) { 20337 this._isRangeSupported = true; 20338 } 20339 this._contentLength = suggestedLength || this._contentLength; 20340 this._filename = extractFilenameFromHeader(responseHeaders); 20341 if (this._isRangeSupported) { 20342 stream._abortRequest(fullRequestXhr); 20343 } 20344 this._headersCapability.resolve(); 20345 } 20346 #onDone(chunk) { 20347 if (this._requests.length > 0) { 20348 const capability = this._requests.shift(); 20349 capability.resolve({ 20350 value: chunk, 20351 done: false 20352 }); 20353 } else { 20354 this._cachedChunks.push(chunk); 20355 } 20356 this._done = true; 20357 if (this._cachedChunks.length === 0) { 20358 this.#endRequests(); 20359 } 20360 } 20361 #onError(status) { 20362 this._storedError = createResponseError(status, this._stream.url); 20363 this._headersCapability.reject(this._storedError); 20364 for (const capability of this._requests) { 20365 capability.reject(this._storedError); 20366 } 20367 this._requests.length = 0; 20368 this._cachedChunks.length = 0; 20369 } 20370 #onProgress(evt) { 20371 this.onProgress?.({ 20372 loaded: evt.loaded, 20373 total: evt.lengthComputable ? evt.total : this._contentLength 20374 }); 20375 } 20376 async read() { 20377 await this._headersCapability.promise; 20378 if (this._storedError) { 20379 throw this._storedError; 20380 } 20381 if (this._cachedChunks.length > 0) { 20382 const chunk = this._cachedChunks.shift(); 20383 return { 20384 value: chunk, 20385 done: false 20386 }; 20387 } 20388 if (this._done) { 20389 return { 20390 value: undefined, 20391 done: true 20392 }; 20393 } 20394 const capability = Promise.withResolvers(); 20395 this._requests.push(capability); 20396 return capability.promise; 20397 } 20398 cancel(reason) { 20399 this._done = true; 20400 this._headersCapability.reject(reason); 20401 this.#endRequests(); 20402 this._stream._abortRequest(this._fullRequestXhr); 20403 this._fullRequestXhr = null; 20404 } 20405} 20406class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader { 20407 #endRequests = endRequests.bind(this); 20408 onClosed = null; 20409 _done = false; 20410 _queuedChunk = null; 20411 _requests = []; 20412 _storedError = null; 20413 constructor(stream, begin, end) { 20414 super(stream, begin, end); 20415 this._requestXhr = stream._request({ 20416 begin, 20417 end, 20418 onHeadersReceived: this.#onHeadersReceived.bind(this), 20419 onDone: this.#onDone.bind(this), 20420 onError: this.#onError.bind(this), 20421 onProgress: null 20422 }); 20423 } 20424 #onHeadersReceived() { 20425 const responseOrigin = getResponseOrigin(this._requestXhr?.responseURL); 20426 try { 20427 ensureResponseOrigin(responseOrigin, this._stream._responseOrigin); 20428 } catch (ex) { 20429 this._storedError = ex; 20430 this.#onError(0); 20431 } 20432 } 20433 #onDone(chunk) { 20434 if (this._requests.length > 0) { 20435 const capability = this._requests.shift(); 20436 capability.resolve({ 20437 value: chunk, 20438 done: false 20439 }); 20440 } else { 20441 this._queuedChunk = chunk; 20442 } 20443 this._done = true; 20444 this.#endRequests(); 20445 this.onClosed?.(); 20446 } 20447 #onError(status) { 20448 this._storedError ??= createResponseError(status, this._stream.url); 20449 for (const capability of this._requests) { 20450 capability.reject(this._storedError); 20451 } 20452 this._requests.length = 0; 20453 this._queuedChunk = null; 20454 } 20455 async read() { 20456 if (this._storedError) { 20457 throw this._storedError; 20458 } 20459 if (this._queuedChunk !== null) { 20460 const chunk = this._queuedChunk; 20461 this._queuedChunk = null; 20462 return { 20463 value: chunk, 20464 done: false 20465 }; 20466 } 20467 if (this._done) { 20468 return { 20469 value: undefined, 20470 done: true 20471 }; 20472 } 20473 const capability = Promise.withResolvers(); 20474 this._requests.push(capability); 20475 return capability.promise; 20476 } 20477 cancel(reason) { 20478 this._done = true; 20479 this.#endRequests(); 20480 this._stream._abortRequest(this._requestXhr); 20481 this.onClosed?.(); 20482 } 20483} 20484 20485;// ./src/display/node_stream.js 20486 20487 20488 20489 20490 20491function getReadableStream(readStream) { 20492 const { 20493 Readable 20494 } = process.getBuiltinModule("stream"); 20495 if (typeof Readable.toWeb === "function") { 20496 return Readable.toWeb(readStream); 20497 } 20498 const require = process.getBuiltinModule("module").createRequire(import.meta.url); 20499 const polyfill = require("node-readable-to-web-readable-stream"); 20500 return polyfill.makeDefaultReadableStreamFromNodeReadable(readStream); 20501} 20502class PDFNodeStream extends BasePDFStream { 20503 constructor(source) { 20504 super(source, PDFNodeStreamReader, PDFNodeStreamRangeReader); 20505 const { 20506 url 20507 } = source; 20508 assert(url.protocol === "file:", "PDFNodeStream only supports file:// URLs."); 20509 } 20510} 20511class PDFNodeStreamReader extends BasePDFStreamReader { 20512 _reader = null; 20513 constructor(stream) { 20514 super(stream); 20515 const { 20516 disableRange, 20517 disableStream, 20518 length, 20519 rangeChunkSize, 20520 url 20521 } = stream._source; 20522 this._contentLength = length; 20523 this._isStreamingSupported = !disableStream; 20524 this._isRangeSupported = !disableRange; 20525 const fs = process.getBuiltinModule("fs"); 20526 fs.promises.lstat(url).then(stat => { 20527 const readStream = fs.createReadStream(url); 20528 const readableStream = getReadableStream(readStream); 20529 this._reader = readableStream.getReader(); 20530 const { 20531 size 20532 } = stat; 20533 if (size <= 2 * rangeChunkSize) { 20534 this._isRangeSupported = false; 20535 } 20536 this._contentLength = size; 20537 if (!this._isStreamingSupported && this._isRangeSupported) { 20538 this.cancel(new AbortException("Streaming is disabled.")); 20539 } 20540 this._headersCapability.resolve(); 20541 }).catch(error => { 20542 if (error.code === "ENOENT") { 20543 error = createResponseError(0, url); 20544 } 20545 this._headersCapability.reject(error); 20546 }); 20547 } 20548 async read() { 20549 await this._headersCapability.promise; 20550 const { 20551 value, 20552 done 20553 } = await this._reader.read(); 20554 if (done) { 20555 return { 20556 value, 20557 done 20558 }; 20559 } 20560 this._loaded += value.byteLength; 20561 this._callOnProgress(); 20562 return { 20563 value: fetch_stream_getArrayBuffer(value), 20564 done: false 20565 }; 20566 } 20567 cancel(reason) { 20568 this._reader?.cancel(reason); 20569 } 20570} 20571class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader { 20572 _readCapability = Promise.withResolvers(); 20573 _reader = null; 20574 constructor(stream, begin, end) { 20575 super(stream, begin, end); 20576 const { 20577 url 20578 } = stream._source; 20579 const fs = process.getBuiltinModule("fs"); 20580 try { 20581 const readStream = fs.createReadStream(url, { 20582 start: begin, 20583 end: end - 1 20584 }); 20585 const readableStream = getReadableStream(readStream); 20586 this._reader = readableStream.getReader(); 20587 this._readCapability.resolve(); 20588 } catch (error) { 20589 this._readCapability.reject(error); 20590 } 20591 } 20592 async read() { 20593 await this._readCapability.promise; 20594 const { 20595 value, 20596 done 20597 } = await this._reader.read(); 20598 if (done) { 20599 return { 20600 value, 20601 done 20602 }; 20603 } 20604 return { 20605 value: fetch_stream_getArrayBuffer(value), 20606 done: false 20607 }; 20608 } 20609 cancel(reason) { 20610 this._reader?.cancel(reason); 20611 } 20612} 20613 20614;// ./src/display/pdf_objects.js 20615 20616 20617 20618const INITIAL_DATA = Symbol("INITIAL_DATA"); 20619const dataObj = () => ({ 20620 ...Promise.withResolvers(), 20621 data: INITIAL_DATA 20622}); 20623class PDFObjects { 20624 #objs = new Map(); 20625 #ensureObj(objId) { 20626 return this.#objs.getOrInsertComputed(objId, dataObj); 20627 } 20628 get(objId, callback = null) { 20629 if (callback) { 20630 const obj = this.#ensureObj(objId); 20631 obj.promise.then(() => callback(obj.data)); 20632 return null; 20633 } 20634 const obj = this.#objs.get(objId); 20635 if (!obj || obj.data === INITIAL_DATA) { 20636 throw new Error(`Requesting object that isn't resolved yet ${objId}.`); 20637 } 20638 return obj.data; 20639 } 20640 has(objId) { 20641 const obj = this.#objs.get(objId); 20642 return !!obj && obj.data !== INITIAL_DATA; 20643 } 20644 delete(objId) { 20645 const obj = this.#objs.get(objId); 20646 if (!obj || obj.data === INITIAL_DATA) { 20647 return false; 20648 } 20649 this.#objs.delete(objId); 20650 return true; 20651 } 20652 resolve(objId, data = null) { 20653 const obj = this.#ensureObj(objId); 20654 obj.data = data; 20655 obj.resolve(); 20656 } 20657 clear() { 20658 for (const { 20659 data 20660 } of this.#objs.values()) { 20661 data?.bitmap?.close(); 20662 } 20663 this.#objs.clear(); 20664 } 20665 *[Symbol.iterator]() { 20666 for (const [objId, { 20667 data 20668 }] of this.#objs) { 20669 if (data !== INITIAL_DATA) { 20670 yield [objId, data]; 20671 } 20672 } 20673 } 20674} 20675 20676;// ./src/display/text_layer.js 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692const MAX_TEXT_DIVS_TO_RENDER = 100000; 20693const DEFAULT_FONT_SIZE = 30; 20694class TextLayer { 20695 #capability = Promise.withResolvers(); 20696 #container = null; 20697 #disableProcessItems = false; 20698 #fontInspectorEnabled = !!globalThis.FontInspector?.enabled; 20699 #lang = null; 20700 #layoutTextParams = null; 20701 #pageHeight = 0; 20702 #pageWidth = 0; 20703 #reader = null; 20704 #rootContainer = null; 20705 #rotation = 0; 20706 #scale = 0; 20707 #styleCache = Object.create(null); 20708 #textContentItemsStr = []; 20709 #textContentSource = null; 20710 #textDivs = []; 20711 #textDivProperties = new WeakMap(); 20712 #transform = null; 20713 static #ascentCache = new Map(); 20714 static #canvasContexts = new Map(); 20715 static #canvasCtxFonts = new WeakMap(); 20716 static #minFontSize = null; 20717 static #pendingTextLayers = new Set(); 20718 constructor({ 20719 textContentSource, 20720 container, 20721 viewport 20722 }) { 20723 if (textContentSource instanceof ReadableStream) { 20724 this.#textContentSource = textContentSource; 20725 } else if (typeof textContentSource === "object") { 20726 this.#textContentSource = new ReadableStream({ 20727 start(controller) { 20728 controller.enqueue(textContentSource); 20729 controller.close(); 20730 } 20731 }); 20732 } else { 20733 throw new Error('No "textContentSource" parameter specified.'); 20734 } 20735 this.#container = this.#rootContainer = container; 20736 this.#scale = viewport.scale * OutputScale.pixelRatio; 20737 this.#rotation = viewport.rotation; 20738 this.#layoutTextParams = { 20739 div: null, 20740 properties: null, 20741 ctx: null 20742 }; 20743 const { 20744 pageWidth, 20745 pageHeight, 20746 pageX, 20747 pageY 20748 } = viewport.rawDims; 20749 this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; 20750 this.#pageWidth = pageWidth; 20751 this.#pageHeight = pageHeight; 20752 TextLayer.#ensureMinFontSizeComputed(); 20753 container.style.setProperty("--min-font-size", TextLayer.#minFontSize); 20754 setLayerDimensions(container, viewport); 20755 this.#capability.promise.finally(() => { 20756 TextLayer.#pendingTextLayers.delete(this); 20757 this.#layoutTextParams = null; 20758 this.#styleCache = null; 20759 }).catch(() => {}); 20760 } 20761 static get fontFamilyMap() { 20762 const { 20763 isWindows, 20764 isFirefox 20765 } = FeatureTest.platform; 20766 return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]])); 20767 } 20768 render() { 20769 const pump = () => { 20770 this.#reader.read().then(({ 20771 value, 20772 done 20773 }) => { 20774 if (done) { 20775 this.#capability.resolve(); 20776 return; 20777 } 20778 this.#lang ??= value.lang; 20779 Object.assign(this.#styleCache, value.styles); 20780 this.#processItems(value.items); 20781 pump(); 20782 }, this.#capability.reject); 20783 }; 20784 this.#reader = this.#textContentSource.getReader(); 20785 TextLayer.#pendingTextLayers.add(this); 20786 pump(); 20787 return this.#capability.promise; 20788 } 20789 update({ 20790 viewport, 20791 onBefore = null 20792 }) { 20793 const scale = viewport.scale * OutputScale.pixelRatio; 20794 const rotation = viewport.rotation; 20795 if (rotation !== this.#rotation) { 20796 onBefore?.(); 20797 this.#rotation = rotation; 20798 setLayerDimensions(this.#rootContainer, { 20799 rotation 20800 }); 20801 } 20802 if (scale !== this.#scale) { 20803 onBefore?.(); 20804 this.#scale = scale; 20805 const params = { 20806 div: null, 20807 properties: null, 20808 ctx: TextLayer.#getCtx(this.#lang) 20809 }; 20810 for (const div of this.#textDivs) { 20811 params.properties = this.#textDivProperties.get(div); 20812 params.div = div; 20813 this.#layout(params); 20814 } 20815 } 20816 } 20817 cancel() { 20818 const abortEx = new AbortException("TextLayer task cancelled."); 20819 this.#reader?.cancel(abortEx).catch(() => {}); 20820 this.#reader = null; 20821 this.#capability.reject(abortEx); 20822 } 20823 get textDivs() { 20824 return this.#textDivs; 20825 } 20826 get textContentItemsStr() { 20827 return this.#textContentItemsStr; 20828 } 20829 #processItems(items) { 20830 if (this.#disableProcessItems) { 20831 return; 20832 } 20833 this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang); 20834 const textDivs = this.#textDivs, 20835 textContentItemsStr = this.#textContentItemsStr; 20836 for (const item of items) { 20837 if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) { 20838 warn("Ignoring additional textDivs for performance reasons."); 20839 this.#disableProcessItems = true; 20840 return; 20841 } 20842 if (item.str === undefined) { 20843 if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { 20844 const parent = this.#container; 20845 this.#container = document.createElement("span"); 20846 this.#container.classList.add("markedContent"); 20847 if (item.id) { 20848 this.#container.setAttribute("id", `${item.id}`); 20849 } 20850 if (item.tag === "Artifact") { 20851 this.#container.ariaHidden = true; 20852 } 20853 parent.append(this.#container); 20854 } else if (item.type === "endMarkedContent") { 20855 this.#container = this.#container.parentNode; 20856 } 20857 continue; 20858 } 20859 textContentItemsStr.push(item.str); 20860 this.#appendText(item); 20861 } 20862 } 20863 #appendText(geom) { 20864 const textDiv = document.createElement("span"); 20865 const textDivProperties = { 20866 angle: 0, 20867 canvasWidth: 0, 20868 hasText: geom.str !== "", 20869 hasEOL: geom.hasEOL, 20870 fontSize: 0 20871 }; 20872 this.#textDivs.push(textDiv); 20873 const tx = Util.transform(this.#transform, geom.transform); 20874 let angle = Math.atan2(tx[1], tx[0]); 20875 const style = this.#styleCache[geom.fontName]; 20876 if (style.vertical) { 20877 angle += Math.PI / 2; 20878 } 20879 let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; 20880 fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; 20881 const fontHeight = Math.hypot(tx[2], tx[3]); 20882 const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, style, this.#lang); 20883 let left, top; 20884 if (angle === 0) { 20885 left = tx[4]; 20886 top = tx[5] - fontAscent; 20887 } else { 20888 left = tx[4] + fontAscent * Math.sin(angle); 20889 top = tx[5] - fontAscent * Math.cos(angle); 20890 } 20891 const divStyle = textDiv.style; 20892 divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`; 20893 divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`; 20894 divStyle.setProperty("--font-height", `${fontHeight.toFixed(2)}px`); 20895 divStyle.fontFamily = fontFamily; 20896 textDivProperties.fontSize = fontHeight; 20897 textDiv.setAttribute("role", "presentation"); 20898 textDiv.textContent = geom.str; 20899 textDiv.dir = geom.dir; 20900 if (this.#fontInspectorEnabled) { 20901 textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName; 20902 } 20903 if (angle !== 0) { 20904 textDivProperties.angle = angle * (180 / Math.PI); 20905 } 20906 let shouldScaleText = false; 20907 if (geom.str.length > 1) { 20908 shouldScaleText = true; 20909 } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { 20910 const absScaleX = Math.abs(geom.transform[0]), 20911 absScaleY = Math.abs(geom.transform[3]); 20912 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { 20913 shouldScaleText = true; 20914 } 20915 } 20916 if (shouldScaleText) { 20917 textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; 20918 } 20919 this.#textDivProperties.set(textDiv, textDivProperties); 20920 this.#layoutTextParams.div = textDiv; 20921 this.#layoutTextParams.properties = textDivProperties; 20922 this.#layout(this.#layoutTextParams); 20923 if (textDivProperties.hasText) { 20924 this.#container.append(textDiv); 20925 } 20926 if (textDivProperties.hasEOL) { 20927 const br = document.createElement("br"); 20928 br.setAttribute("role", "presentation"); 20929 this.#container.append(br); 20930 } 20931 } 20932 #layout(params) { 20933 const { 20934 div, 20935 properties, 20936 ctx 20937 } = params; 20938 const { 20939 style 20940 } = div; 20941 if (properties.canvasWidth !== 0 && properties.hasText) { 20942 const { 20943 fontFamily 20944 } = style; 20945 const { 20946 canvasWidth, 20947 fontSize 20948 } = properties; 20949 TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily); 20950 const { 20951 width 20952 } = ctx.measureText(div.textContent); 20953 if (width > 0) { 20954 style.setProperty("--scale-x", canvasWidth * this.#scale / width); 20955 } 20956 } 20957 if (properties.angle !== 0) { 20958 style.setProperty("--rotate", `${properties.angle}deg`); 20959 } 20960 } 20961 static cleanup() { 20962 if (this.#pendingTextLayers.size > 0) { 20963 return; 20964 } 20965 this.#ascentCache.clear(); 20966 for (const { 20967 canvas 20968 } of this.#canvasContexts.values()) { 20969 canvas.remove(); 20970 } 20971 this.#canvasContexts.clear(); 20972 } 20973 static #getCtx(lang = null) { 20974 let ctx = this.#canvasContexts.get(lang ||= ""); 20975 if (!ctx) { 20976 const canvas = document.createElement("canvas"); 20977 canvas.className = "hiddenCanvasElement"; 20978 canvas.lang = lang; 20979 document.body.append(canvas); 20980 ctx = canvas.getContext("2d", { 20981 alpha: false, 20982 willReadFrequently: true 20983 }); 20984 this.#canvasContexts.set(lang, ctx); 20985 this.#canvasCtxFonts.set(ctx, { 20986 size: 0, 20987 family: "" 20988 }); 20989 } 20990 return ctx; 20991 } 20992 static #ensureCtxFont(ctx, size, family) { 20993 const cached = this.#canvasCtxFonts.get(ctx); 20994 if (size === cached.size && family === cached.family) { 20995 return; 20996 } 20997 ctx.font = `${size}px ${family}`; 20998 cached.size = size; 20999 cached.family = family; 21000 } 21001 static #ensureMinFontSizeComputed() { 21002 if (this.#minFontSize !== null) { 21003 return; 21004 } 21005 const div = document.createElement("div"); 21006 div.style.opacity = 0; 21007 div.style.lineHeight = 1; 21008 div.style.fontSize = "1px"; 21009 div.style.position = "absolute"; 21010 div.textContent = "X"; 21011 document.body.append(div); 21012 this.#minFontSize = div.getBoundingClientRect().height; 21013 div.remove(); 21014 } 21015 static #getAscent(fontFamily, style, lang) { 21016 const cachedAscent = this.#ascentCache.get(fontFamily); 21017 if (cachedAscent) { 21018 return cachedAscent; 21019 } 21020 const ctx = this.#getCtx(lang); 21021 ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; 21022 this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily); 21023 const metrics = ctx.measureText(""); 21024 const ascent = metrics.fontBoundingBoxAscent; 21025 const descent = Math.abs(metrics.fontBoundingBoxDescent); 21026 ctx.canvas.width = ctx.canvas.height = 0; 21027 let ratio = 0.8; 21028 if (ascent) { 21029 ratio = ascent / (ascent + descent); 21030 } else { 21031 if (FeatureTest.platform.isFirefox) { 21032 warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference " + "in `about:config` to improve TextLayer rendering."); 21033 } 21034 if (style.ascent) { 21035 ratio = style.ascent; 21036 }
vendor: 17,959 bytes, lines 21036-21651
21036 else if (style.descent) { 21037 ratio = 1 + style.descent; 21038 } 21039 } 21040 this.#ascentCache.set(fontFamily, ratio); 21041 return ratio; 21042 } 21043} 21044 21045;// ./src/display/api.js 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100const RENDERING_CANCELLED_TIMEOUT = 100; 21101function getDocument(src = {}) { 21102 if (typeof src === "string" || src instanceof URL) { 21103 src = { 21104 url: src 21105 }; 21106 } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) { 21107 src = { 21108 data: src 21109 }; 21110 } 21111 const task = new PDFDocumentLoadingTask(); 21112 const { 21113 docId 21114 } = task; 21115 const url = src.url ? getUrlProp(src.url) : null; 21116 const data = src.data ? getDataProp(src.data) : null; 21117 const httpHeaders = src.httpHeaders || null; 21118 const withCredentials = src.withCredentials === true; 21119 const password = src.password ?? null; 21120 const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; 21121 const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16; 21122 let worker = src.worker instanceof PDFWorker ? src.worker : null; 21123 const verbosity = src.verbosity; 21124 const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null; 21125 const cMapUrl = getFactoryUrlProp(src.cMapUrl); 21126 const cMapPacked = src.cMapPacked !== false; 21127 const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory); 21128 const iccUrl = getFactoryUrlProp(src.iccUrl); 21129 const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl); 21130 const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory); 21131 const wasmUrl = getFactoryUrlProp(src.wasmUrl); 21132 const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory); 21133 const ignoreErrors = src.stopAtErrors !== true; 21134 const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; 21135 const isEvalSupported = src.isEvalSupported !== false; 21136 const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS; 21137 const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (FeatureTest.platform.isFirefox || !globalThis.chrome); 21138 const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; 21139 const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS; 21140 const fontExtraProperties = src.fontExtraProperties === true; 21141 const enableXfa = src.enableXfa === true; 21142 const ownerDocument = src.ownerDocument || globalThis.document; 21143 const disableRange = src.disableRange === true; 21144 const disableStream = src.disableStream === true; 21145 const disableAutoFetch = src.disableAutoFetch === true; 21146 const pdfBug = src.pdfBug === true; 21147 const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory); 21148 const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory); 21149 const enableHWA = src.enableHWA === true; 21150 const useWasm = src.useWasm !== false; 21151 const pagesMapper = src.pagesMapper || new PagesMapper(); 21152 const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; 21153 const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace; 21154 const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI)); 21155 const styleElement = null; 21156 setVerbosityLevel(verbosity); 21157 const transportFactory = { 21158 canvasFactory: new CanvasFactory({ 21159 ownerDocument, 21160 enableHWA 21161 }), 21162 filterFactory: new FilterFactory({ 21163 docId, 21164 ownerDocument 21165 }), 21166 cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({ 21167 baseUrl: cMapUrl, 21168 isCompressed: cMapPacked 21169 }), 21170 standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({ 21171 baseUrl: standardFontDataUrl 21172 }), 21173 wasmFactory: useWorkerFetch ? null : new WasmFactory({ 21174 baseUrl: wasmUrl 21175 }) 21176 }; 21177 if (!worker) { 21178 worker = PDFWorker.create({ 21179 verbosity, 21180 port: GlobalWorkerOptions.workerPort 21181 }); 21182 task._worker = worker; 21183 } 21184 const docParams = { 21185 docId, 21186 apiVersion: "5.5.207", 21187 data, 21188 password, 21189 disableAutoFetch, 21190 rangeChunkSize, 21191 length, 21192 docBaseUrl, 21193 enableXfa, 21194 evaluatorOptions: { 21195 maxImageSize, 21196 disableFontFace, 21197 ignoreErrors, 21198 isEvalSupported, 21199 isOffscreenCanvasSupported, 21200 isImageDecoderSupported, 21201 canvasMaxAreaInBytes, 21202 fontExtraProperties, 21203 useSystemFonts, 21204 useWasm, 21205 useWorkerFetch, 21206 cMapUrl, 21207 iccUrl, 21208 standardFontDataUrl, 21209 wasmUrl 21210 } 21211 }; 21212 const transportParams = { 21213 ownerDocument, 21214 pdfBug, 21215 styleElement, 21216 enableHWA, 21217 loadingParams: { 21218 disableAutoFetch, 21219 enableXfa 21220 } 21221 }; 21222 worker.promise.then(function () { 21223 if (task.destroyed) { 21224 throw new Error("Loading aborted"); 21225 } 21226 if (worker.destroyed) { 21227 throw new Error("Worker was destroyed"); 21228 } 21229 const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null); 21230 let networkStream; 21231 if (rangeTransport) { 21232 networkStream = new PDFDataTransportStream({ 21233 pdfDataRangeTransport: rangeTransport, 21234 disableRange, 21235 disableStream 21236 }); 21237 } else if (!data) { 21238 if (!url) { 21239 throw new Error("getDocument - no `url` parameter provided."); 21240 } 21241 const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream; 21242 networkStream = new NetworkStream({ 21243 url, 21244 length, 21245 httpHeaders, 21246 withCredentials, 21247 rangeChunkSize, 21248 disableRange, 21249 disableStream 21250 }); 21251 } 21252 return workerIdPromise.then(workerId => { 21253 if (task.destroyed) { 21254 throw new Error("Loading aborted"); 21255 } 21256 if (worker.destroyed) { 21257 throw new Error("Worker was destroyed"); 21258 } 21259 const messageHandler = new MessageHandler(docId, workerId, worker.port); 21260 const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, pagesMapper); 21261 task._transport = transport; 21262 messageHandler.send("Ready", null); 21263 }); 21264 }).catch(task._capability.reject); 21265 return task; 21266} 21267class PDFDocumentLoadingTask { 21268 static #docId = 0; 21269 _capability = Promise.withResolvers(); 21270 _transport = null; 21271 _worker = null; 21272 docId = `d${PDFDocumentLoadingTask.#docId++}`; 21273 destroyed = false; 21274 onPassword = null; 21275 onProgress = null; 21276 get promise() { 21277 return this._capability.promise; 21278 } 21279 async destroy() { 21280 this.destroyed = true; 21281 try { 21282 if (this._worker?.port) { 21283 this._worker._pendingDestroy = true; 21284 } 21285 await this._transport?.destroy(); 21286 } catch (ex) { 21287 if (this._worker?.port) { 21288 delete this._worker._pendingDestroy; 21289 } 21290 throw ex; 21291 } 21292 this._transport = null; 21293 this._worker?.destroy(); 21294 this._worker = null; 21295 } 21296 async getData() { 21297 return this._transport.getData(); 21298 } 21299} 21300class PDFDataRangeTransport { 21301 #capability = Promise.withResolvers(); 21302 #progressiveDoneListeners = []; 21303 #progressiveReadListeners = []; 21304 #rangeListeners = []; 21305 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { 21306 this.length = length; 21307 this.initialData = initialData; 21308 this.progressiveDone = progressiveDone; 21309 this.contentDispositionFilename = contentDispositionFilename; 21310 Object.defineProperty(this, "onDataProgress", { 21311 value: () => { 21312 deprecated("`PDFDataRangeTransport.prototype.onDataProgress` - method was " + "removed, since loading progress is now reported automatically " + "through the `PDFDataTransportStream` class (and related code)."); 21313 } 21314 }); 21315 } 21316 addRangeListener(listener) { 21317 this.#rangeListeners.push(listener); 21318 } 21319 addProgressiveReadListener(listener) { 21320 this.#progressiveReadListeners.push(listener); 21321 } 21322 addProgressiveDoneListener(listener) { 21323 this.#progressiveDoneListeners.push(listener); 21324 } 21325 onDataRange(begin, chunk) { 21326 for (const listener of this.#rangeListeners) { 21327 listener(begin, chunk); 21328 } 21329 } 21330 onDataProgressiveRead(chunk) { 21331 this.#capability.promise.then(() => { 21332 for (const listener of this.#progressiveReadListeners) { 21333 listener(chunk); 21334 } 21335 }); 21336 } 21337 onDataProgressiveDone() { 21338 this.#capability.promise.then(() => { 21339 for (const listener of this.#progressiveDoneListeners) { 21340 listener(); 21341 } 21342 }); 21343 } 21344 transportReady() { 21345 this.#capability.resolve(); 21346 } 21347 requestDataRange(begin, end) { 21348 unreachable("Abstract method PDFDataRangeTransport.requestDataRange"); 21349 } 21350 abort() {} 21351} 21352class PDFDocumentProxy { 21353 constructor(pdfInfo, transport) { 21354 this._pdfInfo = pdfInfo; 21355 this._transport = transport; 21356 } 21357 get pagesMapper() { 21358 return this._transport.pagesMapper; 21359 } 21360 get annotationStorage() { 21361 return this._transport.annotationStorage; 21362 } 21363 get canvasFactory() { 21364 return this._transport.canvasFactory; 21365 } 21366 get filterFactory() { 21367 return this._transport.filterFactory; 21368 } 21369 get numPages() { 21370 return this._pdfInfo.numPages; 21371 } 21372 get fingerprints() { 21373 return this._pdfInfo.fingerprints; 21374 } 21375 get isPureXfa() { 21376 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); 21377 } 21378 get allXfaHtml() { 21379 return this._transport._htmlForXfa; 21380 } 21381 getPage(pageNumber) { 21382 return this._transport.getPage(pageNumber); 21383 } 21384 getPageIndex(ref) { 21385 return this._transport.getPageIndex(ref); 21386 } 21387 getDestinations() { 21388 return this._transport.getDestinations(); 21389 } 21390 getDestination(id) { 21391 return this._transport.getDestination(id); 21392 } 21393 getPageLabels() { 21394 return this._transport.getPageLabels(); 21395 } 21396 getPageLayout() { 21397 return this._transport.getPageLayout(); 21398 } 21399 getPageMode() { 21400 return this._transport.getPageMode(); 21401 } 21402 getViewerPreferences() { 21403 return this._transport.getViewerPreferences(); 21404 } 21405 getOpenAction() { 21406 return this._transport.getOpenAction(); 21407 } 21408 getAttachments() { 21409 return this._transport.getAttachments(); 21410 } 21411 getAnnotationsByType(types, pageIndexesToSkip) { 21412 return this._transport.getAnnotationsByType(types, pageIndexesToSkip); 21413 } 21414 getJSActions() { 21415 return this._transport.getDocJSActions(); 21416 } 21417 getOutline() { 21418 return this._transport.getOutline(); 21419 } 21420 getOptionalContentConfig({ 21421 intent = "display" 21422 } = {}) { 21423 const { 21424 renderingIntent 21425 } = this._transport.getRenderingIntent(intent); 21426 return this._transport.getOptionalContentConfig(renderingIntent); 21427 } 21428 getPermissions() { 21429 return this._transport.getPermissions(); 21430 } 21431 getMetadata() { 21432 return this._transport.getMetadata(); 21433 } 21434 getMarkInfo() { 21435 return this._transport.getMarkInfo(); 21436 } 21437 getData() { 21438 return this._transport.getData(); 21439 } 21440 saveDocument() { 21441 return this._transport.saveDocument(); 21442 } 21443 extractPages(pageInfos) { 21444 return this._transport.extractPages(pageInfos); 21445 } 21446 getDownloadInfo() { 21447 return this._transport.downloadInfoCapability.promise; 21448 } 21449 cleanup(keepLoadedFonts = false) { 21450 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); 21451 } 21452 destroy() { 21453 return this.loadingTask.destroy(); 21454 } 21455 cachedPageNumber(ref) { 21456 return this._transport.cachedPageNumber(ref); 21457 } 21458 get loadingParams() { 21459 return this._transport.loadingParams; 21460 } 21461 get loadingTask() { 21462 return this._transport.loadingTask; 21463 } 21464 getFieldObjects() { 21465 return this._transport.getFieldObjects(); 21466 } 21467 hasJSActions() { 21468 return this._transport.hasJSActions(); 21469 } 21470 getCalculationOrderIds() { 21471 return this._transport.getCalculationOrderIds(); 21472 } 21473} 21474class PDFPageProxy { 21475 #pendingCleanup = false; 21476 #pagesMapper = null; 21477 constructor(pageIndex, pageInfo, transport, pagesMapper, pdfBug = false) { 21478 this._pageIndex = pageIndex; 21479 this._pageInfo = pageInfo; 21480 this._transport = transport; 21481 this._stats = pdfBug ? new StatTimer() : null; 21482 this._pdfBug = pdfBug; 21483 this.commonObjs = transport.commonObjs; 21484 this.objs = new PDFObjects(); 21485 this._intentStates = new Map(); 21486 this.destroyed = false; 21487 this.recordedBBoxes = null; 21488 this.#pagesMapper = pagesMapper; 21489 } 21490 get pageNumber() { 21491 return this._pageIndex + 1; 21492 } 21493 set pageNumber(value) { 21494 this._pageIndex = value - 1; 21495 } 21496 get rotate() { 21497 return this._pageInfo.rotate; 21498 } 21499 get ref() { 21500 return this._pageInfo.ref; 21501 } 21502 get userUnit() { 21503 return this._pageInfo.userUnit; 21504 } 21505 get view() { 21506 return this._pageInfo.view; 21507 } 21508 getViewport({ 21509 scale, 21510 rotation = this.rotate, 21511 offsetX = 0, 21512 offsetY = 0, 21513 dontFlip = false 21514 } = {}) { 21515 return new PageViewport({ 21516 viewBox: this.view, 21517 userUnit: this.userUnit, 21518 scale, 21519 rotation, 21520 offsetX, 21521 offsetY, 21522 dontFlip 21523 }); 21524 } 21525 getAnnotations({ 21526 intent = "display" 21527 } = {}) { 21528 const { 21529 renderingIntent 21530 } = this._transport.getRenderingIntent(intent); 21531 return this._transport.getAnnotations(this._pageIndex, renderingIntent); 21532 } 21533 getJSActions() { 21534 return this._transport.getPageJSActions(this._pageIndex); 21535 } 21536 get filterFactory() { 21537 return this._transport.filterFactory; 21538 } 21539 get isPureXfa() { 21540 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); 21541 } 21542 async getXfa() { 21543 return this._transport._htmlForXfa?.children[this._pageIndex] || null; 21544 } 21545 render({ 21546 canvasContext, 21547 canvas = canvasContext.canvas, 21548 viewport, 21549 intent = "display", 21550 annotationMode = AnnotationMode.ENABLE, 21551 transform = null, 21552 background = null, 21553 optionalContentConfigPromise = null, 21554 annotationCanvasMap = null, 21555 pageColors = null, 21556 printAnnotationStorage = null, 21557 isEditing = false, 21558 recordOperations = false, 21559 operationsFilter = null 21560 }) { 21561 this._stats?.time("Overall"); 21562 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); 21563 const { 21564 renderingIntent, 21565 cacheKey 21566 } = intentArgs; 21567 this.#pendingCleanup = false; 21568 optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent); 21569 const intentState = this._intentStates.getOrInsertComputed(cacheKey, makeObj); 21570 if (intentState.streamReaderCancelTimeout) { 21571 clearTimeout(intentState.streamReaderCancelTimeout); 21572 intentState.streamReaderCancelTimeout = null; 21573 } 21574 const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); 21575 if (!intentState.displayReadyCapability) { 21576 intentState.displayReadyCapability = Promise.withResolvers(); 21577 intentState.operatorList = { 21578 fnArray: [], 21579 argsArray: [], 21580 lastChunk: false, 21581 separateAnnots: null 21582 }; 21583 this._stats?.time("Page Request"); 21584 this._pumpOperatorList(intentArgs); 21585 } 21586 const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled); 21587 const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger); 21588 const complete = error => { 21589 intentState.renderTasks.delete(internalRenderTask); 21590 if (shouldRecordOperations) { 21591 const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take(); 21592 if (recordedBBoxes) { 21593 if (internalRenderTask.stepper) { 21594 internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata()); 21595 } 21596 if (recordOperations) { 21597 this.recordedBBoxes = recordedBBoxes; 21598 } 21599 } 21600 } 21601 if (intentPrint) { 21602 this.#pendingCleanup = true; 21603 } 21604 this.#tryCleanup(); 21605 if (error) { 21606 internalRenderTask.capability.reject(error); 21607 this._abortOperatorList({ 21608 intentState, 21609 reason: error instanceof Error ? error : new Error(error) 21610 }); 21611 } else { 21612 internalRenderTask.capability.resolve(); 21613 } 21614 if (this._stats) { 21615 this._stats.timeEnd("Rendering"); 21616 this._stats.timeEnd("Overall"); 21617 if (globalThis.Stats?.enabled) { 21618 globalThis.Stats.add(this.pageNumber, this._stats); 21619 } 21620 } 21621 }; 21622 const internalRenderTask = new InternalRenderTask({ 21623 callback: complete, 21624 params: { 21625 canvas, 21626 canvasContext, 21627 dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null, 21628 viewport, 21629 transform, 21630 background 21631 }, 21632 objs: this.objs, 21633 commonObjs: this.commonObjs, 21634 annotationCanvasMap, 21635 operatorList: intentState.operatorList, 21636 pageIndex: this._pageIndex, 21637 canvasFactory: this._transport.canvasFactory, 21638 filterFactory: this._transport.filterFactory, 21639 useRequestAnimationFrame: !intentPrint, 21640 pdfBug: this._pdfBug, 21641 pageColors, 21642 enableHWA: this._transport.enableHWA, 21643 operationsFilter 21644 }); 21645 (intentState.renderTasks ||= new Set()).add(internalRenderTask); 21646 const renderTask = internalRenderTask.task; 21647 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { 21648 if (this.destroyed) { 21649 complete(); 21650 return; 21651 }
vendor: 9,048 bytes, lines 21652-21939
21652 this._stats?.time("Rendering"); 21653 if (!(optionalContentConfig.renderingIntent & renderingIntent)) { 21654 throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods."); 21655 } 21656 internalRenderTask.initializeGraphics({ 21657 transparency, 21658 optionalContentConfig 21659 }); 21660 internalRenderTask.operatorListChanged(); 21661 }).catch(complete); 21662 return renderTask; 21663 } 21664 getOperatorList({ 21665 intent = "display", 21666 annotationMode = AnnotationMode.ENABLE, 21667 printAnnotationStorage = null, 21668 isEditing = false 21669 } = {}) { 21670 function operatorListChanged() { 21671 if (intentState.operatorList.lastChunk) { 21672 intentState.opListReadCapability.resolve(intentState.operatorList); 21673 intentState.renderTasks.delete(opListTask); 21674 } 21675 } 21676 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true); 21677 const intentState = this._intentStates.getOrInsertComputed(intentArgs.cacheKey, makeObj); 21678 let opListTask; 21679 if (!intentState.opListReadCapability) { 21680 opListTask = Object.create(null); 21681 opListTask.operatorListChanged = operatorListChanged; 21682 intentState.opListReadCapability = Promise.withResolvers(); 21683 (intentState.renderTasks ||= new Set()).add(opListTask); 21684 intentState.operatorList = { 21685 fnArray: [], 21686 argsArray: [], 21687 lastChunk: false, 21688 separateAnnots: null 21689 }; 21690 this._stats?.time("Page Request"); 21691 this._pumpOperatorList(intentArgs); 21692 } 21693 return intentState.opListReadCapability.promise; 21694 } 21695 streamTextContent({ 21696 includeMarkedContent = false, 21697 disableNormalization = false 21698 } = {}) { 21699 const TEXT_CONTENT_CHUNK_SIZE = 100; 21700 return this._transport.messageHandler.sendWithStream("GetTextContent", { 21701 pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1, 21702 pageIndex: this._pageIndex, 21703 includeMarkedContent: includeMarkedContent === true, 21704 disableNormalization: disableNormalization === true 21705 }, { 21706 highWaterMark: TEXT_CONTENT_CHUNK_SIZE, 21707 size(textContent) { 21708 return textContent.items.length; 21709 } 21710 }); 21711 } 21712 async getTextContent(params = {}) { 21713 if (this._transport._htmlForXfa) { 21714 return this.getXfa().then(xfa => XfaText.textContent(xfa)); 21715 } 21716 const readableStream = this.streamTextContent(params); 21717 const textContent = { 21718 items: [], 21719 styles: Object.create(null), 21720 lang: null 21721 }; 21722 for await (const value of readableStream) { 21723 textContent.lang ??= value.lang; 21724 Object.assign(textContent.styles, value.styles); 21725 textContent.items.push(...value.items); 21726 } 21727 return textContent; 21728 } 21729 getStructTree() { 21730 return this._transport.getStructTree(this._pageIndex); 21731 } 21732 _destroy() { 21733 this.destroyed = true; 21734 const waitOn = []; 21735 for (const intentState of this._intentStates.values()) { 21736 this._abortOperatorList({ 21737 intentState, 21738 reason: new Error("Page was destroyed."), 21739 force: true 21740 }); 21741 if (intentState.opListReadCapability) { 21742 continue; 21743 } 21744 for (const internalRenderTask of intentState.renderTasks) { 21745 waitOn.push(internalRenderTask.completed); 21746 internalRenderTask.cancel(); 21747 } 21748 } 21749 this.objs.clear(); 21750 this.#pendingCleanup = false; 21751 return Promise.all(waitOn); 21752 } 21753 cleanup(resetStats = false) { 21754 this.#pendingCleanup = true; 21755 const success = this.#tryCleanup(); 21756 if (resetStats && success) { 21757 this._stats &&= new StatTimer(); 21758 } 21759 return success; 21760 } 21761 #tryCleanup() { 21762 if (!this.#pendingCleanup || this.destroyed) { 21763 return false; 21764 } 21765 for (const { 21766 renderTasks, 21767 operatorList 21768 } of this._intentStates.values()) { 21769 if (renderTasks.size > 0 || !operatorList.lastChunk) { 21770 return false; 21771 } 21772 } 21773 this._intentStates.clear(); 21774 this.objs.clear(); 21775 this.#pendingCleanup = false; 21776 return true; 21777 } 21778 _startRenderPage(transparency, cacheKey) { 21779 const intentState = this._intentStates.get(cacheKey); 21780 if (!intentState) { 21781 return; 21782 } 21783 this._stats?.timeEnd("Page Request"); 21784 intentState.displayReadyCapability?.resolve(transparency); 21785 } 21786 _renderPageChunk(operatorListChunk, intentState) { 21787 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { 21788 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); 21789 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); 21790 } 21791 intentState.operatorList.lastChunk = operatorListChunk.lastChunk; 21792 intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; 21793 for (const internalRenderTask of intentState.renderTasks) { 21794 internalRenderTask.operatorListChanged(); 21795 } 21796 if (operatorListChunk.lastChunk) { 21797 this.#tryCleanup(); 21798 } 21799 } 21800 _pumpOperatorList({ 21801 renderingIntent, 21802 cacheKey, 21803 annotationStorageSerializable, 21804 modifiedIds 21805 }) { 21806 const { 21807 map, 21808 transfer 21809 } = annotationStorageSerializable; 21810 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { 21811 pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1, 21812 pageIndex: this._pageIndex, 21813 intent: renderingIntent, 21814 cacheKey, 21815 annotationStorage: map, 21816 modifiedIds 21817 }, undefined, transfer); 21818 const reader = readableStream.getReader(); 21819 const intentState = this._intentStates.get(cacheKey); 21820 intentState.streamReader = reader; 21821 const pump = () => { 21822 reader.read().then(({ 21823 value, 21824 done 21825 }) => { 21826 if (done) { 21827 intentState.streamReader = null; 21828 return; 21829 } 21830 if (this._transport.destroyed) { 21831 return; 21832 } 21833 this._renderPageChunk(value, intentState); 21834 pump(); 21835 }, reason => { 21836 intentState.streamReader = null; 21837 if (this._transport.destroyed) { 21838 return; 21839 } 21840 if (intentState.operatorList) { 21841 intentState.operatorList.lastChunk = true; 21842 for (const internalRenderTask of intentState.renderTasks) { 21843 internalRenderTask.operatorListChanged(); 21844 } 21845 this.#tryCleanup(); 21846 } 21847 if (intentState.displayReadyCapability) { 21848 intentState.displayReadyCapability.reject(reason); 21849 } else if (intentState.opListReadCapability) { 21850 intentState.opListReadCapability.reject(reason); 21851 } else { 21852 throw reason; 21853 } 21854 }); 21855 }; 21856 pump(); 21857 } 21858 _abortOperatorList({ 21859 intentState, 21860 reason, 21861 force = false 21862 }) { 21863 if (!intentState.streamReader) { 21864 return; 21865 } 21866 if (intentState.streamReaderCancelTimeout) { 21867 clearTimeout(intentState.streamReaderCancelTimeout); 21868 intentState.streamReaderCancelTimeout = null; 21869 } 21870 if (!force) { 21871 if (intentState.renderTasks.size > 0) { 21872 return; 21873 } 21874 if (reason instanceof RenderingCancelledException) { 21875 let delay = RENDERING_CANCELLED_TIMEOUT; 21876 if (reason.extraDelay > 0 && reason.extraDelay < 1000) { 21877 delay += reason.extraDelay; 21878 } 21879 intentState.streamReaderCancelTimeout = setTimeout(() => { 21880 intentState.streamReaderCancelTimeout = null; 21881 this._abortOperatorList({ 21882 intentState, 21883 reason, 21884 force: true 21885 }); 21886 }, delay); 21887 return; 21888 } 21889 } 21890 intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {}); 21891 intentState.streamReader = null; 21892 if (this._transport.destroyed) { 21893 return; 21894 } 21895 for (const [curCacheKey, curIntentState] of this._intentStates) { 21896 if (curIntentState === intentState) { 21897 this._intentStates.delete(curCacheKey); 21898 break; 21899 } 21900 } 21901 this.cleanup(); 21902 } 21903 get stats() { 21904 return this._stats; 21905 } 21906} 21907class PDFWorker { 21908 #capability = Promise.withResolvers(); 21909 #messageHandler = null; 21910 #port = null; 21911 #webWorker = null; 21912 static #fakeWorkerId = 0; 21913 static #isWorkerDisabled = false; 21914 static #workerPorts = new WeakMap(); 21915 static { 21916 if (isNodeJS) { 21917 this.#isWorkerDisabled = true; 21918 GlobalWorkerOptions.workerSrc ||= "./pdf.worker.js"; 21919 } 21920 this._isSameOrigin = (baseUrl, otherUrl) => { 21921 const base = URL.parse(baseUrl); 21922 if (!base?.origin || base.origin === "null") { 21923 return false; 21924 } 21925 const other = new URL(otherUrl, base); 21926 return base.origin === other.origin; 21927 }; 21928 this._createCDNWrapper = url => { 21929 const wrapper = `await import("${url}");`; 21930 return URL.createObjectURL(new Blob([wrapper], { 21931 type: "text/javascript" 21932 })); 21933 }; 21934 this.fromPort = params => { 21935 deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."); 21936 if (!params?.port) { 21937 throw new Error("PDFWorker.fromPort - invalid method signature."); 21938 } 21939 return this.create(params
vendor: 5,303 bytes, lines 21939-22125
21939); 21940 }; 21941 } 21942 constructor({ 21943 name = null, 21944 port = null, 21945 verbosity = getVerbosityLevel() 21946 } = {}) { 21947 this.name = name; 21948 this.destroyed = false; 21949 this.verbosity = verbosity; 21950 if (port) { 21951 if (PDFWorker.#workerPorts.has(port)) { 21952 throw new Error("Cannot use more than one PDFWorker per port."); 21953 } 21954 PDFWorker.#workerPorts.set(port, this); 21955 this.#initializeFromPort(port); 21956 } else { 21957 this.#initialize(); 21958 } 21959 } 21960 get promise() { 21961 return this.#capability.promise; 21962 } 21963 #resolve() { 21964 this.#capability.resolve(); 21965 this.#messageHandler.send("configure", { 21966 verbosity: this.verbosity 21967 }); 21968 } 21969 get port() { 21970 return this.#port; 21971 } 21972 get messageHandler() { 21973 return this.#messageHandler; 21974 } 21975 #initializeFromPort(port) { 21976 this.#port = port; 21977 this.#messageHandler = new MessageHandler("main", "worker", port); 21978 this.#messageHandler.on("ready", () => {}); 21979 this.#resolve(); 21980 } 21981 #initialize() { 21982 if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) { 21983 this.#setupFakeWorker(); 21984 return; 21985 } 21986 let { 21987 workerSrc 21988 } = PDFWorker; 21989 try { 21990 if (!PDFWorker._isSameOrigin(window.location, workerSrc)) { 21991 workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href); 21992 } 21993 const worker = new Worker(workerSrc, { 21994 type: "module" 21995 }); 21996 const messageHandler = new MessageHandler("main", "worker", worker); 21997 const terminateEarly = () => { 21998 ac.abort(); 21999 messageHandler.destroy(); 22000 worker.terminate(); 22001 if (this.destroyed) { 22002 this.#capability.reject(new Error("Worker was destroyed")); 22003 } else { 22004 this.#setupFakeWorker(); 22005 } 22006 }; 22007 const ac = new AbortController(); 22008 worker.addEventListener("error", () => { 22009 if (!this.#webWorker) { 22010 terminateEarly(); 22011 } 22012 }, { 22013 signal: ac.signal 22014 }); 22015 messageHandler.on("test", data => { 22016 ac.abort(); 22017 if (this.destroyed || !data) { 22018 terminateEarly(); 22019 return; 22020 } 22021 this.#messageHandler = messageHandler; 22022 this.#port = worker; 22023 this.#webWorker = worker; 22024 this.#resolve(); 22025 }); 22026 messageHandler.on("ready", data => { 22027 ac.abort(); 22028 if (this.destroyed) { 22029 terminateEarly(); 22030 return; 22031 } 22032 try { 22033 sendTest(); 22034 } catch { 22035 this.#setupFakeWorker(); 22036 } 22037 }); 22038 const sendTest = () => { 22039 const testObj = new Uint8Array(); 22040 messageHandler.send("test", testObj, [testObj.buffer]); 22041 }; 22042 sendTest(); 22043 return; 22044 } catch { 22045 info("The worker has been disabled."); 22046 } 22047 this.#setupFakeWorker(); 22048 } 22049 #setupFakeWorker() { 22050 if (!PDFWorker.#isWorkerDisabled) { 22051 warn("Setting up fake worker."); 22052 PDFWorker.#isWorkerDisabled = true; 22053 } 22054 PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => { 22055 if (this.destroyed) { 22056 this.#capability.reject(new Error("Worker was destroyed")); 22057 return; 22058 } 22059 const port = new LoopbackPort(); 22060 this.#port = port; 22061 const id = `fake${PDFWorker.#fakeWorkerId++}`; 22062 const workerHandler = new MessageHandler(id + "_worker", id, port); 22063 WorkerMessageHandler.setup(workerHandler, port); 22064 this.#messageHandler = new MessageHandler(id, id + "_worker", port); 22065 this.#resolve(); 22066 }).catch(reason => { 22067 this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); 22068 }); 22069 } 22070 destroy() { 22071 this.destroyed = true; 22072 this.#webWorker?.terminate(); 22073 this.#webWorker = null; 22074 PDFWorker.#workerPorts.delete(this.#port); 22075 this.#port = null; 22076 this.#messageHandler?.destroy(); 22077 this.#messageHandler = null; 22078 } 22079 static create(params) { 22080 const cachedPort = this.#workerPorts.get(params?.port); 22081 if (cachedPort) { 22082 if (cachedPort._pendingDestroy) { 22083 throw new Error("PDFWorker.create - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls."); 22084 } 22085 return cachedPort; 22086 } 22087 return new PDFWorker(params); 22088 } 22089 static get workerSrc() { 22090 if (GlobalWorkerOptions.workerSrc) { 22091 return GlobalWorkerOptions.workerSrc; 22092 } 22093 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); 22094 } 22095 static get #mainThreadWorkerMessageHandler() { 22096 try { 22097 return globalThis.pdfjsWorker?.WorkerMessageHandler || null; 22098 } catch { 22099 return null; 22100 } 22101 } 22102 static get _setupFakeWorkerGlobal() { 22103 const loader = async () => { 22104 if (this.#mainThreadWorkerMessageHandler) { 22105 return this.#mainThreadWorkerMessageHandler; 22106 } 22107 const worker = await import( 22108 /*webpackIgnore: true*/ 22109 /*@vite-ignore*/ 22110 this.workerSrc); 22111 return worker.WorkerMessageHandler; 22112 }; 22113 return shadow(this, "_setupFakeWorkerGlobal", loader()); 22114 } 22115} 22116class WorkerTransport { 22117 downloadInfoCapability = Promise.withResolvers(); 22118 #fullReader = null; 22119 #methodPromises = new Map(); 22120 #networkStream = null; 22121 #pageCache = new Map(); 22122 #pagePromises = new Map(); 22123 #pageRefCache = new Map(); 22124 #passwordCapability = null; 22125
22125#copiedPageInfo = null; 22126 constructor(messageHandler, loadingTask, networkStream, params, factory, pagesMapper) { 22127 this.messageHandler = messageHandler; 22128 this.loadingTask = loadingTask; 22129 this.#networkStream = networkStream; 22130 this.commonObjs = new PDFObjects(); 22131 this.fontLoader = new FontLoader({ 22132 ownerDocument: params.ownerDocument, 22133 styleElement: params.styleElement 22134 }); 22135 this.enableHWA = params.enableHWA; 22136 this.loadingParams = params.loadingParams; 22137 this._params = params; 22138 this.canvasFactory = factory.canvasFactory; 22139 this.filterFactory = factory.filterFactory; 22140 this.cMapReaderFactory = factory.cMapReaderFactory; 22141 this.standardFontDataFactory = factory.standardFontDataFactory; 22142 this.wasmFactory = factory.wasmFactory; 22143 this.destroyed = false; 22144 this.destroyCapability = null; 22145 this.setupMessageHandler(); 22146 this.pagesMapper = pagesMapper; 22147 this.pagesMapper.addListener(this.#updateCaches.bind(this)); 22148 } 22149 #updateCaches({ 22150 type, 22151 pageNumbers 22152 }) { 22153 if (type === "copy") { 22154 this.#copiedPageInfo = new Map(); 22155 for (const pageNum of pageNumbers) { 22156 this.#copiedPageInfo.set(pageNum, { 22157 proxy: this.#pageCache.get(pageNum - 1) || null, 22158 promise: this.#pagePromises.get(pageNum - 1) || null 22159 }); 22160 } 22161 return; 22162 } 22163 if (type === "delete") { 22164 for (const pageNum of pageNumbers) { 22165 this.#pageCache.delete(pageNum - 1); 22166 this.#pagePromises.delete(pageNum - 1); 22167 } 22168 } 22169 const newPageCache = new Map(); 22170 const newPromiseCache = new Map(); 22171 const { 22172 pagesMapper 22173 } = this; 22174 for (let i = 0, ii = pagesMapper.pagesNumber; i < ii; i++) { 22175 const prevPageNumber = pagesMapper.getPrevPageNumber(i + 1); 22176 if (prevPageNumber < 0) { 22177 const { 22178 proxy, 22179 promise 22180 } = this.#copiedPageInfo?.get(-prevPageNumber) || {}; 22181 if (proxy) { 22182 newPageCache.set(i, proxy); 22183 } 22184 if (promise) { 22185 newPromiseCache.set(i, promise); 22186 } 22187 continue; 22188 } 22189 const prevPageIndex = prevPageNumber - 1; 22190 const page = this.#pageCache.get(prevPageIndex); 22191 if (page) { 22192 newPageCache.set(i, page); 22193 } 22194 const promise = this.#pagePromises.get(prevPageIndex); 22195 if (promise) { 22196 newPromiseCache.set(i, promise); 22197 } 22198 } 22199 this.#pageCache = newPageCache; 22200 this.#pagePromises = newPromiseCache; 22201 } 22202 #cacheSimpleMethod(name, data = null) { 22203 return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, data)); 22204 } 22205 #onProgress({ 22206 loaded, 22207 total 22208 }) { 22209 this.loadingTask.onProgress?.({ 22210 loaded, 22211 total, 22212 percent: MathClamp(Math.round(loaded / total * 100), 0, 100) 22213 }); 22214 } 22215 get annotationStorage() { 22216 return shadow(this, "annotationStorage", new AnnotationStorage()); 22217 } 22218 getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) { 22219 let renderingIntent = RenderingIntentFlag.DISPLAY; 22220 let annotationStorageSerializable = SerializableEmpty; 22221 switch (intent) { 22222 case "any": 22223 renderingIntent = RenderingIntentFlag.ANY; 22224 break; 22225 case "display": 22226 break; 22227 case "print": 22228 renderingIntent = RenderingIntentFlag.PRINT; 22229 break; 22230 default: 22231 warn(`getRenderingIntent - invalid intent: ${intent}`); 22232 } 22233 const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; 22234 switch (annotationMode) { 22235 case AnnotationMode.DISABLE: 22236 renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE; 22237 break; 22238 case AnnotationMode.ENABLE: 22239 break; 22240 case AnnotationMode.ENABLE_FORMS: 22241 renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS; 22242 break; 22243 case AnnotationMode.ENABLE_STORAGE: 22244 renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE; 22245 annotationStorageSerializable = annotationStorage.serializable; 22246 break; 22247 default: 22248 warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); 22249 } 22250 if (isEditing) { 22251 renderingIntent += RenderingIntentFlag.IS_EDITING; 22252 } 22253 if (isOpList) { 22254 renderingIntent += RenderingIntentFlag.OPLIST; 22255 } 22256 const { 22257 ids: modifiedIds, 22258 hash: modifiedIdsHash 22259 } = annotationStorage.modifiedIds; 22260 const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash]; 22261 return { 22262 renderingIntent, 22263 cacheKey: cacheKeyBuf.join("_"), 22264 annotationStorageSerializable, 22265 modifiedIds 22266 }; 22267 } 22268 destroy() { 22269 if (this.destroyCapability) { 22270 return this.destroyCapability.promise; 22271 } 22272 this.destroyed = true; 22273 this.destroyCapability = Promise.withResolvers(); 22274 this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); 22275 const waitOn = []; 22276 for (const page of this.#pageCache.values()) { 22277 waitOn.push(page._destroy()); 22278 } 22279 this.#pageCache.clear(); 22280 this.#pagePromises.clear();
vendor: 18,955 bytes, lines 22281-22871
22281 this.#pageRefCache.clear(); 22282 if (this.hasOwnProperty("annotationStorage")) { 22283 this.annotationStorage.resetModified(); 22284 } 22285 const terminated = this.messageHandler.sendWithPromise("Terminate", null); 22286 waitOn.push(terminated); 22287 Promise.all(waitOn).then(() => { 22288 this.commonObjs.clear(); 22289 this.fontLoader.clear(); 22290 this.#methodPromises.clear(); 22291 this.filterFactory.destroy(); 22292 TextLayer.cleanup(); 22293 this.#networkStream?.cancelAllRequests(new AbortException("Worker was terminated.")); 22294 this.messageHandler?.destroy(); 22295 this.messageHandler = null; 22296 this.destroyCapability.resolve(); 22297 }, this.destroyCapability.reject); 22298 return this.destroyCapability.promise; 22299 } 22300 setupMessageHandler() { 22301 const { 22302 messageHandler, 22303 loadingTask 22304 } = this; 22305 messageHandler.on("GetReader", (data, sink) => { 22306 assert(this.#networkStream, "GetReader - no `BasePDFStream` instance available."); 22307 this.#fullReader = this.#networkStream.getFullReader(); 22308 this.#fullReader.onProgress = evt => this.#onProgress(evt); 22309 sink.onPull = () => { 22310 this.#fullReader.read().then(function ({ 22311 value, 22312 done 22313 }) { 22314 if (done) { 22315 sink.close(); 22316 return; 22317 } 22318 assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); 22319 sink.enqueue(new Uint8Array(value), 1, [value]); 22320 }).catch(reason => { 22321 sink.error(reason); 22322 }); 22323 }; 22324 sink.onCancel = reason => { 22325 this.#fullReader.cancel(reason); 22326 sink.ready.catch(readyReason => { 22327 if (this.destroyed) { 22328 return; 22329 } 22330 throw readyReason; 22331 }); 22332 }; 22333 }); 22334 messageHandler.on("ReaderHeadersReady", async data => { 22335 await this.#fullReader.headersReady; 22336 const { 22337 isStreamingSupported, 22338 isRangeSupported, 22339 contentLength 22340 } = this.#fullReader; 22341 if (isStreamingSupported && isRangeSupported) { 22342 this.#fullReader.onProgress = null; 22343 } 22344 return { 22345 isStreamingSupported, 22346 isRangeSupported, 22347 contentLength 22348 }; 22349 }); 22350 messageHandler.on("GetRangeReader", (data, sink) => { 22351 assert(this.#networkStream, "GetRangeReader - no `BasePDFStream` instance available."); 22352 const rangeReader = this.#networkStream.getRangeReader(data.begin, data.end); 22353 if (!rangeReader) { 22354 sink.close(); 22355 return; 22356 } 22357 sink.onPull = () => { 22358 rangeReader.read().then(function ({ 22359 value, 22360 done 22361 }) { 22362 if (done) { 22363 sink.close(); 22364 return; 22365 } 22366 assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); 22367 sink.enqueue(new Uint8Array(value), 1, [value]); 22368 }).catch(reason => { 22369 sink.error(reason); 22370 }); 22371 }; 22372 sink.onCancel = reason => { 22373 rangeReader.cancel(reason); 22374 sink.ready.catch(readyReason => { 22375 if (this.destroyed) { 22376 return; 22377 } 22378 throw readyReason; 22379 }); 22380 }; 22381 }); 22382 messageHandler.on("GetDoc", ({ 22383 pdfInfo 22384 }) => { 22385 this.pagesMapper.pagesNumber = pdfInfo.numPages; 22386 this._numPages = pdfInfo.numPages; 22387 this._htmlForXfa = pdfInfo.htmlForXfa; 22388 delete pdfInfo.htmlForXfa; 22389 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); 22390 }); 22391 messageHandler.on("DocException", ex => { 22392 loadingTask._capability.reject(wrapReason(ex)); 22393 }); 22394 messageHandler.on("PasswordRequest", ex => { 22395 this.#passwordCapability = Promise.withResolvers(); 22396 try { 22397 if (!loadingTask.onPassword) { 22398 throw wrapReason(ex); 22399 } 22400 const updatePassword = password => { 22401 if (password instanceof Error) { 22402 this.#passwordCapability.reject(password); 22403 } else { 22404 this.#passwordCapability.resolve({ 22405 password 22406 }); 22407 } 22408 }; 22409 loadingTask.onPassword(updatePassword, ex.code); 22410 } catch (err) { 22411 this.#passwordCapability.reject(err); 22412 } 22413 return this.#passwordCapability.promise; 22414 }); 22415 messageHandler.on("DataLoaded", data => { 22416 this.#onProgress({ 22417 loaded: data.length, 22418 total: data.length 22419 }); 22420 this.downloadInfoCapability.resolve(data); 22421 }); 22422 messageHandler.on("StartRenderPage", data => { 22423 if (this.destroyed) { 22424 return; 22425 } 22426 const page = this.#pageCache.get(data.pageIndex); 22427 page._startRenderPage(data.transparency, data.cacheKey); 22428 }); 22429 messageHandler.on("commonobj", ([id, type, exportedData]) => { 22430 if (this.destroyed) { 22431 return null; 22432 } 22433 if (this.commonObjs.has(id)) { 22434 return null; 22435 } 22436 switch (type) { 22437 case "Font": 22438 if ("error" in exportedData) { 22439 const exportedError = exportedData.error; 22440 warn(`Error during font loading: ${exportedError}`); 22441 this.commonObjs.resolve(id, exportedError); 22442 break; 22443 } 22444 const fontData = new FontInfo(exportedData); 22445 const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null; 22446 const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList); 22447 this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", { 22448 id 22449 })).finally(() => { 22450 if (!font.fontExtraProperties && font.data) { 22451 font.clearData(); 22452 } 22453 this.commonObjs.resolve(id, font); 22454 }); 22455 break; 22456 case "CopyLocalImage": 22457 const { 22458 imageRef 22459 } = exportedData; 22460 assert(imageRef, "The imageRef must be defined."); 22461 for (const pageProxy of this.#pageCache.values()) { 22462 for (const [, data] of pageProxy.objs) { 22463 if (data?.ref !== imageRef) { 22464 continue; 22465 } 22466 if (!data.dataLen) { 22467 return null; 22468 } 22469 this.commonObjs.resolve(id, structuredClone(data)); 22470 return data.dataLen; 22471 } 22472 } 22473 break; 22474 case "FontPath": 22475 this.commonObjs.resolve(id, new FontPathInfo(exportedData)); 22476 break; 22477 case "Image": 22478 this.commonObjs.resolve(id, exportedData); 22479 break; 22480 case "Pattern": 22481 const pattern = new PatternInfo(exportedData); 22482 this.commonObjs.resolve(id, pattern.getIR()); 22483 break; 22484 default: 22485 throw new Error(`Got unknown common object type ${type}`); 22486 } 22487 return null; 22488 }); 22489 messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { 22490 if (this.destroyed) { 22491 return; 22492 } 22493 const pageProxy = this.#pageCache.get(pageIndex); 22494 if (pageProxy.objs.has(id)) { 22495 return; 22496 } 22497 if (pageProxy._intentStates.size === 0) { 22498 imageData?.bitmap?.close(); 22499 return; 22500 } 22501 switch (type) { 22502 case "Image": 22503 case "Pattern": 22504 pageProxy.objs.resolve(id, imageData); 22505 break; 22506 default: 22507 throw new Error(`Got unknown object type ${type}`); 22508 } 22509 }); 22510 messageHandler.on("DocProgress", data => { 22511 if (this.destroyed) { 22512 return; 22513 } 22514 this.#onProgress(data); 22515 }); 22516 messageHandler.on("FetchBinaryData", async data => { 22517 if (this.destroyed) { 22518 throw new Error("Worker was destroyed."); 22519 } 22520 const factory = this[data.type]; 22521 if (!factory) { 22522 throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`); 22523 } 22524 return factory.fetch(data); 22525 }); 22526 } 22527 getData() { 22528 return this.messageHandler.sendWithPromise("GetData", null); 22529 } 22530 saveDocument() { 22531 if (this.annotationStorage.size <= 0) { 22532 warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); 22533 } 22534 const { 22535 map, 22536 transfer 22537 } = this.annotationStorage.serializable; 22538 return this.messageHandler.sendWithPromise("SaveDocument", { 22539 isPureXfa: !!this._htmlForXfa, 22540 numPages: this._numPages, 22541 annotationStorage: map, 22542 filename: this.#fullReader?.filename ?? null 22543 }, transfer).finally(() => { 22544 this.annotationStorage.resetModified(); 22545 }); 22546 } 22547 extractPages(pageInfos) { 22548 return this.messageHandler.sendWithPromise("ExtractPages", { 22549 pageInfos 22550 }); 22551 } 22552 getPage(pageNumber) { 22553 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this.pagesMapper.pagesNumber) { 22554 return Promise.reject(new Error("Invalid page request.")); 22555 } 22556 const pageIndex = pageNumber - 1; 22557 const newPageIndex = this.pagesMapper.getPageId(pageNumber) - 1; 22558 const cachedPromise = this.#pagePromises.get(pageIndex); 22559 if (cachedPromise) { 22560 return cachedPromise; 22561 } 22562 const promise = this.messageHandler.sendWithPromise("GetPage", { 22563 pageIndex: newPageIndex 22564 }).then(pageInfo => { 22565 if (this.destroyed) { 22566 throw new Error("Transport destroyed"); 22567 } 22568 if (pageInfo.refStr) { 22569 this.#pageRefCache.set(pageInfo.refStr, newPageIndex); 22570 } 22571 const page = new PDFPageProxy(pageIndex, pageInfo, this, this.pagesMapper, this._params.pdfBug); 22572 this.#pageCache.set(pageIndex, page); 22573 return page; 22574 }); 22575 this.#pagePromises.set(pageIndex, promise); 22576 return promise; 22577 } 22578 async getPageIndex(ref) { 22579 if (!isRefProxy(ref)) { 22580 throw new Error("Invalid pageIndex request."); 22581 } 22582 const index = await this.messageHandler.sendWithPromise("GetPageIndex", { 22583 num: ref.num, 22584 gen: ref.gen 22585 }); 22586 const pageNumber = this.pagesMapper.getPageNumber(index + 1); 22587 if (pageNumber === 0) { 22588 throw new Error("GetPageIndex: page has been removed."); 22589 } 22590 return pageNumber - 1; 22591 } 22592 getAnnotations(pageIndex, intent) { 22593 return this.messageHandler.sendWithPromise("GetAnnotations", { 22594 pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1, 22595 intent 22596 }); 22597 } 22598 getFieldObjects() { 22599 return this.#cacheSimpleMethod("GetFieldObjects"); 22600 } 22601 hasJSActions() { 22602 return this.#cacheSimpleMethod("HasJSActions"); 22603 } 22604 getCalculationOrderIds() { 22605 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); 22606 } 22607 getDestinations() { 22608 return this.messageHandler.sendWithPromise("GetDestinations", null); 22609 } 22610 getDestination(id) { 22611 if (typeof id !== "string") { 22612 return Promise.reject(new Error("Invalid destination request.")); 22613 } 22614 return this.messageHandler.sendWithPromise("GetDestination", { 22615 id 22616 }); 22617 } 22618 getPageLabels() { 22619 return this.messageHandler.sendWithPromise("GetPageLabels", null); 22620 } 22621 getPageLayout() { 22622 return this.messageHandler.sendWithPromise("GetPageLayout", null); 22623 } 22624 getPageMode() { 22625 return this.messageHandler.sendWithPromise("GetPageMode", null); 22626 } 22627 getViewerPreferences() { 22628 return this.messageHandler.sendWithPromise("GetViewerPreferences", null); 22629 } 22630 getOpenAction() { 22631 return this.messageHandler.sendWithPromise("GetOpenAction", null); 22632 } 22633 getAttachments() { 22634 return this.messageHandler.sendWithPromise("GetAttachments", null); 22635 } 22636 getAnnotationsByType(types, pageIndexesToSkip) { 22637 return this.messageHandler.sendWithPromise("GetAnnotationsByType", { 22638 types, 22639 pageIndexesToSkip 22640 }); 22641 } 22642 getDocJSActions() { 22643 return this.#cacheSimpleMethod("GetDocJSActions"); 22644 } 22645 getPageJSActions(pageIndex) { 22646 return this.messageHandler.sendWithPromise("GetPageJSActions", { 22647 pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1 22648 }); 22649 } 22650 getStructTree(pageIndex) { 22651 return this.messageHandler.sendWithPromise("GetStructTree", { 22652 pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1 22653 }); 22654 } 22655 getOutline() { 22656 return this.messageHandler.sendWithPromise("GetOutline", null); 22657 } 22658 getOptionalContentConfig(renderingIntent) { 22659 return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent)); 22660 } 22661 getPermissions() { 22662 return this.messageHandler.sendWithPromise("GetPermissions", null); 22663 } 22664 getMetadata() { 22665 const name = "GetMetadata"; 22666 return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, null).then(results => ({ 22667 info: results[0], 22668 metadata: results[1] ? new Metadata(results[1]) : null, 22669 contentDispositionFilename: this.#fullReader?.filename ?? null, 22670 contentLength: this.#fullReader?.contentLength ?? null, 22671 hasStructTree: results[2] 22672 }))); 22673 } 22674 getMarkInfo() { 22675 return this.messageHandler.sendWithPromise("GetMarkInfo", null); 22676 } 22677 async startCleanup(keepLoadedFonts = false) { 22678 if (this.destroyed) { 22679 return; 22680 } 22681 await this.messageHandler.sendWithPromise("Cleanup", null); 22682 for (const page of this.#pageCache.values()) { 22683 const cleanupSuccessful = page.cleanup(); 22684 if (!cleanupSuccessful) { 22685 throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); 22686 } 22687 } 22688 this.commonObjs.clear(); 22689 if (!keepLoadedFonts) { 22690 this.fontLoader.clear(); 22691 } 22692 this.#methodPromises.clear(); 22693 this.filterFactory.destroy(true); 22694 TextLayer.cleanup(); 22695 } 22696 cachedPageNumber(ref) { 22697 if (!isRefProxy(ref)) { 22698 return null; 22699 } 22700 const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`; 22701 const pageIndex = this.#pageRefCache.get(refStr); 22702 if (pageIndex >= 0) { 22703 const pageNumber = this.pagesMapper.getPageNumber(pageIndex + 1); 22704 if (pageNumber !== 0) { 22705 return pageNumber; 22706 } 22707 } 22708 return null; 22709 } 22710} 22711class RenderTask { 22712 _internalRenderTask = null; 22713 onContinue = null; 22714 onError = null; 22715 constructor(internalRenderTask) { 22716 this._internalRenderTask = internalRenderTask; 22717 } 22718 get promise() { 22719 return this._internalRenderTask.capability.promise; 22720 } 22721 cancel(extraDelay = 0) { 22722 this._internalRenderTask.cancel(null, extraDelay); 22723 } 22724 get separateAnnots() { 22725 const { 22726 separateAnnots 22727 } = this._internalRenderTask.operatorList; 22728 if (!separateAnnots) { 22729 return false; 22730 } 22731 const { 22732 annotationCanvasMap 22733 } = this._internalRenderTask; 22734 return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; 22735 } 22736} 22737class InternalRenderTask { 22738 #rAF = null; 22739 static #canvasInUse = new WeakSet(); 22740 constructor({ 22741 callback, 22742 params, 22743 objs, 22744 commonObjs, 22745 annotationCanvasMap, 22746 operatorList, 22747 pageIndex, 22748 canvasFactory, 22749 filterFactory, 22750 useRequestAnimationFrame = false, 22751 pdfBug = false, 22752 pageColors = null, 22753 enableHWA = false, 22754 operationsFilter = null 22755 }) { 22756 this.callback = callback; 22757 this.params = params; 22758 this.objs = objs; 22759 this.commonObjs = commonObjs; 22760 this.annotationCanvasMap = annotationCanvasMap; 22761 this.operatorListIdx = null; 22762 this.operatorList = operatorList; 22763 this._pageIndex = pageIndex; 22764 this.canvasFactory = canvasFactory; 22765 this.filterFactory = filterFactory; 22766 this._pdfBug = pdfBug; 22767 this.pageColors = pageColors; 22768 this.running = false; 22769 this.graphicsReadyCallback = null; 22770 this.graphicsReady = false; 22771 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; 22772 this.cancelled = false; 22773 this.capability = Promise.withResolvers(); 22774 this.task = new RenderTask(this); 22775 this._cancelBound = this.cancel.bind(this); 22776 this._continueBound = this._continue.bind(this); 22777 this._scheduleNextBound = this._scheduleNext.bind(this); 22778 this._nextBound = this._next.bind(this); 22779 this._canvas = params.canvas; 22780 this._canvasContext = params.canvas ? null : params.canvasContext; 22781 this._enableHWA = enableHWA; 22782 this._dependencyTracker = params.dependencyTracker; 22783 this._operationsFilter = operationsFilter; 22784 } 22785 get completed() { 22786 return this.capability.promise.catch(function () {}); 22787 } 22788 initializeGraphics({ 22789 transparency = false, 22790 optionalContentConfig 22791 }) { 22792 if (this.cancelled) { 22793 return; 22794 } 22795 if (this._canvas) { 22796 if (InternalRenderTask.#canvasInUse.has(this._canvas)) { 22797 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); 22798 } 22799 InternalRenderTask.#canvasInUse.add(this._canvas); 22800 } 22801 if (this._pdfBug && globalThis.StepperManager?.enabled) { 22802 this.stepper = globalThis.StepperManager.create(this._pageIndex); 22803 this.stepper.init(this.operatorList); 22804 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); 22805 } 22806 const { 22807 viewport, 22808 transform, 22809 background, 22810 dependencyTracker 22811 } = this.params; 22812 const canvasContext = this._canvasContext || this._canvas.getContext("2d", { 22813 alpha: false, 22814 willReadFrequently: !this._enableHWA 22815 }); 22816 this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { 22817 optionalContentConfig 22818 }, this.annotationCanvasMap, this.pageColors, dependencyTracker); 22819 this.gfx.beginDrawing({ 22820 transform, 22821 viewport, 22822 transparency, 22823 background 22824 }); 22825 this.operatorListIdx = 0; 22826 this.graphicsReady = true; 22827 this.graphicsReadyCallback?.(); 22828 } 22829 cancel(error = null, extraDelay = 0) { 22830 this.running = false; 22831 this.cancelled = true; 22832 this.gfx?.endDrawing(); 22833 if (this.#rAF) { 22834 window.cancelAnimationFrame(this.#rAF); 22835 this.#rAF = null; 22836 } 22837 InternalRenderTask.#canvasInUse.delete(this._canvas); 22838 error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay); 22839 this.callback(error); 22840 this.task.onError?.(error); 22841 } 22842 operatorListChanged() { 22843 if (!this.graphicsReady) { 22844 this.graphicsReadyCallback ||= this._continueBound; 22845 return; 22846 } 22847 this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length); 22848 this.stepper?.updateOperatorList(this.operatorList); 22849 if (this.running) { 22850 return; 22851 } 22852 this._continue(); 22853 } 22854 _continue() { 22855 this.running = true; 22856 if (this.cancelled) { 22857 return; 22858 } 22859 if (this.task.onContinue) { 22860 this.task.onContinue(this._scheduleNextBound); 22861 } else { 22862 this._scheduleNext(); 22863 } 22864 } 22865 _scheduleNext() { 22866 if (this._useRequestAnimationFrame) { 22867 this.#rAF = window.requestAnimationFrame(() => { 22868 this.#rAF = null; 22869 this._nextBound().catch(this._cancelBound); 22870 }); 22871 } else {
vendor: 8,899 bytes, lines 22872-23157
22872 Promise.resolve().then(this._nextBound).catch(this._cancelBound); 22873 } 22874 } 22875 async _next() { 22876 if (this.cancelled) { 22877 return; 22878 } 22879 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter); 22880 if (this.operatorListIdx === this.operatorList.argsArray.length) { 22881 this.running = false; 22882 if (this.operatorList.lastChunk) { 22883 this.gfx.endDrawing(); 22884 InternalRenderTask.#canvasInUse.delete(this._canvas); 22885 this.callback(); 22886 } 22887 } 22888 } 22889} 22890const version = "5.5.207"; 22891const build = "527964698"; 22892 22893;// ./src/display/editor/color_picker.js 22894 22895 22896 22897class ColorPicker { 22898 #button = null; 22899 #buttonSwatch = null; 22900 #defaultColor; 22901 #dropdown = null; 22902 #dropdownWasFromKeyboard = false; 22903 #isMainColorPicker = false; 22904 #editor = null; 22905 #eventBus; 22906 #openDropdownAC = null; 22907 #uiManager = null; 22908 static #l10nColor = null; 22909 static get _keyboardManager() { 22910 return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]])); 22911 } 22912 constructor({ 22913 editor = null, 22914 uiManager = null 22915 }) { 22916 if (editor) { 22917 this.#isMainColorPicker = false; 22918 this.#editor = editor; 22919 } else { 22920 this.#isMainColorPicker = true; 22921 } 22922 this.#uiManager = editor?._uiManager || uiManager; 22923 this.#eventBus = this.#uiManager._eventBus; 22924 this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98"; 22925 ColorPicker.#l10nColor ||= Object.freeze({ 22926 blue: "pdfjs-editor-colorpicker-blue", 22927 green: "pdfjs-editor-colorpicker-green", 22928 pink: "pdfjs-editor-colorpicker-pink", 22929 red: "pdfjs-editor-colorpicker-red", 22930 yellow: "pdfjs-editor-colorpicker-yellow" 22931 }); 22932 } 22933 renderButton() { 22934 const button = this.#button = document.createElement("button"); 22935 button.className = "colorPicker"; 22936 button.tabIndex = "0"; 22937 button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button"); 22938 button.ariaHasPopup = "true"; 22939 if (this.#editor) { 22940 button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`; 22941 } 22942 const signal = this.#uiManager._signal; 22943 button.addEventListener("click", this.#openDropdown.bind(this), { 22944 signal 22945 }); 22946 button.addEventListener("keydown", this.#keyDown.bind(this), { 22947 signal 22948 }); 22949 const swatch = this.#buttonSwatch = document.createElement("span"); 22950 swatch.className = "swatch"; 22951 swatch.ariaHidden = "true"; 22952 swatch.style.backgroundColor = this.#defaultColor; 22953 button.append(swatch); 22954 return button; 22955 } 22956 renderMainDropdown() { 22957 const dropdown = this.#dropdown = this.#getDropdownRoot(); 22958 dropdown.ariaOrientation = "horizontal"; 22959 dropdown.ariaLabelledBy = "highlightColorPickerLabel"; 22960 return dropdown; 22961 } 22962 #getDropdownRoot() { 22963 const div = document.createElement("div"); 22964 const signal = this.#uiManager._signal; 22965 div.addEventListener("contextmenu", noContextMenu, { 22966 signal 22967 }); 22968 div.className = "dropdown"; 22969 div.role = "listbox"; 22970 div.ariaMultiSelectable = "false"; 22971 div.ariaOrientation = "vertical"; 22972 div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown"); 22973 if (this.#editor) { 22974 div.id = `${this.#editor.id}_colorpicker_dropdown`; 22975 } 22976 for (const [name, color] of this.#uiManager.highlightColors) { 22977 const button = document.createElement("button"); 22978 button.tabIndex = "0"; 22979 button.role = "option"; 22980 button.setAttribute("data-color", color); 22981 button.title = name; 22982 button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]); 22983 const swatch = document.createElement("span"); 22984 button.append(swatch); 22985 swatch.className = "swatch"; 22986 swatch.style.backgroundColor = color; 22987 button.ariaSelected = color === this.#defaultColor; 22988 button.addEventListener("click", this.#colorSelect.bind(this, color), { 22989 signal 22990 }); 22991 div.append(button); 22992 } 22993 div.addEventListener("keydown", this.#keyDown.bind(this), { 22994 signal 22995 }); 22996 return div; 22997 } 22998 #colorSelect(color, event) { 22999 event.stopPropagation(); 23000 this.#eventBus.dispatch("switchannotationeditorparams", { 23001 source: this, 23002 type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, 23003 value: color 23004 }); 23005 this.updateColor(color); 23006 } 23007 _colorSelectFromKeyboard(event) { 23008 if (event.target === this.#button) { 23009 this.#openDropdown(event); 23010 return; 23011 } 23012 const color = event.target.getAttribute("data-color"); 23013 if (!color) { 23014 return; 23015 } 23016 this.#colorSelect(color, event); 23017 } 23018 _moveToNext(event) { 23019 if (!this.#isDropdownVisible) { 23020 this.#openDropdown(event); 23021 return; 23022 } 23023 if (event.target === this.#button) { 23024 this.#dropdown.firstElementChild?.focus(); 23025 return; 23026 } 23027 event.target.nextSibling?.focus(); 23028 } 23029 _moveToPrevious(event) { 23030 if (event.target === this.#dropdown?.firstElementChild || event.target === this.#button) { 23031 if (this.#isDropdownVisible) { 23032 this._hideDropdownFromKeyboard(); 23033 } 23034 return; 23035 } 23036 if (!this.#isDropdownVisible) { 23037 this.#openDropdown(event); 23038 } 23039 event.target.previousSibling?.focus(); 23040 } 23041 _moveToBeginning(event) { 23042 if (!this.#isDropdownVisible) { 23043 this.#openDropdown(event); 23044 return; 23045 } 23046 this.#dropdown.firstElementChild?.focus(); 23047 } 23048 _moveToEnd(event) { 23049 if (!this.#isDropdownVisible) { 23050 this.#openDropdown(event); 23051 return; 23052 } 23053 this.#dropdown.lastElementChild?.focus(); 23054 } 23055 #keyDown(event) { 23056 ColorPicker._keyboardManager.exec(this, event); 23057 } 23058 #openDropdown(event) { 23059 if (this.#isDropdownVisible) { 23060 this.hideDropdown(); 23061 return; 23062 } 23063 this.#dropdownWasFromKeyboard = event.detail === 0; 23064 if (!this.#openDropdownAC) { 23065 this.#openDropdownAC = new AbortController(); 23066 window.addEventListener("pointerdown", this.#pointerDown.bind(this), { 23067 signal: this.#uiManager.combinedSignal(this.#openDropdownAC) 23068 }); 23069 } 23070 this.#button.ariaExpanded = "true"; 23071 if (this.#dropdown) { 23072 this.#dropdown.classList.remove("hidden"); 23073 return; 23074 } 23075 const root = this.#dropdown = this.#getDropdownRoot(); 23076 this.#button.append(root); 23077 } 23078 #pointerDown(event) { 23079 if (this.#dropdown?.contains(event.target)) { 23080 return; 23081 } 23082 this.hideDropdown(); 23083 } 23084 hideDropdown() { 23085 this.#dropdown?.classList.add("hidden"); 23086 this.#button.ariaExpanded = "false"; 23087 this.#openDropdownAC?.abort(); 23088 this.#openDropdownAC = null; 23089 } 23090 get #isDropdownVisible() { 23091 return this.#dropdown && !this.#dropdown.classList.contains("hidden"); 23092 } 23093 _hideDropdownFromKeyboard() { 23094 if (this.#isMainColorPicker) { 23095 return; 23096 } 23097 if (!this.#isDropdownVisible) { 23098 this.#editor?.unselect(); 23099 return; 23100 } 23101 this.hideDropdown(); 23102 this.#button.focus({ 23103 preventScroll: true, 23104 focusVisible: this.#dropdownWasFromKeyboard 23105 }); 23106 } 23107 updateColor(color) { 23108 if (this.#buttonSwatch) { 23109 this.#buttonSwatch.style.backgroundColor = color; 23110 } 23111 if (!this.#dropdown) { 23112 return; 23113 } 23114 const i = this.#uiManager.highlightColors.values(); 23115 for (const child of this.#dropdown.children) { 23116 child.ariaSelected = i.next().value === color.toUpperCase(); 23117 } 23118 } 23119 destroy() { 23120 this.#button?.remove(); 23121 this.#button = null; 23122 this.#buttonSwatch = null; 23123 this.#dropdown?.remove(); 23124 this.#dropdown = null; 23125 } 23126} 23127class BasicColorPicker { 23128 #input = null; 23129 #editor = null; 23130 #uiManager = null; 23131 static #l10nColor = null; 23132 constructor(editor) { 23133 this.#editor = editor; 23134 this.#uiManager = editor._uiManager; 23135 BasicColorPicker.#l10nColor ||= Object.freeze({ 23136 freetext: "pdfjs-editor-color-picker-free-text-input", 23137 ink: "pdfjs-editor-color-picker-ink-input" 23138 }); 23139 } 23140 renderButton() { 23141 if (this.#input) { 23142 return this.#input; 23143 } 23144 const { 23145 editorType, 23146 colorType, 23147 color 23148 } = this.#editor; 23149 const input = this.#input = document.createElement("input"); 23150 input.type = "color"; 23151 input.value = color || "#000000"; 23152 input.className = "basicColorPicker"; 23153 input.tabIndex = 0; 23154 input.setAttribute("data-l10n-id", BasicColorPicker.#l10nColor[editorType]); 23155 input.addEventListener("input", () => { 23156 this.#uiManager.updateParams(colorType, input.value); 23157 }, {
vendor: 17,901 bytes, lines 23158-23773
23158 signal: this.#uiManager._signal 23159 }); 23160 return input; 23161 } 23162 update(value) { 23163 if (!this.#input) { 23164 return; 23165 } 23166 this.#input.value = value; 23167 } 23168 destroy() { 23169 this.#input?.remove(); 23170 this.#input = null; 23171 } 23172 hideDropdown() {} 23173} 23174 23175// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.flat-map.js 23176var es_iterator_flat_map = __webpack_require__(531); 23177;// ./src/shared/scripting_utils.js 23178 23179 23180function makeColorComp(n) { 23181 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); 23182} 23183function scaleAndClamp(x) { 23184 return Math.max(0, Math.min(255, 255 * x)); 23185} 23186class ColorConverters { 23187 static CMYK_G([c, y, m, k]) { 23188 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)]; 23189 } 23190 static G_CMYK([g]) { 23191 return ["CMYK", 0, 0, 0, 1 - g]; 23192 } 23193 static G_RGB([g]) { 23194 return ["RGB", g, g, g]; 23195 } 23196 static G_rgb([g]) { 23197 g = scaleAndClamp(g); 23198 return [g, g, g]; 23199 } 23200 static G_HTML([g]) { 23201 const G = makeColorComp(g); 23202 return `#${G}${G}${G}`; 23203 } 23204 static RGB_G([r, g, b]) { 23205 return ["G", 0.3 * r + 0.59 * g + 0.11 * b]; 23206 } 23207 static RGB_rgb(color) { 23208 return color.map(scaleAndClamp); 23209 } 23210 static RGB_HTML(color) { 23211 return `#${color.map(makeColorComp).join("")}`; 23212 } 23213 static T_HTML() { 23214 return "#00000000"; 23215 } 23216 static T_rgb() { 23217 return [null]; 23218 } 23219 static CMYK_RGB([c, y, m, k]) { 23220 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)]; 23221 } 23222 static CMYK_rgb([c, y, m, k]) { 23223 return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))]; 23224 } 23225 static CMYK_HTML(components) { 23226 const rgb = this.CMYK_RGB(components).slice(1); 23227 return this.RGB_HTML(rgb); 23228 } 23229 static RGB_CMYK([r, g, b]) { 23230 const c = 1 - r; 23231 const m = 1 - g; 23232 const y = 1 - b; 23233 const k = Math.min(c, m, y); 23234 return ["CMYK", c, m, y, k]; 23235 } 23236} 23237const DateFormats = (/* unused pure expression or super */ null && (["m/d", "m/d/yy", "mm/dd/yy", "mm/yy", "d-mmm", "d-mmm-yy", "dd-mmm-yy", "yy-mm-dd", "mmm-yy", "mmmm-yy", "mmm d, yyyy", "mmmm d, yyyy", "m/d/yy h:MM tt", "m/d/yy HH:MM"])); 23238const TimeFormats = (/* unused pure expression or super */ null && (["HH:MM", "h:MM tt", "HH:MM:ss", "h:MM:ss tt"])); 23239 23240;// ./src/display/svg_factory.js 23241 23242 23243class BaseSVGFactory { 23244 create(width, height, skipDimensions = false) { 23245 if (width <= 0 || height <= 0) { 23246 throw new Error("Invalid SVG dimensions"); 23247 } 23248 const svg = this._createSVG("svg:svg"); 23249 svg.setAttribute("version", "1.1"); 23250 if (!skipDimensions) { 23251 svg.setAttribute("width", `${width}px`); 23252 svg.setAttribute("height", `${height}px`); 23253 } 23254 svg.setAttribute("preserveAspectRatio", "none"); 23255 svg.setAttribute("viewBox", `0 0 ${width} ${height}`); 23256 return svg; 23257 } 23258 createElement(type) { 23259 if (typeof type !== "string") { 23260 throw new Error("Invalid SVG element type"); 23261 } 23262 return this._createSVG(type); 23263 } 23264 _createSVG(type) { 23265 unreachable("Abstract method `_createSVG` called."); 23266 } 23267} 23268class DOMSVGFactory extends BaseSVGFactory { 23269 _createSVG(type) { 23270 return document.createElementNS(SVG_NS, type); 23271 } 23272} 23273 23274;// ./src/display/annotation_layer.js 23275 23276 23277 23278 23279 23280 23281 23282 23283 23284 23285 23286 23287 23288 23289 23290 23291 23292 23293 23294 23295const annotation_layer_DEFAULT_FONT_SIZE = 9; 23296const GetElementsByNameSet = new WeakSet(); 23297const TIMEZONE_OFFSET = new Date().getTimezoneOffset() * 60 * 1000; 23298class AnnotationElementFactory { 23299 static create(parameters) { 23300 const subtype = parameters.data.annotationType; 23301 switch (subtype) { 23302 case AnnotationType.LINK: 23303 return new LinkAnnotationElement(parameters); 23304 case AnnotationType.TEXT: 23305 return new TextAnnotationElement(parameters); 23306 case AnnotationType.WIDGET: 23307 const fieldType = parameters.data.fieldType; 23308 switch (fieldType) { 23309 case "Tx": 23310 return new TextWidgetAnnotationElement(parameters); 23311 case "Btn": 23312 if (parameters.data.radioButton) { 23313 return new RadioButtonWidgetAnnotationElement(parameters); 23314 } else if (parameters.data.checkBox) { 23315 return new CheckboxWidgetAnnotationElement(parameters); 23316 } 23317 return new PushButtonWidgetAnnotationElement(parameters); 23318 case "Ch": 23319 return new ChoiceWidgetAnnotationElement(parameters); 23320 case "Sig": 23321 return new SignatureWidgetAnnotationElement(parameters); 23322 } 23323 return new WidgetAnnotationElement(parameters); 23324 case AnnotationType.POPUP: 23325 return new PopupAnnotationElement(parameters); 23326 case AnnotationType.FREETEXT: 23327 return new FreeTextAnnotationElement(parameters); 23328 case AnnotationType.LINE: 23329 return new LineAnnotationElement(parameters); 23330 case AnnotationType.SQUARE: 23331 return new SquareAnnotationElement(parameters); 23332 case AnnotationType.CIRCLE: 23333 return new CircleAnnotationElement(parameters); 23334 case AnnotationType.POLYLINE: 23335 return new PolylineAnnotationElement(parameters); 23336 case AnnotationType.CARET: 23337 return new CaretAnnotationElement(parameters); 23338 case AnnotationType.INK: 23339 return new InkAnnotationElement(parameters); 23340 case AnnotationType.POLYGON: 23341 return new PolygonAnnotationElement(parameters); 23342 case AnnotationType.HIGHLIGHT: 23343 return new HighlightAnnotationElement(parameters); 23344 case AnnotationType.UNDERLINE: 23345 return new UnderlineAnnotationElement(parameters); 23346 case AnnotationType.SQUIGGLY: 23347 return new SquigglyAnnotationElement(parameters); 23348 case AnnotationType.STRIKEOUT: 23349 return new StrikeOutAnnotationElement(parameters); 23350 case AnnotationType.STAMP: 23351 return new StampAnnotationElement(parameters); 23352 case AnnotationType.FILEATTACHMENT: 23353 return new FileAttachmentAnnotationElement(parameters); 23354 default: 23355 return new AnnotationElement(parameters); 23356 } 23357 } 23358} 23359class AnnotationElement { 23360 #updates = null; 23361 #hasBorder = false; 23362 #popupElement = null; 23363 constructor(parameters, { 23364 isRenderable = false, 23365 ignoreBorder = false, 23366 createQuadrilaterals = false 23367 } = {}) { 23368 this.isRenderable = isRenderable; 23369 this.data = parameters.data; 23370 this.layer = parameters.layer; 23371 this.linkService = parameters.linkService; 23372 this.downloadManager = parameters.downloadManager; 23373 this.imageResourcesPath = parameters.imageResourcesPath; 23374 this.renderForms = parameters.renderForms; 23375 this.svgFactory = parameters.svgFactory; 23376 this.annotationStorage = parameters.annotationStorage; 23377 this.enableComment = parameters.enableComment; 23378 this.enableScripting = parameters.enableScripting; 23379 this.hasJSActions = parameters.hasJSActions; 23380 this._fieldObjects = parameters.fieldObjects; 23381 this.parent = parameters.parent; 23382 this.hasOwnCommentButton = false; 23383 if (isRenderable) { 23384 this.contentElement = this.container = this._createContainer(ignoreBorder); 23385 } 23386 if (createQuadrilaterals) { 23387 this._createQuadrilaterals(); 23388 } 23389 } 23390 static _hasPopupData({ 23391 contentsObj, 23392 richText 23393 }) { 23394 return !!(contentsObj?.str || richText?.str); 23395 } 23396 get _isEditable() { 23397 return this.data.isEditable; 23398 } 23399 get hasPopupData() { 23400 return AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText; 23401 } 23402 get commentData() { 23403 const { 23404 data 23405 } = this; 23406 const editor = this.annotationStorage?.getEditor(data.id); 23407 if (editor) { 23408 return editor.getData(); 23409 } 23410 return data; 23411 } 23412 get hasCommentButton() { 23413 return this.enableComment && this.hasPopupElement; 23414 } 23415 get commentButtonPosition() { 23416 const editor = this.annotationStorage?.getEditor(this.data.id); 23417 if (editor) { 23418 return editor.commentButtonPositionInPage; 23419 } 23420 const { 23421 quadPoints, 23422 inkLists, 23423 rect 23424 } = this.data; 23425 let maxX = -Infinity; 23426 let maxY = -Infinity; 23427 if (quadPoints?.length >= 8) { 23428 for (let i = 0; i < quadPoints.length; i += 8) { 23429 if (quadPoints[i + 1] > maxY) { 23430 maxY = quadPoints[i + 1]; 23431 maxX = quadPoints[i + 2]; 23432 } else if (quadPoints[i + 1] === maxY) { 23433 maxX = Math.max(maxX, quadPoints[i + 2]); 23434 } 23435 } 23436 return [maxX, maxY]; 23437 } 23438 if (inkLists?.length >= 1) { 23439 for (const inkList of inkLists) { 23440 for (let i = 0, ii = inkList.length; i < ii; i += 2) { 23441 if (inkList[i + 1] > maxY) { 23442 maxY = inkList[i + 1]; 23443 maxX = inkList[i]; 23444 } else if (inkList[i + 1] === maxY) { 23445 maxX = Math.max(maxX, inkList[i]); 23446 } 23447 } 23448 } 23449 if (maxX !== Infinity) { 23450 return [maxX, maxY]; 23451 } 23452 } 23453 if (rect) { 23454 return [rect[2], rect[3]]; 23455 } 23456 return null; 23457 } 23458 _normalizePoint(point) { 23459 const { 23460 page: { 23461 view 23462 }, 23463 viewport: { 23464 rawDims: { 23465 pageWidth, 23466 pageHeight, 23467 pageX, 23468 pageY 23469 } 23470 } 23471 } = this.parent; 23472 point[1] = view[3] - point[1] + view[1]; 23473 point[0] = 100 * (point[0] - pageX) / pageWidth; 23474 point[1] = 100 * (point[1] - pageY) / pageHeight; 23475 return point; 23476 } 23477 get commentText() { 23478 const { 23479 data 23480 } = this; 23481 return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || ""; 23482 } 23483 set commentText(text) { 23484 const { 23485 data 23486 } = this; 23487 const popup = { 23488 deleted: !text, 23489 contents: text || "" 23490 }; 23491 if (!this.annotationStorage.updateEditor(data.id, { 23492 popup 23493 })) { 23494 this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, { 23495 id: data.id, 23496 annotationType: data.annotationType, 23497 page: this.parent.page, 23498 popup, 23499 popupRef: data.popupRef, 23500 modificationDate: new Date() 23501 }); 23502 } 23503 if (!text) { 23504 this.removePopup(); 23505 } 23506 } 23507 removePopup() { 23508 (this.#popupElement?.popup || this.popup)?.remove(); 23509 this.#popupElement = this.popup = null; 23510 } 23511 updateEdited(params) { 23512 if (!this.container) { 23513 return; 23514 } 23515 if (params.rect) { 23516 this.#updates ||= { 23517 rect: this.data.rect.slice(0) 23518 }; 23519 } 23520 const { 23521 rect, 23522 popup: newPopup 23523 } = params; 23524 if (rect) { 23525 this.#setRectEdited(rect); 23526 } 23527 let popup = this.#popupElement?.popup || this.popup; 23528 if (!popup && newPopup?.text) { 23529 this._createPopup(newPopup); 23530 popup = this.#popupElement.popup; 23531 } 23532 if (!popup) { 23533 return; 23534 } 23535 popup.updateEdited(params); 23536 if (newPopup?.deleted) { 23537 popup.remove(); 23538 this.#popupElement = null; 23539 this.popup = null; 23540 } 23541 } 23542 resetEdited() { 23543 if (!this.#updates) { 23544 return; 23545 } 23546 this.#setRectEdited(this.#updates.rect); 23547 this.#popupElement?.popup.resetEdited(); 23548 this.#updates = null; 23549 } 23550 #setRectEdited(rect) { 23551 const { 23552 container: { 23553 style 23554 }, 23555 data: { 23556 rect: currentRect, 23557 rotation 23558 }, 23559 parent: { 23560 viewport: { 23561 rawDims: { 23562 pageWidth, 23563 pageHeight, 23564 pageX, 23565 pageY 23566 } 23567 } 23568 } 23569 } = this; 23570 currentRect?.splice(0, 4, ...rect); 23571 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; 23572 style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`; 23573 if (rotation === 0) { 23574 style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`; 23575 style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`; 23576 } else { 23577 this.setRotation(rotation); 23578 } 23579 } 23580 _createContainer(ignoreBorder) { 23581 const { 23582 data, 23583 parent: { 23584 page, 23585 viewport 23586 } 23587 } = this; 23588 const container = document.createElement("section"); 23589 container.setAttribute("data-annotation-id", data.id); 23590 if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) { 23591 container.tabIndex = 0; 23592 } 23593 const { 23594 style 23595 } = container; 23596 style.zIndex = this.parent.zIndex; 23597 this.parent.zIndex += 2; 23598 if (data.alternativeText) { 23599 container.title = data.alternativeText; 23600 } 23601 if (data.noRotate) { 23602 container.classList.add("norotate"); 23603 } 23604 if (!data.rect || this instanceof PopupAnnotationElement) { 23605 const { 23606 rotation 23607 } = data; 23608 if (!data.hasOwnCanvas && rotation !== 0) { 23609 this.setRotation(rotation, container); 23610 } 23611 return container; 23612 } 23613 const { 23614 width, 23615 height 23616 } = this; 23617 if (!ignoreBorder && data.borderStyle.width > 0) { 23618 style.borderWidth = `${data.borderStyle.width}px`; 23619 const horizontalRadius = data.borderStyle.horizontalCornerRadius; 23620 const verticalRadius = data.borderStyle.verticalCornerRadius; 23621 if (horizontalRadius > 0 || verticalRadius > 0) { 23622 const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`; 23623 style.borderRadius = radius; 23624 } else if (this instanceof RadioButtonWidgetAnnotationElement) { 23625 const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`; 23626 style.borderRadius = radius; 23627 } 23628 switch (data.borderStyle.style) { 23629 case AnnotationBorderStyleType.SOLID: 23630 style.borderStyle = "solid"; 23631 break; 23632 case AnnotationBorderStyleType.DASHED: 23633 style.borderStyle = "dashed"; 23634 break; 23635 case AnnotationBorderStyleType.BEVELED: 23636 warn("Unimplemented border style: beveled"); 23637 break; 23638 case AnnotationBorderStyleType.INSET: 23639 warn("Unimplemented border style: inset"); 23640 break; 23641 case AnnotationBorderStyleType.UNDERLINE: 23642 style.borderBottomStyle = "solid"; 23643 break; 23644 default: 23645 break; 23646 } 23647 const borderColor = data.borderColor || null; 23648 if (borderColor) { 23649 this.#hasBorder = true; 23650 style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); 23651 } else { 23652 style.borderWidth = 0; 23653 } 23654 } 23655 const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]); 23656 const { 23657 pageWidth, 23658 pageHeight, 23659 pageX, 23660 pageY 23661 } = viewport.rawDims; 23662 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; 23663 style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; 23664 const { 23665 rotation 23666 } = data; 23667 if (data.hasOwnCanvas || rotation === 0) { 23668 style.width = `${100 * width / pageWidth}%`; 23669 style.height = `${100 * height / pageHeight}%`; 23670 } else { 23671 this.setRotation(rotation, container); 23672 } 23673 return container; 23674 } 23675 setRotation(angle, container = this.container) { 23676 if (!this.data.rect) { 23677 return; 23678 } 23679 const { 23680 pageWidth, 23681 pageHeight 23682 } = this.parent.viewport.rawDims; 23683 let { 23684 width, 23685 height 23686 } = this; 23687 if (angle % 180 !== 0) { 23688 [width, height] = [height, width]; 23689 } 23690 container.style.width = `${100 * width / pageWidth}%`; 23691 container.style.height = `${100 * height / pageHeight}%`; 23692 container.setAttribute("data-main-rotation", (360 - angle) % 360); 23693 } 23694 get _commonActions() { 23695 const setColor = (jsName, styleName, event) => { 23696 const color = event.detail[jsName]; 23697 const colorType = color[0]; 23698 const colorArray = color.slice(1); 23699 event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray); 23700 this.annotationStorage.setValue(this.data.id, { 23701 [styleName]: ColorConverters[`${colorType}_rgb`](colorArray) 23702 }); 23703 }; 23704 return shadow(this, "_commonActions", { 23705 display: event => { 23706 const { 23707 display 23708 } = event.detail; 23709 const hidden = display % 2 === 1; 23710 this.container.style.visibility = hidden ? "hidden" : "visible"; 23711 this.annotationStorage.setValue(this.data.id, { 23712 noView: hidden, 23713 noPrint: display === 1 || display === 2 23714 }); 23715 }, 23716 print: event => { 23717 this.annotationStorage.setValue(this.data.id, { 23718 noPrint: !event.detail.print 23719 }); 23720 }, 23721 hidden: event => { 23722 const { 23723 hidden 23724 } = event.detail; 23725 this.container.style.visibility = hidden ? "hidden" : "visible"; 23726 this.annotationStorage.setValue(this.data.id, { 23727 noPrint: hidden, 23728 noView: hidden 23729 }); 23730 }, 23731 focus: event => { 23732 setTimeout(() => event.target.focus({ 23733 preventScroll: false 23734 }), 0); 23735 }, 23736 userName: event => { 23737 event.target.title = event.detail.userName; 23738 }, 23739 readonly: event => { 23740 event.target.disabled = event.detail.readonly; 23741 }, 23742 required: event => { 23743 this._setRequired(event.target, event.detail.required); 23744 }, 23745 bgColor: event => { 23746 setColor("bgColor", "backgroundColor", event); 23747 }, 23748 fillColor: event => { 23749 setColor("fillColor", "backgroundColor", event); 23750 }, 23751 fgColor: event => { 23752 setColor("fgColor", "color", event); 23753 }, 23754 textColor: event => { 23755 setColor("textColor", "color", event); 23756 }, 23757 borderColor: event => { 23758 setColor("borderColor", "borderColor", event); 23759 }, 23760 strokeColor: event => { 23761 setColor("strokeColor", "borderColor", event); 23762 }, 23763 rotation: event => { 23764 const angle = event.detail.rotation; 23765 this.setRotation(angle); 23766 this.annotationStorage.setValue(this.data.id, { 23767 rotation: angle 23768 }); 23769 } 23770 }); 23771 } 23772 _dispatchEventFromSandbox(actions, jsEvent) { 23773 const commonActions = this._commonActions;
vendor: 18,366 bytes, lines 23774-24401
23774 for (const name of Object.keys(jsEvent.detail)) { 23775 const action = actions[name] || commonActions[name]; 23776 action?.(jsEvent); 23777 } 23778 } 23779 _setDefaultPropertiesFromJS(element) { 23780 if (!this.enableScripting) { 23781 return; 23782 } 23783 const storedData = this.annotationStorage.getRawValue(this.data.id); 23784 if (!storedData) { 23785 return; 23786 } 23787 const commonActions = this._commonActions; 23788 for (const [actionName, detail] of Object.entries(storedData)) { 23789 const action = commonActions[actionName]; 23790 if (action) { 23791 const eventProxy = { 23792 detail: { 23793 [actionName]: detail 23794 }, 23795 target: element 23796 }; 23797 action(eventProxy); 23798 delete storedData[actionName]; 23799 } 23800 } 23801 } 23802 _createQuadrilaterals() { 23803 if (!this.container) { 23804 return; 23805 } 23806 const { 23807 quadPoints 23808 } = this.data; 23809 if (!quadPoints) { 23810 return; 23811 } 23812 const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x)); 23813 if (quadPoints.length === 8) { 23814 const [trX, trY, blX, blY] = quadPoints.subarray(2, 6); 23815 if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { 23816 return; 23817 } 23818 } 23819 const { 23820 style 23821 } = this.container; 23822 let svgBuffer; 23823 if (this.#hasBorder) { 23824 const { 23825 borderColor, 23826 borderWidth 23827 } = style; 23828 style.borderWidth = 0; 23829 svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`]; 23830 this.container.classList.add("hasBorder"); 23831 } 23832 const width = rectTrX - rectBlX; 23833 const height = rectTrY - rectBlY; 23834 const { 23835 svgFactory 23836 } = this; 23837 const svg = svgFactory.createElement("svg"); 23838 svg.classList.add("quadrilateralsContainer"); 23839 svg.setAttribute("width", 0); 23840 svg.setAttribute("height", 0); 23841 svg.role = "none"; 23842 const defs = svgFactory.createElement("defs"); 23843 svg.append(defs); 23844 const clipPath = svgFactory.createElement("clipPath"); 23845 const id = `clippath_${this.data.id}`; 23846 clipPath.setAttribute("id", id); 23847 clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); 23848 defs.append(clipPath); 23849 for (let i = 2, ii = quadPoints.length; i < ii; i += 8) { 23850 const trX = quadPoints[i]; 23851 const trY = quadPoints[i + 1]; 23852 const blX = quadPoints[i + 2]; 23853 const blY = quadPoints[i + 3]; 23854 const rect = svgFactory.createElement("rect"); 23855 const x = (blX - rectBlX) / width; 23856 const y = (rectTrY - trY) / height; 23857 const rectWidth = (trX - blX) / width; 23858 const rectHeight = (trY - blY) / height; 23859 rect.setAttribute("x", x); 23860 rect.setAttribute("y", y); 23861 rect.setAttribute("width", rectWidth); 23862 rect.setAttribute("height", rectHeight); 23863 clipPath.append(rect); 23864 svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`); 23865 } 23866 if (this.#hasBorder) { 23867 svgBuffer.push(`</g></svg>')`); 23868 style.backgroundImage = svgBuffer.join(""); 23869 } 23870 this.container.append(svg); 23871 this.container.style.clipPath = `url(#${id})`; 23872 } 23873 _createPopup(popupData = null) { 23874 const { 23875 data 23876 } = this; 23877 let contentsObj, modificationDate; 23878 if (popupData) { 23879 contentsObj = { 23880 str: popupData.text 23881 }; 23882 modificationDate = popupData.date; 23883 } else { 23884 contentsObj = data.contentsObj; 23885 modificationDate = data.modificationDate; 23886 } 23887 this.#popupElement = new PopupAnnotationElement({ 23888 data: { 23889 color: data.color, 23890 titleObj: data.titleObj, 23891 modificationDate, 23892 contentsObj, 23893 richText: data.richText, 23894 parentRect: data.rect, 23895 borderStyle: 0, 23896 id: `popup_${data.id}`, 23897 rotation: data.rotation, 23898 noRotate: true 23899 }, 23900 linkService: this.linkService, 23901 parent: this.parent, 23902 elements: [this] 23903 }); 23904 } 23905 get hasPopupElement() { 23906 return !!(this.#popupElement || this.popup || this.data.popupRef); 23907 } 23908 get extraPopupElement() { 23909 return this.#popupElement; 23910 } 23911 render() { 23912 unreachable("Abstract method `AnnotationElement.render` called"); 23913 } 23914 _getElementsByName(name, skipId = null) { 23915 const fields = []; 23916 if (this._fieldObjects) { 23917 const fieldObj = this._fieldObjects[name]; 23918 if (fieldObj) { 23919 for (const { 23920 page, 23921 id, 23922 exportValues 23923 } of fieldObj) { 23924 if (page === -1) { 23925 continue; 23926 } 23927 if (id === skipId) { 23928 continue; 23929 } 23930 const exportValue = typeof exportValues === "string" ? exportValues : null; 23931 const domElement = document.querySelector(`[data-element-id="${id}"]`); 23932 if (domElement && !GetElementsByNameSet.has(domElement)) { 23933 warn(`_getElementsByName - element not allowed: ${id}`); 23934 continue; 23935 } 23936 fields.push({ 23937 id, 23938 exportValue, 23939 domElement 23940 }); 23941 } 23942 } 23943 return fields; 23944 } 23945 for (const domElement of document.getElementsByName(name)) { 23946 const { 23947 exportValue 23948 } = domElement; 23949 const id = domElement.getAttribute("data-element-id"); 23950 if (id === skipId) { 23951 continue; 23952 } 23953 if (!GetElementsByNameSet.has(domElement)) { 23954 continue; 23955 } 23956 fields.push({ 23957 id, 23958 exportValue, 23959 domElement 23960 }); 23961 } 23962 return fields; 23963 } 23964 show() { 23965 if (this.container) { 23966 this.container.hidden = false; 23967 } 23968 this.popup?.maybeShow(); 23969 } 23970 hide() { 23971 if (this.container) { 23972 this.container.hidden = true; 23973 } 23974 this.popup?.forceHide(); 23975 } 23976 getElementsToTriggerPopup() { 23977 return this.container; 23978 } 23979 addHighlightArea() { 23980 const triggers = this.getElementsToTriggerPopup(); 23981 if (Array.isArray(triggers)) { 23982 for (const element of triggers) { 23983 element.classList.add("highlightArea"); 23984 } 23985 } else { 23986 triggers.classList.add("highlightArea"); 23987 } 23988 } 23989 _editOnDoubleClick() { 23990 if (!this._isEditable) { 23991 return; 23992 } 23993 const { 23994 annotationEditorType: mode, 23995 data: { 23996 id: editId 23997 } 23998 } = this; 23999 this.container.addEventListener("dblclick", () => { 24000 this.linkService.eventBus?.dispatch("switchannotationeditormode", { 24001 source: this, 24002 mode, 24003 editId, 24004 mustEnterInEditMode: true 24005 }); 24006 }); 24007 } 24008 get width() { 24009 return this.data.rect[2] - this.data.rect[0]; 24010 } 24011 get height() { 24012 return this.data.rect[3] - this.data.rect[1]; 24013 } 24014} 24015class EditorAnnotationElement extends AnnotationElement { 24016 constructor(parameters) { 24017 super(parameters, { 24018 isRenderable: true, 24019 ignoreBorder: true 24020 }); 24021 this.editor = parameters.editor; 24022 } 24023 render() { 24024 this.container.className = "editorAnnotation"; 24025 return this.container; 24026 } 24027 createOrUpdatePopup() { 24028 const { 24029 editor 24030 } = this; 24031 if (!editor.hasComment) { 24032 return; 24033 } 24034 this._createPopup(editor.comment); 24035 } 24036 get hasCommentButton() { 24037 return this.enableComment && this.editor.hasComment; 24038 } 24039 get commentButtonPosition() { 24040 return this.editor.commentButtonPositionInPage; 24041 } 24042 get commentText() { 24043 return this.editor.comment.text; 24044 } 24045 set commentText(text) { 24046 this.editor.comment = text; 24047 if (!text) { 24048 this.removePopup(); 24049 } 24050 } 24051 get commentData() { 24052 return this.editor.getData(); 24053 } 24054 remove() { 24055 this.parent.removeAnnotation(this.data.id); 24056 this.container.remove(); 24057 this.container = null; 24058 this.removePopup(); 24059 } 24060} 24061class LinkAnnotationElement extends AnnotationElement { 24062 constructor(parameters, options = null) { 24063 super(parameters, { 24064 isRenderable: true, 24065 ignoreBorder: !!options?.ignoreBorder, 24066 createQuadrilaterals: true 24067 }); 24068 this.isTooltipOnly = parameters.data.isTooltipOnly; 24069 } 24070 render() { 24071 const { 24072 data, 24073 linkService 24074 } = this; 24075 const link = document.createElement("a"); 24076 link.setAttribute("data-element-id", data.id); 24077 let isBound = false; 24078 if (data.url) { 24079 linkService.addLinkAttributes(link, data.url, data.newWindow); 24080 isBound = true; 24081 } else if (data.action) { 24082 this._bindNamedAction(link, data.action, data.overlaidText); 24083 isBound = true; 24084 } else if (data.attachment) { 24085 this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest); 24086 isBound = true; 24087 } else if (data.setOCGState) { 24088 this.#bindSetOCGState(link, data.setOCGState, data.overlaidText); 24089 isBound = true; 24090 } else if (data.dest) { 24091 this._bindLink(link, data.dest, data.overlaidText); 24092 isBound = true; 24093 } else { 24094 if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { 24095 this._bindJSAction(link, data); 24096 isBound = true; 24097 } 24098 if (data.resetForm) { 24099 this._bindResetFormAction(link, data.resetForm); 24100 isBound = true; 24101 } else if (this.isTooltipOnly && !isBound) { 24102 this._bindLink(link, ""); 24103 isBound = true; 24104 } 24105 } 24106 this.container.classList.add("linkAnnotation"); 24107 if (isBound) { 24108 this.contentElement = link; 24109 this.container.append(link); 24110 } 24111 return this.container; 24112 } 24113 #setInternalLink() { 24114 this.container.setAttribute("data-internal-link", ""); 24115 } 24116 _bindLink(link, destination, overlaidText = "") { 24117 link.href = this.linkService.getDestinationHash(destination); 24118 link.onclick = () => { 24119 if (destination) { 24120 this.linkService.goToDestination(destination); 24121 } 24122 return false; 24123 }; 24124 if (destination || destination === "") { 24125 this.#setInternalLink(); 24126 } 24127 if (overlaidText) { 24128 link.title = overlaidText; 24129 } 24130 } 24131 _bindNamedAction(link, action, overlaidText = "") { 24132 link.href = this.linkService.getAnchorUrl(""); 24133 link.onclick = () => { 24134 this.linkService.executeNamedAction(action); 24135 return false; 24136 }; 24137 if (overlaidText) { 24138 link.title = overlaidText; 24139 } 24140 this.#setInternalLink(); 24141 } 24142 #bindAttachment(link, attachment, overlaidText = "", dest = null) { 24143 link.href = this.linkService.getAnchorUrl(""); 24144 if (attachment.description) { 24145 link.title = attachment.description; 24146 } else if (overlaidText) { 24147 link.title = overlaidText; 24148 } 24149 link.onclick = () => { 24150 this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest); 24151 return false; 24152 }; 24153 this.#setInternalLink(); 24154 } 24155 #bindSetOCGState(link, action, overlaidText = "") { 24156 link.href = this.linkService.getAnchorUrl(""); 24157 link.onclick = () => { 24158 this.linkService.executeSetOCGState(action); 24159 return false; 24160 }; 24161 if (overlaidText) { 24162 link.title = overlaidText; 24163 } 24164 this.#setInternalLink(); 24165 } 24166 _bindJSAction(link, data) { 24167 link.href = this.linkService.getAnchorUrl(""); 24168 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); 24169 for (const name of Object.keys(data.actions)) { 24170 const jsName = map.get(name); 24171 if (!jsName) { 24172 continue; 24173 } 24174 link[jsName] = () => { 24175 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24176 source: this, 24177 detail: { 24178 id: data.id, 24179 name 24180 } 24181 }); 24182 return false; 24183 }; 24184 } 24185 if (data.overlaidText) { 24186 link.title = data.overlaidText; 24187 } 24188 if (!link.onclick) { 24189 link.onclick = () => false; 24190 } 24191 this.#setInternalLink(); 24192 } 24193 _bindResetFormAction(link, resetForm) { 24194 const otherClickAction = link.onclick; 24195 if (!otherClickAction) { 24196 link.href = this.linkService.getAnchorUrl(""); 24197 } 24198 this.#setInternalLink(); 24199 if (!this._fieldObjects) { 24200 warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided."); 24201 if (!otherClickAction) { 24202 link.onclick = () => false; 24203 } 24204 return; 24205 } 24206 link.onclick = () => { 24207 otherClickAction?.(); 24208 const { 24209 fields: resetFormFields, 24210 refs: resetFormRefs, 24211 include 24212 } = resetForm; 24213 const allFields = []; 24214 if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { 24215 const fieldIds = new Set(resetFormRefs); 24216 for (const fieldName of resetFormFields) { 24217 const fields = this._fieldObjects[fieldName] || []; 24218 for (const { 24219 id 24220 } of fields) { 24221 fieldIds.add(id); 24222 } 24223 } 24224 for (const fields of Object.values(this._fieldObjects)) { 24225 for (const field of fields) { 24226 if (fieldIds.has(field.id) === include) { 24227 allFields.push(field); 24228 } 24229 } 24230 } 24231 } else { 24232 for (const fields of Object.values(this._fieldObjects)) { 24233 allFields.push(...fields); 24234 } 24235 } 24236 const storage = this.annotationStorage; 24237 const allIds = []; 24238 for (const field of allFields) { 24239 const { 24240 id 24241 } = field; 24242 allIds.push(id); 24243 switch (field.type) { 24244 case "text": 24245 { 24246 const value = field.defaultValue || ""; 24247 storage.setValue(id, { 24248 value 24249 }); 24250 break; 24251 } 24252 case "checkbox": 24253 case "radiobutton": 24254 { 24255 const value = field.defaultValue === field.exportValues; 24256 storage.setValue(id, { 24257 value 24258 }); 24259 break; 24260 } 24261 case "combobox": 24262 case "listbox": 24263 { 24264 const value = field.defaultValue || ""; 24265 storage.setValue(id, { 24266 value 24267 }); 24268 break; 24269 } 24270 default: 24271 continue; 24272 } 24273 const domElement = document.querySelector(`[data-element-id="${id}"]`); 24274 if (!domElement) { 24275 continue; 24276 } else if (!GetElementsByNameSet.has(domElement)) { 24277 warn(`_bindResetFormAction - element not allowed: ${id}`); 24278 continue; 24279 } 24280 domElement.dispatchEvent(new Event("resetform")); 24281 } 24282 if (this.enableScripting) { 24283 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24284 source: this, 24285 detail: { 24286 id: "app", 24287 ids: allIds, 24288 name: "ResetForm" 24289 } 24290 }); 24291 } 24292 return false; 24293 }; 24294 } 24295} 24296class TextAnnotationElement extends AnnotationElement { 24297 constructor(parameters) { 24298 super(parameters, { 24299 isRenderable: true 24300 }); 24301 } 24302 render() { 24303 this.container.classList.add("textAnnotation"); 24304 const image = document.createElement("img"); 24305 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; 24306 image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type"); 24307 image.setAttribute("data-l10n-args", JSON.stringify({ 24308 type: this.data.name 24309 })); 24310 if (!this.data.popupRef && this.hasPopupData) { 24311 this.hasOwnCommentButton = true; 24312 this._createPopup(); 24313 } 24314 this.container.append(image); 24315 return this.container; 24316 } 24317} 24318class WidgetAnnotationElement extends AnnotationElement { 24319 render() { 24320 return this.container; 24321 } 24322 showElementAndHideCanvas(element) { 24323 if (this.data.hasOwnCanvas) { 24324 if (element.previousSibling?.nodeName === "CANVAS") { 24325 element.previousSibling.hidden = true; 24326 } 24327 element.hidden = false; 24328 } 24329 } 24330 _getKeyModifier(event) { 24331 return FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey; 24332 } 24333 _setEventListener(element, elementData, baseName, eventName, valueGetter) { 24334 if (baseName.includes("mouse")) { 24335 element.addEventListener(baseName, event => { 24336 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24337 source: this, 24338 detail: { 24339 id: this.data.id, 24340 name: eventName, 24341 value: valueGetter(event), 24342 shift: event.shiftKey, 24343 modifier: this._getKeyModifier(event) 24344 } 24345 }); 24346 }); 24347 } else { 24348 element.addEventListener(baseName, event => { 24349 if (baseName === "blur") { 24350 if (!elementData.focused || !event.relatedTarget) { 24351 return; 24352 } 24353 elementData.focused = false; 24354 } else if (baseName === "focus") { 24355 if (elementData.focused) { 24356 return; 24357 } 24358 elementData.focused = true; 24359 } 24360 if (!valueGetter) { 24361 return; 24362 } 24363 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24364 source: this, 24365 detail: { 24366 id: this.data.id, 24367 name: eventName, 24368 value: valueGetter(event) 24369 } 24370 }); 24371 }); 24372 } 24373 } 24374 _setEventListeners(element, elementData, names, getter) { 24375 for (const [baseName, eventName] of names) { 24376 if (eventName === "Action" || this.data.actions?.[eventName]) { 24377 if (eventName === "Focus" || eventName === "Blur") { 24378 elementData ||= { 24379 focused: false 24380 }; 24381 } 24382 this._setEventListener(element, elementData, baseName, eventName, getter); 24383 if (eventName === "Focus" && !this.data.actions?.Blur) { 24384 this._setEventListener(element, elementData, "blur", "Blur", null); 24385 } else if (eventName === "Blur" && !this.data.actions?.Focus) { 24386 this._setEventListener(element, elementData, "focus", "Focus", null); 24387 } 24388 } 24389 } 24390 } 24391 _setBackgroundColor(element) { 24392 const color = this.data.backgroundColor || null; 24393 element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]); 24394 } 24395 _setTextStyle(element) { 24396 const TEXT_ALIGNMENT = ["left", "center", "right"]; 24397 const { 24398 fontColor 24399 } = this.data.defaultAppearanceData; 24400 const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE; 24401 const style = element.style;
vendor: 33,566 bytes, lines 24402-25381
24402 let computedFontSize; 24403 const BORDER_SIZE = 2; 24404 const roundToOneDecimal = x => Math.round(10 * x) / 10; 24405 if (this.data.multiLine) { 24406 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); 24407 const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1; 24408 const lineHeight = height / numberOfLines; 24409 computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR)); 24410 } else { 24411 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); 24412 computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR)); 24413 } 24414 style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`; 24415 style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); 24416 if (this.data.textAlignment !== null) { 24417 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; 24418 } 24419 } 24420 _setRequired(element, isRequired) { 24421 if (isRequired) { 24422 element.setAttribute("required", true); 24423 } else { 24424 element.removeAttribute("required"); 24425 } 24426 element.setAttribute("aria-required", isRequired); 24427 } 24428} 24429class TextWidgetAnnotationElement extends WidgetAnnotationElement { 24430 constructor(parameters) { 24431 const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue; 24432 super(parameters, { 24433 isRenderable 24434 }); 24435 } 24436 setPropertyOnSiblings(base, key, value, keyInStorage) { 24437 const storage = this.annotationStorage; 24438 for (const element of this._getElementsByName(base.name, base.id)) { 24439 if (element.domElement) { 24440 element.domElement[key] = value; 24441 } 24442 storage.setValue(element.id, { 24443 [keyInStorage]: value 24444 }); 24445 } 24446 } 24447 render() { 24448 const storage = this.annotationStorage; 24449 const id = this.data.id; 24450 this.container.classList.add("textWidgetAnnotation"); 24451 let element = null; 24452 if (this.renderForms) { 24453 const storedData = storage.getValue(id, { 24454 value: this.data.fieldValue 24455 }); 24456 let textContent = storedData.value || ""; 24457 const maxLen = storage.getValue(id, { 24458 charLimit: this.data.maxLen 24459 }).charLimit; 24460 if (maxLen && textContent.length > maxLen) { 24461 textContent = textContent.slice(0, maxLen); 24462 } 24463 let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; 24464 if (fieldFormattedValues && this.data.comb) { 24465 fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); 24466 } 24467 const elementData = { 24468 userValue: textContent, 24469 formattedValue: fieldFormattedValues, 24470 lastCommittedValue: null, 24471 commitKey: 1, 24472 focused: false 24473 }; 24474 if (this.data.multiLine) { 24475 element = document.createElement("textarea"); 24476 element.textContent = fieldFormattedValues ?? textContent; 24477 if (this.data.doNotScroll) { 24478 element.style.overflowY = "hidden"; 24479 } 24480 } else { 24481 element = document.createElement("input"); 24482 element.type = this.data.password ? "password" : "text"; 24483 element.setAttribute("value", fieldFormattedValues ?? textContent); 24484 if (this.data.doNotScroll) { 24485 element.style.overflowX = "hidden"; 24486 } 24487 } 24488 if (this.data.hasOwnCanvas) { 24489 element.hidden = true; 24490 } 24491 GetElementsByNameSet.add(element); 24492 this.contentElement = element; 24493 element.setAttribute("data-element-id", id); 24494 element.disabled = this.data.readOnly; 24495 element.name = this.data.fieldName; 24496 element.tabIndex = 0; 24497 const { 24498 datetimeFormat, 24499 datetimeType, 24500 timeStep 24501 } = this.data; 24502 const hasDateOrTime = !!datetimeType && this.enableScripting; 24503 if (datetimeFormat) { 24504 element.title = datetimeFormat; 24505 } 24506 this._setRequired(element, this.data.required); 24507 if (maxLen) { 24508 element.maxLength = maxLen; 24509 } 24510 element.addEventListener("input", event => { 24511 storage.setValue(id, { 24512 value: event.target.value 24513 }); 24514 this.setPropertyOnSiblings(element, "value", event.target.value, "value"); 24515 elementData.formattedValue = null; 24516 }); 24517 element.addEventListener("resetform", event => { 24518 const defaultValue = this.data.defaultFieldValue ?? ""; 24519 element.value = elementData.userValue = defaultValue; 24520 elementData.formattedValue = null; 24521 }); 24522 let blurListener = event => { 24523 const { 24524 formattedValue 24525 } = elementData; 24526 if (formattedValue !== null && formattedValue !== undefined) { 24527 event.target.value = formattedValue; 24528 } 24529 event.target.scrollLeft = 0; 24530 }; 24531 if (this.enableScripting && this.hasJSActions) { 24532 element.addEventListener("focus", event => { 24533 if (elementData.focused) { 24534 return; 24535 } 24536 const { 24537 target 24538 } = event; 24539 if (hasDateOrTime) { 24540 target.type = datetimeType; 24541 if (timeStep) { 24542 target.step = timeStep; 24543 } 24544 } 24545 if (elementData.userValue) { 24546 const value = elementData.userValue; 24547 if (hasDateOrTime) { 24548 if (datetimeType === "time") { 24549 const date = new Date(value); 24550 const parts = [date.getHours(), date.getMinutes(), date.getSeconds()]; 24551 target.value = parts.map(v => v.toString().padStart(2, "0")).join(":"); 24552 } else { 24553 target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0]; 24554 } 24555 } else { 24556 target.value = value; 24557 } 24558 } 24559 elementData.lastCommittedValue = target.value; 24560 elementData.commitKey = 1; 24561 if (!this.data.actions?.Focus) { 24562 elementData.focused = true; 24563 } 24564 }); 24565 element.addEventListener("updatefromsandbox", jsEvent => { 24566 this.showElementAndHideCanvas(jsEvent.target); 24567 const actions = { 24568 value(event) { 24569 elementData.userValue = event.detail.value ?? ""; 24570 if (!hasDateOrTime) { 24571 storage.setValue(id, { 24572 value: elementData.userValue.toString() 24573 }); 24574 } 24575 event.target.value = elementData.userValue; 24576 }, 24577 formattedValue(event) { 24578 const { 24579 formattedValue 24580 } = event.detail; 24581 elementData.formattedValue = formattedValue; 24582 if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) { 24583 event.target.value = formattedValue; 24584 } 24585 const data = { 24586 formattedValue 24587 }; 24588 if (hasDateOrTime) { 24589 data.value = formattedValue; 24590 } 24591 storage.setValue(id, data); 24592 }, 24593 selRange(event) { 24594 event.target.setSelectionRange(...event.detail.selRange); 24595 }, 24596 charLimit: event => { 24597 const { 24598 charLimit 24599 } = event.detail; 24600 const { 24601 target 24602 } = event; 24603 if (charLimit === 0) { 24604 target.removeAttribute("maxLength"); 24605 return; 24606 } 24607 target.setAttribute("maxLength", charLimit); 24608 let value = elementData.userValue; 24609 if (!value || value.length <= charLimit) { 24610 return; 24611 } 24612 value = value.slice(0, charLimit); 24613 target.value = elementData.userValue = value; 24614 storage.setValue(id, { 24615 value 24616 }); 24617 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24618 source: this, 24619 detail: { 24620 id, 24621 name: "Keystroke", 24622 value, 24623 willCommit: true, 24624 commitKey: 1, 24625 selStart: target.selectionStart, 24626 selEnd: target.selectionEnd 24627 } 24628 }); 24629 } 24630 }; 24631 this._dispatchEventFromSandbox(actions, jsEvent); 24632 }); 24633 element.addEventListener("keydown", event => { 24634 elementData.commitKey = 1; 24635 let commitKey = -1; 24636 if (event.key === "Escape") { 24637 commitKey = 0; 24638 } else if (event.key === "Enter" && !this.data.multiLine) { 24639 commitKey = 2; 24640 } else if (event.key === "Tab") { 24641 elementData.commitKey = 3; 24642 } 24643 if (commitKey === -1) { 24644 return; 24645 } 24646 const { 24647 value 24648 } = event.target; 24649 if (elementData.lastCommittedValue === value) { 24650 return; 24651 } 24652 elementData.lastCommittedValue = value; 24653 elementData.userValue = value; 24654 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24655 source: this, 24656 detail: { 24657 id, 24658 name: "Keystroke", 24659 value, 24660 willCommit: true, 24661 commitKey, 24662 selStart: event.target.selectionStart, 24663 selEnd: event.target.selectionEnd 24664 } 24665 }); 24666 }); 24667 const _blurListener = blurListener; 24668 blurListener = null; 24669 element.addEventListener("blur", event => { 24670 if (!elementData.focused || !event.relatedTarget) { 24671 return; 24672 } 24673 if (!this.data.actions?.Blur) { 24674 elementData.focused = false; 24675 } 24676 const { 24677 target 24678 } = event; 24679 let { 24680 value 24681 } = target; 24682 if (hasDateOrTime) { 24683 if (value && datetimeType === "time") { 24684 const parts = value.split(":").map(v => parseInt(v, 10)); 24685 value = new Date(2000, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf(); 24686 target.step = ""; 24687 } else { 24688 if (!value.includes("T")) { 24689 value = `${value}T00:00`; 24690 } 24691 value = new Date(value).valueOf(); 24692 } 24693 target.type = "text"; 24694 } 24695 elementData.userValue = value; 24696 if (elementData.lastCommittedValue !== value) { 24697 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24698 source: this, 24699 detail: { 24700 id, 24701 name: "Keystroke", 24702 value, 24703 willCommit: true, 24704 commitKey: elementData.commitKey, 24705 selStart: event.target.selectionStart, 24706 selEnd: event.target.selectionEnd 24707 } 24708 }); 24709 } 24710 _blurListener(event); 24711 }); 24712 if (this.data.actions?.Keystroke) { 24713 element.addEventListener("beforeinput", event => { 24714 elementData.lastCommittedValue = null; 24715 const { 24716 data, 24717 target 24718 } = event; 24719 const { 24720 value, 24721 selectionStart, 24722 selectionEnd 24723 } = target; 24724 let selStart = selectionStart, 24725 selEnd = selectionEnd; 24726 switch (event.inputType) { 24727 case "deleteWordBackward": 24728 { 24729 const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/); 24730 if (match) { 24731 selStart -= match[0].length; 24732 } 24733 break; 24734 } 24735 case "deleteWordForward": 24736 { 24737 const match = value.substring(selectionStart).match(/^[^\w]*\w*/); 24738 if (match) { 24739 selEnd += match[0].length; 24740 } 24741 break; 24742 } 24743 case "deleteContentBackward": 24744 if (selectionStart === selectionEnd) { 24745 selStart -= 1; 24746 } 24747 break; 24748 case "deleteContentForward": 24749 if (selectionStart === selectionEnd) { 24750 selEnd += 1; 24751 } 24752 break; 24753 } 24754 event.preventDefault(); 24755 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 24756 source: this, 24757 detail: { 24758 id, 24759 name: "Keystroke", 24760 value, 24761 change: data || "", 24762 willCommit: false, 24763 selStart, 24764 selEnd 24765 } 24766 }); 24767 }); 24768 } 24769 this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); 24770 } 24771 if (blurListener) { 24772 element.addEventListener("blur", blurListener); 24773 } 24774 if (this.data.comb) { 24775 const fieldWidth = this.data.rect[2] - this.data.rect[0]; 24776 const combWidth = fieldWidth / maxLen; 24777 element.classList.add("comb"); 24778 element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`; 24779 } 24780 } else { 24781 element = document.createElement("div"); 24782 element.textContent = this.data.fieldValue; 24783 element.style.verticalAlign = "middle"; 24784 element.style.display = "table-cell"; 24785 if (this.data.hasOwnCanvas) { 24786 element.hidden = true; 24787 } 24788 } 24789 this._setTextStyle(element); 24790 this._setBackgroundColor(element); 24791 this._setDefaultPropertiesFromJS(element); 24792 this.container.append(element); 24793 return this.container; 24794 } 24795} 24796class SignatureWidgetAnnotationElement extends WidgetAnnotationElement { 24797 constructor(parameters) { 24798 super(parameters, { 24799 isRenderable: !!parameters.data.hasOwnCanvas 24800 }); 24801 } 24802} 24803class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { 24804 constructor(parameters) { 24805 super(parameters, { 24806 isRenderable: parameters.renderForms 24807 }); 24808 } 24809 render() { 24810 const storage = this.annotationStorage; 24811 const data = this.data; 24812 const id = data.id; 24813 let value = storage.getValue(id, { 24814 value: data.exportValue === data.fieldValue 24815 }).value; 24816 if (typeof value === "string") { 24817 value = value !== "Off"; 24818 storage.setValue(id, { 24819 value 24820 }); 24821 } 24822 this.container.classList.add("buttonWidgetAnnotation", "checkBox"); 24823 const element = document.createElement("input"); 24824 GetElementsByNameSet.add(element); 24825 element.setAttribute("data-element-id", id); 24826 element.disabled = data.readOnly; 24827 this._setRequired(element, this.data.required); 24828 element.type = "checkbox"; 24829 element.name = data.fieldName; 24830 if (value) { 24831 element.setAttribute("checked", true); 24832 } 24833 element.setAttribute("exportValue", data.exportValue); 24834 element.tabIndex = 0; 24835 element.addEventListener("change", event => { 24836 const { 24837 name, 24838 checked 24839 } = event.target; 24840 for (const checkbox of this._getElementsByName(name, id)) { 24841 const curChecked = checked && checkbox.exportValue === data.exportValue; 24842 if (checkbox.domElement) { 24843 checkbox.domElement.checked = curChecked; 24844 } 24845 storage.setValue(checkbox.id, { 24846 value: curChecked 24847 }); 24848 } 24849 storage.setValue(id, { 24850 value: checked 24851 }); 24852 }); 24853 element.addEventListener("resetform", event => { 24854 const defaultValue = data.defaultFieldValue || "Off"; 24855 event.target.checked = defaultValue === data.exportValue; 24856 }); 24857 if (this.enableScripting && this.hasJSActions) { 24858 element.addEventListener("updatefromsandbox", jsEvent => { 24859 const actions = { 24860 value(event) { 24861 event.target.checked = event.detail.value !== "Off"; 24862 storage.setValue(id, { 24863 value: event.target.checked 24864 }); 24865 } 24866 }; 24867 this._dispatchEventFromSandbox(actions, jsEvent); 24868 }); 24869 this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); 24870 } 24871 this._setBackgroundColor(element); 24872 this._setDefaultPropertiesFromJS(element); 24873 this.container.append(element); 24874 return this.container; 24875 } 24876} 24877class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { 24878 constructor(parameters) { 24879 super(parameters, { 24880 isRenderable: parameters.renderForms 24881 }); 24882 } 24883 render() { 24884 this.container.classList.add("buttonWidgetAnnotation", "radioButton"); 24885 const storage = this.annotationStorage; 24886 const data = this.data; 24887 const id = data.id; 24888 let value = storage.getValue(id, { 24889 value: data.fieldValue === data.buttonValue 24890 }).value; 24891 if (typeof value === "string") { 24892 value = value !== data.buttonValue; 24893 storage.setValue(id, { 24894 value 24895 }); 24896 } 24897 if (value) { 24898 for (const radio of this._getElementsByName(data.fieldName, id)) { 24899 storage.setValue(radio.id, { 24900 value: false 24901 }); 24902 } 24903 } 24904 const element = document.createElement("input"); 24905 GetElementsByNameSet.add(element); 24906 element.setAttribute("data-element-id", id); 24907 element.disabled = data.readOnly; 24908 this._setRequired(element, this.data.required); 24909 element.type = "radio"; 24910 element.name = data.fieldName; 24911 if (value) { 24912 element.setAttribute("checked", true); 24913 } 24914 element.tabIndex = 0; 24915 element.addEventListener("change", event => { 24916 const { 24917 name, 24918 checked 24919 } = event.target; 24920 for (const radio of this._getElementsByName(name, id)) { 24921 storage.setValue(radio.id, { 24922 value: false 24923 }); 24924 } 24925 storage.setValue(id, { 24926 value: checked 24927 }); 24928 }); 24929 element.addEventListener("resetform", event => { 24930 const defaultValue = data.defaultFieldValue; 24931 event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue; 24932 }); 24933 if (this.enableScripting && this.hasJSActions) { 24934 const pdfButtonValue = data.buttonValue; 24935 element.addEventListener("updatefromsandbox", jsEvent => { 24936 const actions = { 24937 value: event => { 24938 const checked = pdfButtonValue === event.detail.value; 24939 for (const radio of this._getElementsByName(event.target.name)) { 24940 const curChecked = checked && radio.id === id; 24941 if (radio.domElement) { 24942 radio.domElement.checked = curChecked; 24943 } 24944 storage.setValue(radio.id, { 24945 value: curChecked 24946 }); 24947 } 24948 } 24949 }; 24950 this._dispatchEventFromSandbox(actions, jsEvent); 24951 }); 24952 this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); 24953 } 24954 this._setBackgroundColor(element); 24955 this._setDefaultPropertiesFromJS(element); 24956 this.container.append(element); 24957 return this.container; 24958 } 24959} 24960class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { 24961 constructor(parameters) { 24962 super(parameters, { 24963 ignoreBorder: parameters.data.hasAppearance 24964 }); 24965 } 24966 render() { 24967 const container = super.render(); 24968 container.classList.add("buttonWidgetAnnotation", "pushButton"); 24969 const linkElement = container.lastChild; 24970 if (this.enableScripting && this.hasJSActions && linkElement) { 24971 this._setDefaultPropertiesFromJS(linkElement); 24972 linkElement.addEventListener("updatefromsandbox", jsEvent => { 24973 this._dispatchEventFromSandbox({}, jsEvent); 24974 }); 24975 } 24976 return container; 24977 } 24978} 24979class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { 24980 constructor(parameters) { 24981 super(parameters, { 24982 isRenderable: parameters.renderForms 24983 }); 24984 } 24985 render() { 24986 this.container.classList.add("choiceWidgetAnnotation"); 24987 const storage = this.annotationStorage; 24988 const id = this.data.id; 24989 const storedData = storage.getValue(id, { 24990 value: this.data.fieldValue 24991 }); 24992 const selectElement = document.createElement("select"); 24993 GetElementsByNameSet.add(selectElement); 24994 selectElement.setAttribute("data-element-id", id); 24995 selectElement.disabled = this.data.readOnly; 24996 this._setRequired(selectElement, this.data.required); 24997 selectElement.name = this.data.fieldName; 24998 selectElement.tabIndex = 0; 24999 let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; 25000 if (!this.data.combo) { 25001 selectElement.size = this.data.options.length; 25002 if (this.data.multiSelect) { 25003 selectElement.multiple = true; 25004 } 25005 } 25006 selectElement.addEventListener("resetform", event => { 25007 const defaultValue = this.data.defaultFieldValue; 25008 for (const option of selectElement.options) { 25009 option.selected = option.value === defaultValue; 25010 } 25011 }); 25012 for (const option of this.data.options) { 25013 const optionElement = document.createElement("option"); 25014 optionElement.textContent = option.displayValue; 25015 optionElement.value = option.exportValue; 25016 if (storedData.value.includes(option.exportValue)) { 25017 optionElement.setAttribute("selected", true); 25018 addAnEmptyEntry = false; 25019 } 25020 selectElement.append(optionElement); 25021 } 25022 let removeEmptyEntry = null; 25023 if (addAnEmptyEntry) { 25024 const noneOptionElement = document.createElement("option"); 25025 noneOptionElement.value = " "; 25026 noneOptionElement.setAttribute("hidden", true); 25027 noneOptionElement.setAttribute("selected", true); 25028 selectElement.prepend(noneOptionElement); 25029 removeEmptyEntry = () => { 25030 noneOptionElement.remove(); 25031 selectElement.removeEventListener("input", removeEmptyEntry); 25032 removeEmptyEntry = null; 25033 }; 25034 selectElement.addEventListener("input", removeEmptyEntry); 25035 } 25036 const getValue = isExport => { 25037 const name = isExport ? "value" : "textContent"; 25038 const { 25039 options, 25040 multiple 25041 } = selectElement; 25042 if (!multiple) { 25043 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; 25044 } 25045 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); 25046 }; 25047 let selectedValues = getValue(false); 25048 const getItems = event => { 25049 const options = event.target.options; 25050 return Array.prototype.map.call(options, option => ({ 25051 displayValue: option.textContent, 25052 exportValue: option.value 25053 })); 25054 }; 25055 if (this.enableScripting && this.hasJSActions) { 25056 selectElement.addEventListener("updatefromsandbox", jsEvent => { 25057 const actions = { 25058 value(event) { 25059 removeEmptyEntry?.(); 25060 const value = event.detail.value; 25061 const values = new Set(Array.isArray(value) ? value : [value]); 25062 for (const option of selectElement.options) { 25063 option.selected = values.has(option.value); 25064 } 25065 storage.setValue(id, { 25066 value: getValue(true) 25067 }); 25068 selectedValues = getValue(false); 25069 }, 25070 multipleSelection(event) { 25071 selectElement.multiple = true; 25072 }, 25073 remove(event) { 25074 const options = selectElement.options; 25075 const index = event.detail.remove; 25076 options[index].selected = false; 25077 selectElement.remove(index); 25078 if (options.length > 0) { 25079 const i = Array.prototype.findIndex.call(options, option => option.selected); 25080 if (i === -1) { 25081 options[0].selected = true; 25082 } 25083 } 25084 storage.setValue(id, { 25085 value: getValue(true), 25086 items: getItems(event) 25087 }); 25088 selectedValues = getValue(false); 25089 }, 25090 clear(event) { 25091 while (selectElement.length !== 0) { 25092 selectElement.remove(0); 25093 } 25094 storage.setValue(id, { 25095 value: null, 25096 items: [] 25097 }); 25098 selectedValues = getValue(false); 25099 }, 25100 insert(event) { 25101 const { 25102 index, 25103 displayValue, 25104 exportValue 25105 } = event.detail.insert; 25106 const selectChild = selectElement.children[index]; 25107 const optionElement = document.createElement("option"); 25108 optionElement.textContent = displayValue; 25109 optionElement.value = exportValue; 25110 if (selectChild) { 25111 selectChild.before(optionElement); 25112 } else { 25113 selectElement.append(optionElement); 25114 } 25115 storage.setValue(id, { 25116 value: getValue(true), 25117 items: getItems(event) 25118 }); 25119 selectedValues = getValue(false); 25120 }, 25121 items(event) { 25122 const { 25123 items 25124 } = event.detail; 25125 while (selectElement.length !== 0) { 25126 selectElement.remove(0); 25127 } 25128 for (const item of items) { 25129 const { 25130 displayValue, 25131 exportValue 25132 } = item; 25133 const optionElement = document.createElement("option"); 25134 optionElement.textContent = displayValue; 25135 optionElement.value = exportValue; 25136 selectElement.append(optionElement); 25137 } 25138 if (selectElement.options.length > 0) { 25139 selectElement.options[0].selected = true; 25140 } 25141 storage.setValue(id, { 25142 value: getValue(true), 25143 items: getItems(event) 25144 }); 25145 selectedValues = getValue(false); 25146 }, 25147 indices(event) { 25148 const indices = new Set(event.detail.indices); 25149 for (const option of event.target.options) { 25150 option.selected = indices.has(option.index); 25151 } 25152 storage.setValue(id, { 25153 value: getValue(true) 25154 }); 25155 selectedValues = getValue(false); 25156 }, 25157 editable(event) { 25158 event.target.disabled = !event.detail.editable; 25159 } 25160 }; 25161 this._dispatchEventFromSandbox(actions, jsEvent); 25162 }); 25163 selectElement.addEventListener("input", event => { 25164 const exportValue = getValue(true); 25165 const change = getValue(false); 25166 storage.setValue(id, { 25167 value: exportValue 25168 }); 25169 event.preventDefault(); 25170 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 25171 source: this, 25172 detail: { 25173 id, 25174 name: "Keystroke", 25175 value: selectedValues, 25176 change, 25177 changeEx: exportValue, 25178 willCommit: false, 25179 commitKey: 1, 25180 keyDown: false 25181 } 25182 }); 25183 }); 25184 this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value); 25185 } else { 25186 selectElement.addEventListener("input", function (event) { 25187 storage.setValue(id, { 25188 value: getValue(true) 25189 }); 25190 }); 25191 } 25192 if (this.data.combo) { 25193 this._setTextStyle(selectElement); 25194 } else {} 25195 this._setBackgroundColor(selectElement); 25196 this._setDefaultPropertiesFromJS(selectElement); 25197 this.container.append(selectElement); 25198 return this.container; 25199 } 25200} 25201class PopupAnnotationElement extends AnnotationElement { 25202 constructor(parameters) { 25203 const { 25204 data, 25205 elements, 25206 parent 25207 } = parameters; 25208 const hasCommentManager = !!parent._commentManager; 25209 super(parameters, { 25210 isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data) 25211 }); 25212 this.elements = elements; 25213 if (hasCommentManager && AnnotationElement._hasPopupData(data)) { 25214 const popup = this.popup = this.#createPopup(); 25215 for (const element of elements) { 25216 element.popup = popup; 25217 } 25218 } else { 25219 this.popup = null; 25220 } 25221 } 25222 #createPopup() { 25223 return new PopupElement({ 25224 container: this.container, 25225 color: this.data.color, 25226 titleObj: this.data.titleObj, 25227 modificationDate: this.data.modificationDate || this.data.creationDate, 25228 contentsObj: this.data.contentsObj, 25229 richText: this.data.richText, 25230 rect: this.data.rect, 25231 parentRect: this.data.parentRect || null, 25232 parent: this.parent, 25233 elements: this.elements, 25234 open: this.data.open, 25235 commentManager: this.parent._commentManager 25236 }); 25237 } 25238 render() { 25239 const { 25240 container 25241 } = this; 25242 container.classList.add("popupAnnotation"); 25243 container.role = "comment"; 25244 const popup = this.popup = this.#createPopup(); 25245 const elementIds = []; 25246 for (const element of this.elements) { 25247 element.popup = popup; 25248 element.container.ariaHasPopup = "dialog"; 25249 elementIds.push(element.data.id); 25250 element.addHighlightArea(); 25251 } 25252 this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(",")); 25253 return this.container; 25254 } 25255} 25256class PopupElement { 25257 #commentManager = null; 25258 #boundKeyDown = this.#keyDown.bind(this); 25259 #boundHide = this.#hide.bind(this); 25260 #boundShow = this.#show.bind(this); 25261 #boundToggle = this.#toggle.bind(this); 25262 #color = null; 25263 #container = null; 25264 #contentsObj = null; 25265 #dateObj = null; 25266 #elements = null; 25267 #parent = null; 25268 #parentRect = null; 25269 #pinned = false; 25270 #popup = null; 25271 #popupAbortController = null; 25272 #position = null; 25273 #commentButton = null; 25274 #commentButtonPosition = null; 25275 #popupPosition = null; 25276 #rect = null; 25277 #richText = null; 25278 #titleObj = null; 25279 #updates = null; 25280 #wasVisible = false; 25281 #firstElement = null; 25282 #commentText = null; 25283 constructor({ 25284 container, 25285 color, 25286 elements, 25287 titleObj, 25288 modificationDate, 25289 contentsObj, 25290 richText, 25291 parent, 25292 rect, 25293 parentRect, 25294 open, 25295 commentManager = null 25296 }) { 25297 this.#container = container; 25298 this.#titleObj = titleObj; 25299 this.#contentsObj = contentsObj; 25300 this.#richText = richText; 25301 this.#parent = parent; 25302 this.#color = color; 25303 this.#rect = rect; 25304 this.#parentRect = parentRect; 25305 this.#elements = elements; 25306 this.#commentManager = commentManager; 25307 this.#firstElement = elements[0]; 25308 this.#dateObj = PDFDateString.toDateObject(modificationDate); 25309 this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup()); 25310 if (!commentManager) { 25311 this.#addEventListeners(); 25312 this.#container.hidden = true; 25313 if (open) { 25314 this.#toggle(); 25315 } 25316 } 25317 } 25318 #addEventListeners() { 25319 if (this.#popupAbortController) { 25320 return; 25321 } 25322 this.#popupAbortController = new AbortController(); 25323 const { 25324 signal 25325 } = this.#popupAbortController; 25326 for (const element of this.trigger) { 25327 element.addEventListener("click", this.#boundToggle, { 25328 signal 25329 }); 25330 element.addEventListener("pointerenter", this.#boundShow, { 25331 signal 25332 }); 25333 element.addEventListener("pointerleave", this.#boundHide, { 25334 signal 25335 }); 25336 element.classList.add("popupTriggerArea"); 25337 } 25338 for (const element of this.#elements) { 25339 element.container?.addEventListener("keydown", this.#boundKeyDown, { 25340 signal 25341 }); 25342 } 25343 } 25344 #setCommentButtonPosition() { 25345 const element = this.#elements.find(e => e.hasCommentButton); 25346 if (!element) { 25347 return; 25348 } 25349 this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition); 25350 } 25351 renderCommentButton() { 25352 if (this.#commentButton) { 25353 if (!this.#commentButton.parentNode) { 25354 this.#firstElement.container.after(this.#commentButton); 25355 } 25356 return; 25357 } 25358 if (!this.#commentButtonPosition) { 25359 this.#setCommentButtonPosition(); 25360 } 25361 if (!this.#commentButtonPosition) { 25362 return; 25363 } 25364 const { 25365 signal 25366 } = this.#popupAbortController = new AbortController(); 25367 const hasOwnButton = this.#firstElement.hasOwnCommentButton; 25368 const togglePopup = () => { 25369 this.#commentManager.toggleCommentPopup(this, true, undefined, !hasOwnButton); 25370 }; 25371 const showPopup = () => { 25372 this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton); 25373 }; 25374 const hidePopup = () => { 25375 this.#commentManager.toggleCommentPopup(this, false, false); 25376 }; 25377 if (!hasOwnButton) { 25378 const button = this.#commentButton = document.createElement("button"); 25379 button.className = "annotationCommentButton"; 25380 const parentContainer = this.#firstElement.container; 25381 button.style.zIndex = parentContainer.style.zIndex
vendor: 10,950 bytes, lines 25381-25778
25381 + 1; 25382 button.tabIndex = 0; 25383 button.ariaHasPopup = "dialog"; 25384 button.ariaControls = "commentPopup"; 25385 button.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); 25386 this.#updateColor(); 25387 this.#updateCommentButtonPosition(); 25388 button.addEventListener("keydown", this.#boundKeyDown, { 25389 signal 25390 }); 25391 button.addEventListener("click", togglePopup, { 25392 signal 25393 }); 25394 button.addEventListener("pointerenter", showPopup, { 25395 signal 25396 }); 25397 button.addEventListener("pointerleave", hidePopup, { 25398 signal 25399 }); 25400 parentContainer.after(button); 25401 } else { 25402 this.#commentButton = this.#firstElement.container; 25403 for (const element of this.trigger) { 25404 element.ariaHasPopup = "dialog"; 25405 element.ariaControls = "commentPopup"; 25406 element.addEventListener("keydown", this.#boundKeyDown, { 25407 signal 25408 }); 25409 element.addEventListener("click", togglePopup, { 25410 signal 25411 }); 25412 element.addEventListener("pointerenter", showPopup, { 25413 signal 25414 }); 25415 element.addEventListener("pointerleave", hidePopup, { 25416 signal 25417 }); 25418 element.classList.add("popupTriggerArea"); 25419 } 25420 } 25421 } 25422 #updateCommentButtonPosition() { 25423 if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) { 25424 return; 25425 } 25426 if (!this.#commentButton) { 25427 this.renderCommentButton(); 25428 } 25429 const [x, y] = this.#commentButtonPosition; 25430 const { 25431 style 25432 } = this.#commentButton; 25433 style.left = `calc(${x}%)`; 25434 style.top = `calc(${y}% - var(--comment-button-dim))`; 25435 } 25436 #updateColor() { 25437 if (this.#firstElement.extraPopupElement) { 25438 return; 25439 } 25440 if (!this.#commentButton) { 25441 this.renderCommentButton(); 25442 } 25443 this.#commentButton.style.backgroundColor = this.commentButtonColor || ""; 25444 } 25445 get commentButtonColor() { 25446 const { 25447 color, 25448 opacity 25449 } = this.#firstElement.commentData; 25450 if (!color) { 25451 return null; 25452 } 25453 return this.#parent._commentManager.makeCommentColor(color, opacity); 25454 } 25455 focusCommentButton() { 25456 setTimeout(() => { 25457 this.#commentButton?.focus(); 25458 }, 0); 25459 } 25460 getData() { 25461 const { 25462 richText, 25463 color, 25464 opacity, 25465 creationDate, 25466 modificationDate 25467 } = this.#firstElement.commentData; 25468 return { 25469 contentsObj: { 25470 str: this.comment 25471 }, 25472 richText, 25473 color, 25474 opacity, 25475 creationDate, 25476 modificationDate 25477 }; 25478 } 25479 get elementBeforePopup() { 25480 return this.#commentButton; 25481 } 25482 get comment() { 25483 this.#commentText ||= this.#firstElement.commentText; 25484 return this.#commentText; 25485 } 25486 set comment(text) { 25487 if (text === this.comment) { 25488 return; 25489 } 25490 this.#firstElement.commentText = this.#commentText = text; 25491 } 25492 focus() { 25493 this.#firstElement.container?.focus(); 25494 } 25495 get parentBoundingClientRect() { 25496 return this.#firstElement.layer.getBoundingClientRect(); 25497 } 25498 setCommentButtonStates({ 25499 selected, 25500 hasPopup 25501 }) { 25502 if (!this.#commentButton) { 25503 return; 25504 } 25505 this.#commentButton.classList.toggle("selected", selected); 25506 this.#commentButton.ariaExpanded = hasPopup; 25507 } 25508 setSelectedCommentButton(selected) { 25509 this.#commentButton.classList.toggle("selected", selected); 25510 } 25511 get commentPopupPosition() { 25512 if (this.#popupPosition) { 25513 return this.#popupPosition; 25514 } 25515 const { 25516 x, 25517 y, 25518 height 25519 } = this.#commentButton.getBoundingClientRect(); 25520 const { 25521 x: parentX, 25522 y: parentY, 25523 width: parentWidth, 25524 height: parentHeight 25525 } = this.#firstElement.layer.getBoundingClientRect(); 25526 return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight]; 25527 } 25528 set commentPopupPosition(pos) { 25529 this.#popupPosition = pos; 25530 } 25531 hasDefaultPopupPosition() { 25532 return this.#popupPosition === null; 25533 } 25534 get commentButtonPosition() { 25535 return this.#commentButtonPosition; 25536 } 25537 get commentButtonWidth() { 25538 return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width; 25539 } 25540 editComment(options) { 25541 const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map(x => x / 100); 25542 const parentDimensions = this.parentBoundingClientRect; 25543 const { 25544 x: parentX, 25545 y: parentY, 25546 width: parentWidth, 25547 height: parentHeight 25548 } = parentDimensions; 25549 this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, { 25550 ...options, 25551 parentDimensions 25552 }); 25553 } 25554 render() { 25555 if (this.#popup) { 25556 return; 25557 } 25558 const popup = this.#popup = document.createElement("div"); 25559 popup.className = "popup"; 25560 if (this.#color) { 25561 const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color); 25562 popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; 25563 } 25564 const header = document.createElement("span"); 25565 header.className = "header"; 25566 if (this.#titleObj?.str) { 25567 const title = document.createElement("span"); 25568 title.className = "title"; 25569 header.append(title); 25570 ({ 25571 dir: title.dir, 25572 str: title.textContent 25573 } = this.#titleObj); 25574 } 25575 popup.append(header); 25576 if (this.#dateObj) { 25577 const modificationDate = document.createElement("time"); 25578 modificationDate.className = "popupDate"; 25579 modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string"); 25580 modificationDate.setAttribute("data-l10n-args", JSON.stringify({ 25581 dateObj: this.#dateObj.valueOf() 25582 })); 25583 modificationDate.dateTime = this.#dateObj.toISOString(); 25584 header.append(modificationDate); 25585 } 25586 renderRichText({ 25587 html: this.#html || this.#contentsObj.str, 25588 dir: this.#contentsObj?.dir, 25589 className: "popupContent" 25590 }, popup); 25591 this.#container.append(popup); 25592 } 25593 get #html() { 25594 const richText = this.#richText; 25595 const contentsObj = this.#contentsObj; 25596 if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { 25597 return this.#richText.html || null; 25598 } 25599 return null; 25600 } 25601 get #fontSize() { 25602 return this.#html?.attributes?.style?.fontSize || 0; 25603 } 25604 get #fontColor() { 25605 return this.#html?.attributes?.style?.color || null; 25606 } 25607 #makePopupContent(text) { 25608 const popupLines = []; 25609 const popupContent = { 25610 str: text, 25611 html: { 25612 name: "div", 25613 attributes: { 25614 dir: "auto" 25615 }, 25616 children: [{ 25617 name: "p", 25618 children: popupLines 25619 }] 25620 } 25621 }; 25622 const lineAttributes = { 25623 style: { 25624 color: this.#fontColor, 25625 fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : "" 25626 } 25627 }; 25628 for (const line of text.split("\n")) { 25629 popupLines.push({ 25630 name: "span", 25631 value: line, 25632 attributes: lineAttributes 25633 }); 25634 } 25635 return popupContent; 25636 } 25637 #keyDown(event) { 25638 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { 25639 return; 25640 } 25641 if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { 25642 this.#toggle(); 25643 } 25644 } 25645 updateEdited({ 25646 rect, 25647 popup, 25648 deleted 25649 }) { 25650 if (this.#commentManager) { 25651 if (deleted) { 25652 this.remove(); 25653 this.#commentText = null; 25654 } else if (popup) { 25655 if (popup.deleted) { 25656 this.remove(); 25657 } else { 25658 this.#updateColor(); 25659 this.#commentText = popup.text; 25660 } 25661 } 25662 if (rect) { 25663 this.#commentButtonPosition = null; 25664 this.#setCommentButtonPosition(); 25665 this.#updateCommentButtonPosition(); 25666 } 25667 return; 25668 } 25669 if (deleted || popup?.deleted) { 25670 this.remove(); 25671 return; 25672 } 25673 this.#addEventListeners(); 25674 this.#updates ||= { 25675 contentsObj: this.#contentsObj, 25676 richText: this.#richText 25677 }; 25678 if (rect) { 25679 this.#position = null; 25680 } 25681 if (popup && popup.text) { 25682 this.#richText = this.#makePopupContent(popup.text); 25683 this.#dateObj = PDFDateString.toDateObject(popup.date); 25684 this.#contentsObj = null; 25685 } 25686 this.#popup?.remove(); 25687 this.#popup = null; 25688 } 25689 resetEdited() { 25690 if (!this.#updates) { 25691 return; 25692 } 25693 ({ 25694 contentsObj: this.#contentsObj, 25695 richText: this.#richText 25696 } = this.#updates); 25697 this.#updates = null; 25698 this.#popup?.remove(); 25699 this.#popup = null; 25700 this.#position = null; 25701 } 25702 remove() { 25703 this.#popupAbortController?.abort(); 25704 this.#popupAbortController = null; 25705 this.#popup?.remove(); 25706 this.#popup = null; 25707 this.#wasVisible = false; 25708 this.#pinned = false; 25709 this.#commentButton?.remove(); 25710 this.#commentButton = null; 25711 if (this.trigger) { 25712 for (const element of this.trigger) { 25713 element.classList.remove("popupTriggerArea"); 25714 } 25715 } 25716 } 25717 #setPosition() { 25718 if (this.#position !== null) { 25719 return; 25720 } 25721 const { 25722 page: { 25723 view 25724 }, 25725 viewport: { 25726 rawDims: { 25727 pageWidth, 25728 pageHeight, 25729 pageX, 25730 pageY 25731 } 25732 } 25733 } = this.#parent; 25734 let useParentRect = !!this.#parentRect; 25735 let rect = useParentRect ? this.#parentRect : this.#rect; 25736 for (const element of this.#elements) { 25737 if (!rect || Util.intersect(element.data.rect, rect) !== null) { 25738 rect = element.data.rect; 25739 useParentRect = true; 25740 break; 25741 } 25742 } 25743 const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); 25744 const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; 25745 const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; 25746 const popupLeft = normalizedRect[0] + parentWidth; 25747 const popupTop = normalizedRect[1]; 25748 this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight]; 25749 const { 25750 style 25751 } = this.#container; 25752 style.left = `${this.#position[0]}%`; 25753 style.top = `${this.#position[1]}%`; 25754 } 25755 #toggle() { 25756 if (this.#commentManager) { 25757 this.#commentManager.toggleCommentPopup(this, false); 25758 return; 25759 } 25760 this.#pinned = !this.#pinned; 25761 if (this.#pinned) { 25762 this.#show(); 25763 this.#container.addEventListener("click", this.#boundToggle); 25764 this.#container.addEventListener("keydown", this.#boundKeyDown); 25765 } else { 25766 this.#hide(); 25767 this.#container.removeEventListener("click", this.#boundToggle); 25768 this.#container.removeEventListener("keydown", this.#boundKeyDown); 25769 } 25770 } 25771 #show() { 25772 if (!this.#popup) { 25773 this.render(); 25774 } 25775 if (!this.isVisible) { 25776 this.#setPosition(); 25777 this.#container.hidden = false; 25778 this.#container.style.zIndex = parseInt(this.#container.style.zIndex
vendor: 17,511 bytes, lines 25778-26395
25778) + 1000; 25779 } else if (this.#pinned) { 25780 this.#container.classList.add("focused"); 25781 } 25782 } 25783 #hide() { 25784 this.#container.classList.remove("focused"); 25785 if (this.#pinned || !this.isVisible) { 25786 return; 25787 } 25788 this.#container.hidden = true; 25789 this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000; 25790 } 25791 forceHide() { 25792 this.#wasVisible = this.isVisible; 25793 if (!this.#wasVisible) { 25794 return; 25795 } 25796 this.#container.hidden = true; 25797 } 25798 maybeShow() { 25799 if (this.#commentManager) { 25800 return; 25801 } 25802 this.#addEventListeners(); 25803 if (!this.#wasVisible) { 25804 return; 25805 } 25806 if (!this.#popup) { 25807 this.#show(); 25808 } 25809 this.#wasVisible = false; 25810 this.#container.hidden = false; 25811 } 25812 get isVisible() { 25813 if (this.#commentManager) { 25814 return false; 25815 } 25816 return this.#container.hidden === false; 25817 } 25818} 25819class FreeTextAnnotationElement extends AnnotationElement { 25820 constructor(parameters) { 25821 super(parameters, { 25822 isRenderable: true, 25823 ignoreBorder: true 25824 }); 25825 this.textContent = parameters.data.textContent; 25826 this.textPosition = parameters.data.textPosition; 25827 this.annotationEditorType = AnnotationEditorType.FREETEXT; 25828 } 25829 render() { 25830 this.container.classList.add("freeTextAnnotation"); 25831 if (this.textContent) { 25832 const content = this.contentElement = document.createElement("div"); 25833 content.classList.add("annotationTextContent"); 25834 content.setAttribute("role", "comment"); 25835 for (const line of this.textContent) { 25836 const lineSpan = document.createElement("span"); 25837 lineSpan.textContent = line; 25838 content.append(lineSpan); 25839 } 25840 this.container.append(content); 25841 } 25842 if (!this.data.popupRef && this.hasPopupData) { 25843 this.hasOwnCommentButton = true; 25844 this._createPopup(); 25845 } 25846 this._editOnDoubleClick(); 25847 return this.container; 25848 } 25849} 25850class LineAnnotationElement extends AnnotationElement { 25851 #line = null; 25852 constructor(parameters) { 25853 super(parameters, { 25854 isRenderable: true, 25855 ignoreBorder: true 25856 }); 25857 } 25858 render() { 25859 this.container.classList.add("lineAnnotation"); 25860 const { 25861 data, 25862 width, 25863 height 25864 } = this; 25865 const svg = this.svgFactory.create(width, height, true); 25866 const line = this.#line = this.svgFactory.createElement("svg:line"); 25867 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); 25868 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); 25869 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); 25870 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); 25871 line.setAttribute("stroke-width", data.borderStyle.width || 1); 25872 line.setAttribute("stroke", "transparent"); 25873 line.setAttribute("fill", "transparent"); 25874 svg.append(line); 25875 this.container.append(svg); 25876 if (!data.popupRef && this.hasPopupData) { 25877 this.hasOwnCommentButton = true; 25878 this._createPopup(); 25879 } 25880 return this.container; 25881 } 25882 getElementsToTriggerPopup() { 25883 return this.#line; 25884 } 25885 addHighlightArea() { 25886 this.container.classList.add("highlightArea"); 25887 } 25888} 25889class SquareAnnotationElement extends AnnotationElement { 25890 #square = null; 25891 constructor(parameters) { 25892 super(parameters, { 25893 isRenderable: true, 25894 ignoreBorder: true 25895 }); 25896 } 25897 render() { 25898 this.container.classList.add("squareAnnotation"); 25899 const { 25900 data, 25901 width, 25902 height 25903 } = this; 25904 const svg = this.svgFactory.create(width, height, true); 25905 const borderWidth = data.borderStyle.width; 25906 const square = this.#square = this.svgFactory.createElement("svg:rect"); 25907 square.setAttribute("x", borderWidth / 2); 25908 square.setAttribute("y", borderWidth / 2); 25909 square.setAttribute("width", width - borderWidth); 25910 square.setAttribute("height", height - borderWidth); 25911 square.setAttribute("stroke-width", borderWidth || 1); 25912 square.setAttribute("stroke", "transparent"); 25913 square.setAttribute("fill", "transparent"); 25914 svg.append(square); 25915 this.container.append(svg); 25916 if (!data.popupRef && this.hasPopupData) { 25917 this.hasOwnCommentButton = true; 25918 this._createPopup(); 25919 } 25920 return this.container; 25921 } 25922 getElementsToTriggerPopup() { 25923 return this.#square; 25924 } 25925 addHighlightArea() { 25926 this.container.classList.add("highlightArea"); 25927 } 25928} 25929class CircleAnnotationElement extends AnnotationElement { 25930 #circle = null; 25931 constructor(parameters) { 25932 super(parameters, { 25933 isRenderable: true, 25934 ignoreBorder: true 25935 }); 25936 } 25937 render() { 25938 this.container.classList.add("circleAnnotation"); 25939 const { 25940 data, 25941 width, 25942 height 25943 } = this; 25944 const svg = this.svgFactory.create(width, height, true); 25945 const borderWidth = data.borderStyle.width; 25946 const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); 25947 circle.setAttribute("cx", width / 2); 25948 circle.setAttribute("cy", height / 2); 25949 circle.setAttribute("rx", width / 2 - borderWidth / 2); 25950 circle.setAttribute("ry", height / 2 - borderWidth / 2); 25951 circle.setAttribute("stroke-width", borderWidth || 1); 25952 circle.setAttribute("stroke", "transparent"); 25953 circle.setAttribute("fill", "transparent"); 25954 svg.append(circle); 25955 this.container.append(svg); 25956 if (!data.popupRef && this.hasPopupData) { 25957 this.hasOwnCommentButton = true; 25958 this._createPopup(); 25959 } 25960 return this.container; 25961 } 25962 getElementsToTriggerPopup() { 25963 return this.#circle; 25964 } 25965 addHighlightArea() { 25966 this.container.classList.add("highlightArea"); 25967 } 25968} 25969class PolylineAnnotationElement extends AnnotationElement { 25970 #polyline = null; 25971 constructor(parameters) { 25972 super(parameters, { 25973 isRenderable: true, 25974 ignoreBorder: true 25975 }); 25976 this.containerClassName = "polylineAnnotation"; 25977 this.svgElementName = "svg:polyline"; 25978 } 25979 render() { 25980 this.container.classList.add(this.containerClassName); 25981 const { 25982 data: { 25983 rect, 25984 vertices, 25985 borderStyle, 25986 popupRef 25987 }, 25988 width, 25989 height 25990 } = this; 25991 if (!vertices) { 25992 return this.container; 25993 } 25994 const svg = this.svgFactory.create(width, height, true); 25995 let points = []; 25996 for (let i = 0, ii = vertices.length; i < ii; i += 2) { 25997 const x = vertices[i] - rect[0]; 25998 const y = rect[3] - vertices[i + 1]; 25999 points.push(`${x},${y}`); 26000 } 26001 points = points.join(" "); 26002 const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); 26003 polyline.setAttribute("points", points); 26004 polyline.setAttribute("stroke-width", borderStyle.width || 1); 26005 polyline.setAttribute("stroke", "transparent"); 26006 polyline.setAttribute("fill", "transparent"); 26007 svg.append(polyline); 26008 this.container.append(svg); 26009 if (!popupRef && this.hasPopupData) { 26010 this.hasOwnCommentButton = true; 26011 this._createPopup(); 26012 } 26013 return this.container; 26014 } 26015 getElementsToTriggerPopup() { 26016 return this.#polyline; 26017 } 26018 addHighlightArea() { 26019 this.container.classList.add("highlightArea"); 26020 } 26021} 26022class PolygonAnnotationElement extends PolylineAnnotationElement { 26023 constructor(parameters) { 26024 super(parameters); 26025 this.containerClassName = "polygonAnnotation"; 26026 this.svgElementName = "svg:polygon"; 26027 } 26028} 26029class CaretAnnotationElement extends AnnotationElement { 26030 constructor(parameters) { 26031 super(parameters, { 26032 isRenderable: true, 26033 ignoreBorder: true 26034 }); 26035 } 26036 render() { 26037 this.container.classList.add("caretAnnotation"); 26038 if (!this.data.popupRef && this.hasPopupData) { 26039 this.hasOwnCommentButton = true; 26040 this._createPopup(); 26041 } 26042 return this.container; 26043 } 26044} 26045class InkAnnotationElement extends AnnotationElement { 26046 #polylinesGroupElement = null; 26047 #polylines = []; 26048 constructor(parameters) { 26049 super(parameters, { 26050 isRenderable: true, 26051 ignoreBorder: true 26052 }); 26053 this.containerClassName = "inkAnnotation"; 26054 this.svgElementName = "svg:polyline"; 26055 this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK; 26056 } 26057 #getTransform(rotation, rect) { 26058 switch (rotation) { 26059 case 90: 26060 return { 26061 transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`, 26062 width: rect[3] - rect[1], 26063 height: rect[2] - rect[0] 26064 }; 26065 case 180: 26066 return { 26067 transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`, 26068 width: rect[2] - rect[0], 26069 height: rect[3] - rect[1] 26070 }; 26071 case 270: 26072 return { 26073 transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`, 26074 width: rect[3] - rect[1], 26075 height: rect[2] - rect[0] 26076 }; 26077 default: 26078 return { 26079 transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`, 26080 width: rect[2] - rect[0], 26081 height: rect[3] - rect[1] 26082 }; 26083 } 26084 } 26085 render() { 26086 this.container.classList.add(this.containerClassName); 26087 const { 26088 data: { 26089 rect, 26090 rotation, 26091 inkLists, 26092 borderStyle, 26093 popupRef 26094 } 26095 } = this; 26096 const { 26097 transform, 26098 width, 26099 height 26100 } = this.#getTransform(rotation, rect); 26101 const svg = this.svgFactory.create(width, height, true); 26102 const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g"); 26103 svg.append(g); 26104 g.setAttribute("stroke-width", borderStyle.width || 1); 26105 g.setAttribute("stroke-linecap", "round"); 26106 g.setAttribute("stroke-linejoin", "round"); 26107 g.setAttribute("stroke-miterlimit", 10); 26108 g.setAttribute("stroke", "transparent"); 26109 g.setAttribute("fill", "transparent"); 26110 g.setAttribute("transform", transform); 26111 for (let i = 0, ii = inkLists.length; i < ii; i++) { 26112 const polyline = this.svgFactory.createElement(this.svgElementName); 26113 this.#polylines.push(polyline); 26114 polyline.setAttribute("points", inkLists[i].join(",")); 26115 g.append(polyline); 26116 } 26117 if (!popupRef && this.hasPopupData) { 26118 this.hasOwnCommentButton = true; 26119 this._createPopup(); 26120 } 26121 this.container.append(svg); 26122 this._editOnDoubleClick(); 26123 return this.container; 26124 } 26125 updateEdited(params) { 26126 super.updateEdited(params); 26127 const { 26128 thickness, 26129 points, 26130 rect 26131 } = params; 26132 const g = this.#polylinesGroupElement; 26133 if (thickness >= 0) { 26134 g.setAttribute("stroke-width", thickness || 1); 26135 } 26136 if (points) { 26137 for (let i = 0, ii = this.#polylines.length; i < ii; i++) { 26138 this.#polylines[i].setAttribute("points", points[i].join(",")); 26139 } 26140 } 26141 if (rect) { 26142 const { 26143 transform, 26144 width, 26145 height 26146 } = this.#getTransform(this.data.rotation, rect); 26147 const root = g.parentElement; 26148 root.setAttribute("viewBox", `0 0 ${width} ${height}`); 26149 g.setAttribute("transform", transform); 26150 } 26151 } 26152 getElementsToTriggerPopup() { 26153 return this.#polylines; 26154 } 26155 addHighlightArea() { 26156 this.container.classList.add("highlightArea"); 26157 } 26158} 26159class HighlightAnnotationElement extends AnnotationElement { 26160 constructor(parameters) { 26161 super(parameters, { 26162 isRenderable: true, 26163 ignoreBorder: true, 26164 createQuadrilaterals: true 26165 }); 26166 this.annotationEditorType = AnnotationEditorType.HIGHLIGHT; 26167 } 26168 render() { 26169 const { 26170 data: { 26171 overlaidText, 26172 popupRef 26173 } 26174 } = this; 26175 if (!popupRef && this.hasPopupData) { 26176 this.hasOwnCommentButton = true; 26177 this._createPopup(); 26178 } 26179 this.container.classList.add("highlightAnnotation"); 26180 this._editOnDoubleClick(); 26181 if (overlaidText) { 26182 const mark = document.createElement("mark"); 26183 mark.classList.add("overlaidText"); 26184 mark.textContent = overlaidText; 26185 this.container.append(mark); 26186 } 26187 return this.container; 26188 } 26189} 26190class UnderlineAnnotationElement extends AnnotationElement { 26191 constructor(parameters) { 26192 super(parameters, { 26193 isRenderable: true, 26194 ignoreBorder: true, 26195 createQuadrilaterals: true 26196 }); 26197 } 26198 render() { 26199 const { 26200 data: { 26201 overlaidText, 26202 popupRef 26203 } 26204 } = this; 26205 if (!popupRef && this.hasPopupData) { 26206 this.hasOwnCommentButton = true; 26207 this._createPopup(); 26208 } 26209 this.container.classList.add("underlineAnnotation"); 26210 if (overlaidText) { 26211 const underline = document.createElement("u"); 26212 underline.classList.add("overlaidText"); 26213 underline.textContent = overlaidText; 26214 this.container.append(underline); 26215 } 26216 return this.container; 26217 } 26218} 26219class SquigglyAnnotationElement extends AnnotationElement { 26220 constructor(parameters) { 26221 super(parameters, { 26222 isRenderable: true, 26223 ignoreBorder: true, 26224 createQuadrilaterals: true 26225 }); 26226 } 26227 render() { 26228 const { 26229 data: { 26230 overlaidText, 26231 popupRef 26232 } 26233 } = this; 26234 if (!popupRef && this.hasPopupData) { 26235 this.hasOwnCommentButton = true; 26236 this._createPopup(); 26237 } 26238 this.container.classList.add("squigglyAnnotation"); 26239 if (overlaidText) { 26240 const underline = document.createElement("u"); 26241 underline.classList.add("overlaidText"); 26242 underline.textContent = overlaidText; 26243 this.container.append(underline); 26244 } 26245 return this.container; 26246 } 26247} 26248class StrikeOutAnnotationElement extends AnnotationElement { 26249 constructor(parameters) { 26250 super(parameters, { 26251 isRenderable: true, 26252 ignoreBorder: true, 26253 createQuadrilaterals: true 26254 }); 26255 } 26256 render() { 26257 const { 26258 data: { 26259 overlaidText, 26260 popupRef 26261 } 26262 } = this; 26263 if (!popupRef && this.hasPopupData) { 26264 this.hasOwnCommentButton = true; 26265 this._createPopup(); 26266 } 26267 this.container.classList.add("strikeoutAnnotation"); 26268 if (overlaidText) { 26269 const strikeout = document.createElement("s"); 26270 strikeout.classList.add("overlaidText"); 26271 strikeout.textContent = overlaidText; 26272 this.container.append(strikeout); 26273 } 26274 return this.container; 26275 } 26276} 26277class StampAnnotationElement extends AnnotationElement { 26278 constructor(parameters) { 26279 super(parameters, { 26280 isRenderable: true, 26281 ignoreBorder: true 26282 }); 26283 this.annotationEditorType = AnnotationEditorType.STAMP; 26284 } 26285 render() { 26286 this.container.classList.add("stampAnnotation"); 26287 this.container.setAttribute("role", "img"); 26288 if (!this.data.popupRef && this.hasPopupData) { 26289 this.hasOwnCommentButton = true; 26290 this._createPopup(); 26291 } 26292 this._editOnDoubleClick(); 26293 return this.container; 26294 } 26295} 26296class FileAttachmentAnnotationElement extends AnnotationElement { 26297 #trigger = null; 26298 constructor(parameters) { 26299 super(parameters, { 26300 isRenderable: true 26301 }); 26302 const { 26303 file 26304 } = this.data; 26305 this.filename = file.filename; 26306 this.content = file.content; 26307 this.linkService.eventBus?.dispatch("fileattachmentannotation", { 26308 source: this, 26309 ...file 26310 }); 26311 } 26312 render() { 26313 this.container.classList.add("fileAttachmentAnnotation"); 26314 const { 26315 container, 26316 data 26317 } = this; 26318 let trigger; 26319 if (data.hasAppearance || data.fillAlpha === 0) { 26320 trigger = document.createElement("div"); 26321 } else { 26322 trigger = document.createElement("img"); 26323 trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; 26324 if (data.fillAlpha && data.fillAlpha < 1) { 26325 trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; 26326 } 26327 } 26328 trigger.addEventListener("dblclick", this.#download.bind(this)); 26329 this.#trigger = trigger; 26330 const { 26331 isMac 26332 } = FeatureTest.platform; 26333 container.addEventListener("keydown", evt => { 26334 if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { 26335 this.#download(); 26336 } 26337 }); 26338 if (!data.popupRef && this.hasPopupData) { 26339 this.hasOwnCommentButton = true; 26340 this._createPopup(); 26341 } else { 26342 trigger.classList.add("popupTriggerArea"); 26343 } 26344 container.append(trigger); 26345 return container; 26346 } 26347 getElementsToTriggerPopup() { 26348 return this.#trigger; 26349 } 26350 addHighlightArea() { 26351 this.container.classList.add("highlightArea"); 26352 } 26353 #download() { 26354 this.downloadManager?.openOrDownloadData(this.content, this.filename); 26355 } 26356} 26357class AnnotationLayer { 26358 #accessibilityManager = null; 26359 #annotationCanvasMap = null; 26360 #annotationStorage = null; 26361 #editableAnnotations = new Map(); 26362 #structTreeLayer = null; 26363 #linkService = null; 26364 #elements = []; 26365 #hasAriaAttributesFromStructTree = false; 26366 constructor({ 26367 div, 26368 accessibilityManager, 26369 annotationCanvasMap, 26370 annotationEditorUIManager, 26371 page, 26372 viewport, 26373 structTreeLayer, 26374 commentManager, 26375 linkService, 26376 annotationStorage 26377 }) { 26378 this.div = div; 26379 this.#accessibilityManager = accessibilityManager; 26380 this.#annotationCanvasMap = annotationCanvasMap; 26381 this.#structTreeLayer = structTreeLayer || null; 26382 this.#linkService = linkService || null; 26383 this.#annotationStorage = annotationStorage || new AnnotationStorage(); 26384 this.page = page; 26385 this.viewport = viewport; 26386 this.zIndex = 0; 26387 this._annotationEditorUIManager = annotationEditorUIManager; 26388 this._commentManager = commentManager || null; 26389 } 26390 hasEditableAnnotations() { 26391 return this.#editableAnnotations.size > 0; 26392 } 26393 async render(params) { 26394 const { 26395 annotations
vendor: 1,823 bytes, lines 26395-26452
26395 26396 } = params; 26397 const layer = this.div; 26398 setLayerDimensions(layer, this.viewport); 26399 const popupToElements = new Map(); 26400 const popupAnnotations = []; 26401 const elementParams = { 26402 data: null, 26403 layer, 26404 linkService: this.#linkService, 26405 downloadManager: params.downloadManager, 26406 imageResourcesPath: params.imageResourcesPath || "", 26407 renderForms: params.renderForms !== false, 26408 svgFactory: new DOMSVGFactory(), 26409 annotationStorage: this.#annotationStorage, 26410 enableComment: params.enableComment === true, 26411 enableScripting: params.enableScripting === true, 26412 hasJSActions: params.hasJSActions, 26413 fieldObjects: params.fieldObjects, 26414 parent: this, 26415 elements: null 26416 }; 26417 for (const data of annotations) { 26418 if (data.noHTML) { 26419 continue; 26420 } 26421 const isPopupAnnotation = data.annotationType === AnnotationType.POPUP; 26422 if (!isPopupAnnotation) { 26423 if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) { 26424 continue; 26425 } 26426 } else { 26427 const elements = popupToElements.get(data.id); 26428 if (!elements) { 26429 continue; 26430 } 26431 if (!this._commentManager) { 26432 popupAnnotations.push(data); 26433 continue; 26434 } 26435 elementParams.elements = elements; 26436 } 26437 elementParams.data = data; 26438 const element = AnnotationElementFactory.create(elementParams); 26439 if (!element.isRenderable) { 26440 continue; 26441 } 26442 if (!isPopupAnnotation) { 26443 this.#elements.push(element); 26444 if (data.popupRef) { 26445 popupToElements.getOrInsertComputed(data.popupRef, makeArr).push(element); 26446 } 26447 } 26448 const rendered = element.render(); 26449 if (data.hidden) { 26450 rendered.style.visibility = "hidden"; 26451 } 26452
vendor: 8,832 bytes, lines 26452-26743
26452if (element._isEditable) { 26453 this.#editableAnnotations.set(element.data.id, element); 26454 this._annotationEditorUIManager?.renderAnnotationElement(element); 26455 } 26456 } 26457 await this.#addElementsToDOM(); 26458 for (const data of popupAnnotations) { 26459 const elements = elementParams.elements = popupToElements.get(data.id); 26460 elementParams.data = data; 26461 const element = AnnotationElementFactory.create(elementParams); 26462 if (!element.isRenderable) { 26463 continue; 26464 } 26465 const rendered = element.render(); 26466 element.contentElement.id = `${AnnotationPrefix}${data.id}`; 26467 if (data.hidden) { 26468 rendered.style.visibility = "hidden"; 26469 } 26470 elements.at(-1).container.after(rendered); 26471 } 26472 this.#setAnnotationCanvasMap(); 26473 } 26474 async #addElementsToDOM() { 26475 if (this.#elements.length === 0) { 26476 return; 26477 } 26478 this.div.replaceChildren(); 26479 const promises = []; 26480 if (!this.#hasAriaAttributesFromStructTree) { 26481 this.#hasAriaAttributesFromStructTree = true; 26482 for (const { 26483 contentElement, 26484 data: { 26485 id 26486 } 26487 } of this.#elements) { 26488 const annotationId = contentElement.id = `${AnnotationPrefix}${id}`; 26489 promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then(ariaAttributes => { 26490 if (ariaAttributes) { 26491 for (const [key, value] of ariaAttributes) { 26492 contentElement.setAttribute(key, value); 26493 } 26494 } 26495 })); 26496 } 26497 } 26498 this.#elements.sort(({ 26499 data: { 26500 rect: [a0, a1, a2, a3] 26501 } 26502 }, { 26503 data: { 26504 rect: [b0, b1, b2, b3] 26505 } 26506 }) => { 26507 if (a0 === a2 && a1 === a3) { 26508 return +1; 26509 } 26510 if (b0 === b2 && b1 === b3) { 26511 return -1; 26512 } 26513 const top1 = a3; 26514 const bot1 = a1; 26515 const mid1 = (a1 + a3) / 2; 26516 const top2 = b3; 26517 const bot2 = b1; 26518 const mid2 = (b1 + b3) / 2; 26519 if (mid1 >= top2 && mid2 <= bot1) { 26520 return -1; 26521 } 26522 if (mid2 >= top1 && mid1 <= bot2) { 26523 return +1; 26524 } 26525 const centerX1 = (a0 + a2) / 2; 26526 const centerX2 = (b0 + b2) / 2; 26527 return centerX1 - centerX2; 26528 }); 26529 const fragment = document.createDocumentFragment(); 26530 for (const element of this.#elements) { 26531 fragment.append(element.container); 26532 if (this._commentManager) { 26533 (element.extraPopupElement?.popup || element.popup)?.renderCommentButton(); 26534 } else if (element.extraPopupElement) { 26535 fragment.append(element.extraPopupElement.render()); 26536 } 26537 } 26538 this.div.append(fragment); 26539 await Promise.all(promises); 26540 if (this.#accessibilityManager) { 26541 for (const element of this.#elements) { 26542 this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false); 26543 } 26544 } 26545 } 26546 async addLinkAnnotations(annotations) { 26547 const elementParams = { 26548 data: null, 26549 layer: this.div, 26550 linkService: this.#linkService, 26551 svgFactory: new DOMSVGFactory(), 26552 parent: this 26553 }; 26554 for (const data of annotations) { 26555 data.borderStyle ||= AnnotationLayer._defaultBorderStyle; 26556 elementParams.data = data; 26557 const element = AnnotationElementFactory.create(elementParams); 26558 if (!element.isRenderable) { 26559 continue; 26560 } 26561 element.render(); 26562 element.contentElement.id = `${AnnotationPrefix}${data.id}`; 26563 this.#elements.push(element); 26564 } 26565 await this.#addElementsToDOM(); 26566 } 26567 update({ 26568 viewport 26569 }) { 26570 const layer = this.div; 26571 this.viewport = viewport; 26572 setLayerDimensions(layer, { 26573 rotation: viewport.rotation 26574 }); 26575 this.#setAnnotationCanvasMap(); 26576 layer.hidden = false; 26577 } 26578 #setAnnotationCanvasMap() { 26579 if (!this.#annotationCanvasMap) { 26580 return; 26581 } 26582 const layer = this.div; 26583 for (const [id, canvas] of this.#annotationCanvasMap) { 26584 const element = layer.querySelector(`[data-annotation-id="${id}"]`); 26585 if (!element) { 26586 continue; 26587 } 26588 canvas.className = "annotationContent"; 26589 const { 26590 firstChild 26591 } = element; 26592 if (!firstChild) { 26593 element.append(canvas); 26594 } else if (firstChild.nodeName === "CANVAS") { 26595 firstChild.replaceWith(canvas); 26596 } else if (!firstChild.classList.contains("annotationContent")) { 26597 firstChild.before(canvas); 26598 } else { 26599 firstChild.after(canvas); 26600 } 26601 const editableAnnotation = this.#editableAnnotations.get(id); 26602 if (!editableAnnotation) { 26603 continue; 26604 } 26605 if (editableAnnotation._hasNoCanvas) { 26606 this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas); 26607 editableAnnotation._hasNoCanvas = false; 26608 } else { 26609 editableAnnotation.canvas = canvas; 26610 } 26611 } 26612 this.#annotationCanvasMap.clear(); 26613 } 26614 getEditableAnnotations() { 26615 return Array.from(this.#editableAnnotations.values()); 26616 } 26617 getEditableAnnotation(id) { 26618 return this.#editableAnnotations.get(id); 26619 } 26620 addFakeAnnotation(editor) { 26621 const { 26622 div 26623 } = this; 26624 const { 26625 id, 26626 rotation 26627 } = editor; 26628 const element = new EditorAnnotationElement({ 26629 data: { 26630 id, 26631 rect: editor.getPDFRect(), 26632 rotation 26633 }, 26634 editor, 26635 layer: div, 26636 parent: this, 26637 enableComment: !!this._commentManager, 26638 linkService: this.#linkService, 26639 annotationStorage: this.#annotationStorage 26640 }); 26641 element.render(); 26642 element.contentElement.id = `${AnnotationPrefix}${id}`; 26643 element.createOrUpdatePopup(); 26644 this.#elements.push(element); 26645 return element; 26646 } 26647 removeAnnotation(id) { 26648 const index = this.#elements.findIndex(el => el.data.id === id); 26649 if (index < 0) { 26650 return; 26651 } 26652 const [element] = this.#elements.splice(index, 1); 26653 this.#accessibilityManager?.removePointerInTextLayer(element.contentElement); 26654 } 26655 updateFakeAnnotations(editors) { 26656 if (editors.length === 0) { 26657 return; 26658 } 26659 for (const editor of editors) { 26660 editor.updateFakeAnnotationElement(this); 26661 } 26662 this.#addElementsToDOM(); 26663 } 26664 togglePointerEvents(enabled = false) { 26665 this.div.classList.toggle("disabled", !enabled); 26666 } 26667 static get _defaultBorderStyle() { 26668 return shadow(this, "_defaultBorderStyle", Object.freeze({ 26669 width: 1, 26670 rawWidth: 1, 26671 style: AnnotationBorderStyleType.SOLID, 26672 dashArray: [3], 26673 horizontalCornerRadius: 0, 26674 verticalCornerRadius: 0 26675 })); 26676 } 26677} 26678 26679;// ./src/display/editor/freetext.js 26680 26681 26682 26683 26684 26685 26686 26687 26688 26689const EOL_PATTERN = /\r\n?|\n/g; 26690class FreeTextEditor extends AnnotationEditor { 26691 #content = ""; 26692 #editorDivId = `${this.id}-editor`; 26693 #editModeAC = null; 26694 #fontSize; 26695 _colorPicker = null; 26696 static _freeTextDefaultContent = ""; 26697 static _internalPadding = 0; 26698 static _defaultColor = null; 26699 static _defaultFontSize = 10; 26700 static get _keyboardManager() { 26701 const proto = FreeTextEditor.prototype; 26702 const arrowChecker = self => self.isEmpty(); 26703 const small = AnnotationEditorUIManager.TRANSLATE_SMALL; 26704 const big = AnnotationEditorUIManager.TRANSLATE_BIG; 26705 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { 26706 bubbles: true 26707 }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { 26708 args: [-small, 0], 26709 checker: arrowChecker 26710 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { 26711 args: [-big, 0], 26712 checker: arrowChecker 26713 }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { 26714 args: [small, 0], 26715 checker: arrowChecker 26716 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { 26717 args: [big, 0], 26718 checker: arrowChecker 26719 }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { 26720 args: [0, -small], 26721 checker: arrowChecker 26722 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { 26723 args: [0, -big], 26724 checker: arrowChecker 26725 }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { 26726 args: [0, small], 26727 checker: arrowChecker 26728 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { 26729 args: [0, big], 26730 checker: arrowChecker 26731 }]])); 26732 } 26733 static _type = "freetext"; 26734 static _editorType = AnnotationEditorType.FREETEXT; 26735 constructor(params) { 26736 super({ 26737 ...params, 26738 name: "freeTextEditor" 26739 }); 26740 this.color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor; 26741 this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize; 26742 if (!this.annotationElementId) { 26743 this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"
vendor: 14,846 bytes, lines 26743-27230
26743); 26744 } 26745 this.canAddComment = false; 26746 } 26747 static initialize(l10n, uiManager) { 26748 AnnotationEditor.initialize(l10n, uiManager); 26749 const style = getComputedStyle(document.documentElement); 26750 this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); 26751 } 26752 static updateDefaultParams(type, value) { 26753 switch (type) { 26754 case AnnotationEditorParamsType.FREETEXT_SIZE: 26755 FreeTextEditor._defaultFontSize = value; 26756 break; 26757 case AnnotationEditorParamsType.FREETEXT_COLOR: 26758 FreeTextEditor._defaultColor = value; 26759 break; 26760 } 26761 } 26762 updateParams(type, value) { 26763 switch (type) { 26764 case AnnotationEditorParamsType.FREETEXT_SIZE: 26765 this.#updateFontSize(value); 26766 break; 26767 case AnnotationEditorParamsType.FREETEXT_COLOR: 26768 this.#updateColor(value); 26769 break; 26770 } 26771 } 26772 static get defaultPropertiesToUpdate() { 26773 return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]]; 26774 } 26775 get propertiesToUpdate() { 26776 return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]]; 26777 } 26778 get toolbarButtons() { 26779 this._colorPicker ||= new BasicColorPicker(this); 26780 return [["colorPicker", this._colorPicker]]; 26781 } 26782 get colorType() { 26783 return AnnotationEditorParamsType.FREETEXT_COLOR; 26784 } 26785 #updateFontSize(fontSize) { 26786 const setFontsize = size => { 26787 this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`; 26788 this.translate(0, -(size - this.#fontSize) * this.parentScale); 26789 this.#fontSize = size; 26790 this.#setEditorDimensions(); 26791 }; 26792 const savedFontsize = this.#fontSize; 26793 this.addCommands({ 26794 cmd: setFontsize.bind(this, fontSize), 26795 undo: setFontsize.bind(this, savedFontsize), 26796 post: this._uiManager.updateUI.bind(this._uiManager, this), 26797 mustExec: true, 26798 type: AnnotationEditorParamsType.FREETEXT_SIZE, 26799 overwriteIfSameType: true, 26800 keepUndo: true 26801 }); 26802 } 26803 onUpdatedColor() { 26804 this.editorDiv.style.color = this.color; 26805 this._colorPicker?.update(this.color); 26806 super.onUpdatedColor(); 26807 } 26808 #updateColor(color) { 26809 const setColor = col => { 26810 this.color = col; 26811 this.onUpdatedColor(); 26812 }; 26813 const savedColor = this.color; 26814 this.addCommands({ 26815 cmd: setColor.bind(this, color), 26816 undo: setColor.bind(this, savedColor), 26817 post: this._uiManager.updateUI.bind(this._uiManager, this), 26818 mustExec: true, 26819 type: AnnotationEditorParamsType.FREETEXT_COLOR, 26820 overwriteIfSameType: true, 26821 keepUndo: true 26822 }); 26823 } 26824 _translateEmpty(x, y) { 26825 this._uiManager.translateSelectedEditors(x, y, true); 26826 } 26827 getInitialTranslation() { 26828 const scale = this.parentScale; 26829 return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale]; 26830 } 26831 rebuild() { 26832 if (!this.parent) { 26833 return; 26834 } 26835 super.rebuild(); 26836 if (this.div === null) { 26837 return; 26838 } 26839 if (!this.isAttachedToDOM) { 26840 this.parent.add(this); 26841 } 26842 } 26843 enableEditMode() { 26844 if (!super.enableEditMode()) { 26845 return false; 26846 } 26847 this.overlayDiv.classList.remove("enabled"); 26848 this.editorDiv.contentEditable = true; 26849 this._isDraggable = false; 26850 this.div.removeAttribute("aria-activedescendant"); 26851 this.#editModeAC = new AbortController(); 26852 const signal = this._uiManager.combinedSignal(this.#editModeAC); 26853 this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), { 26854 signal 26855 }); 26856 this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), { 26857 signal 26858 }); 26859 this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), { 26860 signal 26861 }); 26862 this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), { 26863 signal 26864 }); 26865 this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), { 26866 signal 26867 }); 26868 return true; 26869 } 26870 disableEditMode() { 26871 if (!super.disableEditMode()) { 26872 return false; 26873 } 26874 this.overlayDiv.classList.add("enabled"); 26875 this.editorDiv.contentEditable = false; 26876 this.div.setAttribute("aria-activedescendant", this.#editorDivId); 26877 this._isDraggable = true; 26878 this.#editModeAC?.abort(); 26879 this.#editModeAC = null; 26880 this.div.focus({ 26881 preventScroll: true 26882 }); 26883 this.isEditing = false; 26884 this.parent.div.classList.add("freetextEditing"); 26885 return true; 26886 } 26887 focusin(event) { 26888 if (!this._focusEventsAllowed) { 26889 return; 26890 } 26891 super.focusin(event); 26892 if (event.target !== this.editorDiv) { 26893 this.editorDiv.focus(); 26894 } 26895 } 26896 onceAdded(focus) { 26897 if (this.width) { 26898 return; 26899 } 26900 this.enableEditMode(); 26901 if (focus) { 26902 this.editorDiv.focus(); 26903 } 26904 if (this._initialOptions?.isCentered) { 26905 this.center(); 26906 } 26907 this._initialOptions = null; 26908 } 26909 isEmpty() { 26910 return !this.editorDiv || this.editorDiv.innerText.trim() === ""; 26911 } 26912 remove() { 26913 this.isEditing = false; 26914 if (this.parent) { 26915 this.parent.setEditingState(true); 26916 this.parent.div.classList.add("freetextEditing"); 26917 } 26918 super.remove(); 26919 } 26920 #extractText() { 26921 const buffer = []; 26922 this.editorDiv.normalize(); 26923 let prevChild = null; 26924 for (const child of this.editorDiv.childNodes) { 26925 if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { 26926 continue; 26927 } 26928 buffer.push(FreeTextEditor.#getNodeContent(child)); 26929 prevChild = child; 26930 } 26931 return buffer.join("\n"); 26932 } 26933 #setEditorDimensions() { 26934 const [parentWidth, parentHeight] = this.parentDimensions; 26935 let rect; 26936 if (this.isAttachedToDOM) { 26937 rect = this.div.getBoundingClientRect(); 26938 } else { 26939 const { 26940 currentLayer, 26941 div 26942 } = this; 26943 const savedDisplay = div.style.display; 26944 const savedVisibility = div.classList.contains("hidden"); 26945 div.classList.remove("hidden"); 26946 div.style.display = "hidden"; 26947 currentLayer.div.append(this.div); 26948 rect = div.getBoundingClientRect(); 26949 div.remove(); 26950 div.style.display = savedDisplay; 26951 div.classList.toggle("hidden", savedVisibility); 26952 } 26953 if (this.rotation % 180 === this.parentRotation % 180) { 26954 this.width = rect.width / parentWidth; 26955 this.height = rect.height / parentHeight; 26956 } else { 26957 this.width = rect.height / parentWidth; 26958 this.height = rect.width / parentHeight; 26959 } 26960 this.fixAndSetPosition(); 26961 } 26962 commit() { 26963 if (!this.isInEditMode()) { 26964 return; 26965 } 26966 super.commit(); 26967 this.disableEditMode(); 26968 const savedText = this.#content; 26969 const newText = this.#content = this.#extractText().trimEnd(); 26970 if (savedText === newText) { 26971 return; 26972 } 26973 const setText = text => { 26974 this.#content = text; 26975 if (!text) { 26976 this.remove(); 26977 return; 26978 } 26979 this.#setContent(); 26980 this._uiManager.rebuild(this); 26981 this.#setEditorDimensions(); 26982 }; 26983 this.addCommands({ 26984 cmd: () => { 26985 setText(newText); 26986 }, 26987 undo: () => { 26988 setText(savedText); 26989 }, 26990 mustExec: false 26991 }); 26992 this.#setEditorDimensions(); 26993 } 26994 shouldGetKeyboardEvents() { 26995 return this.isInEditMode(); 26996 } 26997 enterInEditMode() { 26998 this.enableEditMode(); 26999 this.editorDiv.focus(); 27000 } 27001 keydown(event) { 27002 if (event.target === this.div && event.key === "Enter") { 27003 this.enterInEditMode(); 27004 event.preventDefault(); 27005 } 27006 } 27007 editorDivKeydown(event) { 27008 FreeTextEditor._keyboardManager.exec(this, event); 27009 } 27010 editorDivFocus(event) { 27011 this.isEditing = true; 27012 } 27013 editorDivBlur(event) { 27014 this.isEditing = false; 27015 } 27016 editorDivInput(event) { 27017 this.parent.div.classList.toggle("freetextEditing", this.isEmpty()); 27018 } 27019 disableEditing() { 27020 this.editorDiv.setAttribute("role", "comment"); 27021 this.editorDiv.removeAttribute("aria-multiline"); 27022 } 27023 enableEditing() { 27024 this.editorDiv.setAttribute("role", "textbox"); 27025 this.editorDiv.setAttribute("aria-multiline", true); 27026 } 27027 get canChangeContent() { 27028 return true; 27029 } 27030 render() { 27031 if (this.div) { 27032 return this.div; 27033 } 27034 let baseX, baseY; 27035 if (this._isCopy || this.annotationElementId) { 27036 baseX = this.x; 27037 baseY = this.y; 27038 } 27039 super.render(); 27040 this.editorDiv = document.createElement("div"); 27041 this.editorDiv.className = "internal"; 27042 this.editorDiv.setAttribute("id", this.#editorDivId); 27043 this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2"); 27044 this.editorDiv.setAttribute("data-l10n-attrs", "default-content"); 27045 this.enableEditing(); 27046 this.editorDiv.contentEditable = true; 27047 const { 27048 style 27049 } = this.editorDiv; 27050 style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; 27051 style.color = this.color; 27052 this.div.append(this.editorDiv); 27053 this.overlayDiv = document.createElement("div"); 27054 this.overlayDiv.classList.add("overlay", "enabled"); 27055 this.div.append(this.overlayDiv); 27056 if (this._isCopy || this.annotationElementId) { 27057 const [parentWidth, parentHeight] = this.parentDimensions; 27058 if (this.annotationElementId) { 27059 const { 27060 position 27061 } = this._initialData; 27062 let [tx, ty] = this.getInitialTranslation(); 27063 [tx, ty] = this.pageTranslationToScreen(tx, ty); 27064 const [pageWidth, pageHeight] = this.pageDimensions; 27065 const [pageX, pageY] = this.pageTranslation; 27066 let posX, posY; 27067 switch (this.rotation) { 27068 case 0: 27069 posX = baseX + (position[0] - pageX) / pageWidth; 27070 posY = baseY + this.height - (position[1] - pageY) / pageHeight; 27071 break; 27072 case 90: 27073 posX = baseX + (position[0] - pageX) / pageWidth; 27074 posY = baseY - (position[1] - pageY) / pageHeight; 27075 [tx, ty] = [ty, -tx]; 27076 break; 27077 case 180: 27078 posX = baseX - this.width + (position[0] - pageX) / pageWidth; 27079 posY = baseY - (position[1] - pageY) / pageHeight; 27080 [tx, ty] = [-tx, -ty]; 27081 break; 27082 case 270: 27083 posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; 27084 posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; 27085 [tx, ty] = [-ty, tx]; 27086 break; 27087 } 27088 this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); 27089 } else { 27090 this._moveAfterPaste(baseX, baseY); 27091 } 27092 this.#setContent(); 27093 this._isDraggable = true; 27094 this.editorDiv.contentEditable = false; 27095 } else { 27096 this._isDraggable = false; 27097 this.editorDiv.contentEditable = true; 27098 } 27099 return this.div; 27100 } 27101 static #getNodeContent(node) { 27102 return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); 27103 } 27104 editorDivPaste(event) { 27105 const clipboardData = event.clipboardData || window.clipboardData; 27106 const { 27107 types 27108 } = clipboardData; 27109 if (types.length === 1 && types[0] === "text/plain") { 27110 return; 27111 } 27112 event.preventDefault(); 27113 const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n"); 27114 if (!paste) { 27115 return; 27116 } 27117 const selection = window.getSelection(); 27118 if (!selection.rangeCount) { 27119 return; 27120 } 27121 this.editorDiv.normalize(); 27122 selection.deleteFromDocument(); 27123 const range = selection.getRangeAt(0); 27124 if (!paste.includes("\n")) { 27125 range.insertNode(document.createTextNode(paste)); 27126 this.editorDiv.normalize(); 27127 selection.collapseToStart(); 27128 return; 27129 } 27130 const { 27131 startContainer, 27132 startOffset 27133 } = range; 27134 const bufferBefore = []; 27135 const bufferAfter = []; 27136 if (startContainer.nodeType === Node.TEXT_NODE) { 27137 const parent = startContainer.parentElement; 27138 bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, "")); 27139 if (parent !== this.editorDiv) { 27140 let buffer = bufferBefore; 27141 for (const child of this.editorDiv.childNodes) { 27142 if (child === parent) { 27143 buffer = bufferAfter; 27144 continue; 27145 } 27146 buffer.push(FreeTextEditor.#getNodeContent(child)); 27147 } 27148 } 27149 bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, "")); 27150 } else if (startContainer === this.editorDiv) { 27151 let buffer = bufferBefore; 27152 let i = 0; 27153 for (const child of this.editorDiv.childNodes) { 27154 if (i++ === startOffset) { 27155 buffer = bufferAfter; 27156 } 27157 buffer.push(FreeTextEditor.#getNodeContent(child)); 27158 } 27159 } 27160 this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`; 27161 this.#setContent(); 27162 const newRange = new Range(); 27163 let beforeLength = Math.sumPrecise(bufferBefore.map(line => line.length)); 27164 for (const { 27165 firstChild 27166 } of this.editorDiv.childNodes) { 27167 if (firstChild.nodeType === Node.TEXT_NODE) { 27168 const length = firstChild.nodeValue.length; 27169 if (beforeLength <= length) { 27170 newRange.setStart(firstChild, beforeLength); 27171 newRange.setEnd(firstChild, beforeLength); 27172 break; 27173 } 27174 beforeLength -= length; 27175 } 27176 } 27177 selection.removeAllRanges(); 27178 selection.addRange(newRange); 27179 } 27180 #setContent() { 27181 this.editorDiv.replaceChildren(); 27182 if (!this.#content) { 27183 return; 27184 } 27185 for (const line of this.#content.split("\n")) { 27186 const div = document.createElement("div"); 27187 div.append(line ? document.createTextNode(line) : document.createElement("br")); 27188 this.editorDiv.append(div); 27189 } 27190 } 27191 #serializeContent() { 27192 return this.#content.replaceAll("\xa0", " "); 27193 } 27194 static #deserializeContent(content) { 27195 return content.replaceAll(" ", "\xa0"); 27196 } 27197 get contentDiv() { 27198 return this.editorDiv; 27199 } 27200 getPDFRect() { 27201 const padding = FreeTextEditor._internalPadding * this.parentScale; 27202 return this.getRect(padding, padding); 27203 } 27204 static async deserialize(data, parent, uiManager) { 27205 let initialData = null; 27206 if (data instanceof FreeTextAnnotationElement) { 27207 const { 27208 data: { 27209 defaultAppearanceData: { 27210 fontSize, 27211 fontColor 27212 }, 27213 rect, 27214 rotation, 27215 id, 27216 popupRef, 27217 richText, 27218 contentsObj, 27219 creationDate, 27220 modificationDate 27221 }, 27222 textContent, 27223 textPosition, 27224 parent: { 27225 page: { 27226 pageNumber 27227 } 27228 } 27229 } = data; 27230 if (!textContent
vendor: 6,232 bytes, lines 27230-27449
27230 || textContent.length === 0) { 27231 return null; 27232 } 27233 initialData = data = { 27234 annotationType: AnnotationEditorType.FREETEXT, 27235 color: Array.from(fontColor), 27236 fontSize, 27237 value: textContent.join("\n"), 27238 position: textPosition, 27239 pageIndex: pageNumber - 1, 27240 rect: rect.slice(0), 27241 rotation, 27242 annotationElementId: id, 27243 id, 27244 deleted: false, 27245 popupRef, 27246 comment: contentsObj?.str || null, 27247 richText, 27248 creationDate, 27249 modificationDate 27250 }; 27251 } 27252 const editor = await super.deserialize(data, parent, uiManager); 27253 editor.#fontSize = data.fontSize; 27254 editor.color = Util.makeHexColor(...data.color); 27255 editor.#content = FreeTextEditor.#deserializeContent(data.value); 27256 editor._initialData = initialData; 27257 if (data.comment) { 27258 editor.setCommentData(data); 27259 } 27260 return editor; 27261 } 27262 serialize(isForCopying = false) { 27263 if (this.isEmpty()) { 27264 return null; 27265 } 27266 if (this.deleted) { 27267 return this.serializeDeleted(); 27268 } 27269 const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color); 27270 const serialized = Object.assign(super.serialize(isForCopying), { 27271 color, 27272 fontSize: this.#fontSize, 27273 value: this.#serializeContent() 27274 }); 27275 this.addComment(serialized); 27276 if (isForCopying) { 27277 serialized.isCopy = true; 27278 return serialized; 27279 } 27280 if (this.annotationElementId && !this.#hasElementChanged(serialized)) { 27281 return null; 27282 } 27283 serialized.id = this.annotationElementId; 27284 return serialized; 27285 } 27286 #hasElementChanged(serialized) { 27287 const { 27288 value, 27289 fontSize, 27290 color, 27291 pageIndex 27292 } = this._initialData; 27293 return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex; 27294 } 27295 renderAnnotationElement(annotation) { 27296 const content = super.renderAnnotationElement(annotation); 27297 if (!content) { 27298 return null; 27299 } 27300 const { 27301 style 27302 } = content; 27303 style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; 27304 style.color = this.color; 27305 content.replaceChildren(); 27306 for (const line of this.#content.split("\n")) { 27307 const div = document.createElement("div"); 27308 div.append(line ? document.createTextNode(line) : document.createElement("br")); 27309 content.append(div); 27310 } 27311 annotation.updateEdited({ 27312 rect: this.getPDFRect(), 27313 popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : { 27314 text: this.#content 27315 } 27316 }); 27317 return content; 27318 } 27319 resetAnnotationElement(annotation) { 27320 super.resetAnnotationElement(annotation); 27321 annotation.resetEdited(); 27322 } 27323} 27324 27325;// ./src/display/editor/drawers/outline.js 27326 27327 27328 27329 27330 27331class Outline { 27332 static PRECISION = 1e-4; 27333 toSVGPath() { 27334 unreachable("Abstract method `toSVGPath` must be implemented."); 27335 } 27336 get box() { 27337 unreachable("Abstract getter `box` must be implemented."); 27338 } 27339 serialize(_bbox, _rotation) { 27340 unreachable("Abstract method `serialize` must be implemented."); 27341 } 27342 static _rescale(src, tx, ty, sx, sy, dest) { 27343 dest ||= new Float32Array(src.length); 27344 for (let i = 0, ii = src.length; i < ii; i += 2) { 27345 dest[i] = tx + src[i] * sx; 27346 dest[i + 1] = ty + src[i + 1] * sy; 27347 } 27348 return dest; 27349 } 27350 static _rescaleAndSwap(src, tx, ty, sx, sy, dest) { 27351 dest ||= new Float32Array(src.length); 27352 for (let i = 0, ii = src.length; i < ii; i += 2) { 27353 dest[i] = tx + src[i + 1] * sx; 27354 dest[i + 1] = ty + src[i] * sy; 27355 } 27356 return dest; 27357 } 27358 static _translate(src, tx, ty, dest) { 27359 dest ||= new Float32Array(src.length); 27360 for (let i = 0, ii = src.length; i < ii; i += 2) { 27361 dest[i] = tx + src[i]; 27362 dest[i + 1] = ty + src[i + 1]; 27363 } 27364 return dest; 27365 } 27366 static svgRound(x) { 27367 return Math.round(x * 10000); 27368 } 27369 static _normalizePoint(x, y, parentWidth, parentHeight, rotation) { 27370 switch (rotation) { 27371 case 90: 27372 return [1 - y / parentWidth, x / parentHeight]; 27373 case 180: 27374 return [1 - x / parentWidth, 1 - y / parentHeight]; 27375 case 270: 27376 return [y / parentWidth, 1 - x / parentHeight]; 27377 default: 27378 return [x / parentWidth, y / parentHeight]; 27379 } 27380 } 27381 static _normalizePagePoint(x, y, rotation) { 27382 switch (rotation) { 27383 case 90: 27384 return [1 - y, x]; 27385 case 180: 27386 return [1 - x, 1 - y]; 27387 case 270: 27388 return [y, 1 - x]; 27389 default: 27390 return [x, y]; 27391 } 27392 } 27393 static createBezierPoints(x1, y1, x2, y2, x3, y3) { 27394 return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2]; 27395 } 27396} 27397 27398;// ./src/display/editor/drawers/freedraw.js 27399 27400 27401 27402 27403 27404 27405 27406class FreeDrawOutliner { 27407 #box; 27408 #bottom = []; 27409 #innerMargin; 27410 #isLTR; 27411 #top = []; 27412 #last = new Float32Array(18); 27413 #lastX; 27414 #lastY; 27415 #min; 27416 #min_dist; 27417 #scaleFactor; 27418 #thickness; 27419 #points = []; 27420 static #MIN_DIST = 8; 27421 static #MIN_DIFF = 2; 27422 static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF; 27423 constructor({ 27424 x, 27425 y 27426 }, box, scaleFactor, thickness, isLTR, innerMargin = 0) { 27427 this.#box = box; 27428 this.#thickness = thickness * scaleFactor; 27429 this.#isLTR = isLTR; 27430 this.#last.set([NaN, NaN, NaN, NaN, x, y], 6); 27431 this.#innerMargin = innerMargin; 27432 this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor; 27433 this.#min = FreeDrawOutliner.#MIN * scaleFactor; 27434 this.#scaleFactor = scaleFactor; 27435 this.#points.push(x, y); 27436 } 27437 isEmpty() { 27438 return isNaN(this.#last[8]); 27439 } 27440 #getLastCoords() { 27441 const lastTop = this.#last.subarray(4, 6); 27442 const lastBottom = this.#last.subarray(16, 18); 27443 const [x, y, width, height] = this.#box; 27444 return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height]; 27445 } 27446 add({ 27447 x, 27448 y 27449 }
vendor: 11,269 bytes, lines 27449-27713
27449) { 27450 this.#lastX = x; 27451 this.#lastY = y; 27452 const [layerX, layerY, layerWidth, layerHeight] = this.#box; 27453 let [x1, y1, x2, y2] = this.#last.subarray(8, 12); 27454 const diffX = x - x2; 27455 const diffY = y - y2; 27456 const d = Math.hypot(diffX, diffY); 27457 if (d < this.#min) { 27458 return false; 27459 } 27460 const diffD = d - this.#min_dist; 27461 const K = diffD / d; 27462 const shiftX = K * diffX; 27463 const shiftY = K * diffY; 27464 let x0 = x1; 27465 let y0 = y1; 27466 x1 = x2; 27467 y1 = y2; 27468 x2 += shiftX; 27469 y2 += shiftY; 27470 this.#points?.push(x, y); 27471 const nX = -shiftY / diffD; 27472 const nY = shiftX / diffD; 27473 const thX = nX * this.#thickness; 27474 const thY = nY * this.#thickness; 27475 this.#last.set(this.#last.subarray(2, 8), 0); 27476 this.#last.set([x2 + thX, y2 + thY], 4); 27477 this.#last.set(this.#last.subarray(14, 18), 12); 27478 this.#last.set([x2 - thX, y2 - thY], 16); 27479 if (isNaN(this.#last[6])) { 27480 if (this.#top.length === 0) { 27481 this.#last.set([x1 + thX, y1 + thY], 2); 27482 this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight); 27483 this.#last.set([x1 - thX, y1 - thY], 14); 27484 this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight); 27485 } 27486 this.#last.set([x0, y0, x1, y1, x2, y2], 6); 27487 return !this.isEmpty(); 27488 } 27489 this.#last.set([x0, y0, x1, y1, x2, y2], 6); 27490 const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX)); 27491 if (angle < Math.PI / 2) { 27492 [x1, y1, x2, y2] = this.#last.subarray(2, 6); 27493 this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); 27494 [x1, y1, x0, y0] = this.#last.subarray(14, 18); 27495 this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight); 27496 return true; 27497 } 27498 [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6); 27499 this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); 27500 [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18); 27501 this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); 27502 return true; 27503 } 27504 toSVGPath() { 27505 if (this.isEmpty()) { 27506 return ""; 27507 } 27508 const top = this.#top; 27509 const bottom = this.#bottom; 27510 if (isNaN(this.#last[6]) && !this.isEmpty()) { 27511 return this.#toSVGPathTwoPoints(); 27512 } 27513 const buffer = []; 27514 buffer.push(`M${top[4]} ${top[5]}`); 27515 for (let i = 6; i < top.length; i += 6) { 27516 if (isNaN(top[i])) { 27517 buffer.push(`L${top[i + 4]} ${top[i + 5]}`); 27518 } else { 27519 buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`); 27520 } 27521 } 27522 this.#toSVGPathEnd(buffer); 27523 for (let i = bottom.length - 6; i >= 6; i -= 6) { 27524 if (isNaN(bottom[i])) { 27525 buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`); 27526 } else { 27527 buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`); 27528 } 27529 } 27530 this.#toSVGPathStart(buffer); 27531 return buffer.join(" "); 27532 } 27533 #toSVGPathTwoPoints() { 27534 const [x, y, width, height] = this.#box; 27535 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); 27536 return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`; 27537 } 27538 #toSVGPathStart(buffer) { 27539 const bottom = this.#bottom; 27540 buffer.push(`L${bottom[4]} ${bottom[5]} Z`); 27541 } 27542 #toSVGPathEnd(buffer) { 27543 const [x, y, width, height] = this.#box; 27544 const lastTop = this.#last.subarray(4, 6); 27545 const lastBottom = this.#last.subarray(16, 18); 27546 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); 27547 buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`); 27548 } 27549 newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { 27550 return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR); 27551 } 27552 getOutlines() { 27553 const top = this.#top; 27554 const bottom = this.#bottom; 27555 const last = this.#last; 27556 const [layerX, layerY, layerWidth, layerHeight] = this.#box; 27557 const points = new Float32Array((this.#points?.length ?? 0) + 2); 27558 for (let i = 0, ii = points.length - 2; i < ii; i += 2) { 27559 points[i] = (this.#points[i] - layerX) / layerWidth; 27560 points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight; 27561 } 27562 points[points.length - 2] = (this.#lastX - layerX) / layerWidth; 27563 points[points.length - 1] = (this.#lastY - layerY) / layerHeight; 27564 if (isNaN(last[6]) && !this.isEmpty()) { 27565 return this.#getOutlineTwoPoints(points); 27566 } 27567 const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length); 27568 let N = top.length; 27569 for (let i = 0; i < N; i += 2) { 27570 if (isNaN(top[i])) { 27571 outline[i] = outline[i + 1] = NaN; 27572 continue; 27573 } 27574 outline[i] = top[i]; 27575 outline[i + 1] = top[i + 1]; 27576 } 27577 N = this.#getOutlineEnd(outline, N); 27578 for (let i = bottom.length - 6; i >= 6; i -= 6) { 27579 for (let j = 0; j < 6; j += 2) { 27580 if (isNaN(bottom[i + j])) { 27581 outline[N] = outline[N + 1] = NaN; 27582 N += 2; 27583 continue; 27584 } 27585 outline[N] = bottom[i + j]; 27586 outline[N + 1] = bottom[i + j + 1]; 27587 N += 2; 27588 } 27589 } 27590 this.#getOutlineStart(outline, N); 27591 return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); 27592 } 27593 #getOutlineTwoPoints(points) { 27594 const last = this.#last; 27595 const [layerX, layerY, layerWidth, layerHeight] = this.#box; 27596 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); 27597 const outline = new Float32Array(36); 27598 outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0); 27599 return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); 27600 } 27601 #getOutlineStart(outline, pos) { 27602 const bottom = this.#bottom; 27603 outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos); 27604 return pos += 6; 27605 } 27606 #getOutlineEnd(outline, pos) { 27607 const lastTop = this.#last.subarray(4, 6); 27608 const lastBottom = this.#last.subarray(16, 18); 27609 const [layerX, layerY, layerWidth, layerHeight] = this.#box; 27610 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); 27611 outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos); 27612 return pos += 24; 27613 } 27614} 27615class FreeDrawOutline extends Outline { 27616 #box; 27617 #bbox = new Float32Array(4); 27618 #innerMargin; 27619 #isLTR; 27620 #points; 27621 #scaleFactor; 27622 #outline; 27623 constructor(outline, points, box, scaleFactor, innerMargin, isLTR) { 27624 super(); 27625 this.#outline = outline; 27626 this.#points = points; 27627 this.#box = box; 27628 this.#scaleFactor = scaleFactor; 27629 this.#innerMargin = innerMargin; 27630 this.#isLTR = isLTR; 27631 this.firstPoint = [NaN, NaN]; 27632 this.lastPoint = [NaN, NaN]; 27633 this.#computeMinMax(isLTR); 27634 const [x, y, width, height] = this.#bbox; 27635 for (let i = 0, ii = outline.length; i < ii; i += 2) { 27636 outline[i] = (outline[i] - x) / width; 27637 outline[i + 1] = (outline[i + 1] - y) / height; 27638 } 27639 for (let i = 0, ii = points.length; i < ii; i += 2) { 27640 points[i] = (points[i] - x) / width; 27641 points[i + 1] = (points[i + 1] - y) / height; 27642 } 27643 } 27644 toSVGPath() { 27645 const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`]; 27646 for (let i = 6, ii = this.#outline.length; i < ii; i += 6) { 27647 if (isNaN(this.#outline[i])) { 27648 buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`); 27649 continue; 27650 } 27651 buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`); 27652 } 27653 buffer.push("Z"); 27654 return buffer.join(" "); 27655 } 27656 serialize([blX, blY, trX, trY], rotation) { 27657 const width = trX - blX; 27658 const height = trY - blY; 27659 let outline; 27660 let points; 27661 switch (rotation) { 27662 case 0: 27663 outline = Outline._rescale(this.#outline, blX, trY, width, -height); 27664 points = Outline._rescale(this.#points, blX, trY, width, -height); 27665 break; 27666 case 90: 27667 outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height); 27668 points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height); 27669 break; 27670 case 180: 27671 outline = Outline._rescale(this.#outline, trX, blY, -width, height); 27672 points = Outline._rescale(this.#points, trX, blY, -width, height); 27673 break; 27674 case 270: 27675 outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height); 27676 points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height); 27677 break; 27678 } 27679 return { 27680 outline: Array.from(outline), 27681 points: [Array.from(points)] 27682 }; 27683 } 27684 #computeMinMax(isLTR) { 27685 const outline = this.#outline; 27686 let lastX = outline[4]; 27687 let lastY = outline[5]; 27688 const minMax = [lastX, lastY, lastX, lastY]; 27689 let firstPointX = lastX; 27690 let firstPointY = lastY; 27691 let lastPointX = lastX; 27692 let lastPointY = lastY; 27693 const ltrCallback = isLTR ? Math.max : Math.min; 27694 const bezierBbox = new Float32Array(4); 27695 for (let i = 6, ii = outline.length; i < ii; i += 6) { 27696 const x = outline[i + 4], 27697 y = outline[i + 5]; 27698 if (isNaN(outline[i])) { 27699 Util.pointBoundingBox(x, y, minMax); 27700 if (firstPointY > y) { 27701 firstPointX = x; 27702 firstPointY = y; 27703 } else if (firstPointY === y) { 27704 firstPointX = ltrCallback(firstPointX, x); 27705 } 27706 if (lastPointY < y) { 27707 lastPointX = x; 27708 lastPointY = y; 27709 } else if (lastPointY === y) { 27710 lastPointX = ltrCallback(lastPointX, x); 27711 } 27712 } else { 27713 bezierBbox
vendor: 46,790 bytes, lines 27713-29376
27713[0] = bezierBbox[1] = Infinity; 27714 bezierBbox[2] = bezierBbox[3] = -Infinity; 27715 Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6), bezierBbox); 27716 Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax); 27717 if (firstPointY > bezierBbox[1]) { 27718 firstPointX = bezierBbox[0]; 27719 firstPointY = bezierBbox[1]; 27720 } else if (firstPointY === bezierBbox[1]) { 27721 firstPointX = ltrCallback(firstPointX, bezierBbox[0]); 27722 } 27723 if (lastPointY < bezierBbox[3]) { 27724 lastPointX = bezierBbox[2]; 27725 lastPointY = bezierBbox[3]; 27726 } else if (lastPointY === bezierBbox[3]) { 27727 lastPointX = ltrCallback(lastPointX, bezierBbox[2]); 27728 } 27729 } 27730 lastX = x; 27731 lastY = y; 27732 } 27733 const bbox = this.#bbox; 27734 bbox[0] = minMax[0] - this.#innerMargin; 27735 bbox[1] = minMax[1] - this.#innerMargin; 27736 bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin; 27737 bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin; 27738 this.firstPoint = [firstPointX, firstPointY]; 27739 this.lastPoint = [lastPointX, lastPointY]; 27740 } 27741 get box() { 27742 return this.#bbox; 27743 } 27744 newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { 27745 return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); 27746 } 27747 getNewOutline(thickness, innerMargin) { 27748 const [x, y, width, height] = this.#bbox; 27749 const [layerX, layerY, layerWidth, layerHeight] = this.#box; 27750 const sx = width * layerWidth; 27751 const sy = height * layerHeight; 27752 const tx = x * layerWidth + layerX; 27753 const ty = y * layerHeight + layerY; 27754 const outliner = this.newOutliner({ 27755 x: this.#points[0] * sx + tx, 27756 y: this.#points[1] * sy + ty 27757 }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin); 27758 for (let i = 2; i < this.#points.length; i += 2) { 27759 outliner.add({ 27760 x: this.#points[i] * sx + tx, 27761 y: this.#points[i + 1] * sy + ty 27762 }); 27763 } 27764 return outliner.getOutlines(); 27765 } 27766} 27767 27768;// ./src/display/editor/drawers/highlight.js 27769 27770 27771 27772 27773 27774 27775 27776 27777 27778 27779 27780 27781 27782 27783 27784class HighlightOutliner { 27785 #box; 27786 #firstPoint; 27787 #lastPoint; 27788 #verticalEdges = []; 27789 #intervals = []; 27790 constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) { 27791 const minMax = [Infinity, Infinity, -Infinity, -Infinity]; 27792 const NUMBER_OF_DIGITS = 4; 27793 const EPSILON = 10 ** -NUMBER_OF_DIGITS; 27794 for (const { 27795 x, 27796 y, 27797 width, 27798 height 27799 } of boxes) { 27800 const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON; 27801 const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON; 27802 const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON; 27803 const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON; 27804 const left = [x1, y1, y2, true]; 27805 const right = [x2, y1, y2, false]; 27806 this.#verticalEdges.push(left, right); 27807 Util.rectBoundingBox(x1, y1, x2, y2, minMax); 27808 } 27809 const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin; 27810 const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin; 27811 const shiftedMinX = minMax[0] - innerMargin; 27812 const shiftedMinY = minMax[1] - innerMargin; 27813 let firstPointX = isLTR ? -Infinity : Infinity; 27814 let firstPointY = Infinity; 27815 const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2); 27816 const lastPoint = [lastEdge[0], lastEdge[2]]; 27817 for (const edge of this.#verticalEdges) { 27818 const [x, y1, y2, left] = edge; 27819 if (!left && isLTR) { 27820 if (y1 < firstPointY) { 27821 firstPointY = y1; 27822 firstPointX = x; 27823 } else if (y1 === firstPointY) { 27824 firstPointX = Math.max(firstPointX, x); 27825 } 27826 } else if (left && !isLTR) { 27827 if (y1 < firstPointY) { 27828 firstPointY = y1; 27829 firstPointX = x; 27830 } else if (y1 === firstPointY) { 27831 firstPointX = Math.min(firstPointX, x); 27832 } 27833 } 27834 edge[0] = (x - shiftedMinX) / bboxWidth; 27835 edge[1] = (y1 - shiftedMinY) / bboxHeight; 27836 edge[2] = (y2 - shiftedMinY) / bboxHeight; 27837 } 27838 this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]); 27839 this.#firstPoint = [firstPointX, firstPointY]; 27840 this.#lastPoint = lastPoint; 27841 } 27842 getOutlines() { 27843 this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); 27844 const outlineVerticalEdges = []; 27845 for (const edge of this.#verticalEdges) { 27846 if (edge[3]) { 27847 outlineVerticalEdges.push(...this.#breakEdge(edge)); 27848 this.#insert(edge); 27849 } else { 27850 this.#remove(edge); 27851 outlineVerticalEdges.push(...this.#breakEdge(edge)); 27852 } 27853 } 27854 return this.#getOutlines(outlineVerticalEdges); 27855 } 27856 #getOutlines(outlineVerticalEdges) { 27857 const edges = []; 27858 const allEdges = new Set(); 27859 for (const edge of outlineVerticalEdges) { 27860 const [x, y1, y2] = edge; 27861 edges.push([x, y1, edge], [x, y2, edge]); 27862 } 27863 edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]); 27864 for (let i = 0, ii = edges.length; i < ii; i += 2) { 27865 const edge1 = edges[i][2]; 27866 const edge2 = edges[i + 1][2]; 27867 edge1.push(edge2); 27868 edge2.push(edge1); 27869 allEdges.add(edge1); 27870 allEdges.add(edge2); 27871 } 27872 const outlines = []; 27873 let outline; 27874 while (allEdges.size > 0) { 27875 const edge = allEdges.values().next().value; 27876 let [x, y1, y2, edge1, edge2] = edge; 27877 allEdges.delete(edge); 27878 let lastPointX = x; 27879 let lastPointY = y1; 27880 outline = [x, y2]; 27881 outlines.push(outline); 27882 while (true) { 27883 let e; 27884 if (allEdges.has(edge1)) { 27885 e = edge1; 27886 } else if (allEdges.has(edge2)) { 27887 e = edge2; 27888 } else { 27889 break; 27890 } 27891 allEdges.delete(e); 27892 [x, y1, y2, edge1, edge2] = e; 27893 if (lastPointX !== x) { 27894 outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2); 27895 lastPointX = x; 27896 } 27897 lastPointY = lastPointY === y1 ? y2 : y1; 27898 } 27899 outline.push(lastPointX, lastPointY); 27900 } 27901 return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint); 27902 } 27903 #binarySearch(y) { 27904 const array = this.#intervals; 27905 let start = 0; 27906 let end = array.length - 1; 27907 while (start <= end) { 27908 const middle = start + end >> 1; 27909 const y1 = array[middle][0]; 27910 if (y1 === y) { 27911 return middle; 27912 } 27913 if (y1 < y) { 27914 start = middle + 1; 27915 } else { 27916 end = middle - 1; 27917 } 27918 } 27919 return end + 1; 27920 } 27921 #insert([, y1, y2]) { 27922 const index = this.#binarySearch(y1); 27923 this.#intervals.splice(index, 0, [y1, y2]); 27924 } 27925 #remove([, y1, y2]) { 27926 const index = this.#binarySearch(y1); 27927 for (let i = index; i < this.#intervals.length; i++) { 27928 const [start, end] = this.#intervals[i]; 27929 if (start !== y1) { 27930 break; 27931 } 27932 if (start === y1 && end === y2) { 27933 this.#intervals.splice(i, 1); 27934 return; 27935 } 27936 } 27937 for (let i = index - 1; i >= 0; i--) { 27938 const [start, end] = this.#intervals[i]; 27939 if (start !== y1) { 27940 break; 27941 } 27942 if (start === y1 && end === y2) { 27943 this.#intervals.splice(i, 1); 27944 return; 27945 } 27946 } 27947 } 27948 #breakEdge(edge) { 27949 const [x, y1, y2] = edge; 27950 const results = [[x, y1, y2]]; 27951 const index = this.#binarySearch(y2); 27952 for (let i = 0; i < index; i++) { 27953 const [start, end] = this.#intervals[i]; 27954 for (let j = 0, jj = results.length; j < jj; j++) { 27955 const [, y3, y4] = results[j]; 27956 if (end <= y3 || y4 <= start) { 27957 continue; 27958 } 27959 if (y3 >= start) { 27960 if (y4 > end) { 27961 results[j][1] = end; 27962 } else { 27963 if (jj === 1) { 27964 return []; 27965 } 27966 results.splice(j, 1); 27967 j--; 27968 jj--; 27969 } 27970 continue; 27971 } 27972 results[j][2] = start; 27973 if (y4 > end) { 27974 results.push([x, end, y4]); 27975 } 27976 } 27977 } 27978 return results; 27979 } 27980} 27981class HighlightOutline extends Outline { 27982 #box; 27983 #outlines; 27984 constructor(outlines, box, firstPoint, lastPoint) { 27985 super(); 27986 this.#outlines = outlines; 27987 this.#box = box; 27988 this.firstPoint = firstPoint; 27989 this.lastPoint = lastPoint; 27990 } 27991 toSVGPath() { 27992 const buffer = []; 27993 for (const polygon of this.#outlines) { 27994 let [prevX, prevY] = polygon; 27995 buffer.push(`M${prevX} ${prevY}`); 27996 for (let i = 2; i < polygon.length; i += 2) { 27997 const x = polygon[i]; 27998 const y = polygon[i + 1]; 27999 if (x === prevX) { 28000 buffer.push(`V${y}`); 28001 prevY = y; 28002 } else if (y === prevY) { 28003 buffer.push(`H${x}`); 28004 prevX = x; 28005 } 28006 } 28007 buffer.push("Z"); 28008 } 28009 return buffer.join(" "); 28010 } 28011 serialize([blX, blY, trX, trY], _rotation) { 28012 const outlines = []; 28013 const width = trX - blX; 28014 const height = trY - blY; 28015 for (const outline of this.#outlines) { 28016 const points = new Array(outline.length); 28017 for (let i = 0; i < outline.length; i += 2) { 28018 points[i] = blX + outline[i] * width; 28019 points[i + 1] = trY - outline[i + 1] * height; 28020 } 28021 outlines.push(points); 28022 } 28023 return outlines; 28024 } 28025 get box() { 28026 return this.#box; 28027 } 28028 get classNamesForOutlining() { 28029 return ["highlightOutline"]; 28030 } 28031} 28032class FreeHighlightOutliner extends FreeDrawOutliner { 28033 newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { 28034 return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR); 28035 } 28036} 28037class FreeHighlightOutline extends FreeDrawOutline { 28038 newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { 28039 return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); 28040 } 28041} 28042 28043;// ./src/display/editor/highlight.js 28044 28045 28046 28047 28048 28049 28050 28051 28052 28053 28054 28055 28056 28057 28058class HighlightEditor extends AnnotationEditor { 28059 #anchorNode = null; 28060 #anchorOffset = 0; 28061 #boxes; 28062 #clipPathId = null; 28063 #colorPicker = null; 28064 #focusOutlines = null; 28065 #focusNode = null; 28066 #focusOffset = 0; 28067 #highlightDiv = null; 28068 #highlightOutlines = null; 28069 #id = null; 28070 #isFreeHighlight = false; 28071 #firstPoint = null; 28072 #lastPoint = null; 28073 #outlineId = null; 28074 #text = ""; 28075 #thickness; 28076 #methodOfCreation = ""; 28077 static _defaultColor = null; 28078 static _defaultOpacity = 1; 28079 static _defaultThickness = 12; 28080 static _type = "highlight"; 28081 static _editorType = AnnotationEditorType.HIGHLIGHT; 28082 static _freeHighlightId = -1; 28083 static _freeHighlight = null; 28084 static _freeHighlightClipId = ""; 28085 static get _keyboardManager() { 28086 const proto = HighlightEditor.prototype; 28087 return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, { 28088 args: [0] 28089 }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, { 28090 args: [1] 28091 }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, { 28092 args: [2] 28093 }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, { 28094 args: [3] 28095 }]])); 28096 } 28097 constructor(params) { 28098 super({ 28099 ...params, 28100 name: "highlightEditor" 28101 }); 28102 this.color = params.color || HighlightEditor._defaultColor; 28103 this.#thickness = params.thickness || HighlightEditor._defaultThickness; 28104 this.opacity = params.opacity || HighlightEditor._defaultOpacity; 28105 this.#boxes = params.boxes || null; 28106 this.#methodOfCreation = params.methodOfCreation || ""; 28107 this.#text = params.text || ""; 28108 this._isDraggable = false; 28109 this.defaultL10nId = "pdfjs-editor-highlight-editor"; 28110 if (params.highlightId > -1) { 28111 this.#isFreeHighlight = true; 28112 this.#createFreeOutlines(params); 28113 this.#addToDrawLayer(); 28114 } else if (this.#boxes) { 28115 this.#anchorNode = params.anchorNode; 28116 this.#anchorOffset = params.anchorOffset; 28117 this.#focusNode = params.focusNode; 28118 this.#focusOffset = params.focusOffset; 28119 this.#createOutlines(); 28120 this.#addToDrawLayer(); 28121 this.rotate(this.rotation); 28122 } 28123 if (!this.annotationElementId) { 28124 this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert"); 28125 } 28126 } 28127 get telemetryInitialData() { 28128 return { 28129 action: "added", 28130 type: this.#isFreeHighlight ? "free_highlight" : "highlight", 28131 color: this._uiManager.getNonHCMColorName(this.color), 28132 thickness: this.#thickness, 28133 methodOfCreation: this.#methodOfCreation 28134 }; 28135 } 28136 get telemetryFinalData() { 28137 return { 28138 type: "highlight", 28139 color: this._uiManager.getNonHCMColorName(this.color) 28140 }; 28141 } 28142 static computeTelemetryFinalData(data) { 28143 return { 28144 numberOfColors: data.get("color").size 28145 }; 28146 } 28147 #createOutlines() { 28148 const outliner = new HighlightOutliner(this.#boxes, 0.001); 28149 this.#highlightOutlines = outliner.getOutlines(); 28150 [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box; 28151 const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr"); 28152 this.#focusOutlines = outlinerForOutline.getOutlines(); 28153 const { 28154 firstPoint 28155 } = this.#highlightOutlines; 28156 this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height]; 28157 const { 28158 lastPoint 28159 } = this.#focusOutlines; 28160 this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height]; 28161 } 28162 #createFreeOutlines({ 28163 highlightOutlines, 28164 highlightId, 28165 clipPathId 28166 }) { 28167 this.#highlightOutlines = highlightOutlines; 28168 const extraThickness = 1.5; 28169 this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025); 28170 if (highlightId >= 0) { 28171 this.#id = highlightId; 28172 this.#clipPathId = clipPathId; 28173 this.parent.drawLayer.finalizeDraw(highlightId, { 28174 bbox: highlightOutlines.box, 28175 path: { 28176 d: highlightOutlines.toSVGPath() 28177 } 28178 }); 28179 this.#outlineId = this.parent.drawLayer.drawOutline({ 28180 rootClass: { 28181 highlightOutline: true, 28182 free: true 28183 }, 28184 bbox: this.#focusOutlines.box, 28185 path: { 28186 d: this.#focusOutlines.toSVGPath() 28187 } 28188 }, true); 28189 } else if (this.parent) { 28190 const angle = this.parent.viewport.rotation; 28191 this.parent.drawLayer.updateProperties(this.#id, { 28192 bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360), 28193 path: { 28194 d: highlightOutlines.toSVGPath() 28195 } 28196 }); 28197 this.parent.drawLayer.updateProperties(this.#outlineId, { 28198 bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), 28199 path: { 28200 d: this.#focusOutlines.toSVGPath() 28201 } 28202 }); 28203 } 28204 const [x, y, width, height] = highlightOutlines.box; 28205 switch (this.rotation) { 28206 case 0: 28207 this.x = x; 28208 this.y = y; 28209 this.width = width; 28210 this.height = height; 28211 break; 28212 case 90: 28213 { 28214 const [pageWidth, pageHeight] = this.parentDimensions; 28215 this.x = y; 28216 this.y = 1 - x; 28217 this.width = width * pageHeight / pageWidth; 28218 this.height = height * pageWidth / pageHeight; 28219 break; 28220 } 28221 case 180: 28222 this.x = 1 - x; 28223 this.y = 1 - y; 28224 this.width = width; 28225 this.height = height; 28226 break; 28227 case 270: 28228 { 28229 const [pageWidth, pageHeight] = this.parentDimensions; 28230 this.x = 1 - y; 28231 this.y = x; 28232 this.width = width * pageHeight / pageWidth; 28233 this.height = height * pageWidth / pageHeight; 28234 break; 28235 } 28236 } 28237 const { 28238 firstPoint 28239 } = highlightOutlines; 28240 this.#firstPoint = [(firstPoint[0] - x) / width, (firstPoint[1] - y) / height]; 28241 const { 28242 lastPoint 28243 } = this.#focusOutlines; 28244 this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height]; 28245 } 28246 static initialize(l10n, uiManager) { 28247 AnnotationEditor.initialize(l10n, uiManager); 28248 HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066"; 28249 } 28250 static updateDefaultParams(type, value) { 28251 switch (type) { 28252 case AnnotationEditorParamsType.HIGHLIGHT_COLOR: 28253 HighlightEditor._defaultColor = value; 28254 break; 28255 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: 28256 HighlightEditor._defaultThickness = value; 28257 break; 28258 } 28259 } 28260 translateInPage(x, y) {} 28261 get toolbarPosition() { 28262 return this.#lastPoint; 28263 } 28264 get commentButtonPosition() { 28265 return this.#firstPoint; 28266 } 28267 updateParams(type, value) { 28268 switch (type) { 28269 case AnnotationEditorParamsType.HIGHLIGHT_COLOR: 28270 this.#updateColor(value); 28271 break; 28272 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: 28273 this.#updateThickness(value); 28274 break; 28275 } 28276 } 28277 static get defaultPropertiesToUpdate() { 28278 return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]]; 28279 } 28280 get propertiesToUpdate() { 28281 return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]]; 28282 } 28283 onUpdatedColor() { 28284 this.parent?.drawLayer.updateProperties(this.#id, { 28285 root: { 28286 fill: this.color, 28287 "fill-opacity": this.opacity 28288 } 28289 }); 28290 this.#colorPicker?.updateColor(this.color); 28291 super.onUpdatedColor(); 28292 } 28293 #updateColor(color) { 28294 const setColorAndOpacity = (col, opa) => { 28295 this.color = col; 28296 this.opacity = opa; 28297 this.onUpdatedColor(); 28298 }; 28299 const savedColor = this.color; 28300 const savedOpacity = this.opacity; 28301 this.addCommands({ 28302 cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity), 28303 undo: setColorAndOpacity.bind(this, savedColor, savedOpacity), 28304 post: this._uiManager.updateUI.bind(this._uiManager, this), 28305 mustExec: true, 28306 type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, 28307 overwriteIfSameType: true, 28308 keepUndo: true 28309 }); 28310 this._reportTelemetry({ 28311 action: "color_changed", 28312 color: this._uiManager.getNonHCMColorName(color) 28313 }, true); 28314 } 28315 #updateThickness(thickness) { 28316 const savedThickness = this.#thickness; 28317 const setThickness = th => { 28318 this.#thickness = th; 28319 this.#changeThickness(th); 28320 }; 28321 this.addCommands({ 28322 cmd: setThickness.bind(this, thickness), 28323 undo: setThickness.bind(this, savedThickness), 28324 post: this._uiManager.updateUI.bind(this._uiManager, this), 28325 mustExec: true, 28326 type: AnnotationEditorParamsType.INK_THICKNESS, 28327 overwriteIfSameType: true, 28328 keepUndo: true 28329 }); 28330 this._reportTelemetry({ 28331 action: "thickness_changed", 28332 thickness 28333 }, true); 28334 } 28335 get toolbarButtons() { 28336 if (this._uiManager.highlightColors) { 28337 const colorPicker = this.#colorPicker = new ColorPicker({ 28338 editor: this 28339 }); 28340 return [["colorPicker", colorPicker]]; 28341 } 28342 return super.toolbarButtons; 28343 } 28344 disableEditing() { 28345 super.disableEditing(); 28346 this.div.classList.toggle("disabled", true); 28347 } 28348 enableEditing() { 28349 super.enableEditing(); 28350 this.div.classList.toggle("disabled", false); 28351 } 28352 fixAndSetPosition() { 28353 return super.fixAndSetPosition(this.#getRotation()); 28354 } 28355 getBaseTranslation() { 28356 return [0, 0]; 28357 } 28358 getRect(tx, ty) { 28359 return super.getRect(tx, ty, this.#getRotation()); 28360 } 28361 onceAdded(focus) { 28362 if (!this.annotationElementId) { 28363 this.parent.addUndoableEditor(this); 28364 } 28365 if (focus) { 28366 this.div.focus(); 28367 } 28368 } 28369 remove() { 28370 this.#cleanDrawLayer(); 28371 this._reportTelemetry({ 28372 action: "deleted" 28373 }); 28374 super.remove(); 28375 } 28376 rebuild() { 28377 if (!this.parent) { 28378 return; 28379 } 28380 super.rebuild(); 28381 if (this.div === null) { 28382 return; 28383 } 28384 this.#addToDrawLayer(); 28385 if (!this.isAttachedToDOM) { 28386 this.parent.add(this); 28387 } 28388 } 28389 setParent(parent) { 28390 let mustBeSelected = false; 28391 if (this.parent && !parent) { 28392 this.#cleanDrawLayer(); 28393 } else if (parent) { 28394 this.#addToDrawLayer(parent); 28395 mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); 28396 } 28397 super.setParent(parent); 28398 this.show(this._isVisible); 28399 if (mustBeSelected) { 28400 this.select(); 28401 } 28402 } 28403 #changeThickness(thickness) { 28404 if (!this.#isFreeHighlight) { 28405 return; 28406 } 28407 this.#createFreeOutlines({ 28408 highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2) 28409 }); 28410 this.fixAndSetPosition(); 28411 this.setDims(); 28412 } 28413 #cleanDrawLayer() { 28414 if (this.#id === null || !this.parent) { 28415 return; 28416 } 28417 this.parent.drawLayer.remove(this.#id); 28418 this.#id = null; 28419 this.parent.drawLayer.remove(this.#outlineId); 28420 this.#outlineId = null; 28421 } 28422 #addToDrawLayer(parent = this.parent) { 28423 if (this.#id !== null) { 28424 return; 28425 } 28426 ({ 28427 id: this.#id, 28428 clipPathId: this.#clipPathId 28429 } = parent.drawLayer.draw({ 28430 bbox: this.#highlightOutlines.box, 28431 root: { 28432 viewBox: "0 0 1 1", 28433 fill: this.color, 28434 "fill-opacity": this.opacity 28435 }, 28436 rootClass: { 28437 highlight: true, 28438 free: this.#isFreeHighlight 28439 }, 28440 path: { 28441 d: this.#highlightOutlines.toSVGPath() 28442 } 28443 }, false, true)); 28444 this.#outlineId = parent.drawLayer.drawOutline({ 28445 rootClass: { 28446 highlightOutline: true, 28447 free: this.#isFreeHighlight 28448 }, 28449 bbox: this.#focusOutlines.box, 28450 path: { 28451 d: this.#focusOutlines.toSVGPath() 28452 } 28453 }, this.#isFreeHighlight); 28454 if (this.#highlightDiv) { 28455 this.#highlightDiv.style.clipPath = this.#clipPathId; 28456 } 28457 } 28458 static #rotateBbox([x, y, width, height], angle) { 28459 switch (angle) { 28460 case 90: 28461 return [1 - y - height, x, height, width]; 28462 case 180: 28463 return [1 - x - width, 1 - y - height, width, height]; 28464 case 270: 28465 return [y, 1 - x - width, height, width]; 28466 } 28467 return [x, y, width, height]; 28468 } 28469 rotate(angle) { 28470 const { 28471 drawLayer 28472 } = this.parent; 28473 let box; 28474 if (this.#isFreeHighlight) { 28475 angle = (angle - this.rotation + 360) % 360; 28476 box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle); 28477 } else { 28478 box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle); 28479 } 28480 drawLayer.updateProperties(this.#id, { 28481 bbox: box, 28482 root: { 28483 "data-main-rotation": angle 28484 } 28485 }); 28486 drawLayer.updateProperties(this.#outlineId, { 28487 bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), 28488 root: { 28489 "data-main-rotation": angle 28490 } 28491 }); 28492 } 28493 render() { 28494 if (this.div) { 28495 return this.div; 28496 } 28497 const div = super.render(); 28498 if (this.#text) { 28499 div.setAttribute("aria-label", this.#text); 28500 div.setAttribute("role", "mark"); 28501 } 28502 if (this.#isFreeHighlight) { 28503 div.classList.add("free"); 28504 } else { 28505 this.div.addEventListener("keydown", this.#keydown.bind(this), { 28506 signal: this._uiManager._signal 28507 }); 28508 } 28509 const highlightDiv = this.#highlightDiv = document.createElement("div"); 28510 div.append(highlightDiv); 28511 highlightDiv.setAttribute("aria-hidden", "true"); 28512 highlightDiv.className = "internal"; 28513 highlightDiv.style.clipPath = this.#clipPathId; 28514 this.setDims(); 28515 bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]); 28516 this.enableEditing(); 28517 return div; 28518 } 28519 pointerover() { 28520 if (!this.isSelected) { 28521 this.parent?.drawLayer.updateProperties(this.#outlineId, { 28522 rootClass: { 28523 hovered: true 28524 } 28525 }); 28526 } 28527 } 28528 pointerleave() { 28529 if (!this.isSelected) { 28530 this.parent?.drawLayer.updateProperties(this.#outlineId, { 28531 rootClass: { 28532 hovered: false 28533 } 28534 }); 28535 } 28536 } 28537 #keydown(event) { 28538 HighlightEditor._keyboardManager.exec(this, event); 28539 } 28540 _moveCaret(direction) { 28541 this.parent.unselect(this); 28542 switch (direction) { 28543 case 0: 28544 case 2: 28545 this.#setCaret(true); 28546 break; 28547 case 1: 28548 case 3: 28549 this.#setCaret(false); 28550 break; 28551 } 28552 } 28553 #setCaret(start) { 28554 if (!this.#anchorNode) { 28555 return; 28556 } 28557 const selection = window.getSelection(); 28558 if (start) { 28559 selection.setPosition(this.#anchorNode, this.#anchorOffset); 28560 } else { 28561 selection.setPosition(this.#focusNode, this.#focusOffset); 28562 } 28563 } 28564 select() { 28565 super.select(); 28566 if (!this.#outlineId) { 28567 return; 28568 } 28569 this.parent?.drawLayer.updateProperties(this.#outlineId, { 28570 rootClass: { 28571 hovered: false, 28572 selected: true 28573 } 28574 }); 28575 } 28576 unselect() { 28577 super.unselect(); 28578 if (!this.#outlineId) { 28579 return; 28580 } 28581 this.parent?.drawLayer.updateProperties(this.#outlineId, { 28582 rootClass: { 28583 selected: false 28584 } 28585 }); 28586 if (!this.#isFreeHighlight) { 28587 this.#setCaret(false); 28588 } 28589 } 28590 get _mustFixPosition() { 28591 return !this.#isFreeHighlight; 28592 } 28593 show(visible = this._isVisible) { 28594 super.show(visible); 28595 if (this.parent) { 28596 this.parent.drawLayer.updateProperties(this.#id, { 28597 rootClass: { 28598 hidden: !visible 28599 } 28600 }); 28601 this.parent.drawLayer.updateProperties(this.#outlineId, { 28602 rootClass: { 28603 hidden: !visible 28604 } 28605 }); 28606 } 28607 } 28608 #getRotation() { 28609 return this.#isFreeHighlight ? this.rotation : 0; 28610 } 28611 #serializeBoxes() { 28612 if (this.#isFreeHighlight) { 28613 return null; 28614 } 28615 const [pageWidth, pageHeight] = this.pageDimensions; 28616 const [pageX, pageY] = this.pageTranslation; 28617 const boxes = this.#boxes; 28618 const quadPoints = new Float32Array(boxes.length * 8); 28619 let i = 0; 28620 for (const { 28621 x, 28622 y, 28623 width, 28624 height 28625 } of boxes) { 28626 const sx = x * pageWidth + pageX; 28627 const sy = (1 - y) * pageHeight + pageY; 28628 quadPoints[i] = quadPoints[i + 4] = sx; 28629 quadPoints[i + 1] = quadPoints[i + 3] = sy; 28630 quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth; 28631 quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight; 28632 i += 8; 28633 } 28634 return quadPoints; 28635 } 28636 #serializeOutlines(rect) { 28637 return this.#highlightOutlines.serialize(rect, this.#getRotation()); 28638 } 28639 static startHighlighting(parent, isLTR, { 28640 target: textLayer, 28641 x, 28642 y 28643 }) { 28644 const { 28645 x: layerX, 28646 y: layerY, 28647 width: parentWidth, 28648 height: parentHeight 28649 } = textLayer.getBoundingClientRect(); 28650 const ac = new AbortController(); 28651 const signal = parent.combinedSignal(ac); 28652 const pointerUpCallback = e => { 28653 ac.abort(); 28654 this.#endHighlight(parent, e); 28655 }; 28656 window.addEventListener("blur", pointerUpCallback, { 28657 signal 28658 }); 28659 window.addEventListener("pointerup", pointerUpCallback, { 28660 signal 28661 }); 28662 window.addEventListener("pointerdown", stopEvent, { 28663 capture: true, 28664 passive: false, 28665 signal 28666 }); 28667 window.addEventListener("contextmenu", noContextMenu, { 28668 signal 28669 }); 28670 textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), { 28671 signal 28672 }); 28673 this._freeHighlight = new FreeHighlightOutliner({ 28674 x, 28675 y 28676 }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001); 28677 ({ 28678 id: this._freeHighlightId, 28679 clipPathId: this._freeHighlightClipId 28680 } = parent.drawLayer.draw({ 28681 bbox: [0, 0, 1, 1], 28682 root: { 28683 viewBox: "0 0 1 1", 28684 fill: this._defaultColor, 28685 "fill-opacity": this._defaultOpacity 28686 }, 28687 rootClass: { 28688 highlight: true, 28689 free: true 28690 }, 28691 path: { 28692 d: this._freeHighlight.toSVGPath() 28693 } 28694 }, true, true)); 28695 } 28696 static #highlightMove(parent, event) { 28697 if (this._freeHighlight.add(event)) { 28698 parent.drawLayer.updateProperties(this._freeHighlightId, { 28699 path: { 28700 d: this._freeHighlight.toSVGPath() 28701 } 28702 }); 28703 } 28704 } 28705 static #endHighlight(parent, event) { 28706 if (!this._freeHighlight.isEmpty()) { 28707 parent.createAndAddNewEditor(event, false, { 28708 highlightId: this._freeHighlightId, 28709 highlightOutlines: this._freeHighlight.getOutlines(), 28710 clipPathId: this._freeHighlightClipId, 28711 methodOfCreation: "main_toolbar" 28712 }); 28713 } else { 28714 parent.drawLayer.remove(this._freeHighlightId); 28715 } 28716 this._freeHighlightId = -1; 28717 this._freeHighlight = null; 28718 this._freeHighlightClipId = ""; 28719 } 28720 static async deserialize(data, parent, uiManager) { 28721 let initialData = null; 28722 if (data instanceof HighlightAnnotationElement) { 28723 const { 28724 data: { 28725 quadPoints, 28726 rect, 28727 rotation, 28728 id, 28729 color, 28730 opacity, 28731 popupRef, 28732 richText, 28733 contentsObj, 28734 creationDate, 28735 modificationDate 28736 }, 28737 parent: { 28738 page: { 28739 pageNumber 28740 } 28741 } 28742 } = data; 28743 initialData = data = { 28744 annotationType: AnnotationEditorType.HIGHLIGHT, 28745 color: Array.from(color), 28746 opacity, 28747 quadPoints, 28748 boxes: null, 28749 pageIndex: pageNumber - 1, 28750 rect: rect.slice(0), 28751 rotation, 28752 annotationElementId: id, 28753 id, 28754 deleted: false, 28755 popupRef, 28756 richText, 28757 comment: contentsObj?.str || null, 28758 creationDate, 28759 modificationDate 28760 }; 28761 } else if (data instanceof InkAnnotationElement) { 28762 const { 28763 data: { 28764 inkLists, 28765 rect, 28766 rotation, 28767 id, 28768 color, 28769 borderStyle: { 28770 rawWidth: thickness 28771 }, 28772 popupRef, 28773 richText, 28774 contentsObj, 28775 creationDate, 28776 modificationDate 28777 }, 28778 parent: { 28779 page: { 28780 pageNumber 28781 } 28782 } 28783 } = data; 28784 initialData = data = { 28785 annotationType: AnnotationEditorType.HIGHLIGHT, 28786 color: Array.from(color), 28787 thickness, 28788 inkLists, 28789 boxes: null, 28790 pageIndex: pageNumber - 1, 28791 rect: rect.slice(0), 28792 rotation, 28793 annotationElementId: id, 28794 id, 28795 deleted: false, 28796 popupRef, 28797 richText, 28798 comment: contentsObj?.str || null, 28799 creationDate, 28800 modificationDate 28801 }; 28802 } 28803 const { 28804 color, 28805 quadPoints, 28806 inkLists, 28807 opacity 28808 } = data; 28809 const editor = await super.deserialize(data, parent, uiManager); 28810 editor.color = Util.makeHexColor(...color); 28811 editor.opacity = opacity || 1; 28812 if (inkLists) { 28813 editor.#thickness = data.thickness; 28814 } 28815 editor._initialData = initialData; 28816 if (data.comment) { 28817 editor.setCommentData(data); 28818 } 28819 const [pageWidth, pageHeight] = editor.pageDimensions; 28820 const [pageX, pageY] = editor.pageTranslation; 28821 if (quadPoints) { 28822 const boxes = editor.#boxes = []; 28823 for (let i = 0; i < quadPoints.length; i += 8) { 28824 boxes.push({ 28825 x: (quadPoints[i] - pageX) / pageWidth, 28826 y: 1 - (quadPoints[i + 1] - pageY) / pageHeight, 28827 width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth, 28828 height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight 28829 }); 28830 } 28831 editor.#createOutlines(); 28832 editor.#addToDrawLayer(); 28833 editor.rotate(editor.rotation); 28834 } else if (inkLists) { 28835 editor.#isFreeHighlight = true; 28836 const points = inkLists[0]; 28837 const point = { 28838 x: points[0] - pageX, 28839 y: pageHeight - (points[1] - pageY) 28840 }; 28841 const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001); 28842 for (let i = 0, ii = points.length; i < ii; i += 2) { 28843 point.x = points[i] - pageX; 28844 point.y = pageHeight - (points[i + 1] - pageY); 28845 outliner.add(point); 28846 } 28847 const { 28848 id, 28849 clipPathId 28850 } = parent.drawLayer.draw({ 28851 bbox: [0, 0, 1, 1], 28852 root: { 28853 viewBox: "0 0 1 1", 28854 fill: editor.color, 28855 "fill-opacity": editor._defaultOpacity 28856 }, 28857 rootClass: { 28858 highlight: true, 28859 free: true 28860 }, 28861 path: { 28862 d: outliner.toSVGPath() 28863 } 28864 }, true, true); 28865 editor.#createFreeOutlines({ 28866 highlightOutlines: outliner.getOutlines(), 28867 highlightId: id, 28868 clipPathId 28869 }); 28870 editor.#addToDrawLayer(); 28871 editor.rotate(editor.parentRotation); 28872 } 28873 return editor; 28874 } 28875 serialize(isForCopying = false) { 28876 if (this.isEmpty() || isForCopying) { 28877 return null; 28878 } 28879 if (this.deleted) { 28880 return this.serializeDeleted(); 28881 } 28882 const color = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); 28883 const serialized = super.serialize(isForCopying); 28884 Object.assign(serialized, { 28885 color, 28886 opacity: this.opacity, 28887 thickness: this.#thickness, 28888 quadPoints: this.#serializeBoxes(), 28889 outlines: this.#serializeOutlines(serialized.rect) 28890 }); 28891 this.addComment(serialized); 28892 if (this.annotationElementId && !this.#hasElementChanged(serialized)) { 28893 return null; 28894 } 28895 serialized.id = this.annotationElementId; 28896 return serialized; 28897 } 28898 #hasElementChanged(serialized) { 28899 const { 28900 color 28901 } = this._initialData; 28902 return this.hasEditedComment || serialized.color.some((c, i) => c !== color[i]); 28903 } 28904 renderAnnotationElement(annotation) { 28905 if (this.deleted) { 28906 annotation.hide(); 28907 return null; 28908 } 28909 annotation.updateEdited({ 28910 rect: this.getPDFRect(), 28911 popup: this.comment 28912 }); 28913 return null; 28914 } 28915 static canCreateNewEmptyEditor() { 28916 return false; 28917 } 28918} 28919 28920;// ./src/display/editor/draw.js 28921 28922 28923 28924 28925 28926 28927 28928 28929 28930 28931 28932 28933class DrawingOptions { 28934 #svgProperties = Object.create(null); 28935 updateProperty(name, value) { 28936 this[name] = value; 28937 this.updateSVGProperty(name, value); 28938 } 28939 updateProperties(properties) { 28940 if (!properties) { 28941 return; 28942 } 28943 for (const [name, value] of Object.entries(properties)) { 28944 if (!name.startsWith("_")) { 28945 this.updateProperty(name, value); 28946 } 28947 } 28948 } 28949 updateSVGProperty(name, value) { 28950 this.#svgProperties[name] = value; 28951 } 28952 toSVGProperties() { 28953 const root = this.#svgProperties; 28954 this.#svgProperties = Object.create(null); 28955 return { 28956 root 28957 }; 28958 } 28959 reset() { 28960 this.#svgProperties = Object.create(null); 28961 } 28962 updateAll(options = this) { 28963 this.updateProperties(options); 28964 } 28965 clone() { 28966 unreachable("Not implemented"); 28967 } 28968} 28969class DrawingEditor extends AnnotationEditor { 28970 #drawOutlines = null; 28971 #mustBeCommitted; 28972 _colorPicker = null; 28973 _drawId = null; 28974 static _currentDrawId = -1; 28975 static _currentParent = null; 28976 static #currentDraw = null; 28977 static #currentDrawingAC = null; 28978 static #currentDrawingOptions = null; 28979 static _INNER_MARGIN = 3; 28980 constructor(params) { 28981 super(params); 28982 this.#mustBeCommitted = params.mustBeCommitted || false; 28983 this._addOutlines(params); 28984 } 28985 onUpdatedColor() { 28986 this._colorPicker?.update(this.color); 28987 super.onUpdatedColor(); 28988 } 28989 _addOutlines(params) { 28990 if (params.drawOutlines) { 28991 this.#createDrawOutlines(params); 28992 this.#addToDrawLayer(); 28993 } 28994 } 28995 #createDrawOutlines({ 28996 drawOutlines, 28997 drawId, 28998 drawingOptions 28999 }) { 29000 this.#drawOutlines = drawOutlines; 29001 this._drawingOptions ||= drawingOptions; 29002 if (!this.annotationElementId) { 29003 this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`); 29004 } 29005 if (drawId >= 0) { 29006 this._drawId = drawId; 29007 this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties); 29008 } else { 29009 this._drawId = this.#createDrawing(drawOutlines, this.parent); 29010 } 29011 this.#updateBbox(drawOutlines.box); 29012 } 29013 #createDrawing(drawOutlines, parent) { 29014 const { 29015 id 29016 } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false); 29017 return id; 29018 } 29019 static _mergeSVGProperties(p1, p2) { 29020 const p1Keys = new Set(Object.keys(p1)); 29021 for (const [key, value] of Object.entries(p2)) { 29022 if (p1Keys.has(key)) { 29023 Object.assign(p1[key], value); 29024 } else { 29025 p1[key] = value; 29026 } 29027 } 29028 return p1; 29029 } 29030 static getDefaultDrawingOptions(_options) { 29031 unreachable("Not implemented"); 29032 } 29033 static get typesMap() { 29034 unreachable("Not implemented"); 29035 } 29036 static get isDrawer() { 29037 return true; 29038 } 29039 static get supportMultipleDrawings() { 29040 return false; 29041 } 29042 static updateDefaultParams(type, value) { 29043 const propertyName = this.typesMap.get(type); 29044 if (propertyName) { 29045 this._defaultDrawingOptions.updateProperty(propertyName, value); 29046 } 29047 if (this._currentParent) { 29048 DrawingEditor.#currentDraw.updateProperty(propertyName, value); 29049 this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); 29050 } 29051 } 29052 updateParams(type, value) { 29053 const propertyName = this.constructor.typesMap.get(type); 29054 if (propertyName) { 29055 this._updateProperty(type, propertyName, value); 29056 } 29057 } 29058 static get defaultPropertiesToUpdate() { 29059 const properties = []; 29060 const options = this._defaultDrawingOptions; 29061 for (const [type, name] of this.typesMap) { 29062 properties.push([type, options[name]]); 29063 } 29064 return properties; 29065 } 29066 get propertiesToUpdate() { 29067 const properties = []; 29068 const { 29069 _drawingOptions 29070 } = this; 29071 for (const [type, name] of this.constructor.typesMap) { 29072 properties.push([type, _drawingOptions[name]]); 29073 } 29074 return properties; 29075 } 29076 _updateProperty(type, name, value) { 29077 const options = this._drawingOptions; 29078 const savedValue = options[name]; 29079 const setter = val => { 29080 options.updateProperty(name, val); 29081 const bbox = this.#drawOutlines.updateProperty(name, val); 29082 if (bbox) { 29083 this.#updateBbox(bbox); 29084 } 29085 this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties()); 29086 if (type === this.colorType) { 29087 this.onUpdatedColor(); 29088 } 29089 }; 29090 this.addCommands({ 29091 cmd: setter.bind(this, value), 29092 undo: setter.bind(this, savedValue), 29093 post: this._uiManager.updateUI.bind(this._uiManager, this), 29094 mustExec: true, 29095 type, 29096 overwriteIfSameType: true, 29097 keepUndo: true 29098 }); 29099 } 29100 _onResizing() { 29101 this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), { 29102 bbox: this.#rotateBox() 29103 })); 29104 } 29105 _onResized() { 29106 this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), { 29107 bbox: this.#rotateBox() 29108 })); 29109 } 29110 _onTranslating(_x, _y) { 29111 this.parent?.drawLayer.updateProperties(this._drawId, { 29112 bbox: this.#rotateBox() 29113 }); 29114 } 29115 _onTranslated() { 29116 this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), { 29117 bbox: this.#rotateBox() 29118 })); 29119 } 29120 _onStartDragging() { 29121 this.parent?.drawLayer.updateProperties(this._drawId, { 29122 rootClass: { 29123 moving: true 29124 } 29125 }); 29126 } 29127 _onStopDragging() { 29128 this.parent?.drawLayer.updateProperties(this._drawId, { 29129 rootClass: { 29130 moving: false 29131 } 29132 }); 29133 } 29134 commit() { 29135 super.commit(); 29136 this.disableEditMode(); 29137 this.disableEditing(); 29138 } 29139 disableEditing() { 29140 super.disableEditing(); 29141 this.div.classList.toggle("disabled", true); 29142 } 29143 enableEditing() { 29144 super.enableEditing(); 29145 this.div.classList.toggle("disabled", false); 29146 } 29147 getBaseTranslation() { 29148 return [0, 0]; 29149 } 29150 get isResizable() { 29151 return true; 29152 } 29153 onceAdded(focus) { 29154 if (!this.annotationElementId) { 29155 this.parent.addUndoableEditor(this); 29156 } 29157 this._isDraggable = true; 29158 if (this.#mustBeCommitted) { 29159 this.#mustBeCommitted = false; 29160 this.commit(); 29161 this.parent.setSelected(this); 29162 if (focus && this.isOnScreen) { 29163 this.div.focus(); 29164 } 29165 } 29166 } 29167 remove() { 29168 this.#cleanDrawLayer(); 29169 super.remove(); 29170 } 29171 rebuild() { 29172 if (!this.parent) { 29173 return; 29174 } 29175 super.rebuild(); 29176 if (this.div === null) { 29177 return; 29178 } 29179 this.#addToDrawLayer(); 29180 this.#updateBbox(this.#drawOutlines.box); 29181 if (!this.isAttachedToDOM) { 29182 this.parent.add(this); 29183 } 29184 } 29185 setParent(parent) { 29186 let mustBeSelected = false; 29187 if (this.parent && !parent) { 29188 this._uiManager.removeShouldRescale(this); 29189 this.#cleanDrawLayer(); 29190 } else if (parent) { 29191 this._uiManager.addShouldRescale(this); 29192 this.#addToDrawLayer(parent); 29193 mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); 29194 } 29195 super.setParent(parent); 29196 if (mustBeSelected) { 29197 this.select(); 29198 } 29199 } 29200 #cleanDrawLayer() { 29201 if (this._drawId === null || !this.parent) { 29202 return; 29203 } 29204 this.parent.drawLayer.remove(this._drawId); 29205 this._drawId = null; 29206 this._drawingOptions.reset(); 29207 } 29208 #addToDrawLayer(parent = this.parent) { 29209 if (this._drawId !== null && this.parent === parent) { 29210 return; 29211 } 29212 if (this._drawId !== null) { 29213 this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer); 29214 return; 29215 } 29216 this._drawingOptions.updateAll(); 29217 this._drawId = this.#createDrawing(this.#drawOutlines, parent); 29218 } 29219 #convertToParentSpace([x, y, width, height]) { 29220 const { 29221 parentDimensions: [pW, pH], 29222 rotation 29223 } = this; 29224 switch (rotation) { 29225 case 90: 29226 return [y, 1 - x, width * (pH / pW), height * (pW / pH)]; 29227 case 180: 29228 return [1 - x, 1 - y, width, height]; 29229 case 270: 29230 return [1 - y, x, width * (pH / pW), height * (pW / pH)]; 29231 default: 29232 return [x, y, width, height]; 29233 } 29234 } 29235 #convertToDrawSpace() { 29236 const { 29237 x, 29238 y, 29239 width, 29240 height, 29241 parentDimensions: [pW, pH], 29242 rotation 29243 } = this; 29244 switch (rotation) { 29245 case 90: 29246 return [1 - y, x, width * (pW / pH), height * (pH / pW)]; 29247 case 180: 29248 return [1 - x, 1 - y, width, height]; 29249 case 270: 29250 return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; 29251 default: 29252 return [x, y, width, height]; 29253 } 29254 } 29255 #updateBbox(bbox) { 29256 [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox); 29257 if (this.div) { 29258 this.fixAndSetPosition(); 29259 this.setDims(); 29260 } 29261 this._onResized(); 29262 } 29263 #rotateBox() { 29264 const { 29265 x, 29266 y, 29267 width, 29268 height, 29269 rotation, 29270 parentRotation, 29271 parentDimensions: [pW, pH] 29272 } = this; 29273 switch ((rotation * 4 + parentRotation) / 90) { 29274 case 1: 29275 return [1 - y - height, x, height, width]; 29276 case 2: 29277 return [1 - x - width, 1 - y - height, width, height]; 29278 case 3: 29279 return [y, 1 - x - width, height, width]; 29280 case 4: 29281 return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; 29282 case 5: 29283 return [1 - y, x, width * (pW / pH), height * (pH / pW)]; 29284 case 6: 29285 return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)]; 29286 case 7: 29287 return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; 29288 case 8: 29289 return [x - width, y - height, width, height]; 29290 case 9: 29291 return [1 - y, x - width, height, width]; 29292 case 10: 29293 return [1 - x, 1 - y, width, height]; 29294 case 11: 29295 return [y - height, 1 - x, height, width]; 29296 case 12: 29297 return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)]; 29298 case 13: 29299 return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; 29300 case 14: 29301 return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; 29302 case 15: 29303 return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; 29304 default: 29305 return [x, y, width, height]; 29306 } 29307 } 29308 rotate() { 29309 if (!this.parent) { 29310 return; 29311 } 29312 this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({ 29313 bbox: this.#rotateBox() 29314 }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360))); 29315 } 29316 onScaleChanging() { 29317 if (!this.parent) { 29318 return; 29319 } 29320 this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale)); 29321 } 29322 static onScaleChangingWhenDrawing() {} 29323 render() { 29324 if (this.div) { 29325 return this.div; 29326 } 29327 let baseX, baseY; 29328 if (this._isCopy) { 29329 baseX = this.x; 29330 baseY = this.y; 29331 } 29332 const div = super.render(); 29333 div.classList.add("draw"); 29334 const drawDiv = document.createElement("div"); 29335 div.append(drawDiv); 29336 drawDiv.setAttribute("aria-hidden", "true"); 29337 drawDiv.className = "internal"; 29338 this.setDims(); 29339 this._uiManager.addShouldRescale(this); 29340 this.disableEditing(); 29341 if (this._isCopy) { 29342 this._moveAfterPaste(baseX, baseY); 29343 } 29344 return div; 29345 } 29346 static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) { 29347 unreachable("Not implemented"); 29348 } 29349 static startDrawing(parent, uiManager, _isLTR, event) { 29350 const { 29351 target, 29352 offsetX: x, 29353 offsetY: y, 29354 pointerId, 29355 pointerType 29356 } = event; 29357 if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) { 29358 return; 29359 } 29360 const { 29361 viewport: { 29362 rotation 29363 } 29364 } = parent; 29365 const { 29366 width: parentWidth, 29367 height: parentHeight 29368 } = target.getBoundingClientRect(); 29369 const ac = DrawingEditor.#currentDrawingAC = new AbortController(); 29370 const signal = parent.combinedSignal(ac); 29371 CurrentPointers.setPointer(pointerType, pointerId); 29372 window.addEventListener("pointerup", e => { 29373 if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) { 29374 this._endDraw(e); 29375 } 29376 }, {
vendor: 5,835 bytes, lines 29377-29558
29377 signal 29378 }); 29379 window.addEventListener("pointercancel", e => { 29380 if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) { 29381 this._currentParent.endDrawingSession(); 29382 } 29383 }, { 29384 signal 29385 }); 29386 window.addEventListener("pointerdown", e => { 29387 if (!CurrentPointers.isSamePointerType(e.pointerType)) { 29388 return; 29389 } 29390 CurrentPointers.initializeAndAddPointerId(e.pointerId); 29391 if (DrawingEditor.#currentDraw.isCancellable()) { 29392 DrawingEditor.#currentDraw.removeLastElement(); 29393 if (DrawingEditor.#currentDraw.isEmpty()) { 29394 this._currentParent.endDrawingSession(true); 29395 } else { 29396 this._endDraw(null); 29397 } 29398 } 29399 }, { 29400 capture: true, 29401 passive: false, 29402 signal 29403 }); 29404 window.addEventListener("contextmenu", noContextMenu, { 29405 signal 29406 }); 29407 target.addEventListener("pointermove", this._drawMove.bind(this), { 29408 signal 29409 }); 29410 target.addEventListener("touchmove", e => { 29411 if (CurrentPointers.isSameTimeStamp(e.timeStamp)) { 29412 stopEvent(e); 29413 } 29414 }, { 29415 signal 29416 }); 29417 parent.toggleDrawing(); 29418 uiManager._editorUndoBar?.hide(); 29419 if (DrawingEditor.#currentDraw) { 29420 parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.startNew(x, y, parentWidth, parentHeight, rotation)); 29421 return; 29422 } 29423 uiManager.updateUIForDefaultProperties(this); 29424 DrawingEditor.#currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation); 29425 DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions(); 29426 this._currentParent = parent; 29427 ({ 29428 id: this._currentDrawId 29429 } = parent.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#currentDrawingOptions.toSVGProperties(), DrawingEditor.#currentDraw.defaultSVGProperties), true, false)); 29430 } 29431 static _drawMove(event) { 29432 CurrentPointers.isSameTimeStamp(event.timeStamp); 29433 if (!DrawingEditor.#currentDraw) { 29434 return; 29435 } 29436 const { 29437 offsetX, 29438 offsetY, 29439 pointerId 29440 } = event; 29441 if (!CurrentPointers.isSamePointerId(pointerId)) { 29442 return; 29443 } 29444 if (CurrentPointers.isUsingMultiplePointers()) { 29445 this._endDraw(event); 29446 return; 29447 } 29448 this._currentParent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.add(offsetX, offsetY)); 29449 CurrentPointers.setTimeStamp(event.timeStamp); 29450 stopEvent(event); 29451 } 29452 static _cleanup(all) { 29453 if (all) { 29454 this._currentDrawId = -1; 29455 this._currentParent = null; 29456 DrawingEditor.#currentDraw = null; 29457 DrawingEditor.#currentDrawingOptions = null; 29458 CurrentPointers.clearTimeStamp(); 29459 } 29460 if (DrawingEditor.#currentDrawingAC) { 29461 DrawingEditor.#currentDrawingAC.abort(); 29462 DrawingEditor.#currentDrawingAC = null; 29463 CurrentPointers.clearPointerIds(); 29464 } 29465 } 29466 static _endDraw(event) { 29467 const parent = this._currentParent; 29468 if (!parent) { 29469 return; 29470 } 29471 parent.toggleDrawing(true); 29472 this._cleanup(false); 29473 if (event?.target === parent.div) { 29474 parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY)); 29475 } 29476 if (this.supportMultipleDrawings) { 29477 const draw = DrawingEditor.#currentDraw; 29478 const drawId = this._currentDrawId; 29479 const lastElement = draw.getLastElement(); 29480 parent.addCommands({ 29481 cmd: () => { 29482 parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement)); 29483 }, 29484 undo: () => { 29485 parent.drawLayer.updateProperties(drawId, draw.removeLastElement()); 29486 }, 29487 mustExec: false, 29488 type: AnnotationEditorParamsType.DRAW_STEP 29489 }); 29490 return; 29491 } 29492 this.endDrawing(false); 29493 } 29494 static endDrawing(isAborted) { 29495 const parent = this._currentParent; 29496 if (!parent) { 29497 return null; 29498 } 29499 parent.toggleDrawing(true); 29500 parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP); 29501 if (!DrawingEditor.#currentDraw.isEmpty()) { 29502 const { 29503 pageDimensions: [pageWidth, pageHeight], 29504 scale 29505 } = parent; 29506 const editor = parent.createAndAddNewEditor({ 29507 offsetX: 0, 29508 offsetY: 0 29509 }, false, { 29510 drawId: this._currentDrawId, 29511 drawOutlines: DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN), 29512 drawingOptions: DrawingEditor.#currentDrawingOptions, 29513 mustBeCommitted: !isAborted 29514 }); 29515 this._cleanup(true); 29516 return editor; 29517 } 29518 parent.drawLayer.remove(this._currentDrawId); 29519 this._cleanup(true); 29520 return null; 29521 } 29522 createDrawingOptions(_data) {} 29523 static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) { 29524 unreachable("Not implemented"); 29525 } 29526 static async deserialize(data, parent, uiManager) { 29527 const { 29528 rawDims: { 29529 pageWidth, 29530 pageHeight, 29531 pageX, 29532 pageY 29533 } 29534 } = parent.viewport; 29535 const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data); 29536 const editor = await super.deserialize(data, parent, uiManager); 29537 editor.createDrawingOptions(data); 29538 editor.#createDrawOutlines({ 29539 drawOutlines 29540 }); 29541 editor.#addToDrawLayer(); 29542 editor.onScaleChanging(); 29543 editor.rotate(); 29544 return editor; 29545 } 29546 serializeDraw(isForCopying) { 29547 const [pageX, pageY] = this.pageTranslation; 29548 const [pageWidth, pageHeight] = this.pageDimensions; 29549 return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying); 29550 } 29551 renderAnnotationElement(annotation) { 29552 annotation.updateEdited({ 29553 rect: this.getPDFRect() 29554 }); 29555 return null; 29556 } 29557 static canCreateNewEmptyEditor() { 29558 return false;
29559 } 29560} 29561 29562;// ./src/display/editor/drawers/inkdraw.js 29563 29564 29565 29566 29567 29568 29569 29570
vendor: 10,994 bytes, lines 29571-29961
29571 29572class InkDrawOutliner { 29573 #last = new Float64Array(6); 29574 #line; 29575 #lines; 29576 #rotation; 29577 #thickness; 29578 #points; 29579 #lastSVGPath = ""; 29580 #lastIndex = 0; 29581 #outlines = new InkDrawOutline(); 29582 #parentWidth; 29583 #parentHeight; 29584 constructor(x, y, parentWidth, parentHeight, rotation, thickness) { 29585 this.#parentWidth = parentWidth; 29586 this.#parentHeight = parentHeight; 29587 this.#rotation = rotation; 29588 this.#thickness = thickness; 29589 [x, y] = this.#normalizePoint(x, y); 29590 const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; 29591 this.#points = [x, y]; 29592 this.#lines = [{ 29593 line, 29594 points: this.#points 29595 }]; 29596 this.#last.set(line, 0); 29597 } 29598 updateProperty(name, value) { 29599 if (name === "stroke-width") { 29600 this.#thickness = value; 29601 } 29602 } 29603 #normalizePoint(x, y) { 29604 return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation); 29605 } 29606 isEmpty() { 29607 return !this.#lines || this.#lines.length === 0; 29608 } 29609 isCancellable() { 29610 return this.#points.length <= 10; 29611 } 29612 add(x, y) { 29613 [x, y] = this.#normalizePoint(x, y); 29614 const [x1, y1, x2, y2] = this.#last.subarray(2, 6); 29615 const diffX = x - x2; 29616 const diffY = y - y2; 29617 const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY); 29618 if (d <= 2) { 29619 return null; 29620 } 29621 this.#points.push(x, y); 29622 if (isNaN(x1)) { 29623 this.#last.set([x2, y2, x, y], 2); 29624 this.#line.push(NaN, NaN, NaN, NaN, x, y); 29625 return { 29626 path: { 29627 d: this.toSVGPath() 29628 } 29629 }; 29630 } 29631 if (isNaN(this.#last[0])) { 29632 this.#line.splice(6, 6); 29633 } 29634 this.#last.set([x1, y1, x2, y2, x, y], 0); 29635 this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y)); 29636 return { 29637 path: { 29638 d: this.toSVGPath() 29639 } 29640 }; 29641 } 29642 end(x, y) { 29643 const change = this.add(x, y); 29644 if (change) { 29645 return change; 29646 } 29647 if (this.#points.length === 2) { 29648 return { 29649 path: { 29650 d: this.toSVGPath() 29651 } 29652 }; 29653 } 29654 return null; 29655 } 29656 startNew(x, y, parentWidth, parentHeight, rotation) { 29657 this.#parentWidth = parentWidth; 29658 this.#parentHeight = parentHeight; 29659 this.#rotation = rotation; 29660 [x, y] = this.#normalizePoint(x, y); 29661 const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; 29662 this.#points = [x, y]; 29663 const last = this.#lines.at(-1); 29664 if (last) { 29665 last.line = new Float32Array(last.line); 29666 last.points = new Float32Array(last.points); 29667 } 29668 this.#lines.push({ 29669 line, 29670 points: this.#points 29671 }); 29672 this.#last.set(line, 0); 29673 this.#lastIndex = 0; 29674 this.toSVGPath(); 29675 return null; 29676 } 29677 getLastElement() { 29678 return this.#lines.at(-1); 29679 } 29680 setLastElement(element) { 29681 if (!this.#lines) { 29682 return this.#outlines.setLastElement(element); 29683 } 29684 this.#lines.push(element); 29685 this.#line = element.line; 29686 this.#points = element.points; 29687 this.#lastIndex = 0; 29688 return { 29689 path: { 29690 d: this.toSVGPath() 29691 } 29692 }; 29693 } 29694 removeLastElement() { 29695 if (!this.#lines) { 29696 return this.#outlines.removeLastElement(); 29697 } 29698 this.#lines.pop(); 29699 this.#lastSVGPath = ""; 29700 for (let i = 0, ii = this.#lines.length; i < ii; i++) { 29701 const { 29702 line, 29703 points 29704 } = this.#lines[i]; 29705 this.#line = line; 29706 this.#points = points; 29707 this.#lastIndex = 0; 29708 this.toSVGPath(); 29709 } 29710 return { 29711 path: { 29712 d: this.#lastSVGPath 29713 } 29714 }; 29715 } 29716 toSVGPath() { 29717 const firstX = Outline.svgRound(this.#line[4]); 29718 const firstY = Outline.svgRound(this.#line[5]); 29719 if (this.#points.length === 2) { 29720 this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`; 29721 return this.#lastSVGPath; 29722 } 29723 if (this.#points.length <= 6) { 29724 const i = this.#lastSVGPath.lastIndexOf("M"); 29725 this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`; 29726 this.#lastIndex = 6; 29727 } 29728 if (this.#points.length === 4) { 29729 const secondX = Outline.svgRound(this.#line[10]); 29730 const secondY = Outline.svgRound(this.#line[11]); 29731 this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`; 29732 this.#lastIndex = 12; 29733 return this.#lastSVGPath; 29734 } 29735 const buffer = []; 29736 if (this.#lastIndex === 0) { 29737 buffer.push(`M ${firstX} ${firstY}`); 29738 this.#lastIndex = 6; 29739 } 29740 for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) { 29741 const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound); 29742 buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); 29743 } 29744 this.#lastSVGPath += buffer.join(" "); 29745 this.#lastIndex = this.#line.length; 29746 return this.#lastSVGPath; 29747 } 29748 getOutlines(parentWidth, parentHeight, scale, innerMargin) { 29749 const last = this.#lines.at(-1); 29750 last.line = new Float32Array(last.line); 29751 last.points = new Float32Array(last.points); 29752 this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin); 29753 this.#last = null; 29754 this.#line = null; 29755 this.#lines = null; 29756 this.#lastSVGPath = null; 29757 return this.#outlines; 29758 } 29759 get defaultSVGProperties() { 29760 return { 29761 root: { 29762 viewBox: "0 0 10000 10000" 29763 }, 29764 rootClass: { 29765 draw: true 29766 }, 29767 bbox: [0, 0, 1, 1] 29768 }; 29769 } 29770} 29771class InkDrawOutline extends Outline { 29772 #bbox; 29773 #currentRotation = 0; 29774 #innerMargin; 29775 #lines; 29776 #parentWidth; 29777 #parentHeight; 29778 #parentScale; 29779 #rotation; 29780 #thickness; 29781 build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) { 29782 this.#parentWidth = parentWidth; 29783 this.#parentHeight = parentHeight; 29784 this.#parentScale = parentScale; 29785 this.#rotation = rotation; 29786 this.#thickness = thickness; 29787 this.#innerMargin = innerMargin ?? 0; 29788 this.#lines = lines; 29789 this.#computeBbox(); 29790 } 29791 get thickness() { 29792 return this.#thickness; 29793 } 29794 setLastElement(element) { 29795 this.#lines.push(element); 29796 return { 29797 path: { 29798 d: this.toSVGPath() 29799 } 29800 }; 29801 } 29802 removeLastElement() { 29803 this.#lines.pop(); 29804 return { 29805 path: { 29806 d: this.toSVGPath() 29807 } 29808 }; 29809 } 29810 toSVGPath() { 29811 const buffer = []; 29812 for (const { 29813 line 29814 } of this.#lines) { 29815 buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`); 29816 if (line.length === 6) { 29817 buffer.push("Z"); 29818 continue; 29819 } 29820 if (line.length === 12 && isNaN(line[6])) { 29821 buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`); 29822 continue; 29823 } 29824 for (let i = 6, ii = line.length; i < ii; i += 6) { 29825 const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound); 29826 buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); 29827 } 29828 } 29829 return buffer.join(""); 29830 } 29831 serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) { 29832 const serializedLines = []; 29833 const serializedPoints = []; 29834 const [x, y, width, height] = this.#getBBoxWithNoMargin(); 29835 let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn; 29836 switch (this.#rotation) { 29837 case 0: 29838 rescaleFn = Outline._rescale; 29839 tx = pageX; 29840 ty = pageY + pageHeight; 29841 sx = pageWidth; 29842 sy = -pageHeight; 29843 x1 = pageX + x * pageWidth; 29844 y1 = pageY + (1 - y - height) * pageHeight; 29845 x2 = pageX + (x + width) * pageWidth; 29846 y2 = pageY + (1 - y) * pageHeight; 29847 break; 29848 case 90: 29849 rescaleFn = Outline._rescaleAndSwap; 29850 tx = pageX; 29851 ty = pageY; 29852 sx = pageWidth; 29853 sy = pageHeight; 29854 x1 = pageX + y * pageWidth; 29855 y1 = pageY + x * pageHeight; 29856 x2 = pageX + (y + height) * pageWidth; 29857 y2 = pageY + (x + width) * pageHeight; 29858 break; 29859 case 180: 29860 rescaleFn = Outline._rescale; 29861 tx = pageX + pageWidth; 29862 ty = pageY; 29863 sx = -pageWidth; 29864 sy = pageHeight; 29865 x1 = pageX + (1 - x - width) * pageWidth; 29866 y1 = pageY + y * pageHeight; 29867 x2 = pageX + (1 - x) * pageWidth; 29868 y2 = pageY + (y + height) * pageHeight; 29869 break; 29870 case 270: 29871 rescaleFn = Outline._rescaleAndSwap; 29872 tx = pageX + pageWidth; 29873 ty = pageY + pageHeight; 29874 sx = -pageWidth; 29875 sy = -pageHeight; 29876 x1 = pageX + (1 - y - height) * pageWidth; 29877 y1 = pageY + (1 - x - width) * pageHeight; 29878 x2 = pageX + (1 - y) * pageWidth; 29879 y2 = pageY + (1 - x) * pageHeight; 29880 break; 29881 } 29882 for (const { 29883 line, 29884 points 29885 } of this.#lines) { 29886 serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null)); 29887 serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null)); 29888 } 29889 return { 29890 lines: serializedLines, 29891 points: serializedPoints, 29892 rect: [x1, y1, x2, y2] 29893 }; 29894 } 29895 static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, { 29896 paths: { 29897 lines, 29898 points 29899 }, 29900 rotation, 29901 thickness 29902 }) { 29903 const newLines = []; 29904 let tx, ty, sx, sy, rescaleFn; 29905 switch (rotation) { 29906 case 0: 29907 rescaleFn = Outline._rescale; 29908 tx = -pageX / pageWidth; 29909 ty = pageY / pageHeight + 1; 29910 sx = 1 / pageWidth; 29911 sy = -1 / pageHeight; 29912 break; 29913 case 90: 29914 rescaleFn = Outline._rescaleAndSwap; 29915 tx = -pageY / pageHeight; 29916 ty = -pageX / pageWidth; 29917 sx = 1 / pageHeight; 29918 sy = 1 / pageWidth; 29919 break; 29920 case 180: 29921 rescaleFn = Outline._rescale; 29922 tx = pageX / pageWidth + 1; 29923 ty = -pageY / pageHeight; 29924 sx = -1 / pageWidth; 29925 sy = 1 / pageHeight; 29926 break; 29927 case 270: 29928 rescaleFn = Outline._rescaleAndSwap; 29929 tx = pageY / pageHeight + 1; 29930 ty = pageX / pageWidth + 1; 29931 sx = -1 / pageHeight; 29932 sy = -1 / pageWidth; 29933 break; 29934 } 29935 if (!lines) { 29936 lines = []; 29937 for (const point of points) { 29938 const len = point.length; 29939 if (len === 2) { 29940 lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]])); 29941 continue; 29942 } 29943 if (len === 4) { 29944 lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]])); 29945 continue; 29946 } 29947 const line = new Float32Array(3 * (len - 2)); 29948 lines.push(line); 29949 let [x1, y1, x2, y2] = point.subarray(0, 4); 29950 line.set([NaN, NaN, NaN, NaN, x1, y1], 0); 29951 for (let i = 4; i < len; i += 2) { 29952 const x = point[i]; 29953 const y = point[i + 1]; 29954 line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3); 29955 [x1, y1, x2, y2] = [x2, y2, x, y]; 29956 } 29957 } 29958 } 29959 for (let i = 0, ii = lines.length; i < ii; i++) { 29960 newLines.push({ 29961 line: rescaleFn(lines[i].map(
vendor: 1,940 bytes, lines 29961-30013
29961x => x ?? NaN), tx, ty, sx, sy), 29962 points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy) 29963 }); 29964 } 29965 const outlines = new this.prototype.constructor(); 29966 outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin); 29967 return outlines; 29968 } 29969 #getMarginComponents(thickness = this.#thickness) { 29970 const margin = this.#innerMargin + thickness / 2 * this.#parentScale; 29971 return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth]; 29972 } 29973 #getBBoxWithNoMargin() { 29974 const [x, y, width, height] = this.#bbox; 29975 const [marginX, marginY] = this.#getMarginComponents(0); 29976 return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY]; 29977 } 29978 #computeBbox() { 29979 const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); 29980 for (const { 29981 line 29982 } of this.#lines) { 29983 if (line.length <= 12) { 29984 for (let i = 4, ii = line.length; i < ii; i += 6) { 29985 Util.pointBoundingBox(line[i], line[i + 1], bbox); 29986 } 29987 continue; 29988 } 29989 let lastX = line[4], 29990 lastY = line[5]; 29991 for (let i = 6, ii = line.length; i < ii; i += 6) { 29992 const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6); 29993 Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox); 29994 lastX = x; 29995 lastY = y; 29996 } 29997 } 29998 const [marginX, marginY] = this.#getMarginComponents(); 29999 bbox[0] = MathClamp(bbox[0] - marginX, 0, 1); 30000 bbox[1] = MathClamp(bbox[1] - marginY, 0, 1); 30001 bbox[2] = MathClamp(bbox[2] + marginX, 0, 1); 30002 bbox[3] = MathClamp(bbox[3] + marginY, 0, 1); 30003 bbox[2] -= bbox[0]; 30004 bbox[3] -= bbox[1]; 30005 } 30006 get box() { 30007 return this.#bbox; 30008 } 30009 updateProperty(name, value) { 30010 if (name === "stroke-width") { 30011 return this.#updateThickness(value); 30012 } 30013 return
vendor: 6,651 bytes, lines 30013-30236
30013 null; 30014 } 30015 #updateThickness(thickness) { 30016 const [oldMarginX, oldMarginY] = this.#getMarginComponents(); 30017 this.#thickness = thickness; 30018 const [newMarginX, newMarginY] = this.#getMarginComponents(); 30019 const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY]; 30020 const bbox = this.#bbox; 30021 bbox[0] -= diffMarginX; 30022 bbox[1] -= diffMarginY; 30023 bbox[2] += 2 * diffMarginX; 30024 bbox[3] += 2 * diffMarginY; 30025 return bbox; 30026 } 30027 updateParentDimensions([width, height], scale) { 30028 const [oldMarginX, oldMarginY] = this.#getMarginComponents(); 30029 this.#parentWidth = width; 30030 this.#parentHeight = height; 30031 this.#parentScale = scale; 30032 const [newMarginX, newMarginY] = this.#getMarginComponents(); 30033 const diffMarginX = newMarginX - oldMarginX; 30034 const diffMarginY = newMarginY - oldMarginY; 30035 const bbox = this.#bbox; 30036 bbox[0] -= diffMarginX; 30037 bbox[1] -= diffMarginY; 30038 bbox[2] += 2 * diffMarginX; 30039 bbox[3] += 2 * diffMarginY; 30040 return bbox; 30041 } 30042 updateRotation(rotation) { 30043 this.#currentRotation = rotation; 30044 return { 30045 path: { 30046 transform: this.rotationTransform 30047 } 30048 }; 30049 } 30050 get viewBox() { 30051 return this.#bbox.map(Outline.svgRound).join(" "); 30052 } 30053 get defaultProperties() { 30054 const [x, y] = this.#bbox; 30055 return { 30056 root: { 30057 viewBox: this.viewBox 30058 }, 30059 path: { 30060 "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}` 30061 } 30062 }; 30063 } 30064 get rotationTransform() { 30065 const [,, width, height] = this.#bbox; 30066 let a = 0, 30067 b = 0, 30068 c = 0, 30069 d = 0, 30070 e = 0, 30071 f = 0; 30072 switch (this.#currentRotation) { 30073 case 90: 30074 b = height / width; 30075 c = -width / height; 30076 e = width; 30077 break; 30078 case 180: 30079 a = -1; 30080 d = -1; 30081 e = width; 30082 f = height; 30083 break; 30084 case 270: 30085 b = -height / width; 30086 c = width / height; 30087 f = height; 30088 break; 30089 default: 30090 return ""; 30091 } 30092 return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`; 30093 } 30094 getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) { 30095 const [marginX, marginY] = this.#getMarginComponents(); 30096 const [x, y, width, height] = this.#bbox; 30097 if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { 30098 const tx = newX + newWidth / 2 - (x + width / 2); 30099 const ty = newY + newHeight / 2 - (y + height / 2); 30100 return { 30101 path: { 30102 "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, 30103 transform: `${this.rotationTransform} translate(${tx} ${ty})` 30104 } 30105 }; 30106 } 30107 const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); 30108 const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); 30109 const s2x = width / newWidth; 30110 const s2y = height / newHeight; 30111 return { 30112 path: { 30113 "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`, 30114 transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})` 30115 } 30116 }; 30117 } 30118 getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) { 30119 const [marginX, marginY] = this.#getMarginComponents(); 30120 const bbox = this.#bbox; 30121 const [x, y, width, height] = bbox; 30122 bbox[0] = newX; 30123 bbox[1] = newY; 30124 bbox[2] = newWidth; 30125 bbox[3] = newHeight; 30126 if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { 30127 const tx = newX + newWidth / 2 - (x + width / 2); 30128 const ty = newY + newHeight / 2 - (y + height / 2); 30129 for (const { 30130 line, 30131 points 30132 } of this.#lines) { 30133 Outline._translate(line, tx, ty, line); 30134 Outline._translate(points, tx, ty, points); 30135 } 30136 return { 30137 root: { 30138 viewBox: this.viewBox 30139 }, 30140 path: { 30141 "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, 30142 transform: this.rotationTransform || null, 30143 d: this.toSVGPath() 30144 } 30145 }; 30146 } 30147 const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); 30148 const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); 30149 const tx = -s1x * (x + marginX) + newX + marginX; 30150 const ty = -s1y * (y + marginY) + newY + marginY; 30151 if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) { 30152 for (const { 30153 line, 30154 points 30155 } of this.#lines) { 30156 Outline._rescale(line, tx, ty, s1x, s1y, line); 30157 Outline._rescale(points, tx, ty, s1x, s1y, points); 30158 } 30159 } 30160 return { 30161 root: { 30162 viewBox: this.viewBox 30163 }, 30164 path: { 30165 "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, 30166 transform: this.rotationTransform || null, 30167 d: this.toSVGPath() 30168 } 30169 }; 30170 } 30171 getPathTranslatedSVGProperties([newX, newY], parentDimensions) { 30172 const [newParentWidth, newParentHeight] = parentDimensions; 30173 const bbox = this.#bbox; 30174 const tx = newX - bbox[0]; 30175 const ty = newY - bbox[1]; 30176 if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) { 30177 for (const { 30178 line, 30179 points 30180 } of this.#lines) { 30181 Outline._translate(line, tx, ty, line); 30182 Outline._translate(points, tx, ty, points); 30183 } 30184 } else { 30185 const sx = this.#parentWidth / newParentWidth; 30186 const sy = this.#parentHeight / newParentHeight; 30187 this.#parentWidth = newParentWidth; 30188 this.#parentHeight = newParentHeight; 30189 for (const { 30190 line, 30191 points 30192 } of this.#lines) { 30193 Outline._rescale(line, tx, ty, sx, sy, line); 30194 Outline._rescale(points, tx, ty, sx, sy, points); 30195 } 30196 bbox[2] *= sx; 30197 bbox[3] *= sy; 30198 } 30199 bbox[0] = newX; 30200 bbox[1] = newY; 30201 return { 30202 root: { 30203 viewBox: this.viewBox 30204 }, 30205 path: { 30206 d: this.toSVGPath(), 30207 "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}` 30208 } 30209 }; 30210 } 30211 get defaultSVGProperties() { 30212 const bbox = this.#bbox; 30213 return { 30214 root: { 30215 viewBox: this.viewBox 30216 }, 30217 rootClass: { 30218 draw: true 30219 }, 30220 path: { 30221 d: this.toSVGPath(), 30222 "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`, 30223 transform: this.rotationTransform || null 30224 }, 30225 bbox 30226 }; 30227 } 30228} 30229 30230;// ./src/display/editor/ink.js 30231 30232 30233 30234 30235 30236
vendor: 6,669 bytes, lines 30237-30493
30237 30238 30239 30240 30241class InkDrawingOptions extends DrawingOptions { 30242 constructor(viewerParameters) { 30243 super(); 30244 this._viewParameters = viewerParameters; 30245 super.updateProperties({ 30246 fill: "none", 30247 stroke: AnnotationEditor._defaultLineColor, 30248 "stroke-opacity": 1, 30249 "stroke-width": 1, 30250 "stroke-linecap": "round", 30251 "stroke-linejoin": "round", 30252 "stroke-miterlimit": 10 30253 }); 30254 } 30255 updateSVGProperty(name, value) { 30256 if (name === "stroke-width") { 30257 value ??= this["stroke-width"]; 30258 value *= this._viewParameters.realScale; 30259 } 30260 super.updateSVGProperty(name, value); 30261 } 30262 clone() { 30263 const clone = new InkDrawingOptions(this._viewParameters); 30264 clone.updateAll(this); 30265 return clone; 30266 } 30267} 30268class InkEditor extends DrawingEditor { 30269 static _type = "ink"; 30270 static _editorType = AnnotationEditorType.INK; 30271 static _defaultDrawingOptions = null; 30272 constructor(params) { 30273 super({ 30274 ...params, 30275 name: "inkEditor" 30276 }); 30277 this._willKeepAspectRatio = true; 30278 this.defaultL10nId = "pdfjs-editor-ink-editor"; 30279 } 30280 static initialize(l10n, uiManager) { 30281 AnnotationEditor.initialize(l10n, uiManager); 30282 this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters); 30283 } 30284 static getDefaultDrawingOptions(options) { 30285 const clone = this._defaultDrawingOptions.clone(); 30286 clone.updateProperties(options); 30287 return clone; 30288 } 30289 static get supportMultipleDrawings() { 30290 return true; 30291 } 30292 static get typesMap() { 30293 return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]])); 30294 } 30295 static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) { 30296 return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]); 30297 } 30298 static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { 30299 return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); 30300 } 30301 static async deserialize(data, parent, uiManager) { 30302 let initialData = null; 30303 if (data instanceof InkAnnotationElement) { 30304 const { 30305 data: { 30306 inkLists, 30307 rect, 30308 rotation, 30309 id, 30310 color, 30311 opacity, 30312 borderStyle: { 30313 rawWidth: thickness 30314 }, 30315 popupRef, 30316 richText, 30317 contentsObj, 30318 creationDate, 30319 modificationDate 30320 }, 30321 parent: { 30322 page: { 30323 pageNumber 30324 } 30325 } 30326 } = data; 30327 initialData = data = { 30328 annotationType: AnnotationEditorType.INK, 30329 color: Array.from(color), 30330 thickness, 30331 opacity, 30332 paths: { 30333 points: inkLists 30334 }, 30335 boxes: null, 30336 pageIndex: pageNumber - 1, 30337 rect: rect.slice(0), 30338 rotation, 30339 annotationElementId: id, 30340 id, 30341 deleted: false, 30342 popupRef, 30343 richText, 30344 comment: contentsObj?.str || null, 30345 creationDate, 30346 modificationDate 30347 }; 30348 } 30349 const editor = await super.deserialize(data, parent, uiManager); 30350 editor._initialData = initialData; 30351 if (data.comment) { 30352 editor.setCommentData(data); 30353 } 30354 return editor; 30355 } 30356 get toolbarButtons() { 30357 this._colorPicker ||= new BasicColorPicker(this); 30358 return [["colorPicker", this._colorPicker]]; 30359 } 30360 get colorType() { 30361 return AnnotationEditorParamsType.INK_COLOR; 30362 } 30363 get color() { 30364 return this._drawingOptions.stroke; 30365 } 30366 get opacity() { 30367 return this._drawingOptions["stroke-opacity"]; 30368 } 30369 onScaleChanging() { 30370 if (!this.parent) { 30371 return; 30372 } 30373 super.onScaleChanging(); 30374 const { 30375 _drawId, 30376 _drawingOptions, 30377 parent 30378 } = this; 30379 _drawingOptions.updateSVGProperty("stroke-width"); 30380 parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties()); 30381 } 30382 static onScaleChangingWhenDrawing() { 30383 const parent = this._currentParent; 30384 if (!parent) { 30385 return; 30386 } 30387 super.onScaleChangingWhenDrawing(); 30388 this._defaultDrawingOptions.updateSVGProperty("stroke-width"); 30389 parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); 30390 } 30391 createDrawingOptions({ 30392 color, 30393 thickness, 30394 opacity 30395 }) { 30396 this._drawingOptions = InkEditor.getDefaultDrawingOptions({ 30397 stroke: Util.makeHexColor(...color), 30398 "stroke-width": thickness, 30399 "stroke-opacity": opacity 30400 }); 30401 } 30402 serialize(isForCopying = false) { 30403 if (this.isEmpty()) { 30404 return null; 30405 } 30406 if (this.deleted) { 30407 return this.serializeDeleted(); 30408 } 30409 const { 30410 lines, 30411 points 30412 } = this.serializeDraw(isForCopying); 30413 const { 30414 _drawingOptions: { 30415 stroke, 30416 "stroke-opacity": opacity, 30417 "stroke-width": thickness 30418 } 30419 } = this; 30420 const serialized = Object.assign(super.serialize(isForCopying), { 30421 color: AnnotationEditor._colorManager.convert(stroke), 30422 opacity, 30423 thickness, 30424 paths: { 30425 lines, 30426 points 30427 } 30428 }); 30429 this.addComment(serialized); 30430 if (isForCopying) { 30431 serialized.isCopy = true; 30432 return serialized; 30433 } 30434 if (this.annotationElementId && !this.#hasElementChanged(serialized)) { 30435 return null; 30436 } 30437 serialized.id = this.annotationElementId; 30438 return serialized; 30439 } 30440 #hasElementChanged(serialized) { 30441 const { 30442 color, 30443 thickness, 30444 opacity, 30445 pageIndex 30446 } = this._initialData; 30447 return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex; 30448 } 30449 renderAnnotationElement(annotation) { 30450 if (this.deleted) { 30451 annotation.hide(); 30452 return null; 30453 } 30454 const { 30455 points, 30456 rect 30457 } = this.serializeDraw(false); 30458 annotation.updateEdited({ 30459 rect, 30460 thickness: this._drawingOptions["stroke-width"], 30461 points, 30462 popup: this.comment 30463 }); 30464 return null; 30465 } 30466} 30467 30468;// ./src/display/editor/drawers/contour.js 30469 30470class ContourDrawOutline extends InkDrawOutline { 30471 toSVGPath() { 30472 let path = super.toSVGPath(); 30473 if (!path.endsWith("Z")) { 30474 path += "Z"; 30475 } 30476 return path; 30477 } 30478} 30479 30480// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.from-base64.js 30481var es_uint8_array_from_base64 = __webpack_require__(5213); 30482;// ./src/display/editor/drawers/signaturedraw.js 30483 30484 30485 30486 30487 30488 30489 30490 30491 30492 30493
vendor: 17,099 bytes, lines 30494-31037
30494 30495 30496 30497 30498 30499const BASE_HEADER_LENGTH = 8; 30500const POINTS_PROPERTIES_NUMBER = 3; 30501class SignatureExtractor { 30502 static #PARAMETERS = { 30503 maxDim: 512, 30504 sigmaSFactor: 0.02, 30505 sigmaR: 25, 30506 kernelSize: 16 30507 }; 30508 static #neighborIndexToId(i0, j0, i, j) { 30509 i -= i0; 30510 j -= j0; 30511 if (i === 0) { 30512 return j > 0 ? 0 : 4; 30513 } 30514 if (i === 1) { 30515 return j + 6; 30516 } 30517 return 2 - j; 30518 } 30519 static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]); 30520 static #clockwiseNonZero(buf, width, i0, j0, i, j, offset) { 30521 const id = this.#neighborIndexToId(i0, j0, i, j); 30522 for (let k = 0; k < 8; k++) { 30523 const kk = (-k + id - offset + 16) % 8; 30524 const shiftI = this.#neighborIdToIndex[2 * kk]; 30525 const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; 30526 if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { 30527 return kk; 30528 } 30529 } 30530 return -1; 30531 } 30532 static #counterClockwiseNonZero(buf, width, i0, j0, i, j, offset) { 30533 const id = this.#neighborIndexToId(i0, j0, i, j); 30534 for (let k = 0; k < 8; k++) { 30535 const kk = (k + id + offset + 16) % 8; 30536 const shiftI = this.#neighborIdToIndex[2 * kk]; 30537 const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; 30538 if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { 30539 return kk; 30540 } 30541 } 30542 return -1; 30543 } 30544 static #findContours(buf, width, height, threshold) { 30545 const N = buf.length; 30546 const types = new Int32Array(N); 30547 for (let i = 0; i < N; i++) { 30548 types[i] = buf[i] <= threshold ? 1 : 0; 30549 } 30550 for (let i = 1; i < height - 1; i++) { 30551 types[i * width] = types[i * width + width - 1] = 0; 30552 } 30553 for (let i = 0; i < width; i++) { 30554 types[i] = types[width * height - 1 - i] = 0; 30555 } 30556 let nbd = 1; 30557 let lnbd; 30558 const contours = []; 30559 for (let i = 1; i < height - 1; i++) { 30560 lnbd = 1; 30561 for (let j = 1; j < width - 1; j++) { 30562 const ij = i * width + j; 30563 const pix = types[ij]; 30564 if (pix === 0) { 30565 continue; 30566 } 30567 let i2 = i; 30568 let j2 = j; 30569 if (pix === 1 && types[ij - 1] === 0) { 30570 nbd += 1; 30571 j2 -= 1; 30572 } else if (pix >= 1 && types[ij + 1] === 0) { 30573 nbd += 1; 30574 j2 += 1; 30575 if (pix > 1) { 30576 lnbd = pix; 30577 } 30578 } else { 30579 if (pix !== 1) { 30580 lnbd = Math.abs(pix); 30581 } 30582 continue; 30583 } 30584 const points = [j, i]; 30585 const isHole = j2 === j + 1; 30586 const contour = { 30587 isHole, 30588 points, 30589 id: nbd, 30590 parent: 0 30591 }; 30592 contours.push(contour); 30593 let contour0; 30594 for (const c of contours) { 30595 if (c.id === lnbd) { 30596 contour0 = c; 30597 break; 30598 } 30599 } 30600 if (!contour0) { 30601 contour.parent = isHole ? lnbd : 0; 30602 } else if (contour0.isHole) { 30603 contour.parent = isHole ? contour0.parent : lnbd; 30604 } else { 30605 contour.parent = isHole ? lnbd : contour0.parent; 30606 } 30607 const k = this.#clockwiseNonZero(types, width, i, j, i2, j2, 0); 30608 if (k === -1) { 30609 types[ij] = -nbd; 30610 if (types[ij] !== 1) { 30611 lnbd = Math.abs(types[ij]); 30612 } 30613 continue; 30614 } 30615 let shiftI = this.#neighborIdToIndex[2 * k]; 30616 let shiftJ = this.#neighborIdToIndex[2 * k + 1]; 30617 const i1 = i + shiftI; 30618 const j1 = j + shiftJ; 30619 i2 = i1; 30620 j2 = j1; 30621 let i3 = i; 30622 let j3 = j; 30623 while (true) { 30624 const kk = this.#counterClockwiseNonZero(types, width, i3, j3, i2, j2, 1); 30625 shiftI = this.#neighborIdToIndex[2 * kk]; 30626 shiftJ = this.#neighborIdToIndex[2 * kk + 1]; 30627 const i4 = i3 + shiftI; 30628 const j4 = j3 + shiftJ; 30629 points.push(j4, i4); 30630 const ij3 = i3 * width + j3; 30631 if (types[ij3 + 1] === 0) { 30632 types[ij3] = -nbd; 30633 } else if (types[ij3] === 1) { 30634 types[ij3] = nbd; 30635 } 30636 if (i4 === i && j4 === j && i3 === i1 && j3 === j1) { 30637 if (types[ij] !== 1) { 30638 lnbd = Math.abs(types[ij]); 30639 } 30640 break; 30641 } else { 30642 i2 = i3; 30643 j2 = j3; 30644 i3 = i4; 30645 j3 = j4; 30646 } 30647 } 30648 } 30649 } 30650 return contours; 30651 } 30652 static #douglasPeuckerHelper(points, start, end, output) { 30653 if (end - start <= 4) { 30654 for (let i = start; i < end - 2; i += 2) { 30655 output.push(points[i], points[i + 1]); 30656 } 30657 return; 30658 } 30659 const ax = points[start]; 30660 const ay = points[start + 1]; 30661 const abx = points[end - 4] - ax; 30662 const aby = points[end - 3] - ay; 30663 const dist = Math.hypot(abx, aby); 30664 const nabx = abx / dist; 30665 const naby = aby / dist; 30666 const aa = nabx * ay - naby * ax; 30667 const m = aby / abx; 30668 const invS = 1 / dist; 30669 const phi = Math.atan(m); 30670 const cosPhi = Math.cos(phi); 30671 const sinPhi = Math.sin(phi); 30672 const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi)); 30673 const poly = invS * (1 - tmax + tmax ** 2); 30674 const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly)); 30675 let dmax = 0; 30676 let index = start; 30677 for (let i = start + 2; i < end - 2; i += 2) { 30678 const d = Math.abs(aa - nabx * points[i + 1] + naby * points[i]); 30679 if (d > dmax) { 30680 index = i; 30681 dmax = d; 30682 } 30683 } 30684 if (dmax > (dist * partialPhi) ** 2) { 30685 this.#douglasPeuckerHelper(points, start, index + 2, output); 30686 this.#douglasPeuckerHelper(points, index, end, output); 30687 } else { 30688 output.push(ax, ay); 30689 } 30690 } 30691 static #douglasPeucker(points) { 30692 const output = []; 30693 const len = points.length; 30694 this.#douglasPeuckerHelper(points, 0, len, output); 30695 output.push(points[len - 2], points[len - 1]); 30696 return output.length <= 4 ? null : output; 30697 } 30698 static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) { 30699 const kernel = new Float32Array(kernelSize ** 2); 30700 const sigmaS2 = -2 * sigmaS ** 2; 30701 const halfSize = kernelSize >> 1; 30702 for (let i = 0; i < kernelSize; i++) { 30703 const x = (i - halfSize) ** 2; 30704 for (let j = 0; j < kernelSize; j++) { 30705 kernel[i * kernelSize + j] = Math.exp((x + (j - halfSize) ** 2) / sigmaS2); 30706 } 30707 } 30708 const rangeValues = new Float32Array(256); 30709 const sigmaR2 = -2 * sigmaR ** 2; 30710 for (let i = 0; i < 256; i++) { 30711 rangeValues[i] = Math.exp(i ** 2 / sigmaR2); 30712 } 30713 const N = buf.length; 30714 const out = new Uint8Array(N); 30715 const histogram = new Uint32Array(256); 30716 for (let i = 0; i < height; i++) { 30717 for (let j = 0; j < width; j++) { 30718 const ij = i * width + j; 30719 const center = buf[ij]; 30720 let sum = 0; 30721 let norm = 0; 30722 for (let k = 0; k < kernelSize; k++) { 30723 const y = i + k - halfSize; 30724 if (y < 0 || y >= height) { 30725 continue; 30726 } 30727 for (let l = 0; l < kernelSize; l++) { 30728 const x = j + l - halfSize; 30729 if (x < 0 || x >= width) { 30730 continue; 30731 } 30732 const neighbour = buf[y * width + x]; 30733 const w = kernel[k * kernelSize + l] * rangeValues[Math.abs(neighbour - center)]; 30734 sum += neighbour * w; 30735 norm += w; 30736 } 30737 } 30738 const pix = out[ij] = Math.round(sum / norm); 30739 histogram[pix]++; 30740 } 30741 } 30742 return [out, histogram]; 30743 } 30744 static #getHistogram(buf) { 30745 const histogram = new Uint32Array(256); 30746 for (const g of buf) { 30747 histogram[g]++; 30748 } 30749 return histogram; 30750 } 30751 static #toUint8(buf) { 30752 const N = buf.length; 30753 const out = new Uint8ClampedArray(N >> 2); 30754 let max = -Infinity; 30755 let min = Infinity; 30756 for (let i = 0, ii = out.length; i < ii; i++) { 30757 const pix = out[i] = buf[i << 2]; 30758 max = Math.max(max, pix); 30759 min = Math.min(min, pix); 30760 } 30761 const ratio = 255 / (max - min); 30762 for (let i = 0, ii = out.length; i < ii; i++) { 30763 out[i] = (out[i] - min) * ratio; 30764 } 30765 return out; 30766 } 30767 static #guessThreshold(histogram) { 30768 let i; 30769 let M = -Infinity; 30770 let L = -Infinity; 30771 const min = histogram.findIndex(v => v !== 0); 30772 let pos = min; 30773 let spos = min; 30774 for (i = min; i < 256; i++) { 30775 const v = histogram[i]; 30776 if (v > M) { 30777 if (i - pos > L) { 30778 L = i - pos; 30779 spos = i - 1; 30780 } 30781 M = v; 30782 pos = i; 30783 } 30784 } 30785 for (i = spos - 1; i >= 0; i--) { 30786 if (histogram[i] > histogram[i + 1]) { 30787 break; 30788 } 30789 } 30790 return i; 30791 } 30792 static #getGrayPixels(bitmap) { 30793 const originalBitmap = bitmap; 30794 const { 30795 width, 30796 height 30797 } = bitmap; 30798 const { 30799 maxDim 30800 } = this.#PARAMETERS; 30801 let newWidth = width; 30802 let newHeight = height; 30803 if (width > maxDim || height > maxDim) { 30804 let prevWidth = width; 30805 let prevHeight = height; 30806 let steps = Math.log2(Math.max(width, height) / maxDim); 30807 const isteps = Math.floor(steps); 30808 steps = steps === isteps ? isteps - 1 : isteps; 30809 for (let i = 0; i < steps; i++) { 30810 newWidth = Math.ceil(prevWidth / 2); 30811 newHeight = Math.ceil(prevHeight / 2); 30812 const offscreen = new OffscreenCanvas(newWidth, newHeight); 30813 const ctx = offscreen.getContext("2d"); 30814 ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); 30815 prevWidth = newWidth; 30816 prevHeight = newHeight; 30817 if (bitmap !== originalBitmap) { 30818 bitmap.close(); 30819 } 30820 bitmap = offscreen.transferToImageBitmap(); 30821 } 30822 const ratio = Math.min(maxDim / newWidth, maxDim / newHeight); 30823 newWidth = Math.round(newWidth * ratio); 30824 newHeight = Math.round(newHeight * ratio); 30825 } 30826 const offscreen = new OffscreenCanvas(newWidth, newHeight); 30827 const ctx = offscreen.getContext("2d", { 30828 willReadFrequently: true 30829 }); 30830 ctx.fillStyle = "white"; 30831 ctx.fillRect(0, 0, newWidth, newHeight); 30832 ctx.filter = "grayscale(1)"; 30833 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight); 30834 const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data; 30835 const uint8Buf = this.#toUint8(grayImage); 30836 return [uint8Buf, newWidth, newHeight]; 30837 } 30838 static extractContoursFromText(text, { 30839 fontFamily, 30840 fontStyle, 30841 fontWeight 30842 }, pageWidth, pageHeight, rotation, innerMargin) { 30843 let canvas = new OffscreenCanvas(1, 1); 30844 let ctx = canvas.getContext("2d", { 30845 alpha: false 30846 }); 30847 const fontSize = 200; 30848 const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; 30849 const { 30850 actualBoundingBoxLeft, 30851 actualBoundingBoxRight, 30852 actualBoundingBoxAscent, 30853 actualBoundingBoxDescent, 30854 fontBoundingBoxAscent, 30855 fontBoundingBoxDescent, 30856 width 30857 } = ctx.measureText(text); 30858 const SCALE = 1.5; 30859 const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE); 30860 const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE); 30861 canvas = new OffscreenCanvas(canvasWidth, canvasHeight); 30862 ctx = canvas.getContext("2d", { 30863 alpha: true, 30864 willReadFrequently: true 30865 }); 30866 ctx.font = font; 30867 ctx.filter = "grayscale(1)"; 30868 ctx.fillStyle = "white"; 30869 ctx.fillRect(0, 0, canvasWidth, canvasHeight); 30870 ctx.fillStyle = "black"; 30871 ctx.fillText(text, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2); 30872 const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data); 30873 const histogram = this.#getHistogram(uint8Buf); 30874 const threshold = this.#guessThreshold(histogram); 30875 const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold); 30876 return this.processDrawnLines({ 30877 lines: { 30878 curves: contourList, 30879 width: canvasWidth, 30880 height: canvasHeight 30881 }, 30882 pageWidth, 30883 pageHeight, 30884 rotation, 30885 innerMargin, 30886 mustSmooth: true, 30887 areContours: true 30888 }); 30889 } 30890 static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) { 30891 const [uint8Buf, width, height] = this.#getGrayPixels(bitmap); 30892 const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize); 30893 const threshold = this.#guessThreshold(histogram); 30894 const contourList = this.#findContours(buffer, width, height, threshold); 30895 return this.processDrawnLines({ 30896 lines: { 30897 curves: contourList, 30898 width, 30899 height 30900 }, 30901 pageWidth, 30902 pageHeight, 30903 rotation, 30904 innerMargin, 30905 mustSmooth: true, 30906 areContours: true 30907 }); 30908 } 30909 static processDrawnLines({ 30910 lines, 30911 pageWidth, 30912 pageHeight, 30913 rotation, 30914 innerMargin, 30915 mustSmooth, 30916 areContours 30917 }) { 30918 if (rotation % 180 !== 0) { 30919 [pageWidth, pageHeight] = [pageHeight, pageWidth]; 30920 } 30921 const { 30922 curves, 30923 width, 30924 height 30925 } = lines; 30926 const thickness = lines.thickness ?? 0; 30927 const linesAndPoints = []; 30928 const ratio = Math.min(pageWidth / width, pageHeight / height); 30929 const xScale = ratio / pageWidth; 30930 const yScale = ratio / pageHeight; 30931 const newCurves = []; 30932 for (const { 30933 points 30934 } of curves) { 30935 const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points; 30936 if (!reducedPoints) { 30937 continue; 30938 } 30939 newCurves.push(reducedPoints); 30940 const len = reducedPoints.length; 30941 const newPoints = new Float32Array(len); 30942 const line = new Float32Array(3 * (len === 2 ? 2 : len - 2)); 30943 linesAndPoints.push({ 30944 line, 30945 points: newPoints 30946 }); 30947 if (len === 2) { 30948 newPoints[0] = reducedPoints[0] * xScale; 30949 newPoints[1] = reducedPoints[1] * yScale; 30950 line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0); 30951 continue; 30952 } 30953 let [x1, y1, x2, y2] = reducedPoints; 30954 x1 *= xScale; 30955 y1 *= yScale; 30956 x2 *= xScale; 30957 y2 *= yScale; 30958 newPoints.set([x1, y1, x2, y2], 0); 30959 line.set([NaN, NaN, NaN, NaN, x1, y1], 0); 30960 for (let i = 4; i < len; i += 2) { 30961 const x = newPoints[i] = reducedPoints[i] * xScale; 30962 const y = newPoints[i + 1] = reducedPoints[i + 1] * yScale; 30963 line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3); 30964 [x1, y1, x2, y2] = [x2, y2, x, y]; 30965 } 30966 } 30967 if (linesAndPoints.length === 0) { 30968 return null; 30969 } 30970 const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline(); 30971 outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin); 30972 return { 30973 outline, 30974 newCurves, 30975 areContours, 30976 thickness, 30977 width, 30978 height 30979 }; 30980 } 30981 static async compressSignature({ 30982 outlines, 30983 areContours, 30984 thickness, 30985 width, 30986 height 30987 }) { 30988 let minDiff = Infinity; 30989 let maxDiff = -Infinity; 30990 let outlinesLength = 0; 30991 for (const points of outlines) { 30992 outlinesLength += points.length; 30993 for (let i = 2, ii = points.length; i < ii; i++) { 30994 const dx = points[i] - points[i - 2]; 30995 minDiff = Math.min(minDiff, dx); 30996 maxDiff = Math.max(maxDiff, dx); 30997 } 30998 } 30999 let bufferType; 31000 if (minDiff >= -128 && maxDiff <= 127) { 31001 bufferType = Int8Array; 31002 } else if (minDiff >= -32768 && maxDiff <= 32767) { 31003 bufferType = Int16Array; 31004 } else { 31005 bufferType = Int32Array; 31006 } 31007 const len = outlines.length; 31008 const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len; 31009 const header = new Uint32Array(headerLength); 31010 let offset = 0; 31011 header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT; 31012 header[offset++] = 0; 31013 header[offset++] = width; 31014 header[offset++] = height; 31015 header[offset++] = areContours ? 0 : 1; 31016 header[offset++] = Math.max(0, Math.floor(thickness ?? 0)); 31017 header[offset++] = len; 31018 header[offset++] = bufferType.BYTES_PER_ELEMENT; 31019 for (const points of outlines) { 31020 header[offset++] = points.length - 2; 31021 header[offset++] = points[0]; 31022 header[offset++] = points[1]; 31023 } 31024 const cs = new CompressionStream("deflate-raw"); 31025 const writer = cs.writable.getWriter(); 31026 await writer.ready; 31027 writer.write(header); 31028 const BufferCtor = bufferType.prototype.constructor; 31029 for (const points of outlines) { 31030 const diffs = new BufferCtor(points.length - 2); 31031 for (let i = 2, ii = points.length; i < ii; i++) { 31032 diffs[i - 2] = points[i] - points[i - 2]; 31033 } 31034 writer.write(diffs); 31035 } 31036 writer.close(); 31037 const b
vendor: 11,797 bytes, lines 31037-31488
31037uf = await new Response(cs.readable).arrayBuffer(); 31038 const bytes = new Uint8Array(buf); 31039 return bytes.toBase64(); 31040 } 31041 static async decompressSignature(signatureData) { 31042 try { 31043 const bytes = Uint8Array.fromBase64(signatureData); 31044 const { 31045 readable, 31046 writable 31047 } = new DecompressionStream("deflate-raw"); 31048 const writer = writable.getWriter(); 31049 await writer.ready; 31050 writer.write(bytes).then(async () => { 31051 await writer.ready; 31052 await writer.close(); 31053 }).catch(() => {}); 31054 let data = null; 31055 let offset = 0; 31056 for await (const chunk of readable) { 31057 data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]); 31058 data.set(chunk, offset); 31059 offset += chunk.length; 31060 } 31061 const header = new Uint32Array(data.buffer, 0, data.length >> 2); 31062 const version = header[1]; 31063 if (version !== 0) { 31064 throw new Error(`Invalid version: ${version}`); 31065 } 31066 const width = header[2]; 31067 const height = header[3]; 31068 const areContours = header[4] === 0; 31069 const thickness = header[5]; 31070 const numberOfDrawings = header[6]; 31071 const bufferType = header[7]; 31072 const outlines = []; 31073 const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT; 31074 let diffs; 31075 switch (bufferType) { 31076 case Int8Array.BYTES_PER_ELEMENT: 31077 diffs = new Int8Array(data.buffer, diffsOffset); 31078 break; 31079 case Int16Array.BYTES_PER_ELEMENT: 31080 diffs = new Int16Array(data.buffer, diffsOffset); 31081 break; 31082 case Int32Array.BYTES_PER_ELEMENT: 31083 diffs = new Int32Array(data.buffer, diffsOffset); 31084 break; 31085 } 31086 offset = 0; 31087 for (let i = 0; i < numberOfDrawings; i++) { 31088 const len = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH]; 31089 const points = new Float32Array(len + 2); 31090 outlines.push(points); 31091 for (let j = 0; j < POINTS_PROPERTIES_NUMBER - 1; j++) { 31092 points[j] = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH + j + 1]; 31093 } 31094 for (let j = 0; j < len; j++) { 31095 points[j + 2] = points[j] + diffs[offset++]; 31096 } 31097 } 31098 return { 31099 areContours, 31100 thickness, 31101 outlines, 31102 width, 31103 height 31104 }; 31105 } catch (e) { 31106 warn(`decompressSignature: ${e}`); 31107 return null; 31108 } 31109 } 31110} 31111 31112;// ./src/display/editor/signature.js 31113 31114 31115 31116 31117 31118 31119 31120 31121 31122 31123 31124 31125class SignatureOptions extends DrawingOptions { 31126 constructor() { 31127 super(); 31128 super.updateProperties({ 31129 fill: AnnotationEditor._defaultLineColor, 31130 "stroke-width": 0 31131 }); 31132 } 31133 clone() { 31134 const clone = new SignatureOptions(); 31135 clone.updateAll(this); 31136 return clone; 31137 } 31138} 31139class DrawnSignatureOptions extends InkDrawingOptions { 31140 constructor(viewerParameters) { 31141 super(viewerParameters); 31142 super.updateProperties({ 31143 stroke: AnnotationEditor._defaultLineColor, 31144 "stroke-width": 1 31145 }); 31146 } 31147 clone() { 31148 const clone = new DrawnSignatureOptions(this._viewParameters); 31149 clone.updateAll(this); 31150 return clone; 31151 } 31152} 31153class SignatureEditor extends DrawingEditor { 31154 #isExtracted = false; 31155 #description = null; 31156 #signatureData = null; 31157 #signatureUUID = null; 31158 static _type = "signature"; 31159 static _editorType = AnnotationEditorType.SIGNATURE; 31160 static _defaultDrawingOptions = null; 31161 constructor(params) { 31162 super({ 31163 ...params, 31164 mustBeCommitted: true, 31165 name: "signatureEditor" 31166 }); 31167 this._willKeepAspectRatio = true; 31168 this.#signatureData = params.signatureData || null; 31169 this.#description = null; 31170 this.defaultL10nId = "pdfjs-editor-signature-editor1"; 31171 } 31172 static initialize(l10n, uiManager) { 31173 AnnotationEditor.initialize(l10n, uiManager); 31174 this._defaultDrawingOptions = new SignatureOptions(); 31175 this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters); 31176 } 31177 static getDefaultDrawingOptions(options) { 31178 const clone = this._defaultDrawingOptions.clone(); 31179 clone.updateProperties(options); 31180 return clone; 31181 } 31182 static get supportMultipleDrawings() { 31183 return false; 31184 } 31185 static get typesMap() { 31186 return shadow(this, "typesMap", new Map()); 31187 } 31188 static get isDrawer() { 31189 return false; 31190 } 31191 get telemetryFinalData() { 31192 return { 31193 type: "signature", 31194 hasDescription: !!this.#description 31195 }; 31196 } 31197 static computeTelemetryFinalData(data) { 31198 const hasDescriptionStats = data.get("hasDescription"); 31199 return { 31200 hasAltText: hasDescriptionStats.get(true) ?? 0, 31201 hasNoAltText: hasDescriptionStats.get(false) ?? 0 31202 }; 31203 } 31204 get isResizable() { 31205 return true; 31206 } 31207 onScaleChanging() { 31208 if (this._drawId === null) { 31209 return; 31210 } 31211 super.onScaleChanging(); 31212 } 31213 render() { 31214 if (this.div) { 31215 return this.div; 31216 } 31217 let baseX, baseY; 31218 const { 31219 _isCopy 31220 } = this; 31221 if (_isCopy) { 31222 this._isCopy = false; 31223 baseX = this.x; 31224 baseY = this.y; 31225 } 31226 super.render(); 31227 if (this._drawId === null) { 31228 if (this.#signatureData) { 31229 const { 31230 lines, 31231 mustSmooth, 31232 areContours, 31233 description, 31234 uuid, 31235 heightInPage 31236 } = this.#signatureData; 31237 const { 31238 rawDims: { 31239 pageWidth, 31240 pageHeight 31241 }, 31242 rotation 31243 } = this.parent.viewport; 31244 const outline = SignatureExtractor.processDrawnLines({ 31245 lines, 31246 pageWidth, 31247 pageHeight, 31248 rotation, 31249 innerMargin: SignatureEditor._INNER_MARGIN, 31250 mustSmooth, 31251 areContours 31252 }); 31253 this.addSignature(outline, heightInPage, description, uuid); 31254 } else { 31255 this.div.setAttribute("data-l10n-args", JSON.stringify({ 31256 description: "" 31257 })); 31258 this.div.hidden = true; 31259 this._uiManager.getSignature(this); 31260 } 31261 } else { 31262 this.div.setAttribute("data-l10n-args", JSON.stringify({ 31263 description: this.#description || "" 31264 })); 31265 } 31266 if (_isCopy) { 31267 this._isCopy = true; 31268 this._moveAfterPaste(baseX, baseY); 31269 } 31270 return this.div; 31271 } 31272 setUuid(uuid) { 31273 this.#signatureUUID = uuid; 31274 this.addEditToolbar(); 31275 } 31276 getUuid() { 31277 return this.#signatureUUID; 31278 } 31279 get description() { 31280 return this.#description; 31281 } 31282 set description(description) { 31283 this.#description = description; 31284 if (!this.div) { 31285 return; 31286 } 31287 this.div.setAttribute("data-l10n-args", JSON.stringify({ 31288 description 31289 })); 31290 super.addEditToolbar().then(toolbar => { 31291 toolbar?.updateEditSignatureButton(description); 31292 }); 31293 } 31294 getSignaturePreview() { 31295 const { 31296 newCurves, 31297 areContours, 31298 thickness, 31299 width, 31300 height 31301 } = this.#signatureData; 31302 const maxDim = Math.max(width, height); 31303 const outlineData = SignatureExtractor.processDrawnLines({ 31304 lines: { 31305 curves: newCurves.map(points => ({ 31306 points 31307 })), 31308 thickness, 31309 width, 31310 height 31311 }, 31312 pageWidth: maxDim, 31313 pageHeight: maxDim, 31314 rotation: 0, 31315 innerMargin: 0, 31316 mustSmooth: false, 31317 areContours 31318 }); 31319 return { 31320 areContours, 31321 outline: outlineData.outline 31322 }; 31323 } 31324 get toolbarButtons() { 31325 if (this._uiManager.signatureManager) { 31326 return [["editSignature", this._uiManager.signatureManager]]; 31327 } 31328 return super.toolbarButtons; 31329 } 31330 addSignature(data, heightInPage, description, uuid) { 31331 const { 31332 x: savedX, 31333 y: savedY 31334 } = this; 31335 const { 31336 outline 31337 } = this.#signatureData = data; 31338 this.#isExtracted = outline instanceof ContourDrawOutline; 31339 this.description = description; 31340 let drawingOptions; 31341 if (this.#isExtracted) { 31342 drawingOptions = SignatureEditor.getDefaultDrawingOptions(); 31343 } else { 31344 drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone(); 31345 drawingOptions.updateProperties({ 31346 "stroke-width": outline.thickness 31347 }); 31348 } 31349 this._addOutlines({ 31350 drawOutlines: outline, 31351 drawingOptions 31352 }); 31353 const [, pageHeight] = this.pageDimensions; 31354 let newHeight = heightInPage / pageHeight; 31355 newHeight = newHeight >= 1 ? 0.5 : newHeight; 31356 this.width *= newHeight / this.height; 31357 if (this.width >= 1) { 31358 newHeight *= 0.9 / this.width; 31359 this.width = 0.9; 31360 } 31361 this.height = newHeight; 31362 this.setDims(); 31363 this.x = savedX; 31364 this.y = savedY; 31365 this.center(); 31366 this._onResized(); 31367 this.onScaleChanging(); 31368 this.rotate(); 31369 this._uiManager.addToAnnotationStorage(this); 31370 this.setUuid(uuid); 31371 this._reportTelemetry({ 31372 action: "pdfjs.signature.inserted", 31373 data: { 31374 hasBeenSaved: !!uuid, 31375 hasDescription: !!description 31376 } 31377 }); 31378 this.div.hidden = false; 31379 } 31380 getFromImage(bitmap) { 31381 const { 31382 rawDims: { 31383 pageWidth, 31384 pageHeight 31385 }, 31386 rotation 31387 } = this.parent.viewport; 31388 return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN); 31389 } 31390 getFromText(text, fontInfo) { 31391 const { 31392 rawDims: { 31393 pageWidth, 31394 pageHeight 31395 }, 31396 rotation 31397 } = this.parent.viewport; 31398 return SignatureExtractor.extractContoursFromText(text, fontInfo, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN); 31399 } 31400 getDrawnSignature(curves) { 31401 const { 31402 rawDims: { 31403 pageWidth, 31404 pageHeight 31405 }, 31406 rotation 31407 } = this.parent.viewport; 31408 return SignatureExtractor.processDrawnLines({ 31409 lines: curves, 31410 pageWidth, 31411 pageHeight, 31412 rotation, 31413 innerMargin: SignatureEditor._INNER_MARGIN, 31414 mustSmooth: false, 31415 areContours: false 31416 }); 31417 } 31418 createDrawingOptions({ 31419 areContours, 31420 thickness 31421 }) { 31422 if (areContours) { 31423 this._drawingOptions = SignatureEditor.getDefaultDrawingOptions(); 31424 } else { 31425 this._drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone(); 31426 this._drawingOptions.updateProperties({ 31427 "stroke-width": thickness 31428 }); 31429 } 31430 } 31431 serialize(isForCopying = false) { 31432 if (this.isEmpty()) { 31433 return null; 31434 } 31435 const { 31436 lines, 31437 points 31438 } = this.serializeDraw(isForCopying); 31439 const { 31440 _drawingOptions: { 31441 "stroke-width": thickness 31442 } 31443 } = this; 31444 const serialized = Object.assign(super.serialize(isForCopying), { 31445 isSignature: true, 31446 areContours: this.#isExtracted, 31447 color: [0, 0, 0], 31448 thickness: this.#isExtracted ? 0 : thickness 31449 }); 31450 this.addComment(serialized); 31451 if (isForCopying) { 31452 serialized.paths = { 31453 lines, 31454 points 31455 }; 31456 serialized.uuid = this.#signatureUUID; 31457 serialized.isCopy = true; 31458 } else { 31459 serialized.lines = lines; 31460 } 31461 if (this.#description) { 31462 serialized.accessibilityData = { 31463 type: "Figure", 31464 alt: this.#description 31465 }; 31466 } 31467 return serialized; 31468 } 31469 static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { 31470 if (data.areContours) { 31471 return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); 31472 } 31473 return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); 31474 } 31475 static async deserialize(data, parent, uiManager) { 31476 const editor = await super.deserialize(data, parent, uiManager); 31477 editor.#isExtracted = data.areContours; 31478 editor.description = data.accessibilityData?.alt || ""; 31479 editor.#signatureUUID = data.uuid; 31480 return editor; 31481 } 31482} 31483 31484;// ./src/display/editor/stamp.js 31485 31486 31487 31488
vendor: 9,537 bytes, lines 31489-31840
31489 31490 31491 31492 31493 31494class StampEditor extends AnnotationEditor { 31495 #bitmap = null; 31496 #bitmapId = null; 31497 #bitmapPromise = null; 31498 #bitmapUrl = null; 31499 #bitmapFile = null; 31500 #bitmapFileName = ""; 31501 #canvas = null; 31502 #missingCanvas = false; 31503 #resizeTimeoutId = null; 31504 #isSvg = false; 31505 #hasBeenAddedInUndoStack = false; 31506 static _type = "stamp"; 31507 static _editorType = AnnotationEditorType.STAMP; 31508 constructor(params) { 31509 super({ 31510 ...params, 31511 name: "stampEditor" 31512 }); 31513 this.#bitmapUrl = params.bitmapUrl; 31514 this.#bitmapFile = params.bitmapFile; 31515 this.defaultL10nId = "pdfjs-editor-stamp-editor"; 31516 } 31517 static initialize(l10n, uiManager) { 31518 AnnotationEditor.initialize(l10n, uiManager); 31519 } 31520 static isHandlingMimeForPasting(mime) { 31521 return SupportedImageMimeTypes.includes(mime); 31522 } 31523 static paste(item, parent) { 31524 parent.pasteEditor({ 31525 mode: AnnotationEditorType.STAMP 31526 }, { 31527 bitmapFile: item.getAsFile() 31528 }); 31529 } 31530 altTextFinish() { 31531 if (this._uiManager.useNewAltTextFlow) { 31532 this.div.hidden = false; 31533 } 31534 super.altTextFinish(); 31535 } 31536 get telemetryFinalData() { 31537 return { 31538 type: "stamp", 31539 hasAltText: !!this.altTextData?.altText 31540 }; 31541 } 31542 static computeTelemetryFinalData(data) { 31543 const hasAltTextStats = data.get("hasAltText"); 31544 return { 31545 hasAltText: hasAltTextStats.get(true) ?? 0, 31546 hasNoAltText: hasAltTextStats.get(false) ?? 0 31547 }; 31548 } 31549 #getBitmapFetched(data, fromId = false) { 31550 if (!data) { 31551 this.remove(); 31552 return; 31553 } 31554 this.#bitmap = data.bitmap; 31555 if (!fromId) { 31556 this.#bitmapId = data.id; 31557 this.#isSvg = data.isSvg; 31558 } 31559 if (data.file) { 31560 this.#bitmapFileName = data.file.name; 31561 } 31562 this.#createCanvas(); 31563 } 31564 #getBitmapDone() { 31565 this.#bitmapPromise = null; 31566 this._uiManager.enableWaiting(false); 31567 if (!this.#canvas) { 31568 return; 31569 } 31570 if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { 31571 this.addEditToolbar().then(() => { 31572 this._editToolbar.hide(); 31573 this._uiManager.editAltText(this, true); 31574 }); 31575 return; 31576 } 31577 if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { 31578 this._reportTelemetry({ 31579 action: "pdfjs.image.image_added", 31580 data: { 31581 alt_text_modal: false, 31582 alt_text_type: "empty" 31583 } 31584 }); 31585 try { 31586 this.mlGuessAltText(); 31587 } catch {} 31588 } 31589 this.div.focus(); 31590 } 31591 async mlGuessAltText(imageData = null, updateAltTextData = true) { 31592 if (this.hasAltTextData()) { 31593 return null; 31594 } 31595 const { 31596 mlManager 31597 } = this._uiManager; 31598 if (!mlManager) { 31599 throw new Error("No ML."); 31600 } 31601 if (!(await mlManager.isEnabledFor("altText"))) { 31602 throw new Error("ML isn't enabled for alt text."); 31603 } 31604 const { 31605 data, 31606 width, 31607 height 31608 } = imageData || this.copyCanvas(null, null, true).imageData; 31609 const response = await mlManager.guess({ 31610 name: "altText", 31611 request: { 31612 data, 31613 width, 31614 height, 31615 channels: data.length / (width * height) 31616 } 31617 }); 31618 if (!response) { 31619 throw new Error("No response from the AI service."); 31620 } 31621 if (response.error) { 31622 throw new Error("Error from the AI service."); 31623 } 31624 if (response.cancel) { 31625 return null; 31626 } 31627 if (!response.output) { 31628 throw new Error("No valid response from the AI service."); 31629 } 31630 const altText = response.output; 31631 await this.setGuessedAltText(altText); 31632 if (updateAltTextData && !this.hasAltTextData()) { 31633 this.altTextData = { 31634 alt: altText, 31635 decorative: false 31636 }; 31637 } 31638 return altText; 31639 } 31640 #getBitmap() { 31641 if (this.#bitmapId) { 31642 this._uiManager.enableWaiting(true); 31643 this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone()); 31644 return; 31645 } 31646 if (this.#bitmapUrl) { 31647 const url = this.#bitmapUrl; 31648 this.#bitmapUrl = null; 31649 this._uiManager.enableWaiting(true); 31650 this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); 31651 return; 31652 } 31653 if (this.#bitmapFile) { 31654 const file = this.#bitmapFile; 31655 this.#bitmapFile = null; 31656 this._uiManager.enableWaiting(true); 31657 this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); 31658 return; 31659 } 31660 const input = document.createElement("input"); 31661 input.type = "file"; 31662 input.accept = SupportedImageMimeTypes.join(","); 31663 const signal = this._uiManager._signal; 31664 this.#bitmapPromise = new Promise(resolve => { 31665 input.addEventListener("change", async () => { 31666 if (!input.files || input.files.length === 0) { 31667 this.remove(); 31668 } else { 31669 this._uiManager.enableWaiting(true); 31670 const data = await this._uiManager.imageManager.getFromFile(input.files[0]); 31671 this._reportTelemetry({ 31672 action: "pdfjs.image.image_selected", 31673 data: { 31674 alt_text_modal: this._uiManager.useNewAltTextFlow 31675 } 31676 }); 31677 this.#getBitmapFetched(data); 31678 } 31679 resolve(); 31680 }, { 31681 signal 31682 }); 31683 input.addEventListener("cancel", () => { 31684 this.remove(); 31685 resolve(); 31686 }, { 31687 signal 31688 }); 31689 }).finally(() => this.#getBitmapDone()); 31690 input.click(); 31691 } 31692 remove() { 31693 if (this.#bitmapId) { 31694 this.#bitmap = null; 31695 this._uiManager.imageManager.deleteId(this.#bitmapId); 31696 this.#canvas?.remove(); 31697 this.#canvas = null; 31698 if (this.#resizeTimeoutId) { 31699 clearTimeout(this.#resizeTimeoutId); 31700 this.#resizeTimeoutId = null; 31701 } 31702 } 31703 super.remove(); 31704 } 31705 rebuild() { 31706 if (!this.parent) { 31707 if (this.#bitmapId) { 31708 this.#getBitmap(); 31709 } 31710 return; 31711 } 31712 super.rebuild(); 31713 if (this.div === null) { 31714 return; 31715 } 31716 if (this.#bitmapId && this.#canvas === null) { 31717 this.#getBitmap(); 31718 } 31719 if (!this.isAttachedToDOM) { 31720 this.parent.add(this); 31721 } 31722 } 31723 onceAdded(focus) { 31724 this._isDraggable = true; 31725 if (focus) { 31726 this.div.focus(); 31727 } 31728 } 31729 isEmpty() { 31730 return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas); 31731 } 31732 get toolbarButtons() { 31733 return [["altText", this.createAltText()]]; 31734 } 31735 get isResizable() { 31736 return true; 31737 } 31738 render() { 31739 if (this.div) { 31740 return this.div; 31741 } 31742 let baseX, baseY; 31743 if (this._isCopy) { 31744 baseX = this.x; 31745 baseY = this.y; 31746 } 31747 super.render(); 31748 this.div.hidden = true; 31749 this.createAltText(); 31750 if (!this.#missingCanvas) { 31751 if (this.#bitmap) { 31752 this.#createCanvas(); 31753 } else { 31754 this.#getBitmap(); 31755 } 31756 } 31757 if (this._isCopy) { 31758 this._moveAfterPaste(baseX, baseY); 31759 } 31760 this._uiManager.addShouldRescale(this); 31761 return this.div; 31762 } 31763 setCanvas(annotationElementId, canvas) { 31764 const { 31765 id: bitmapId, 31766 bitmap 31767 } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas); 31768 canvas.remove(); 31769 if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) { 31770 this.#bitmapId = bitmapId; 31771 if (bitmap) { 31772 this.#bitmap = bitmap; 31773 } 31774 this.#missingCanvas = false; 31775 this.#createCanvas(); 31776 } 31777 } 31778 _onResized() { 31779 this.onScaleChanging(); 31780 } 31781 onScaleChanging() { 31782 if (!this.parent) { 31783 return; 31784 } 31785 if (this.#resizeTimeoutId !== null) { 31786 clearTimeout(this.#resizeTimeoutId); 31787 } 31788 const TIME_TO_WAIT = 200; 31789 this.#resizeTimeoutId = setTimeout(() => { 31790 this.#resizeTimeoutId = null; 31791 this.#drawBitmap(); 31792 }, TIME_TO_WAIT); 31793 } 31794 #createCanvas() { 31795 const { 31796 div 31797 } = this; 31798 let { 31799 width, 31800 height 31801 } = this.#bitmap; 31802 const [pageWidth, pageHeight] = this.pageDimensions; 31803 const MAX_RATIO = 0.75; 31804 if (this.width) { 31805 width = this.width * pageWidth; 31806 height = this.height * pageHeight; 31807 } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) { 31808 const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height); 31809 width *= factor; 31810 height *= factor; 31811 } 31812 this._uiManager.enableWaiting(false); 31813 const canvas = this.#canvas = document.createElement("canvas"); 31814 canvas.setAttribute("role", "img"); 31815 this.addContainer(canvas); 31816 this.width = width / pageWidth; 31817 this.height = height / pageHeight; 31818 this.setDims(); 31819 if (this._initialOptions?.isCentered) { 31820 this.center(); 31821 } else { 31822 this.fixAndSetPosition(); 31823 } 31824 this._initialOptions = null; 31825 if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) { 31826 div.hidden = false; 31827 } 31828 this.#drawBitmap(); 31829 if (!this.#hasBeenAddedInUndoStack) { 31830 this.parent.addUndoableEditor(this); 31831 this.#hasBeenAddedInUndoStack = true; 31832 } 31833 this._reportTelemetry({ 31834 action: "inserted_image" 31835 }); 31836 if (this.#bitmapFileName) { 31837 this.div.setAttribute("aria-description", this.#bitmapFileName); 31838 } 31839 if (!this.annotationElementId) { 31840 this._uiManager.a11yAlert(
vendor: 4,524 bytes, lines 31840-31958
31840"pdfjs-editor-stamp-added-alert"); 31841 } 31842 } 31843 copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) { 31844 if (!maxDataDimension) { 31845 maxDataDimension = 224; 31846 } 31847 const { 31848 width: bitmapWidth, 31849 height: bitmapHeight 31850 } = this.#bitmap; 31851 const outputScale = new OutputScale(); 31852 let bitmap = this.#bitmap; 31853 let width = bitmapWidth, 31854 height = bitmapHeight; 31855 let canvas = null; 31856 if (maxPreviewDimension) { 31857 if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) { 31858 const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight); 31859 width = Math.floor(bitmapWidth * ratio); 31860 height = Math.floor(bitmapHeight * ratio); 31861 } 31862 canvas = document.createElement("canvas"); 31863 const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx); 31864 const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy); 31865 if (!this.#isSvg) { 31866 bitmap = this.#scaleBitmap(scaledWidth, scaledHeight); 31867 } 31868 const ctx = canvas.getContext("2d"); 31869 ctx.filter = this._uiManager.hcmFilter; 31870 let white = "white", 31871 black = "#cfcfd8"; 31872 if (this._uiManager.hcmFilter !== "none") { 31873 black = "black"; 31874 } else if (ColorScheme.isDarkMode) { 31875 white = "#8f8f9d"; 31876 black = "#42414d"; 31877 } 31878 const boxDim = 15; 31879 const boxDimWidth = boxDim * outputScale.sx; 31880 const boxDimHeight = boxDim * outputScale.sy; 31881 const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2); 31882 const patternCtx = pattern.getContext("2d"); 31883 patternCtx.fillStyle = white; 31884 patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2); 31885 patternCtx.fillStyle = black; 31886 patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight); 31887 patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight); 31888 ctx.fillStyle = ctx.createPattern(pattern, "repeat"); 31889 ctx.fillRect(0, 0, scaledWidth, scaledHeight); 31890 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); 31891 } 31892 let imageData = null; 31893 if (createImageData) { 31894 let dataWidth, dataHeight; 31895 if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) { 31896 dataWidth = bitmap.width; 31897 dataHeight = bitmap.height; 31898 } else { 31899 bitmap = this.#bitmap; 31900 if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) { 31901 const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight); 31902 dataWidth = Math.floor(bitmapWidth * ratio); 31903 dataHeight = Math.floor(bitmapHeight * ratio); 31904 if (!this.#isSvg) { 31905 bitmap = this.#scaleBitmap(dataWidth, dataHeight); 31906 } 31907 } 31908 } 31909 const offscreen = new OffscreenCanvas(dataWidth, dataHeight); 31910 const offscreenCtx = offscreen.getContext("2d", { 31911 willReadFrequently: true 31912 }); 31913 offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight); 31914 imageData = { 31915 width: dataWidth, 31916 height: dataHeight, 31917 data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data 31918 }; 31919 } 31920 return { 31921 canvas, 31922 width, 31923 height, 31924 imageData 31925 }; 31926 } 31927 #scaleBitmap(width, height) { 31928 const { 31929 width: bitmapWidth, 31930 height: bitmapHeight 31931 } = this.#bitmap; 31932 let newWidth = bitmapWidth; 31933 let newHeight = bitmapHeight; 31934 let bitmap = this.#bitmap; 31935 while (newWidth > 2 * width || newHeight > 2 * height) { 31936 const prevWidth = newWidth; 31937 const prevHeight = newHeight; 31938 if (newWidth > 2 * width) { 31939 newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2); 31940 } 31941 if (newHeight > 2 * height) { 31942 newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2); 31943 } 31944 const offscreen = new OffscreenCanvas(newWidth, newHeight); 31945 const ctx = offscreen.getContext("2d"); 31946 ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); 31947 bitmap = offscreen.transferToImageBitmap(); 31948 } 31949 return bitmap; 31950 } 31951 #drawBitmap() { 31952 const [parentWidth, parentHeight] = this.parentDimensions; 31953 const { 31954 width, 31955 height 31956 } = this; 31957 const outputScale = new OutputScale(); 31958 const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);
vendor: 16,248 bytes, lines 31959-32504
31959 const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy); 31960 const canvas = this.#canvas; 31961 if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) { 31962 return; 31963 } 31964 canvas.width = scaledWidth; 31965 canvas.height = scaledHeight; 31966 const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight); 31967 const ctx = canvas.getContext("2d"); 31968 ctx.filter = this._uiManager.hcmFilter; 31969 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); 31970 } 31971 #serializeBitmap(toUrl) { 31972 if (toUrl) { 31973 if (this.#isSvg) { 31974 const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId); 31975 if (url) { 31976 return url; 31977 } 31978 } 31979 const canvas = document.createElement("canvas"); 31980 ({ 31981 width: canvas.width, 31982 height: canvas.height 31983 } = this.#bitmap); 31984 const ctx = canvas.getContext("2d"); 31985 ctx.drawImage(this.#bitmap, 0, 0); 31986 return canvas.toDataURL(); 31987 } 31988 if (this.#isSvg) { 31989 const [pageWidth, pageHeight] = this.pageDimensions; 31990 const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS); 31991 const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS); 31992 const offscreen = new OffscreenCanvas(width, height); 31993 const ctx = offscreen.getContext("2d"); 31994 ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height); 31995 return offscreen.transferToImageBitmap(); 31996 } 31997 return structuredClone(this.#bitmap); 31998 } 31999 static async deserialize(data, parent, uiManager) { 32000 let initialData = null; 32001 let missingCanvas = false; 32002 if (data instanceof StampAnnotationElement) { 32003 const { 32004 data: { 32005 rect, 32006 rotation, 32007 id, 32008 structParent, 32009 popupRef, 32010 richText, 32011 contentsObj, 32012 creationDate, 32013 modificationDate 32014 }, 32015 container, 32016 parent: { 32017 page: { 32018 pageNumber 32019 } 32020 }, 32021 canvas 32022 } = data; 32023 let bitmapId, bitmap; 32024 if (canvas) { 32025 delete data.canvas; 32026 ({ 32027 id: bitmapId, 32028 bitmap 32029 } = uiManager.imageManager.getFromCanvas(container.id, canvas)); 32030 canvas.remove(); 32031 } else { 32032 missingCanvas = true; 32033 data._hasNoCanvas = true; 32034 } 32035 const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || ""; 32036 initialData = data = { 32037 annotationType: AnnotationEditorType.STAMP, 32038 bitmapId, 32039 bitmap, 32040 pageIndex: pageNumber - 1, 32041 rect: rect.slice(0), 32042 rotation, 32043 annotationElementId: id, 32044 id, 32045 deleted: false, 32046 accessibilityData: { 32047 decorative: false, 32048 altText 32049 }, 32050 isSvg: false, 32051 structParent, 32052 popupRef, 32053 richText, 32054 comment: contentsObj?.str || null, 32055 creationDate, 32056 modificationDate 32057 }; 32058 } 32059 const editor = await super.deserialize(data, parent, uiManager); 32060 const { 32061 rect, 32062 bitmap, 32063 bitmapUrl, 32064 bitmapId, 32065 isSvg, 32066 accessibilityData 32067 } = data; 32068 if (missingCanvas) { 32069 uiManager.addMissingCanvas(data.id, editor); 32070 editor.#missingCanvas = true; 32071 } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) { 32072 editor.#bitmapId = bitmapId; 32073 if (bitmap) { 32074 editor.#bitmap = bitmap; 32075 } 32076 } else { 32077 editor.#bitmapUrl = bitmapUrl; 32078 } 32079 editor.#isSvg = isSvg; 32080 const [parentWidth, parentHeight] = editor.pageDimensions; 32081 editor.width = (rect[2] - rect[0]) / parentWidth; 32082 editor.height = (rect[3] - rect[1]) / parentHeight; 32083 if (accessibilityData) { 32084 editor.altTextData = accessibilityData; 32085 } 32086 editor._initialData = initialData; 32087 if (data.comment) { 32088 editor.setCommentData(data); 32089 } 32090 editor.#hasBeenAddedInUndoStack = !!initialData; 32091 return editor; 32092 } 32093 serialize(isForCopying = false, context = null) { 32094 if (this.isEmpty()) { 32095 return null; 32096 } 32097 if (this.deleted) { 32098 return this.serializeDeleted(); 32099 } 32100 const serialized = Object.assign(super.serialize(isForCopying), { 32101 bitmapId: this.#bitmapId, 32102 isSvg: this.#isSvg 32103 }); 32104 this.addComment(serialized); 32105 if (isForCopying) { 32106 serialized.bitmapUrl = this.#serializeBitmap(true); 32107 serialized.accessibilityData = this.serializeAltText(true); 32108 serialized.isCopy = true; 32109 return serialized; 32110 } 32111 const { 32112 decorative, 32113 altText 32114 } = this.serializeAltText(false); 32115 if (!decorative && altText) { 32116 serialized.accessibilityData = { 32117 type: "Figure", 32118 alt: altText 32119 }; 32120 } 32121 if (this.annotationElementId) { 32122 const changes = this.#hasElementChanged(serialized); 32123 if (changes.isSame) { 32124 return null; 32125 } 32126 if (changes.isSameAltText) { 32127 delete serialized.accessibilityData; 32128 } else { 32129 serialized.accessibilityData.structParent = this._initialData.structParent ?? -1; 32130 } 32131 serialized.id = this.annotationElementId; 32132 delete serialized.bitmapId; 32133 return serialized; 32134 } 32135 if (context === null) { 32136 return serialized; 32137 } 32138 context.stamps ||= new Map(); 32139 const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null; 32140 if (!context.stamps.has(this.#bitmapId)) { 32141 context.stamps.set(this.#bitmapId, { 32142 area, 32143 serialized 32144 }); 32145 serialized.bitmap = this.#serializeBitmap(false); 32146 } else if (this.#isSvg) { 32147 const prevData = context.stamps.get(this.#bitmapId); 32148 if (area > prevData.area) { 32149 prevData.area = area; 32150 prevData.serialized.bitmap.close(); 32151 prevData.serialized.bitmap = this.#serializeBitmap(false); 32152 } 32153 } 32154 return serialized; 32155 } 32156 #hasElementChanged(serialized) { 32157 const { 32158 pageIndex, 32159 accessibilityData: { 32160 altText 32161 } 32162 } = this._initialData; 32163 const isSamePageIndex = serialized.pageIndex === pageIndex; 32164 const isSameAltText = (serialized.accessibilityData?.alt || "") === altText; 32165 return { 32166 isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText, 32167 isSameAltText 32168 }; 32169 } 32170 renderAnnotationElement(annotation) { 32171 if (this.deleted) { 32172 annotation.hide(); 32173 return null; 32174 } 32175 annotation.updateEdited({ 32176 rect: this.getPDFRect(), 32177 popup: this.comment 32178 }); 32179 return null; 32180 } 32181} 32182 32183;// ./src/display/editor/annotation_editor_layer.js 32184 32185 32186 32187 32188 32189 32190 32191 32192 32193 32194 32195 32196 32197 32198 32199 32200 32201 32202class AnnotationEditorLayer { 32203 #accessibilityManager; 32204 #allowClick = false; 32205 #annotationLayer = null; 32206 #clickAC = null; 32207 #editorFocusTimeoutId = null; 32208 #editors = new Map(); 32209 #hadPointerDown = false; 32210 #isDisabling = false; 32211 #isEnabling = false; 32212 #drawingAC = null; 32213 #focusedElement = null; 32214 #textLayer = null; 32215 #textSelectionAC = null; 32216 #textLayerDblClickAC = null; 32217 #lastPointerDownTimestamp = -1; 32218 #uiManager; 32219 static _initialized = false; 32220 static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map(type => [type._editorType, type])); 32221 constructor({ 32222 uiManager, 32223 pageIndex, 32224 div, 32225 structTreeLayer, 32226 accessibilityManager, 32227 annotationLayer, 32228 drawLayer, 32229 textLayer, 32230 viewport, 32231 l10n 32232 }) { 32233 const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()]; 32234 if (!AnnotationEditorLayer._initialized) { 32235 AnnotationEditorLayer._initialized = true; 32236 for (const editorType of editorTypes) { 32237 editorType.initialize(l10n, uiManager); 32238 } 32239 } 32240 uiManager.registerEditorTypes(editorTypes); 32241 this.#uiManager = uiManager; 32242 this.pageIndex = pageIndex; 32243 this.div = div; 32244 this.#accessibilityManager = accessibilityManager; 32245 this.#annotationLayer = annotationLayer; 32246 this.viewport = viewport; 32247 this.#textLayer = textLayer; 32248 this.drawLayer = drawLayer; 32249 this._structTree = structTreeLayer; 32250 this.#uiManager.addLayer(this); 32251 } 32252 updatePageIndex(newPageIndex) { 32253 for (const editor of this.#allEditorsIterator) { 32254 editor.updatePageIndex(newPageIndex); 32255 } 32256 this.pageIndex = newPageIndex; 32257 this.#uiManager.addLayer(this); 32258 } 32259 async setClonedFrom(clonedFrom) { 32260 if (!clonedFrom) { 32261 return; 32262 } 32263 const promises = []; 32264 for (const editor of clonedFrom.#allEditorsIterator) { 32265 const serialized = editor.serialize(true); 32266 if (!serialized) { 32267 continue; 32268 } 32269 serialized.isCopy = false; 32270 promises.push(this.deserialize(serialized).then(deserialized => { 32271 if (deserialized) { 32272 this.addOrRebuild(deserialized); 32273 } 32274 })); 32275 } 32276 await Promise.all(promises); 32277 } 32278 get isEmpty() { 32279 return this.#editors.size === 0; 32280 } 32281 get isInvisible() { 32282 return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE; 32283 } 32284 updateToolbar(options) { 32285 this.#uiManager.updateToolbar(options); 32286 } 32287 updateMode(mode = this.#uiManager.getMode()) { 32288 this.#cleanup(); 32289 switch (mode) { 32290 case AnnotationEditorType.NONE: 32291 this.div.classList.toggle("nonEditing", true); 32292 this.disableTextSelection(); 32293 this.togglePointerEvents(false); 32294 this.toggleAnnotationLayerPointerEvents(true); 32295 this.disableClick(); 32296 return; 32297 case AnnotationEditorType.INK: 32298 this.disableTextSelection(); 32299 this.togglePointerEvents(true); 32300 this.enableClick(); 32301 break; 32302 case AnnotationEditorType.HIGHLIGHT: 32303 this.enableTextSelection(); 32304 this.togglePointerEvents(false); 32305 this.disableClick(); 32306 break; 32307 default: 32308 this.disableTextSelection(); 32309 this.togglePointerEvents(true); 32310 this.enableClick(); 32311 } 32312 this.toggleAnnotationLayerPointerEvents(false); 32313 const { 32314 classList 32315 } = this.div; 32316 classList.toggle("nonEditing", false); 32317 if (mode === AnnotationEditorType.POPUP) { 32318 classList.toggle("commentEditing", true); 32319 } else { 32320 classList.toggle("commentEditing", false); 32321 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { 32322 classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType); 32323 } 32324 } 32325 this.div.hidden = false; 32326 } 32327 hasTextLayer(textLayer) { 32328 return textLayer === this.#textLayer?.div; 32329 } 32330 setEditingState(isEditing) { 32331 this.#uiManager.setEditingState(isEditing); 32332 } 32333 addCommands(params) { 32334 this.#uiManager.addCommands(params); 32335 } 32336 cleanUndoStack(type) { 32337 this.#uiManager.cleanUndoStack(type); 32338 } 32339 toggleDrawing(enabled = false) { 32340 this.div.classList.toggle("drawing", !enabled); 32341 } 32342 togglePointerEvents(enabled = false) { 32343 this.div.classList.toggle("disabled", !enabled); 32344 } 32345 toggleAnnotationLayerPointerEvents(enabled = false) { 32346 this.#annotationLayer?.togglePointerEvents(enabled); 32347 } 32348 get #allEditorsIterator() { 32349 return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex); 32350 } 32351 async enable() { 32352 this.#isEnabling = true; 32353 this.div.tabIndex = 0; 32354 this.togglePointerEvents(true); 32355 this.div.classList.toggle("nonEditing", false); 32356 this.#textLayerDblClickAC?.abort(); 32357 this.#textLayerDblClickAC = null; 32358 const annotationElementIds = new Set(); 32359 for (const editor of this.#allEditorsIterator) { 32360 editor.enableEditing(); 32361 editor.show(true); 32362 if (editor.annotationElementId) { 32363 this.#uiManager.removeChangedExistingAnnotation(editor); 32364 annotationElementIds.add(editor.annotationElementId); 32365 } 32366 } 32367 const annotationLayer = this.#annotationLayer; 32368 if (annotationLayer) { 32369 for (const editable of annotationLayer.getEditableAnnotations()) { 32370 editable.hide(); 32371 if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { 32372 continue; 32373 } 32374 if (annotationElementIds.has(editable.data.id)) { 32375 continue; 32376 } 32377 const editor = await this.deserialize(editable); 32378 if (!editor) { 32379 continue; 32380 } 32381 this.addOrRebuild(editor); 32382 editor.enableEditing(); 32383 } 32384 } 32385 this.#isEnabling = false; 32386 this.#uiManager._eventBus.dispatch("editorsrendered", { 32387 source: this, 32388 pageNumber: this.pageIndex + 1 32389 }); 32390 } 32391 disable() { 32392 this.#isDisabling = true; 32393 this.div.tabIndex = -1; 32394 this.togglePointerEvents(false); 32395 this.div.classList.toggle("nonEditing", true); 32396 if (this.#textLayer && !this.#textLayerDblClickAC) { 32397 this.#textLayerDblClickAC = new AbortController(); 32398 const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC); 32399 this.#textLayer.div.addEventListener("pointerdown", e => { 32400 const DBL_CLICK_THRESHOLD = 500; 32401 const { 32402 clientX, 32403 clientY, 32404 timeStamp 32405 } = e; 32406 const lastPointerDownTimestamp = this.#lastPointerDownTimestamp; 32407 if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) { 32408 this.#lastPointerDownTimestamp = timeStamp; 32409 return; 32410 } 32411 this.#lastPointerDownTimestamp = -1; 32412 const { 32413 classList 32414 } = this.div; 32415 classList.toggle("getElements", true); 32416 const elements = document.elementsFromPoint(clientX, clientY); 32417 classList.toggle("getElements", false); 32418 if (!this.div.contains(elements[0])) { 32419 return; 32420 } 32421 let id; 32422 const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`); 32423 for (const element of elements) { 32424 if (regex.test(element.id)) { 32425 id = element.id; 32426 break; 32427 } 32428 } 32429 if (!id) { 32430 return; 32431 } 32432 const editor = this.#editors.get(id); 32433 if (editor?.annotationElementId === null) { 32434 e.stopPropagation(); 32435 e.preventDefault(); 32436 editor.dblclick(e); 32437 } 32438 }, { 32439 signal, 32440 capture: true 32441 }); 32442 } 32443 const annotationLayer = this.#annotationLayer; 32444 const needFakeAnnotation = []; 32445 if (annotationLayer) { 32446 const changedAnnotations = new Map(); 32447 const resetAnnotations = new Map(); 32448 for (const editor of this.#allEditorsIterator) { 32449 editor.disableEditing(); 32450 if (!editor.annotationElementId) { 32451 needFakeAnnotation.push(editor); 32452 continue; 32453 } 32454 if (editor.serialize() !== null) { 32455 changedAnnotations.set(editor.annotationElementId, editor); 32456 continue; 32457 } else { 32458 resetAnnotations.set(editor.annotationElementId, editor); 32459 } 32460 this.getEditableAnnotation(editor.annotationElementId)?.show(); 32461 editor.remove(); 32462 } 32463 const editables = annotationLayer.getEditableAnnotations(); 32464 for (const editable of editables) { 32465 const { 32466 id 32467 } = editable.data; 32468 if (this.#uiManager.isDeletedAnnotationElement(id)) { 32469 editable.updateEdited({ 32470 deleted: true 32471 }); 32472 continue; 32473 } 32474 let editor = resetAnnotations.get(id); 32475 if (editor) { 32476 editor.resetAnnotationElement(editable); 32477 editor.show(false); 32478 editable.show(); 32479 continue; 32480 } 32481 editor = changedAnnotations.get(id); 32482 if (editor) { 32483 this.#uiManager.addChangedExistingAnnotation(editor); 32484 if (editor.renderAnnotationElement(editable)) { 32485 editor.show(false); 32486 } 32487 } 32488 editable.show(); 32489 } 32490 } 32491 this.#cleanup(); 32492 if (this.isEmpty) { 32493 this.div.hidden = true; 32494 } 32495 const { 32496 classList 32497 } = this.div; 32498 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { 32499 classList.remove(`${editorType._type}Editing`); 32500 } 32501 this.disableTextSelection(); 32502 this.toggleAnnotationLayerPointerEvents(true); 32503 annotationLayer?.updateFakeAnnotations(needFakeAnnotation); 32504 this.#isDisabling = false;
vendor: 4,515 bytes, lines 32505-32650
32505 } 32506 getEditableAnnotation(id) { 32507 return this.#annotationLayer?.getEditableAnnotation(id) || null; 32508 } 32509 setActiveEditor(editor) { 32510 const currentActive = this.#uiManager.getActive(); 32511 if (currentActive === editor) { 32512 return; 32513 } 32514 this.#uiManager.setActiveEditor(editor); 32515 } 32516 enableTextSelection() { 32517 this.div.tabIndex = -1; 32518 if (this.#textLayer?.div && !this.#textSelectionAC) { 32519 this.#textSelectionAC = new AbortController(); 32520 const signal = this.#uiManager.combinedSignal(this.#textSelectionAC); 32521 this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), { 32522 signal 32523 }); 32524 this.#textLayer.div.classList.add("highlighting"); 32525 } 32526 } 32527 disableTextSelection() { 32528 this.div.tabIndex = 0; 32529 if (this.#textLayer?.div && this.#textSelectionAC) { 32530 this.#textSelectionAC.abort(); 32531 this.#textSelectionAC = null; 32532 this.#textLayer.div.classList.remove("highlighting"); 32533 } 32534 } 32535 #textLayerPointerDown(event) { 32536 this.#uiManager.unselectAll(); 32537 const { 32538 target 32539 } = event; 32540 if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) { 32541 const { 32542 isMac 32543 } = FeatureTest.platform; 32544 if (event.button !== 0 || event.ctrlKey && isMac) { 32545 return; 32546 } 32547 this.#uiManager.showAllEditors("highlight", true, true); 32548 this.#textLayer.div.classList.add("free"); 32549 this.toggleDrawing(); 32550 HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", { 32551 target: this.#textLayer.div, 32552 x: event.x, 32553 y: event.y 32554 }); 32555 this.#textLayer.div.addEventListener("pointerup", () => { 32556 this.#textLayer.div.classList.remove("free"); 32557 this.toggleDrawing(true); 32558 }, { 32559 once: true, 32560 signal: this.#uiManager._signal 32561 }); 32562 event.preventDefault(); 32563 } 32564 } 32565 enableClick() { 32566 if (this.#clickAC) { 32567 return; 32568 } 32569 this.#clickAC = new AbortController(); 32570 const signal = this.#uiManager.combinedSignal(this.#clickAC); 32571 this.div.addEventListener("pointerdown", this.pointerdown.bind(this), { 32572 signal 32573 }); 32574 const pointerup = this.pointerup.bind(this); 32575 this.div.addEventListener("pointerup", pointerup, { 32576 signal 32577 }); 32578 this.div.addEventListener("pointercancel", pointerup, { 32579 signal 32580 }); 32581 } 32582 disableClick() { 32583 this.#clickAC?.abort(); 32584 this.#clickAC = null; 32585 } 32586 attach(editor) { 32587 this.#editors.set(editor.id, editor); 32588 const { 32589 annotationElementId 32590 } = editor; 32591 if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { 32592 this.#uiManager.removeDeletedAnnotationElement(editor); 32593 } 32594 } 32595 detach(editor) { 32596 this.#editors.delete(editor.id); 32597 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); 32598 if (!this.#isDisabling && editor.annotationElementId) { 32599 this.#uiManager.addDeletedAnnotationElement(editor); 32600 } 32601 } 32602 remove(editor) { 32603 this.detach(editor); 32604 this.#uiManager.removeEditor(editor); 32605 editor.div.remove(); 32606 editor.isAttachedToDOM = false; 32607 } 32608 changeParent(editor) { 32609 if (editor.parent === this) { 32610 return; 32611 } 32612 if (editor.parent && editor.annotationElementId) { 32613 this.#uiManager.addDeletedAnnotationElement(editor); 32614 AnnotationEditor.deleteAnnotationElement(editor); 32615 editor.annotationElementId = null; 32616 } 32617 this.attach(editor); 32618 editor.parent?.detach(editor); 32619 editor.setParent(this); 32620 if (editor.div && editor.isAttachedToDOM) { 32621 editor.div.remove(); 32622 this.div.append(editor.div); 32623 } 32624 } 32625 add(editor) { 32626 if (editor.parent === this && editor.isAttachedToDOM) { 32627 return; 32628 } 32629 this.changeParent(editor); 32630 this.#uiManager.addEditor(editor); 32631 this.attach(editor); 32632 if (!editor.isAttachedToDOM) { 32633 const div = editor.render(); 32634 this.div.append(div); 32635 editor.isAttachedToDOM = true; 32636 } 32637 editor.fixAndSetPosition(); 32638 editor.onceAdded(!this.#isEnabling); 32639 this.#uiManager.addToAnnotationStorage(editor); 32640 editor._reportTelemetry(editor.telemetryInitialData); 32641 } 32642 moveEditorInDOM(editor) { 32643 if (!editor.isAttachedToDOM) { 32644 return; 32645 } 32646 const { 32647 activeElement 32648 } = document; 32649 if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) { 32650 editor._focusEventsAllowed = false;
vendor: 4,572 bytes, lines 32651-32819
32651 this.#editorFocusTimeoutId = setTimeout(() => { 32652 this.#editorFocusTimeoutId = null; 32653 if (!editor.div.contains(document.activeElement)) { 32654 editor.div.addEventListener("focusin", () => { 32655 editor._focusEventsAllowed = true; 32656 }, { 32657 once: true, 32658 signal: this.#uiManager._signal 32659 }); 32660 activeElement.focus(); 32661 } else { 32662 editor._focusEventsAllowed = true; 32663 } 32664 }, 0); 32665 } 32666 editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); 32667 } 32668 addOrRebuild(editor) { 32669 if (editor.needsToBeRebuilt()) { 32670 editor.parent ||= this; 32671 editor.rebuild(); 32672 editor.show(); 32673 } else { 32674 this.add(editor); 32675 } 32676 } 32677 addUndoableEditor(editor) { 32678 const cmd = () => editor._uiManager.rebuild(editor); 32679 const undo = () => { 32680 editor.remove(); 32681 }; 32682 this.addCommands({ 32683 cmd, 32684 undo, 32685 mustExec: false 32686 }); 32687 } 32688 getEditorByUID(uid) { 32689 for (const editor of this.#editors.values()) { 32690 if (editor.uid === uid) { 32691 return editor; 32692 } 32693 } 32694 return null; 32695 } 32696 getNextId() { 32697 return this.#uiManager.getId(); 32698 } 32699 get #currentEditorType() { 32700 return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode()); 32701 } 32702 combinedSignal(ac) { 32703 return this.#uiManager.combinedSignal(ac); 32704 } 32705 #createNewEditor(params) { 32706 const editorType = this.#currentEditorType; 32707 return editorType ? new editorType.prototype.constructor(params) : null; 32708 } 32709 canCreateNewEmptyEditor() { 32710 return this.#currentEditorType?.canCreateNewEmptyEditor(); 32711 } 32712 async pasteEditor(options, params) { 32713 this.updateToolbar(options); 32714 await this.#uiManager.updateMode(options.mode); 32715 const { 32716 offsetX, 32717 offsetY 32718 } = this.#getCenterPoint(); 32719 const id = this.getNextId(); 32720 const editor = this.#createNewEditor({ 32721 parent: this, 32722 id, 32723 x: offsetX, 32724 y: offsetY, 32725 uiManager: this.#uiManager, 32726 isCentered: true, 32727 ...params 32728 }); 32729 if (editor) { 32730 this.add(editor); 32731 } 32732 } 32733 async deserialize(data) { 32734 return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null; 32735 } 32736 createAndAddNewEditor(event, isCentered, data = {}) { 32737 const id = this.getNextId(); 32738 const editor = this.#createNewEditor({ 32739 parent: this, 32740 id, 32741 x: event.offsetX, 32742 y: event.offsetY, 32743 uiManager: this.#uiManager, 32744 isCentered, 32745 ...data 32746 }); 32747 if (editor) { 32748 this.add(editor); 32749 } 32750 return editor; 32751 } 32752 get boundingClientRect() { 32753 return this.div.getBoundingClientRect(); 32754 } 32755 #getCenterPoint() { 32756 const { 32757 x, 32758 y, 32759 width, 32760 height 32761 } = this.boundingClientRect; 32762 const tlX = Math.max(0, x); 32763 const tlY = Math.max(0, y); 32764 const brX = Math.min(window.innerWidth, x + width); 32765 const brY = Math.min(window.innerHeight, y + height); 32766 const centerX = (tlX + brX) / 2 - x; 32767 const centerY = (tlY + brY) / 2 - y; 32768 const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; 32769 return { 32770 offsetX, 32771 offsetY 32772 }; 32773 } 32774 addNewEditor(data = {}) { 32775 this.createAndAddNewEditor(this.#getCenterPoint(), true, data); 32776 } 32777 setSelected(editor) { 32778 this.#uiManager.setSelected(editor); 32779 } 32780 toggleSelected(editor) { 32781 this.#uiManager.toggleSelected(editor); 32782 } 32783 unselect(editor) { 32784 this.#uiManager.unselect(editor); 32785 } 32786 pointerup(event) { 32787 const { 32788 isMac 32789 } = FeatureTest.platform; 32790 if (event.button !== 0 || event.ctrlKey && isMac) { 32791 return; 32792 } 32793 if (event.target !== this.div) { 32794 return; 32795 } 32796 if (!this.#hadPointerDown) { 32797 return; 32798 } 32799 this.#hadPointerDown = false; 32800 if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) { 32801 return; 32802 } 32803 if (!this.#allowClick) { 32804 this.#allowClick = true; 32805 return; 32806 } 32807 const currentMode = this.#uiManager.getMode(); 32808 if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) { 32809 this.#uiManager.unselectAll(); 32810 return; 32811 } 32812 this.createAndAddNewEditor(event, false); 32813 } 32814 pointerdown(event) { 32815 if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) { 32816 this.enableTextSelection(); 32817 } 32818 if (this.#hadPointerDown) { 32819 this.#hadPointerDown = false;
vendor: 8,453 bytes, lines 32820-33122
32820 return; 32821 } 32822 const { 32823 isMac 32824 } = FeatureTest.platform; 32825 if (event.button !== 0 || event.ctrlKey && isMac) { 32826 return; 32827 } 32828 if (event.target !== this.div) { 32829 return; 32830 } 32831 this.#hadPointerDown = true; 32832 if (this.#currentEditorType?.isDrawer) { 32833 this.startDrawingSession(event); 32834 return; 32835 } 32836 const editor = this.#uiManager.getActive(); 32837 this.#allowClick = !editor || editor.isEmpty(); 32838 } 32839 startDrawingSession(event) { 32840 this.div.focus({ 32841 preventScroll: true 32842 }); 32843 if (this.#drawingAC) { 32844 this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); 32845 return; 32846 } 32847 this.#uiManager.setCurrentDrawingSession(this); 32848 this.#drawingAC = new AbortController(); 32849 const signal = this.#uiManager.combinedSignal(this.#drawingAC); 32850 this.div.addEventListener("blur", ({ 32851 relatedTarget 32852 }) => { 32853 if (relatedTarget && !this.div.contains(relatedTarget)) { 32854 this.#focusedElement = null; 32855 this.commitOrRemove(); 32856 } 32857 }, { 32858 signal 32859 }); 32860 this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); 32861 } 32862 pause(on) { 32863 if (on) { 32864 const { 32865 activeElement 32866 } = document; 32867 if (this.div.contains(activeElement)) { 32868 this.#focusedElement = activeElement; 32869 } 32870 return; 32871 } 32872 if (this.#focusedElement) { 32873 setTimeout(() => { 32874 this.#focusedElement?.focus(); 32875 this.#focusedElement = null; 32876 }, 0); 32877 } 32878 } 32879 endDrawingSession(isAborted = false) { 32880 if (!this.#drawingAC) { 32881 return null; 32882 } 32883 this.#uiManager.setCurrentDrawingSession(null); 32884 this.#drawingAC.abort(); 32885 this.#drawingAC = null; 32886 this.#focusedElement = null; 32887 return this.#currentEditorType.endDrawing(isAborted); 32888 } 32889 findNewParent(editor, x, y) { 32890 const layer = this.#uiManager.findParent(x, y); 32891 if (layer === null || layer === this) { 32892 return false; 32893 } 32894 layer.changeParent(editor); 32895 return true; 32896 } 32897 commitOrRemove() { 32898 if (this.#drawingAC) { 32899 this.endDrawingSession(); 32900 return true; 32901 } 32902 return false; 32903 } 32904 onScaleChanging() { 32905 if (!this.#drawingAC) { 32906 return; 32907 } 32908 this.#currentEditorType.onScaleChangingWhenDrawing(this); 32909 } 32910 destroy() { 32911 this.commitOrRemove(); 32912 if (this.#uiManager.getActive()?.parent === this) { 32913 this.#uiManager.commitOrRemove(); 32914 this.#uiManager.setActiveEditor(null); 32915 } 32916 if (this.#editorFocusTimeoutId) { 32917 clearTimeout(this.#editorFocusTimeoutId); 32918 this.#editorFocusTimeoutId = null; 32919 } 32920 for (const editor of this.#editors.values()) { 32921 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); 32922 editor.setParent(null); 32923 editor.isAttachedToDOM = false; 32924 editor.div.remove(); 32925 } 32926 this.div = null; 32927 this.#editors.clear(); 32928 this.#uiManager.removeLayer(this); 32929 } 32930 #cleanup() { 32931 for (const editor of this.#editors.values()) { 32932 if (editor.isEmpty()) { 32933 editor.remove(); 32934 } 32935 } 32936 } 32937 render({ 32938 viewport 32939 }) { 32940 this.viewport = viewport; 32941 setLayerDimensions(this.div, viewport); 32942 for (const editor of this.#uiManager.getEditors(this.pageIndex)) { 32943 this.add(editor); 32944 editor.rebuild(); 32945 } 32946 this.updateMode(); 32947 } 32948 update({ 32949 viewport 32950 }) { 32951 this.#uiManager.commitOrRemove(); 32952 this.#cleanup(); 32953 const oldRotation = this.viewport.rotation; 32954 const rotation = viewport.rotation; 32955 this.viewport = viewport; 32956 setLayerDimensions(this.div, { 32957 rotation 32958 }); 32959 if (oldRotation !== rotation) { 32960 for (const editor of this.#editors.values()) { 32961 editor.rotate(rotation); 32962 } 32963 } 32964 } 32965 get pageDimensions() { 32966 const { 32967 pageWidth, 32968 pageHeight 32969 } = this.viewport.rawDims; 32970 return [pageWidth, pageHeight]; 32971 } 32972 get scale() { 32973 return this.#uiManager.viewParameters.realScale; 32974 } 32975} 32976 32977;// ./src/display/draw_layer.js 32978 32979 32980 32981 32982class DrawLayer { 32983 #parent = null; 32984 #mapping = new Map(); 32985 #toUpdate = new Map(); 32986 static #id = 0; 32987 setParent(parent) { 32988 if (!this.#parent) { 32989 this.#parent = parent; 32990 return; 32991 } 32992 if (this.#parent !== parent) { 32993 if (this.#mapping.size > 0) { 32994 for (const root of this.#mapping.values()) { 32995 root.remove(); 32996 parent.append(root); 32997 } 32998 } 32999 this.#parent = parent; 33000 } 33001 } 33002 static get _svgFactory() { 33003 return shadow(this, "_svgFactory", new DOMSVGFactory()); 33004 } 33005 static #setBox(element, [x, y, width, height]) { 33006 const { 33007 style 33008 } = element; 33009 style.top = `${100 * y}%`; 33010 style.left = `${100 * x}%`; 33011 style.width = `${100 * width}%`; 33012 style.height = `${100 * height}%`; 33013 } 33014 #createSVG() { 33015 const svg = DrawLayer._svgFactory.create(1, 1, true); 33016 this.#parent.append(svg); 33017 svg.setAttribute("aria-hidden", true); 33018 return svg; 33019 } 33020 #createClipPath(defs, pathId) { 33021 const clipPath = DrawLayer._svgFactory.createElement("clipPath"); 33022 defs.append(clipPath); 33023 const clipPathId = `clip_${pathId}`; 33024 clipPath.setAttribute("id", clipPathId); 33025 clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); 33026 const clipPathUse = DrawLayer._svgFactory.createElement("use"); 33027 clipPath.append(clipPathUse); 33028 clipPathUse.setAttribute("href", `#${pathId}`); 33029 clipPathUse.classList.add("clip"); 33030 return clipPathId; 33031 } 33032 #updateProperties(element, properties) { 33033 for (const [key, value] of Object.entries(properties)) { 33034 if (value === null) { 33035 element.removeAttribute(key); 33036 } else { 33037 element.setAttribute(key, value); 33038 } 33039 } 33040 } 33041 draw(properties, isPathUpdatable = false, hasClip = false) { 33042 const id = DrawLayer.#id++; 33043 const root = this.#createSVG(); 33044 const defs = DrawLayer._svgFactory.createElement("defs"); 33045 root.append(defs); 33046 const path = DrawLayer._svgFactory.createElement("path"); 33047 defs.append(path); 33048 const pathId = `path_${id}`; 33049 path.setAttribute("id", pathId); 33050 path.setAttribute("vector-effect", "non-scaling-stroke"); 33051 if (isPathUpdatable) { 33052 this.#toUpdate.set(id, path); 33053 } 33054 const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null; 33055 const use = DrawLayer._svgFactory.createElement("use"); 33056 root.append(use); 33057 use.setAttribute("href", `#${pathId}`); 33058 this.updateProperties(root, properties); 33059 this.#mapping.set(id, root); 33060 return { 33061 id, 33062 clipPathId: `url(#${clipPathId})` 33063 }; 33064 } 33065 drawOutline(properties, mustRemoveSelfIntersections) { 33066 const id = DrawLayer.#id++; 33067 const root = this.#createSVG(); 33068 const defs = DrawLayer._svgFactory.createElement("defs"); 33069 root.append(defs); 33070 const path = DrawLayer._svgFactory.createElement("path"); 33071 defs.append(path); 33072 const pathId = `path_${id}`; 33073 path.setAttribute("id", pathId); 33074 path.setAttribute("vector-effect", "non-scaling-stroke"); 33075 let maskId; 33076 if (mustRemoveSelfIntersections) { 33077 const mask = DrawLayer._svgFactory.createElement("mask"); 33078 defs.append(mask); 33079 maskId = `mask_${id}`; 33080 mask.setAttribute("id", maskId); 33081 mask.setAttribute("maskUnits", "objectBoundingBox"); 33082 const rect = DrawLayer._svgFactory.createElement("rect"); 33083 mask.append(rect); 33084 rect.setAttribute("width", "1"); 33085 rect.setAttribute("height", "1"); 33086 rect.setAttribute("fill", "white"); 33087 const use = DrawLayer._svgFactory.createElement("use"); 33088 mask.append(use); 33089 use.setAttribute("href", `#${pathId}`); 33090 use.setAttribute("stroke", "none"); 33091 use.setAttribute("fill", "black"); 33092 use.setAttribute("fill-rule", "nonzero"); 33093 use.classList.add("mask"); 33094 } 33095 const use1 = DrawLayer._svgFactory.createElement("use"); 33096 root.append(use1); 33097 use1.setAttribute("href", `#${pathId}`); 33098 if (maskId) { 33099 use1.setAttribute("mask", `url(#${maskId})`); 33100 } 33101 const use2 = use1.cloneNode(); 33102 root.append(use2); 33103 use1.classList.add("mainOutline"); 33104 use2.classList.add("secondaryOutline"); 33105 this.updateProperties(root, properties); 33106 this.#mapping.set(id, root); 33107 return id; 33108 } 33109 finalizeDraw(id, properties) { 33110 this.#toUpdate.delete(id); 33111 this.updateProperties(id, properties); 33112 } 33113 updateProperties(elementOrId, properties) { 33114 if (!properties) { 33115 return; 33116 } 33117 const { 33118 root, 33119 bbox, 33120 rootClass, 33121 path 33122 } = properties;
vendor: 4,251 bytes, lines 33123-33261
33123 const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId; 33124 if (!element) { 33125 return; 33126 } 33127 if (root) { 33128 this.#updateProperties(element, root); 33129 } 33130 if (bbox) { 33131 DrawLayer.#setBox(element, bbox); 33132 } 33133 if (rootClass) { 33134 const { 33135 classList 33136 } = element; 33137 for (const [className, value] of Object.entries(rootClass)) { 33138 classList.toggle(className, value); 33139 } 33140 } 33141 if (path) { 33142 const defs = element.firstElementChild; 33143 const pathElement = defs.firstElementChild; 33144 this.#updateProperties(pathElement, path); 33145 } 33146 } 33147 updateParent(id, layer) { 33148 if (layer === this) { 33149 return; 33150 } 33151 const root = this.#mapping.get(id); 33152 if (!root) { 33153 return; 33154 } 33155 layer.#parent.append(root); 33156 this.#mapping.delete(id); 33157 layer.#mapping.set(id, root); 33158 } 33159 remove(id) { 33160 this.#toUpdate.delete(id); 33161 if (this.#parent === null) { 33162 return; 33163 } 33164 this.#mapping.get(id).remove(); 33165 this.#mapping.delete(id); 33166 } 33167 destroy() { 33168 this.#parent = null; 33169 for (const root of this.#mapping.values()) { 33170 root.remove(); 33171 } 33172 this.#mapping.clear(); 33173 this.#toUpdate.clear(); 33174 } 33175} 33176 33177;// ./src/pdf.js 33178 33179 33180 33181 33182 33183 33184 33185 33186 33187 33188 33189 33190 33191 33192 33193 33194{ 33195 globalThis._pdfjsTestingUtils = { 33196 HighlightOutliner: HighlightOutliner 33197 }; 33198} 33199globalThis.pdfjsLib = { 33200 AbortException: AbortException, 33201 AnnotationEditorLayer: AnnotationEditorLayer, 33202 AnnotationEditorParamsType: AnnotationEditorParamsType, 33203 AnnotationEditorType: AnnotationEditorType, 33204 AnnotationEditorUIManager: AnnotationEditorUIManager, 33205 AnnotationLayer: AnnotationLayer, 33206 AnnotationMode: AnnotationMode, 33207 AnnotationType: AnnotationType, 33208 applyOpacity: applyOpacity, 33209 build: build, 33210 ColorPicker: ColorPicker, 33211 createValidAbsoluteUrl: createValidAbsoluteUrl, 33212 CSSConstants: CSSConstants, 33213 DOMSVGFactory: DOMSVGFactory, 33214 DrawLayer: DrawLayer, 33215 FeatureTest: FeatureTest, 33216 fetchData: fetchData, 33217 findContrastColor: findContrastColor, 33218 getDocument: getDocument, 33219 getFilenameFromUrl: getFilenameFromUrl, 33220 getPdfFilenameFromUrl: getPdfFilenameFromUrl, 33221 getRGB: getRGB, 33222 getUuid: getUuid, 33223 getXfaPageViewport: getXfaPageViewport, 33224 GlobalWorkerOptions: GlobalWorkerOptions, 33225 ImageKind: ImageKind, 33226 InvalidPDFException: InvalidPDFException, 33227 isDataScheme: isDataScheme, 33228 isPdfFile: isPdfFile, 33229 isValidExplicitDest: isValidExplicitDest, 33230 makeArr: makeArr, 33231 makeMap: makeMap, 33232 makeObj: makeObj, 33233 MathClamp: MathClamp, 33234 noContextMenu: noContextMenu, 33235 normalizeUnicode: normalizeUnicode, 33236 OPS: OPS, 33237 OutputScale: OutputScale, 33238 PasswordResponses: PasswordResponses, 33239 PDFDataRangeTransport: PDFDataRangeTransport, 33240 PDFDateString: PDFDateString, 33241 PDFWorker: PDFWorker, 33242 PermissionFlag: PermissionFlag, 33243 PixelsPerInch: PixelsPerInch, 33244 RenderingCancelledException: RenderingCancelledException, 33245 renderRichText: renderRichText, 33246 ResponseException: ResponseException, 33247 setLayerDimensions: setLayerDimensions, 33248 shadow: shadow, 33249 SignatureExtractor: SignatureExtractor, 33250 stopEvent: stopEvent, 33251 SupportedImageMimeTypes: SupportedImageMimeTypes, 33252 TextLayer: TextLayer, 33253 TouchManager: TouchManager, 33254 updateUrlHash: updateUrlHash, 33255 Util: Util, 33256 VerbosityLevel: VerbosityLevel, 33257 version: version, 33258 XfaLayer: XfaLayer 33259}; 33260 33261export { AbortException, AnnotationEditorLayer, AnnotationEditorParamsType, AnnotationEditorType, AnnotationEditorUIManager, AnnotationLayer, AnnotationMode, AnnotationType, CSSConstants, ColorPicker, DOMSVGFactory, DrawLayer, FeatureTest, GlobalWorkerOptions, ImageKind, InvalidPDFException, MathClamp, OPS, OutputScale, PDFDataRangeTransport, PDFDateString, PDFWorker, PasswordResponses, PermissionFlag, PixelsPerInch, RenderingCancelledException, ResponseException, SignatureExtractor, SupportedImageMimeTypes, TextLayer, TouchManager, Util, VerbosityLevel, XfaLayer, applyOpacity, build, createValidAbsoluteUrl, fetchData, findContrastColor, getDocument, getFilenameFromUrl, getPdfFilenameFromUrl, getRGB, getUuid, getXfaPageViewport, isDataScheme, isPdfFile, isValidExplicitDest, makeArr, makeMap, makeObj, noContextMenu, normalizeUnicode, renderRichText, setLayerDimensions, shadow, stopEvent, updateUrlHash, version
vendor: 36 bytes, lines 33261-33263
33261 }; 33262 33263//# sourceMappingURL=pdf.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.