PluginProbe ʕ •ᴥ•ʔ
EmbedPress – PDF Embedder, 3D PDF FlipBook, Google Reviews, YouTube Videos, Upload & Embed PDF documents / 4.4.10
EmbedPress – PDF Embedder, 3D PDF FlipBook, Google Reviews, YouTube Videos, Upload & Embed PDF documents v4.4.10
4.6.5 4.6.4 4.6.3 4.6.2 4.6.1 4.6.0 4.5.6 4.5.5 4.5.4 4.5.3 4.5.2 trunk 1.0.0 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.5.0 1.6.0 1.6.1 1.6.2 1.6.3 1.7.0 1.7.1 1.7.2 1.7.3 1.7.4 1.7.5 2.0.0 2.0.1 2.0.2 2.0.3 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.2.0 2.2.1 2.2.2 2.3.0 2.3.1 2.3.2 2.3.3 2.4.0 2.4.1 2.5.0 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.6.0 2.6.1 2.6.2 2.7.0 2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.1.0 3.1.1 3.1.2 3.1.3 3.2.0 3.2.1 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4 3.3.5 3.3.6 3.3.7 3.4.0 3.4.1 3.4.2 3.4.3 3.5.0 3.5.1 3.5.2 3.5.3 3.6.0 3.6.1 3.6.2 3.6.3 3.6.4 3.6.5 3.6.6 3.6.7 3.6.8 3.7.0 3.7.1 3.7.2 3.7.3 3.8.0 3.8.1 3.8.2 3.8.3 3.8.4 3.8.5 3.9.0 3.9.1 3.9.10 3.9.11 3.9.12 3.9.13 3.9.14 3.9.15 3.9.16 3.9.17 3.9.2 3.9.3 3.9.4 3.9.5 3.9.6 3.9.7 3.9.8 3.9.9 4.0.0 4.0.1 4.0.10 4.0.11 4.0.12 4.0.13 4.0.14 4.0.2 4.0.3 4.0.4 4.0.5 4.0.6 4.0.7 4.0.8 4.0.9 4.1.0 4.1.1 4.1.10 4.1.2 4.1.3 4.1.4 4.1.5 4.1.6 4.1.7 4.1.8 4.1.9 4.2.0 4.2.1 4.2.2 4.2.3 4.2.4 4.2.5 4.2.6 4.2.7 4.2.8 4.2.9 4.3.0 4.3.1 4.4.0 4.4.1 4.4.10 4.4.11 4.4.2 4.4.3 4.4.4 4.4.5 4.4.6 4.4.7 4.4.8 4.4.9 4.5.0 4.5.1
embedpress / assets / pdf / build / script.js
embedpress / assets / pdf / build Last commit date
pdf.worker.js 2 years ago script.js 2 years ago
script.js
24321 lines
1 /**
2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
4 *
5 * Copyright 2023 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 /******/ var __webpack_modules__ = ({
24
25 /***/ 9306:
26 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
27
28
29 var isCallable = __webpack_require__(4901);
30 var tryToString = __webpack_require__(6823);
31
32 var $TypeError = TypeError;
33
34 // `Assert: IsCallable(argument) is true`
35 module.exports = function (argument) {
36 if (isCallable(argument)) return argument;
37 throw new $TypeError(tryToString(argument) + ' is not a function');
38 };
39
40
41 /***/ }),
42
43 /***/ 3506:
44 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
45
46
47 var isPossiblePrototype = __webpack_require__(3925);
48
49 var $String = String;
50 var $TypeError = TypeError;
51
52 module.exports = function (argument) {
53 if (isPossiblePrototype(argument)) return argument;
54 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
55 };
56
57
58 /***/ }),
59
60 /***/ 7080:
61 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
62
63
64 var has = (__webpack_require__(4402).has);
65
66 // Perform ? RequireInternalSlot(M, [[SetData]])
67 module.exports = function (it) {
68 has(it);
69 return it;
70 };
71
72
73 /***/ }),
74
75 /***/ 679:
76 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
77
78
79 var isPrototypeOf = __webpack_require__(1625);
80
81 var $TypeError = TypeError;
82
83 module.exports = function (it, Prototype) {
84 if (isPrototypeOf(Prototype, it)) return it;
85 throw new $TypeError('Incorrect invocation');
86 };
87
88
89 /***/ }),
90
91 /***/ 8551:
92 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
93
94
95 var isObject = __webpack_require__(34);
96
97 var $String = String;
98 var $TypeError = TypeError;
99
100 // `Assert: Type(argument) is Object`
101 module.exports = function (argument) {
102 if (isObject(argument)) return argument;
103 throw new $TypeError($String(argument) + ' is not an object');
104 };
105
106
107 /***/ }),
108
109 /***/ 7811:
110 /***/ ((module) => {
111
112
113 // eslint-disable-next-line es/no-typed-arrays -- safe
114 module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';
115
116
117 /***/ }),
118
119 /***/ 7394:
120 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
121
122
123 var uncurryThisAccessor = __webpack_require__(6706);
124 var classof = __webpack_require__(4576);
125
126 var $TypeError = TypeError;
127
128 // Includes
129 // - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
130 // - If IsSharedArrayBuffer(O) is true, throw a TypeError exception.
131 module.exports = uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) {
132 if (classof(O) !== 'ArrayBuffer') throw new $TypeError('ArrayBuffer expected');
133 return O.byteLength;
134 };
135
136
137 /***/ }),
138
139 /***/ 3238:
140 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
141
142
143 var uncurryThis = __webpack_require__(9504);
144 var arrayBufferByteLength = __webpack_require__(7394);
145
146 var slice = uncurryThis(ArrayBuffer.prototype.slice);
147
148 module.exports = function (O) {
149 if (arrayBufferByteLength(O) !== 0) return false;
150 try {
151 slice(O, 0, 0);
152 return false;
153 } catch (error) {
154 return true;
155 }
156 };
157
158
159 /***/ }),
160
161 /***/ 5636:
162 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
163
164
165 var global = __webpack_require__(4475);
166 var uncurryThis = __webpack_require__(9504);
167 var uncurryThisAccessor = __webpack_require__(6706);
168 var toIndex = __webpack_require__(7696);
169 var isDetached = __webpack_require__(3238);
170 var arrayBufferByteLength = __webpack_require__(7394);
171 var detachTransferable = __webpack_require__(4483);
172 var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
173
174 var structuredClone = global.structuredClone;
175 var ArrayBuffer = global.ArrayBuffer;
176 var DataView = global.DataView;
177 var TypeError = global.TypeError;
178 var min = Math.min;
179 var ArrayBufferPrototype = ArrayBuffer.prototype;
180 var DataViewPrototype = DataView.prototype;
181 var slice = uncurryThis(ArrayBufferPrototype.slice);
182 var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get');
183 var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get');
184 var getInt8 = uncurryThis(DataViewPrototype.getInt8);
185 var setInt8 = uncurryThis(DataViewPrototype.setInt8);
186
187 module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) {
188 var byteLength = arrayBufferByteLength(arrayBuffer);
189 var newByteLength = newLength === undefined ? byteLength : toIndex(newLength);
190 var fixedLength = !isResizable || !isResizable(arrayBuffer);
191 var newBuffer;
192 if (isDetached(arrayBuffer)) throw new TypeError('ArrayBuffer is detached');
193 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
194 arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
195 if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer;
196 }
197 if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) {
198 newBuffer = slice(arrayBuffer, 0, newByteLength);
199 } else {
200 var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined;
201 newBuffer = new ArrayBuffer(newByteLength, options);
202 var a = new DataView(arrayBuffer);
203 var b = new DataView(newBuffer);
204 var copyLength = min(newByteLength, byteLength);
205 for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i));
206 }
207 if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer);
208 return newBuffer;
209 };
210
211
212 /***/ }),
213
214 /***/ 4644:
215 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
216
217
218 var NATIVE_ARRAY_BUFFER = __webpack_require__(7811);
219 var DESCRIPTORS = __webpack_require__(3724);
220 var global = __webpack_require__(4475);
221 var isCallable = __webpack_require__(4901);
222 var isObject = __webpack_require__(34);
223 var hasOwn = __webpack_require__(9297);
224 var classof = __webpack_require__(6955);
225 var tryToString = __webpack_require__(6823);
226 var createNonEnumerableProperty = __webpack_require__(6699);
227 var defineBuiltIn = __webpack_require__(6840);
228 var defineBuiltInAccessor = __webpack_require__(2106);
229 var isPrototypeOf = __webpack_require__(1625);
230 var getPrototypeOf = __webpack_require__(2787);
231 var setPrototypeOf = __webpack_require__(2967);
232 var wellKnownSymbol = __webpack_require__(8227);
233 var uid = __webpack_require__(3392);
234 var InternalStateModule = __webpack_require__(1181);
235
236 var enforceInternalState = InternalStateModule.enforce;
237 var getInternalState = InternalStateModule.get;
238 var Int8Array = global.Int8Array;
239 var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
240 var Uint8ClampedArray = global.Uint8ClampedArray;
241 var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
242 var TypedArray = Int8Array && getPrototypeOf(Int8Array);
243 var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
244 var ObjectPrototype = Object.prototype;
245 var TypeError = global.TypeError;
246
247 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
248 var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
249 var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
250 // Fixing native typed arrays in Opera Presto crashes the browser, see #595
251 var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
252 var TYPED_ARRAY_TAG_REQUIRED = false;
253 var NAME, Constructor, Prototype;
254
255 var TypedArrayConstructorsList = {
256 Int8Array: 1,
257 Uint8Array: 1,
258 Uint8ClampedArray: 1,
259 Int16Array: 2,
260 Uint16Array: 2,
261 Int32Array: 4,
262 Uint32Array: 4,
263 Float32Array: 4,
264 Float64Array: 8
265 };
266
267 var BigIntArrayConstructorsList = {
268 BigInt64Array: 8,
269 BigUint64Array: 8
270 };
271
272 var isView = function isView(it) {
273 if (!isObject(it)) return false;
274 var klass = classof(it);
275 return klass === 'DataView'
276 || hasOwn(TypedArrayConstructorsList, klass)
277 || hasOwn(BigIntArrayConstructorsList, klass);
278 };
279
280 var getTypedArrayConstructor = function (it) {
281 var proto = getPrototypeOf(it);
282 if (!isObject(proto)) return;
283 var state = getInternalState(proto);
284 return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);
285 };
286
287 var isTypedArray = function (it) {
288 if (!isObject(it)) return false;
289 var klass = classof(it);
290 return hasOwn(TypedArrayConstructorsList, klass)
291 || hasOwn(BigIntArrayConstructorsList, klass);
292 };
293
294 var aTypedArray = function (it) {
295 if (isTypedArray(it)) return it;
296 throw new TypeError('Target is not a typed array');
297 };
298
299 var aTypedArrayConstructor = function (C) {
300 if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
301 throw new TypeError(tryToString(C) + ' is not a typed array constructor');
302 };
303
304 var exportTypedArrayMethod = function (KEY, property, forced, options) {
305 if (!DESCRIPTORS) return;
306 if (forced) for (var ARRAY in TypedArrayConstructorsList) {
307 var TypedArrayConstructor = global[ARRAY];
308 if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
309 delete TypedArrayConstructor.prototype[KEY];
310 } catch (error) {
311 // old WebKit bug - some methods are non-configurable
312 try {
313 TypedArrayConstructor.prototype[KEY] = property;
314 } catch (error2) { /* empty */ }
315 }
316 }
317 if (!TypedArrayPrototype[KEY] || forced) {
318 defineBuiltIn(TypedArrayPrototype, KEY, forced ? property
319 : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);
320 }
321 };
322
323 var exportTypedArrayStaticMethod = function (KEY, property, forced) {
324 var ARRAY, TypedArrayConstructor;
325 if (!DESCRIPTORS) return;
326 if (setPrototypeOf) {
327 if (forced) for (ARRAY in TypedArrayConstructorsList) {
328 TypedArrayConstructor = global[ARRAY];
329 if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
330 delete TypedArrayConstructor[KEY];
331 } catch (error) { /* empty */ }
332 }
333 if (!TypedArray[KEY] || forced) {
334 // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
335 try {
336 return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
337 } catch (error) { /* empty */ }
338 } else return;
339 }
340 for (ARRAY in TypedArrayConstructorsList) {
341 TypedArrayConstructor = global[ARRAY];
342 if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
343 defineBuiltIn(TypedArrayConstructor, KEY, property);
344 }
345 }
346 };
347
348 for (NAME in TypedArrayConstructorsList) {
349 Constructor = global[NAME];
350 Prototype = Constructor && Constructor.prototype;
351 if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
352 else NATIVE_ARRAY_BUFFER_VIEWS = false;
353 }
354
355 for (NAME in BigIntArrayConstructorsList) {
356 Constructor = global[NAME];
357 Prototype = Constructor && Constructor.prototype;
358 if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
359 }
360
361 // WebKit bug - typed arrays constructors prototype is Object.prototype
362 if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
363 // eslint-disable-next-line no-shadow -- safe
364 TypedArray = function TypedArray() {
365 throw new TypeError('Incorrect invocation');
366 };
367 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
368 if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
369 }
370 }
371
372 if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
373 TypedArrayPrototype = TypedArray.prototype;
374 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
375 if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
376 }
377 }
378
379 // WebKit bug - one more object in Uint8ClampedArray prototype chain
380 if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
381 setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
382 }
383
384 if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
385 TYPED_ARRAY_TAG_REQUIRED = true;
386 defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, {
387 configurable: true,
388 get: function () {
389 return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
390 }
391 });
392 for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
393 createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
394 }
395 }
396
397 module.exports = {
398 NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
399 TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,
400 aTypedArray: aTypedArray,
401 aTypedArrayConstructor: aTypedArrayConstructor,
402 exportTypedArrayMethod: exportTypedArrayMethod,
403 exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
404 getTypedArrayConstructor: getTypedArrayConstructor,
405 isView: isView,
406 isTypedArray: isTypedArray,
407 TypedArray: TypedArray,
408 TypedArrayPrototype: TypedArrayPrototype
409 };
410
411
412 /***/ }),
413
414 /***/ 5370:
415 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
416
417
418 var lengthOfArrayLike = __webpack_require__(6198);
419
420 module.exports = function (Constructor, list, $length) {
421 var index = 0;
422 var length = arguments.length > 2 ? $length : lengthOfArrayLike(list);
423 var result = new Constructor(length);
424 while (length > index) result[index] = list[index++];
425 return result;
426 };
427
428
429 /***/ }),
430
431 /***/ 9617:
432 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
433
434
435 var toIndexedObject = __webpack_require__(5397);
436 var toAbsoluteIndex = __webpack_require__(5610);
437 var lengthOfArrayLike = __webpack_require__(6198);
438
439 // `Array.prototype.{ indexOf, includes }` methods implementation
440 var createMethod = function (IS_INCLUDES) {
441 return function ($this, el, fromIndex) {
442 var O = toIndexedObject($this);
443 var length = lengthOfArrayLike(O);
444 if (length === 0) return !IS_INCLUDES && -1;
445 var index = toAbsoluteIndex(fromIndex, length);
446 var value;
447 // Array#includes uses SameValueZero equality algorithm
448 // eslint-disable-next-line no-self-compare -- NaN check
449 if (IS_INCLUDES && el !== el) while (length > index) {
450 value = O[index++];
451 // eslint-disable-next-line no-self-compare -- NaN check
452 if (value !== value) return true;
453 // Array#indexOf ignores holes, Array#includes - not
454 } else for (;length > index; index++) {
455 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
456 } return !IS_INCLUDES && -1;
457 };
458 };
459
460 module.exports = {
461 // `Array.prototype.includes` method
462 // https://tc39.es/ecma262/#sec-array.prototype.includes
463 includes: createMethod(true),
464 // `Array.prototype.indexOf` method
465 // https://tc39.es/ecma262/#sec-array.prototype.indexof
466 indexOf: createMethod(false)
467 };
468
469
470 /***/ }),
471
472 /***/ 4527:
473 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
474
475
476 var DESCRIPTORS = __webpack_require__(3724);
477 var isArray = __webpack_require__(4376);
478
479 var $TypeError = TypeError;
480 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
481 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
482
483 // Safari < 13 does not throw an error in this case
484 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
485 // makes no sense without proper strict mode support
486 if (this !== undefined) return true;
487 try {
488 // eslint-disable-next-line es/no-object-defineproperty -- safe
489 Object.defineProperty([], 'length', { writable: false }).length = 1;
490 } catch (error) {
491 return error instanceof TypeError;
492 }
493 }();
494
495 module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
496 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
497 throw new $TypeError('Cannot set read only .length');
498 } return O.length = length;
499 } : function (O, length) {
500 return O.length = length;
501 };
502
503
504 /***/ }),
505
506 /***/ 7628:
507 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
508
509
510 var lengthOfArrayLike = __webpack_require__(6198);
511
512 // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed
513 // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed
514 module.exports = function (O, C) {
515 var len = lengthOfArrayLike(O);
516 var A = new C(len);
517 var k = 0;
518 for (; k < len; k++) A[k] = O[len - k - 1];
519 return A;
520 };
521
522
523 /***/ }),
524
525 /***/ 9928:
526 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
527
528
529 var lengthOfArrayLike = __webpack_require__(6198);
530 var toIntegerOrInfinity = __webpack_require__(1291);
531
532 var $RangeError = RangeError;
533
534 // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with
535 // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with
536 module.exports = function (O, C, index, value) {
537 var len = lengthOfArrayLike(O);
538 var relativeIndex = toIntegerOrInfinity(index);
539 var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex;
540 if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index');
541 var A = new C(len);
542 var k = 0;
543 for (; k < len; k++) A[k] = k === actualIndex ? value : O[k];
544 return A;
545 };
546
547
548 /***/ }),
549
550 /***/ 6319:
551 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
552
553
554 var anObject = __webpack_require__(8551);
555 var iteratorClose = __webpack_require__(9539);
556
557 // call something on iterator step with safe closing on error
558 module.exports = function (iterator, fn, value, ENTRIES) {
559 try {
560 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
561 } catch (error) {
562 iteratorClose(iterator, 'throw', error);
563 }
564 };
565
566
567 /***/ }),
568
569 /***/ 4576:
570 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
571
572
573 var uncurryThis = __webpack_require__(9504);
574
575 var toString = uncurryThis({}.toString);
576 var stringSlice = uncurryThis(''.slice);
577
578 module.exports = function (it) {
579 return stringSlice(toString(it), 8, -1);
580 };
581
582
583 /***/ }),
584
585 /***/ 6955:
586 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
587
588
589 var TO_STRING_TAG_SUPPORT = __webpack_require__(2140);
590 var isCallable = __webpack_require__(4901);
591 var classofRaw = __webpack_require__(4576);
592 var wellKnownSymbol = __webpack_require__(8227);
593
594 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
595 var $Object = Object;
596
597 // ES3 wrong here
598 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
599
600 // fallback for IE11 Script Access Denied error
601 var tryGet = function (it, key) {
602 try {
603 return it[key];
604 } catch (error) { /* empty */ }
605 };
606
607 // getting tag from ES6+ `Object.prototype.toString`
608 module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
609 var O, tag, result;
610 return it === undefined ? 'Undefined' : it === null ? 'Null'
611 // @@toStringTag case
612 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
613 // builtinTag case
614 : CORRECT_ARGUMENTS ? classofRaw(O)
615 // ES3 arguments fallback
616 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
617 };
618
619
620 /***/ }),
621
622 /***/ 7740:
623 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
624
625
626 var hasOwn = __webpack_require__(9297);
627 var ownKeys = __webpack_require__(5031);
628 var getOwnPropertyDescriptorModule = __webpack_require__(7347);
629 var definePropertyModule = __webpack_require__(4913);
630
631 module.exports = function (target, source, exceptions) {
632 var keys = ownKeys(source);
633 var defineProperty = definePropertyModule.f;
634 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
635 for (var i = 0; i < keys.length; i++) {
636 var key = keys[i];
637 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
638 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
639 }
640 }
641 };
642
643
644 /***/ }),
645
646 /***/ 2211:
647 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
648
649
650 var fails = __webpack_require__(9039);
651
652 module.exports = !fails(function () {
653 function F() { /* empty */ }
654 F.prototype.constructor = null;
655 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
656 return Object.getPrototypeOf(new F()) !== F.prototype;
657 });
658
659
660 /***/ }),
661
662 /***/ 2529:
663 /***/ ((module) => {
664
665
666 // `CreateIterResultObject` abstract operation
667 // https://tc39.es/ecma262/#sec-createiterresultobject
668 module.exports = function (value, done) {
669 return { value: value, done: done };
670 };
671
672
673 /***/ }),
674
675 /***/ 6699:
676 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
677
678
679 var DESCRIPTORS = __webpack_require__(3724);
680 var definePropertyModule = __webpack_require__(4913);
681 var createPropertyDescriptor = __webpack_require__(6980);
682
683 module.exports = DESCRIPTORS ? function (object, key, value) {
684 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
685 } : function (object, key, value) {
686 object[key] = value;
687 return object;
688 };
689
690
691 /***/ }),
692
693 /***/ 6980:
694 /***/ ((module) => {
695
696
697 module.exports = function (bitmap, value) {
698 return {
699 enumerable: !(bitmap & 1),
700 configurable: !(bitmap & 2),
701 writable: !(bitmap & 4),
702 value: value
703 };
704 };
705
706
707 /***/ }),
708
709 /***/ 4659:
710 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
711
712
713 var DESCRIPTORS = __webpack_require__(3724);
714 var definePropertyModule = __webpack_require__(4913);
715 var createPropertyDescriptor = __webpack_require__(6980);
716
717 module.exports = function (object, key, value) {
718 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
719 else object[key] = value;
720 };
721
722
723 /***/ }),
724
725 /***/ 2106:
726 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
727
728
729 var makeBuiltIn = __webpack_require__(283);
730 var defineProperty = __webpack_require__(4913);
731
732 module.exports = function (target, name, descriptor) {
733 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
734 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
735 return defineProperty.f(target, name, descriptor);
736 };
737
738
739 /***/ }),
740
741 /***/ 6840:
742 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
743
744
745 var isCallable = __webpack_require__(4901);
746 var definePropertyModule = __webpack_require__(4913);
747 var makeBuiltIn = __webpack_require__(283);
748 var defineGlobalProperty = __webpack_require__(9433);
749
750 module.exports = function (O, key, value, options) {
751 if (!options) options = {};
752 var simple = options.enumerable;
753 var name = options.name !== undefined ? options.name : key;
754 if (isCallable(value)) makeBuiltIn(value, name, options);
755 if (options.global) {
756 if (simple) O[key] = value;
757 else defineGlobalProperty(key, value);
758 } else {
759 try {
760 if (!options.unsafe) delete O[key];
761 else if (O[key]) simple = true;
762 } catch (error) { /* empty */ }
763 if (simple) O[key] = value;
764 else definePropertyModule.f(O, key, {
765 value: value,
766 enumerable: false,
767 configurable: !options.nonConfigurable,
768 writable: !options.nonWritable
769 });
770 } return O;
771 };
772
773
774 /***/ }),
775
776 /***/ 6279:
777 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
778
779
780 var defineBuiltIn = __webpack_require__(6840);
781
782 module.exports = function (target, src, options) {
783 for (var key in src) defineBuiltIn(target, key, src[key], options);
784 return target;
785 };
786
787
788 /***/ }),
789
790 /***/ 9433:
791 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
792
793
794 var global = __webpack_require__(4475);
795
796 // eslint-disable-next-line es/no-object-defineproperty -- safe
797 var defineProperty = Object.defineProperty;
798
799 module.exports = function (key, value) {
800 try {
801 defineProperty(global, key, { value: value, configurable: true, writable: true });
802 } catch (error) {
803 global[key] = value;
804 } return value;
805 };
806
807
808 /***/ }),
809
810 /***/ 3724:
811 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
812
813
814 var fails = __webpack_require__(9039);
815
816 // Detect IE8's incomplete defineProperty implementation
817 module.exports = !fails(function () {
818 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
819 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
820 });
821
822
823 /***/ }),
824
825 /***/ 4483:
826 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
827
828
829 var global = __webpack_require__(4475);
830 var tryNodeRequire = __webpack_require__(9714);
831 var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
832
833 var structuredClone = global.structuredClone;
834 var $ArrayBuffer = global.ArrayBuffer;
835 var $MessageChannel = global.MessageChannel;
836 var detach = false;
837 var WorkerThreads, channel, buffer, $detach;
838
839 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
840 detach = function (transferable) {
841 structuredClone(transferable, { transfer: [transferable] });
842 };
843 } else if ($ArrayBuffer) try {
844 if (!$MessageChannel) {
845 WorkerThreads = tryNodeRequire('worker_threads');
846 if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
847 }
848
849 if ($MessageChannel) {
850 channel = new $MessageChannel();
851 buffer = new $ArrayBuffer(2);
852
853 $detach = function (transferable) {
854 channel.port1.postMessage(null, [transferable]);
855 };
856
857 if (buffer.byteLength === 2) {
858 $detach(buffer);
859 if (buffer.byteLength === 0) detach = $detach;
860 }
861 }
862 } catch (error) { /* empty */ }
863
864 module.exports = detach;
865
866
867 /***/ }),
868
869 /***/ 4055:
870 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
871
872
873 var global = __webpack_require__(4475);
874 var isObject = __webpack_require__(34);
875
876 var document = global.document;
877 // typeof document.createElement is 'object' in old IE
878 var EXISTS = isObject(document) && isObject(document.createElement);
879
880 module.exports = function (it) {
881 return EXISTS ? document.createElement(it) : {};
882 };
883
884
885 /***/ }),
886
887 /***/ 6837:
888 /***/ ((module) => {
889
890
891 var $TypeError = TypeError;
892 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
893
894 module.exports = function (it) {
895 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
896 return it;
897 };
898
899
900 /***/ }),
901
902 /***/ 5002:
903 /***/ ((module) => {
904
905
906 module.exports = {
907 IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
908 DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
909 HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
910 WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
911 InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
912 NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
913 NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
914 NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
915 NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
916 InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
917 InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
918 SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
919 InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
920 NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
921 InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
922 ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
923 TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
924 SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
925 NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
926 AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
927 URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
928 QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
929 TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
930 InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
931 DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
932 };
933
934
935 /***/ }),
936
937 /***/ 7290:
938 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
939
940
941 var IS_DENO = __webpack_require__(516);
942 var IS_NODE = __webpack_require__(9088);
943
944 module.exports = !IS_DENO && !IS_NODE
945 && typeof window == 'object'
946 && typeof document == 'object';
947
948
949 /***/ }),
950
951 /***/ 516:
952 /***/ ((module) => {
953
954
955 /* global Deno -- Deno case */
956 module.exports = typeof Deno == 'object' && Deno && typeof Deno.version == 'object';
957
958
959 /***/ }),
960
961 /***/ 9088:
962 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
963
964
965 var global = __webpack_require__(4475);
966 var classof = __webpack_require__(4576);
967
968 module.exports = classof(global.process) === 'process';
969
970
971 /***/ }),
972
973 /***/ 9392:
974 /***/ ((module) => {
975
976
977 module.exports = typeof navigator != 'undefined' && String(navigator.userAgent) || '';
978
979
980 /***/ }),
981
982 /***/ 7388:
983 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
984
985
986 var global = __webpack_require__(4475);
987 var userAgent = __webpack_require__(9392);
988
989 var process = global.process;
990 var Deno = global.Deno;
991 var versions = process && process.versions || Deno && Deno.version;
992 var v8 = versions && versions.v8;
993 var match, version;
994
995 if (v8) {
996 match = v8.split('.');
997 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
998 // but their correct versions are not interesting for us
999 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
1000 }
1001
1002 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
1003 // so check `userAgent` even if `.v8` exists, but 0
1004 if (!version && userAgent) {
1005 match = userAgent.match(/Edge\/(\d+)/);
1006 if (!match || match[1] >= 74) {
1007 match = userAgent.match(/Chrome\/(\d+)/);
1008 if (match) version = +match[1];
1009 }
1010 }
1011
1012 module.exports = version;
1013
1014
1015 /***/ }),
1016
1017 /***/ 8727:
1018 /***/ ((module) => {
1019
1020
1021 // IE8- don't enum bug keys
1022 module.exports = [
1023 'constructor',
1024 'hasOwnProperty',
1025 'isPrototypeOf',
1026 'propertyIsEnumerable',
1027 'toLocaleString',
1028 'toString',
1029 'valueOf'
1030 ];
1031
1032
1033 /***/ }),
1034
1035 /***/ 6193:
1036 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1037
1038
1039 var uncurryThis = __webpack_require__(9504);
1040
1041 var $Error = Error;
1042 var replace = uncurryThis(''.replace);
1043
1044 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
1045 // eslint-disable-next-line redos/no-vulnerable -- safe
1046 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
1047 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
1048
1049 module.exports = function (stack, dropEntries) {
1050 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
1051 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
1052 } return stack;
1053 };
1054
1055
1056 /***/ }),
1057
1058 /***/ 6518:
1059 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1060
1061
1062 var global = __webpack_require__(4475);
1063 var getOwnPropertyDescriptor = (__webpack_require__(7347).f);
1064 var createNonEnumerableProperty = __webpack_require__(6699);
1065 var defineBuiltIn = __webpack_require__(6840);
1066 var defineGlobalProperty = __webpack_require__(9433);
1067 var copyConstructorProperties = __webpack_require__(7740);
1068 var isForced = __webpack_require__(2796);
1069
1070 /*
1071 options.target - name of the target object
1072 options.global - target is the global object
1073 options.stat - export as static methods of target
1074 options.proto - export as prototype methods of target
1075 options.real - real prototype method for the `pure` version
1076 options.forced - export even if the native feature is available
1077 options.bind - bind methods to the target, required for the `pure` version
1078 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1079 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1080 options.sham - add a flag to not completely full polyfills
1081 options.enumerable - export as enumerable property
1082 options.dontCallGetSet - prevent calling a getter on target
1083 options.name - the .name of the function if it does not match the key
1084 */
1085 module.exports = function (options, source) {
1086 var TARGET = options.target;
1087 var GLOBAL = options.global;
1088 var STATIC = options.stat;
1089 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1090 if (GLOBAL) {
1091 target = global;
1092 } else if (STATIC) {
1093 target = global[TARGET] || defineGlobalProperty(TARGET, {});
1094 } else {
1095 target = global[TARGET] && global[TARGET].prototype;
1096 }
1097 if (target) for (key in source) {
1098 sourceProperty = source[key];
1099 if (options.dontCallGetSet) {
1100 descriptor = getOwnPropertyDescriptor(target, key);
1101 targetProperty = descriptor && descriptor.value;
1102 } else targetProperty = target[key];
1103 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1104 // contained in target
1105 if (!FORCED && targetProperty !== undefined) {
1106 if (typeof sourceProperty == typeof targetProperty) continue;
1107 copyConstructorProperties(sourceProperty, targetProperty);
1108 }
1109 // add a flag to not completely full polyfills
1110 if (options.sham || (targetProperty && targetProperty.sham)) {
1111 createNonEnumerableProperty(sourceProperty, 'sham', true);
1112 }
1113 defineBuiltIn(target, key, sourceProperty, options);
1114 }
1115 };
1116
1117
1118 /***/ }),
1119
1120 /***/ 9039:
1121 /***/ ((module) => {
1122
1123
1124 module.exports = function (exec) {
1125 try {
1126 return !!exec();
1127 } catch (error) {
1128 return true;
1129 }
1130 };
1131
1132
1133 /***/ }),
1134
1135 /***/ 6080:
1136 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1137
1138
1139 var uncurryThis = __webpack_require__(7476);
1140 var aCallable = __webpack_require__(9306);
1141 var NATIVE_BIND = __webpack_require__(616);
1142
1143 var bind = uncurryThis(uncurryThis.bind);
1144
1145 // optional / simple context binding
1146 module.exports = function (fn, that) {
1147 aCallable(fn);
1148 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
1149 return fn.apply(that, arguments);
1150 };
1151 };
1152
1153
1154 /***/ }),
1155
1156 /***/ 616:
1157 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1158
1159
1160 var fails = __webpack_require__(9039);
1161
1162 module.exports = !fails(function () {
1163 // eslint-disable-next-line es/no-function-prototype-bind -- safe
1164 var test = (function () { /* empty */ }).bind();
1165 // eslint-disable-next-line no-prototype-builtins -- safe
1166 return typeof test != 'function' || test.hasOwnProperty('prototype');
1167 });
1168
1169
1170 /***/ }),
1171
1172 /***/ 9565:
1173 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1174
1175
1176 var NATIVE_BIND = __webpack_require__(616);
1177
1178 var call = Function.prototype.call;
1179
1180 module.exports = NATIVE_BIND ? call.bind(call) : function () {
1181 return call.apply(call, arguments);
1182 };
1183
1184
1185 /***/ }),
1186
1187 /***/ 350:
1188 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1189
1190
1191 var DESCRIPTORS = __webpack_require__(3724);
1192 var hasOwn = __webpack_require__(9297);
1193
1194 var FunctionPrototype = Function.prototype;
1195 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
1196 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
1197
1198 var EXISTS = hasOwn(FunctionPrototype, 'name');
1199 // additional protection from minified / mangled / dropped function names
1200 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
1201 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
1202
1203 module.exports = {
1204 EXISTS: EXISTS,
1205 PROPER: PROPER,
1206 CONFIGURABLE: CONFIGURABLE
1207 };
1208
1209
1210 /***/ }),
1211
1212 /***/ 6706:
1213 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1214
1215
1216 var uncurryThis = __webpack_require__(9504);
1217 var aCallable = __webpack_require__(9306);
1218
1219 module.exports = function (object, key, method) {
1220 try {
1221 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
1222 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
1223 } catch (error) { /* empty */ }
1224 };
1225
1226
1227 /***/ }),
1228
1229 /***/ 7476:
1230 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1231
1232
1233 var classofRaw = __webpack_require__(4576);
1234 var uncurryThis = __webpack_require__(9504);
1235
1236 module.exports = function (fn) {
1237 // Nashorn bug:
1238 // https://github.com/zloirock/core-js/issues/1128
1239 // https://github.com/zloirock/core-js/issues/1130
1240 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
1241 };
1242
1243
1244 /***/ }),
1245
1246 /***/ 9504:
1247 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1248
1249
1250 var NATIVE_BIND = __webpack_require__(616);
1251
1252 var FunctionPrototype = Function.prototype;
1253 var call = FunctionPrototype.call;
1254 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
1255
1256 module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
1257 return function () {
1258 return call.apply(fn, arguments);
1259 };
1260 };
1261
1262
1263 /***/ }),
1264
1265 /***/ 7751:
1266 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1267
1268
1269 var global = __webpack_require__(4475);
1270 var isCallable = __webpack_require__(4901);
1271
1272 var aFunction = function (argument) {
1273 return isCallable(argument) ? argument : undefined;
1274 };
1275
1276 module.exports = function (namespace, method) {
1277 return arguments.length < 2 ? aFunction(global[namespace]) : global[namespace] && global[namespace][method];
1278 };
1279
1280
1281 /***/ }),
1282
1283 /***/ 1767:
1284 /***/ ((module) => {
1285
1286
1287 // `GetIteratorDirect(obj)` abstract operation
1288 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
1289 module.exports = function (obj) {
1290 return {
1291 iterator: obj,
1292 next: obj.next,
1293 done: false
1294 };
1295 };
1296
1297
1298 /***/ }),
1299
1300 /***/ 8646:
1301 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1302
1303
1304 var call = __webpack_require__(9565);
1305 var anObject = __webpack_require__(8551);
1306 var getIteratorDirect = __webpack_require__(1767);
1307 var getIteratorMethod = __webpack_require__(851);
1308
1309 module.exports = function (obj, stringHandling) {
1310 if (!stringHandling || typeof obj !== 'string') anObject(obj);
1311 var method = getIteratorMethod(obj);
1312 return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj));
1313 };
1314
1315
1316 /***/ }),
1317
1318 /***/ 851:
1319 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1320
1321
1322 var classof = __webpack_require__(6955);
1323 var getMethod = __webpack_require__(5966);
1324 var isNullOrUndefined = __webpack_require__(4117);
1325 var Iterators = __webpack_require__(6269);
1326 var wellKnownSymbol = __webpack_require__(8227);
1327
1328 var ITERATOR = wellKnownSymbol('iterator');
1329
1330 module.exports = function (it) {
1331 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
1332 || getMethod(it, '@@iterator')
1333 || Iterators[classof(it)];
1334 };
1335
1336
1337 /***/ }),
1338
1339 /***/ 81:
1340 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1341
1342
1343 var call = __webpack_require__(9565);
1344 var aCallable = __webpack_require__(9306);
1345 var anObject = __webpack_require__(8551);
1346 var tryToString = __webpack_require__(6823);
1347 var getIteratorMethod = __webpack_require__(851);
1348
1349 var $TypeError = TypeError;
1350
1351 module.exports = function (argument, usingIterator) {
1352 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
1353 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
1354 throw new $TypeError(tryToString(argument) + ' is not iterable');
1355 };
1356
1357
1358 /***/ }),
1359
1360 /***/ 5966:
1361 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1362
1363
1364 var aCallable = __webpack_require__(9306);
1365 var isNullOrUndefined = __webpack_require__(4117);
1366
1367 // `GetMethod` abstract operation
1368 // https://tc39.es/ecma262/#sec-getmethod
1369 module.exports = function (V, P) {
1370 var func = V[P];
1371 return isNullOrUndefined(func) ? undefined : aCallable(func);
1372 };
1373
1374
1375 /***/ }),
1376
1377 /***/ 3789:
1378 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1379
1380
1381 var aCallable = __webpack_require__(9306);
1382 var anObject = __webpack_require__(8551);
1383 var call = __webpack_require__(9565);
1384 var toIntegerOrInfinity = __webpack_require__(1291);
1385 var getIteratorDirect = __webpack_require__(1767);
1386
1387 var INVALID_SIZE = 'Invalid size';
1388 var $RangeError = RangeError;
1389 var $TypeError = TypeError;
1390 var max = Math.max;
1391
1392 var SetRecord = function (set, intSize) {
1393 this.set = set;
1394 this.size = max(intSize, 0);
1395 this.has = aCallable(set.has);
1396 this.keys = aCallable(set.keys);
1397 };
1398
1399 SetRecord.prototype = {
1400 getIterator: function () {
1401 return getIteratorDirect(anObject(call(this.keys, this.set)));
1402 },
1403 includes: function (it) {
1404 return call(this.has, this.set, it);
1405 }
1406 };
1407
1408 // `GetSetRecord` abstract operation
1409 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
1410 module.exports = function (obj) {
1411 anObject(obj);
1412 var numSize = +obj.size;
1413 // NOTE: If size is undefined, then numSize will be NaN
1414 // eslint-disable-next-line no-self-compare -- NaN check
1415 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
1416 var intSize = toIntegerOrInfinity(numSize);
1417 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
1418 return new SetRecord(obj, intSize);
1419 };
1420
1421
1422 /***/ }),
1423
1424 /***/ 4475:
1425 /***/ (function(module) {
1426
1427
1428 var check = function (it) {
1429 return it && it.Math === Math && it;
1430 };
1431
1432 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
1433 module.exports =
1434 // eslint-disable-next-line es/no-global-this -- safe
1435 check(typeof globalThis == 'object' && globalThis) ||
1436 check(typeof window == 'object' && window) ||
1437 // eslint-disable-next-line no-restricted-globals -- safe
1438 check(typeof self == 'object' && self) ||
1439 check(typeof global == 'object' && global) ||
1440 check(typeof this == 'object' && this) ||
1441 // eslint-disable-next-line no-new-func -- fallback
1442 (function () { return this; })() || Function('return this')();
1443
1444
1445 /***/ }),
1446
1447 /***/ 9297:
1448 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1449
1450
1451 var uncurryThis = __webpack_require__(9504);
1452 var toObject = __webpack_require__(8981);
1453
1454 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
1455
1456 // `HasOwnProperty` abstract operation
1457 // https://tc39.es/ecma262/#sec-hasownproperty
1458 // eslint-disable-next-line es/no-object-hasown -- safe
1459 module.exports = Object.hasOwn || function hasOwn(it, key) {
1460 return hasOwnProperty(toObject(it), key);
1461 };
1462
1463
1464 /***/ }),
1465
1466 /***/ 421:
1467 /***/ ((module) => {
1468
1469
1470 module.exports = {};
1471
1472
1473 /***/ }),
1474
1475 /***/ 397:
1476 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1477
1478
1479 var getBuiltIn = __webpack_require__(7751);
1480
1481 module.exports = getBuiltIn('document', 'documentElement');
1482
1483
1484 /***/ }),
1485
1486 /***/ 5917:
1487 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1488
1489
1490 var DESCRIPTORS = __webpack_require__(3724);
1491 var fails = __webpack_require__(9039);
1492 var createElement = __webpack_require__(4055);
1493
1494 // Thanks to IE8 for its funny defineProperty
1495 module.exports = !DESCRIPTORS && !fails(function () {
1496 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
1497 return Object.defineProperty(createElement('div'), 'a', {
1498 get: function () { return 7; }
1499 }).a !== 7;
1500 });
1501
1502
1503 /***/ }),
1504
1505 /***/ 7055:
1506 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1507
1508
1509 var uncurryThis = __webpack_require__(9504);
1510 var fails = __webpack_require__(9039);
1511 var classof = __webpack_require__(4576);
1512
1513 var $Object = Object;
1514 var split = uncurryThis(''.split);
1515
1516 // fallback for non-array-like ES3 and non-enumerable old V8 strings
1517 module.exports = fails(function () {
1518 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
1519 // eslint-disable-next-line no-prototype-builtins -- safe
1520 return !$Object('z').propertyIsEnumerable(0);
1521 }) ? function (it) {
1522 return classof(it) === 'String' ? split(it, '') : $Object(it);
1523 } : $Object;
1524
1525
1526 /***/ }),
1527
1528 /***/ 3167:
1529 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1530
1531
1532 var isCallable = __webpack_require__(4901);
1533 var isObject = __webpack_require__(34);
1534 var setPrototypeOf = __webpack_require__(2967);
1535
1536 // makes subclassing work correct for wrapped built-ins
1537 module.exports = function ($this, dummy, Wrapper) {
1538 var NewTarget, NewTargetPrototype;
1539 if (
1540 // it can work only with native `setPrototypeOf`
1541 setPrototypeOf &&
1542 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
1543 isCallable(NewTarget = dummy.constructor) &&
1544 NewTarget !== Wrapper &&
1545 isObject(NewTargetPrototype = NewTarget.prototype) &&
1546 NewTargetPrototype !== Wrapper.prototype
1547 ) setPrototypeOf($this, NewTargetPrototype);
1548 return $this;
1549 };
1550
1551
1552 /***/ }),
1553
1554 /***/ 3706:
1555 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1556
1557
1558 var uncurryThis = __webpack_require__(9504);
1559 var isCallable = __webpack_require__(4901);
1560 var store = __webpack_require__(7629);
1561
1562 var functionToString = uncurryThis(Function.toString);
1563
1564 // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
1565 if (!isCallable(store.inspectSource)) {
1566 store.inspectSource = function (it) {
1567 return functionToString(it);
1568 };
1569 }
1570
1571 module.exports = store.inspectSource;
1572
1573
1574 /***/ }),
1575
1576 /***/ 1181:
1577 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1578
1579
1580 var NATIVE_WEAK_MAP = __webpack_require__(8622);
1581 var global = __webpack_require__(4475);
1582 var isObject = __webpack_require__(34);
1583 var createNonEnumerableProperty = __webpack_require__(6699);
1584 var hasOwn = __webpack_require__(9297);
1585 var shared = __webpack_require__(7629);
1586 var sharedKey = __webpack_require__(6119);
1587 var hiddenKeys = __webpack_require__(421);
1588
1589 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
1590 var TypeError = global.TypeError;
1591 var WeakMap = global.WeakMap;
1592 var set, get, has;
1593
1594 var enforce = function (it) {
1595 return has(it) ? get(it) : set(it, {});
1596 };
1597
1598 var getterFor = function (TYPE) {
1599 return function (it) {
1600 var state;
1601 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1602 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1603 } return state;
1604 };
1605 };
1606
1607 if (NATIVE_WEAK_MAP || shared.state) {
1608 var store = shared.state || (shared.state = new WeakMap());
1609 /* eslint-disable no-self-assign -- prototype methods protection */
1610 store.get = store.get;
1611 store.has = store.has;
1612 store.set = store.set;
1613 /* eslint-enable no-self-assign -- prototype methods protection */
1614 set = function (it, metadata) {
1615 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1616 metadata.facade = it;
1617 store.set(it, metadata);
1618 return metadata;
1619 };
1620 get = function (it) {
1621 return store.get(it) || {};
1622 };
1623 has = function (it) {
1624 return store.has(it);
1625 };
1626 } else {
1627 var STATE = sharedKey('state');
1628 hiddenKeys[STATE] = true;
1629 set = function (it, metadata) {
1630 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1631 metadata.facade = it;
1632 createNonEnumerableProperty(it, STATE, metadata);
1633 return metadata;
1634 };
1635 get = function (it) {
1636 return hasOwn(it, STATE) ? it[STATE] : {};
1637 };
1638 has = function (it) {
1639 return hasOwn(it, STATE);
1640 };
1641 }
1642
1643 module.exports = {
1644 set: set,
1645 get: get,
1646 has: has,
1647 enforce: enforce,
1648 getterFor: getterFor
1649 };
1650
1651
1652 /***/ }),
1653
1654 /***/ 4209:
1655 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1656
1657
1658 var wellKnownSymbol = __webpack_require__(8227);
1659 var Iterators = __webpack_require__(6269);
1660
1661 var ITERATOR = wellKnownSymbol('iterator');
1662 var ArrayPrototype = Array.prototype;
1663
1664 // check on default Array iterator
1665 module.exports = function (it) {
1666 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
1667 };
1668
1669
1670 /***/ }),
1671
1672 /***/ 4376:
1673 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1674
1675
1676 var classof = __webpack_require__(4576);
1677
1678 // `IsArray` abstract operation
1679 // https://tc39.es/ecma262/#sec-isarray
1680 // eslint-disable-next-line es/no-array-isarray -- safe
1681 module.exports = Array.isArray || function isArray(argument) {
1682 return classof(argument) === 'Array';
1683 };
1684
1685
1686 /***/ }),
1687
1688 /***/ 1108:
1689 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1690
1691
1692 var classof = __webpack_require__(6955);
1693
1694 module.exports = function (it) {
1695 var klass = classof(it);
1696 return klass === 'BigInt64Array' || klass === 'BigUint64Array';
1697 };
1698
1699
1700 /***/ }),
1701
1702 /***/ 4901:
1703 /***/ ((module) => {
1704
1705
1706 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
1707 var documentAll = typeof document == 'object' && document.all;
1708
1709 // `IsCallable` abstract operation
1710 // https://tc39.es/ecma262/#sec-iscallable
1711 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
1712 module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
1713 return typeof argument == 'function' || argument === documentAll;
1714 } : function (argument) {
1715 return typeof argument == 'function';
1716 };
1717
1718
1719 /***/ }),
1720
1721 /***/ 2796:
1722 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1723
1724
1725 var fails = __webpack_require__(9039);
1726 var isCallable = __webpack_require__(4901);
1727
1728 var replacement = /#|\.prototype\./;
1729
1730 var isForced = function (feature, detection) {
1731 var value = data[normalize(feature)];
1732 return value === POLYFILL ? true
1733 : value === NATIVE ? false
1734 : isCallable(detection) ? fails(detection)
1735 : !!detection;
1736 };
1737
1738 var normalize = isForced.normalize = function (string) {
1739 return String(string).replace(replacement, '.').toLowerCase();
1740 };
1741
1742 var data = isForced.data = {};
1743 var NATIVE = isForced.NATIVE = 'N';
1744 var POLYFILL = isForced.POLYFILL = 'P';
1745
1746 module.exports = isForced;
1747
1748
1749 /***/ }),
1750
1751 /***/ 4117:
1752 /***/ ((module) => {
1753
1754
1755 // we can't use just `it == null` since of `document.all` special case
1756 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
1757 module.exports = function (it) {
1758 return it === null || it === undefined;
1759 };
1760
1761
1762 /***/ }),
1763
1764 /***/ 34:
1765 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1766
1767
1768 var isCallable = __webpack_require__(4901);
1769
1770 module.exports = function (it) {
1771 return typeof it == 'object' ? it !== null : isCallable(it);
1772 };
1773
1774
1775 /***/ }),
1776
1777 /***/ 3925:
1778 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1779
1780
1781 var isObject = __webpack_require__(34);
1782
1783 module.exports = function (argument) {
1784 return isObject(argument) || argument === null;
1785 };
1786
1787
1788 /***/ }),
1789
1790 /***/ 6395:
1791 /***/ ((module) => {
1792
1793
1794 module.exports = false;
1795
1796
1797 /***/ }),
1798
1799 /***/ 757:
1800 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1801
1802
1803 var getBuiltIn = __webpack_require__(7751);
1804 var isCallable = __webpack_require__(4901);
1805 var isPrototypeOf = __webpack_require__(1625);
1806 var USE_SYMBOL_AS_UID = __webpack_require__(7040);
1807
1808 var $Object = Object;
1809
1810 module.exports = USE_SYMBOL_AS_UID ? function (it) {
1811 return typeof it == 'symbol';
1812 } : function (it) {
1813 var $Symbol = getBuiltIn('Symbol');
1814 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
1815 };
1816
1817
1818 /***/ }),
1819
1820 /***/ 507:
1821 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1822
1823
1824 var call = __webpack_require__(9565);
1825
1826 module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
1827 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
1828 var next = record.next;
1829 var step, result;
1830 while (!(step = call(next, iterator)).done) {
1831 result = fn(step.value);
1832 if (result !== undefined) return result;
1833 }
1834 };
1835
1836
1837 /***/ }),
1838
1839 /***/ 2652:
1840 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1841
1842
1843 var bind = __webpack_require__(6080);
1844 var call = __webpack_require__(9565);
1845 var anObject = __webpack_require__(8551);
1846 var tryToString = __webpack_require__(6823);
1847 var isArrayIteratorMethod = __webpack_require__(4209);
1848 var lengthOfArrayLike = __webpack_require__(6198);
1849 var isPrototypeOf = __webpack_require__(1625);
1850 var getIterator = __webpack_require__(81);
1851 var getIteratorMethod = __webpack_require__(851);
1852 var iteratorClose = __webpack_require__(9539);
1853
1854 var $TypeError = TypeError;
1855
1856 var Result = function (stopped, result) {
1857 this.stopped = stopped;
1858 this.result = result;
1859 };
1860
1861 var ResultPrototype = Result.prototype;
1862
1863 module.exports = function (iterable, unboundFunction, options) {
1864 var that = options && options.that;
1865 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
1866 var IS_RECORD = !!(options && options.IS_RECORD);
1867 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
1868 var INTERRUPTED = !!(options && options.INTERRUPTED);
1869 var fn = bind(unboundFunction, that);
1870 var iterator, iterFn, index, length, result, next, step;
1871
1872 var stop = function (condition) {
1873 if (iterator) iteratorClose(iterator, 'normal', condition);
1874 return new Result(true, condition);
1875 };
1876
1877 var callFn = function (value) {
1878 if (AS_ENTRIES) {
1879 anObject(value);
1880 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
1881 } return INTERRUPTED ? fn(value, stop) : fn(value);
1882 };
1883
1884 if (IS_RECORD) {
1885 iterator = iterable.iterator;
1886 } else if (IS_ITERATOR) {
1887 iterator = iterable;
1888 } else {
1889 iterFn = getIteratorMethod(iterable);
1890 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
1891 // optimisation for array iterators
1892 if (isArrayIteratorMethod(iterFn)) {
1893 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
1894 result = callFn(iterable[index]);
1895 if (result && isPrototypeOf(ResultPrototype, result)) return result;
1896 } return new Result(false);
1897 }
1898 iterator = getIterator(iterable, iterFn);
1899 }
1900
1901 next = IS_RECORD ? iterable.next : iterator.next;
1902 while (!(step = call(next, iterator)).done) {
1903 try {
1904 result = callFn(step.value);
1905 } catch (error) {
1906 iteratorClose(iterator, 'throw', error);
1907 }
1908 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
1909 } return new Result(false);
1910 };
1911
1912
1913 /***/ }),
1914
1915 /***/ 9539:
1916 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1917
1918
1919 var call = __webpack_require__(9565);
1920 var anObject = __webpack_require__(8551);
1921 var getMethod = __webpack_require__(5966);
1922
1923 module.exports = function (iterator, kind, value) {
1924 var innerResult, innerError;
1925 anObject(iterator);
1926 try {
1927 innerResult = getMethod(iterator, 'return');
1928 if (!innerResult) {
1929 if (kind === 'throw') throw value;
1930 return value;
1931 }
1932 innerResult = call(innerResult, iterator);
1933 } catch (error) {
1934 innerError = true;
1935 innerResult = error;
1936 }
1937 if (kind === 'throw') throw value;
1938 if (innerError) throw innerResult;
1939 anObject(innerResult);
1940 return value;
1941 };
1942
1943
1944 /***/ }),
1945
1946 /***/ 9462:
1947 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1948
1949
1950 var call = __webpack_require__(9565);
1951 var create = __webpack_require__(2360);
1952 var createNonEnumerableProperty = __webpack_require__(6699);
1953 var defineBuiltIns = __webpack_require__(6279);
1954 var wellKnownSymbol = __webpack_require__(8227);
1955 var InternalStateModule = __webpack_require__(1181);
1956 var getMethod = __webpack_require__(5966);
1957 var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
1958 var createIterResultObject = __webpack_require__(2529);
1959 var iteratorClose = __webpack_require__(9539);
1960
1961 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1962 var ITERATOR_HELPER = 'IteratorHelper';
1963 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
1964 var setInternalState = InternalStateModule.set;
1965
1966 var createIteratorProxyPrototype = function (IS_ITERATOR) {
1967 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
1968
1969 return defineBuiltIns(create(IteratorPrototype), {
1970 next: function next() {
1971 var state = getInternalState(this);
1972 // for simplification:
1973 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
1974 // for `%IteratorHelperPrototype%.next` - just a value
1975 if (IS_ITERATOR) return state.nextHandler();
1976 try {
1977 var result = state.done ? undefined : state.nextHandler();
1978 return createIterResultObject(result, state.done);
1979 } catch (error) {
1980 state.done = true;
1981 throw error;
1982 }
1983 },
1984 'return': function () {
1985 var state = getInternalState(this);
1986 var iterator = state.iterator;
1987 state.done = true;
1988 if (IS_ITERATOR) {
1989 var returnMethod = getMethod(iterator, 'return');
1990 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
1991 }
1992 if (state.inner) try {
1993 iteratorClose(state.inner.iterator, 'normal');
1994 } catch (error) {
1995 return iteratorClose(iterator, 'throw', error);
1996 }
1997 iteratorClose(iterator, 'normal');
1998 return createIterResultObject(undefined, true);
1999 }
2000 });
2001 };
2002
2003 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
2004 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
2005
2006 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
2007
2008 module.exports = function (nextHandler, IS_ITERATOR) {
2009 var IteratorProxy = function Iterator(record, state) {
2010 if (state) {
2011 state.iterator = record.iterator;
2012 state.next = record.next;
2013 } else state = record;
2014 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
2015 state.nextHandler = nextHandler;
2016 state.counter = 0;
2017 state.done = false;
2018 setInternalState(this, state);
2019 };
2020
2021 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
2022
2023 return IteratorProxy;
2024 };
2025
2026
2027 /***/ }),
2028
2029 /***/ 713:
2030 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2031
2032
2033 var call = __webpack_require__(9565);
2034 var aCallable = __webpack_require__(9306);
2035 var anObject = __webpack_require__(8551);
2036 var getIteratorDirect = __webpack_require__(1767);
2037 var createIteratorProxy = __webpack_require__(9462);
2038 var callWithSafeIterationClosing = __webpack_require__(6319);
2039
2040 var IteratorProxy = createIteratorProxy(function () {
2041 var iterator = this.iterator;
2042 var result = anObject(call(this.next, iterator));
2043 var done = this.done = !!result.done;
2044 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
2045 });
2046
2047 // `Iterator.prototype.map` method
2048 // https://github.com/tc39/proposal-iterator-helpers
2049 module.exports = function map(mapper) {
2050 anObject(this);
2051 aCallable(mapper);
2052 return new IteratorProxy(getIteratorDirect(this), {
2053 mapper: mapper
2054 });
2055 };
2056
2057
2058 /***/ }),
2059
2060 /***/ 7657:
2061 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2062
2063
2064 var fails = __webpack_require__(9039);
2065 var isCallable = __webpack_require__(4901);
2066 var isObject = __webpack_require__(34);
2067 var create = __webpack_require__(2360);
2068 var getPrototypeOf = __webpack_require__(2787);
2069 var defineBuiltIn = __webpack_require__(6840);
2070 var wellKnownSymbol = __webpack_require__(8227);
2071 var IS_PURE = __webpack_require__(6395);
2072
2073 var ITERATOR = wellKnownSymbol('iterator');
2074 var BUGGY_SAFARI_ITERATORS = false;
2075
2076 // `%IteratorPrototype%` object
2077 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
2078 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
2079
2080 /* eslint-disable es/no-array-prototype-keys -- safe */
2081 if ([].keys) {
2082 arrayIterator = [].keys();
2083 // Safari 8 has buggy iterators w/o `next`
2084 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
2085 else {
2086 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
2087 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
2088 }
2089 }
2090
2091 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
2092 var test = {};
2093 // FF44- legacy iterators case
2094 return IteratorPrototype[ITERATOR].call(test) !== test;
2095 });
2096
2097 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
2098 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
2099
2100 // `%IteratorPrototype%[@@iterator]()` method
2101 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
2102 if (!isCallable(IteratorPrototype[ITERATOR])) {
2103 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
2104 return this;
2105 });
2106 }
2107
2108 module.exports = {
2109 IteratorPrototype: IteratorPrototype,
2110 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
2111 };
2112
2113
2114 /***/ }),
2115
2116 /***/ 6269:
2117 /***/ ((module) => {
2118
2119
2120 module.exports = {};
2121
2122
2123 /***/ }),
2124
2125 /***/ 6198:
2126 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2127
2128
2129 var toLength = __webpack_require__(8014);
2130
2131 // `LengthOfArrayLike` abstract operation
2132 // https://tc39.es/ecma262/#sec-lengthofarraylike
2133 module.exports = function (obj) {
2134 return toLength(obj.length);
2135 };
2136
2137
2138 /***/ }),
2139
2140 /***/ 283:
2141 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2142
2143
2144 var uncurryThis = __webpack_require__(9504);
2145 var fails = __webpack_require__(9039);
2146 var isCallable = __webpack_require__(4901);
2147 var hasOwn = __webpack_require__(9297);
2148 var DESCRIPTORS = __webpack_require__(3724);
2149 var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(350).CONFIGURABLE);
2150 var inspectSource = __webpack_require__(3706);
2151 var InternalStateModule = __webpack_require__(1181);
2152
2153 var enforceInternalState = InternalStateModule.enforce;
2154 var getInternalState = InternalStateModule.get;
2155 var $String = String;
2156 // eslint-disable-next-line es/no-object-defineproperty -- safe
2157 var defineProperty = Object.defineProperty;
2158 var stringSlice = uncurryThis(''.slice);
2159 var replace = uncurryThis(''.replace);
2160 var join = uncurryThis([].join);
2161
2162 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
2163 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
2164 });
2165
2166 var TEMPLATE = String(String).split('String');
2167
2168 var makeBuiltIn = module.exports = function (value, name, options) {
2169 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
2170 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
2171 }
2172 if (options && options.getter) name = 'get ' + name;
2173 if (options && options.setter) name = 'set ' + name;
2174 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
2175 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
2176 else value.name = name;
2177 }
2178 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
2179 defineProperty(value, 'length', { value: options.arity });
2180 }
2181 try {
2182 if (options && hasOwn(options, 'constructor') && options.constructor) {
2183 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
2184 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
2185 } else if (value.prototype) value.prototype = undefined;
2186 } catch (error) { /* empty */ }
2187 var state = enforceInternalState(value);
2188 if (!hasOwn(state, 'source')) {
2189 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
2190 } return value;
2191 };
2192
2193 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
2194 // eslint-disable-next-line no-extend-native -- required
2195 Function.prototype.toString = makeBuiltIn(function toString() {
2196 return isCallable(this) && getInternalState(this).source || inspectSource(this);
2197 }, 'toString');
2198
2199
2200 /***/ }),
2201
2202 /***/ 741:
2203 /***/ ((module) => {
2204
2205
2206 var ceil = Math.ceil;
2207 var floor = Math.floor;
2208
2209 // `Math.trunc` method
2210 // https://tc39.es/ecma262/#sec-math.trunc
2211 // eslint-disable-next-line es/no-math-trunc -- safe
2212 module.exports = Math.trunc || function trunc(x) {
2213 var n = +x;
2214 return (n > 0 ? floor : ceil)(n);
2215 };
2216
2217
2218 /***/ }),
2219
2220 /***/ 6043:
2221 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2222
2223
2224 var aCallable = __webpack_require__(9306);
2225
2226 var $TypeError = TypeError;
2227
2228 var PromiseCapability = function (C) {
2229 var resolve, reject;
2230 this.promise = new C(function ($$resolve, $$reject) {
2231 if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor');
2232 resolve = $$resolve;
2233 reject = $$reject;
2234 });
2235 this.resolve = aCallable(resolve);
2236 this.reject = aCallable(reject);
2237 };
2238
2239 // `NewPromiseCapability` abstract operation
2240 // https://tc39.es/ecma262/#sec-newpromisecapability
2241 module.exports.f = function (C) {
2242 return new PromiseCapability(C);
2243 };
2244
2245
2246 /***/ }),
2247
2248 /***/ 2603:
2249 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2250
2251
2252 var toString = __webpack_require__(655);
2253
2254 module.exports = function (argument, $default) {
2255 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
2256 };
2257
2258
2259 /***/ }),
2260
2261 /***/ 2360:
2262 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2263
2264
2265 /* global ActiveXObject -- old IE, WSH */
2266 var anObject = __webpack_require__(8551);
2267 var definePropertiesModule = __webpack_require__(6801);
2268 var enumBugKeys = __webpack_require__(8727);
2269 var hiddenKeys = __webpack_require__(421);
2270 var html = __webpack_require__(397);
2271 var documentCreateElement = __webpack_require__(4055);
2272 var sharedKey = __webpack_require__(6119);
2273
2274 var GT = '>';
2275 var LT = '<';
2276 var PROTOTYPE = 'prototype';
2277 var SCRIPT = 'script';
2278 var IE_PROTO = sharedKey('IE_PROTO');
2279
2280 var EmptyConstructor = function () { /* empty */ };
2281
2282 var scriptTag = function (content) {
2283 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
2284 };
2285
2286 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
2287 var NullProtoObjectViaActiveX = function (activeXDocument) {
2288 activeXDocument.write(scriptTag(''));
2289 activeXDocument.close();
2290 var temp = activeXDocument.parentWindow.Object;
2291 activeXDocument = null; // avoid memory leak
2292 return temp;
2293 };
2294
2295 // Create object with fake `null` prototype: use iframe Object with cleared prototype
2296 var NullProtoObjectViaIFrame = function () {
2297 // Thrash, waste and sodomy: IE GC bug
2298 var iframe = documentCreateElement('iframe');
2299 var JS = 'java' + SCRIPT + ':';
2300 var iframeDocument;
2301 iframe.style.display = 'none';
2302 html.appendChild(iframe);
2303 // https://github.com/zloirock/core-js/issues/475
2304 iframe.src = String(JS);
2305 iframeDocument = iframe.contentWindow.document;
2306 iframeDocument.open();
2307 iframeDocument.write(scriptTag('document.F=Object'));
2308 iframeDocument.close();
2309 return iframeDocument.F;
2310 };
2311
2312 // Check for document.domain and active x support
2313 // No need to use active x approach when document.domain is not set
2314 // see https://github.com/es-shims/es5-shim/issues/150
2315 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
2316 // avoid IE GC bug
2317 var activeXDocument;
2318 var NullProtoObject = function () {
2319 try {
2320 activeXDocument = new ActiveXObject('htmlfile');
2321 } catch (error) { /* ignore */ }
2322 NullProtoObject = typeof document != 'undefined'
2323 ? document.domain && activeXDocument
2324 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
2325 : NullProtoObjectViaIFrame()
2326 : NullProtoObjectViaActiveX(activeXDocument); // WSH
2327 var length = enumBugKeys.length;
2328 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
2329 return NullProtoObject();
2330 };
2331
2332 hiddenKeys[IE_PROTO] = true;
2333
2334 // `Object.create` method
2335 // https://tc39.es/ecma262/#sec-object.create
2336 // eslint-disable-next-line es/no-object-create -- safe
2337 module.exports = Object.create || function create(O, Properties) {
2338 var result;
2339 if (O !== null) {
2340 EmptyConstructor[PROTOTYPE] = anObject(O);
2341 result = new EmptyConstructor();
2342 EmptyConstructor[PROTOTYPE] = null;
2343 // add "__proto__" for Object.getPrototypeOf polyfill
2344 result[IE_PROTO] = O;
2345 } else result = NullProtoObject();
2346 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
2347 };
2348
2349
2350 /***/ }),
2351
2352 /***/ 6801:
2353 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2354
2355
2356 var DESCRIPTORS = __webpack_require__(3724);
2357 var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
2358 var definePropertyModule = __webpack_require__(4913);
2359 var anObject = __webpack_require__(8551);
2360 var toIndexedObject = __webpack_require__(5397);
2361 var objectKeys = __webpack_require__(1072);
2362
2363 // `Object.defineProperties` method
2364 // https://tc39.es/ecma262/#sec-object.defineproperties
2365 // eslint-disable-next-line es/no-object-defineproperties -- safe
2366 exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
2367 anObject(O);
2368 var props = toIndexedObject(Properties);
2369 var keys = objectKeys(Properties);
2370 var length = keys.length;
2371 var index = 0;
2372 var key;
2373 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
2374 return O;
2375 };
2376
2377
2378 /***/ }),
2379
2380 /***/ 4913:
2381 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2382
2383
2384 var DESCRIPTORS = __webpack_require__(3724);
2385 var IE8_DOM_DEFINE = __webpack_require__(5917);
2386 var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
2387 var anObject = __webpack_require__(8551);
2388 var toPropertyKey = __webpack_require__(6969);
2389
2390 var $TypeError = TypeError;
2391 // eslint-disable-next-line es/no-object-defineproperty -- safe
2392 var $defineProperty = Object.defineProperty;
2393 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2394 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2395 var ENUMERABLE = 'enumerable';
2396 var CONFIGURABLE = 'configurable';
2397 var WRITABLE = 'writable';
2398
2399 // `Object.defineProperty` method
2400 // https://tc39.es/ecma262/#sec-object.defineproperty
2401 exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
2402 anObject(O);
2403 P = toPropertyKey(P);
2404 anObject(Attributes);
2405 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
2406 var current = $getOwnPropertyDescriptor(O, P);
2407 if (current && current[WRITABLE]) {
2408 O[P] = Attributes.value;
2409 Attributes = {
2410 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
2411 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
2412 writable: false
2413 };
2414 }
2415 } return $defineProperty(O, P, Attributes);
2416 } : $defineProperty : function defineProperty(O, P, Attributes) {
2417 anObject(O);
2418 P = toPropertyKey(P);
2419 anObject(Attributes);
2420 if (IE8_DOM_DEFINE) try {
2421 return $defineProperty(O, P, Attributes);
2422 } catch (error) { /* empty */ }
2423 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
2424 if ('value' in Attributes) O[P] = Attributes.value;
2425 return O;
2426 };
2427
2428
2429 /***/ }),
2430
2431 /***/ 7347:
2432 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2433
2434
2435 var DESCRIPTORS = __webpack_require__(3724);
2436 var call = __webpack_require__(9565);
2437 var propertyIsEnumerableModule = __webpack_require__(8773);
2438 var createPropertyDescriptor = __webpack_require__(6980);
2439 var toIndexedObject = __webpack_require__(5397);
2440 var toPropertyKey = __webpack_require__(6969);
2441 var hasOwn = __webpack_require__(9297);
2442 var IE8_DOM_DEFINE = __webpack_require__(5917);
2443
2444 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2445 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2446
2447 // `Object.getOwnPropertyDescriptor` method
2448 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
2449 exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
2450 O = toIndexedObject(O);
2451 P = toPropertyKey(P);
2452 if (IE8_DOM_DEFINE) try {
2453 return $getOwnPropertyDescriptor(O, P);
2454 } catch (error) { /* empty */ }
2455 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
2456 };
2457
2458
2459 /***/ }),
2460
2461 /***/ 8480:
2462 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2463
2464
2465 var internalObjectKeys = __webpack_require__(1828);
2466 var enumBugKeys = __webpack_require__(8727);
2467
2468 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
2469
2470 // `Object.getOwnPropertyNames` method
2471 // https://tc39.es/ecma262/#sec-object.getownpropertynames
2472 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
2473 exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
2474 return internalObjectKeys(O, hiddenKeys);
2475 };
2476
2477
2478 /***/ }),
2479
2480 /***/ 3717:
2481 /***/ ((__unused_webpack_module, exports) => {
2482
2483
2484 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
2485 exports.f = Object.getOwnPropertySymbols;
2486
2487
2488 /***/ }),
2489
2490 /***/ 2787:
2491 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2492
2493
2494 var hasOwn = __webpack_require__(9297);
2495 var isCallable = __webpack_require__(4901);
2496 var toObject = __webpack_require__(8981);
2497 var sharedKey = __webpack_require__(6119);
2498 var CORRECT_PROTOTYPE_GETTER = __webpack_require__(2211);
2499
2500 var IE_PROTO = sharedKey('IE_PROTO');
2501 var $Object = Object;
2502 var ObjectPrototype = $Object.prototype;
2503
2504 // `Object.getPrototypeOf` method
2505 // https://tc39.es/ecma262/#sec-object.getprototypeof
2506 // eslint-disable-next-line es/no-object-getprototypeof -- safe
2507 module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
2508 var object = toObject(O);
2509 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
2510 var constructor = object.constructor;
2511 if (isCallable(constructor) && object instanceof constructor) {
2512 return constructor.prototype;
2513 } return object instanceof $Object ? ObjectPrototype : null;
2514 };
2515
2516
2517 /***/ }),
2518
2519 /***/ 1625:
2520 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2521
2522
2523 var uncurryThis = __webpack_require__(9504);
2524
2525 module.exports = uncurryThis({}.isPrototypeOf);
2526
2527
2528 /***/ }),
2529
2530 /***/ 1828:
2531 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2532
2533
2534 var uncurryThis = __webpack_require__(9504);
2535 var hasOwn = __webpack_require__(9297);
2536 var toIndexedObject = __webpack_require__(5397);
2537 var indexOf = (__webpack_require__(9617).indexOf);
2538 var hiddenKeys = __webpack_require__(421);
2539
2540 var push = uncurryThis([].push);
2541
2542 module.exports = function (object, names) {
2543 var O = toIndexedObject(object);
2544 var i = 0;
2545 var result = [];
2546 var key;
2547 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
2548 // Don't enum bug & hidden keys
2549 while (names.length > i) if (hasOwn(O, key = names[i++])) {
2550 ~indexOf(result, key) || push(result, key);
2551 }
2552 return result;
2553 };
2554
2555
2556 /***/ }),
2557
2558 /***/ 1072:
2559 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2560
2561
2562 var internalObjectKeys = __webpack_require__(1828);
2563 var enumBugKeys = __webpack_require__(8727);
2564
2565 // `Object.keys` method
2566 // https://tc39.es/ecma262/#sec-object.keys
2567 // eslint-disable-next-line es/no-object-keys -- safe
2568 module.exports = Object.keys || function keys(O) {
2569 return internalObjectKeys(O, enumBugKeys);
2570 };
2571
2572
2573 /***/ }),
2574
2575 /***/ 8773:
2576 /***/ ((__unused_webpack_module, exports) => {
2577
2578
2579 var $propertyIsEnumerable = {}.propertyIsEnumerable;
2580 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2581 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2582
2583 // Nashorn ~ JDK8 bug
2584 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
2585
2586 // `Object.prototype.propertyIsEnumerable` method implementation
2587 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
2588 exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
2589 var descriptor = getOwnPropertyDescriptor(this, V);
2590 return !!descriptor && descriptor.enumerable;
2591 } : $propertyIsEnumerable;
2592
2593
2594 /***/ }),
2595
2596 /***/ 2967:
2597 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2598
2599
2600 /* eslint-disable no-proto -- safe */
2601 var uncurryThisAccessor = __webpack_require__(6706);
2602 var isObject = __webpack_require__(34);
2603 var requireObjectCoercible = __webpack_require__(7750);
2604 var aPossiblePrototype = __webpack_require__(3506);
2605
2606 // `Object.setPrototypeOf` method
2607 // https://tc39.es/ecma262/#sec-object.setprototypeof
2608 // Works with __proto__ only. Old v8 can't work with null proto objects.
2609 // eslint-disable-next-line es/no-object-setprototypeof -- safe
2610 module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
2611 var CORRECT_SETTER = false;
2612 var test = {};
2613 var setter;
2614 try {
2615 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
2616 setter(test, []);
2617 CORRECT_SETTER = test instanceof Array;
2618 } catch (error) { /* empty */ }
2619 return function setPrototypeOf(O, proto) {
2620 requireObjectCoercible(O);
2621 aPossiblePrototype(proto);
2622 if (!isObject(O)) return O;
2623 if (CORRECT_SETTER) setter(O, proto);
2624 else O.__proto__ = proto;
2625 return O;
2626 };
2627 }() : undefined);
2628
2629
2630 /***/ }),
2631
2632 /***/ 4270:
2633 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2634
2635
2636 var call = __webpack_require__(9565);
2637 var isCallable = __webpack_require__(4901);
2638 var isObject = __webpack_require__(34);
2639
2640 var $TypeError = TypeError;
2641
2642 // `OrdinaryToPrimitive` abstract operation
2643 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
2644 module.exports = function (input, pref) {
2645 var fn, val;
2646 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
2647 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
2648 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
2649 throw new $TypeError("Can't convert object to primitive value");
2650 };
2651
2652
2653 /***/ }),
2654
2655 /***/ 5031:
2656 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2657
2658
2659 var getBuiltIn = __webpack_require__(7751);
2660 var uncurryThis = __webpack_require__(9504);
2661 var getOwnPropertyNamesModule = __webpack_require__(8480);
2662 var getOwnPropertySymbolsModule = __webpack_require__(3717);
2663 var anObject = __webpack_require__(8551);
2664
2665 var concat = uncurryThis([].concat);
2666
2667 // all object keys, includes non-enumerable and symbols
2668 module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
2669 var keys = getOwnPropertyNamesModule.f(anObject(it));
2670 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
2671 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
2672 };
2673
2674
2675 /***/ }),
2676
2677 /***/ 8235:
2678 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2679
2680
2681 var uncurryThis = __webpack_require__(9504);
2682 var hasOwn = __webpack_require__(9297);
2683
2684 var $SyntaxError = SyntaxError;
2685 var $parseInt = parseInt;
2686 var fromCharCode = String.fromCharCode;
2687 var at = uncurryThis(''.charAt);
2688 var slice = uncurryThis(''.slice);
2689 var exec = uncurryThis(/./.exec);
2690
2691 var codePoints = {
2692 '\\"': '"',
2693 '\\\\': '\\',
2694 '\\/': '/',
2695 '\\b': '\b',
2696 '\\f': '\f',
2697 '\\n': '\n',
2698 '\\r': '\r',
2699 '\\t': '\t'
2700 };
2701
2702 var IS_4_HEX_DIGITS = /^[\da-f]{4}$/i;
2703 // eslint-disable-next-line regexp/no-control-character -- safe
2704 var IS_C0_CONTROL_CODE = /^[\u0000-\u001F]$/;
2705
2706 module.exports = function (source, i) {
2707 var unterminated = true;
2708 var value = '';
2709 while (i < source.length) {
2710 var chr = at(source, i);
2711 if (chr === '\\') {
2712 var twoChars = slice(source, i, i + 2);
2713 if (hasOwn(codePoints, twoChars)) {
2714 value += codePoints[twoChars];
2715 i += 2;
2716 } else if (twoChars === '\\u') {
2717 i += 2;
2718 var fourHexDigits = slice(source, i, i + 4);
2719 if (!exec(IS_4_HEX_DIGITS, fourHexDigits)) throw new $SyntaxError('Bad Unicode escape at: ' + i);
2720 value += fromCharCode($parseInt(fourHexDigits, 16));
2721 i += 4;
2722 } else throw new $SyntaxError('Unknown escape sequence: "' + twoChars + '"');
2723 } else if (chr === '"') {
2724 unterminated = false;
2725 i++;
2726 break;
2727 } else {
2728 if (exec(IS_C0_CONTROL_CODE, chr)) throw new $SyntaxError('Bad control character in string literal at: ' + i);
2729 value += chr;
2730 i++;
2731 }
2732 }
2733 if (unterminated) throw new $SyntaxError('Unterminated string at: ' + i);
2734 return { value: value, end: i };
2735 };
2736
2737
2738 /***/ }),
2739
2740 /***/ 7750:
2741 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2742
2743
2744 var isNullOrUndefined = __webpack_require__(4117);
2745
2746 var $TypeError = TypeError;
2747
2748 // `RequireObjectCoercible` abstract operation
2749 // https://tc39.es/ecma262/#sec-requireobjectcoercible
2750 module.exports = function (it) {
2751 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
2752 return it;
2753 };
2754
2755
2756 /***/ }),
2757
2758 /***/ 9286:
2759 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2760
2761
2762 var SetHelpers = __webpack_require__(4402);
2763 var iterate = __webpack_require__(8469);
2764
2765 var Set = SetHelpers.Set;
2766 var add = SetHelpers.add;
2767
2768 module.exports = function (set) {
2769 var result = new Set();
2770 iterate(set, function (it) {
2771 add(result, it);
2772 });
2773 return result;
2774 };
2775
2776
2777 /***/ }),
2778
2779 /***/ 3440:
2780 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2781
2782
2783 var aSet = __webpack_require__(7080);
2784 var SetHelpers = __webpack_require__(4402);
2785 var clone = __webpack_require__(9286);
2786 var size = __webpack_require__(5170);
2787 var getSetRecord = __webpack_require__(3789);
2788 var iterateSet = __webpack_require__(8469);
2789 var iterateSimple = __webpack_require__(507);
2790
2791 var has = SetHelpers.has;
2792 var remove = SetHelpers.remove;
2793
2794 // `Set.prototype.difference` method
2795 // https://github.com/tc39/proposal-set-methods
2796 module.exports = function difference(other) {
2797 var O = aSet(this);
2798 var otherRec = getSetRecord(other);
2799 var result = clone(O);
2800 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
2801 if (otherRec.includes(e)) remove(result, e);
2802 });
2803 else iterateSimple(otherRec.getIterator(), function (e) {
2804 if (has(O, e)) remove(result, e);
2805 });
2806 return result;
2807 };
2808
2809
2810 /***/ }),
2811
2812 /***/ 4402:
2813 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2814
2815
2816 var uncurryThis = __webpack_require__(9504);
2817
2818 // eslint-disable-next-line es/no-set -- safe
2819 var SetPrototype = Set.prototype;
2820
2821 module.exports = {
2822 // eslint-disable-next-line es/no-set -- safe
2823 Set: Set,
2824 add: uncurryThis(SetPrototype.add),
2825 has: uncurryThis(SetPrototype.has),
2826 remove: uncurryThis(SetPrototype['delete']),
2827 proto: SetPrototype
2828 };
2829
2830
2831 /***/ }),
2832
2833 /***/ 8750:
2834 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2835
2836
2837 var aSet = __webpack_require__(7080);
2838 var SetHelpers = __webpack_require__(4402);
2839 var size = __webpack_require__(5170);
2840 var getSetRecord = __webpack_require__(3789);
2841 var iterateSet = __webpack_require__(8469);
2842 var iterateSimple = __webpack_require__(507);
2843
2844 var Set = SetHelpers.Set;
2845 var add = SetHelpers.add;
2846 var has = SetHelpers.has;
2847
2848 // `Set.prototype.intersection` method
2849 // https://github.com/tc39/proposal-set-methods
2850 module.exports = function intersection(other) {
2851 var O = aSet(this);
2852 var otherRec = getSetRecord(other);
2853 var result = new Set();
2854
2855 if (size(O) > otherRec.size) {
2856 iterateSimple(otherRec.getIterator(), function (e) {
2857 if (has(O, e)) add(result, e);
2858 });
2859 } else {
2860 iterateSet(O, function (e) {
2861 if (otherRec.includes(e)) add(result, e);
2862 });
2863 }
2864
2865 return result;
2866 };
2867
2868
2869 /***/ }),
2870
2871 /***/ 4449:
2872 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2873
2874
2875 var aSet = __webpack_require__(7080);
2876 var has = (__webpack_require__(4402).has);
2877 var size = __webpack_require__(5170);
2878 var getSetRecord = __webpack_require__(3789);
2879 var iterateSet = __webpack_require__(8469);
2880 var iterateSimple = __webpack_require__(507);
2881 var iteratorClose = __webpack_require__(9539);
2882
2883 // `Set.prototype.isDisjointFrom` method
2884 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
2885 module.exports = function isDisjointFrom(other) {
2886 var O = aSet(this);
2887 var otherRec = getSetRecord(other);
2888 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
2889 if (otherRec.includes(e)) return false;
2890 }, true) !== false;
2891 var iterator = otherRec.getIterator();
2892 return iterateSimple(iterator, function (e) {
2893 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
2894 }) !== false;
2895 };
2896
2897
2898 /***/ }),
2899
2900 /***/ 3838:
2901 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2902
2903
2904 var aSet = __webpack_require__(7080);
2905 var size = __webpack_require__(5170);
2906 var iterate = __webpack_require__(8469);
2907 var getSetRecord = __webpack_require__(3789);
2908
2909 // `Set.prototype.isSubsetOf` method
2910 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
2911 module.exports = function isSubsetOf(other) {
2912 var O = aSet(this);
2913 var otherRec = getSetRecord(other);
2914 if (size(O) > otherRec.size) return false;
2915 return iterate(O, function (e) {
2916 if (!otherRec.includes(e)) return false;
2917 }, true) !== false;
2918 };
2919
2920
2921 /***/ }),
2922
2923 /***/ 8527:
2924 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2925
2926
2927 var aSet = __webpack_require__(7080);
2928 var has = (__webpack_require__(4402).has);
2929 var size = __webpack_require__(5170);
2930 var getSetRecord = __webpack_require__(3789);
2931 var iterateSimple = __webpack_require__(507);
2932 var iteratorClose = __webpack_require__(9539);
2933
2934 // `Set.prototype.isSupersetOf` method
2935 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
2936 module.exports = function isSupersetOf(other) {
2937 var O = aSet(this);
2938 var otherRec = getSetRecord(other);
2939 if (size(O) < otherRec.size) return false;
2940 var iterator = otherRec.getIterator();
2941 return iterateSimple(iterator, function (e) {
2942 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
2943 }) !== false;
2944 };
2945
2946
2947 /***/ }),
2948
2949 /***/ 8469:
2950 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2951
2952
2953 var uncurryThis = __webpack_require__(9504);
2954 var iterateSimple = __webpack_require__(507);
2955 var SetHelpers = __webpack_require__(4402);
2956
2957 var Set = SetHelpers.Set;
2958 var SetPrototype = SetHelpers.proto;
2959 var forEach = uncurryThis(SetPrototype.forEach);
2960 var keys = uncurryThis(SetPrototype.keys);
2961 var next = keys(new Set()).next;
2962
2963 module.exports = function (set, fn, interruptible) {
2964 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
2965 };
2966
2967
2968 /***/ }),
2969
2970 /***/ 4916:
2971 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2972
2973
2974 var getBuiltIn = __webpack_require__(7751);
2975
2976 var createSetLike = function (size) {
2977 return {
2978 size: size,
2979 has: function () {
2980 return false;
2981 },
2982 keys: function () {
2983 return {
2984 next: function () {
2985 return { done: true };
2986 }
2987 };
2988 }
2989 };
2990 };
2991
2992 module.exports = function (name) {
2993 var Set = getBuiltIn('Set');
2994 try {
2995 new Set()[name](createSetLike(0));
2996 try {
2997 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
2998 // https://github.com/tc39/proposal-set-methods/pull/88
2999 new Set()[name](createSetLike(-1));
3000 return false;
3001 } catch (error2) {
3002 return true;
3003 }
3004 } catch (error) {
3005 return false;
3006 }
3007 };
3008
3009
3010 /***/ }),
3011
3012 /***/ 5170:
3013 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3014
3015
3016 var uncurryThisAccessor = __webpack_require__(6706);
3017 var SetHelpers = __webpack_require__(4402);
3018
3019 module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
3020 return set.size;
3021 };
3022
3023
3024 /***/ }),
3025
3026 /***/ 3650:
3027 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3028
3029
3030 var aSet = __webpack_require__(7080);
3031 var SetHelpers = __webpack_require__(4402);
3032 var clone = __webpack_require__(9286);
3033 var getSetRecord = __webpack_require__(3789);
3034 var iterateSimple = __webpack_require__(507);
3035
3036 var add = SetHelpers.add;
3037 var has = SetHelpers.has;
3038 var remove = SetHelpers.remove;
3039
3040 // `Set.prototype.symmetricDifference` method
3041 // https://github.com/tc39/proposal-set-methods
3042 module.exports = function symmetricDifference(other) {
3043 var O = aSet(this);
3044 var keysIter = getSetRecord(other).getIterator();
3045 var result = clone(O);
3046 iterateSimple(keysIter, function (e) {
3047 if (has(O, e)) remove(result, e);
3048 else add(result, e);
3049 });
3050 return result;
3051 };
3052
3053
3054 /***/ }),
3055
3056 /***/ 4204:
3057 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3058
3059
3060 var aSet = __webpack_require__(7080);
3061 var add = (__webpack_require__(4402).add);
3062 var clone = __webpack_require__(9286);
3063 var getSetRecord = __webpack_require__(3789);
3064 var iterateSimple = __webpack_require__(507);
3065
3066 // `Set.prototype.union` method
3067 // https://github.com/tc39/proposal-set-methods
3068 module.exports = function union(other) {
3069 var O = aSet(this);
3070 var keysIter = getSetRecord(other).getIterator();
3071 var result = clone(O);
3072 iterateSimple(keysIter, function (it) {
3073 add(result, it);
3074 });
3075 return result;
3076 };
3077
3078
3079 /***/ }),
3080
3081 /***/ 6119:
3082 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3083
3084
3085 var shared = __webpack_require__(5745);
3086 var uid = __webpack_require__(3392);
3087
3088 var keys = shared('keys');
3089
3090 module.exports = function (key) {
3091 return keys[key] || (keys[key] = uid(key));
3092 };
3093
3094
3095 /***/ }),
3096
3097 /***/ 7629:
3098 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3099
3100
3101 var IS_PURE = __webpack_require__(6395);
3102 var globalThis = __webpack_require__(4475);
3103 var defineGlobalProperty = __webpack_require__(9433);
3104
3105 var SHARED = '__core-js_shared__';
3106 var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
3107
3108 (store.versions || (store.versions = [])).push({
3109 version: '3.37.1',
3110 mode: IS_PURE ? 'pure' : 'global',
3111 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
3112 license: 'https://github.com/zloirock/core-js/blob/v3.37.1/LICENSE',
3113 source: 'https://github.com/zloirock/core-js'
3114 });
3115
3116
3117 /***/ }),
3118
3119 /***/ 5745:
3120 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3121
3122
3123 var store = __webpack_require__(7629);
3124
3125 module.exports = function (key, value) {
3126 return store[key] || (store[key] = value || {});
3127 };
3128
3129
3130 /***/ }),
3131
3132 /***/ 1548:
3133 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3134
3135
3136 var global = __webpack_require__(4475);
3137 var fails = __webpack_require__(9039);
3138 var V8 = __webpack_require__(7388);
3139 var IS_BROWSER = __webpack_require__(7290);
3140 var IS_DENO = __webpack_require__(516);
3141 var IS_NODE = __webpack_require__(9088);
3142
3143 var structuredClone = global.structuredClone;
3144
3145 module.exports = !!structuredClone && !fails(function () {
3146 // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
3147 // https://github.com/zloirock/core-js/issues/679
3148 if ((IS_DENO && V8 > 92) || (IS_NODE && V8 > 94) || (IS_BROWSER && V8 > 97)) return false;
3149 var buffer = new ArrayBuffer(8);
3150 var clone = structuredClone(buffer, { transfer: [buffer] });
3151 return buffer.byteLength !== 0 || clone.byteLength !== 8;
3152 });
3153
3154
3155 /***/ }),
3156
3157 /***/ 4495:
3158 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3159
3160
3161 /* eslint-disable es/no-symbol -- required for testing */
3162 var V8_VERSION = __webpack_require__(7388);
3163 var fails = __webpack_require__(9039);
3164 var global = __webpack_require__(4475);
3165
3166 var $String = global.String;
3167
3168 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
3169 module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
3170 var symbol = Symbol('symbol detection');
3171 // Chrome 38 Symbol has incorrect toString conversion
3172 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
3173 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
3174 // of course, fail.
3175 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
3176 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
3177 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
3178 });
3179
3180
3181 /***/ }),
3182
3183 /***/ 5610:
3184 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3185
3186
3187 var toIntegerOrInfinity = __webpack_require__(1291);
3188
3189 var max = Math.max;
3190 var min = Math.min;
3191
3192 // Helper for a popular repeating case of the spec:
3193 // Let integer be ? ToInteger(index).
3194 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
3195 module.exports = function (index, length) {
3196 var integer = toIntegerOrInfinity(index);
3197 return integer < 0 ? max(integer + length, 0) : min(integer, length);
3198 };
3199
3200
3201 /***/ }),
3202
3203 /***/ 5854:
3204 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3205
3206
3207 var toPrimitive = __webpack_require__(2777);
3208
3209 var $TypeError = TypeError;
3210
3211 // `ToBigInt` abstract operation
3212 // https://tc39.es/ecma262/#sec-tobigint
3213 module.exports = function (argument) {
3214 var prim = toPrimitive(argument, 'number');
3215 if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint");
3216 // eslint-disable-next-line es/no-bigint -- safe
3217 return BigInt(prim);
3218 };
3219
3220
3221 /***/ }),
3222
3223 /***/ 7696:
3224 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3225
3226
3227 var toIntegerOrInfinity = __webpack_require__(1291);
3228 var toLength = __webpack_require__(8014);
3229
3230 var $RangeError = RangeError;
3231
3232 // `ToIndex` abstract operation
3233 // https://tc39.es/ecma262/#sec-toindex
3234 module.exports = function (it) {
3235 if (it === undefined) return 0;
3236 var number = toIntegerOrInfinity(it);
3237 var length = toLength(number);
3238 if (number !== length) throw new $RangeError('Wrong length or index');
3239 return length;
3240 };
3241
3242
3243 /***/ }),
3244
3245 /***/ 5397:
3246 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3247
3248
3249 // toObject with fallback for non-array-like ES3 strings
3250 var IndexedObject = __webpack_require__(7055);
3251 var requireObjectCoercible = __webpack_require__(7750);
3252
3253 module.exports = function (it) {
3254 return IndexedObject(requireObjectCoercible(it));
3255 };
3256
3257
3258 /***/ }),
3259
3260 /***/ 1291:
3261 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3262
3263
3264 var trunc = __webpack_require__(741);
3265
3266 // `ToIntegerOrInfinity` abstract operation
3267 // https://tc39.es/ecma262/#sec-tointegerorinfinity
3268 module.exports = function (argument) {
3269 var number = +argument;
3270 // eslint-disable-next-line no-self-compare -- NaN check
3271 return number !== number || number === 0 ? 0 : trunc(number);
3272 };
3273
3274
3275 /***/ }),
3276
3277 /***/ 8014:
3278 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3279
3280
3281 var toIntegerOrInfinity = __webpack_require__(1291);
3282
3283 var min = Math.min;
3284
3285 // `ToLength` abstract operation
3286 // https://tc39.es/ecma262/#sec-tolength
3287 module.exports = function (argument) {
3288 var len = toIntegerOrInfinity(argument);
3289 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
3290 };
3291
3292
3293 /***/ }),
3294
3295 /***/ 8981:
3296 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3297
3298
3299 var requireObjectCoercible = __webpack_require__(7750);
3300
3301 var $Object = Object;
3302
3303 // `ToObject` abstract operation
3304 // https://tc39.es/ecma262/#sec-toobject
3305 module.exports = function (argument) {
3306 return $Object(requireObjectCoercible(argument));
3307 };
3308
3309
3310 /***/ }),
3311
3312 /***/ 2777:
3313 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3314
3315
3316 var call = __webpack_require__(9565);
3317 var isObject = __webpack_require__(34);
3318 var isSymbol = __webpack_require__(757);
3319 var getMethod = __webpack_require__(5966);
3320 var ordinaryToPrimitive = __webpack_require__(4270);
3321 var wellKnownSymbol = __webpack_require__(8227);
3322
3323 var $TypeError = TypeError;
3324 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
3325
3326 // `ToPrimitive` abstract operation
3327 // https://tc39.es/ecma262/#sec-toprimitive
3328 module.exports = function (input, pref) {
3329 if (!isObject(input) || isSymbol(input)) return input;
3330 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
3331 var result;
3332 if (exoticToPrim) {
3333 if (pref === undefined) pref = 'default';
3334 result = call(exoticToPrim, input, pref);
3335 if (!isObject(result) || isSymbol(result)) return result;
3336 throw new $TypeError("Can't convert object to primitive value");
3337 }
3338 if (pref === undefined) pref = 'number';
3339 return ordinaryToPrimitive(input, pref);
3340 };
3341
3342
3343 /***/ }),
3344
3345 /***/ 6969:
3346 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3347
3348
3349 var toPrimitive = __webpack_require__(2777);
3350 var isSymbol = __webpack_require__(757);
3351
3352 // `ToPropertyKey` abstract operation
3353 // https://tc39.es/ecma262/#sec-topropertykey
3354 module.exports = function (argument) {
3355 var key = toPrimitive(argument, 'string');
3356 return isSymbol(key) ? key : key + '';
3357 };
3358
3359
3360 /***/ }),
3361
3362 /***/ 2140:
3363 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3364
3365
3366 var wellKnownSymbol = __webpack_require__(8227);
3367
3368 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
3369 var test = {};
3370
3371 test[TO_STRING_TAG] = 'z';
3372
3373 module.exports = String(test) === '[object z]';
3374
3375
3376 /***/ }),
3377
3378 /***/ 655:
3379 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3380
3381
3382 var classof = __webpack_require__(6955);
3383
3384 var $String = String;
3385
3386 module.exports = function (argument) {
3387 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
3388 return $String(argument);
3389 };
3390
3391
3392 /***/ }),
3393
3394 /***/ 9714:
3395 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3396
3397
3398 var IS_NODE = __webpack_require__(9088);
3399
3400 module.exports = function (name) {
3401 try {
3402 // eslint-disable-next-line no-new-func -- safe
3403 if (IS_NODE) return Function('return require("' + name + '")')();
3404 } catch (error) { /* empty */ }
3405 };
3406
3407
3408 /***/ }),
3409
3410 /***/ 6823:
3411 /***/ ((module) => {
3412
3413
3414 var $String = String;
3415
3416 module.exports = function (argument) {
3417 try {
3418 return $String(argument);
3419 } catch (error) {
3420 return 'Object';
3421 }
3422 };
3423
3424
3425 /***/ }),
3426
3427 /***/ 3392:
3428 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3429
3430
3431 var uncurryThis = __webpack_require__(9504);
3432
3433 var id = 0;
3434 var postfix = Math.random();
3435 var toString = uncurryThis(1.0.toString);
3436
3437 module.exports = function (key) {
3438 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
3439 };
3440
3441
3442 /***/ }),
3443
3444 /***/ 7040:
3445 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3446
3447
3448 /* eslint-disable es/no-symbol -- required for testing */
3449 var NATIVE_SYMBOL = __webpack_require__(4495);
3450
3451 module.exports = NATIVE_SYMBOL
3452 && !Symbol.sham
3453 && typeof Symbol.iterator == 'symbol';
3454
3455
3456 /***/ }),
3457
3458 /***/ 8686:
3459 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3460
3461
3462 var DESCRIPTORS = __webpack_require__(3724);
3463 var fails = __webpack_require__(9039);
3464
3465 // V8 ~ Chrome 36-
3466 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
3467 module.exports = DESCRIPTORS && fails(function () {
3468 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
3469 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
3470 value: 42,
3471 writable: false
3472 }).prototype !== 42;
3473 });
3474
3475
3476 /***/ }),
3477
3478 /***/ 2812:
3479 /***/ ((module) => {
3480
3481
3482 var $TypeError = TypeError;
3483
3484 module.exports = function (passed, required) {
3485 if (passed < required) throw new $TypeError('Not enough arguments');
3486 return passed;
3487 };
3488
3489
3490 /***/ }),
3491
3492 /***/ 8622:
3493 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3494
3495
3496 var global = __webpack_require__(4475);
3497 var isCallable = __webpack_require__(4901);
3498
3499 var WeakMap = global.WeakMap;
3500
3501 module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));
3502
3503
3504 /***/ }),
3505
3506 /***/ 8227:
3507 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
3508
3509
3510 var global = __webpack_require__(4475);
3511 var shared = __webpack_require__(5745);
3512 var hasOwn = __webpack_require__(9297);
3513 var uid = __webpack_require__(3392);
3514 var NATIVE_SYMBOL = __webpack_require__(4495);
3515 var USE_SYMBOL_AS_UID = __webpack_require__(7040);
3516
3517 var Symbol = global.Symbol;
3518 var WellKnownSymbolsStore = shared('wks');
3519 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
3520
3521 module.exports = function (name) {
3522 if (!hasOwn(WellKnownSymbolsStore, name)) {
3523 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
3524 ? Symbol[name]
3525 : createWellKnownSymbol('Symbol.' + name);
3526 } return WellKnownSymbolsStore[name];
3527 };
3528
3529
3530 /***/ }),
3531
3532 /***/ 6573:
3533 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3534
3535
3536 var DESCRIPTORS = __webpack_require__(3724);
3537 var defineBuiltInAccessor = __webpack_require__(2106);
3538 var isDetached = __webpack_require__(3238);
3539
3540 var ArrayBufferPrototype = ArrayBuffer.prototype;
3541
3542 if (DESCRIPTORS && !('detached' in ArrayBufferPrototype)) {
3543 defineBuiltInAccessor(ArrayBufferPrototype, 'detached', {
3544 configurable: true,
3545 get: function detached() {
3546 return isDetached(this);
3547 }
3548 });
3549 }
3550
3551
3552 /***/ }),
3553
3554 /***/ 7936:
3555 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3556
3557
3558 var $ = __webpack_require__(6518);
3559 var $transfer = __webpack_require__(5636);
3560
3561 // `ArrayBuffer.prototype.transferToFixedLength` method
3562 // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
3563 if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
3564 transferToFixedLength: function transferToFixedLength() {
3565 return $transfer(this, arguments.length ? arguments[0] : undefined, false);
3566 }
3567 });
3568
3569
3570 /***/ }),
3571
3572 /***/ 8100:
3573 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3574
3575
3576 var $ = __webpack_require__(6518);
3577 var $transfer = __webpack_require__(5636);
3578
3579 // `ArrayBuffer.prototype.transfer` method
3580 // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer
3581 if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
3582 transfer: function transfer() {
3583 return $transfer(this, arguments.length ? arguments[0] : undefined, true);
3584 }
3585 });
3586
3587
3588 /***/ }),
3589
3590 /***/ 4114:
3591 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3592
3593
3594 var $ = __webpack_require__(6518);
3595 var toObject = __webpack_require__(8981);
3596 var lengthOfArrayLike = __webpack_require__(6198);
3597 var setArrayLength = __webpack_require__(4527);
3598 var doesNotExceedSafeInteger = __webpack_require__(6837);
3599 var fails = __webpack_require__(9039);
3600
3601 var INCORRECT_TO_LENGTH = fails(function () {
3602 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
3603 });
3604
3605 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
3606 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
3607 var properErrorOnNonWritableLength = function () {
3608 try {
3609 // eslint-disable-next-line es/no-object-defineproperty -- safe
3610 Object.defineProperty([], 'length', { writable: false }).push();
3611 } catch (error) {
3612 return error instanceof TypeError;
3613 }
3614 };
3615
3616 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
3617
3618 // `Array.prototype.push` method
3619 // https://tc39.es/ecma262/#sec-array.prototype.push
3620 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
3621 // eslint-disable-next-line no-unused-vars -- required for `.length`
3622 push: function push(item) {
3623 var O = toObject(this);
3624 var len = lengthOfArrayLike(O);
3625 var argCount = arguments.length;
3626 doesNotExceedSafeInteger(len + argCount);
3627 for (var i = 0; i < argCount; i++) {
3628 O[len] = arguments[i];
3629 len++;
3630 }
3631 setArrayLength(O, len);
3632 return len;
3633 }
3634 });
3635
3636
3637 /***/ }),
3638
3639 /***/ 4628:
3640 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3641
3642
3643 var $ = __webpack_require__(6518);
3644 var newPromiseCapabilityModule = __webpack_require__(6043);
3645
3646 // `Promise.withResolvers` method
3647 // https://github.com/tc39/proposal-promise-with-resolvers
3648 $({ target: 'Promise', stat: true }, {
3649 withResolvers: function withResolvers() {
3650 var promiseCapability = newPromiseCapabilityModule.f(this);
3651 return {
3652 promise: promiseCapability.promise,
3653 resolve: promiseCapability.resolve,
3654 reject: promiseCapability.reject
3655 };
3656 }
3657 });
3658
3659
3660 /***/ }),
3661
3662 /***/ 7642:
3663 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3664
3665
3666 var $ = __webpack_require__(6518);
3667 var difference = __webpack_require__(3440);
3668 var setMethodAcceptSetLike = __webpack_require__(4916);
3669
3670 // `Set.prototype.difference` method
3671 // https://github.com/tc39/proposal-set-methods
3672 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
3673 difference: difference
3674 });
3675
3676
3677 /***/ }),
3678
3679 /***/ 8004:
3680 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3681
3682
3683 var $ = __webpack_require__(6518);
3684 var fails = __webpack_require__(9039);
3685 var intersection = __webpack_require__(8750);
3686 var setMethodAcceptSetLike = __webpack_require__(4916);
3687
3688 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
3689 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
3690 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
3691 });
3692
3693 // `Set.prototype.intersection` method
3694 // https://github.com/tc39/proposal-set-methods
3695 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
3696 intersection: intersection
3697 });
3698
3699
3700 /***/ }),
3701
3702 /***/ 3853:
3703 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3704
3705
3706 var $ = __webpack_require__(6518);
3707 var isDisjointFrom = __webpack_require__(4449);
3708 var setMethodAcceptSetLike = __webpack_require__(4916);
3709
3710 // `Set.prototype.isDisjointFrom` method
3711 // https://github.com/tc39/proposal-set-methods
3712 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
3713 isDisjointFrom: isDisjointFrom
3714 });
3715
3716
3717 /***/ }),
3718
3719 /***/ 5876:
3720 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3721
3722
3723 var $ = __webpack_require__(6518);
3724 var isSubsetOf = __webpack_require__(3838);
3725 var setMethodAcceptSetLike = __webpack_require__(4916);
3726
3727 // `Set.prototype.isSubsetOf` method
3728 // https://github.com/tc39/proposal-set-methods
3729 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
3730 isSubsetOf: isSubsetOf
3731 });
3732
3733
3734 /***/ }),
3735
3736 /***/ 2475:
3737 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3738
3739
3740 var $ = __webpack_require__(6518);
3741 var isSupersetOf = __webpack_require__(8527);
3742 var setMethodAcceptSetLike = __webpack_require__(4916);
3743
3744 // `Set.prototype.isSupersetOf` method
3745 // https://github.com/tc39/proposal-set-methods
3746 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
3747 isSupersetOf: isSupersetOf
3748 });
3749
3750
3751 /***/ }),
3752
3753 /***/ 5024:
3754 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3755
3756
3757 var $ = __webpack_require__(6518);
3758 var symmetricDifference = __webpack_require__(3650);
3759 var setMethodAcceptSetLike = __webpack_require__(4916);
3760
3761 // `Set.prototype.symmetricDifference` method
3762 // https://github.com/tc39/proposal-set-methods
3763 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
3764 symmetricDifference: symmetricDifference
3765 });
3766
3767
3768 /***/ }),
3769
3770 /***/ 1698:
3771 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3772
3773
3774 var $ = __webpack_require__(6518);
3775 var union = __webpack_require__(4204);
3776 var setMethodAcceptSetLike = __webpack_require__(4916);
3777
3778 // `Set.prototype.union` method
3779 // https://github.com/tc39/proposal-set-methods
3780 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
3781 union: union
3782 });
3783
3784
3785 /***/ }),
3786
3787 /***/ 7467:
3788 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3789
3790
3791 var arrayToReversed = __webpack_require__(7628);
3792 var ArrayBufferViewCore = __webpack_require__(4644);
3793
3794 var aTypedArray = ArrayBufferViewCore.aTypedArray;
3795 var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
3796 var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
3797
3798 // `%TypedArray%.prototype.toReversed` method
3799 // https://tc39.es/ecma262/#sec-%typedarray%.prototype.toreversed
3800 exportTypedArrayMethod('toReversed', function toReversed() {
3801 return arrayToReversed(aTypedArray(this), getTypedArrayConstructor(this));
3802 });
3803
3804
3805 /***/ }),
3806
3807 /***/ 4732:
3808 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3809
3810
3811 var ArrayBufferViewCore = __webpack_require__(4644);
3812 var uncurryThis = __webpack_require__(9504);
3813 var aCallable = __webpack_require__(9306);
3814 var arrayFromConstructorAndList = __webpack_require__(5370);
3815
3816 var aTypedArray = ArrayBufferViewCore.aTypedArray;
3817 var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
3818 var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
3819 var sort = uncurryThis(ArrayBufferViewCore.TypedArrayPrototype.sort);
3820
3821 // `%TypedArray%.prototype.toSorted` method
3822 // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tosorted
3823 exportTypedArrayMethod('toSorted', function toSorted(compareFn) {
3824 if (compareFn !== undefined) aCallable(compareFn);
3825 var O = aTypedArray(this);
3826 var A = arrayFromConstructorAndList(getTypedArrayConstructor(O), O);
3827 return sort(A, compareFn);
3828 });
3829
3830
3831 /***/ }),
3832
3833 /***/ 9577:
3834 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3835
3836
3837 var arrayWith = __webpack_require__(9928);
3838 var ArrayBufferViewCore = __webpack_require__(4644);
3839 var isBigIntArray = __webpack_require__(1108);
3840 var toIntegerOrInfinity = __webpack_require__(1291);
3841 var toBigInt = __webpack_require__(5854);
3842
3843 var aTypedArray = ArrayBufferViewCore.aTypedArray;
3844 var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
3845 var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
3846
3847 var PROPER_ORDER = !!function () {
3848 try {
3849 // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing
3850 new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } });
3851 } catch (error) {
3852 // some early implementations, like WebKit, does not follow the final semantic
3853 // https://github.com/tc39/proposal-change-array-by-copy/pull/86
3854 return error === 8;
3855 }
3856 }();
3857
3858 // `%TypedArray%.prototype.with` method
3859 // https://tc39.es/ecma262/#sec-%typedarray%.prototype.with
3860 exportTypedArrayMethod('with', { 'with': function (index, value) {
3861 var O = aTypedArray(this);
3862 var relativeIndex = toIntegerOrInfinity(index);
3863 var actualValue = isBigIntArray(O) ? toBigInt(value) : +value;
3864 return arrayWith(O, getTypedArrayConstructor(O), relativeIndex, actualValue);
3865 } }['with'], !PROPER_ORDER);
3866
3867
3868 /***/ }),
3869
3870 /***/ 8992:
3871 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3872
3873
3874 var $ = __webpack_require__(6518);
3875 var global = __webpack_require__(4475);
3876 var anInstance = __webpack_require__(679);
3877 var anObject = __webpack_require__(8551);
3878 var isCallable = __webpack_require__(4901);
3879 var getPrototypeOf = __webpack_require__(2787);
3880 var defineBuiltInAccessor = __webpack_require__(2106);
3881 var createProperty = __webpack_require__(4659);
3882 var fails = __webpack_require__(9039);
3883 var hasOwn = __webpack_require__(9297);
3884 var wellKnownSymbol = __webpack_require__(8227);
3885 var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
3886 var DESCRIPTORS = __webpack_require__(3724);
3887 var IS_PURE = __webpack_require__(6395);
3888
3889 var CONSTRUCTOR = 'constructor';
3890 var ITERATOR = 'Iterator';
3891 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
3892
3893 var $TypeError = TypeError;
3894 var NativeIterator = global[ITERATOR];
3895
3896 // FF56- have non-standard global helper `Iterator`
3897 var FORCED = IS_PURE
3898 || !isCallable(NativeIterator)
3899 || NativeIterator.prototype !== IteratorPrototype
3900 // FF44- non-standard `Iterator` passes previous tests
3901 || !fails(function () { NativeIterator({}); });
3902
3903 var IteratorConstructor = function Iterator() {
3904 anInstance(this, IteratorPrototype);
3905 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
3906 };
3907
3908 var defineIteratorPrototypeAccessor = function (key, value) {
3909 if (DESCRIPTORS) {
3910 defineBuiltInAccessor(IteratorPrototype, key, {
3911 configurable: true,
3912 get: function () {
3913 return value;
3914 },
3915 set: function (replacement) {
3916 anObject(this);
3917 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
3918 if (hasOwn(this, key)) this[key] = replacement;
3919 else createProperty(this, key, replacement);
3920 }
3921 });
3922 } else IteratorPrototype[key] = value;
3923 };
3924
3925 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
3926
3927 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
3928 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
3929 }
3930
3931 IteratorConstructor.prototype = IteratorPrototype;
3932
3933 // `Iterator` constructor
3934 // https://github.com/tc39/proposal-iterator-helpers
3935 $({ global: true, constructor: true, forced: FORCED }, {
3936 Iterator: IteratorConstructor
3937 });
3938
3939
3940 /***/ }),
3941
3942 /***/ 3215:
3943 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3944
3945
3946 var $ = __webpack_require__(6518);
3947 var iterate = __webpack_require__(2652);
3948 var aCallable = __webpack_require__(9306);
3949 var anObject = __webpack_require__(8551);
3950 var getIteratorDirect = __webpack_require__(1767);
3951
3952 // `Iterator.prototype.every` method
3953 // https://github.com/tc39/proposal-iterator-helpers
3954 $({ target: 'Iterator', proto: true, real: true }, {
3955 every: function every(predicate) {
3956 anObject(this);
3957 aCallable(predicate);
3958 var record = getIteratorDirect(this);
3959 var counter = 0;
3960 return !iterate(record, function (value, stop) {
3961 if (!predicate(value, counter++)) return stop();
3962 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
3963 }
3964 });
3965
3966
3967 /***/ }),
3968
3969 /***/ 4520:
3970 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
3971
3972
3973 var $ = __webpack_require__(6518);
3974 var call = __webpack_require__(9565);
3975 var aCallable = __webpack_require__(9306);
3976 var anObject = __webpack_require__(8551);
3977 var getIteratorDirect = __webpack_require__(1767);
3978 var createIteratorProxy = __webpack_require__(9462);
3979 var callWithSafeIterationClosing = __webpack_require__(6319);
3980 var IS_PURE = __webpack_require__(6395);
3981
3982 var IteratorProxy = createIteratorProxy(function () {
3983 var iterator = this.iterator;
3984 var predicate = this.predicate;
3985 var next = this.next;
3986 var result, done, value;
3987 while (true) {
3988 result = anObject(call(next, iterator));
3989 done = this.done = !!result.done;
3990 if (done) return;
3991 value = result.value;
3992 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
3993 }
3994 });
3995
3996 // `Iterator.prototype.filter` method
3997 // https://github.com/tc39/proposal-iterator-helpers
3998 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
3999 filter: function filter(predicate) {
4000 anObject(this);
4001 aCallable(predicate);
4002 return new IteratorProxy(getIteratorDirect(this), {
4003 predicate: predicate
4004 });
4005 }
4006 });
4007
4008
4009 /***/ }),
4010
4011 /***/ 670:
4012 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4013
4014
4015 var $ = __webpack_require__(6518);
4016 var call = __webpack_require__(9565);
4017 var aCallable = __webpack_require__(9306);
4018 var anObject = __webpack_require__(8551);
4019 var getIteratorDirect = __webpack_require__(1767);
4020 var getIteratorFlattenable = __webpack_require__(8646);
4021 var createIteratorProxy = __webpack_require__(9462);
4022 var iteratorClose = __webpack_require__(9539);
4023 var IS_PURE = __webpack_require__(6395);
4024
4025 var IteratorProxy = createIteratorProxy(function () {
4026 var iterator = this.iterator;
4027 var mapper = this.mapper;
4028 var result, inner;
4029
4030 while (true) {
4031 if (inner = this.inner) try {
4032 result = anObject(call(inner.next, inner.iterator));
4033 if (!result.done) return result.value;
4034 this.inner = null;
4035 } catch (error) { iteratorClose(iterator, 'throw', error); }
4036
4037 result = anObject(call(this.next, iterator));
4038
4039 if (this.done = !!result.done) return;
4040
4041 try {
4042 this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false);
4043 } catch (error) { iteratorClose(iterator, 'throw', error); }
4044 }
4045 });
4046
4047 // `Iterator.prototype.flatMap` method
4048 // https://github.com/tc39/proposal-iterator-helpers
4049 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
4050 flatMap: function flatMap(mapper) {
4051 anObject(this);
4052 aCallable(mapper);
4053 return new IteratorProxy(getIteratorDirect(this), {
4054 mapper: mapper,
4055 inner: null
4056 });
4057 }
4058 });
4059
4060
4061 /***/ }),
4062
4063 /***/ 1454:
4064 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4065
4066
4067 var $ = __webpack_require__(6518);
4068 var map = __webpack_require__(713);
4069 var IS_PURE = __webpack_require__(6395);
4070
4071 // `Iterator.prototype.map` method
4072 // https://github.com/tc39/proposal-iterator-helpers
4073 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
4074 map: map
4075 });
4076
4077
4078 /***/ }),
4079
4080 /***/ 7550:
4081 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4082
4083
4084 var $ = __webpack_require__(6518);
4085 var iterate = __webpack_require__(2652);
4086 var aCallable = __webpack_require__(9306);
4087 var anObject = __webpack_require__(8551);
4088 var getIteratorDirect = __webpack_require__(1767);
4089
4090 // `Iterator.prototype.some` method
4091 // https://github.com/tc39/proposal-iterator-helpers
4092 $({ target: 'Iterator', proto: true, real: true }, {
4093 some: function some(predicate) {
4094 anObject(this);
4095 aCallable(predicate);
4096 var record = getIteratorDirect(this);
4097 var counter = 0;
4098 return iterate(record, function (value, stop) {
4099 if (predicate(value, counter++)) return stop();
4100 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
4101 }
4102 });
4103
4104
4105 /***/ }),
4106
4107 /***/ 8335:
4108 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4109
4110
4111 var $ = __webpack_require__(6518);
4112 var DESCRIPTORS = __webpack_require__(3724);
4113 var global = __webpack_require__(4475);
4114 var getBuiltIn = __webpack_require__(7751);
4115 var uncurryThis = __webpack_require__(9504);
4116 var call = __webpack_require__(9565);
4117 var isCallable = __webpack_require__(4901);
4118 var isObject = __webpack_require__(34);
4119 var isArray = __webpack_require__(4376);
4120 var hasOwn = __webpack_require__(9297);
4121 var toString = __webpack_require__(655);
4122 var lengthOfArrayLike = __webpack_require__(6198);
4123 var createProperty = __webpack_require__(4659);
4124 var fails = __webpack_require__(9039);
4125 var parseJSONString = __webpack_require__(8235);
4126 var NATIVE_SYMBOL = __webpack_require__(4495);
4127
4128 var JSON = global.JSON;
4129 var Number = global.Number;
4130 var SyntaxError = global.SyntaxError;
4131 var nativeParse = JSON && JSON.parse;
4132 var enumerableOwnProperties = getBuiltIn('Object', 'keys');
4133 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4134 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
4135 var at = uncurryThis(''.charAt);
4136 var slice = uncurryThis(''.slice);
4137 var exec = uncurryThis(/./.exec);
4138 var push = uncurryThis([].push);
4139
4140 var IS_DIGIT = /^\d$/;
4141 var IS_NON_ZERO_DIGIT = /^[1-9]$/;
4142 var IS_NUMBER_START = /^(?:-|\d)$/;
4143 var IS_WHITESPACE = /^[\t\n\r ]$/;
4144
4145 var PRIMITIVE = 0;
4146 var OBJECT = 1;
4147
4148 var $parse = function (source, reviver) {
4149 source = toString(source);
4150 var context = new Context(source, 0, '');
4151 var root = context.parse();
4152 var value = root.value;
4153 var endIndex = context.skip(IS_WHITESPACE, root.end);
4154 if (endIndex < source.length) {
4155 throw new SyntaxError('Unexpected extra character: "' + at(source, endIndex) + '" after the parsed data at: ' + endIndex);
4156 }
4157 return isCallable(reviver) ? internalize({ '': value }, '', reviver, root) : value;
4158 };
4159
4160 var internalize = function (holder, name, reviver, node) {
4161 var val = holder[name];
4162 var unmodified = node && val === node.value;
4163 var context = unmodified && typeof node.source == 'string' ? { source: node.source } : {};
4164 var elementRecordsLen, keys, len, i, P;
4165 if (isObject(val)) {
4166 var nodeIsArray = isArray(val);
4167 var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {};
4168 if (nodeIsArray) {
4169 elementRecordsLen = nodes.length;
4170 len = lengthOfArrayLike(val);
4171 for (i = 0; i < len; i++) {
4172 internalizeProperty(val, i, internalize(val, '' + i, reviver, i < elementRecordsLen ? nodes[i] : undefined));
4173 }
4174 } else {
4175 keys = enumerableOwnProperties(val);
4176 len = lengthOfArrayLike(keys);
4177 for (i = 0; i < len; i++) {
4178 P = keys[i];
4179 internalizeProperty(val, P, internalize(val, P, reviver, hasOwn(nodes, P) ? nodes[P] : undefined));
4180 }
4181 }
4182 }
4183 return call(reviver, holder, name, val, context);
4184 };
4185
4186 var internalizeProperty = function (object, key, value) {
4187 if (DESCRIPTORS) {
4188 var descriptor = getOwnPropertyDescriptor(object, key);
4189 if (descriptor && !descriptor.configurable) return;
4190 }
4191 if (value === undefined) delete object[key];
4192 else createProperty(object, key, value);
4193 };
4194
4195 var Node = function (value, end, source, nodes) {
4196 this.value = value;
4197 this.end = end;
4198 this.source = source;
4199 this.nodes = nodes;
4200 };
4201
4202 var Context = function (source, index) {
4203 this.source = source;
4204 this.index = index;
4205 };
4206
4207 // https://www.json.org/json-en.html
4208 Context.prototype = {
4209 fork: function (nextIndex) {
4210 return new Context(this.source, nextIndex);
4211 },
4212 parse: function () {
4213 var source = this.source;
4214 var i = this.skip(IS_WHITESPACE, this.index);
4215 var fork = this.fork(i);
4216 var chr = at(source, i);
4217 if (exec(IS_NUMBER_START, chr)) return fork.number();
4218 switch (chr) {
4219 case '{':
4220 return fork.object();
4221 case '[':
4222 return fork.array();
4223 case '"':
4224 return fork.string();
4225 case 't':
4226 return fork.keyword(true);
4227 case 'f':
4228 return fork.keyword(false);
4229 case 'n':
4230 return fork.keyword(null);
4231 } throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
4232 },
4233 node: function (type, value, start, end, nodes) {
4234 return new Node(value, end, type ? null : slice(this.source, start, end), nodes);
4235 },
4236 object: function () {
4237 var source = this.source;
4238 var i = this.index + 1;
4239 var expectKeypair = false;
4240 var object = {};
4241 var nodes = {};
4242 while (i < source.length) {
4243 i = this.until(['"', '}'], i);
4244 if (at(source, i) === '}' && !expectKeypair) {
4245 i++;
4246 break;
4247 }
4248 // Parsing the key
4249 var result = this.fork(i).string();
4250 var key = result.value;
4251 i = result.end;
4252 i = this.until([':'], i) + 1;
4253 // Parsing value
4254 i = this.skip(IS_WHITESPACE, i);
4255 result = this.fork(i).parse();
4256 createProperty(nodes, key, result);
4257 createProperty(object, key, result.value);
4258 i = this.until([',', '}'], result.end);
4259 var chr = at(source, i);
4260 if (chr === ',') {
4261 expectKeypair = true;
4262 i++;
4263 } else if (chr === '}') {
4264 i++;
4265 break;
4266 }
4267 }
4268 return this.node(OBJECT, object, this.index, i, nodes);
4269 },
4270 array: function () {
4271 var source = this.source;
4272 var i = this.index + 1;
4273 var expectElement = false;
4274 var array = [];
4275 var nodes = [];
4276 while (i < source.length) {
4277 i = this.skip(IS_WHITESPACE, i);
4278 if (at(source, i) === ']' && !expectElement) {
4279 i++;
4280 break;
4281 }
4282 var result = this.fork(i).parse();
4283 push(nodes, result);
4284 push(array, result.value);
4285 i = this.until([',', ']'], result.end);
4286 if (at(source, i) === ',') {
4287 expectElement = true;
4288 i++;
4289 } else if (at(source, i) === ']') {
4290 i++;
4291 break;
4292 }
4293 }
4294 return this.node(OBJECT, array, this.index, i, nodes);
4295 },
4296 string: function () {
4297 var index = this.index;
4298 var parsed = parseJSONString(this.source, this.index + 1);
4299 return this.node(PRIMITIVE, parsed.value, index, parsed.end);
4300 },
4301 number: function () {
4302 var source = this.source;
4303 var startIndex = this.index;
4304 var i = startIndex;
4305 if (at(source, i) === '-') i++;
4306 if (at(source, i) === '0') i++;
4307 else if (exec(IS_NON_ZERO_DIGIT, at(source, i))) i = this.skip(IS_DIGIT, ++i);
4308 else throw new SyntaxError('Failed to parse number at: ' + i);
4309 if (at(source, i) === '.') i = this.skip(IS_DIGIT, ++i);
4310 if (at(source, i) === 'e' || at(source, i) === 'E') {
4311 i++;
4312 if (at(source, i) === '+' || at(source, i) === '-') i++;
4313 var exponentStartIndex = i;
4314 i = this.skip(IS_DIGIT, i);
4315 if (exponentStartIndex === i) throw new SyntaxError("Failed to parse number's exponent value at: " + i);
4316 }
4317 return this.node(PRIMITIVE, Number(slice(source, startIndex, i)), startIndex, i);
4318 },
4319 keyword: function (value) {
4320 var keyword = '' + value;
4321 var index = this.index;
4322 var endIndex = index + keyword.length;
4323 if (slice(this.source, index, endIndex) !== keyword) throw new SyntaxError('Failed to parse value at: ' + index);
4324 return this.node(PRIMITIVE, value, index, endIndex);
4325 },
4326 skip: function (regex, i) {
4327 var source = this.source;
4328 for (; i < source.length; i++) if (!exec(regex, at(source, i))) break;
4329 return i;
4330 },
4331 until: function (array, i) {
4332 i = this.skip(IS_WHITESPACE, i);
4333 var chr = at(this.source, i);
4334 for (var j = 0; j < array.length; j++) if (array[j] === chr) return i;
4335 throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
4336 }
4337 };
4338
4339 var NO_SOURCE_SUPPORT = fails(function () {
4340 var unsafeInt = '9007199254740993';
4341 var source;
4342 nativeParse(unsafeInt, function (key, value, context) {
4343 source = context.source;
4344 });
4345 return source !== unsafeInt;
4346 });
4347
4348 var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails(function () {
4349 // Safari 9 bug
4350 return 1 / nativeParse('-0 \t') !== -Infinity;
4351 });
4352
4353 // `JSON.parse` method
4354 // https://tc39.es/ecma262/#sec-json.parse
4355 // https://github.com/tc39/proposal-json-parse-with-source
4356 $({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, {
4357 parse: function parse(text, reviver) {
4358 return PROPER_BASE_PARSE && !isCallable(reviver) ? nativeParse(text) : $parse(text, reviver);
4359 }
4360 });
4361
4362
4363 /***/ }),
4364
4365 /***/ 3375:
4366 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4367
4368
4369 // TODO: Remove from `core-js@4`
4370 __webpack_require__(7642);
4371
4372
4373 /***/ }),
4374
4375 /***/ 9225:
4376 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4377
4378
4379 // TODO: Remove from `core-js@4`
4380 __webpack_require__(8004);
4381
4382
4383 /***/ }),
4384
4385 /***/ 3972:
4386 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4387
4388
4389 // TODO: Remove from `core-js@4`
4390 __webpack_require__(3853);
4391
4392
4393 /***/ }),
4394
4395 /***/ 9209:
4396 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4397
4398
4399 // TODO: Remove from `core-js@4`
4400 __webpack_require__(5876);
4401
4402
4403 /***/ }),
4404
4405 /***/ 5714:
4406 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4407
4408
4409 // TODO: Remove from `core-js@4`
4410 __webpack_require__(2475);
4411
4412
4413 /***/ }),
4414
4415 /***/ 7561:
4416 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4417
4418
4419 // TODO: Remove from `core-js@4`
4420 __webpack_require__(5024);
4421
4422
4423 /***/ }),
4424
4425 /***/ 6197:
4426 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4427
4428
4429 // TODO: Remove from `core-js@4`
4430 __webpack_require__(1698);
4431
4432
4433 /***/ }),
4434
4435 /***/ 4979:
4436 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4437
4438
4439 var $ = __webpack_require__(6518);
4440 var global = __webpack_require__(4475);
4441 var getBuiltIn = __webpack_require__(7751);
4442 var createPropertyDescriptor = __webpack_require__(6980);
4443 var defineProperty = (__webpack_require__(4913).f);
4444 var hasOwn = __webpack_require__(9297);
4445 var anInstance = __webpack_require__(679);
4446 var inheritIfRequired = __webpack_require__(3167);
4447 var normalizeStringArgument = __webpack_require__(2603);
4448 var DOMExceptionConstants = __webpack_require__(5002);
4449 var clearErrorStack = __webpack_require__(6193);
4450 var DESCRIPTORS = __webpack_require__(3724);
4451 var IS_PURE = __webpack_require__(6395);
4452
4453 var DOM_EXCEPTION = 'DOMException';
4454 var Error = getBuiltIn('Error');
4455 var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
4456
4457 var $DOMException = function DOMException() {
4458 anInstance(this, DOMExceptionPrototype);
4459 var argumentsLength = arguments.length;
4460 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
4461 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
4462 var that = new NativeDOMException(message, name);
4463 var error = new Error(message);
4464 error.name = DOM_EXCEPTION;
4465 defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
4466 inheritIfRequired(that, this, $DOMException);
4467 return that;
4468 };
4469
4470 var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
4471
4472 var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
4473 var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
4474
4475 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4476 var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(global, DOM_EXCEPTION);
4477
4478 // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
4479 // https://github.com/Jarred-Sumner/bun/issues/399
4480 var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
4481
4482 var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
4483
4484 // `DOMException` constructor patch for `.stack` where it's required
4485 // https://webidl.spec.whatwg.org/#es-DOMException-specialness
4486 $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
4487 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
4488 });
4489
4490 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
4491 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
4492
4493 if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
4494 if (!IS_PURE) {
4495 defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
4496 }
4497
4498 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
4499 var constant = DOMExceptionConstants[key];
4500 var constantName = constant.s;
4501 if (!hasOwn(PolyfilledDOMException, constantName)) {
4502 defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
4503 }
4504 }
4505 }
4506
4507
4508 /***/ }),
4509
4510 /***/ 4603:
4511 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4512
4513
4514 var defineBuiltIn = __webpack_require__(6840);
4515 var uncurryThis = __webpack_require__(9504);
4516 var toString = __webpack_require__(655);
4517 var validateArgumentsLength = __webpack_require__(2812);
4518
4519 var $URLSearchParams = URLSearchParams;
4520 var URLSearchParamsPrototype = $URLSearchParams.prototype;
4521 var append = uncurryThis(URLSearchParamsPrototype.append);
4522 var $delete = uncurryThis(URLSearchParamsPrototype['delete']);
4523 var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
4524 var push = uncurryThis([].push);
4525 var params = new $URLSearchParams('a=1&a=2&b=3');
4526
4527 params['delete']('a', 1);
4528 // `undefined` case is a Chromium 117 bug
4529 // https://bugs.chromium.org/p/v8/issues/detail?id=14222
4530 params['delete']('b', undefined);
4531
4532 if (params + '' !== 'a=2') {
4533 defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) {
4534 var length = arguments.length;
4535 var $value = length < 2 ? undefined : arguments[1];
4536 if (length && $value === undefined) return $delete(this, name);
4537 var entries = [];
4538 forEach(this, function (v, k) { // also validates `this`
4539 push(entries, { key: k, value: v });
4540 });
4541 validateArgumentsLength(length, 1);
4542 var key = toString(name);
4543 var value = toString($value);
4544 var index = 0;
4545 var dindex = 0;
4546 var found = false;
4547 var entriesLength = entries.length;
4548 var entry;
4549 while (index < entriesLength) {
4550 entry = entries[index++];
4551 if (found || entry.key === key) {
4552 found = true;
4553 $delete(this, entry.key);
4554 } else dindex++;
4555 }
4556 while (dindex < entriesLength) {
4557 entry = entries[dindex++];
4558 if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value);
4559 }
4560 }, { enumerable: true, unsafe: true });
4561 }
4562
4563
4564 /***/ }),
4565
4566 /***/ 7566:
4567 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4568
4569
4570 var defineBuiltIn = __webpack_require__(6840);
4571 var uncurryThis = __webpack_require__(9504);
4572 var toString = __webpack_require__(655);
4573 var validateArgumentsLength = __webpack_require__(2812);
4574
4575 var $URLSearchParams = URLSearchParams;
4576 var URLSearchParamsPrototype = $URLSearchParams.prototype;
4577 var getAll = uncurryThis(URLSearchParamsPrototype.getAll);
4578 var $has = uncurryThis(URLSearchParamsPrototype.has);
4579 var params = new $URLSearchParams('a=1');
4580
4581 // `undefined` case is a Chromium 117 bug
4582 // https://bugs.chromium.org/p/v8/issues/detail?id=14222
4583 if (params.has('a', 2) || !params.has('a', undefined)) {
4584 defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) {
4585 var length = arguments.length;
4586 var $value = length < 2 ? undefined : arguments[1];
4587 if (length && $value === undefined) return $has(this, name);
4588 var values = getAll(this, name); // also validates `this`
4589 validateArgumentsLength(length, 1);
4590 var value = toString($value);
4591 var index = 0;
4592 while (index < values.length) {
4593 if (values[index++] === value) return true;
4594 } return false;
4595 }, { enumerable: true, unsafe: true });
4596 }
4597
4598
4599 /***/ }),
4600
4601 /***/ 8721:
4602 /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
4603
4604
4605 var DESCRIPTORS = __webpack_require__(3724);
4606 var uncurryThis = __webpack_require__(9504);
4607 var defineBuiltInAccessor = __webpack_require__(2106);
4608
4609 var URLSearchParamsPrototype = URLSearchParams.prototype;
4610 var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
4611
4612 // `URLSearchParams.prototype.size` getter
4613 // https://github.com/whatwg/url/pull/734
4614 if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) {
4615 defineBuiltInAccessor(URLSearchParamsPrototype, 'size', {
4616 get: function size() {
4617 var count = 0;
4618 forEach(this, function () { count++; });
4619 return count;
4620 },
4621 configurable: true,
4622 enumerable: true
4623 });
4624 }
4625
4626
4627 /***/ })
4628
4629 /******/ });
4630 /************************************************************************/
4631 /******/ // The module cache
4632 /******/ var __webpack_module_cache__ = {};
4633 /******/
4634 /******/ // The require function
4635 /******/ function __webpack_require__(moduleId) {
4636 /******/ // Check if module is in cache
4637 /******/ var cachedModule = __webpack_module_cache__[moduleId];
4638 /******/ if (cachedModule !== undefined) {
4639 /******/ return cachedModule.exports;
4640 /******/ }
4641 /******/ // Create a new module (and put it into the cache)
4642 /******/ var module = __webpack_module_cache__[moduleId] = {
4643 /******/ // no module.id needed
4644 /******/ // no module.loaded needed
4645 /******/ exports: {}
4646 /******/ };
4647 /******/
4648 /******/ // Execute the module function
4649 /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
4650 /******/
4651 /******/ // Return the exports of the module
4652 /******/ return module.exports;
4653 /******/ }
4654 /******/
4655 /************************************************************************/
4656 /******/ /* webpack/runtime/define property getters */
4657 /******/ (() => {
4658 /******/ // define getter functions for harmony exports
4659 /******/ __webpack_require__.d = (exports, definition) => {
4660 /******/ for(var key in definition) {
4661 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
4662 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
4663 /******/ }
4664 /******/ }
4665 /******/ };
4666 /******/ })();
4667 /******/
4668 /******/ /* webpack/runtime/hasOwnProperty shorthand */
4669 /******/ (() => {
4670 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
4671 /******/ })();
4672 /******/
4673 /************************************************************************/
4674 var __webpack_exports__ = globalThis.pdfjsLib = {};
4675 // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
4676 (() => {
4677
4678 // EXPORTS
4679 __webpack_require__.d(__webpack_exports__, {
4680 AbortException: () => (/* reexport */ AbortException),
4681 AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer),
4682 AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType),
4683 AnnotationEditorType: () => (/* reexport */ AnnotationEditorType),
4684 AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager),
4685 AnnotationLayer: () => (/* reexport */ AnnotationLayer),
4686 AnnotationMode: () => (/* reexport */ AnnotationMode),
4687 CMapCompressionType: () => (/* reexport */ CMapCompressionType),
4688 ColorPicker: () => (/* reexport */ ColorPicker),
4689 DOMSVGFactory: () => (/* reexport */ DOMSVGFactory),
4690 DrawLayer: () => (/* reexport */ DrawLayer),
4691 FeatureTest: () => (/* reexport */ util_FeatureTest),
4692 GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions),
4693 ImageKind: () => (/* reexport */ util_ImageKind),
4694 InvalidPDFException: () => (/* reexport */ InvalidPDFException),
4695 MissingPDFException: () => (/* reexport */ MissingPDFException),
4696 OPS: () => (/* reexport */ OPS),
4697 Outliner: () => (/* reexport */ Outliner),
4698 PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport),
4699 PDFDateString: () => (/* reexport */ PDFDateString),
4700 PDFWorker: () => (/* reexport */ PDFWorker),
4701 PasswordResponses: () => (/* reexport */ PasswordResponses),
4702 PermissionFlag: () => (/* reexport */ PermissionFlag),
4703 PixelsPerInch: () => (/* reexport */ PixelsPerInch),
4704 RenderingCancelledException: () => (/* reexport */ RenderingCancelledException),
4705 TextLayer: () => (/* reexport */ TextLayer),
4706 UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException),
4707 Util: () => (/* reexport */ Util),
4708 VerbosityLevel: () => (/* reexport */ VerbosityLevel),
4709 XfaLayer: () => (/* reexport */ XfaLayer),
4710 build: () => (/* reexport */ build),
4711 createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl),
4712 fetchData: () => (/* reexport */ fetchData),
4713 getDocument: () => (/* reexport */ getDocument),
4714 getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl),
4715 getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl),
4716 getXfaPageViewport: () => (/* reexport */ getXfaPageViewport),
4717 isDataScheme: () => (/* reexport */ isDataScheme),
4718 isPdfFile: () => (/* reexport */ isPdfFile),
4719 noContextMenu: () => (/* reexport */ noContextMenu),
4720 normalizeUnicode: () => (/* reexport */ normalizeUnicode),
4721 renderTextLayer: () => (/* reexport */ renderTextLayer),
4722 setLayerDimensions: () => (/* reexport */ setLayerDimensions),
4723 shadow: () => (/* reexport */ shadow),
4724 updateTextLayer: () => (/* reexport */ updateTextLayer),
4725 version: () => (/* reexport */ version)
4726 });
4727
4728 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array.push.js
4729 var es_array_push = __webpack_require__(4114);
4730 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.detached.js
4731 var es_array_buffer_detached = __webpack_require__(6573);
4732 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer.js
4733 var es_array_buffer_transfer = __webpack_require__(8100);
4734 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer-to-fixed-length.js
4735 var es_array_buffer_transfer_to_fixed_length = __webpack_require__(7936);
4736 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.to-reversed.js
4737 var es_typed_array_to_reversed = __webpack_require__(7467);
4738 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.to-sorted.js
4739 var es_typed_array_to_sorted = __webpack_require__(4732);
4740 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.with.js
4741 var es_typed_array_with = __webpack_require__(9577);
4742 // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.delete.js
4743 var web_url_search_params_delete = __webpack_require__(4603);
4744 // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.has.js
4745 var web_url_search_params_has = __webpack_require__(7566);
4746 // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.size.js
4747 var web_url_search_params_size = __webpack_require__(8721);
4748 ;// CONCATENATED MODULE: ./src/shared/util.js
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759 const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
4760 const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
4761 const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
4762 const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
4763 const LINE_FACTOR = 1.35;
4764 const LINE_DESCENT_FACTOR = 0.35;
4765 const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
4766 const RenderingIntentFlag = {
4767 ANY: 0x01,
4768 DISPLAY: 0x02,
4769 PRINT: 0x04,
4770 SAVE: 0x08,
4771 ANNOTATIONS_FORMS: 0x10,
4772 ANNOTATIONS_STORAGE: 0x20,
4773 ANNOTATIONS_DISABLE: 0x40,
4774 OPLIST: 0x100
4775 };
4776 const AnnotationMode = {
4777 DISABLE: 0,
4778 ENABLE: 1,
4779 ENABLE_FORMS: 2,
4780 ENABLE_STORAGE: 3
4781 };
4782 const AnnotationEditorPrefix = "pdfjs_internal_editor_";
4783 const AnnotationEditorType = {
4784 DISABLE: -1,
4785 NONE: 0,
4786 FREETEXT: 3,
4787 HIGHLIGHT: 9,
4788 STAMP: 13,
4789 INK: 15
4790 };
4791 const AnnotationEditorParamsType = {
4792 RESIZE: 1,
4793 CREATE: 2,
4794 FREETEXT_SIZE: 11,
4795 FREETEXT_COLOR: 12,
4796 FREETEXT_OPACITY: 13,
4797 INK_COLOR: 21,
4798 INK_THICKNESS: 22,
4799 INK_OPACITY: 23,
4800 HIGHLIGHT_COLOR: 31,
4801 HIGHLIGHT_DEFAULT_COLOR: 32,
4802 HIGHLIGHT_THICKNESS: 33,
4803 HIGHLIGHT_FREE: 34,
4804 HIGHLIGHT_SHOW_ALL: 35
4805 };
4806 const PermissionFlag = {
4807 PRINT: 0x04,
4808 MODIFY_CONTENTS: 0x08,
4809 COPY: 0x10,
4810 MODIFY_ANNOTATIONS: 0x20,
4811 FILL_INTERACTIVE_FORMS: 0x100,
4812 COPY_FOR_ACCESSIBILITY: 0x200,
4813 ASSEMBLE: 0x400,
4814 PRINT_HIGH_QUALITY: 0x800
4815 };
4816 const TextRenderingMode = {
4817 FILL: 0,
4818 STROKE: 1,
4819 FILL_STROKE: 2,
4820 INVISIBLE: 3,
4821 FILL_ADD_TO_PATH: 4,
4822 STROKE_ADD_TO_PATH: 5,
4823 FILL_STROKE_ADD_TO_PATH: 6,
4824 ADD_TO_PATH: 7,
4825 FILL_STROKE_MASK: 3,
4826 ADD_TO_PATH_FLAG: 4
4827 };
4828 const util_ImageKind = {
4829 GRAYSCALE_1BPP: 1,
4830 RGB_24BPP: 2,
4831 RGBA_32BPP: 3
4832 };
4833 const AnnotationType = {
4834 TEXT: 1,
4835 LINK: 2,
4836 FREETEXT: 3,
4837 LINE: 4,
4838 SQUARE: 5,
4839 CIRCLE: 6,
4840 POLYGON: 7,
4841 POLYLINE: 8,
4842 HIGHLIGHT: 9,
4843 UNDERLINE: 10,
4844 SQUIGGLY: 11,
4845 STRIKEOUT: 12,
4846 STAMP: 13,
4847 CARET: 14,
4848 INK: 15,
4849 POPUP: 16,
4850 FILEATTACHMENT: 17,
4851 SOUND: 18,
4852 MOVIE: 19,
4853 WIDGET: 20,
4854 SCREEN: 21,
4855 PRINTERMARK: 22,
4856 TRAPNET: 23,
4857 WATERMARK: 24,
4858 THREED: 25,
4859 REDACT: 26
4860 };
4861 const AnnotationReplyType = {
4862 GROUP: "Group",
4863 REPLY: "R"
4864 };
4865 const AnnotationFlag = {
4866 INVISIBLE: 0x01,
4867 HIDDEN: 0x02,
4868 PRINT: 0x04,
4869 NOZOOM: 0x08,
4870 NOROTATE: 0x10,
4871 NOVIEW: 0x20,
4872 READONLY: 0x40,
4873 LOCKED: 0x80,
4874 TOGGLENOVIEW: 0x100,
4875 LOCKEDCONTENTS: 0x200
4876 };
4877 const AnnotationFieldFlag = {
4878 READONLY: 0x0000001,
4879 REQUIRED: 0x0000002,
4880 NOEXPORT: 0x0000004,
4881 MULTILINE: 0x0001000,
4882 PASSWORD: 0x0002000,
4883 NOTOGGLETOOFF: 0x0004000,
4884 RADIO: 0x0008000,
4885 PUSHBUTTON: 0x0010000,
4886 COMBO: 0x0020000,
4887 EDIT: 0x0040000,
4888 SORT: 0x0080000,
4889 FILESELECT: 0x0100000,
4890 MULTISELECT: 0x0200000,
4891 DONOTSPELLCHECK: 0x0400000,
4892 DONOTSCROLL: 0x0800000,
4893 COMB: 0x1000000,
4894 RICHTEXT: 0x2000000,
4895 RADIOSINUNISON: 0x2000000,
4896 COMMITONSELCHANGE: 0x4000000
4897 };
4898 const AnnotationBorderStyleType = {
4899 SOLID: 1,
4900 DASHED: 2,
4901 BEVELED: 3,
4902 INSET: 4,
4903 UNDERLINE: 5
4904 };
4905 const AnnotationActionEventType = {
4906 E: "Mouse Enter",
4907 X: "Mouse Exit",
4908 D: "Mouse Down",
4909 U: "Mouse Up",
4910 Fo: "Focus",
4911 Bl: "Blur",
4912 PO: "PageOpen",
4913 PC: "PageClose",
4914 PV: "PageVisible",
4915 PI: "PageInvisible",
4916 K: "Keystroke",
4917 F: "Format",
4918 V: "Validate",
4919 C: "Calculate"
4920 };
4921 const DocumentActionEventType = {
4922 WC: "WillClose",
4923 WS: "WillSave",
4924 DS: "DidSave",
4925 WP: "WillPrint",
4926 DP: "DidPrint"
4927 };
4928 const PageActionEventType = {
4929 O: "PageOpen",
4930 C: "PageClose"
4931 };
4932 const VerbosityLevel = {
4933 ERRORS: 0,
4934 WARNINGS: 1,
4935 INFOS: 5
4936 };
4937 const CMapCompressionType = {
4938 NONE: 0,
4939 BINARY: 1
4940 };
4941 const OPS = {
4942 dependency: 1,
4943 setLineWidth: 2,
4944 setLineCap: 3,
4945 setLineJoin: 4,
4946 setMiterLimit: 5,
4947 setDash: 6,
4948 setRenderingIntent: 7,
4949 setFlatness: 8,
4950 setGState: 9,
4951 save: 10,
4952 restore: 11,
4953 transform: 12,
4954 moveTo: 13,
4955 lineTo: 14,
4956 curveTo: 15,
4957 curveTo2: 16,
4958 curveTo3: 17,
4959 closePath: 18,
4960 rectangle: 19,
4961 stroke: 20,
4962 closeStroke: 21,
4963 fill: 22,
4964 eoFill: 23,
4965 fillStroke: 24,
4966 eoFillStroke: 25,
4967 closeFillStroke: 26,
4968 closeEOFillStroke: 27,
4969 endPath: 28,
4970 clip: 29,
4971 eoClip: 30,
4972 beginText: 31,
4973 endText: 32,
4974 setCharSpacing: 33,
4975 setWordSpacing: 34,
4976 setHScale: 35,
4977 setLeading: 36,
4978 setFont: 37,
4979 setTextRenderingMode: 38,
4980 setTextRise: 39,
4981 moveText: 40,
4982 setLeadingMoveText: 41,
4983 setTextMatrix: 42,
4984 nextLine: 43,
4985 showText: 44,
4986 showSpacedText: 45,
4987 nextLineShowText: 46,
4988 nextLineSetSpacingShowText: 47,
4989 setCharWidth: 48,
4990 setCharWidthAndBounds: 49,
4991 setStrokeColorSpace: 50,
4992 setFillColorSpace: 51,
4993 setStrokeColor: 52,
4994 setStrokeColorN: 53,
4995 setFillColor: 54,
4996 setFillColorN: 55,
4997 setStrokeGray: 56,
4998 setFillGray: 57,
4999 setStrokeRGBColor: 58,
5000 setFillRGBColor: 59,
5001 setStrokeCMYKColor: 60,
5002 setFillCMYKColor: 61,
5003 shadingFill: 62,
5004 beginInlineImage: 63,
5005 beginImageData: 64,
5006 endInlineImage: 65,
5007 paintXObject: 66,
5008 markPoint: 67,
5009 markPointProps: 68,
5010 beginMarkedContent: 69,
5011 beginMarkedContentProps: 70,
5012 endMarkedContent: 71,
5013 beginCompat: 72,
5014 endCompat: 73,
5015 paintFormXObjectBegin: 74,
5016 paintFormXObjectEnd: 75,
5017 beginGroup: 76,
5018 endGroup: 77,
5019 beginAnnotation: 80,
5020 endAnnotation: 81,
5021 paintImageMaskXObject: 83,
5022 paintImageMaskXObjectGroup: 84,
5023 paintImageXObject: 85,
5024 paintInlineImageXObject: 86,
5025 paintInlineImageXObjectGroup: 87,
5026 paintImageXObjectRepeat: 88,
5027 paintImageMaskXObjectRepeat: 89,
5028 paintSolidColorImageMask: 90,
5029 constructPath: 91
5030 };
5031 const PasswordResponses = {
5032 NEED_PASSWORD: 1,
5033 INCORRECT_PASSWORD: 2
5034 };
5035 let verbosity = VerbosityLevel.WARNINGS;
5036 function setVerbosityLevel(level) {
5037 if (Number.isInteger(level)) {
5038 verbosity = level;
5039 }
5040 }
5041 function getVerbosityLevel() {
5042 return verbosity;
5043 }
5044 function info(msg) {
5045 if (verbosity >= VerbosityLevel.INFOS) {
5046 console.log(`Info: ${msg}`);
5047 }
5048 }
5049 function warn(msg) {
5050 if (verbosity >= VerbosityLevel.WARNINGS) {
5051 console.log(`Warning: ${msg}`);
5052 }
5053 }
5054 function unreachable(msg) {
5055 throw new Error(msg);
5056 }
5057 function assert(cond, msg) {
5058 if (!cond) {
5059 unreachable(msg);
5060 }
5061 }
5062 function _isValidProtocol(url) {
5063 switch (url?.protocol) {
5064 case "http:":
5065 case "https:":
5066 case "ftp:":
5067 case "mailto:":
5068 case "tel:":
5069 return true;
5070 default:
5071 return false;
5072 }
5073 }
5074 function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
5075 if (!url) {
5076 return null;
5077 }
5078 try {
5079 if (options && typeof url === "string") {
5080 if (options.addDefaultProtocol && url.startsWith("www.")) {
5081 const dots = url.match(/\./g);
5082 if (dots?.length >= 2) {
5083 url = `http://${url}`;
5084 }
5085 }
5086 if (options.tryConvertEncoding) {
5087 try {
5088 url = stringToUTF8String(url);
5089 } catch {}
5090 }
5091 }
5092 const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
5093 if (_isValidProtocol(absoluteUrl)) {
5094 return absoluteUrl;
5095 }
5096 } catch {}
5097 return null;
5098 }
5099 function shadow(obj, prop, value, nonSerializable = false) {
5100 Object.defineProperty(obj, prop, {
5101 value,
5102 enumerable: !nonSerializable,
5103 configurable: true,
5104 writable: false
5105 });
5106 return value;
5107 }
5108 const BaseException = function BaseExceptionClosure() {
5109 function BaseException(message, name) {
5110 if (this.constructor === BaseException) {
5111 unreachable("Cannot initialize BaseException.");
5112 }
5113 this.message = message;
5114 this.name = name;
5115 }
5116 BaseException.prototype = new Error();
5117 BaseException.constructor = BaseException;
5118 return BaseException;
5119 }();
5120 class PasswordException extends BaseException {
5121 constructor(msg, code) {
5122 super(msg, "PasswordException");
5123 this.code = code;
5124 }
5125 }
5126 class UnknownErrorException extends BaseException {
5127 constructor(msg, details) {
5128 super(msg, "UnknownErrorException");
5129 this.details = details;
5130 }
5131 }
5132 class InvalidPDFException extends BaseException {
5133 constructor(msg) {
5134 super(msg, "InvalidPDFException");
5135 }
5136 }
5137 class MissingPDFException extends BaseException {
5138 constructor(msg) {
5139 super(msg, "MissingPDFException");
5140 }
5141 }
5142 class UnexpectedResponseException extends BaseException {
5143 constructor(msg, status) {
5144 super(msg, "UnexpectedResponseException");
5145 this.status = status;
5146 }
5147 }
5148 class FormatError extends BaseException {
5149 constructor(msg) {
5150 super(msg, "FormatError");
5151 }
5152 }
5153 class AbortException extends BaseException {
5154 constructor(msg) {
5155 super(msg, "AbortException");
5156 }
5157 }
5158 function bytesToString(bytes) {
5159 if (typeof bytes !== "object" || bytes?.length === undefined) {
5160 unreachable("Invalid argument for bytesToString");
5161 }
5162 const length = bytes.length;
5163 const MAX_ARGUMENT_COUNT = 8192;
5164 if (length < MAX_ARGUMENT_COUNT) {
5165 return String.fromCharCode.apply(null, bytes);
5166 }
5167 const strBuf = [];
5168 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
5169 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
5170 const chunk = bytes.subarray(i, chunkEnd);
5171 strBuf.push(String.fromCharCode.apply(null, chunk));
5172 }
5173 return strBuf.join("");
5174 }
5175 function stringToBytes(str) {
5176 if (typeof str !== "string") {
5177 unreachable("Invalid argument for stringToBytes");
5178 }
5179 const length = str.length;
5180 const bytes = new Uint8Array(length);
5181 for (let i = 0; i < length; ++i) {
5182 bytes[i] = str.charCodeAt(i) & 0xff;
5183 }
5184 return bytes;
5185 }
5186 function string32(value) {
5187 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
5188 }
5189 function objectSize(obj) {
5190 return Object.keys(obj).length;
5191 }
5192 function objectFromMap(map) {
5193 const obj = Object.create(null);
5194 for (const [key, value] of map) {
5195 obj[key] = value;
5196 }
5197 return obj;
5198 }
5199 function isLittleEndian() {
5200 const buffer8 = new Uint8Array(4);
5201 buffer8[0] = 1;
5202 const view32 = new Uint32Array(buffer8.buffer, 0, 1);
5203 return view32[0] === 1;
5204 }
5205 function isEvalSupported() {
5206 try {
5207 new Function("");
5208 return true;
5209 } catch {
5210 return false;
5211 }
5212 }
5213 class util_FeatureTest {
5214 static get isLittleEndian() {
5215 return shadow(this, "isLittleEndian", isLittleEndian());
5216 }
5217 static get isEvalSupported() {
5218 return shadow(this, "isEvalSupported", isEvalSupported());
5219 }
5220 static get isOffscreenCanvasSupported() {
5221 return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
5222 }
5223 static get platform() {
5224 if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") {
5225 return shadow(this, "platform", {
5226 isMac: navigator.platform.includes("Mac")
5227 });
5228 }
5229 return shadow(this, "platform", {
5230 isMac: false
5231 });
5232 }
5233 static get isCSSRoundSupported() {
5234 return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
5235 }
5236 }
5237 const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
5238 class Util {
5239 static makeHexColor(r, g, b) {
5240 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
5241 }
5242 static scaleMinMax(transform, minMax) {
5243 let temp;
5244 if (transform[0]) {
5245 if (transform[0] < 0) {
5246 temp = minMax[0];
5247 minMax[0] = minMax[2];
5248 minMax[2] = temp;
5249 }
5250 minMax[0] *= transform[0];
5251 minMax[2] *= transform[0];
5252 if (transform[3] < 0) {
5253 temp = minMax[1];
5254 minMax[1] = minMax[3];
5255 minMax[3] = temp;
5256 }
5257 minMax[1] *= transform[3];
5258 minMax[3] *= transform[3];
5259 } else {
5260 temp = minMax[0];
5261 minMax[0] = minMax[1];
5262 minMax[1] = temp;
5263 temp = minMax[2];
5264 minMax[2] = minMax[3];
5265 minMax[3] = temp;
5266 if (transform[1] < 0) {
5267 temp = minMax[1];
5268 minMax[1] = minMax[3];
5269 minMax[3] = temp;
5270 }
5271 minMax[1] *= transform[1];
5272 minMax[3] *= transform[1];
5273 if (transform[2] < 0) {
5274 temp = minMax[0];
5275 minMax[0] = minMax[2];
5276 minMax[2] = temp;
5277 }
5278 minMax[0] *= transform[2];
5279 minMax[2] *= transform[2];
5280 }
5281 minMax[0] += transform[4];
5282 minMax[1] += transform[5];
5283 minMax[2] += transform[4];
5284 minMax[3] += transform[5];
5285 }
5286 static transform(m1, m2) {
5287 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]];
5288 }
5289 static applyTransform(p, m) {
5290 const xt = p[0] * m[0] + p[1] * m[2] + m[4];
5291 const yt = p[0] * m[1] + p[1] * m[3] + m[5];
5292 return [xt, yt];
5293 }
5294 static applyInverseTransform(p, m) {
5295 const d = m[0] * m[3] - m[1] * m[2];
5296 const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
5297 const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
5298 return [xt, yt];
5299 }
5300 static getAxialAlignedBoundingBox(r, m) {
5301 const p1 = this.applyTransform(r, m);
5302 const p2 = this.applyTransform(r.slice(2, 4), m);
5303 const p3 = this.applyTransform([r[0], r[3]], m);
5304 const p4 = this.applyTransform([r[2], r[1]], m);
5305 return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
5306 }
5307 static inverseTransform(m) {
5308 const d = m[0] * m[3] - m[1] * m[2];
5309 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];
5310 }
5311 static singularValueDecompose2dScale(m) {
5312 const transpose = [m[0], m[2], m[1], m[3]];
5313 const a = m[0] * transpose[0] + m[1] * transpose[2];
5314 const b = m[0] * transpose[1] + m[1] * transpose[3];
5315 const c = m[2] * transpose[0] + m[3] * transpose[2];
5316 const d = m[2] * transpose[1] + m[3] * transpose[3];
5317 const first = (a + d) / 2;
5318 const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
5319 const sx = first + second || 1;
5320 const sy = first - second || 1;
5321 return [Math.sqrt(sx), Math.sqrt(sy)];
5322 }
5323 static normalizeRect(rect) {
5324 const r = rect.slice(0);
5325 if (rect[0] > rect[2]) {
5326 r[0] = rect[2];
5327 r[2] = rect[0];
5328 }
5329 if (rect[1] > rect[3]) {
5330 r[1] = rect[3];
5331 r[3] = rect[1];
5332 }
5333 return r;
5334 }
5335 static intersect(rect1, rect2) {
5336 const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
5337 const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
5338 if (xLow > xHigh) {
5339 return null;
5340 }
5341 const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
5342 const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
5343 if (yLow > yHigh) {
5344 return null;
5345 }
5346 return [xLow, yLow, xHigh, yHigh];
5347 }
5348 static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
5349 if (t <= 0 || t >= 1) {
5350 return;
5351 }
5352 const mt = 1 - t;
5353 const tt = t * t;
5354 const ttt = tt * t;
5355 const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
5356 const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
5357 minMax[0] = Math.min(minMax[0], x);
5358 minMax[1] = Math.min(minMax[1], y);
5359 minMax[2] = Math.max(minMax[2], x);
5360 minMax[3] = Math.max(minMax[3], y);
5361 }
5362 static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
5363 if (Math.abs(a) < 1e-12) {
5364 if (Math.abs(b) >= 1e-12) {
5365 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
5366 }
5367 return;
5368 }
5369 const delta = b ** 2 - 4 * c * a;
5370 if (delta < 0) {
5371 return;
5372 }
5373 const sqrtDelta = Math.sqrt(delta);
5374 const a2 = 2 * a;
5375 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
5376 this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
5377 }
5378 static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
5379 if (minMax) {
5380 minMax[0] = Math.min(minMax[0], x0, x3);
5381 minMax[1] = Math.min(minMax[1], y0, y3);
5382 minMax[2] = Math.max(minMax[2], x0, x3);
5383 minMax[3] = Math.max(minMax[3], y0, y3);
5384 } else {
5385 minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
5386 }
5387 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);
5388 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);
5389 return minMax;
5390 }
5391 }
5392 const 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]));
5393 function stringToPDFString(str) {
5394 if (str[0] >= "\xEF") {
5395 let encoding;
5396 if (str[0] === "\xFE" && str[1] === "\xFF") {
5397 encoding = "utf-16be";
5398 if (str.length % 2 === 1) {
5399 str = str.slice(0, -1);
5400 }
5401 } else if (str[0] === "\xFF" && str[1] === "\xFE") {
5402 encoding = "utf-16le";
5403 if (str.length % 2 === 1) {
5404 str = str.slice(0, -1);
5405 }
5406 } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
5407 encoding = "utf-8";
5408 }
5409 if (encoding) {
5410 try {
5411 const decoder = new TextDecoder(encoding, {
5412 fatal: true
5413 });
5414 const buffer = stringToBytes(str);
5415 const decoded = decoder.decode(buffer);
5416 if (!decoded.includes("\x1b")) {
5417 return decoded;
5418 }
5419 return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
5420 } catch (ex) {
5421 warn(`stringToPDFString: "${ex}".`);
5422 }
5423 }
5424 }
5425 const strBuf = [];
5426 for (let i = 0, ii = str.length; i < ii; i++) {
5427 const charCode = str.charCodeAt(i);
5428 if (charCode === 0x1b) {
5429 while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
5430 continue;
5431 }
5432 const code = PDFStringTranslateTable[charCode];
5433 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
5434 }
5435 return strBuf.join("");
5436 }
5437 function stringToUTF8String(str) {
5438 return decodeURIComponent(escape(str));
5439 }
5440 function utf8StringToString(str) {
5441 return unescape(encodeURIComponent(str));
5442 }
5443 function isArrayEqual(arr1, arr2) {
5444 if (arr1.length !== arr2.length) {
5445 return false;
5446 }
5447 for (let i = 0, ii = arr1.length; i < ii; i++) {
5448 if (arr1[i] !== arr2[i]) {
5449 return false;
5450 }
5451 }
5452 return true;
5453 }
5454 function getModificationDate(date = new Date()) {
5455 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")];
5456 return buffer.join("");
5457 }
5458 let NormalizeRegex = null;
5459 let NormalizationMap = null;
5460 function normalizeUnicode(str) {
5461 if (!NormalizeRegex) {
5462 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;
5463 NormalizationMap = new Map([["�
5464 ", "ſt"]]);
5465 }
5466 return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
5467 }
5468 function getUuid() {
5469 if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") {
5470 return crypto.randomUUID();
5471 }
5472 const buf = new Uint8Array(32);
5473 if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") {
5474 crypto.getRandomValues(buf);
5475 } else {
5476 for (let i = 0; i < 32; i++) {
5477 buf[i] = Math.floor(Math.random() * 255);
5478 }
5479 }
5480 return bytesToString(buf);
5481 }
5482 const AnnotationPrefix = "pdfjs_internal_id_";
5483 const FontRenderOps = {
5484 BEZIER_CURVE_TO: 0,
5485 MOVE_TO: 1,
5486 LINE_TO: 2,
5487 QUADRATIC_CURVE_TO: 3,
5488 RESTORE: 4,
5489 SAVE: 5,
5490 SCALE: 6,
5491 TRANSFORM: 7,
5492 TRANSLATE: 8
5493 };
5494
5495 // EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.with-resolvers.js
5496 var es_promise_with_resolvers = __webpack_require__(4628);
5497 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.map.js
5498 var esnext_iterator_map = __webpack_require__(1454);
5499 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.difference.v2.js
5500 var esnext_set_difference_v2 = __webpack_require__(3375);
5501 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.intersection.v2.js
5502 var esnext_set_intersection_v2 = __webpack_require__(9225);
5503 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.is-disjoint-from.v2.js
5504 var esnext_set_is_disjoint_from_v2 = __webpack_require__(3972);
5505 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.is-subset-of.v2.js
5506 var esnext_set_is_subset_of_v2 = __webpack_require__(9209);
5507 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.is-superset-of.v2.js
5508 var esnext_set_is_superset_of_v2 = __webpack_require__(5714);
5509 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.symmetric-difference.v2.js
5510 var esnext_set_symmetric_difference_v2 = __webpack_require__(7561);
5511 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.set.union.v2.js
5512 var esnext_set_union_v2 = __webpack_require__(6197);
5513 // EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom-exception.stack.js
5514 var web_dom_exception_stack = __webpack_require__(4979);
5515 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.constructor.js
5516 var esnext_iterator_constructor = __webpack_require__(8992);
5517 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.every.js
5518 var esnext_iterator_every = __webpack_require__(3215);
5519 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.some.js
5520 var esnext_iterator_some = __webpack_require__(7550);
5521 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.json.parse.js
5522 var esnext_json_parse = __webpack_require__(8335);
5523 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.filter.js
5524 var esnext_iterator_filter = __webpack_require__(4520);
5525 ;// CONCATENATED MODULE: ./src/display/base_factory.js
5526
5527 class BaseFilterFactory {
5528 constructor() {
5529 if (this.constructor === BaseFilterFactory) {
5530 unreachable("Cannot initialize BaseFilterFactory.");
5531 }
5532 }
5533 addFilter(maps) {
5534 return "none";
5535 }
5536 addHCMFilter(fgColor, bgColor) {
5537 return "none";
5538 }
5539 addAlphaFilter(map) {
5540 return "none";
5541 }
5542 addLuminosityFilter(map) {
5543 return "none";
5544 }
5545 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
5546 return "none";
5547 }
5548 destroy(keepHCM = false) {}
5549 }
5550 class BaseCanvasFactory {
5551 constructor() {
5552 if (this.constructor === BaseCanvasFactory) {
5553 unreachable("Cannot initialize BaseCanvasFactory.");
5554 }
5555 }
5556 create(width, height) {
5557 if (width <= 0 || height <= 0) {
5558 throw new Error("Invalid canvas size");
5559 }
5560 const canvas = this._createCanvas(width, height);
5561 return {
5562 canvas,
5563 context: canvas.getContext("2d")
5564 };
5565 }
5566 reset(canvasAndContext, width, height) {
5567 if (!canvasAndContext.canvas) {
5568 throw new Error("Canvas is not specified");
5569 }
5570 if (width <= 0 || height <= 0) {
5571 throw new Error("Invalid canvas size");
5572 }
5573 canvasAndContext.canvas.width = width;
5574 canvasAndContext.canvas.height = height;
5575 }
5576 destroy(canvasAndContext) {
5577 if (!canvasAndContext.canvas) {
5578 throw new Error("Canvas is not specified");
5579 }
5580 canvasAndContext.canvas.width = 0;
5581 canvasAndContext.canvas.height = 0;
5582 canvasAndContext.canvas = null;
5583 canvasAndContext.context = null;
5584 }
5585 _createCanvas(width, height) {
5586 unreachable("Abstract method `_createCanvas` called.");
5587 }
5588 }
5589 class BaseCMapReaderFactory {
5590 constructor({
5591 baseUrl = null,
5592 isCompressed = true
5593 }) {
5594 if (this.constructor === BaseCMapReaderFactory) {
5595 unreachable("Cannot initialize BaseCMapReaderFactory.");
5596 }
5597 this.baseUrl = baseUrl;
5598 this.isCompressed = isCompressed;
5599 }
5600 async fetch({
5601 name
5602 }) {
5603 if (!this.baseUrl) {
5604 throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
5605 }
5606 if (!name) {
5607 throw new Error("CMap name must be specified.");
5608 }
5609 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
5610 const compressionType = this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE;
5611 return this._fetchData(url, compressionType).catch(reason => {
5612 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
5613 });
5614 }
5615 _fetchData(url, compressionType) {
5616 unreachable("Abstract method `_fetchData` called.");
5617 }
5618 }
5619 class BaseStandardFontDataFactory {
5620 constructor({
5621 baseUrl = null
5622 }) {
5623 if (this.constructor === BaseStandardFontDataFactory) {
5624 unreachable("Cannot initialize BaseStandardFontDataFactory.");
5625 }
5626 this.baseUrl = baseUrl;
5627 }
5628 async fetch({
5629 filename
5630 }) {
5631 if (!this.baseUrl) {
5632 throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
5633 }
5634 if (!filename) {
5635 throw new Error("Font filename must be specified.");
5636 }
5637 const url = `${this.baseUrl}${filename}`;
5638 return this._fetchData(url).catch(reason => {
5639 throw new Error(`Unable to load font data at: ${url}`);
5640 });
5641 }
5642 _fetchData(url) {
5643 unreachable("Abstract method `_fetchData` called.");
5644 }
5645 }
5646 class BaseSVGFactory {
5647 constructor() {
5648 if (this.constructor === BaseSVGFactory) {
5649 unreachable("Cannot initialize BaseSVGFactory.");
5650 }
5651 }
5652 create(width, height, skipDimensions = false) {
5653 if (width <= 0 || height <= 0) {
5654 throw new Error("Invalid SVG dimensions");
5655 }
5656 const svg = this._createSVG("svg:svg");
5657 svg.setAttribute("version", "1.1");
5658 if (!skipDimensions) {
5659 svg.setAttribute("width", `${width}px`);
5660 svg.setAttribute("height", `${height}px`);
5661 }
5662 svg.setAttribute("preserveAspectRatio", "none");
5663 svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
5664 return svg;
5665 }
5666 createElement(type) {
5667 if (typeof type !== "string") {
5668 throw new Error("Invalid SVG element type");
5669 }
5670 return this._createSVG(type);
5671 }
5672 _createSVG(type) {
5673 unreachable("Abstract method `_createSVG` called.");
5674 }
5675 }
5676
5677 ;// CONCATENATED MODULE: ./src/display/display_utils.js
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693 const SVG_NS = "http://www.w3.org/2000/svg";
5694 class PixelsPerInch {
5695 static CSS = 96.0;
5696 static PDF = 72.0;
5697 static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
5698 }
5699 class DOMFilterFactory extends BaseFilterFactory {
5700 #_cache;
5701 #_defs;
5702 #docId;
5703 #document;
5704 #_hcmCache;
5705 #id = 0;
5706 constructor({
5707 docId,
5708 ownerDocument = globalThis.document
5709 } = {}) {
5710 super();
5711 this.#docId = docId;
5712 this.#document = ownerDocument;
5713 }
5714 get #cache() {
5715 return this.#_cache ||= new Map();
5716 }
5717 get #hcmCache() {
5718 return this.#_hcmCache ||= new Map();
5719 }
5720 get #defs() {
5721 if (!this.#_defs) {
5722 const div = this.#document.createElement("div");
5723 const {
5724 style
5725 } = div;
5726 style.visibility = "hidden";
5727 style.contain = "strict";
5728 style.width = style.height = 0;
5729 style.position = "absolute";
5730 style.top = style.left = 0;
5731 style.zIndex = -1;
5732 const svg = this.#document.createElementNS(SVG_NS, "svg");
5733 svg.setAttribute("width", 0);
5734 svg.setAttribute("height", 0);
5735 this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
5736 div.append(svg);
5737 svg.append(this.#_defs);
5738 this.#document.body.append(div);
5739 }
5740 return this.#_defs;
5741 }
5742 #createTables(maps) {
5743 if (maps.length === 1) {
5744 const mapR = maps[0];
5745 const buffer = new Array(256);
5746 for (let i = 0; i < 256; i++) {
5747 buffer[i] = mapR[i] / 255;
5748 }
5749 const table = buffer.join(",");
5750 return [table, table, table];
5751 }
5752 const [mapR, mapG, mapB] = maps;
5753 const bufferR = new Array(256);
5754 const bufferG = new Array(256);
5755 const bufferB = new Array(256);
5756 for (let i = 0; i < 256; i++) {
5757 bufferR[i] = mapR[i] / 255;
5758 bufferG[i] = mapG[i] / 255;
5759 bufferB[i] = mapB[i] / 255;
5760 }
5761 return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
5762 }
5763 addFilter(maps) {
5764 if (!maps) {
5765 return "none";
5766 }
5767 let value = this.#cache.get(maps);
5768 if (value) {
5769 return value;
5770 }
5771 const [tableR, tableG, tableB] = this.#createTables(maps);
5772 const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
5773 value = this.#cache.get(key);
5774 if (value) {
5775 this.#cache.set(maps, value);
5776 return value;
5777 }
5778 const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
5779 const url = `url(#${id})`;
5780 this.#cache.set(maps, url);
5781 this.#cache.set(key, url);
5782 const filter = this.#createFilter(id);
5783 this.#addTransferMapConversion(tableR, tableG, tableB, filter);
5784 return url;
5785 }
5786 addHCMFilter(fgColor, bgColor) {
5787 const key = `${fgColor}-${bgColor}`;
5788 const filterName = "base";
5789 let info = this.#hcmCache.get(filterName);
5790 if (info?.key === key) {
5791 return info.url;
5792 }
5793 if (info) {
5794 info.filter?.remove();
5795 info.key = key;
5796 info.url = "none";
5797 info.filter = null;
5798 } else {
5799 info = {
5800 key,
5801 url: "none",
5802 filter: null
5803 };
5804 this.#hcmCache.set(filterName, info);
5805 }
5806 if (!fgColor || !bgColor) {
5807 return info.url;
5808 }
5809 const fgRGB = this.#getRGB(fgColor);
5810 fgColor = Util.makeHexColor(...fgRGB);
5811 const bgRGB = this.#getRGB(bgColor);
5812 bgColor = Util.makeHexColor(...bgRGB);
5813 this.#defs.style.color = "";
5814 if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
5815 return info.url;
5816 }
5817 const map = new Array(256);
5818 for (let i = 0; i <= 255; i++) {
5819 const x = i / 255;
5820 map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
5821 }
5822 const table = map.join(",");
5823 const id = `g_${this.#docId}_hcm_filter`;
5824 const filter = info.filter = this.#createFilter(id);
5825 this.#addTransferMapConversion(table, table, table, filter);
5826 this.#addGrayConversion(filter);
5827 const getSteps = (c, n) => {
5828 const start = fgRGB[c] / 255;
5829 const end = bgRGB[c] / 255;
5830 const arr = new Array(n + 1);
5831 for (let i = 0; i <= n; i++) {
5832 arr[i] = start + i / n * (end - start);
5833 }
5834 return arr.join(",");
5835 };
5836 this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
5837 info.url = `url(#${id})`;
5838 return info.url;
5839 }
5840 addAlphaFilter(map) {
5841 let value = this.#cache.get(map);
5842 if (value) {
5843 return value;
5844 }
5845 const [tableA] = this.#createTables([map]);
5846 const key = `alpha_${tableA}`;
5847 value = this.#cache.get(key);
5848 if (value) {
5849 this.#cache.set(map, value);
5850 return value;
5851 }
5852 const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
5853 const url = `url(#${id})`;
5854 this.#cache.set(map, url);
5855 this.#cache.set(key, url);
5856 const filter = this.#createFilter(id);
5857 this.#addTransferMapAlphaConversion(tableA, filter);
5858 return url;
5859 }
5860 addLuminosityFilter(map) {
5861 let value = this.#cache.get(map || "luminosity");
5862 if (value) {
5863 return value;
5864 }
5865 let tableA, key;
5866 if (map) {
5867 [tableA] = this.#createTables([map]);
5868 key = `luminosity_${tableA}`;
5869 } else {
5870 key = "luminosity";
5871 }
5872 value = this.#cache.get(key);
5873 if (value) {
5874 this.#cache.set(map, value);
5875 return value;
5876 }
5877 const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
5878 const url = `url(#${id})`;
5879 this.#cache.set(map, url);
5880 this.#cache.set(key, url);
5881 const filter = this.#createFilter(id);
5882 this.#addLuminosityConversion(filter);
5883 if (map) {
5884 this.#addTransferMapAlphaConversion(tableA, filter);
5885 }
5886 return url;
5887 }
5888 addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
5889 const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
5890 let info = this.#hcmCache.get(filterName);
5891 if (info?.key === key) {
5892 return info.url;
5893 }
5894 if (info) {
5895 info.filter?.remove();
5896 info.key = key;
5897 info.url = "none";
5898 info.filter = null;
5899 } else {
5900 info = {
5901 key,
5902 url: "none",
5903 filter: null
5904 };
5905 this.#hcmCache.set(filterName, info);
5906 }
5907 if (!fgColor || !bgColor) {
5908 return info.url;
5909 }
5910 const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
5911 let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
5912 let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
5913 let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
5914 if (bgGray < fgGray) {
5915 [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
5916 }
5917 this.#defs.style.color = "";
5918 const getSteps = (fg, bg, n) => {
5919 const arr = new Array(256);
5920 const step = (bgGray - fgGray) / n;
5921 const newStart = fg / 255;
5922 const newStep = (bg - fg) / (255 * n);
5923 let prev = 0;
5924 for (let i = 0; i <= n; i++) {
5925 const k = Math.round(fgGray + i * step);
5926 const value = newStart + i * newStep;
5927 for (let j = prev; j <= k; j++) {
5928 arr[j] = value;
5929 }
5930 prev = k + 1;
5931 }
5932 for (let i = prev; i < 256; i++) {
5933 arr[i] = arr[prev - 1];
5934 }
5935 return arr.join(",");
5936 };
5937 const id = `g_${this.#docId}_hcm_${filterName}_filter`;
5938 const filter = info.filter = this.#createFilter(id);
5939 this.#addGrayConversion(filter);
5940 this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
5941 info.url = `url(#${id})`;
5942 return info.url;
5943 }
5944 destroy(keepHCM = false) {
5945 if (keepHCM && this.#hcmCache.size !== 0) {
5946 return;
5947 }
5948 if (this.#_defs) {
5949 this.#_defs.parentNode.parentNode.remove();
5950 this.#_defs = null;
5951 }
5952 if (this.#_cache) {
5953 this.#_cache.clear();
5954 this.#_cache = null;
5955 }
5956 this.#id = 0;
5957 }
5958 #addLuminosityConversion(filter) {
5959 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
5960 feColorMatrix.setAttribute("type", "matrix");
5961 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");
5962 filter.append(feColorMatrix);
5963 }
5964 #addGrayConversion(filter) {
5965 const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
5966 feColorMatrix.setAttribute("type", "matrix");
5967 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");
5968 filter.append(feColorMatrix);
5969 }
5970 #createFilter(id) {
5971 const filter = this.#document.createElementNS(SVG_NS, "filter");
5972 filter.setAttribute("color-interpolation-filters", "sRGB");
5973 filter.setAttribute("id", id);
5974 this.#defs.append(filter);
5975 return filter;
5976 }
5977 #appendFeFunc(feComponentTransfer, func, table) {
5978 const feFunc = this.#document.createElementNS(SVG_NS, func);
5979 feFunc.setAttribute("type", "discrete");
5980 feFunc.setAttribute("tableValues", table);
5981 feComponentTransfer.append(feFunc);
5982 }
5983 #addTransferMapConversion(rTable, gTable, bTable, filter) {
5984 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
5985 filter.append(feComponentTransfer);
5986 this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
5987 this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
5988 this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
5989 }
5990 #addTransferMapAlphaConversion(aTable, filter) {
5991 const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
5992 filter.append(feComponentTransfer);
5993 this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
5994 }
5995 #getRGB(color) {
5996 this.#defs.style.color = color;
5997 return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
5998 }
5999 }
6000 class DOMCanvasFactory extends BaseCanvasFactory {
6001 constructor({
6002 ownerDocument = globalThis.document
6003 } = {}) {
6004 super();
6005 this._document = ownerDocument;
6006 }
6007 _createCanvas(width, height) {
6008 const canvas = this._document.createElement("canvas");
6009 canvas.width = width;
6010 canvas.height = height;
6011 return canvas;
6012 }
6013 }
6014 async function fetchData(url, type = "text") {
6015 if (isValidFetchUrl(url, document.baseURI)) {
6016 const response = await fetch(url);
6017 if (!response.ok) {
6018 throw new Error(response.statusText);
6019 }
6020 switch (type) {
6021 case "arraybuffer":
6022 return response.arrayBuffer();
6023 case "blob":
6024 return response.blob();
6025 case "json":
6026 return response.json();
6027 }
6028 return response.text();
6029 }
6030 return new Promise((resolve, reject) => {
6031 const request = new XMLHttpRequest();
6032 request.open("GET", url, true);
6033 request.responseType = type;
6034 request.onreadystatechange = () => {
6035 if (request.readyState !== XMLHttpRequest.DONE) {
6036 return;
6037 }
6038 if (request.status === 200 || request.status === 0) {
6039 switch (type) {
6040 case "arraybuffer":
6041 case "blob":
6042 case "json":
6043 resolve(request.response);
6044 return;
6045 }
6046 resolve(request.responseText);
6047 return;
6048 }
6049 reject(new Error(request.statusText));
6050 };
6051 request.send(null);
6052 });
6053 }
6054 class DOMCMapReaderFactory extends BaseCMapReaderFactory {
6055 _fetchData(url, compressionType) {
6056 return fetchData(url, this.isCompressed ? "arraybuffer" : "text").then(data => ({
6057 cMapData: data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data),
6058 compressionType
6059 }));
6060 }
6061 }
6062 class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
6063 _fetchData(url) {
6064 return fetchData(url, "arraybuffer").then(data => new Uint8Array(data));
6065 }
6066 }
6067 class DOMSVGFactory extends BaseSVGFactory {
6068 _createSVG(type) {
6069 return document.createElementNS(SVG_NS, type);
6070 }
6071 }
6072 class PageViewport {
6073 constructor({
6074 viewBox,
6075 scale,
6076 rotation,
6077 offsetX = 0,
6078 offsetY = 0,
6079 dontFlip = false
6080 }) {
6081 this.viewBox = viewBox;
6082 this.scale = scale;
6083 this.rotation = rotation;
6084 this.offsetX = offsetX;
6085 this.offsetY = offsetY;
6086 const centerX = (viewBox[2] + viewBox[0]) / 2;
6087 const centerY = (viewBox[3] + viewBox[1]) / 2;
6088 let rotateA, rotateB, rotateC, rotateD;
6089 rotation %= 360;
6090 if (rotation < 0) {
6091 rotation += 360;
6092 }
6093 switch (rotation) {
6094 case 180:
6095 rotateA = -1;
6096 rotateB = 0;
6097 rotateC = 0;
6098 rotateD = 1;
6099 break;
6100 case 90:
6101 rotateA = 0;
6102 rotateB = 1;
6103 rotateC = 1;
6104 rotateD = 0;
6105 break;
6106 case 270:
6107 rotateA = 0;
6108 rotateB = -1;
6109 rotateC = -1;
6110 rotateD = 0;
6111 break;
6112 case 0:
6113 rotateA = 1;
6114 rotateB = 0;
6115 rotateC = 0;
6116 rotateD = -1;
6117 break;
6118 default:
6119 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
6120 }
6121 if (dontFlip) {
6122 rotateC = -rotateC;
6123 rotateD = -rotateD;
6124 }
6125 let offsetCanvasX, offsetCanvasY;
6126 let width, height;
6127 if (rotateA === 0) {
6128 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
6129 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
6130 width = (viewBox[3] - viewBox[1]) * scale;
6131 height = (viewBox[2] - viewBox[0]) * scale;
6132 } else {
6133 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
6134 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
6135 width = (viewBox[2] - viewBox[0]) * scale;
6136 height = (viewBox[3] - viewBox[1]) * scale;
6137 }
6138 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
6139 this.width = width;
6140 this.height = height;
6141 }
6142 get rawDims() {
6143 const {
6144 viewBox
6145 } = this;
6146 return shadow(this, "rawDims", {
6147 pageWidth: viewBox[2] - viewBox[0],
6148 pageHeight: viewBox[3] - viewBox[1],
6149 pageX: viewBox[0],
6150 pageY: viewBox[1]
6151 });
6152 }
6153 clone({
6154 scale = this.scale,
6155 rotation = this.rotation,
6156 offsetX = this.offsetX,
6157 offsetY = this.offsetY,
6158 dontFlip = false
6159 } = {}) {
6160 return new PageViewport({
6161 viewBox: this.viewBox.slice(),
6162 scale,
6163 rotation,
6164 offsetX,
6165 offsetY,
6166 dontFlip
6167 });
6168 }
6169 convertToViewportPoint(x, y) {
6170 return Util.applyTransform([x, y], this.transform);
6171 }
6172 convertToViewportRectangle(rect) {
6173 const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
6174 const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
6175 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
6176 }
6177 convertToPdfPoint(x, y) {
6178 return Util.applyInverseTransform([x, y], this.transform);
6179 }
6180 }
6181 class RenderingCancelledException extends BaseException {
6182 constructor(msg, extraDelay = 0) {
6183 super(msg, "RenderingCancelledException");
6184 this.extraDelay = extraDelay;
6185 }
6186 }
6187 function isDataScheme(url) {
6188 const ii = url.length;
6189 let i = 0;
6190 while (i < ii && url[i].trim() === "") {
6191 i++;
6192 }
6193 return url.substring(i, i + 5).toLowerCase() === "data:";
6194 }
6195 function isPdfFile(filename) {
6196 return typeof filename === "string" && /\.pdf$/i.test(filename);
6197 }
6198 function getFilenameFromUrl(url) {
6199 [url] = url.split(/[#?]/, 1);
6200 return url.substring(url.lastIndexOf("/") + 1);
6201 }
6202 function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
6203 if (typeof url !== "string") {
6204 return defaultFilename;
6205 }
6206 if (isDataScheme(url)) {
6207 warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
6208 return defaultFilename;
6209 }
6210 const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
6211 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
6212 const splitURI = reURI.exec(url);
6213 let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
6214 if (suggestedFilename) {
6215 suggestedFilename = suggestedFilename[0];
6216 if (suggestedFilename.includes("%")) {
6217 try {
6218 suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
6219 } catch {}
6220 }
6221 }
6222 return suggestedFilename || defaultFilename;
6223 }
6224 class StatTimer {
6225 started = Object.create(null);
6226 times = [];
6227 time(name) {
6228 if (name in this.started) {
6229 warn(`Timer is already running for ${name}`);
6230 }
6231 this.started[name] = Date.now();
6232 }
6233 timeEnd(name) {
6234 if (!(name in this.started)) {
6235 warn(`Timer has not been started for ${name}`);
6236 }
6237 this.times.push({
6238 name,
6239 start: this.started[name],
6240 end: Date.now()
6241 });
6242 delete this.started[name];
6243 }
6244 toString() {
6245 const outBuf = [];
6246 let longest = 0;
6247 for (const {
6248 name
6249 } of this.times) {
6250 longest = Math.max(name.length, longest);
6251 }
6252 for (const {
6253 name,
6254 start,
6255 end
6256 } of this.times) {
6257 outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
6258 }
6259 return outBuf.join("");
6260 }
6261 }
6262 function isValidFetchUrl(url, baseUrl) {
6263 try {
6264 const {
6265 protocol
6266 } = baseUrl ? new URL(url, baseUrl) : new URL(url);
6267 return protocol === "http:" || protocol === "https:";
6268 } catch {
6269 return false;
6270 }
6271 }
6272 function noContextMenu(e) {
6273 e.preventDefault();
6274 }
6275 function deprecated(details) {
6276 console.log("Deprecated API usage: " + details);
6277 }
6278 let pdfDateStringRegex;
6279 class PDFDateString {
6280 static toDateObject(input) {
6281 if (!input || typeof input !== "string") {
6282 return null;
6283 }
6284 pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
6285 const matches = pdfDateStringRegex.exec(input);
6286 if (!matches) {
6287 return null;
6288 }
6289 const year = parseInt(matches[1], 10);
6290 let month = parseInt(matches[2], 10);
6291 month = month >= 1 && month <= 12 ? month - 1 : 0;
6292 let day = parseInt(matches[3], 10);
6293 day = day >= 1 && day <= 31 ? day : 1;
6294 let hour = parseInt(matches[4], 10);
6295 hour = hour >= 0 && hour <= 23 ? hour : 0;
6296 let minute = parseInt(matches[5], 10);
6297 minute = minute >= 0 && minute <= 59 ? minute : 0;
6298 let second = parseInt(matches[6], 10);
6299 second = second >= 0 && second <= 59 ? second : 0;
6300 const universalTimeRelation = matches[7] || "Z";
6301 let offsetHour = parseInt(matches[8], 10);
6302 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
6303 let offsetMinute = parseInt(matches[9], 10) || 0;
6304 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
6305 if (universalTimeRelation === "-") {
6306 hour += offsetHour;
6307 minute += offsetMinute;
6308 } else if (universalTimeRelation === "+") {
6309 hour -= offsetHour;
6310 minute -= offsetMinute;
6311 }
6312 return new Date(Date.UTC(year, month, day, hour, minute, second));
6313 }
6314 }
6315 function getXfaPageViewport(xfaPage, {
6316 scale = 1,
6317 rotation = 0
6318 }) {
6319 const {
6320 width,
6321 height
6322 } = xfaPage.attributes.style;
6323 const viewBox = [0, 0, parseInt(width), parseInt(height)];
6324 return new PageViewport({
6325 viewBox,
6326 scale,
6327 rotation
6328 });
6329 }
6330 function getRGB(color) {
6331 if (color.startsWith("#")) {
6332 const colorRGB = parseInt(color.slice(1), 16);
6333 return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
6334 }
6335 if (color.startsWith("rgb(")) {
6336 return color.slice(4, -1).split(",").map(x => parseInt(x));
6337 }
6338 if (color.startsWith("rgba(")) {
6339 return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
6340 }
6341 warn(`Not a valid color format: "${color}"`);
6342 return [0, 0, 0];
6343 }
6344 function getColorValues(colors) {
6345 const span = document.createElement("span");
6346 span.style.visibility = "hidden";
6347 document.body.append(span);
6348 for (const name of colors.keys()) {
6349 span.style.color = name;
6350 const computedColor = window.getComputedStyle(span).color;
6351 colors.set(name, getRGB(computedColor));
6352 }
6353 span.remove();
6354 }
6355 function getCurrentTransform(ctx) {
6356 const {
6357 a,
6358 b,
6359 c,
6360 d,
6361 e,
6362 f
6363 } = ctx.getTransform();
6364 return [a, b, c, d, e, f];
6365 }
6366 function getCurrentTransformInverse(ctx) {
6367 const {
6368 a,
6369 b,
6370 c,
6371 d,
6372 e,
6373 f
6374 } = ctx.getTransform().invertSelf();
6375 return [a, b, c, d, e, f];
6376 }
6377 function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
6378 if (viewport instanceof PageViewport) {
6379 const {
6380 pageWidth,
6381 pageHeight
6382 } = viewport.rawDims;
6383 const {
6384 style
6385 } = div;
6386 const useRound = util_FeatureTest.isCSSRoundSupported;
6387 const w = `var(--scale-factor) * ${pageWidth}px`,
6388 h = `var(--scale-factor) * ${pageHeight}px`;
6389 const widthStr = useRound ? `round(${w}, 1px)` : `calc(${w})`,
6390 heightStr = useRound ? `round(${h}, 1px)` : `calc(${h})`;
6391 if (!mustFlip || viewport.rotation % 180 === 0) {
6392 style.width = widthStr;
6393 style.height = heightStr;
6394 } else {
6395 style.width = heightStr;
6396 style.height = widthStr;
6397 }
6398 }
6399 if (mustRotate) {
6400 div.setAttribute("data-main-rotation", viewport.rotation);
6401 }
6402 }
6403
6404 ;// CONCATENATED MODULE: ./src/display/editor/toolbar.js
6405
6406 class EditorToolbar {
6407 #toolbar = null;
6408 #colorPicker = null;
6409 #editor;
6410 #buttons = null;
6411 constructor(editor) {
6412 this.#editor = editor;
6413 }
6414 render() {
6415 const editToolbar = this.#toolbar = document.createElement("div");
6416 editToolbar.className = "editToolbar";
6417 editToolbar.setAttribute("role", "toolbar");
6418 editToolbar.addEventListener("contextmenu", noContextMenu);
6419 editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown);
6420 const buttons = this.#buttons = document.createElement("div");
6421 buttons.className = "buttons";
6422 editToolbar.append(buttons);
6423 const position = this.#editor.toolbarPosition;
6424 if (position) {
6425 const {
6426 style
6427 } = editToolbar;
6428 const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
6429 style.insetInlineEnd = `${100 * x}%`;
6430 style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
6431 }
6432 this.#addDeleteButton();
6433 return editToolbar;
6434 }
6435 static #pointerDown(e) {
6436 e.stopPropagation();
6437 }
6438 #focusIn(e) {
6439 this.#editor._focusEventsAllowed = false;
6440 e.preventDefault();
6441 e.stopPropagation();
6442 }
6443 #focusOut(e) {
6444 this.#editor._focusEventsAllowed = true;
6445 e.preventDefault();
6446 e.stopPropagation();
6447 }
6448 #addListenersToElement(element) {
6449 element.addEventListener("focusin", this.#focusIn.bind(this), {
6450 capture: true
6451 });
6452 element.addEventListener("focusout", this.#focusOut.bind(this), {
6453 capture: true
6454 });
6455 element.addEventListener("contextmenu", noContextMenu);
6456 }
6457 hide() {
6458 this.#toolbar.classList.add("hidden");
6459 this.#colorPicker?.hideDropdown();
6460 }
6461 show() {
6462 this.#toolbar.classList.remove("hidden");
6463 }
6464 #addDeleteButton() {
6465 const button = document.createElement("button");
6466 button.className = "delete";
6467 button.tabIndex = 0;
6468 button.setAttribute("data-l10n-id", `pdfjs-editor-remove-${this.#editor.editorType}-button`);
6469 this.#addListenersToElement(button);
6470 button.addEventListener("click", e => {
6471 this.#editor._uiManager.delete();
6472 });
6473 this.#buttons.append(button);
6474 }
6475 get #divider() {
6476 const divider = document.createElement("div");
6477 divider.className = "divider";
6478 return divider;
6479 }
6480 addAltTextButton(button) {
6481 this.#addListenersToElement(button);
6482 this.#buttons.prepend(button, this.#divider);
6483 }
6484 addColorPicker(colorPicker) {
6485 this.#colorPicker = colorPicker;
6486 const button = colorPicker.renderButton();
6487 this.#addListenersToElement(button);
6488 this.#buttons.prepend(button, this.#divider);
6489 }
6490 remove() {
6491 this.#toolbar.remove();
6492 this.#colorPicker?.destroy();
6493 this.#colorPicker = null;
6494 }
6495 }
6496 class HighlightToolbar {
6497 #buttons = null;
6498 #toolbar = null;
6499 #uiManager;
6500 constructor(uiManager) {
6501 this.#uiManager = uiManager;
6502 }
6503 #render() {
6504 const editToolbar = this.#toolbar = document.createElement("div");
6505 editToolbar.className = "editToolbar";
6506 editToolbar.setAttribute("role", "toolbar");
6507 editToolbar.addEventListener("contextmenu", noContextMenu);
6508 const buttons = this.#buttons = document.createElement("div");
6509 buttons.className = "buttons";
6510 editToolbar.append(buttons);
6511 this.#addHighlightButton();
6512 return editToolbar;
6513 }
6514 #getLastPoint(boxes, isLTR) {
6515 let lastY = 0;
6516 let lastX = 0;
6517 for (const box of boxes) {
6518 const y = box.y + box.height;
6519 if (y < lastY) {
6520 continue;
6521 }
6522 const x = box.x + (isLTR ? box.width : 0);
6523 if (y > lastY) {
6524 lastX = x;
6525 lastY = y;
6526 continue;
6527 }
6528 if (isLTR) {
6529 if (x > lastX) {
6530 lastX = x;
6531 }
6532 } else if (x < lastX) {
6533 lastX = x;
6534 }
6535 }
6536 return [isLTR ? 1 - lastX : lastX, lastY];
6537 }
6538 show(parent, boxes, isLTR) {
6539 const [x, y] = this.#getLastPoint(boxes, isLTR);
6540 const {
6541 style
6542 } = this.#toolbar ||= this.#render();
6543 parent.append(this.#toolbar);
6544 style.insetInlineEnd = `${100 * x}%`;
6545 style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
6546 }
6547 hide() {
6548 this.#toolbar.remove();
6549 }
6550 #addHighlightButton() {
6551 const button = document.createElement("button");
6552 button.className = "highlightButton";
6553 button.tabIndex = 0;
6554 button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
6555 const span = document.createElement("span");
6556 button.append(span);
6557 span.className = "visuallyHidden";
6558 span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
6559 button.addEventListener("contextmenu", noContextMenu);
6560 button.addEventListener("click", () => {
6561 this.#uiManager.highlightSelection("floating_button");
6562 });
6563 this.#buttons.append(button);
6564 }
6565 }
6566
6567 ;// CONCATENATED MODULE: ./src/display/editor/tools.js
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590 function bindEvents(obj, element, names) {
6591 for (const name of names) {
6592 element.addEventListener(name, obj[name].bind(obj));
6593 }
6594 }
6595 function opacityToHex(opacity) {
6596 return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
6597 }
6598 class IdManager {
6599 #id = 0;
6600 get id() {
6601 return `${AnnotationEditorPrefix}${this.#id++}`;
6602 }
6603 }
6604 class ImageManager {
6605 #baseId = getUuid();
6606 #id = 0;
6607 #cache = null;
6608 static get _isSVGFittingCanvas() {
6609 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>`;
6610 const canvas = new OffscreenCanvas(1, 3);
6611 const ctx = canvas.getContext("2d");
6612 const image = new Image();
6613 image.src = svg;
6614 const promise = image.decode().then(() => {
6615 ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
6616 return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
6617 });
6618 return shadow(this, "_isSVGFittingCanvas", promise);
6619 }
6620 async #get(key, rawData) {
6621 this.#cache ||= new Map();
6622 let data = this.#cache.get(key);
6623 if (data === null) {
6624 return null;
6625 }
6626 if (data?.bitmap) {
6627 data.refCounter += 1;
6628 return data;
6629 }
6630 try {
6631 data ||= {
6632 bitmap: null,
6633 id: `image_${this.#baseId}_${this.#id++}`,
6634 refCounter: 0,
6635 isSvg: false
6636 };
6637 let image;
6638 if (typeof rawData === "string") {
6639 data.url = rawData;
6640 image = await fetchData(rawData, "blob");
6641 } else {
6642 image = data.file = rawData;
6643 }
6644 if (image.type === "image/svg+xml") {
6645 const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
6646 const fileReader = new FileReader();
6647 const imageElement = new Image();
6648 const imagePromise = new Promise((resolve, reject) => {
6649 imageElement.onload = () => {
6650 data.bitmap = imageElement;
6651 data.isSvg = true;
6652 resolve();
6653 };
6654 fileReader.onload = async () => {
6655 const url = data.svgUrl = fileReader.result;
6656 imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
6657 };
6658 imageElement.onerror = fileReader.onerror = reject;
6659 });
6660 fileReader.readAsDataURL(image);
6661 await imagePromise;
6662 } else {
6663 data.bitmap = await createImageBitmap(image);
6664 }
6665 data.refCounter = 1;
6666 } catch (e) {
6667 console.error(e);
6668 data = null;
6669 }
6670 this.#cache.set(key, data);
6671 if (data) {
6672 this.#cache.set(data.id, data);
6673 }
6674 return data;
6675 }
6676 async getFromFile(file) {
6677 const {
6678 lastModified,
6679 name,
6680 size,
6681 type
6682 } = file;
6683 return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
6684 }
6685 async getFromUrl(url) {
6686 return this.#get(url, url);
6687 }
6688 async getFromId(id) {
6689 this.#cache ||= new Map();
6690 const data = this.#cache.get(id);
6691 if (!data) {
6692 return null;
6693 }
6694 if (data.bitmap) {
6695 data.refCounter += 1;
6696 return data;
6697 }
6698 if (data.file) {
6699 return this.getFromFile(data.file);
6700 }
6701 return this.getFromUrl(data.url);
6702 }
6703 getSvgUrl(id) {
6704 const data = this.#cache.get(id);
6705 if (!data?.isSvg) {
6706 return null;
6707 }
6708 return data.svgUrl;
6709 }
6710 deleteId(id) {
6711 this.#cache ||= new Map();
6712 const data = this.#cache.get(id);
6713 if (!data) {
6714 return;
6715 }
6716 data.refCounter -= 1;
6717 if (data.refCounter !== 0) {
6718 return;
6719 }
6720 data.bitmap = null;
6721 }
6722 isValidId(id) {
6723 return id.startsWith(`image_${this.#baseId}_`);
6724 }
6725 }
6726 class CommandManager {
6727 #commands = [];
6728 #locked = false;
6729 #maxSize;
6730 #position = -1;
6731 constructor(maxSize = 128) {
6732 this.#maxSize = maxSize;
6733 }
6734 add({
6735 cmd,
6736 undo,
6737 post,
6738 mustExec,
6739 type = NaN,
6740 overwriteIfSameType = false,
6741 keepUndo = false
6742 }) {
6743 if (mustExec) {
6744 cmd();
6745 }
6746 if (this.#locked) {
6747 return;
6748 }
6749 const save = {
6750 cmd,
6751 undo,
6752 post,
6753 type
6754 };
6755 if (this.#position === -1) {
6756 if (this.#commands.length > 0) {
6757 this.#commands.length = 0;
6758 }
6759 this.#position = 0;
6760 this.#commands.push(save);
6761 return;
6762 }
6763 if (overwriteIfSameType && this.#commands[this.#position].type === type) {
6764 if (keepUndo) {
6765 save.undo = this.#commands[this.#position].undo;
6766 }
6767 this.#commands[this.#position] = save;
6768 return;
6769 }
6770 const next = this.#position + 1;
6771 if (next === this.#maxSize) {
6772 this.#commands.splice(0, 1);
6773 } else {
6774 this.#position = next;
6775 if (next < this.#commands.length) {
6776 this.#commands.splice(next);
6777 }
6778 }
6779 this.#commands.push(save);
6780 }
6781 undo() {
6782 if (this.#position === -1) {
6783 return;
6784 }
6785 this.#locked = true;
6786 const {
6787 undo,
6788 post
6789 } = this.#commands[this.#position];
6790 undo();
6791 post?.();
6792 this.#locked = false;
6793 this.#position -= 1;
6794 }
6795 redo() {
6796 if (this.#position < this.#commands.length - 1) {
6797 this.#position += 1;
6798 this.#locked = true;
6799 const {
6800 cmd,
6801 post
6802 } = this.#commands[this.#position];
6803 cmd();
6804 post?.();
6805 this.#locked = false;
6806 }
6807 }
6808 hasSomethingToUndo() {
6809 return this.#position !== -1;
6810 }
6811 hasSomethingToRedo() {
6812 return this.#position < this.#commands.length - 1;
6813 }
6814 destroy() {
6815 this.#commands = null;
6816 }
6817 }
6818 class KeyboardManager {
6819 constructor(callbacks) {
6820 this.buffer = [];
6821 this.callbacks = new Map();
6822 this.allKeys = new Set();
6823 const {
6824 isMac
6825 } = util_FeatureTest.platform;
6826 for (const [keys, callback, options = {}] of callbacks) {
6827 for (const key of keys) {
6828 const isMacKey = key.startsWith("mac+");
6829 if (isMac && isMacKey) {
6830 this.callbacks.set(key.slice(4), {
6831 callback,
6832 options
6833 });
6834 this.allKeys.add(key.split("+").at(-1));
6835 } else if (!isMac && !isMacKey) {
6836 this.callbacks.set(key, {
6837 callback,
6838 options
6839 });
6840 this.allKeys.add(key.split("+").at(-1));
6841 }
6842 }
6843 }
6844 }
6845 #serialize(event) {
6846 if (event.altKey) {
6847 this.buffer.push("alt");
6848 }
6849 if (event.ctrlKey) {
6850 this.buffer.push("ctrl");
6851 }
6852 if (event.metaKey) {
6853 this.buffer.push("meta");
6854 }
6855 if (event.shiftKey) {
6856 this.buffer.push("shift");
6857 }
6858 this.buffer.push(event.key);
6859 const str = this.buffer.join("+");
6860 this.buffer.length = 0;
6861 return str;
6862 }
6863 exec(self, event) {
6864 if (!this.allKeys.has(event.key)) {
6865 return;
6866 }
6867 const info = this.callbacks.get(this.#serialize(event));
6868 if (!info) {
6869 return;
6870 }
6871 const {
6872 callback,
6873 options: {
6874 bubbles = false,
6875 args = [],
6876 checker = null
6877 }
6878 } = info;
6879 if (checker && !checker(self, event)) {
6880 return;
6881 }
6882 callback.bind(self, ...args, event)();
6883 if (!bubbles) {
6884 event.stopPropagation();
6885 event.preventDefault();
6886 }
6887 }
6888 }
6889 class ColorManager {
6890 static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
6891 get _colors() {
6892 const colors = new Map([["CanvasText", null], ["Canvas", null]]);
6893 getColorValues(colors);
6894 return shadow(this, "_colors", colors);
6895 }
6896 convert(color) {
6897 const rgb = getRGB(color);
6898 if (!window.matchMedia("(forced-colors: active)").matches) {
6899 return rgb;
6900 }
6901 for (const [name, RGB] of this._colors) {
6902 if (RGB.every((x, i) => x === rgb[i])) {
6903 return ColorManager._colorsMapping.get(name);
6904 }
6905 }
6906 return rgb;
6907 }
6908 getHexCode(name) {
6909 const rgb = this._colors.get(name);
6910 if (!rgb) {
6911 return name;
6912 }
6913 return Util.makeHexColor(...rgb);
6914 }
6915 }
6916 class AnnotationEditorUIManager {
6917 #activeEditor = null;
6918 #allEditors = new Map();
6919 #allLayers = new Map();
6920 #altTextManager = null;
6921 #annotationStorage = null;
6922 #changedExistingAnnotations = null;
6923 #commandManager = new CommandManager();
6924 #currentPageIndex = 0;
6925 #deletedAnnotationsElementIds = new Set();
6926 #draggingEditors = null;
6927 #editorTypes = null;
6928 #editorsToRescale = new Set();
6929 #enableHighlightFloatingButton = false;
6930 #filterFactory = null;
6931 #focusMainContainerTimeoutId = null;
6932 #highlightColors = null;
6933 #highlightWhenShiftUp = false;
6934 #highlightToolbar = null;
6935 #idManager = new IdManager();
6936 #isEnabled = false;
6937 #isWaiting = false;
6938 #lastActiveElement = null;
6939 #mainHighlightColorPicker = null;
6940 #mlManager = null;
6941 #mode = AnnotationEditorType.NONE;
6942 #selectedEditors = new Set();
6943 #selectedTextNode = null;
6944 #pageColors = null;
6945 #showAllStates = null;
6946 #boundBlur = this.blur.bind(this);
6947 #boundFocus = this.focus.bind(this);
6948 #boundCopy = this.copy.bind(this);
6949 #boundCut = this.cut.bind(this);
6950 #boundPaste = this.paste.bind(this);
6951 #boundKeydown = this.keydown.bind(this);
6952 #boundKeyup = this.keyup.bind(this);
6953 #boundOnEditingAction = this.onEditingAction.bind(this);
6954 #boundOnPageChanging = this.onPageChanging.bind(this);
6955 #boundOnScaleChanging = this.onScaleChanging.bind(this);
6956 #boundSelectionChange = this.#selectionChange.bind(this);
6957 #boundOnRotationChanging = this.onRotationChanging.bind(this);
6958 #previousStates = {
6959 isEditing: false,
6960 isEmpty: true,
6961 hasSomethingToUndo: false,
6962 hasSomethingToRedo: false,
6963 hasSelectedEditor: false,
6964 hasSelectedText: false
6965 };
6966 #translation = [0, 0];
6967 #translationTimeoutId = null;
6968 #container = null;
6969 #viewer = null;
6970 static TRANSLATE_SMALL = 1;
6971 static TRANSLATE_BIG = 10;
6972 static get _keyboardManager() {
6973 const proto = AnnotationEditorUIManager.prototype;
6974 const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
6975 const textInputChecker = (_self, {
6976 target: el
6977 }) => {
6978 if (el instanceof HTMLInputElement) {
6979 const {
6980 type
6981 } = el;
6982 return type !== "text" && type !== "number";
6983 }
6984 return true;
6985 };
6986 const small = this.TRANSLATE_SMALL;
6987 const big = this.TRANSLATE_BIG;
6988 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
6989 checker: textInputChecker
6990 }], [["ctrl+z", "mac+meta+z"], proto.undo, {
6991 checker: textInputChecker
6992 }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
6993 checker: textInputChecker
6994 }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
6995 checker: textInputChecker
6996 }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
6997 checker: (self, {
6998 target: el
6999 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
7000 }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
7001 checker: (self, {
7002 target: el
7003 }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
7004 }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
7005 args: [-small, 0],
7006 checker: arrowChecker
7007 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
7008 args: [-big, 0],
7009 checker: arrowChecker
7010 }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
7011 args: [small, 0],
7012 checker: arrowChecker
7013 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
7014 args: [big, 0],
7015 checker: arrowChecker
7016 }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
7017 args: [0, -small],
7018 checker: arrowChecker
7019 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
7020 args: [0, -big],
7021 checker: arrowChecker
7022 }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
7023 args: [0, small],
7024 checker: arrowChecker
7025 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
7026 args: [0, big],
7027 checker: arrowChecker
7028 }]]));
7029 }
7030 constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, mlManager) {
7031 this.#container = container;
7032 this.#viewer = viewer;
7033 this.#altTextManager = altTextManager;
7034 this._eventBus = eventBus;
7035 this._eventBus._on("editingaction", this.#boundOnEditingAction);
7036 this._eventBus._on("pagechanging", this.#boundOnPageChanging);
7037 this._eventBus._on("scalechanging", this.#boundOnScaleChanging);
7038 this._eventBus._on("rotationchanging", this.#boundOnRotationChanging);
7039 this.#addSelectionListener();
7040 this.#addKeyboardManager();
7041 this.#annotationStorage = pdfDocument.annotationStorage;
7042 this.#filterFactory = pdfDocument.filterFactory;
7043 this.#pageColors = pageColors;
7044 this.#highlightColors = highlightColors || null;
7045 this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
7046 this.#mlManager = mlManager || null;
7047 this.viewParameters = {
7048 realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
7049 rotation: 0
7050 };
7051 this.isShiftKeyDown = false;
7052 }
7053 destroy() {
7054 this.#removeKeyboardManager();
7055 this.#removeFocusManager();
7056 this._eventBus._off("editingaction", this.#boundOnEditingAction);
7057 this._eventBus._off("pagechanging", this.#boundOnPageChanging);
7058 this._eventBus._off("scalechanging", this.#boundOnScaleChanging);
7059 this._eventBus._off("rotationchanging", this.#boundOnRotationChanging);
7060 for (const layer of this.#allLayers.values()) {
7061 layer.destroy();
7062 }
7063 this.#allLayers.clear();
7064 this.#allEditors.clear();
7065 this.#editorsToRescale.clear();
7066 this.#activeEditor = null;
7067 this.#selectedEditors.clear();
7068 this.#commandManager.destroy();
7069 this.#altTextManager?.destroy();
7070 this.#highlightToolbar?.hide();
7071 this.#highlightToolbar = null;
7072 if (this.#focusMainContainerTimeoutId) {
7073 clearTimeout(this.#focusMainContainerTimeoutId);
7074 this.#focusMainContainerTimeoutId = null;
7075 }
7076 if (this.#translationTimeoutId) {
7077 clearTimeout(this.#translationTimeoutId);
7078 this.#translationTimeoutId = null;
7079 }
7080 this.#removeSelectionListener();
7081 }
7082 async mlGuess(data) {
7083 return this.#mlManager?.guess(data) || null;
7084 }
7085 get hasMLManager() {
7086 return !!this.#mlManager;
7087 }
7088 get hcmFilter() {
7089 return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
7090 }
7091 get direction() {
7092 return shadow(this, "direction", getComputedStyle(this.#container).direction);
7093 }
7094 get highlightColors() {
7095 return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
7096 }
7097 get highlightColorNames() {
7098 return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
7099 }
7100 setMainHighlightColorPicker(colorPicker) {
7101 this.#mainHighlightColorPicker = colorPicker;
7102 }
7103 editAltText(editor) {
7104 this.#altTextManager?.editAltText(this, editor);
7105 }
7106 onPageChanging({
7107 pageNumber
7108 }) {
7109 this.#currentPageIndex = pageNumber - 1;
7110 }
7111 focusMainContainer() {
7112 this.#container.focus();
7113 }
7114 findParent(x, y) {
7115 for (const layer of this.#allLayers.values()) {
7116 const {
7117 x: layerX,
7118 y: layerY,
7119 width,
7120 height
7121 } = layer.div.getBoundingClientRect();
7122 if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
7123 return layer;
7124 }
7125 }
7126 return null;
7127 }
7128 disableUserSelect(value = false) {
7129 this.#viewer.classList.toggle("noUserSelect", value);
7130 }
7131 addShouldRescale(editor) {
7132 this.#editorsToRescale.add(editor);
7133 }
7134 removeShouldRescale(editor) {
7135 this.#editorsToRescale.delete(editor);
7136 }
7137 onScaleChanging({
7138 scale
7139 }) {
7140 this.commitOrRemove();
7141 this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
7142 for (const editor of this.#editorsToRescale) {
7143 editor.onScaleChanging();
7144 }
7145 }
7146 onRotationChanging({
7147 pagesRotation
7148 }) {
7149 this.commitOrRemove();
7150 this.viewParameters.rotation = pagesRotation;
7151 }
7152 #getAnchorElementForSelection({
7153 anchorNode
7154 }) {
7155 return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
7156 }
7157 highlightSelection(methodOfCreation = "") {
7158 const selection = document.getSelection();
7159 if (!selection || selection.isCollapsed) {
7160 return;
7161 }
7162 const {
7163 anchorNode,
7164 anchorOffset,
7165 focusNode,
7166 focusOffset
7167 } = selection;
7168 const text = selection.toString();
7169 const anchorElement = this.#getAnchorElementForSelection(selection);
7170 const textLayer = anchorElement.closest(".textLayer");
7171 const boxes = this.getSelectionBoxes(textLayer);
7172 if (!boxes) {
7173 return;
7174 }
7175 selection.empty();
7176 if (this.#mode === AnnotationEditorType.NONE) {
7177 this._eventBus.dispatch("showannotationeditorui", {
7178 source: this,
7179 mode: AnnotationEditorType.HIGHLIGHT
7180 });
7181 this.showAllEditors("highlight", true, true);
7182 }
7183 for (const layer of this.#allLayers.values()) {
7184 if (layer.hasTextLayer(textLayer)) {
7185 layer.createAndAddNewEditor({
7186 x: 0,
7187 y: 0
7188 }, false, {
7189 methodOfCreation,
7190 boxes,
7191 anchorNode,
7192 anchorOffset,
7193 focusNode,
7194 focusOffset,
7195 text
7196 });
7197 break;
7198 }
7199 }
7200 }
7201 #displayHighlightToolbar() {
7202 const selection = document.getSelection();
7203 if (!selection || selection.isCollapsed) {
7204 return;
7205 }
7206 const anchorElement = this.#getAnchorElementForSelection(selection);
7207 const textLayer = anchorElement.closest(".textLayer");
7208 const boxes = this.getSelectionBoxes(textLayer);
7209 if (!boxes) {
7210 return;
7211 }
7212 this.#highlightToolbar ||= new HighlightToolbar(this);
7213 this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
7214 }
7215 addToAnnotationStorage(editor) {
7216 if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
7217 this.#annotationStorage.setValue(editor.id, editor);
7218 }
7219 }
7220 #selectionChange() {
7221 const selection = document.getSelection();
7222 if (!selection || selection.isCollapsed) {
7223 if (this.#selectedTextNode) {
7224 this.#highlightToolbar?.hide();
7225 this.#selectedTextNode = null;
7226 this.#dispatchUpdateStates({
7227 hasSelectedText: false
7228 });
7229 }
7230 return;
7231 }
7232 const {
7233 anchorNode
7234 } = selection;
7235 if (anchorNode === this.#selectedTextNode) {
7236 return;
7237 }
7238 const anchorElement = this.#getAnchorElementForSelection(selection);
7239 const textLayer = anchorElement.closest(".textLayer");
7240 if (!textLayer) {
7241 if (this.#selectedTextNode) {
7242 this.#highlightToolbar?.hide();
7243 this.#selectedTextNode = null;
7244 this.#dispatchUpdateStates({
7245 hasSelectedText: false
7246 });
7247 }
7248 return;
7249 }
7250 this.#highlightToolbar?.hide();
7251 this.#selectedTextNode = anchorNode;
7252 this.#dispatchUpdateStates({
7253 hasSelectedText: true
7254 });
7255 if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
7256 return;
7257 }
7258 if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
7259 this.showAllEditors("highlight", true, true);
7260 }
7261 this.#highlightWhenShiftUp = this.isShiftKeyDown;
7262 if (!this.isShiftKeyDown) {
7263 const pointerup = e => {
7264 if (e.type === "pointerup" && e.button !== 0) {
7265 return;
7266 }
7267 window.removeEventListener("pointerup", pointerup);
7268 window.removeEventListener("blur", pointerup);
7269 if (e.type === "pointerup") {
7270 this.#onSelectEnd("main_toolbar");
7271 }
7272 };
7273 window.addEventListener("pointerup", pointerup);
7274 window.addEventListener("blur", pointerup);
7275 }
7276 }
7277 #onSelectEnd(methodOfCreation = "") {
7278 if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
7279 this.highlightSelection(methodOfCreation);
7280 } else if (this.#enableHighlightFloatingButton) {
7281 this.#displayHighlightToolbar();
7282 }
7283 }
7284 #addSelectionListener() {
7285 document.addEventListener("selectionchange", this.#boundSelectionChange);
7286 }
7287 #removeSelectionListener() {
7288 document.removeEventListener("selectionchange", this.#boundSelectionChange);
7289 }
7290 #addFocusManager() {
7291 window.addEventListener("focus", this.#boundFocus);
7292 window.addEventListener("blur", this.#boundBlur);
7293 }
7294 #removeFocusManager() {
7295 window.removeEventListener("focus", this.#boundFocus);
7296 window.removeEventListener("blur", this.#boundBlur);
7297 }
7298 blur() {
7299 this.isShiftKeyDown = false;
7300 if (this.#highlightWhenShiftUp) {
7301 this.#highlightWhenShiftUp = false;
7302 this.#onSelectEnd("main_toolbar");
7303 }
7304 if (!this.hasSelection) {
7305 return;
7306 }
7307 const {
7308 activeElement
7309 } = document;
7310 for (const editor of this.#selectedEditors) {
7311 if (editor.div.contains(activeElement)) {
7312 this.#lastActiveElement = [editor, activeElement];
7313 editor._focusEventsAllowed = false;
7314 break;
7315 }
7316 }
7317 }
7318 focus() {
7319 if (!this.#lastActiveElement) {
7320 return;
7321 }
7322 const [lastEditor, lastActiveElement] = this.#lastActiveElement;
7323 this.#lastActiveElement = null;
7324 lastActiveElement.addEventListener("focusin", () => {
7325 lastEditor._focusEventsAllowed = true;
7326 }, {
7327 once: true
7328 });
7329 lastActiveElement.focus();
7330 }
7331 #addKeyboardManager() {
7332 window.addEventListener("keydown", this.#boundKeydown);
7333 window.addEventListener("keyup", this.#boundKeyup);
7334 }
7335 #removeKeyboardManager() {
7336 window.removeEventListener("keydown", this.#boundKeydown);
7337 window.removeEventListener("keyup", this.#boundKeyup);
7338 }
7339 #addCopyPasteListeners() {
7340 document.addEventListener("copy", this.#boundCopy);
7341 document.addEventListener("cut", this.#boundCut);
7342 document.addEventListener("paste", this.#boundPaste);
7343 }
7344 #removeCopyPasteListeners() {
7345 document.removeEventListener("copy", this.#boundCopy);
7346 document.removeEventListener("cut", this.#boundCut);
7347 document.removeEventListener("paste", this.#boundPaste);
7348 }
7349 addEditListeners() {
7350 this.#addKeyboardManager();
7351 this.#addCopyPasteListeners();
7352 }
7353 removeEditListeners() {
7354 this.#removeKeyboardManager();
7355 this.#removeCopyPasteListeners();
7356 }
7357 copy(event) {
7358 event.preventDefault();
7359 this.#activeEditor?.commitOrRemove();
7360 if (!this.hasSelection) {
7361 return;
7362 }
7363 const editors = [];
7364 for (const editor of this.#selectedEditors) {
7365 const serialized = editor.serialize(true);
7366 if (serialized) {
7367 editors.push(serialized);
7368 }
7369 }
7370 if (editors.length === 0) {
7371 return;
7372 }
7373 event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
7374 }
7375 cut(event) {
7376 this.copy(event);
7377 this.delete();
7378 }
7379 paste(event) {
7380 event.preventDefault();
7381 const {
7382 clipboardData
7383 } = event;
7384 for (const item of clipboardData.items) {
7385 for (const editorType of this.#editorTypes) {
7386 if (editorType.isHandlingMimeForPasting(item.type)) {
7387 editorType.paste(item, this.currentLayer);
7388 return;
7389 }
7390 }
7391 }
7392 let data = clipboardData.getData("application/pdfjs");
7393 if (!data) {
7394 return;
7395 }
7396 try {
7397 data = JSON.parse(data);
7398 } catch (ex) {
7399 warn(`paste: "${ex.message}".`);
7400 return;
7401 }
7402 if (!Array.isArray(data)) {
7403 return;
7404 }
7405 this.unselectAll();
7406 const layer = this.currentLayer;
7407 try {
7408 const newEditors = [];
7409 for (const editor of data) {
7410 const deserializedEditor = layer.deserialize(editor);
7411 if (!deserializedEditor) {
7412 return;
7413 }
7414 newEditors.push(deserializedEditor);
7415 }
7416 const cmd = () => {
7417 for (const editor of newEditors) {
7418 this.#addEditorToLayer(editor);
7419 }
7420 this.#selectEditors(newEditors);
7421 };
7422 const undo = () => {
7423 for (const editor of newEditors) {
7424 editor.remove();
7425 }
7426 };
7427 this.addCommands({
7428 cmd,
7429 undo,
7430 mustExec: true
7431 });
7432 } catch (ex) {
7433 warn(`paste: "${ex.message}".`);
7434 }
7435 }
7436 keydown(event) {
7437 if (!this.isShiftKeyDown && event.key === "Shift") {
7438 this.isShiftKeyDown = true;
7439 }
7440 if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
7441 AnnotationEditorUIManager._keyboardManager.exec(this, event);
7442 }
7443 }
7444 keyup(event) {
7445 if (this.isShiftKeyDown && event.key === "Shift") {
7446 this.isShiftKeyDown = false;
7447 if (this.#highlightWhenShiftUp) {
7448 this.#highlightWhenShiftUp = false;
7449 this.#onSelectEnd("main_toolbar");
7450 }
7451 }
7452 }
7453 onEditingAction({
7454 name
7455 }) {
7456 switch (name) {
7457 case "undo":
7458 case "redo":
7459 case "delete":
7460 case "selectAll":
7461 this[name]();
7462 break;
7463 case "highlightSelection":
7464 this.highlightSelection("context_menu");
7465 break;
7466 }
7467 }
7468 #dispatchUpdateStates(details) {
7469 const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
7470 if (hasChanged) {
7471 this._eventBus.dispatch("annotationeditorstateschanged", {
7472 source: this,
7473 details: Object.assign(this.#previousStates, details)
7474 });
7475 if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
7476 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
7477 }
7478 }
7479 }
7480 #dispatchUpdateUI(details) {
7481 this._eventBus.dispatch("annotationeditorparamschanged", {
7482 source: this,
7483 details
7484 });
7485 }
7486 setEditingState(isEditing) {
7487 if (isEditing) {
7488 this.#addFocusManager();
7489 this.#addCopyPasteListeners();
7490 this.#dispatchUpdateStates({
7491 isEditing: this.#mode !== AnnotationEditorType.NONE,
7492 isEmpty: this.#isEmpty(),
7493 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
7494 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
7495 hasSelectedEditor: false
7496 });
7497 } else {
7498 this.#removeFocusManager();
7499 this.#removeCopyPasteListeners();
7500 this.#dispatchUpdateStates({
7501 isEditing: false
7502 });
7503 this.disableUserSelect(false);
7504 }
7505 }
7506 registerEditorTypes(types) {
7507 if (this.#editorTypes) {
7508 return;
7509 }
7510 this.#editorTypes = types;
7511 for (const editorType of this.#editorTypes) {
7512 this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
7513 }
7514 }
7515 getId() {
7516 return this.#idManager.id;
7517 }
7518 get currentLayer() {
7519 return this.#allLayers.get(this.#currentPageIndex);
7520 }
7521 getLayer(pageIndex) {
7522 return this.#allLayers.get(pageIndex);
7523 }
7524 get currentPageIndex() {
7525 return this.#currentPageIndex;
7526 }
7527 addLayer(layer) {
7528 this.#allLayers.set(layer.pageIndex, layer);
7529 if (this.#isEnabled) {
7530 layer.enable();
7531 } else {
7532 layer.disable();
7533 }
7534 }
7535 removeLayer(layer) {
7536 this.#allLayers.delete(layer.pageIndex);
7537 }
7538 updateMode(mode, editId = null, isFromKeyboard = false) {
7539 if (this.#mode === mode) {
7540 return;
7541 }
7542 this.#mode = mode;
7543 if (mode === AnnotationEditorType.NONE) {
7544 this.setEditingState(false);
7545 this.#disableAll();
7546 return;
7547 }
7548 this.setEditingState(true);
7549 this.#enableAll();
7550 this.unselectAll();
7551 for (const layer of this.#allLayers.values()) {
7552 layer.updateMode(mode);
7553 }
7554 if (!editId && isFromKeyboard) {
7555 this.addNewEditorFromKeyboard();
7556 return;
7557 }
7558 if (!editId) {
7559 return;
7560 }
7561 for (const editor of this.#allEditors.values()) {
7562 if (editor.annotationElementId === editId) {
7563 this.setSelected(editor);
7564 editor.enterInEditMode();
7565 break;
7566 }
7567 }
7568 }
7569 addNewEditorFromKeyboard() {
7570 if (this.currentLayer.canCreateNewEmptyEditor()) {
7571 this.currentLayer.addNewEditor();
7572 }
7573 }
7574 updateToolbar(mode) {
7575 if (mode === this.#mode) {
7576 return;
7577 }
7578 this._eventBus.dispatch("switchannotationeditormode", {
7579 source: this,
7580 mode
7581 });
7582 }
7583 updateParams(type, value) {
7584 if (!this.#editorTypes) {
7585 return;
7586 }
7587 switch (type) {
7588 case AnnotationEditorParamsType.CREATE:
7589 this.currentLayer.addNewEditor();
7590 return;
7591 case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
7592 this.#mainHighlightColorPicker?.updateColor(value);
7593 break;
7594 case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
7595 this._eventBus.dispatch("reporttelemetry", {
7596 source: this,
7597 details: {
7598 type: "editing",
7599 data: {
7600 type: "highlight",
7601 action: "toggle_visibility"
7602 }
7603 }
7604 });
7605 (this.#showAllStates ||= new Map()).set(type, value);
7606 this.showAllEditors("highlight", value);
7607 break;
7608 }
7609 for (const editor of this.#selectedEditors) {
7610 editor.updateParams(type, value);
7611 }
7612 for (const editorType of this.#editorTypes) {
7613 editorType.updateDefaultParams(type, value);
7614 }
7615 }
7616 showAllEditors(type, visible, updateButton = false) {
7617 for (const editor of this.#allEditors.values()) {
7618 if (editor.editorType === type) {
7619 editor.show(visible);
7620 }
7621 }
7622 const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
7623 if (state !== visible) {
7624 this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
7625 }
7626 }
7627 enableWaiting(mustWait = false) {
7628 if (this.#isWaiting === mustWait) {
7629 return;
7630 }
7631 this.#isWaiting = mustWait;
7632 for (const layer of this.#allLayers.values()) {
7633 if (mustWait) {
7634 layer.disableClick();
7635 } else {
7636 layer.enableClick();
7637 }
7638 layer.div.classList.toggle("waiting", mustWait);
7639 }
7640 }
7641 #enableAll() {
7642 if (!this.#isEnabled) {
7643 this.#isEnabled = true;
7644 for (const layer of this.#allLayers.values()) {
7645 layer.enable();
7646 }
7647 for (const editor of this.#allEditors.values()) {
7648 editor.enable();
7649 }
7650 }
7651 }
7652 #disableAll() {
7653 this.unselectAll();
7654 if (this.#isEnabled) {
7655 this.#isEnabled = false;
7656 for (const layer of this.#allLayers.values()) {
7657 layer.disable();
7658 }
7659 for (const editor of this.#allEditors.values()) {
7660 editor.disable();
7661 }
7662 }
7663 }
7664 getEditors(pageIndex) {
7665 const editors = [];
7666 for (const editor of this.#allEditors.values()) {
7667 if (editor.pageIndex === pageIndex) {
7668 editors.push(editor);
7669 }
7670 }
7671 return editors;
7672 }
7673 getEditor(id) {
7674 return this.#allEditors.get(id);
7675 }
7676 addEditor(editor) {
7677 this.#allEditors.set(editor.id, editor);
7678 }
7679 removeEditor(editor) {
7680 if (editor.div.contains(document.activeElement)) {
7681 if (this.#focusMainContainerTimeoutId) {
7682 clearTimeout(this.#focusMainContainerTimeoutId);
7683 }
7684 this.#focusMainContainerTimeoutId = setTimeout(() => {
7685 this.focusMainContainer();
7686 this.#focusMainContainerTimeoutId = null;
7687 }, 0);
7688 }
7689 this.#allEditors.delete(editor.id);
7690 this.unselect(editor);
7691 if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
7692 this.#annotationStorage?.remove(editor.id);
7693 }
7694 }
7695 addDeletedAnnotationElement(editor) {
7696 this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
7697 this.addChangedExistingAnnotation(editor);
7698 editor.deleted = true;
7699 }
7700 isDeletedAnnotationElement(annotationElementId) {
7701 return this.#deletedAnnotationsElementIds.has(annotationElementId);
7702 }
7703 removeDeletedAnnotationElement(editor) {
7704 this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
7705 this.removeChangedExistingAnnotation(editor);
7706 editor.deleted = false;
7707 }
7708 #addEditorToLayer(editor) {
7709 const layer = this.#allLayers.get(editor.pageIndex);
7710 if (layer) {
7711 layer.addOrRebuild(editor);
7712 } else {
7713 this.addEditor(editor);
7714 this.addToAnnotationStorage(editor);
7715 }
7716 }
7717 setActiveEditor(editor) {
7718 if (this.#activeEditor === editor) {
7719 return;
7720 }
7721 this.#activeEditor = editor;
7722 if (editor) {
7723 this.#dispatchUpdateUI(editor.propertiesToUpdate);
7724 }
7725 }
7726 get #lastSelectedEditor() {
7727 let ed = null;
7728 for (ed of this.#selectedEditors) {}
7729 return ed;
7730 }
7731 updateUI(editor) {
7732 if (this.#lastSelectedEditor === editor) {
7733 this.#dispatchUpdateUI(editor.propertiesToUpdate);
7734 }
7735 }
7736 toggleSelected(editor) {
7737 if (this.#selectedEditors.has(editor)) {
7738 this.#selectedEditors.delete(editor);
7739 editor.unselect();
7740 this.#dispatchUpdateStates({
7741 hasSelectedEditor: this.hasSelection
7742 });
7743 return;
7744 }
7745 this.#selectedEditors.add(editor);
7746 editor.select();
7747 this.#dispatchUpdateUI(editor.propertiesToUpdate);
7748 this.#dispatchUpdateStates({
7749 hasSelectedEditor: true
7750 });
7751 }
7752 setSelected(editor) {
7753 for (const ed of this.#selectedEditors) {
7754 if (ed !== editor) {
7755 ed.unselect();
7756 }
7757 }
7758 this.#selectedEditors.clear();
7759 this.#selectedEditors.add(editor);
7760 editor.select();
7761 this.#dispatchUpdateUI(editor.propertiesToUpdate);
7762 this.#dispatchUpdateStates({
7763 hasSelectedEditor: true
7764 });
7765 }
7766 isSelected(editor) {
7767 return this.#selectedEditors.has(editor);
7768 }
7769 get firstSelectedEditor() {
7770 return this.#selectedEditors.values().next().value;
7771 }
7772 unselect(editor) {
7773 editor.unselect();
7774 this.#selectedEditors.delete(editor);
7775 this.#dispatchUpdateStates({
7776 hasSelectedEditor: this.hasSelection
7777 });
7778 }
7779 get hasSelection() {
7780 return this.#selectedEditors.size !== 0;
7781 }
7782 get isEnterHandled() {
7783 return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
7784 }
7785 undo() {
7786 this.#commandManager.undo();
7787 this.#dispatchUpdateStates({
7788 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
7789 hasSomethingToRedo: true,
7790 isEmpty: this.#isEmpty()
7791 });
7792 }
7793 redo() {
7794 this.#commandManager.redo();
7795 this.#dispatchUpdateStates({
7796 hasSomethingToUndo: true,
7797 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
7798 isEmpty: this.#isEmpty()
7799 });
7800 }
7801 addCommands(params) {
7802 this.#commandManager.add(params);
7803 this.#dispatchUpdateStates({
7804 hasSomethingToUndo: true,
7805 hasSomethingToRedo: false,
7806 isEmpty: this.#isEmpty()
7807 });
7808 }
7809 #isEmpty() {
7810 if (this.#allEditors.size === 0) {
7811 return true;
7812 }
7813 if (this.#allEditors.size === 1) {
7814 for (const editor of this.#allEditors.values()) {
7815 return editor.isEmpty();
7816 }
7817 }
7818 return false;
7819 }
7820 delete() {
7821 this.commitOrRemove();
7822 if (!this.hasSelection) {
7823 return;
7824 }
7825 const editors = [...this.#selectedEditors];
7826 const cmd = () => {
7827 for (const editor of editors) {
7828 editor.remove();
7829 }
7830 };
7831 const undo = () => {
7832 for (const editor of editors) {
7833 this.#addEditorToLayer(editor);
7834 }
7835 };
7836 this.addCommands({
7837 cmd,
7838 undo,
7839 mustExec: true
7840 });
7841 }
7842 commitOrRemove() {
7843 this.#activeEditor?.commitOrRemove();
7844 }
7845 hasSomethingToControl() {
7846 return this.#activeEditor || this.hasSelection;
7847 }
7848 #selectEditors(editors) {
7849 for (const editor of this.#selectedEditors) {
7850 editor.unselect();
7851 }
7852 this.#selectedEditors.clear();
7853 for (const editor of editors) {
7854 if (editor.isEmpty()) {
7855 continue;
7856 }
7857 this.#selectedEditors.add(editor);
7858 editor.select();
7859 }
7860 this.#dispatchUpdateStates({
7861 hasSelectedEditor: this.hasSelection
7862 });
7863 }
7864 selectAll() {
7865 for (const editor of this.#selectedEditors) {
7866 editor.commit();
7867 }
7868 this.#selectEditors(this.#allEditors.values());
7869 }
7870 unselectAll() {
7871 if (this.#activeEditor) {
7872 this.#activeEditor.commitOrRemove();
7873 if (this.#mode !== AnnotationEditorType.NONE) {
7874 return;
7875 }
7876 }
7877 if (!this.hasSelection) {
7878 return;
7879 }
7880 for (const editor of this.#selectedEditors) {
7881 editor.unselect();
7882 }
7883 this.#selectedEditors.clear();
7884 this.#dispatchUpdateStates({
7885 hasSelectedEditor: false
7886 });
7887 }
7888 translateSelectedEditors(x, y, noCommit = false) {
7889 if (!noCommit) {
7890 this.commitOrRemove();
7891 }
7892 if (!this.hasSelection) {
7893 return;
7894 }
7895 this.#translation[0] += x;
7896 this.#translation[1] += y;
7897 const [totalX, totalY] = this.#translation;
7898 const editors = [...this.#selectedEditors];
7899 const TIME_TO_WAIT = 1000;
7900 if (this.#translationTimeoutId) {
7901 clearTimeout(this.#translationTimeoutId);
7902 }
7903 this.#translationTimeoutId = setTimeout(() => {
7904 this.#translationTimeoutId = null;
7905 this.#translation[0] = this.#translation[1] = 0;
7906 this.addCommands({
7907 cmd: () => {
7908 for (const editor of editors) {
7909 if (this.#allEditors.has(editor.id)) {
7910 editor.translateInPage(totalX, totalY);
7911 }
7912 }
7913 },
7914 undo: () => {
7915 for (const editor of editors) {
7916 if (this.#allEditors.has(editor.id)) {
7917 editor.translateInPage(-totalX, -totalY);
7918 }
7919 }
7920 },
7921 mustExec: false
7922 });
7923 }, TIME_TO_WAIT);
7924 for (const editor of editors) {
7925 editor.translateInPage(x, y);
7926 }
7927 }
7928 setUpDragSession() {
7929 if (!this.hasSelection) {
7930 return;
7931 }
7932 this.disableUserSelect(true);
7933 this.#draggingEditors = new Map();
7934 for (const editor of this.#selectedEditors) {
7935 this.#draggingEditors.set(editor, {
7936 savedX: editor.x,
7937 savedY: editor.y,
7938 savedPageIndex: editor.pageIndex,
7939 newX: 0,
7940 newY: 0,
7941 newPageIndex: -1
7942 });
7943 }
7944 }
7945 endDragSession() {
7946 if (!this.#draggingEditors) {
7947 return false;
7948 }
7949 this.disableUserSelect(false);
7950 const map = this.#draggingEditors;
7951 this.#draggingEditors = null;
7952 let mustBeAddedInUndoStack = false;
7953 for (const [{
7954 x,
7955 y,
7956 pageIndex
7957 }, value] of map) {
7958 value.newX = x;
7959 value.newY = y;
7960 value.newPageIndex = pageIndex;
7961 mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
7962 }
7963 if (!mustBeAddedInUndoStack) {
7964 return false;
7965 }
7966 const move = (editor, x, y, pageIndex) => {
7967 if (this.#allEditors.has(editor.id)) {
7968 const parent = this.#allLayers.get(pageIndex);
7969 if (parent) {
7970 editor._setParentAndPosition(parent, x, y);
7971 } else {
7972 editor.pageIndex = pageIndex;
7973 editor.x = x;
7974 editor.y = y;
7975 }
7976 }
7977 };
7978 this.addCommands({
7979 cmd: () => {
7980 for (const [editor, {
7981 newX,
7982 newY,
7983 newPageIndex
7984 }] of map) {
7985 move(editor, newX, newY, newPageIndex);
7986 }
7987 },
7988 undo: () => {
7989 for (const [editor, {
7990 savedX,
7991 savedY,
7992 savedPageIndex
7993 }] of map) {
7994 move(editor, savedX, savedY, savedPageIndex);
7995 }
7996 },
7997 mustExec: true
7998 });
7999 return true;
8000 }
8001 dragSelectedEditors(tx, ty) {
8002 if (!this.#draggingEditors) {
8003 return;
8004 }
8005 for (const editor of this.#draggingEditors.keys()) {
8006 editor.drag(tx, ty);
8007 }
8008 }
8009 rebuild(editor) {
8010 if (editor.parent === null) {
8011 const parent = this.getLayer(editor.pageIndex);
8012 if (parent) {
8013 parent.changeParent(editor);
8014 parent.addOrRebuild(editor);
8015 } else {
8016 this.addEditor(editor);
8017 this.addToAnnotationStorage(editor);
8018 editor.rebuild();
8019 }
8020 } else {
8021 editor.parent.addOrRebuild(editor);
8022 }
8023 }
8024 get isEditorHandlingKeyboard() {
8025 return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
8026 }
8027 isActive(editor) {
8028 return this.#activeEditor === editor;
8029 }
8030 getActive() {
8031 return this.#activeEditor;
8032 }
8033 getMode() {
8034 return this.#mode;
8035 }
8036 get imageManager() {
8037 return shadow(this, "imageManager", new ImageManager());
8038 }
8039 getSelectionBoxes(textLayer) {
8040 if (!textLayer) {
8041 return null;
8042 }
8043 const selection = document.getSelection();
8044 for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
8045 if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
8046 return null;
8047 }
8048 }
8049 const {
8050 x: layerX,
8051 y: layerY,
8052 width: parentWidth,
8053 height: parentHeight
8054 } = textLayer.getBoundingClientRect();
8055 let rotator;
8056 switch (textLayer.getAttribute("data-main-rotation")) {
8057 case "90":
8058 rotator = (x, y, w, h) => ({
8059 x: (y - layerY) / parentHeight,
8060 y: 1 - (x + w - layerX) / parentWidth,
8061 width: h / parentHeight,
8062 height: w / parentWidth
8063 });
8064 break;
8065 case "180":
8066 rotator = (x, y, w, h) => ({
8067 x: 1 - (x + w - layerX) / parentWidth,
8068 y: 1 - (y + h - layerY) / parentHeight,
8069 width: w / parentWidth,
8070 height: h / parentHeight
8071 });
8072 break;
8073 case "270":
8074 rotator = (x, y, w, h) => ({
8075 x: 1 - (y + h - layerY) / parentHeight,
8076 y: (x - layerX) / parentWidth,
8077 width: h / parentHeight,
8078 height: w / parentWidth
8079 });
8080 break;
8081 default:
8082 rotator = (x, y, w, h) => ({
8083 x: (x - layerX) / parentWidth,
8084 y: (y - layerY) / parentHeight,
8085 width: w / parentWidth,
8086 height: h / parentHeight
8087 });
8088 break;
8089 }
8090 const boxes = [];
8091 for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
8092 const range = selection.getRangeAt(i);
8093 if (range.collapsed) {
8094 continue;
8095 }
8096 for (const {
8097 x,
8098 y,
8099 width,
8100 height
8101 } of range.getClientRects()) {
8102 if (width === 0 || height === 0) {
8103 continue;
8104 }
8105 boxes.push(rotator(x, y, width, height));
8106 }
8107 }
8108 return boxes.length === 0 ? null : boxes;
8109 }
8110 addChangedExistingAnnotation({
8111 annotationElementId,
8112 id
8113 }) {
8114 (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
8115 }
8116 removeChangedExistingAnnotation({
8117 annotationElementId
8118 }) {
8119 this.#changedExistingAnnotations?.delete(annotationElementId);
8120 }
8121 renderAnnotationElement(annotation) {
8122 const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
8123 if (!editorId) {
8124 return;
8125 }
8126 const editor = this.#annotationStorage.getRawValue(editorId);
8127 if (!editor) {
8128 return;
8129 }
8130 if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
8131 return;
8132 }
8133 editor.renderAnnotationElement(annotation);
8134 }
8135 }
8136
8137 ;// CONCATENATED MODULE: ./src/display/editor/alt_text.js
8138
8139 class AltText {
8140 #altText = "";
8141 #altTextDecorative = false;
8142 #altTextButton = null;
8143 #altTextTooltip = null;
8144 #altTextTooltipTimeout = null;
8145 #altTextWasFromKeyBoard = false;
8146 #editor = null;
8147 static _l10nPromise = null;
8148 constructor(editor) {
8149 this.#editor = editor;
8150 }
8151 static initialize(l10nPromise) {
8152 AltText._l10nPromise ||= l10nPromise;
8153 }
8154 async render() {
8155 const altText = this.#altTextButton = document.createElement("button");
8156 altText.className = "altText";
8157 const msg = await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label");
8158 altText.textContent = msg;
8159 altText.setAttribute("aria-label", msg);
8160 altText.tabIndex = "0";
8161 altText.addEventListener("contextmenu", noContextMenu);
8162 altText.addEventListener("pointerdown", event => event.stopPropagation());
8163 const onClick = event => {
8164 event.preventDefault();
8165 this.#editor._uiManager.editAltText(this.#editor);
8166 };
8167 altText.addEventListener("click", onClick, {
8168 capture: true
8169 });
8170 altText.addEventListener("keydown", event => {
8171 if (event.target === altText && event.key === "Enter") {
8172 this.#altTextWasFromKeyBoard = true;
8173 onClick(event);
8174 }
8175 });
8176 await this.#setState();
8177 return altText;
8178 }
8179 finish() {
8180 if (!this.#altTextButton) {
8181 return;
8182 }
8183 this.#altTextButton.focus({
8184 focusVisible: this.#altTextWasFromKeyBoard
8185 });
8186 this.#altTextWasFromKeyBoard = false;
8187 }
8188 isEmpty() {
8189 return !this.#altText && !this.#altTextDecorative;
8190 }
8191 get data() {
8192 return {
8193 altText: this.#altText,
8194 decorative: this.#altTextDecorative
8195 };
8196 }
8197 set data({
8198 altText,
8199 decorative
8200 }) {
8201 if (this.#altText === altText && this.#altTextDecorative === decorative) {
8202 return;
8203 }
8204 this.#altText = altText;
8205 this.#altTextDecorative = decorative;
8206 this.#setState();
8207 }
8208 toggle(enabled = false) {
8209 if (!this.#altTextButton) {
8210 return;
8211 }
8212 if (!enabled && this.#altTextTooltipTimeout) {
8213 clearTimeout(this.#altTextTooltipTimeout);
8214 this.#altTextTooltipTimeout = null;
8215 }
8216 this.#altTextButton.disabled = !enabled;
8217 }
8218 destroy() {
8219 this.#altTextButton?.remove();
8220 this.#altTextButton = null;
8221 this.#altTextTooltip = null;
8222 }
8223 async #setState() {
8224 const button = this.#altTextButton;
8225 if (!button) {
8226 return;
8227 }
8228 if (!this.#altText && !this.#altTextDecorative) {
8229 button.classList.remove("done");
8230 this.#altTextTooltip?.remove();
8231 return;
8232 }
8233 button.classList.add("done");
8234 AltText._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(msg => {
8235 button.setAttribute("aria-label", msg);
8236 });
8237 let tooltip = this.#altTextTooltip;
8238 if (!tooltip) {
8239 this.#altTextTooltip = tooltip = document.createElement("span");
8240 tooltip.className = "tooltip";
8241 tooltip.setAttribute("role", "tooltip");
8242 const id = tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
8243 button.setAttribute("aria-describedby", id);
8244 const DELAY_TO_SHOW_TOOLTIP = 100;
8245 button.addEventListener("mouseenter", () => {
8246 this.#altTextTooltipTimeout = setTimeout(() => {
8247 this.#altTextTooltipTimeout = null;
8248 this.#altTextTooltip.classList.add("show");
8249 this.#editor._reportTelemetry({
8250 action: "alt_text_tooltip"
8251 });
8252 }, DELAY_TO_SHOW_TOOLTIP);
8253 });
8254 button.addEventListener("mouseleave", () => {
8255 if (this.#altTextTooltipTimeout) {
8256 clearTimeout(this.#altTextTooltipTimeout);
8257 this.#altTextTooltipTimeout = null;
8258 }
8259 this.#altTextTooltip?.classList.remove("show");
8260 });
8261 }
8262 tooltip.innerText = this.#altTextDecorative ? await AltText._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip") : this.#altText;
8263 if (!tooltip.parentNode) {
8264 button.append(tooltip);
8265 }
8266 const element = this.#editor.getImageForAltText();
8267 element?.setAttribute("aria-describedby", tooltip.id);
8268 }
8269 }
8270
8271 ;// CONCATENATED MODULE: ./src/display/editor/editor.js
8272
8273
8274
8275
8276
8277 class AnnotationEditor {
8278 #allResizerDivs = null;
8279 #altText = null;
8280 #disabled = false;
8281 #keepAspectRatio = false;
8282 #resizersDiv = null;
8283 #savedDimensions = null;
8284 #boundFocusin = this.focusin.bind(this);
8285 #boundFocusout = this.focusout.bind(this);
8286 #editToolbar = null;
8287 #focusedResizerName = "";
8288 #hasBeenClicked = false;
8289 #initialPosition = null;
8290 #isEditing = false;
8291 #isInEditMode = false;
8292 #isResizerEnabledForKeyboard = false;
8293 #moveInDOMTimeout = null;
8294 #prevDragX = 0;
8295 #prevDragY = 0;
8296 #telemetryTimeouts = null;
8297 _initialOptions = Object.create(null);
8298 _isVisible = true;
8299 _uiManager = null;
8300 _focusEventsAllowed = true;
8301 _l10nPromise = null;
8302 #isDraggable = false;
8303 #zIndex = AnnotationEditor._zIndex++;
8304 static _borderLineWidth = -1;
8305 static _colorManager = new ColorManager();
8306 static _zIndex = 1;
8307 static _telemetryTimeout = 1000;
8308 static get _resizerKeyboardManager() {
8309 const resize = AnnotationEditor.prototype._resizeWithKeyboard;
8310 const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
8311 const big = AnnotationEditorUIManager.TRANSLATE_BIG;
8312 return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
8313 args: [-small, 0]
8314 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
8315 args: [-big, 0]
8316 }], [["ArrowRight", "mac+ArrowRight"], resize, {
8317 args: [small, 0]
8318 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
8319 args: [big, 0]
8320 }], [["ArrowUp", "mac+ArrowUp"], resize, {
8321 args: [0, -small]
8322 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
8323 args: [0, -big]
8324 }], [["ArrowDown", "mac+ArrowDown"], resize, {
8325 args: [0, small]
8326 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
8327 args: [0, big]
8328 }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
8329 }
8330 constructor(parameters) {
8331 if (this.constructor === AnnotationEditor) {
8332 unreachable("Cannot initialize AnnotationEditor.");
8333 }
8334 this.parent = parameters.parent;
8335 this.id = parameters.id;
8336 this.width = this.height = null;
8337 this.pageIndex = parameters.parent.pageIndex;
8338 this.name = parameters.name;
8339 this.div = null;
8340 this._uiManager = parameters.uiManager;
8341 this.annotationElementId = null;
8342 this._willKeepAspectRatio = false;
8343 this._initialOptions.isCentered = parameters.isCentered;
8344 this._structTreeParentId = null;
8345 const {
8346 rotation,
8347 rawDims: {
8348 pageWidth,
8349 pageHeight,
8350 pageX,
8351 pageY
8352 }
8353 } = this.parent.viewport;
8354 this.rotation = rotation;
8355 this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
8356 this.pageDimensions = [pageWidth, pageHeight];
8357 this.pageTranslation = [pageX, pageY];
8358 const [width, height] = this.parentDimensions;
8359 this.x = parameters.x / width;
8360 this.y = parameters.y / height;
8361 this.isAttachedToDOM = false;
8362 this.deleted = false;
8363 }
8364 get editorType() {
8365 return Object.getPrototypeOf(this).constructor._type;
8366 }
8367 static get _defaultLineColor() {
8368 return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
8369 }
8370 static deleteAnnotationElement(editor) {
8371 const fakeEditor = new FakeEditor({
8372 id: editor.parent.getNextId(),
8373 parent: editor.parent,
8374 uiManager: editor._uiManager
8375 });
8376 fakeEditor.annotationElementId = editor.annotationElementId;
8377 fakeEditor.deleted = true;
8378 fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
8379 }
8380 static initialize(l10n, _uiManager, options) {
8381 AnnotationEditor._l10nPromise ||= new Map(["pdfjs-editor-alt-text-button-label", "pdfjs-editor-alt-text-edit-button-label", "pdfjs-editor-alt-text-decorative-tooltip", "pdfjs-editor-resizer-label-topLeft", "pdfjs-editor-resizer-label-topMiddle", "pdfjs-editor-resizer-label-topRight", "pdfjs-editor-resizer-label-middleRight", "pdfjs-editor-resizer-label-bottomRight", "pdfjs-editor-resizer-label-bottomMiddle", "pdfjs-editor-resizer-label-bottomLeft", "pdfjs-editor-resizer-label-middleLeft"].map(str => [str, l10n.get(str.replaceAll(/([A-Z])/g, c => `-${c.toLowerCase()}`))]));
8382 if (options?.strings) {
8383 for (const str of options.strings) {
8384 AnnotationEditor._l10nPromise.set(str, l10n.get(str));
8385 }
8386 }
8387 if (AnnotationEditor._borderLineWidth !== -1) {
8388 return;
8389 }
8390 const style = getComputedStyle(document.documentElement);
8391 AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
8392 }
8393 static updateDefaultParams(_type, _value) {}
8394 static get defaultPropertiesToUpdate() {
8395 return [];
8396 }
8397 static isHandlingMimeForPasting(mime) {
8398 return false;
8399 }
8400 static paste(item, parent) {
8401 unreachable("Not implemented");
8402 }
8403 get propertiesToUpdate() {
8404 return [];
8405 }
8406 get _isDraggable() {
8407 return this.#isDraggable;
8408 }
8409 set _isDraggable(value) {
8410 this.#isDraggable = value;
8411 this.div?.classList.toggle("draggable", value);
8412 }
8413 get isEnterHandled() {
8414 return true;
8415 }
8416 center() {
8417 const [pageWidth, pageHeight] = this.pageDimensions;
8418 switch (this.parentRotation) {
8419 case 90:
8420 this.x -= this.height * pageHeight / (pageWidth * 2);
8421 this.y += this.width * pageWidth / (pageHeight * 2);
8422 break;
8423 case 180:
8424 this.x += this.width / 2;
8425 this.y += this.height / 2;
8426 break;
8427 case 270:
8428 this.x += this.height * pageHeight / (pageWidth * 2);
8429 this.y -= this.width * pageWidth / (pageHeight * 2);
8430 break;
8431 default:
8432 this.x -= this.width / 2;
8433 this.y -= this.height / 2;
8434 break;
8435 }
8436 this.fixAndSetPosition();
8437 }
8438 addCommands(params) {
8439 this._uiManager.addCommands(params);
8440 }
8441 get currentLayer() {
8442 return this._uiManager.currentLayer;
8443 }
8444 setInBackground() {
8445 this.div.style.zIndex = 0;
8446 }
8447 setInForeground() {
8448 this.div.style.zIndex = this.#zIndex;
8449 }
8450 setParent(parent) {
8451 if (parent !== null) {
8452 this.pageIndex = parent.pageIndex;
8453 this.pageDimensions = parent.pageDimensions;
8454 } else {
8455 this.#stopResizing();
8456 }
8457 this.parent = parent;
8458 }
8459 focusin(event) {
8460 if (!this._focusEventsAllowed) {
8461 return;
8462 }
8463 if (!this.#hasBeenClicked) {
8464 this.parent.setSelected(this);
8465 } else {
8466 this.#hasBeenClicked = false;
8467 }
8468 }
8469 focusout(event) {
8470 if (!this._focusEventsAllowed) {
8471 return;
8472 }
8473 if (!this.isAttachedToDOM) {
8474 return;
8475 }
8476 const target = event.relatedTarget;
8477 if (target?.closest(`#${this.id}`)) {
8478 return;
8479 }
8480 event.preventDefault();
8481 if (!this.parent?.isMultipleSelection) {
8482 this.commitOrRemove();
8483 }
8484 }
8485 commitOrRemove() {
8486 if (this.isEmpty()) {
8487 this.remove();
8488 } else {
8489 this.commit();
8490 }
8491 }
8492 commit() {
8493 this.addToAnnotationStorage();
8494 }
8495 addToAnnotationStorage() {
8496 this._uiManager.addToAnnotationStorage(this);
8497 }
8498 setAt(x, y, tx, ty) {
8499 const [width, height] = this.parentDimensions;
8500 [tx, ty] = this.screenToPageTranslation(tx, ty);
8501 this.x = (x + tx) / width;
8502 this.y = (y + ty) / height;
8503 this.fixAndSetPosition();
8504 }
8505 #translate([width, height], x, y) {
8506 [x, y] = this.screenToPageTranslation(x, y);
8507 this.x += x / width;
8508 this.y += y / height;
8509 this.fixAndSetPosition();
8510 }
8511 translate(x, y) {
8512 this.#translate(this.parentDimensions, x, y);
8513 }
8514 translateInPage(x, y) {
8515 this.#initialPosition ||= [this.x, this.y];
8516 this.#translate(this.pageDimensions, x, y);
8517 this.div.scrollIntoView({
8518 block: "nearest"
8519 });
8520 }
8521 drag(tx, ty) {
8522 this.#initialPosition ||= [this.x, this.y];
8523 const [parentWidth, parentHeight] = this.parentDimensions;
8524 this.x += tx / parentWidth;
8525 this.y += ty / parentHeight;
8526 if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
8527 const {
8528 x,
8529 y
8530 } = this.div.getBoundingClientRect();
8531 if (this.parent.findNewParent(this, x, y)) {
8532 this.x -= Math.floor(this.x);
8533 this.y -= Math.floor(this.y);
8534 }
8535 }
8536 let {
8537 x,
8538 y
8539 } = this;
8540 const [bx, by] = this.getBaseTranslation();
8541 x += bx;
8542 y += by;
8543 this.div.style.left = `${(100 * x).toFixed(2)}%`;
8544 this.div.style.top = `${(100 * y).toFixed(2)}%`;
8545 this.div.scrollIntoView({
8546 block: "nearest"
8547 });
8548 }
8549 get _hasBeenMoved() {
8550 return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y);
8551 }
8552 getBaseTranslation() {
8553 const [parentWidth, parentHeight] = this.parentDimensions;
8554 const {
8555 _borderLineWidth
8556 } = AnnotationEditor;
8557 const x = _borderLineWidth / parentWidth;
8558 const y = _borderLineWidth / parentHeight;
8559 switch (this.rotation) {
8560 case 90:
8561 return [-x, y];
8562 case 180:
8563 return [x, y];
8564 case 270:
8565 return [x, -y];
8566 default:
8567 return [-x, -y];
8568 }
8569 }
8570 get _mustFixPosition() {
8571 return true;
8572 }
8573 fixAndSetPosition(rotation = this.rotation) {
8574 const [pageWidth, pageHeight] = this.pageDimensions;
8575 let {
8576 x,
8577 y,
8578 width,
8579 height
8580 } = this;
8581 width *= pageWidth;
8582 height *= pageHeight;
8583 x *= pageWidth;
8584 y *= pageHeight;
8585 if (this._mustFixPosition) {
8586 switch (rotation) {
8587 case 0:
8588 x = Math.max(0, Math.min(pageWidth - width, x));
8589 y = Math.max(0, Math.min(pageHeight - height, y));
8590 break;
8591 case 90:
8592 x = Math.max(0, Math.min(pageWidth - height, x));
8593 y = Math.min(pageHeight, Math.max(width, y));
8594 break;
8595 case 180:
8596 x = Math.min(pageWidth, Math.max(width, x));
8597 y = Math.min(pageHeight, Math.max(height, y));
8598 break;
8599 case 270:
8600 x = Math.min(pageWidth, Math.max(height, x));
8601 y = Math.max(0, Math.min(pageHeight - width, y));
8602 break;
8603 }
8604 }
8605 this.x = x /= pageWidth;
8606 this.y = y /= pageHeight;
8607 const [bx, by] = this.getBaseTranslation();
8608 x += bx;
8609 y += by;
8610 const {
8611 style
8612 } = this.div;
8613 style.left = `${(100 * x).toFixed(2)}%`;
8614 style.top = `${(100 * y).toFixed(2)}%`;
8615 this.moveInDOM();
8616 }
8617 static #rotatePoint(x, y, angle) {
8618 switch (angle) {
8619 case 90:
8620 return [y, -x];
8621 case 180:
8622 return [-x, -y];
8623 case 270:
8624 return [-y, x];
8625 default:
8626 return [x, y];
8627 }
8628 }
8629 screenToPageTranslation(x, y) {
8630 return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
8631 }
8632 pageTranslationToScreen(x, y) {
8633 return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
8634 }
8635 #getRotationMatrix(rotation) {
8636 switch (rotation) {
8637 case 90:
8638 {
8639 const [pageWidth, pageHeight] = this.pageDimensions;
8640 return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
8641 }
8642 case 180:
8643 return [-1, 0, 0, -1];
8644 case 270:
8645 {
8646 const [pageWidth, pageHeight] = this.pageDimensions;
8647 return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
8648 }
8649 default:
8650 return [1, 0, 0, 1];
8651 }
8652 }
8653 get parentScale() {
8654 return this._uiManager.viewParameters.realScale;
8655 }
8656 get parentRotation() {
8657 return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
8658 }
8659 get parentDimensions() {
8660 const {
8661 parentScale,
8662 pageDimensions: [pageWidth, pageHeight]
8663 } = this;
8664 const scaledWidth = pageWidth * parentScale;
8665 const scaledHeight = pageHeight * parentScale;
8666 return util_FeatureTest.isCSSRoundSupported ? [Math.round(scaledWidth), Math.round(scaledHeight)] : [scaledWidth, scaledHeight];
8667 }
8668 setDims(width, height) {
8669 const [parentWidth, parentHeight] = this.parentDimensions;
8670 this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
8671 if (!this.#keepAspectRatio) {
8672 this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
8673 }
8674 }
8675 fixDims() {
8676 const {
8677 style
8678 } = this.div;
8679 const {
8680 height,
8681 width
8682 } = style;
8683 const widthPercent = width.endsWith("%");
8684 const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
8685 if (widthPercent && heightPercent) {
8686 return;
8687 }
8688 const [parentWidth, parentHeight] = this.parentDimensions;
8689 if (!widthPercent) {
8690 style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
8691 }
8692 if (!this.#keepAspectRatio && !heightPercent) {
8693 style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
8694 }
8695 }
8696 getInitialTranslation() {
8697 return [0, 0];
8698 }
8699 #createResizers() {
8700 if (this.#resizersDiv) {
8701 return;
8702 }
8703 this.#resizersDiv = document.createElement("div");
8704 this.#resizersDiv.classList.add("resizers");
8705 const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
8706 for (const name of classes) {
8707 const div = document.createElement("div");
8708 this.#resizersDiv.append(div);
8709 div.classList.add("resizer", name);
8710 div.setAttribute("data-resizer-name", name);
8711 div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name));
8712 div.addEventListener("contextmenu", noContextMenu);
8713 div.tabIndex = -1;
8714 }
8715 this.div.prepend(this.#resizersDiv);
8716 }
8717 #resizerPointerdown(name, event) {
8718 event.preventDefault();
8719 const {
8720 isMac
8721 } = util_FeatureTest.platform;
8722 if (event.button !== 0 || event.ctrlKey && isMac) {
8723 return;
8724 }
8725 this.#altText?.toggle(false);
8726 const boundResizerPointermove = this.#resizerPointermove.bind(this, name);
8727 const savedDraggable = this._isDraggable;
8728 this._isDraggable = false;
8729 const pointerMoveOptions = {
8730 passive: true,
8731 capture: true
8732 };
8733 this.parent.togglePointerEvents(false);
8734 window.addEventListener("pointermove", boundResizerPointermove, pointerMoveOptions);
8735 window.addEventListener("contextmenu", noContextMenu);
8736 const savedX = this.x;
8737 const savedY = this.y;
8738 const savedWidth = this.width;
8739 const savedHeight = this.height;
8740 const savedParentCursor = this.parent.div.style.cursor;
8741 const savedCursor = this.div.style.cursor;
8742 this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
8743 const pointerUpCallback = () => {
8744 this.parent.togglePointerEvents(true);
8745 this.#altText?.toggle(true);
8746 this._isDraggable = savedDraggable;
8747 window.removeEventListener("pointerup", pointerUpCallback);
8748 window.removeEventListener("blur", pointerUpCallback);
8749 window.removeEventListener("pointermove", boundResizerPointermove, pointerMoveOptions);
8750 window.removeEventListener("contextmenu", noContextMenu);
8751 this.parent.div.style.cursor = savedParentCursor;
8752 this.div.style.cursor = savedCursor;
8753 this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
8754 };
8755 window.addEventListener("pointerup", pointerUpCallback);
8756 window.addEventListener("blur", pointerUpCallback);
8757 }
8758 #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) {
8759 const newX = this.x;
8760 const newY = this.y;
8761 const newWidth = this.width;
8762 const newHeight = this.height;
8763 if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
8764 return;
8765 }
8766 this.addCommands({
8767 cmd: () => {
8768 this.width = newWidth;
8769 this.height = newHeight;
8770 this.x = newX;
8771 this.y = newY;
8772 const [parentWidth, parentHeight] = this.parentDimensions;
8773 this.setDims(parentWidth * newWidth, parentHeight * newHeight);
8774 this.fixAndSetPosition();
8775 },
8776 undo: () => {
8777 this.width = savedWidth;
8778 this.height = savedHeight;
8779 this.x = savedX;
8780 this.y = savedY;
8781 const [parentWidth, parentHeight] = this.parentDimensions;
8782 this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);
8783 this.fixAndSetPosition();
8784 },
8785 mustExec: true
8786 });
8787 }
8788 #resizerPointermove(name, event) {
8789 const [parentWidth, parentHeight] = this.parentDimensions;
8790 const savedX = this.x;
8791 const savedY = this.y;
8792 const savedWidth = this.width;
8793 const savedHeight = this.height;
8794 const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
8795 const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
8796 const round = x => Math.round(x * 10000) / 10000;
8797 const rotationMatrix = this.#getRotationMatrix(this.rotation);
8798 const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
8799 const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
8800 const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
8801 let getPoint;
8802 let getOpposite;
8803 let isDiagonal = false;
8804 let isHorizontal = false;
8805 switch (name) {
8806 case "topLeft":
8807 isDiagonal = true;
8808 getPoint = (w, h) => [0, 0];
8809 getOpposite = (w, h) => [w, h];
8810 break;
8811 case "topMiddle":
8812 getPoint = (w, h) => [w / 2, 0];
8813 getOpposite = (w, h) => [w / 2, h];
8814 break;
8815 case "topRight":
8816 isDiagonal = true;
8817 getPoint = (w, h) => [w, 0];
8818 getOpposite = (w, h) => [0, h];
8819 break;
8820 case "middleRight":
8821 isHorizontal = true;
8822 getPoint = (w, h) => [w, h / 2];
8823 getOpposite = (w, h) => [0, h / 2];
8824 break;
8825 case "bottomRight":
8826 isDiagonal = true;
8827 getPoint = (w, h) => [w, h];
8828 getOpposite = (w, h) => [0, 0];
8829 break;
8830 case "bottomMiddle":
8831 getPoint = (w, h) => [w / 2, h];
8832 getOpposite = (w, h) => [w / 2, 0];
8833 break;
8834 case "bottomLeft":
8835 isDiagonal = true;
8836 getPoint = (w, h) => [0, h];
8837 getOpposite = (w, h) => [w, 0];
8838 break;
8839 case "middleLeft":
8840 isHorizontal = true;
8841 getPoint = (w, h) => [0, h / 2];
8842 getOpposite = (w, h) => [w, h / 2];
8843 break;
8844 }
8845 const point = getPoint(savedWidth, savedHeight);
8846 const oppositePoint = getOpposite(savedWidth, savedHeight);
8847 let transfOppositePoint = transf(...oppositePoint);
8848 const oppositeX = round(savedX + transfOppositePoint[0]);
8849 const oppositeY = round(savedY + transfOppositePoint[1]);
8850 let ratioX = 1;
8851 let ratioY = 1;
8852 let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY);
8853 [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
8854 if (isDiagonal) {
8855 const oldDiag = Math.hypot(savedWidth, savedHeight);
8856 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);
8857 } else if (isHorizontal) {
8858 ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
8859 } else {
8860 ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
8861 }
8862 const newWidth = round(savedWidth * ratioX);
8863 const newHeight = round(savedHeight * ratioY);
8864 transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
8865 const newX = oppositeX - transfOppositePoint[0];
8866 const newY = oppositeY - transfOppositePoint[1];
8867 this.width = newWidth;
8868 this.height = newHeight;
8869 this.x = newX;
8870 this.y = newY;
8871 this.setDims(parentWidth * newWidth, parentHeight * newHeight);
8872 this.fixAndSetPosition();
8873 }
8874 altTextFinish() {
8875 this.#altText?.finish();
8876 }
8877 async addEditToolbar() {
8878 if (this.#editToolbar || this.#isInEditMode) {
8879 return this.#editToolbar;
8880 }
8881 this.#editToolbar = new EditorToolbar(this);
8882 this.div.append(this.#editToolbar.render());
8883 if (this.#altText) {
8884 this.#editToolbar.addAltTextButton(await this.#altText.render());
8885 }
8886 return this.#editToolbar;
8887 }
8888 removeEditToolbar() {
8889 if (!this.#editToolbar) {
8890 return;
8891 }
8892 this.#editToolbar.remove();
8893 this.#editToolbar = null;
8894 this.#altText?.destroy();
8895 }
8896 getClientDimensions() {
8897 return this.div.getBoundingClientRect();
8898 }
8899 async addAltTextButton() {
8900 if (this.#altText) {
8901 return;
8902 }
8903 AltText.initialize(AnnotationEditor._l10nPromise);
8904 this.#altText = new AltText(this);
8905 await this.addEditToolbar();
8906 }
8907 get altTextData() {
8908 return this.#altText?.data;
8909 }
8910 set altTextData(data) {
8911 if (!this.#altText) {
8912 return;
8913 }
8914 this.#altText.data = data;
8915 }
8916 hasAltText() {
8917 return !this.#altText?.isEmpty();
8918 }
8919 render() {
8920 this.div = document.createElement("div");
8921 this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
8922 this.div.className = this.name;
8923 this.div.setAttribute("id", this.id);
8924 this.div.tabIndex = this.#disabled ? -1 : 0;
8925 if (!this._isVisible) {
8926 this.div.classList.add("hidden");
8927 }
8928 this.setInForeground();
8929 this.div.addEventListener("focusin", this.#boundFocusin);
8930 this.div.addEventListener("focusout", this.#boundFocusout);
8931 const [parentWidth, parentHeight] = this.parentDimensions;
8932 if (this.parentRotation % 180 !== 0) {
8933 this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
8934 this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
8935 }
8936 const [tx, ty] = this.getInitialTranslation();
8937 this.translate(tx, ty);
8938 bindEvents(this, this.div, ["pointerdown"]);
8939 return this.div;
8940 }
8941 pointerdown(event) {
8942 const {
8943 isMac
8944 } = util_FeatureTest.platform;
8945 if (event.button !== 0 || event.ctrlKey && isMac) {
8946 event.preventDefault();
8947 return;
8948 }
8949 this.#hasBeenClicked = true;
8950 if (this._isDraggable) {
8951 this.#setUpDragSession(event);
8952 return;
8953 }
8954 this.#selectOnPointerEvent(event);
8955 }
8956 #selectOnPointerEvent(event) {
8957 const {
8958 isMac
8959 } = util_FeatureTest.platform;
8960 if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
8961 this.parent.toggleSelected(this);
8962 } else {
8963 this.parent.setSelected(this);
8964 }
8965 }
8966 #setUpDragSession(event) {
8967 const isSelected = this._uiManager.isSelected(this);
8968 this._uiManager.setUpDragSession();
8969 let pointerMoveOptions, pointerMoveCallback;
8970 if (isSelected) {
8971 this.div.classList.add("moving");
8972 pointerMoveOptions = {
8973 passive: true,
8974 capture: true
8975 };
8976 this.#prevDragX = event.clientX;
8977 this.#prevDragY = event.clientY;
8978 pointerMoveCallback = e => {
8979 const {
8980 clientX: x,
8981 clientY: y
8982 } = e;
8983 const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
8984 this.#prevDragX = x;
8985 this.#prevDragY = y;
8986 this._uiManager.dragSelectedEditors(tx, ty);
8987 };
8988 window.addEventListener("pointermove", pointerMoveCallback, pointerMoveOptions);
8989 }
8990 const pointerUpCallback = () => {
8991 window.removeEventListener("pointerup", pointerUpCallback);
8992 window.removeEventListener("blur", pointerUpCallback);
8993 if (isSelected) {
8994 this.div.classList.remove("moving");
8995 window.removeEventListener("pointermove", pointerMoveCallback, pointerMoveOptions);
8996 }
8997 this.#hasBeenClicked = false;
8998 if (!this._uiManager.endDragSession()) {
8999 this.#selectOnPointerEvent(event);
9000 }
9001 };
9002 window.addEventListener("pointerup", pointerUpCallback);
9003 window.addEventListener("blur", pointerUpCallback);
9004 }
9005 moveInDOM() {
9006 if (this.#moveInDOMTimeout) {
9007 clearTimeout(this.#moveInDOMTimeout);
9008 }
9009 this.#moveInDOMTimeout = setTimeout(() => {
9010 this.#moveInDOMTimeout = null;
9011 this.parent?.moveEditorInDOM(this);
9012 }, 0);
9013 }
9014 _setParentAndPosition(parent, x, y) {
9015 parent.changeParent(this);
9016 this.x = x;
9017 this.y = y;
9018 this.fixAndSetPosition();
9019 }
9020 getRect(tx, ty, rotation = this.rotation) {
9021 const scale = this.parentScale;
9022 const [pageWidth, pageHeight] = this.pageDimensions;
9023 const [pageX, pageY] = this.pageTranslation;
9024 const shiftX = tx / scale;
9025 const shiftY = ty / scale;
9026 const x = this.x * pageWidth;
9027 const y = this.y * pageHeight;
9028 const width = this.width * pageWidth;
9029 const height = this.height * pageHeight;
9030 switch (rotation) {
9031 case 0:
9032 return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
9033 case 90:
9034 return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
9035 case 180:
9036 return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
9037 case 270:
9038 return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
9039 default:
9040 throw new Error("Invalid rotation");
9041 }
9042 }
9043 getRectInCurrentCoords(rect, pageHeight) {
9044 const [x1, y1, x2, y2] = rect;
9045 const width = x2 - x1;
9046 const height = y2 - y1;
9047 switch (this.rotation) {
9048 case 0:
9049 return [x1, pageHeight - y2, width, height];
9050 case 90:
9051 return [x1, pageHeight - y1, height, width];
9052 case 180:
9053 return [x2, pageHeight - y1, width, height];
9054 case 270:
9055 return [x2, pageHeight - y2, height, width];
9056 default:
9057 throw new Error("Invalid rotation");
9058 }
9059 }
9060 onceAdded() {}
9061 isEmpty() {
9062 return false;
9063 }
9064 enableEditMode() {
9065 this.#isInEditMode = true;
9066 }
9067 disableEditMode() {
9068 this.#isInEditMode = false;
9069 }
9070 isInEditMode() {
9071 return this.#isInEditMode;
9072 }
9073 shouldGetKeyboardEvents() {
9074 return this.#isResizerEnabledForKeyboard;
9075 }
9076 needsToBeRebuilt() {
9077 return this.div && !this.isAttachedToDOM;
9078 }
9079 rebuild() {
9080 this.div?.addEventListener("focusin", this.#boundFocusin);
9081 this.div?.addEventListener("focusout", this.#boundFocusout);
9082 }
9083 rotate(_angle) {}
9084 serialize(isForCopying = false, context = null) {
9085 unreachable("An editor must be serializable");
9086 }
9087 static deserialize(data, parent, uiManager) {
9088 const editor = new this.prototype.constructor({
9089 parent,
9090 id: parent.getNextId(),
9091 uiManager
9092 });
9093 editor.rotation = data.rotation;
9094 const [pageWidth, pageHeight] = editor.pageDimensions;
9095 const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
9096 editor.x = x / pageWidth;
9097 editor.y = y / pageHeight;
9098 editor.width = width / pageWidth;
9099 editor.height = height / pageHeight;
9100 return editor;
9101 }
9102 get hasBeenModified() {
9103 return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
9104 }
9105 remove() {
9106 this.div.removeEventListener("focusin", this.#boundFocusin);
9107 this.div.removeEventListener("focusout", this.#boundFocusout);
9108 if (!this.isEmpty()) {
9109 this.commit();
9110 }
9111 if (this.parent) {
9112 this.parent.remove(this);
9113 } else {
9114 this._uiManager.removeEditor(this);
9115 }
9116 if (this.#moveInDOMTimeout) {
9117 clearTimeout(this.#moveInDOMTimeout);
9118 this.#moveInDOMTimeout = null;
9119 }
9120 this.#stopResizing();
9121 this.removeEditToolbar();
9122 if (this.#telemetryTimeouts) {
9123 for (const timeout of this.#telemetryTimeouts.values()) {
9124 clearTimeout(timeout);
9125 }
9126 this.#telemetryTimeouts = null;
9127 }
9128 this.parent = null;
9129 }
9130 get isResizable() {
9131 return false;
9132 }
9133 makeResizable() {
9134 if (this.isResizable) {
9135 this.#createResizers();
9136 this.#resizersDiv.classList.remove("hidden");
9137 bindEvents(this, this.div, ["keydown"]);
9138 }
9139 }
9140 get toolbarPosition() {
9141 return null;
9142 }
9143 keydown(event) {
9144 if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
9145 return;
9146 }
9147 this._uiManager.setSelected(this);
9148 this.#savedDimensions = {
9149 savedX: this.x,
9150 savedY: this.y,
9151 savedWidth: this.width,
9152 savedHeight: this.height
9153 };
9154 const children = this.#resizersDiv.children;
9155 if (!this.#allResizerDivs) {
9156 this.#allResizerDivs = Array.from(children);
9157 const boundResizerKeydown = this.#resizerKeydown.bind(this);
9158 const boundResizerBlur = this.#resizerBlur.bind(this);
9159 for (const div of this.#allResizerDivs) {
9160 const name = div.getAttribute("data-resizer-name");
9161 div.setAttribute("role", "spinbutton");
9162 div.addEventListener("keydown", boundResizerKeydown);
9163 div.addEventListener("blur", boundResizerBlur);
9164 div.addEventListener("focus", this.#resizerFocus.bind(this, name));
9165 AnnotationEditor._l10nPromise.get(`pdfjs-editor-resizer-label-${name}`).then(msg => div.setAttribute("aria-label", msg));
9166 }
9167 }
9168 const first = this.#allResizerDivs[0];
9169 let firstPosition = 0;
9170 for (const div of children) {
9171 if (div === first) {
9172 break;
9173 }
9174 firstPosition++;
9175 }
9176 const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
9177 if (nextFirstPosition !== firstPosition) {
9178 if (nextFirstPosition < firstPosition) {
9179 for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
9180 this.#resizersDiv.append(this.#resizersDiv.firstChild);
9181 }
9182 } else if (nextFirstPosition > firstPosition) {
9183 for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
9184 this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
9185 }
9186 }
9187 let i = 0;
9188 for (const child of children) {
9189 const div = this.#allResizerDivs[i++];
9190 const name = div.getAttribute("data-resizer-name");
9191 AnnotationEditor._l10nPromise.get(`pdfjs-editor-resizer-label-${name}`).then(msg => child.setAttribute("aria-label", msg));
9192 }
9193 }
9194 this.#setResizerTabIndex(0);
9195 this.#isResizerEnabledForKeyboard = true;
9196 this.#resizersDiv.firstChild.focus({
9197 focusVisible: true
9198 });
9199 event.preventDefault();
9200 event.stopImmediatePropagation();
9201 }
9202 #resizerKeydown(event) {
9203 AnnotationEditor._resizerKeyboardManager.exec(this, event);
9204 }
9205 #resizerBlur(event) {
9206 if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
9207 this.#stopResizing();
9208 }
9209 }
9210 #resizerFocus(name) {
9211 this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
9212 }
9213 #setResizerTabIndex(value) {
9214 if (!this.#allResizerDivs) {
9215 return;
9216 }
9217 for (const div of this.#allResizerDivs) {
9218 div.tabIndex = value;
9219 }
9220 }
9221 _resizeWithKeyboard(x, y) {
9222 if (!this.#isResizerEnabledForKeyboard) {
9223 return;
9224 }
9225 this.#resizerPointermove(this.#focusedResizerName, {
9226 movementX: x,
9227 movementY: y
9228 });
9229 }
9230 #stopResizing() {
9231 this.#isResizerEnabledForKeyboard = false;
9232 this.#setResizerTabIndex(-1);
9233 if (this.#savedDimensions) {
9234 const {
9235 savedX,
9236 savedY,
9237 savedWidth,
9238 savedHeight
9239 } = this.#savedDimensions;
9240 this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
9241 this.#savedDimensions = null;
9242 }
9243 }
9244 _stopResizingWithKeyboard() {
9245 this.#stopResizing();
9246 this.div.focus();
9247 }
9248 select() {
9249 this.makeResizable();
9250 this.div?.classList.add("selectedEditor");
9251 if (!this.#editToolbar) {
9252 this.addEditToolbar().then(() => {
9253 if (this.div?.classList.contains("selectedEditor")) {
9254 this.#editToolbar?.show();
9255 }
9256 });
9257 return;
9258 }
9259 this.#editToolbar?.show();
9260 }
9261 unselect() {
9262 this.#resizersDiv?.classList.add("hidden");
9263 this.div?.classList.remove("selectedEditor");
9264 if (this.div?.contains(document.activeElement)) {
9265 this._uiManager.currentLayer.div.focus({
9266 preventScroll: true
9267 });
9268 }
9269 this.#editToolbar?.hide();
9270 }
9271 updateParams(type, value) {}
9272 disableEditing() {}
9273 enableEditing() {}
9274 enterInEditMode() {}
9275 getImageForAltText() {
9276 return null;
9277 }
9278 get contentDiv() {
9279 return this.div;
9280 }
9281 get isEditing() {
9282 return this.#isEditing;
9283 }
9284 set isEditing(value) {
9285 this.#isEditing = value;
9286 if (!this.parent) {
9287 return;
9288 }
9289 if (value) {
9290 this.parent.setSelected(this);
9291 this.parent.setActiveEditor(this);
9292 } else {
9293 this.parent.setActiveEditor(null);
9294 }
9295 }
9296 setAspectRatio(width, height) {
9297 this.#keepAspectRatio = true;
9298 const aspectRatio = width / height;
9299 const {
9300 style
9301 } = this.div;
9302 style.aspectRatio = aspectRatio;
9303 style.height = "auto";
9304 }
9305 static get MIN_SIZE() {
9306 return 16;
9307 }
9308 static canCreateNewEmptyEditor() {
9309 return true;
9310 }
9311 get telemetryInitialData() {
9312 return {
9313 action: "added"
9314 };
9315 }
9316 get telemetryFinalData() {
9317 return null;
9318 }
9319 _reportTelemetry(data, mustWait = false) {
9320 if (mustWait) {
9321 this.#telemetryTimeouts ||= new Map();
9322 const {
9323 action
9324 } = data;
9325 let timeout = this.#telemetryTimeouts.get(action);
9326 if (timeout) {
9327 clearTimeout(timeout);
9328 }
9329 timeout = setTimeout(() => {
9330 this._reportTelemetry(data);
9331 this.#telemetryTimeouts.delete(action);
9332 if (this.#telemetryTimeouts.size === 0) {
9333 this.#telemetryTimeouts = null;
9334 }
9335 }, AnnotationEditor._telemetryTimeout);
9336 this.#telemetryTimeouts.set(action, timeout);
9337 return;
9338 }
9339 data.type ||= this.editorType;
9340 this._uiManager._eventBus.dispatch("reporttelemetry", {
9341 source: this,
9342 details: {
9343 type: "editing",
9344 data
9345 }
9346 });
9347 }
9348 show(visible = this._isVisible) {
9349 this.div.classList.toggle("hidden", !visible);
9350 this._isVisible = visible;
9351 }
9352 enable() {
9353 if (this.div) {
9354 this.div.tabIndex = 0;
9355 }
9356 this.#disabled = false;
9357 }
9358 disable() {
9359 if (this.div) {
9360 this.div.tabIndex = -1;
9361 }
9362 this.#disabled = true;
9363 }
9364 renderAnnotationElement(annotation) {
9365 let content = annotation.container.querySelector(".annotationContent");
9366 if (!content) {
9367 content = document.createElement("div");
9368 content.classList.add("annotationContent", this.editorType);
9369 annotation.container.prepend(content);
9370 } else if (content.nodeName === "CANVAS") {
9371 const canvas = content;
9372 content = document.createElement("div");
9373 content.classList.add("annotationContent", this.editorType);
9374 canvas.before(content);
9375 }
9376 return content;
9377 }
9378 resetAnnotationElement(annotation) {
9379 const {
9380 firstChild
9381 } = annotation.container;
9382 if (firstChild.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
9383 firstChild.remove();
9384 }
9385 }
9386 }
9387 class FakeEditor extends AnnotationEditor {
9388 constructor(params) {
9389 super(params);
9390 this.annotationElementId = params.annotationElementId;
9391 this.deleted = true;
9392 }
9393 serialize() {
9394 return {
9395 id: this.annotationElementId,
9396 deleted: true,
9397 pageIndex: this.pageIndex
9398 };
9399 }
9400 }
9401
9402 ;// CONCATENATED MODULE: ./src/shared/murmurhash3.js
9403
9404
9405
9406
9407
9408
9409 const SEED = 0xc3d2e1f0;
9410 const MASK_HIGH = 0xffff0000;
9411 const MASK_LOW = 0xffff;
9412 class MurmurHash3_64 {
9413 constructor(seed) {
9414 this.h1 = seed ? seed & 0xffffffff : SEED;
9415 this.h2 = seed ? seed & 0xffffffff : SEED;
9416 }
9417 update(input) {
9418 let data, length;
9419 if (typeof input === "string") {
9420 data = new Uint8Array(input.length * 2);
9421 length = 0;
9422 for (let i = 0, ii = input.length; i < ii; i++) {
9423 const code = input.charCodeAt(i);
9424 if (code <= 0xff) {
9425 data[length++] = code;
9426 } else {
9427 data[length++] = code >>> 8;
9428 data[length++] = code & 0xff;
9429 }
9430 }
9431 } else if (ArrayBuffer.isView(input)) {
9432 data = input.slice();
9433 length = data.byteLength;
9434 } else {
9435 throw new Error("Invalid data format, must be a string or TypedArray.");
9436 }
9437 const blockCounts = length >> 2;
9438 const tailLength = length - blockCounts * 4;
9439 const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
9440 let k1 = 0,
9441 k2 = 0;
9442 let h1 = this.h1,
9443 h2 = this.h2;
9444 const C1 = 0xcc9e2d51,
9445 C2 = 0x1b873593;
9446 const C1_LOW = C1 & MASK_LOW,
9447 C2_LOW = C2 & MASK_LOW;
9448 for (let i = 0; i < blockCounts; i++) {
9449 if (i & 1) {
9450 k1 = dataUint32[i];
9451 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
9452 k1 = k1 << 15 | k1 >>> 17;
9453 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
9454 h1 ^= k1;
9455 h1 = h1 << 13 | h1 >>> 19;
9456 h1 = h1 * 5 + 0xe6546b64;
9457 } else {
9458 k2 = dataUint32[i];
9459 k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
9460 k2 = k2 << 15 | k2 >>> 17;
9461 k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
9462 h2 ^= k2;
9463 h2 = h2 << 13 | h2 >>> 19;
9464 h2 = h2 * 5 + 0xe6546b64;
9465 }
9466 }
9467 k1 = 0;
9468 switch (tailLength) {
9469 case 3:
9470 k1 ^= data[blockCounts * 4 + 2] << 16;
9471 case 2:
9472 k1 ^= data[blockCounts * 4 + 1] << 8;
9473 case 1:
9474 k1 ^= data[blockCounts * 4];
9475 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
9476 k1 = k1 << 15 | k1 >>> 17;
9477 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
9478 if (blockCounts & 1) {
9479 h1 ^= k1;
9480 } else {
9481 h2 ^= k1;
9482 }
9483 }
9484 this.h1 = h1;
9485 this.h2 = h2;
9486 }
9487 hexdigest() {
9488 let h1 = this.h1,
9489 h2 = this.h2;
9490 h1 ^= h2 >>> 1;
9491 h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
9492 h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
9493 h1 ^= h2 >>> 1;
9494 h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
9495 h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
9496 h1 ^= h2 >>> 1;
9497 return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
9498 }
9499 }
9500
9501 ;// CONCATENATED MODULE: ./src/display/annotation_storage.js
9502
9503
9504
9505
9506
9507
9508 const SerializableEmpty = Object.freeze({
9509 map: null,
9510 hash: "",
9511 transfer: undefined
9512 });
9513 class AnnotationStorage {
9514 #modified = false;
9515 #storage = new Map();
9516 constructor() {
9517 this.onSetModified = null;
9518 this.onResetModified = null;
9519 this.onAnnotationEditor = null;
9520 }
9521 getValue(key, defaultValue) {
9522 const value = this.#storage.get(key);
9523 if (value === undefined) {
9524 return defaultValue;
9525 }
9526 return Object.assign(defaultValue, value);
9527 }
9528 getRawValue(key) {
9529 return this.#storage.get(key);
9530 }
9531 remove(key) {
9532 this.#storage.delete(key);
9533 if (this.#storage.size === 0) {
9534 this.resetModified();
9535 }
9536 if (typeof this.onAnnotationEditor === "function") {
9537 for (const value of this.#storage.values()) {
9538 if (value instanceof AnnotationEditor) {
9539 return;
9540 }
9541 }
9542 this.onAnnotationEditor(null);
9543 }
9544 }
9545 setValue(key, value) {
9546 const obj = this.#storage.get(key);
9547 let modified = false;
9548 if (obj !== undefined) {
9549 for (const [entry, val] of Object.entries(value)) {
9550 if (obj[entry] !== val) {
9551 modified = true;
9552 obj[entry] = val;
9553 }
9554 }
9555 } else {
9556 modified = true;
9557 this.#storage.set(key, value);
9558 }
9559 if (modified) {
9560 this.#setModified();
9561 }
9562 if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
9563 this.onAnnotationEditor(value.constructor._type);
9564 }
9565 }
9566 has(key) {
9567 return this.#storage.has(key);
9568 }
9569 getAll() {
9570 return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;
9571 }
9572 setAll(obj) {
9573 for (const [key, val] of Object.entries(obj)) {
9574 this.setValue(key, val);
9575 }
9576 }
9577 get size() {
9578 return this.#storage.size;
9579 }
9580 #setModified() {
9581 if (!this.#modified) {
9582 this.#modified = true;
9583 if (typeof this.onSetModified === "function") {
9584 this.onSetModified();
9585 }
9586 }
9587 }
9588 resetModified() {
9589 if (this.#modified) {
9590 this.#modified = false;
9591 if (typeof this.onResetModified === "function") {
9592 this.onResetModified();
9593 }
9594 }
9595 }
9596 get print() {
9597 return new PrintAnnotationStorage(this);
9598 }
9599 get serializable() {
9600 if (this.#storage.size === 0) {
9601 return SerializableEmpty;
9602 }
9603 const map = new Map(),
9604 hash = new MurmurHash3_64(),
9605 transfer = [];
9606 const context = Object.create(null);
9607 let hasBitmap = false;
9608 for (const [key, val] of this.#storage) {
9609 const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
9610 if (serialized) {
9611 map.set(key, serialized);
9612 hash.update(`${key}:${JSON.stringify(serialized)}`);
9613 hasBitmap ||= !!serialized.bitmap;
9614 }
9615 }
9616 if (hasBitmap) {
9617 for (const value of map.values()) {
9618 if (value.bitmap) {
9619 transfer.push(value.bitmap);
9620 }
9621 }
9622 }
9623 return map.size > 0 ? {
9624 map,
9625 hash: hash.hexdigest(),
9626 transfer
9627 } : SerializableEmpty;
9628 }
9629 get editorStats() {
9630 let stats = null;
9631 const typeToEditor = new Map();
9632 for (const value of this.#storage.values()) {
9633 if (!(value instanceof AnnotationEditor)) {
9634 continue;
9635 }
9636 const editorStats = value.telemetryFinalData;
9637 if (!editorStats) {
9638 continue;
9639 }
9640 const {
9641 type
9642 } = editorStats;
9643 if (!typeToEditor.has(type)) {
9644 typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
9645 }
9646 stats ||= Object.create(null);
9647 const map = stats[type] ||= new Map();
9648 for (const [key, val] of Object.entries(editorStats)) {
9649 if (key === "type") {
9650 continue;
9651 }
9652 let counters = map.get(key);
9653 if (!counters) {
9654 counters = new Map();
9655 map.set(key, counters);
9656 }
9657 const count = counters.get(val) ?? 0;
9658 counters.set(val, count + 1);
9659 }
9660 }
9661 for (const [type, editor] of typeToEditor) {
9662 stats[type] = editor.computeTelemetryFinalData(stats[type]);
9663 }
9664 return stats;
9665 }
9666 }
9667 class PrintAnnotationStorage extends AnnotationStorage {
9668 #serializable;
9669 constructor(parent) {
9670 super();
9671 const {
9672 map,
9673 hash,
9674 transfer
9675 } = parent.serializable;
9676 const clone = structuredClone(map, transfer ? {
9677 transfer
9678 } : null);
9679 this.#serializable = {
9680 map: clone,
9681 hash,
9682 transfer
9683 };
9684 }
9685 get print() {
9686 unreachable("Should not call PrintAnnotationStorage.print");
9687 }
9688 get serializable() {
9689 return this.#serializable;
9690 }
9691 }
9692
9693 ;// CONCATENATED MODULE: ./src/display/font_loader.js
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704 class FontLoader {
9705 #systemFonts = new Set();
9706 constructor({
9707 ownerDocument = globalThis.document,
9708 styleElement = null
9709 }) {
9710 this._document = ownerDocument;
9711 this.nativeFontFaces = new Set();
9712 this.styleElement = null;
9713 this.loadingRequests = [];
9714 this.loadTestFontId = 0;
9715 }
9716 addNativeFontFace(nativeFontFace) {
9717 this.nativeFontFaces.add(nativeFontFace);
9718 this._document.fonts.add(nativeFontFace);
9719 }
9720 removeNativeFontFace(nativeFontFace) {
9721 this.nativeFontFaces.delete(nativeFontFace);
9722 this._document.fonts.delete(nativeFontFace);
9723 }
9724 insertRule(rule) {
9725 if (!this.styleElement) {
9726 this.styleElement = this._document.createElement("style");
9727 this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
9728 }
9729 const styleSheet = this.styleElement.sheet;
9730 styleSheet.insertRule(rule, styleSheet.cssRules.length);
9731 }
9732 clear() {
9733 for (const nativeFontFace of this.nativeFontFaces) {
9734 this._document.fonts.delete(nativeFontFace);
9735 }
9736 this.nativeFontFaces.clear();
9737 this.#systemFonts.clear();
9738 if (this.styleElement) {
9739 this.styleElement.remove();
9740 this.styleElement = null;
9741 }
9742 }
9743 async loadSystemFont({
9744 systemFontInfo: info,
9745 _inspectFont
9746 }) {
9747 if (!info || this.#systemFonts.has(info.loadedName)) {
9748 return;
9749 }
9750 assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
9751 if (this.isFontLoadingAPISupported) {
9752 const {
9753 loadedName,
9754 src,
9755 style
9756 } = info;
9757 const fontFace = new FontFace(loadedName, src, style);
9758 this.addNativeFontFace(fontFace);
9759 try {
9760 await fontFace.load();
9761 this.#systemFonts.add(loadedName);
9762 _inspectFont?.(info);
9763 } catch {
9764 warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
9765 this.removeNativeFontFace(fontFace);
9766 }
9767 return;
9768 }
9769 unreachable("Not implemented: loadSystemFont without the Font Loading API.");
9770 }
9771 async bind(font) {
9772 if (font.attached || font.missingFile && !font.systemFontInfo) {
9773 return;
9774 }
9775 font.attached = true;
9776 if (font.systemFontInfo) {
9777 await this.loadSystemFont(font);
9778 return;
9779 }
9780 if (this.isFontLoadingAPISupported) {
9781 const nativeFontFace = font.createNativeFontFace();
9782 if (nativeFontFace) {
9783 this.addNativeFontFace(nativeFontFace);
9784 try {
9785 await nativeFontFace.loaded;
9786 } catch (ex) {
9787 warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
9788 font.disableFontFace = true;
9789 throw ex;
9790 }
9791 }
9792 return;
9793 }
9794 const rule = font.createFontFaceRule();
9795 if (rule) {
9796 this.insertRule(rule);
9797 if (this.isSyncFontLoadingSupported) {
9798 return;
9799 }
9800 await new Promise(resolve => {
9801 const request = this._queueLoadingCallback(resolve);
9802 this._prepareFontLoadEvent(font, request);
9803 });
9804 }
9805 }
9806 get isFontLoadingAPISupported() {
9807 const hasFonts = !!this._document?.fonts;
9808 return shadow(this, "isFontLoadingAPISupported", hasFonts);
9809 }
9810 get isSyncFontLoadingSupported() {
9811 let supported = false;
9812 if (isNodeJS) {
9813 supported = true;
9814 } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
9815 supported = true;
9816 }
9817 return shadow(this, "isSyncFontLoadingSupported", supported);
9818 }
9819 _queueLoadingCallback(callback) {
9820 function completeRequest() {
9821 assert(!request.done, "completeRequest() cannot be called twice.");
9822 request.done = true;
9823 while (loadingRequests.length > 0 && loadingRequests[0].done) {
9824 const otherRequest = loadingRequests.shift();
9825 setTimeout(otherRequest.callback, 0);
9826 }
9827 }
9828 const {
9829 loadingRequests
9830 } = this;
9831 const request = {
9832 done: false,
9833 complete: completeRequest,
9834 callback
9835 };
9836 loadingRequests.push(request);
9837 return request;
9838 }
9839 get _loadTestFont() {
9840 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==");
9841 return shadow(this, "_loadTestFont", testFont);
9842 }
9843 _prepareFontLoadEvent(font, request) {
9844 function int32(data, offset) {
9845 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
9846 }
9847 function spliceString(s, offset, remove, insert) {
9848 const chunk1 = s.substring(0, offset);
9849 const chunk2 = s.substring(offset + remove);
9850 return chunk1 + insert + chunk2;
9851 }
9852 let i, ii;
9853 const canvas = this._document.createElement("canvas");
9854 canvas.width = 1;
9855 canvas.height = 1;
9856 const ctx = canvas.getContext("2d");
9857 let called = 0;
9858 function isFontReady(name, callback) {
9859 if (++called > 30) {
9860 warn("Load test font never loaded.");
9861 callback();
9862 return;
9863 }
9864 ctx.font = "30px " + name;
9865 ctx.fillText(".", 0, 20);
9866 const imageData = ctx.getImageData(0, 0, 1, 1);
9867 if (imageData.data[3] > 0) {
9868 callback();
9869 return;
9870 }
9871 setTimeout(isFontReady.bind(null, name, callback));
9872 }
9873 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
9874 let data = this._loadTestFont;
9875 const COMMENT_OFFSET = 976;
9876 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
9877 const CFF_CHECKSUM_OFFSET = 16;
9878 const XXXX_VALUE = 0x58585858;
9879 let checksum = int32(data, CFF_CHECKSUM_OFFSET);
9880 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
9881 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
9882 }
9883 if (i < loadTestFontId.length) {
9884 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
9885 }
9886 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
9887 const url = `url(data:font/opentype;base64,${btoa(data)});`;
9888 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
9889 this.insertRule(rule);
9890 const div = this._document.createElement("div");
9891 div.style.visibility = "hidden";
9892 div.style.width = div.style.height = "10px";
9893 div.style.position = "absolute";
9894 div.style.top = div.style.left = "0px";
9895 for (const name of [font.loadedName, loadTestFontId]) {
9896 const span = this._document.createElement("span");
9897 span.textContent = "Hi";
9898 span.style.fontFamily = name;
9899 div.append(span);
9900 }
9901 this._document.body.append(div);
9902 isFontReady(loadTestFontId, () => {
9903 div.remove();
9904 request.complete();
9905 });
9906 }
9907 }
9908 class FontFaceObject {
9909 constructor(translatedData, {
9910 disableFontFace = false,
9911 inspectFont = null
9912 }) {
9913 this.compiledGlyphs = Object.create(null);
9914 for (const i in translatedData) {
9915 this[i] = translatedData[i];
9916 }
9917 this.disableFontFace = disableFontFace === true;
9918 this._inspectFont = inspectFont;
9919 }
9920 createNativeFontFace() {
9921 if (!this.data || this.disableFontFace) {
9922 return null;
9923 }
9924 let nativeFontFace;
9925 if (!this.cssFontInfo) {
9926 nativeFontFace = new FontFace(this.loadedName, this.data, {});
9927 } else {
9928 const css = {
9929 weight: this.cssFontInfo.fontWeight
9930 };
9931 if (this.cssFontInfo.italicAngle) {
9932 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
9933 }
9934 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
9935 }
9936 this._inspectFont?.(this);
9937 return nativeFontFace;
9938 }
9939 createFontFaceRule() {
9940 if (!this.data || this.disableFontFace) {
9941 return null;
9942 }
9943 const data = bytesToString(this.data);
9944 const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
9945 let rule;
9946 if (!this.cssFontInfo) {
9947 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
9948 } else {
9949 let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
9950 if (this.cssFontInfo.italicAngle) {
9951 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
9952 }
9953 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
9954 }
9955 this._inspectFont?.(this, url);
9956 return rule;
9957 }
9958 getPathGenerator(objs, character) {
9959 if (this.compiledGlyphs[character] !== undefined) {
9960 return this.compiledGlyphs[character];
9961 }
9962 let cmds;
9963 try {
9964 cmds = objs.get(this.loadedName + "_path_" + character);
9965 } catch (ex) {
9966 warn(`getPathGenerator - ignoring character: "${ex}".`);
9967 }
9968 if (!Array.isArray(cmds) || cmds.length === 0) {
9969 return this.compiledGlyphs[character] = function (c, size) {};
9970 }
9971 const commands = [];
9972 for (let i = 0, ii = cmds.length; i < ii;) {
9973 switch (cmds[i++]) {
9974 case FontRenderOps.BEZIER_CURVE_TO:
9975 {
9976 const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
9977 commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));
9978 i += 6;
9979 }
9980 break;
9981 case FontRenderOps.MOVE_TO:
9982 {
9983 const [a, b] = cmds.slice(i, i + 2);
9984 commands.push(ctx => ctx.moveTo(a, b));
9985 i += 2;
9986 }
9987 break;
9988 case FontRenderOps.LINE_TO:
9989 {
9990 const [a, b] = cmds.slice(i, i + 2);
9991 commands.push(ctx => ctx.lineTo(a, b));
9992 i += 2;
9993 }
9994 break;
9995 case FontRenderOps.QUADRATIC_CURVE_TO:
9996 {
9997 const [a, b, c, d] = cmds.slice(i, i + 4);
9998 commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));
9999 i += 4;
10000 }
10001 break;
10002 case FontRenderOps.RESTORE:
10003 commands.push(ctx => ctx.restore());
10004 break;
10005 case FontRenderOps.SAVE:
10006 commands.push(ctx => ctx.save());
10007 break;
10008 case FontRenderOps.SCALE:
10009 assert(commands.length === 2, "Scale command is only valid at the third position.");
10010 break;
10011 case FontRenderOps.TRANSFORM:
10012 {
10013 const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
10014 commands.push(ctx => ctx.transform(a, b, c, d, e, f));
10015 i += 6;
10016 }
10017 break;
10018 case FontRenderOps.TRANSLATE:
10019 {
10020 const [a, b] = cmds.slice(i, i + 2);
10021 commands.push(ctx => ctx.translate(a, b));
10022 i += 2;
10023 }
10024 break;
10025 }
10026 }
10027 return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {
10028 commands[0](ctx);
10029 commands[1](ctx);
10030 ctx.scale(size, -size);
10031 for (let i = 2, ii = commands.length; i < ii; i++) {
10032 commands[i](ctx);
10033 }
10034 };
10035 }
10036 }
10037
10038 ;// CONCATENATED MODULE: ./src/display/node_utils.js
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048 if (isNodeJS) {
10049 var packageCapability = Promise.withResolvers();
10050 var packageMap = null;
10051 const loadPackages = async () => {
10052 const fs = await import( /*webpackIgnore: true*/"fs"),
10053 http = await import( /*webpackIgnore: true*/"http"),
10054 https = await import( /*webpackIgnore: true*/"https"),
10055 url = await import( /*webpackIgnore: true*/"url");
10056 let canvas, path2d;
10057 try {
10058 canvas = await import( /*webpackIgnore: true*/"canvas");
10059 } catch {}
10060 try {
10061 path2d = await import( /*webpackIgnore: true*/"path2d");
10062 } catch {}
10063 return new Map(Object.entries({
10064 fs,
10065 http,
10066 https,
10067 url,
10068 canvas,
10069 path2d
10070 }));
10071 };
10072 loadPackages().then(map => {
10073 packageMap = map;
10074 packageCapability.resolve();
10075 if (!globalThis.DOMMatrix) {
10076 const DOMMatrix = map.get("canvas")?.DOMMatrix;
10077 if (DOMMatrix) {
10078 globalThis.DOMMatrix = DOMMatrix;
10079 } else {
10080 warn("Cannot polyfill `DOMMatrix`, rendering may be broken.");
10081 }
10082 }
10083 if (!globalThis.Path2D) {
10084 const CanvasRenderingContext2D = map.get("canvas")?.CanvasRenderingContext2D;
10085 const applyPath2DToCanvasRenderingContext = map.get("path2d")?.applyPath2DToCanvasRenderingContext;
10086 const Path2D = map.get("path2d")?.Path2D;
10087 if (CanvasRenderingContext2D && applyPath2DToCanvasRenderingContext && Path2D) {
10088 applyPath2DToCanvasRenderingContext(CanvasRenderingContext2D);
10089 globalThis.Path2D = Path2D;
10090 } else {
10091 warn("Cannot polyfill `Path2D`, rendering may be broken.");
10092 }
10093 }
10094 }, reason => {
10095 warn(`loadPackages: ${reason}`);
10096 packageMap = new Map();
10097 packageCapability.resolve();
10098 });
10099 }
10100 class NodePackages {
10101 static get promise() {
10102 return packageCapability.promise;
10103 }
10104 static get(name) {
10105 return packageMap?.get(name);
10106 }
10107 }
10108 const node_utils_fetchData = function (url) {
10109 const fs = NodePackages.get("fs");
10110 return fs.promises.readFile(url).then(data => new Uint8Array(data));
10111 };
10112 class NodeFilterFactory extends BaseFilterFactory {}
10113 class NodeCanvasFactory extends BaseCanvasFactory {
10114 _createCanvas(width, height) {
10115 const canvas = NodePackages.get("canvas");
10116 return canvas.createCanvas(width, height);
10117 }
10118 }
10119 class NodeCMapReaderFactory extends BaseCMapReaderFactory {
10120 _fetchData(url, compressionType) {
10121 return node_utils_fetchData(url).then(data => ({
10122 cMapData: data,
10123 compressionType
10124 }));
10125 }
10126 }
10127 class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
10128 _fetchData(url) {
10129 return node_utils_fetchData(url);
10130 }
10131 }
10132
10133 ;// CONCATENATED MODULE: ./src/display/pattern_helper.js
10134
10135
10136 const PathType = {
10137 FILL: "Fill",
10138 STROKE: "Stroke",
10139 SHADING: "Shading"
10140 };
10141 function applyBoundingBox(ctx, bbox) {
10142 if (!bbox) {
10143 return;
10144 }
10145 const width = bbox[2] - bbox[0];
10146 const height = bbox[3] - bbox[1];
10147 const region = new Path2D();
10148 region.rect(bbox[0], bbox[1], width, height);
10149 ctx.clip(region);
10150 }
10151 class BaseShadingPattern {
10152 constructor() {
10153 if (this.constructor === BaseShadingPattern) {
10154 unreachable("Cannot initialize BaseShadingPattern.");
10155 }
10156 }
10157 getPattern() {
10158 unreachable("Abstract method `getPattern` called.");
10159 }
10160 }
10161 class RadialAxialShadingPattern extends BaseShadingPattern {
10162 constructor(IR) {
10163 super();
10164 this._type = IR[1];
10165 this._bbox = IR[2];
10166 this._colorStops = IR[3];
10167 this._p0 = IR[4];
10168 this._p1 = IR[5];
10169 this._r0 = IR[6];
10170 this._r1 = IR[7];
10171 this.matrix = null;
10172 }
10173 _createGradient(ctx) {
10174 let grad;
10175 if (this._type === "axial") {
10176 grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
10177 } else if (this._type === "radial") {
10178 grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
10179 }
10180 for (const colorStop of this._colorStops) {
10181 grad.addColorStop(colorStop[0], colorStop[1]);
10182 }
10183 return grad;
10184 }
10185 getPattern(ctx, owner, inverse, pathType) {
10186 let pattern;
10187 if (pathType === PathType.STROKE || pathType === PathType.FILL) {
10188 const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
10189 const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
10190 const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
10191 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
10192 const tmpCtx = tmpCanvas.context;
10193 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
10194 tmpCtx.beginPath();
10195 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
10196 tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
10197 inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
10198 tmpCtx.transform(...owner.baseTransform);
10199 if (this.matrix) {
10200 tmpCtx.transform(...this.matrix);
10201 }
10202 applyBoundingBox(tmpCtx, this._bbox);
10203 tmpCtx.fillStyle = this._createGradient(tmpCtx);
10204 tmpCtx.fill();
10205 pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
10206 const domMatrix = new DOMMatrix(inverse);
10207 pattern.setTransform(domMatrix);
10208 } else {
10209 applyBoundingBox(ctx, this._bbox);
10210 pattern = this._createGradient(ctx);
10211 }
10212 return pattern;
10213 }
10214 }
10215 function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
10216 const coords = context.coords,
10217 colors = context.colors;
10218 const bytes = data.data,
10219 rowSize = data.width * 4;
10220 let tmp;
10221 if (coords[p1 + 1] > coords[p2 + 1]) {
10222 tmp = p1;
10223 p1 = p2;
10224 p2 = tmp;
10225 tmp = c1;
10226 c1 = c2;
10227 c2 = tmp;
10228 }
10229 if (coords[p2 + 1] > coords[p3 + 1]) {
10230 tmp = p2;
10231 p2 = p3;
10232 p3 = tmp;
10233 tmp = c2;
10234 c2 = c3;
10235 c3 = tmp;
10236 }
10237 if (coords[p1 + 1] > coords[p2 + 1]) {
10238 tmp = p1;
10239 p1 = p2;
10240 p2 = tmp;
10241 tmp = c1;
10242 c1 = c2;
10243 c2 = tmp;
10244 }
10245 const x1 = (coords[p1] + context.offsetX) * context.scaleX;
10246 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
10247 const x2 = (coords[p2] + context.offsetX) * context.scaleX;
10248 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
10249 const x3 = (coords[p3] + context.offsetX) * context.scaleX;
10250 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
10251 if (y1 >= y3) {
10252 return;
10253 }
10254 const c1r = colors[c1],
10255 c1g = colors[c1 + 1],
10256 c1b = colors[c1 + 2];
10257 const c2r = colors[c2],
10258 c2g = colors[c2 + 1],
10259 c2b = colors[c2 + 2];
10260 const c3r = colors[c3],
10261 c3g = colors[c3 + 1],
10262 c3b = colors[c3 + 2];
10263 const minY = Math.round(y1),
10264 maxY = Math.round(y3);
10265 let xa, car, cag, cab;
10266 let xb, cbr, cbg, cbb;
10267 for (let y = minY; y <= maxY; y++) {
10268 if (y < y2) {
10269 const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
10270 xa = x1 - (x1 - x2) * k;
10271 car = c1r - (c1r - c2r) * k;
10272 cag = c1g - (c1g - c2g) * k;
10273 cab = c1b - (c1b - c2b) * k;
10274 } else {
10275 let k;
10276 if (y > y3) {
10277 k = 1;
10278 } else if (y2 === y3) {
10279 k = 0;
10280 } else {
10281 k = (y2 - y) / (y2 - y3);
10282 }
10283 xa = x2 - (x2 - x3) * k;
10284 car = c2r - (c2r - c3r) * k;
10285 cag = c2g - (c2g - c3g) * k;
10286 cab = c2b - (c2b - c3b) * k;
10287 }
10288 let k;
10289 if (y < y1) {
10290 k = 0;
10291 } else if (y > y3) {
10292 k = 1;
10293 } else {
10294 k = (y1 - y) / (y1 - y3);
10295 }
10296 xb = x1 - (x1 - x3) * k;
10297 cbr = c1r - (c1r - c3r) * k;
10298 cbg = c1g - (c1g - c3g) * k;
10299 cbb = c1b - (c1b - c3b) * k;
10300 const x1_ = Math.round(Math.min(xa, xb));
10301 const x2_ = Math.round(Math.max(xa, xb));
10302 let j = rowSize * y + x1_ * 4;
10303 for (let x = x1_; x <= x2_; x++) {
10304 k = (xa - x) / (xa - xb);
10305 if (k < 0) {
10306 k = 0;
10307 } else if (k > 1) {
10308 k = 1;
10309 }
10310 bytes[j++] = car - (car - cbr) * k | 0;
10311 bytes[j++] = cag - (cag - cbg) * k | 0;
10312 bytes[j++] = cab - (cab - cbb) * k | 0;
10313 bytes[j++] = 255;
10314 }
10315 }
10316 }
10317 function drawFigure(data, figure, context) {
10318 const ps = figure.coords;
10319 const cs = figure.colors;
10320 let i, ii;
10321 switch (figure.type) {
10322 case "lattice":
10323 const verticesPerRow = figure.verticesPerRow;
10324 const rows = Math.floor(ps.length / verticesPerRow) - 1;
10325 const cols = verticesPerRow - 1;
10326 for (i = 0; i < rows; i++) {
10327 let q = i * verticesPerRow;
10328 for (let j = 0; j < cols; j++, q++) {
10329 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
10330 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
10331 }
10332 }
10333 break;
10334 case "triangles":
10335 for (i = 0, ii = ps.length; i < ii; i += 3) {
10336 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
10337 }
10338 break;
10339 default:
10340 throw new Error("illegal figure");
10341 }
10342 }
10343 class MeshShadingPattern extends BaseShadingPattern {
10344 constructor(IR) {
10345 super();
10346 this._coords = IR[2];
10347 this._colors = IR[3];
10348 this._figures = IR[4];
10349 this._bounds = IR[5];
10350 this._bbox = IR[7];
10351 this._background = IR[8];
10352 this.matrix = null;
10353 }
10354 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
10355 const EXPECTED_SCALE = 1.1;
10356 const MAX_PATTERN_SIZE = 3000;
10357 const BORDER_SIZE = 2;
10358 const offsetX = Math.floor(this._bounds[0]);
10359 const offsetY = Math.floor(this._bounds[1]);
10360 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
10361 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
10362 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
10363 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
10364 const scaleX = boundsWidth / width;
10365 const scaleY = boundsHeight / height;
10366 const context = {
10367 coords: this._coords,
10368 colors: this._colors,
10369 offsetX: -offsetX,
10370 offsetY: -offsetY,
10371 scaleX: 1 / scaleX,
10372 scaleY: 1 / scaleY
10373 };
10374 const paddedWidth = width + BORDER_SIZE * 2;
10375 const paddedHeight = height + BORDER_SIZE * 2;
10376 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
10377 const tmpCtx = tmpCanvas.context;
10378 const data = tmpCtx.createImageData(width, height);
10379 if (backgroundColor) {
10380 const bytes = data.data;
10381 for (let i = 0, ii = bytes.length; i < ii; i += 4) {
10382 bytes[i] = backgroundColor[0];
10383 bytes[i + 1] = backgroundColor[1];
10384 bytes[i + 2] = backgroundColor[2];
10385 bytes[i + 3] = 255;
10386 }
10387 }
10388 for (const figure of this._figures) {
10389 drawFigure(data, figure, context);
10390 }
10391 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
10392 const canvas = tmpCanvas.canvas;
10393 return {
10394 canvas,
10395 offsetX: offsetX - BORDER_SIZE * scaleX,
10396 offsetY: offsetY - BORDER_SIZE * scaleY,
10397 scaleX,
10398 scaleY
10399 };
10400 }
10401 getPattern(ctx, owner, inverse, pathType) {
10402 applyBoundingBox(ctx, this._bbox);
10403 let scale;
10404 if (pathType === PathType.SHADING) {
10405 scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));
10406 } else {
10407 scale = Util.singularValueDecompose2dScale(owner.baseTransform);
10408 if (this.matrix) {
10409 const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
10410 scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
10411 }
10412 }
10413 const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
10414 if (pathType !== PathType.SHADING) {
10415 ctx.setTransform(...owner.baseTransform);
10416 if (this.matrix) {
10417 ctx.transform(...this.matrix);
10418 }
10419 }
10420 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
10421 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
10422 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
10423 }
10424 }
10425 class DummyShadingPattern extends BaseShadingPattern {
10426 getPattern() {
10427 return "hotpink";
10428 }
10429 }
10430 function getShadingPattern(IR) {
10431 switch (IR[0]) {
10432 case "RadialAxial":
10433 return new RadialAxialShadingPattern(IR);
10434 case "Mesh":
10435 return new MeshShadingPattern(IR);
10436 case "Dummy":
10437 return new DummyShadingPattern();
10438 }
10439 throw new Error(`Unknown IR type: ${IR[0]}`);
10440 }
10441 const PaintType = {
10442 COLORED: 1,
10443 UNCOLORED: 2
10444 };
10445 class TilingPattern {
10446 static MAX_PATTERN_SIZE = 3000;
10447 constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
10448 this.operatorList = IR[2];
10449 this.matrix = IR[3];
10450 this.bbox = IR[4];
10451 this.xstep = IR[5];
10452 this.ystep = IR[6];
10453 this.paintType = IR[7];
10454 this.tilingType = IR[8];
10455 this.color = color;
10456 this.ctx = ctx;
10457 this.canvasGraphicsFactory = canvasGraphicsFactory;
10458 this.baseTransform = baseTransform;
10459 }
10460 createPatternCanvas(owner) {
10461 const operatorList = this.operatorList;
10462 const bbox = this.bbox;
10463 const xstep = this.xstep;
10464 const ystep = this.ystep;
10465 const paintType = this.paintType;
10466 const tilingType = this.tilingType;
10467 const color = this.color;
10468 const canvasGraphicsFactory = this.canvasGraphicsFactory;
10469 info("TilingType: " + tilingType);
10470 const x0 = bbox[0],
10471 y0 = bbox[1],
10472 x1 = bbox[2],
10473 y1 = bbox[3];
10474 const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
10475 const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
10476 const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
10477 const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
10478 const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
10479 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
10480 const tmpCtx = tmpCanvas.context;
10481 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
10482 graphics.groupLevel = owner.groupLevel;
10483 this.setFillAndStrokeStyleToContext(graphics, paintType, color);
10484 let adjustedX0 = x0;
10485 let adjustedY0 = y0;
10486 let adjustedX1 = x1;
10487 let adjustedY1 = y1;
10488 if (x0 < 0) {
10489 adjustedX0 = 0;
10490 adjustedX1 += Math.abs(x0);
10491 }
10492 if (y0 < 0) {
10493 adjustedY0 = 0;
10494 adjustedY1 += Math.abs(y0);
10495 }
10496 tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
10497 graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
10498 tmpCtx.save();
10499 this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
10500 graphics.baseTransform = getCurrentTransform(graphics.ctx);
10501 graphics.executeOperatorList(operatorList);
10502 graphics.endDrawing();
10503 return {
10504 canvas: tmpCanvas.canvas,
10505 scaleX: dimx.scale,
10506 scaleY: dimy.scale,
10507 offsetX: adjustedX0,
10508 offsetY: adjustedY0
10509 };
10510 }
10511 getSizeAndScale(step, realOutputSize, scale) {
10512 step = Math.abs(step);
10513 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
10514 let size = Math.ceil(step * scale);
10515 if (size >= maxSize) {
10516 size = maxSize;
10517 } else {
10518 scale = size / step;
10519 }
10520 return {
10521 scale,
10522 size
10523 };
10524 }
10525 clipBbox(graphics, x0, y0, x1, y1) {
10526 const bboxWidth = x1 - x0;
10527 const bboxHeight = y1 - y0;
10528 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
10529 graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]);
10530 graphics.clip();
10531 graphics.endPath();
10532 }
10533 setFillAndStrokeStyleToContext(graphics, paintType, color) {
10534 const context = graphics.ctx,
10535 current = graphics.current;
10536 switch (paintType) {
10537 case PaintType.COLORED:
10538 const ctx = this.ctx;
10539 context.fillStyle = ctx.fillStyle;
10540 context.strokeStyle = ctx.strokeStyle;
10541 current.fillColor = ctx.fillStyle;
10542 current.strokeColor = ctx.strokeStyle;
10543 break;
10544 case PaintType.UNCOLORED:
10545 const cssColor = Util.makeHexColor(color[0], color[1], color[2]);
10546 context.fillStyle = cssColor;
10547 context.strokeStyle = cssColor;
10548 current.fillColor = cssColor;
10549 current.strokeColor = cssColor;
10550 break;
10551 default:
10552 throw new FormatError(`Unsupported paint type: ${paintType}`);
10553 }
10554 }
10555 getPattern(ctx, owner, inverse, pathType) {
10556 let matrix = inverse;
10557 if (pathType !== PathType.SHADING) {
10558 matrix = Util.transform(matrix, owner.baseTransform);
10559 if (this.matrix) {
10560 matrix = Util.transform(matrix, this.matrix);
10561 }
10562 }
10563 const temporaryPatternCanvas = this.createPatternCanvas(owner);
10564 let domMatrix = new DOMMatrix(matrix);
10565 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
10566 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
10567 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
10568 pattern.setTransform(domMatrix);
10569 return pattern;
10570 }
10571 }
10572
10573 ;// CONCATENATED MODULE: ./src/shared/image_utils.js
10574
10575
10576
10577
10578
10579
10580
10581 function convertToRGBA(params) {
10582 switch (params.kind) {
10583 case ImageKind.GRAYSCALE_1BPP:
10584 return convertBlackAndWhiteToRGBA(params);
10585 case ImageKind.RGB_24BPP:
10586 return convertRGBToRGBA(params);
10587 }
10588 return null;
10589 }
10590 function convertBlackAndWhiteToRGBA({
10591 src,
10592 srcPos = 0,
10593 dest,
10594 width,
10595 height,
10596 nonBlackColor = 0xffffffff,
10597 inverseDecode = false
10598 }) {
10599 const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
10600 const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
10601 const widthInSource = width >> 3;
10602 const widthRemainder = width & 7;
10603 const srcLength = src.length;
10604 dest = new Uint32Array(dest.buffer);
10605 let destPos = 0;
10606 for (let i = 0; i < height; i++) {
10607 for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
10608 const elem = srcPos < srcLength ? src[srcPos] : 255;
10609 dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
10610 dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
10611 dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
10612 dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
10613 dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
10614 dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
10615 dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
10616 dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
10617 }
10618 if (widthRemainder === 0) {
10619 continue;
10620 }
10621 const elem = srcPos < srcLength ? src[srcPos++] : 255;
10622 for (let j = 0; j < widthRemainder; j++) {
10623 dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
10624 }
10625 }
10626 return {
10627 srcPos,
10628 destPos
10629 };
10630 }
10631 function convertRGBToRGBA({
10632 src,
10633 srcPos = 0,
10634 dest,
10635 destPos = 0,
10636 width,
10637 height
10638 }) {
10639 let i = 0;
10640 const len32 = src.length >> 2;
10641 const src32 = new Uint32Array(src.buffer, srcPos, len32);
10642 if (FeatureTest.isLittleEndian) {
10643 for (; i < len32 - 2; i += 3, destPos += 4) {
10644 const s1 = src32[i];
10645 const s2 = src32[i + 1];
10646 const s3 = src32[i + 2];
10647 dest[destPos] = s1 | 0xff000000;
10648 dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
10649 dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
10650 dest[destPos + 3] = s3 >>> 8 | 0xff000000;
10651 }
10652 for (let j = i * 4, jj = src.length; j < jj; j += 3) {
10653 dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
10654 }
10655 } else {
10656 for (; i < len32 - 2; i += 3, destPos += 4) {
10657 const s1 = src32[i];
10658 const s2 = src32[i + 1];
10659 const s3 = src32[i + 2];
10660 dest[destPos] = s1 | 0xff;
10661 dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
10662 dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
10663 dest[destPos + 3] = s3 << 8 | 0xff;
10664 }
10665 for (let j = i * 4, jj = src.length; j < jj; j += 3) {
10666 dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
10667 }
10668 }
10669 return {
10670 srcPos,
10671 destPos
10672 };
10673 }
10674 function grayToRGBA(src, dest) {
10675 if (FeatureTest.isLittleEndian) {
10676 for (let i = 0, ii = src.length; i < ii; i++) {
10677 dest[i] = src[i] * 0x10101 | 0xff000000;
10678 }
10679 } else {
10680 for (let i = 0, ii = src.length; i < ii; i++) {
10681 dest[i] = src[i] * 0x1010100 | 0x000000ff;
10682 }
10683 }
10684 }
10685
10686 ;// CONCATENATED MODULE: ./src/display/canvas.js
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702 const MIN_FONT_SIZE = 16;
10703 const MAX_FONT_SIZE = 100;
10704 const EXECUTION_TIME = 15;
10705 const EXECUTION_STEPS = 10;
10706 const MAX_SIZE_TO_COMPILE = 1000;
10707 const FULL_CHUNK_HEIGHT = 16;
10708 function mirrorContextOperations(ctx, destCtx) {
10709 if (ctx._removeMirroring) {
10710 throw new Error("Context is already forwarding operations.");
10711 }
10712 ctx.__originalSave = ctx.save;
10713 ctx.__originalRestore = ctx.restore;
10714 ctx.__originalRotate = ctx.rotate;
10715 ctx.__originalScale = ctx.scale;
10716 ctx.__originalTranslate = ctx.translate;
10717 ctx.__originalTransform = ctx.transform;
10718 ctx.__originalSetTransform = ctx.setTransform;
10719 ctx.__originalResetTransform = ctx.resetTransform;
10720 ctx.__originalClip = ctx.clip;
10721 ctx.__originalMoveTo = ctx.moveTo;
10722 ctx.__originalLineTo = ctx.lineTo;
10723 ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
10724 ctx.__originalRect = ctx.rect;
10725 ctx.__originalClosePath = ctx.closePath;
10726 ctx.__originalBeginPath = ctx.beginPath;
10727 ctx._removeMirroring = () => {
10728 ctx.save = ctx.__originalSave;
10729 ctx.restore = ctx.__originalRestore;
10730 ctx.rotate = ctx.__originalRotate;
10731 ctx.scale = ctx.__originalScale;
10732 ctx.translate = ctx.__originalTranslate;
10733 ctx.transform = ctx.__originalTransform;
10734 ctx.setTransform = ctx.__originalSetTransform;
10735 ctx.resetTransform = ctx.__originalResetTransform;
10736 ctx.clip = ctx.__originalClip;
10737 ctx.moveTo = ctx.__originalMoveTo;
10738 ctx.lineTo = ctx.__originalLineTo;
10739 ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
10740 ctx.rect = ctx.__originalRect;
10741 ctx.closePath = ctx.__originalClosePath;
10742 ctx.beginPath = ctx.__originalBeginPath;
10743 delete ctx._removeMirroring;
10744 };
10745 ctx.save = function ctxSave() {
10746 destCtx.save();
10747 this.__originalSave();
10748 };
10749 ctx.restore = function ctxRestore() {
10750 destCtx.restore();
10751 this.__originalRestore();
10752 };
10753 ctx.translate = function ctxTranslate(x, y) {
10754 destCtx.translate(x, y);
10755 this.__originalTranslate(x, y);
10756 };
10757 ctx.scale = function ctxScale(x, y) {
10758 destCtx.scale(x, y);
10759 this.__originalScale(x, y);
10760 };
10761 ctx.transform = function ctxTransform(a, b, c, d, e, f) {
10762 destCtx.transform(a, b, c, d, e, f);
10763 this.__originalTransform(a, b, c, d, e, f);
10764 };
10765 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
10766 destCtx.setTransform(a, b, c, d, e, f);
10767 this.__originalSetTransform(a, b, c, d, e, f);
10768 };
10769 ctx.resetTransform = function ctxResetTransform() {
10770 destCtx.resetTransform();
10771 this.__originalResetTransform();
10772 };
10773 ctx.rotate = function ctxRotate(angle) {
10774 destCtx.rotate(angle);
10775 this.__originalRotate(angle);
10776 };
10777 ctx.clip = function ctxRotate(rule) {
10778 destCtx.clip(rule);
10779 this.__originalClip(rule);
10780 };
10781 ctx.moveTo = function (x, y) {
10782 destCtx.moveTo(x, y);
10783 this.__originalMoveTo(x, y);
10784 };
10785 ctx.lineTo = function (x, y) {
10786 destCtx.lineTo(x, y);
10787 this.__originalLineTo(x, y);
10788 };
10789 ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
10790 destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
10791 this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
10792 };
10793 ctx.rect = function (x, y, width, height) {
10794 destCtx.rect(x, y, width, height);
10795 this.__originalRect(x, y, width, height);
10796 };
10797 ctx.closePath = function () {
10798 destCtx.closePath();
10799 this.__originalClosePath();
10800 };
10801 ctx.beginPath = function () {
10802 destCtx.beginPath();
10803 this.__originalBeginPath();
10804 };
10805 }
10806 class CachedCanvases {
10807 constructor(canvasFactory) {
10808 this.canvasFactory = canvasFactory;
10809 this.cache = Object.create(null);
10810 }
10811 getCanvas(id, width, height) {
10812 let canvasEntry;
10813 if (this.cache[id] !== undefined) {
10814 canvasEntry = this.cache[id];
10815 this.canvasFactory.reset(canvasEntry, width, height);
10816 } else {
10817 canvasEntry = this.canvasFactory.create(width, height);
10818 this.cache[id] = canvasEntry;
10819 }
10820 return canvasEntry;
10821 }
10822 delete(id) {
10823 delete this.cache[id];
10824 }
10825 clear() {
10826 for (const id in this.cache) {
10827 const canvasEntry = this.cache[id];
10828 this.canvasFactory.destroy(canvasEntry);
10829 delete this.cache[id];
10830 }
10831 }
10832 }
10833 function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
10834 const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
10835 if (b === 0 && c === 0) {
10836 const tlX = destX * a + tx;
10837 const rTlX = Math.round(tlX);
10838 const tlY = destY * d + ty;
10839 const rTlY = Math.round(tlY);
10840 const brX = (destX + destW) * a + tx;
10841 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
10842 const brY = (destY + destH) * d + ty;
10843 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
10844 ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
10845 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
10846 ctx.setTransform(a, b, c, d, tx, ty);
10847 return [rWidth, rHeight];
10848 }
10849 if (a === 0 && d === 0) {
10850 const tlX = destY * c + tx;
10851 const rTlX = Math.round(tlX);
10852 const tlY = destX * b + ty;
10853 const rTlY = Math.round(tlY);
10854 const brX = (destY + destH) * c + tx;
10855 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
10856 const brY = (destX + destW) * b + ty;
10857 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
10858 ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
10859 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
10860 ctx.setTransform(a, b, c, d, tx, ty);
10861 return [rHeight, rWidth];
10862 }
10863 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
10864 const scaleX = Math.hypot(a, b);
10865 const scaleY = Math.hypot(c, d);
10866 return [scaleX * destW, scaleY * destH];
10867 }
10868 function compileType3Glyph(imgData) {
10869 const {
10870 width,
10871 height
10872 } = imgData;
10873 if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
10874 return null;
10875 }
10876 const POINT_TO_PROCESS_LIMIT = 1000;
10877 const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
10878 const width1 = width + 1;
10879 let points = new Uint8Array(width1 * (height + 1));
10880 let i, j, j0;
10881 const lineSize = width + 7 & ~7;
10882 let data = new Uint8Array(lineSize * height),
10883 pos = 0;
10884 for (const elem of imgData.data) {
10885 let mask = 128;
10886 while (mask > 0) {
10887 data[pos++] = elem & mask ? 0 : 255;
10888 mask >>= 1;
10889 }
10890 }
10891 let count = 0;
10892 pos = 0;
10893 if (data[pos] !== 0) {
10894 points[0] = 1;
10895 ++count;
10896 }
10897 for (j = 1; j < width; j++) {
10898 if (data[pos] !== data[pos + 1]) {
10899 points[j] = data[pos] ? 2 : 1;
10900 ++count;
10901 }
10902 pos++;
10903 }
10904 if (data[pos] !== 0) {
10905 points[j] = 2;
10906 ++count;
10907 }
10908 for (i = 1; i < height; i++) {
10909 pos = i * lineSize;
10910 j0 = i * width1;
10911 if (data[pos - lineSize] !== data[pos]) {
10912 points[j0] = data[pos] ? 1 : 8;
10913 ++count;
10914 }
10915 let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
10916 for (j = 1; j < width; j++) {
10917 sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
10918 if (POINT_TYPES[sum]) {
10919 points[j0 + j] = POINT_TYPES[sum];
10920 ++count;
10921 }
10922 pos++;
10923 }
10924 if (data[pos - lineSize] !== data[pos]) {
10925 points[j0 + j] = data[pos] ? 2 : 4;
10926 ++count;
10927 }
10928 if (count > POINT_TO_PROCESS_LIMIT) {
10929 return null;
10930 }
10931 }
10932 pos = lineSize * (height - 1);
10933 j0 = i * width1;
10934 if (data[pos] !== 0) {
10935 points[j0] = 8;
10936 ++count;
10937 }
10938 for (j = 1; j < width; j++) {
10939 if (data[pos] !== data[pos + 1]) {
10940 points[j0 + j] = data[pos] ? 4 : 8;
10941 ++count;
10942 }
10943 pos++;
10944 }
10945 if (data[pos] !== 0) {
10946 points[j0 + j] = 4;
10947 ++count;
10948 }
10949 if (count > POINT_TO_PROCESS_LIMIT) {
10950 return null;
10951 }
10952 const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
10953 const path = new Path2D();
10954 for (i = 0; count && i <= height; i++) {
10955 let p = i * width1;
10956 const end = p + width;
10957 while (p < end && !points[p]) {
10958 p++;
10959 }
10960 if (p === end) {
10961 continue;
10962 }
10963 path.moveTo(p % width1, i);
10964 const p0 = p;
10965 let type = points[p];
10966 do {
10967 const step = steps[type];
10968 do {
10969 p += step;
10970 } while (!points[p]);
10971 const pp = points[p];
10972 if (pp !== 5 && pp !== 10) {
10973 type = pp;
10974 points[p] = 0;
10975 } else {
10976 type = pp & 0x33 * type >> 4;
10977 points[p] &= type >> 2 | type << 2;
10978 }
10979 path.lineTo(p % width1, p / width1 | 0);
10980 if (!points[p]) {
10981 --count;
10982 }
10983 } while (p0 !== p);
10984 --i;
10985 }
10986 data = null;
10987 points = null;
10988 const drawOutline = function (c) {
10989 c.save();
10990 c.scale(1 / width, -1 / height);
10991 c.translate(0, -height);
10992 c.fill(path);
10993 c.beginPath();
10994 c.restore();
10995 };
10996 return drawOutline;
10997 }
10998 class CanvasExtraState {
10999 constructor(width, height) {
11000 this.alphaIsShape = false;
11001 this.fontSize = 0;
11002 this.fontSizeScale = 1;
11003 this.textMatrix = IDENTITY_MATRIX;
11004 this.textMatrixScale = 1;
11005 this.fontMatrix = FONT_IDENTITY_MATRIX;
11006 this.leading = 0;
11007 this.x = 0;
11008 this.y = 0;
11009 this.lineX = 0;
11010 this.lineY = 0;
11011 this.charSpacing = 0;
11012 this.wordSpacing = 0;
11013 this.textHScale = 1;
11014 this.textRenderingMode = TextRenderingMode.FILL;
11015 this.textRise = 0;
11016 this.fillColor = "#000000";
11017 this.strokeColor = "#000000";
11018 this.patternFill = false;
11019 this.fillAlpha = 1;
11020 this.strokeAlpha = 1;
11021 this.lineWidth = 1;
11022 this.activeSMask = null;
11023 this.transferMaps = "none";
11024 this.startNewPathAndClipBox([0, 0, width, height]);
11025 }
11026 clone() {
11027 const clone = Object.create(this);
11028 clone.clipBox = this.clipBox.slice();
11029 return clone;
11030 }
11031 setCurrentPoint(x, y) {
11032 this.x = x;
11033 this.y = y;
11034 }
11035 updatePathMinMax(transform, x, y) {
11036 [x, y] = Util.applyTransform([x, y], transform);
11037 this.minX = Math.min(this.minX, x);
11038 this.minY = Math.min(this.minY, y);
11039 this.maxX = Math.max(this.maxX, x);
11040 this.maxY = Math.max(this.maxY, y);
11041 }
11042 updateRectMinMax(transform, rect) {
11043 const p1 = Util.applyTransform(rect, transform);
11044 const p2 = Util.applyTransform(rect.slice(2), transform);
11045 const p3 = Util.applyTransform([rect[0], rect[3]], transform);
11046 const p4 = Util.applyTransform([rect[2], rect[1]], transform);
11047 this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);
11048 this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);
11049 this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);
11050 this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);
11051 }
11052 updateScalingPathMinMax(transform, minMax) {
11053 Util.scaleMinMax(transform, minMax);
11054 this.minX = Math.min(this.minX, minMax[0]);
11055 this.minY = Math.min(this.minY, minMax[1]);
11056 this.maxX = Math.max(this.maxX, minMax[2]);
11057 this.maxY = Math.max(this.maxY, minMax[3]);
11058 }
11059 updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
11060 const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);
11061 if (minMax) {
11062 return;
11063 }
11064 this.updateRectMinMax(transform, box);
11065 }
11066 getPathBoundingBox(pathType = PathType.FILL, transform = null) {
11067 const box = [this.minX, this.minY, this.maxX, this.maxY];
11068 if (pathType === PathType.STROKE) {
11069 if (!transform) {
11070 unreachable("Stroke bounding box must include transform.");
11071 }
11072 const scale = Util.singularValueDecompose2dScale(transform);
11073 const xStrokePad = scale[0] * this.lineWidth / 2;
11074 const yStrokePad = scale[1] * this.lineWidth / 2;
11075 box[0] -= xStrokePad;
11076 box[1] -= yStrokePad;
11077 box[2] += xStrokePad;
11078 box[3] += yStrokePad;
11079 }
11080 return box;
11081 }
11082 updateClipFromPath() {
11083 const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
11084 this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
11085 }
11086 isEmptyClip() {
11087 return this.minX === Infinity;
11088 }
11089 startNewPathAndClipBox(box) {
11090 this.clipBox = box;
11091 this.minX = Infinity;
11092 this.minY = Infinity;
11093 this.maxX = 0;
11094 this.maxY = 0;
11095 }
11096 getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
11097 return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
11098 }
11099 }
11100 function putBinaryImageData(ctx, imgData) {
11101 if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
11102 ctx.putImageData(imgData, 0, 0);
11103 return;
11104 }
11105 const height = imgData.height,
11106 width = imgData.width;
11107 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
11108 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
11109 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
11110 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
11111 let srcPos = 0,
11112 destPos;
11113 const src = imgData.data;
11114 const dest = chunkImgData.data;
11115 let i, j, thisChunkHeight, elemsInThisChunk;
11116 if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
11117 const srcLength = src.byteLength;
11118 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
11119 const dest32DataLength = dest32.length;
11120 const fullSrcDiff = width + 7 >> 3;
11121 const white = 0xffffffff;
11122 const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
11123 for (i = 0; i < totalChunks; i++) {
11124 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
11125 destPos = 0;
11126 for (j = 0; j < thisChunkHeight; j++) {
11127 const srcDiff = srcLength - srcPos;
11128 let k = 0;
11129 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
11130 const kEndUnrolled = kEnd & ~7;
11131 let mask = 0;
11132 let srcByte = 0;
11133 for (; k < kEndUnrolled; k += 8) {
11134 srcByte = src[srcPos++];
11135 dest32[destPos++] = srcByte & 128 ? white : black;
11136 dest32[destPos++] = srcByte & 64 ? white : black;
11137 dest32[destPos++] = srcByte & 32 ? white : black;
11138 dest32[destPos++] = srcByte & 16 ? white : black;
11139 dest32[destPos++] = srcByte & 8 ? white : black;
11140 dest32[destPos++] = srcByte & 4 ? white : black;
11141 dest32[destPos++] = srcByte & 2 ? white : black;
11142 dest32[destPos++] = srcByte & 1 ? white : black;
11143 }
11144 for (; k < kEnd; k++) {
11145 if (mask === 0) {
11146 srcByte = src[srcPos++];
11147 mask = 128;
11148 }
11149 dest32[destPos++] = srcByte & mask ? white : black;
11150 mask >>= 1;
11151 }
11152 }
11153 while (destPos < dest32DataLength) {
11154 dest32[destPos++] = 0;
11155 }
11156 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
11157 }
11158 } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
11159 j = 0;
11160 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
11161 for (i = 0; i < fullChunks; i++) {
11162 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
11163 srcPos += elemsInThisChunk;
11164 ctx.putImageData(chunkImgData, 0, j);
11165 j += FULL_CHUNK_HEIGHT;
11166 }
11167 if (i < totalChunks) {
11168 elemsInThisChunk = width * partialChunkHeight * 4;
11169 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
11170 ctx.putImageData(chunkImgData, 0, j);
11171 }
11172 } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
11173 thisChunkHeight = FULL_CHUNK_HEIGHT;
11174 elemsInThisChunk = width * thisChunkHeight;
11175 for (i = 0; i < totalChunks; i++) {
11176 if (i >= fullChunks) {
11177 thisChunkHeight = partialChunkHeight;
11178 elemsInThisChunk = width * thisChunkHeight;
11179 }
11180 destPos = 0;
11181 for (j = elemsInThisChunk; j--;) {
11182 dest[destPos++] = src[srcPos++];
11183 dest[destPos++] = src[srcPos++];
11184 dest[destPos++] = src[srcPos++];
11185 dest[destPos++] = 255;
11186 }
11187 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
11188 }
11189 } else {
11190 throw new Error(`bad image kind: ${imgData.kind}`);
11191 }
11192 }
11193 function putBinaryImageMask(ctx, imgData) {
11194 if (imgData.bitmap) {
11195 ctx.drawImage(imgData.bitmap, 0, 0);
11196 return;
11197 }
11198 const height = imgData.height,
11199 width = imgData.width;
11200 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
11201 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
11202 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
11203 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
11204 let srcPos = 0;
11205 const src = imgData.data;
11206 const dest = chunkImgData.data;
11207 for (let i = 0; i < totalChunks; i++) {
11208 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
11209 ({
11210 srcPos
11211 } = convertBlackAndWhiteToRGBA({
11212 src,
11213 srcPos,
11214 dest,
11215 width,
11216 height: thisChunkHeight,
11217 nonBlackColor: 0
11218 }));
11219 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
11220 }
11221 }
11222 function copyCtxState(sourceCtx, destCtx) {
11223 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
11224 for (const property of properties) {
11225 if (sourceCtx[property] !== undefined) {
11226 destCtx[property] = sourceCtx[property];
11227 }
11228 }
11229 if (sourceCtx.setLineDash !== undefined) {
11230 destCtx.setLineDash(sourceCtx.getLineDash());
11231 destCtx.lineDashOffset = sourceCtx.lineDashOffset;
11232 }
11233 }
11234 function resetCtxToDefault(ctx) {
11235 ctx.strokeStyle = ctx.fillStyle = "#000000";
11236 ctx.fillRule = "nonzero";
11237 ctx.globalAlpha = 1;
11238 ctx.lineWidth = 1;
11239 ctx.lineCap = "butt";
11240 ctx.lineJoin = "miter";
11241 ctx.miterLimit = 10;
11242 ctx.globalCompositeOperation = "source-over";
11243 ctx.font = "10px sans-serif";
11244 if (ctx.setLineDash !== undefined) {
11245 ctx.setLineDash([]);
11246 ctx.lineDashOffset = 0;
11247 }
11248 if (!isNodeJS) {
11249 const {
11250 filter
11251 } = ctx;
11252 if (filter !== "none" && filter !== "") {
11253 ctx.filter = "none";
11254 }
11255 }
11256 }
11257 function getImageSmoothingEnabled(transform, interpolate) {
11258 if (interpolate) {
11259 return true;
11260 }
11261 const scale = Util.singularValueDecompose2dScale(transform);
11262 scale[0] = Math.fround(scale[0]);
11263 scale[1] = Math.fround(scale[1]);
11264 const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS);
11265 return scale[0] <= actualScale && scale[1] <= actualScale;
11266 }
11267 const LINE_CAP_STYLES = ["butt", "round", "square"];
11268 const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
11269 const NORMAL_CLIP = {};
11270 const EO_CLIP = {};
11271 class CanvasGraphics {
11272 constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
11273 optionalContentConfig,
11274 markedContentStack = null
11275 }, annotationCanvasMap, pageColors) {
11276 this.ctx = canvasCtx;
11277 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
11278 this.stateStack = [];
11279 this.pendingClip = null;
11280 this.pendingEOFill = false;
11281 this.res = null;
11282 this.xobjs = null;
11283 this.commonObjs = commonObjs;
11284 this.objs = objs;
11285 this.canvasFactory = canvasFactory;
11286 this.filterFactory = filterFactory;
11287 this.groupStack = [];
11288 this.processingType3 = null;
11289 this.baseTransform = null;
11290 this.baseTransformStack = [];
11291 this.groupLevel = 0;
11292 this.smaskStack = [];
11293 this.smaskCounter = 0;
11294 this.tempSMask = null;
11295 this.suspendedCtx = null;
11296 this.contentVisible = true;
11297 this.markedContentStack = markedContentStack || [];
11298 this.optionalContentConfig = optionalContentConfig;
11299 this.cachedCanvases = new CachedCanvases(this.canvasFactory);
11300 this.cachedPatterns = new Map();
11301 this.annotationCanvasMap = annotationCanvasMap;
11302 this.viewportScale = 1;
11303 this.outputScaleX = 1;
11304 this.outputScaleY = 1;
11305 this.pageColors = pageColors;
11306 this._cachedScaleForStroking = [-1, 0];
11307 this._cachedGetSinglePixelWidth = null;
11308 this._cachedBitmapsMap = new Map();
11309 }
11310 getObject(data, fallback = null) {
11311 if (typeof data === "string") {
11312 return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
11313 }
11314 return fallback;
11315 }
11316 beginDrawing({
11317 transform,
11318 viewport,
11319 transparency = false,
11320 background = null
11321 }) {
11322 const width = this.ctx.canvas.width;
11323 const height = this.ctx.canvas.height;
11324 const savedFillStyle = this.ctx.fillStyle;
11325 this.ctx.fillStyle = background || "#ffffff";
11326 this.ctx.fillRect(0, 0, width, height);
11327 this.ctx.fillStyle = savedFillStyle;
11328 if (transparency) {
11329 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
11330 this.compositeCtx = this.ctx;
11331 this.transparentCanvas = transparentCanvas.canvas;
11332 this.ctx = transparentCanvas.context;
11333 this.ctx.save();
11334 this.ctx.transform(...getCurrentTransform(this.compositeCtx));
11335 }
11336 this.ctx.save();
11337 resetCtxToDefault(this.ctx);
11338 if (transform) {
11339 this.ctx.transform(...transform);
11340 this.outputScaleX = transform[0];
11341 this.outputScaleY = transform[0];
11342 }
11343 this.ctx.transform(...viewport.transform);
11344 this.viewportScale = viewport.scale;
11345 this.baseTransform = getCurrentTransform(this.ctx);
11346 }
11347 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
11348 const argsArray = operatorList.argsArray;
11349 const fnArray = operatorList.fnArray;
11350 let i = executionStartIdx || 0;
11351 const argsArrayLen = argsArray.length;
11352 if (argsArrayLen === i) {
11353 return i;
11354 }
11355 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
11356 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
11357 let steps = 0;
11358 const commonObjs = this.commonObjs;
11359 const objs = this.objs;
11360 let fnId;
11361 while (true) {
11362 if (stepper !== undefined && i === stepper.nextBreakPoint) {
11363 stepper.breakIt(i, continueCallback);
11364 return i;
11365 }
11366 fnId = fnArray[i];
11367 if (fnId !== OPS.dependency) {
11368 this[fnId].apply(this, argsArray[i]);
11369 } else {
11370 for (const depObjId of argsArray[i]) {
11371 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
11372 if (!objsPool.has(depObjId)) {
11373 objsPool.get(depObjId, continueCallback);
11374 return i;
11375 }
11376 }
11377 }
11378 i++;
11379 if (i === argsArrayLen) {
11380 return i;
11381 }
11382 if (chunkOperations && ++steps > EXECUTION_STEPS) {
11383 if (Date.now() > endTime) {
11384 continueCallback();
11385 return i;
11386 }
11387 steps = 0;
11388 }
11389 }
11390 }
11391 #restoreInitialState() {
11392 while (this.stateStack.length || this.inSMaskMode) {
11393 this.restore();
11394 }
11395 this.ctx.restore();
11396 if (this.transparentCanvas) {
11397 this.ctx = this.compositeCtx;
11398 this.ctx.save();
11399 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
11400 this.ctx.drawImage(this.transparentCanvas, 0, 0);
11401 this.ctx.restore();
11402 this.transparentCanvas = null;
11403 }
11404 }
11405 endDrawing() {
11406 this.#restoreInitialState();
11407 this.cachedCanvases.clear();
11408 this.cachedPatterns.clear();
11409 for (const cache of this._cachedBitmapsMap.values()) {
11410 for (const canvas of cache.values()) {
11411 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
11412 canvas.width = canvas.height = 0;
11413 }
11414 }
11415 cache.clear();
11416 }
11417 this._cachedBitmapsMap.clear();
11418 this.#drawFilter();
11419 }
11420 #drawFilter() {
11421 if (this.pageColors) {
11422 const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
11423 if (hcmFilterId !== "none") {
11424 const savedFilter = this.ctx.filter;
11425 this.ctx.filter = hcmFilterId;
11426 this.ctx.drawImage(this.ctx.canvas, 0, 0);
11427 this.ctx.filter = savedFilter;
11428 }
11429 }
11430 }
11431 _scaleImage(img, inverseTransform) {
11432 const width = img.width;
11433 const height = img.height;
11434 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
11435 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
11436 let paintWidth = width,
11437 paintHeight = height;
11438 let tmpCanvasId = "prescale1";
11439 let tmpCanvas, tmpCtx;
11440 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
11441 let newWidth = paintWidth,
11442 newHeight = paintHeight;
11443 if (widthScale > 2 && paintWidth > 1) {
11444 newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
11445 widthScale /= paintWidth / newWidth;
11446 }
11447 if (heightScale > 2 && paintHeight > 1) {
11448 newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
11449 heightScale /= paintHeight / newHeight;
11450 }
11451 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
11452 tmpCtx = tmpCanvas.context;
11453 tmpCtx.clearRect(0, 0, newWidth, newHeight);
11454 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
11455 img = tmpCanvas.canvas;
11456 paintWidth = newWidth;
11457 paintHeight = newHeight;
11458 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
11459 }
11460 return {
11461 img,
11462 paintWidth,
11463 paintHeight
11464 };
11465 }
11466 _createMaskCanvas(img) {
11467 const ctx = this.ctx;
11468 const {
11469 width,
11470 height
11471 } = img;
11472 const fillColor = this.current.fillColor;
11473 const isPatternFill = this.current.patternFill;
11474 const currentTransform = getCurrentTransform(ctx);
11475 let cache, cacheKey, scaled, maskCanvas;
11476 if ((img.bitmap || img.data) && img.count > 1) {
11477 const mainKey = img.bitmap || img.data.buffer;
11478 cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
11479 cache = this._cachedBitmapsMap.get(mainKey);
11480 if (!cache) {
11481 cache = new Map();
11482 this._cachedBitmapsMap.set(mainKey, cache);
11483 }
11484 const cachedImage = cache.get(cacheKey);
11485 if (cachedImage && !isPatternFill) {
11486 const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
11487 const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
11488 return {
11489 canvas: cachedImage,
11490 offsetX,
11491 offsetY
11492 };
11493 }
11494 scaled = cachedImage;
11495 }
11496 if (!scaled) {
11497 maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
11498 putBinaryImageMask(maskCanvas.context, img);
11499 }
11500 let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
11501 maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
11502 const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas);
11503 const drawnWidth = Math.round(maxX - minX) || 1;
11504 const drawnHeight = Math.round(maxY - minY) || 1;
11505 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
11506 const fillCtx = fillCanvas.context;
11507 const offsetX = minX;
11508 const offsetY = minY;
11509 fillCtx.translate(-offsetX, -offsetY);
11510 fillCtx.transform(...maskToCanvas);
11511 if (!scaled) {
11512 scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
11513 scaled = scaled.img;
11514 if (cache && isPatternFill) {
11515 cache.set(cacheKey, scaled);
11516 }
11517 }
11518 fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
11519 drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
11520 fillCtx.globalCompositeOperation = "source-in";
11521 const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
11522 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
11523 fillCtx.fillRect(0, 0, width, height);
11524 if (cache && !isPatternFill) {
11525 this.cachedCanvases.delete("fillCanvas");
11526 cache.set(cacheKey, fillCanvas.canvas);
11527 }
11528 return {
11529 canvas: fillCanvas.canvas,
11530 offsetX: Math.round(offsetX),
11531 offsetY: Math.round(offsetY)
11532 };
11533 }
11534 setLineWidth(width) {
11535 if (width !== this.current.lineWidth) {
11536 this._cachedScaleForStroking[0] = -1;
11537 }
11538 this.current.lineWidth = width;
11539 this.ctx.lineWidth = width;
11540 }
11541 setLineCap(style) {
11542 this.ctx.lineCap = LINE_CAP_STYLES[style];
11543 }
11544 setLineJoin(style) {
11545 this.ctx.lineJoin = LINE_JOIN_STYLES[style];
11546 }
11547 setMiterLimit(limit) {
11548 this.ctx.miterLimit = limit;
11549 }
11550 setDash(dashArray, dashPhase) {
11551 const ctx = this.ctx;
11552 if (ctx.setLineDash !== undefined) {
11553 ctx.setLineDash(dashArray);
11554 ctx.lineDashOffset = dashPhase;
11555 }
11556 }
11557 setRenderingIntent(intent) {}
11558 setFlatness(flatness) {}
11559 setGState(states) {
11560 for (const [key, value] of states) {
11561 switch (key) {
11562 case "LW":
11563 this.setLineWidth(value);
11564 break;
11565 case "LC":
11566 this.setLineCap(value);
11567 break;
11568 case "LJ":
11569 this.setLineJoin(value);
11570 break;
11571 case "ML":
11572 this.setMiterLimit(value);
11573 break;
11574 case "D":
11575 this.setDash(value[0], value[1]);
11576 break;
11577 case "RI":
11578 this.setRenderingIntent(value);
11579 break;
11580 case "FL":
11581 this.setFlatness(value);
11582 break;
11583 case "Font":
11584 this.setFont(value[0], value[1]);
11585 break;
11586 case "CA":
11587 this.current.strokeAlpha = value;
11588 break;
11589 case "ca":
11590 this.current.fillAlpha = value;
11591 this.ctx.globalAlpha = value;
11592 break;
11593 case "BM":
11594 this.ctx.globalCompositeOperation = value;
11595 break;
11596 case "SMask":
11597 this.current.activeSMask = value ? this.tempSMask : null;
11598 this.tempSMask = null;
11599 this.checkSMaskState();
11600 break;
11601 case "TR":
11602 this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
11603 break;
11604 }
11605 }
11606 }
11607 get inSMaskMode() {
11608 return !!this.suspendedCtx;
11609 }
11610 checkSMaskState() {
11611 const inSMaskMode = this.inSMaskMode;
11612 if (this.current.activeSMask && !inSMaskMode) {
11613 this.beginSMaskMode();
11614 } else if (!this.current.activeSMask && inSMaskMode) {
11615 this.endSMaskMode();
11616 }
11617 }
11618 beginSMaskMode() {
11619 if (this.inSMaskMode) {
11620 throw new Error("beginSMaskMode called while already in smask mode");
11621 }
11622 const drawnWidth = this.ctx.canvas.width;
11623 const drawnHeight = this.ctx.canvas.height;
11624 const cacheId = "smaskGroupAt" + this.groupLevel;
11625 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
11626 this.suspendedCtx = this.ctx;
11627 this.ctx = scratchCanvas.context;
11628 const ctx = this.ctx;
11629 ctx.setTransform(...getCurrentTransform(this.suspendedCtx));
11630 copyCtxState(this.suspendedCtx, ctx);
11631 mirrorContextOperations(ctx, this.suspendedCtx);
11632 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
11633 }
11634 endSMaskMode() {
11635 if (!this.inSMaskMode) {
11636 throw new Error("endSMaskMode called while not in smask mode");
11637 }
11638 this.ctx._removeMirroring();
11639 copyCtxState(this.ctx, this.suspendedCtx);
11640 this.ctx = this.suspendedCtx;
11641 this.suspendedCtx = null;
11642 }
11643 compose(dirtyBox) {
11644 if (!this.current.activeSMask) {
11645 return;
11646 }
11647 if (!dirtyBox) {
11648 dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
11649 } else {
11650 dirtyBox[0] = Math.floor(dirtyBox[0]);
11651 dirtyBox[1] = Math.floor(dirtyBox[1]);
11652 dirtyBox[2] = Math.ceil(dirtyBox[2]);
11653 dirtyBox[3] = Math.ceil(dirtyBox[3]);
11654 }
11655 const smask = this.current.activeSMask;
11656 const suspendedCtx = this.suspendedCtx;
11657 this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
11658 this.ctx.save();
11659 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
11660 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
11661 this.ctx.restore();
11662 }
11663 composeSMask(ctx, smask, layerCtx, layerBox) {
11664 const layerOffsetX = layerBox[0];
11665 const layerOffsetY = layerBox[1];
11666 const layerWidth = layerBox[2] - layerOffsetX;
11667 const layerHeight = layerBox[3] - layerOffsetY;
11668 if (layerWidth === 0 || layerHeight === 0) {
11669 return;
11670 }
11671 this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
11672 ctx.save();
11673 ctx.globalAlpha = 1;
11674 ctx.globalCompositeOperation = "source-over";
11675 ctx.setTransform(1, 0, 0, 1, 0, 0);
11676 ctx.drawImage(layerCtx.canvas, 0, 0);
11677 ctx.restore();
11678 }
11679 genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
11680 let maskCanvas = maskCtx.canvas;
11681 let maskX = layerOffsetX - maskOffsetX;
11682 let maskY = layerOffsetY - maskOffsetY;
11683 if (backdrop) {
11684 if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
11685 const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
11686 const ctx = canvas.context;
11687 ctx.drawImage(maskCanvas, -maskX, -maskY);
11688 if (backdrop.some(c => c !== 0)) {
11689 ctx.globalCompositeOperation = "destination-atop";
11690 ctx.fillStyle = Util.makeHexColor(...backdrop);
11691 ctx.fillRect(0, 0, width, height);
11692 ctx.globalCompositeOperation = "source-over";
11693 }
11694 maskCanvas = canvas.canvas;
11695 maskX = maskY = 0;
11696 } else if (backdrop.some(c => c !== 0)) {
11697 maskCtx.save();
11698 maskCtx.globalAlpha = 1;
11699 maskCtx.setTransform(1, 0, 0, 1, 0, 0);
11700 const clip = new Path2D();
11701 clip.rect(maskX, maskY, width, height);
11702 maskCtx.clip(clip);
11703 maskCtx.globalCompositeOperation = "destination-atop";
11704 maskCtx.fillStyle = Util.makeHexColor(...backdrop);
11705 maskCtx.fillRect(maskX, maskY, width, height);
11706 maskCtx.restore();
11707 }
11708 }
11709 layerCtx.save();
11710 layerCtx.globalAlpha = 1;
11711 layerCtx.setTransform(1, 0, 0, 1, 0, 0);
11712 if (subtype === "Alpha" && transferMap) {
11713 layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
11714 } else if (subtype === "Luminosity") {
11715 layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
11716 }
11717 const clip = new Path2D();
11718 clip.rect(layerOffsetX, layerOffsetY, width, height);
11719 layerCtx.clip(clip);
11720 layerCtx.globalCompositeOperation = "destination-in";
11721 layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
11722 layerCtx.restore();
11723 }
11724 save() {
11725 if (this.inSMaskMode) {
11726 copyCtxState(this.ctx, this.suspendedCtx);
11727 this.suspendedCtx.save();
11728 } else {
11729 this.ctx.save();
11730 }
11731 const old = this.current;
11732 this.stateStack.push(old);
11733 this.current = old.clone();
11734 }
11735 restore() {
11736 if (this.stateStack.length === 0 && this.inSMaskMode) {
11737 this.endSMaskMode();
11738 }
11739 if (this.stateStack.length !== 0) {
11740 this.current = this.stateStack.pop();
11741 if (this.inSMaskMode) {
11742 this.suspendedCtx.restore();
11743 copyCtxState(this.suspendedCtx, this.ctx);
11744 } else {
11745 this.ctx.restore();
11746 }
11747 this.checkSMaskState();
11748 this.pendingClip = null;
11749 this._cachedScaleForStroking[0] = -1;
11750 this._cachedGetSinglePixelWidth = null;
11751 }
11752 }
11753 transform(a, b, c, d, e, f) {
11754 this.ctx.transform(a, b, c, d, e, f);
11755 this._cachedScaleForStroking[0] = -1;
11756 this._cachedGetSinglePixelWidth = null;
11757 }
11758 constructPath(ops, args, minMax) {
11759 const ctx = this.ctx;
11760 const current = this.current;
11761 let x = current.x,
11762 y = current.y;
11763 let startX, startY;
11764 const currentTransform = getCurrentTransform(ctx);
11765 const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
11766 const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
11767 for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
11768 switch (ops[i] | 0) {
11769 case OPS.rectangle:
11770 x = args[j++];
11771 y = args[j++];
11772 const width = args[j++];
11773 const height = args[j++];
11774 const xw = x + width;
11775 const yh = y + height;
11776 ctx.moveTo(x, y);
11777 if (width === 0 || height === 0) {
11778 ctx.lineTo(xw, yh);
11779 } else {
11780 ctx.lineTo(xw, y);
11781 ctx.lineTo(xw, yh);
11782 ctx.lineTo(x, yh);
11783 }
11784 if (!isScalingMatrix) {
11785 current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
11786 }
11787 ctx.closePath();
11788 break;
11789 case OPS.moveTo:
11790 x = args[j++];
11791 y = args[j++];
11792 ctx.moveTo(x, y);
11793 if (!isScalingMatrix) {
11794 current.updatePathMinMax(currentTransform, x, y);
11795 }
11796 break;
11797 case OPS.lineTo:
11798 x = args[j++];
11799 y = args[j++];
11800 ctx.lineTo(x, y);
11801 if (!isScalingMatrix) {
11802 current.updatePathMinMax(currentTransform, x, y);
11803 }
11804 break;
11805 case OPS.curveTo:
11806 startX = x;
11807 startY = y;
11808 x = args[j + 4];
11809 y = args[j + 5];
11810 ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
11811 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
11812 j += 6;
11813 break;
11814 case OPS.curveTo2:
11815 startX = x;
11816 startY = y;
11817 ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
11818 current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
11819 x = args[j + 2];
11820 y = args[j + 3];
11821 j += 4;
11822 break;
11823 case OPS.curveTo3:
11824 startX = x;
11825 startY = y;
11826 x = args[j + 2];
11827 y = args[j + 3];
11828 ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
11829 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
11830 j += 4;
11831 break;
11832 case OPS.closePath:
11833 ctx.closePath();
11834 break;
11835 }
11836 }
11837 if (isScalingMatrix) {
11838 current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
11839 }
11840 current.setCurrentPoint(x, y);
11841 }
11842 closePath() {
11843 this.ctx.closePath();
11844 }
11845 stroke(consumePath = true) {
11846 const ctx = this.ctx;
11847 const strokeColor = this.current.strokeColor;
11848 ctx.globalAlpha = this.current.strokeAlpha;
11849 if (this.contentVisible) {
11850 if (typeof strokeColor === "object" && strokeColor?.getPattern) {
11851 ctx.save();
11852 ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
11853 this.rescaleAndStroke(false);
11854 ctx.restore();
11855 } else {
11856 this.rescaleAndStroke(true);
11857 }
11858 }
11859 if (consumePath) {
11860 this.consumePath(this.current.getClippedPathBoundingBox());
11861 }
11862 ctx.globalAlpha = this.current.fillAlpha;
11863 }
11864 closeStroke() {
11865 this.closePath();
11866 this.stroke();
11867 }
11868 fill(consumePath = true) {
11869 const ctx = this.ctx;
11870 const fillColor = this.current.fillColor;
11871 const isPatternFill = this.current.patternFill;
11872 let needRestore = false;
11873 if (isPatternFill) {
11874 ctx.save();
11875 ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
11876 needRestore = true;
11877 }
11878 const intersect = this.current.getClippedPathBoundingBox();
11879 if (this.contentVisible && intersect !== null) {
11880 if (this.pendingEOFill) {
11881 ctx.fill("evenodd");
11882 this.pendingEOFill = false;
11883 } else {
11884 ctx.fill();
11885 }
11886 }
11887 if (needRestore) {
11888 ctx.restore();
11889 }
11890 if (consumePath) {
11891 this.consumePath(intersect);
11892 }
11893 }
11894 eoFill() {
11895 this.pendingEOFill = true;
11896 this.fill();
11897 }
11898 fillStroke() {
11899 this.fill(false);
11900 this.stroke(false);
11901 this.consumePath();
11902 }
11903 eoFillStroke() {
11904 this.pendingEOFill = true;
11905 this.fillStroke();
11906 }
11907 closeFillStroke() {
11908 this.closePath();
11909 this.fillStroke();
11910 }
11911 closeEOFillStroke() {
11912 this.pendingEOFill = true;
11913 this.closePath();
11914 this.fillStroke();
11915 }
11916 endPath() {
11917 this.consumePath();
11918 }
11919 clip() {
11920 this.pendingClip = NORMAL_CLIP;
11921 }
11922 eoClip() {
11923 this.pendingClip = EO_CLIP;
11924 }
11925 beginText() {
11926 this.current.textMatrix = IDENTITY_MATRIX;
11927 this.current.textMatrixScale = 1;
11928 this.current.x = this.current.lineX = 0;
11929 this.current.y = this.current.lineY = 0;
11930 }
11931 endText() {
11932 const paths = this.pendingTextPaths;
11933 const ctx = this.ctx;
11934 if (paths === undefined) {
11935 ctx.beginPath();
11936 return;
11937 }
11938 ctx.save();
11939 ctx.beginPath();
11940 for (const path of paths) {
11941 ctx.setTransform(...path.transform);
11942 ctx.translate(path.x, path.y);
11943 path.addToPath(ctx, path.fontSize);
11944 }
11945 ctx.restore();
11946 ctx.clip();
11947 ctx.beginPath();
11948 delete this.pendingTextPaths;
11949 }
11950 setCharSpacing(spacing) {
11951 this.current.charSpacing = spacing;
11952 }
11953 setWordSpacing(spacing) {
11954 this.current.wordSpacing = spacing;
11955 }
11956 setHScale(scale) {
11957 this.current.textHScale = scale / 100;
11958 }
11959 setLeading(leading) {
11960 this.current.leading = -leading;
11961 }
11962 setFont(fontRefName, size) {
11963 const fontObj = this.commonObjs.get(fontRefName);
11964 const current = this.current;
11965 if (!fontObj) {
11966 throw new Error(`Can't find font for ${fontRefName}`);
11967 }
11968 current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
11969 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
11970 warn("Invalid font matrix for font " + fontRefName);
11971 }
11972 if (size < 0) {
11973 size = -size;
11974 current.fontDirection = -1;
11975 } else {
11976 current.fontDirection = 1;
11977 }
11978 this.current.font = fontObj;
11979 this.current.fontSize = size;
11980 if (fontObj.isType3Font) {
11981 return;
11982 }
11983 const name = fontObj.loadedName || "sans-serif";
11984 const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
11985 let bold = "normal";
11986 if (fontObj.black) {
11987 bold = "900";
11988 } else if (fontObj.bold) {
11989 bold = "bold";
11990 }
11991 const italic = fontObj.italic ? "italic" : "normal";
11992 let browserFontSize = size;
11993 if (size < MIN_FONT_SIZE) {
11994 browserFontSize = MIN_FONT_SIZE;
11995 } else if (size > MAX_FONT_SIZE) {
11996 browserFontSize = MAX_FONT_SIZE;
11997 }
11998 this.current.fontSizeScale = size / browserFontSize;
11999 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
12000 }
12001 setTextRenderingMode(mode) {
12002 this.current.textRenderingMode = mode;
12003 }
12004 setTextRise(rise) {
12005 this.current.textRise = rise;
12006 }
12007 moveText(x, y) {
12008 this.current.x = this.current.lineX += x;
12009 this.current.y = this.current.lineY += y;
12010 }
12011 setLeadingMoveText(x, y) {
12012 this.setLeading(-y);
12013 this.moveText(x, y);
12014 }
12015 setTextMatrix(a, b, c, d, e, f) {
12016 this.current.textMatrix = [a, b, c, d, e, f];
12017 this.current.textMatrixScale = Math.hypot(a, b);
12018 this.current.x = this.current.lineX = 0;
12019 this.current.y = this.current.lineY = 0;
12020 }
12021 nextLine() {
12022 this.moveText(0, this.current.leading);
12023 }
12024 paintChar(character, x, y, patternTransform) {
12025 const ctx = this.ctx;
12026 const current = this.current;
12027 const font = current.font;
12028 const textRenderingMode = current.textRenderingMode;
12029 const fontSize = current.fontSize / current.fontSizeScale;
12030 const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
12031 const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
12032 const patternFill = current.patternFill && !font.missingFile;
12033 let addToPath;
12034 if (font.disableFontFace || isAddToPathSet || patternFill) {
12035 addToPath = font.getPathGenerator(this.commonObjs, character);
12036 }
12037 if (font.disableFontFace || patternFill) {
12038 ctx.save();
12039 ctx.translate(x, y);
12040 ctx.beginPath();
12041 addToPath(ctx, fontSize);
12042 if (patternTransform) {
12043 ctx.setTransform(...patternTransform);
12044 }
12045 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
12046 ctx.fill();
12047 }
12048 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
12049 ctx.stroke();
12050 }
12051 ctx.restore();
12052 } else {
12053 if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
12054 ctx.fillText(character, x, y);
12055 }
12056 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
12057 ctx.strokeText(character, x, y);
12058 }
12059 }
12060 if (isAddToPathSet) {
12061 const paths = this.pendingTextPaths ||= [];
12062 paths.push({
12063 transform: getCurrentTransform(ctx),
12064 x,
12065 y,
12066 fontSize,
12067 addToPath
12068 });
12069 }
12070 }
12071 get isFontSubpixelAAEnabled() {
12072 const {
12073 context: ctx
12074 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
12075 ctx.scale(1.5, 1);
12076 ctx.fillText("I", 0, 10);
12077 const data = ctx.getImageData(0, 0, 10, 10).data;
12078 let enabled = false;
12079 for (let i = 3; i < data.length; i += 4) {
12080 if (data[i] > 0 && data[i] < 255) {
12081 enabled = true;
12082 break;
12083 }
12084 }
12085 return shadow(this, "isFontSubpixelAAEnabled", enabled);
12086 }
12087 showText(glyphs) {
12088 const current = this.current;
12089 const font = current.font;
12090 if (font.isType3Font) {
12091 return this.showType3Text(glyphs);
12092 }
12093 const fontSize = current.fontSize;
12094 if (fontSize === 0) {
12095 return undefined;
12096 }
12097 const ctx = this.ctx;
12098 const fontSizeScale = current.fontSizeScale;
12099 const charSpacing = current.charSpacing;
12100 const wordSpacing = current.wordSpacing;
12101 const fontDirection = current.fontDirection;
12102 const textHScale = current.textHScale * fontDirection;
12103 const glyphsLength = glyphs.length;
12104 const vertical = font.vertical;
12105 const spacingDir = vertical ? 1 : -1;
12106 const defaultVMetrics = font.defaultVMetrics;
12107 const widthAdvanceScale = fontSize * current.fontMatrix[0];
12108 const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
12109 ctx.save();
12110 ctx.transform(...current.textMatrix);
12111 ctx.translate(current.x, current.y + current.textRise);
12112 if (fontDirection > 0) {
12113 ctx.scale(textHScale, -1);
12114 } else {
12115 ctx.scale(textHScale, 1);
12116 }
12117 let patternTransform;
12118 if (current.patternFill) {
12119 ctx.save();
12120 const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
12121 patternTransform = getCurrentTransform(ctx);
12122 ctx.restore();
12123 ctx.fillStyle = pattern;
12124 }
12125 let lineWidth = current.lineWidth;
12126 const scale = current.textMatrixScale;
12127 if (scale === 0 || lineWidth === 0) {
12128 const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
12129 if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
12130 lineWidth = this.getSinglePixelWidth();
12131 }
12132 } else {
12133 lineWidth /= scale;
12134 }
12135 if (fontSizeScale !== 1.0) {
12136 ctx.scale(fontSizeScale, fontSizeScale);
12137 lineWidth /= fontSizeScale;
12138 }
12139 ctx.lineWidth = lineWidth;
12140 if (font.isInvalidPDFjsFont) {
12141 const chars = [];
12142 let width = 0;
12143 for (const glyph of glyphs) {
12144 chars.push(glyph.unicode);
12145 width += glyph.width;
12146 }
12147 ctx.fillText(chars.join(""), 0, 0);
12148 current.x += width * widthAdvanceScale * textHScale;
12149 ctx.restore();
12150 this.compose();
12151 return undefined;
12152 }
12153 let x = 0,
12154 i;
12155 for (i = 0; i < glyphsLength; ++i) {
12156 const glyph = glyphs[i];
12157 if (typeof glyph === "number") {
12158 x += spacingDir * glyph * fontSize / 1000;
12159 continue;
12160 }
12161 let restoreNeeded = false;
12162 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
12163 const character = glyph.fontChar;
12164 const accent = glyph.accent;
12165 let scaledX, scaledY;
12166 let width = glyph.width;
12167 if (vertical) {
12168 const vmetric = glyph.vmetric || defaultVMetrics;
12169 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
12170 const vy = vmetric[2] * widthAdvanceScale;
12171 width = vmetric ? -vmetric[0] : width;
12172 scaledX = vx / fontSizeScale;
12173 scaledY = (x + vy) / fontSizeScale;
12174 } else {
12175 scaledX = x / fontSizeScale;
12176 scaledY = 0;
12177 }
12178 if (font.remeasure && width > 0) {
12179 const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
12180 if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
12181 const characterScaleX = width / measuredWidth;
12182 restoreNeeded = true;
12183 ctx.save();
12184 ctx.scale(characterScaleX, 1);
12185 scaledX /= characterScaleX;
12186 } else if (width !== measuredWidth) {
12187 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
12188 }
12189 }
12190 if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
12191 if (simpleFillText && !accent) {
12192 ctx.fillText(character, scaledX, scaledY);
12193 } else {
12194 this.paintChar(character, scaledX, scaledY, patternTransform);
12195 if (accent) {
12196 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
12197 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
12198 this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
12199 }
12200 }
12201 }
12202 const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
12203 x += charWidth;
12204 if (restoreNeeded) {
12205 ctx.restore();
12206 }
12207 }
12208 if (vertical) {
12209 current.y -= x;
12210 } else {
12211 current.x += x * textHScale;
12212 }
12213 ctx.restore();
12214 this.compose();
12215 return undefined;
12216 }
12217 showType3Text(glyphs) {
12218 const ctx = this.ctx;
12219 const current = this.current;
12220 const font = current.font;
12221 const fontSize = current.fontSize;
12222 const fontDirection = current.fontDirection;
12223 const spacingDir = font.vertical ? 1 : -1;
12224 const charSpacing = current.charSpacing;
12225 const wordSpacing = current.wordSpacing;
12226 const textHScale = current.textHScale * fontDirection;
12227 const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
12228 const glyphsLength = glyphs.length;
12229 const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
12230 let i, glyph, width, spacingLength;
12231 if (isTextInvisible || fontSize === 0) {
12232 return;
12233 }
12234 this._cachedScaleForStroking[0] = -1;
12235 this._cachedGetSinglePixelWidth = null;
12236 ctx.save();
12237 ctx.transform(...current.textMatrix);
12238 ctx.translate(current.x, current.y);
12239 ctx.scale(textHScale, fontDirection);
12240 for (i = 0; i < glyphsLength; ++i) {
12241 glyph = glyphs[i];
12242 if (typeof glyph === "number") {
12243 spacingLength = spacingDir * glyph * fontSize / 1000;
12244 this.ctx.translate(spacingLength, 0);
12245 current.x += spacingLength * textHScale;
12246 continue;
12247 }
12248 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
12249 const operatorList = font.charProcOperatorList[glyph.operatorListId];
12250 if (!operatorList) {
12251 warn(`Type3 character "${glyph.operatorListId}" is not available.`);
12252 continue;
12253 }
12254 if (this.contentVisible) {
12255 this.processingType3 = glyph;
12256 this.save();
12257 ctx.scale(fontSize, fontSize);
12258 ctx.transform(...fontMatrix);
12259 this.executeOperatorList(operatorList);
12260 this.restore();
12261 }
12262 const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
12263 width = transformed[0] * fontSize + spacing;
12264 ctx.translate(width, 0);
12265 current.x += width * textHScale;
12266 }
12267 ctx.restore();
12268 this.processingType3 = null;
12269 }
12270 setCharWidth(xWidth, yWidth) {}
12271 setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
12272 this.ctx.rect(llx, lly, urx - llx, ury - lly);
12273 this.ctx.clip();
12274 this.endPath();
12275 }
12276 getColorN_Pattern(IR) {
12277 let pattern;
12278 if (IR[0] === "TilingPattern") {
12279 const color = IR[1];
12280 const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
12281 const canvasGraphicsFactory = {
12282 createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
12283 optionalContentConfig: this.optionalContentConfig,
12284 markedContentStack: this.markedContentStack
12285 })
12286 };
12287 pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
12288 } else {
12289 pattern = this._getPattern(IR[1], IR[2]);
12290 }
12291 return pattern;
12292 }
12293 setStrokeColorN() {
12294 this.current.strokeColor = this.getColorN_Pattern(arguments);
12295 }
12296 setFillColorN() {
12297 this.current.fillColor = this.getColorN_Pattern(arguments);
12298 this.current.patternFill = true;
12299 }
12300 setStrokeRGBColor(r, g, b) {
12301 const color = Util.makeHexColor(r, g, b);
12302 this.ctx.strokeStyle = color;
12303 this.current.strokeColor = color;
12304 }
12305 setFillRGBColor(r, g, b) {
12306 const color = Util.makeHexColor(r, g, b);
12307 this.ctx.fillStyle = color;
12308 this.current.fillColor = color;
12309 this.current.patternFill = false;
12310 }
12311 _getPattern(objId, matrix = null) {
12312 let pattern;
12313 if (this.cachedPatterns.has(objId)) {
12314 pattern = this.cachedPatterns.get(objId);
12315 } else {
12316 pattern = getShadingPattern(this.getObject(objId));
12317 this.cachedPatterns.set(objId, pattern);
12318 }
12319 if (matrix) {
12320 pattern.matrix = matrix;
12321 }
12322 return pattern;
12323 }
12324 shadingFill(objId) {
12325 if (!this.contentVisible) {
12326 return;
12327 }
12328 const ctx = this.ctx;
12329 this.save();
12330 const pattern = this._getPattern(objId);
12331 ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
12332 const inv = getCurrentTransformInverse(ctx);
12333 if (inv) {
12334 const {
12335 width,
12336 height
12337 } = ctx.canvas;
12338 const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
12339 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
12340 } else {
12341 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
12342 }
12343 this.compose(this.current.getClippedPathBoundingBox());
12344 this.restore();
12345 }
12346 beginInlineImage() {
12347 unreachable("Should not call beginInlineImage");
12348 }
12349 beginImageData() {
12350 unreachable("Should not call beginImageData");
12351 }
12352 paintFormXObjectBegin(matrix, bbox) {
12353 if (!this.contentVisible) {
12354 return;
12355 }
12356 this.save();
12357 this.baseTransformStack.push(this.baseTransform);
12358 if (matrix) {
12359 this.transform(...matrix);
12360 }
12361 this.baseTransform = getCurrentTransform(this.ctx);
12362 if (bbox) {
12363 const width = bbox[2] - bbox[0];
12364 const height = bbox[3] - bbox[1];
12365 this.ctx.rect(bbox[0], bbox[1], width, height);
12366 this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);
12367 this.clip();
12368 this.endPath();
12369 }
12370 }
12371 paintFormXObjectEnd() {
12372 if (!this.contentVisible) {
12373 return;
12374 }
12375 this.restore();
12376 this.baseTransform = this.baseTransformStack.pop();
12377 }
12378 beginGroup(group) {
12379 if (!this.contentVisible) {
12380 return;
12381 }
12382 this.save();
12383 if (this.inSMaskMode) {
12384 this.endSMaskMode();
12385 this.current.activeSMask = null;
12386 }
12387 const currentCtx = this.ctx;
12388 if (!group.isolated) {
12389 info("TODO: Support non-isolated groups.");
12390 }
12391 if (group.knockout) {
12392 warn("Knockout groups not supported.");
12393 }
12394 const currentTransform = getCurrentTransform(currentCtx);
12395 if (group.matrix) {
12396 currentCtx.transform(...group.matrix);
12397 }
12398 if (!group.bbox) {
12399 throw new Error("Bounding box is required.");
12400 }
12401 let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx));
12402 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
12403 bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
12404 const offsetX = Math.floor(bounds[0]);
12405 const offsetY = Math.floor(bounds[1]);
12406 const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
12407 const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
12408 this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
12409 let cacheId = "groupAt" + this.groupLevel;
12410 if (group.smask) {
12411 cacheId += "_smask_" + this.smaskCounter++ % 2;
12412 }
12413 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
12414 const groupCtx = scratchCanvas.context;
12415 groupCtx.translate(-offsetX, -offsetY);
12416 groupCtx.transform(...currentTransform);
12417 if (group.smask) {
12418 this.smaskStack.push({
12419 canvas: scratchCanvas.canvas,
12420 context: groupCtx,
12421 offsetX,
12422 offsetY,
12423 subtype: group.smask.subtype,
12424 backdrop: group.smask.backdrop,
12425 transferMap: group.smask.transferMap || null,
12426 startTransformInverse: null
12427 });
12428 } else {
12429 currentCtx.setTransform(1, 0, 0, 1, 0, 0);
12430 currentCtx.translate(offsetX, offsetY);
12431 currentCtx.save();
12432 }
12433 copyCtxState(currentCtx, groupCtx);
12434 this.ctx = groupCtx;
12435 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
12436 this.groupStack.push(currentCtx);
12437 this.groupLevel++;
12438 }
12439 endGroup(group) {
12440 if (!this.contentVisible) {
12441 return;
12442 }
12443 this.groupLevel--;
12444 const groupCtx = this.ctx;
12445 const ctx = this.groupStack.pop();
12446 this.ctx = ctx;
12447 this.ctx.imageSmoothingEnabled = false;
12448 if (group.smask) {
12449 this.tempSMask = this.smaskStack.pop();
12450 this.restore();
12451 } else {
12452 this.ctx.restore();
12453 const currentMtx = getCurrentTransform(this.ctx);
12454 this.restore();
12455 this.ctx.save();
12456 this.ctx.setTransform(...currentMtx);
12457 const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
12458 this.ctx.drawImage(groupCtx.canvas, 0, 0);
12459 this.ctx.restore();
12460 this.compose(dirtyBox);
12461 }
12462 }
12463 beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
12464 this.#restoreInitialState();
12465 resetCtxToDefault(this.ctx);
12466 this.ctx.save();
12467 this.save();
12468 if (this.baseTransform) {
12469 this.ctx.setTransform(...this.baseTransform);
12470 }
12471 if (rect) {
12472 const width = rect[2] - rect[0];
12473 const height = rect[3] - rect[1];
12474 if (hasOwnCanvas && this.annotationCanvasMap) {
12475 transform = transform.slice();
12476 transform[4] -= rect[0];
12477 transform[5] -= rect[1];
12478 rect = rect.slice();
12479 rect[0] = rect[1] = 0;
12480 rect[2] = width;
12481 rect[3] = height;
12482 const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));
12483 const {
12484 viewportScale
12485 } = this;
12486 const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
12487 const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
12488 this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
12489 const {
12490 canvas,
12491 context
12492 } = this.annotationCanvas;
12493 this.annotationCanvasMap.set(id, canvas);
12494 this.annotationCanvas.savedCtx = this.ctx;
12495 this.ctx = context;
12496 this.ctx.save();
12497 this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
12498 resetCtxToDefault(this.ctx);
12499 } else {
12500 resetCtxToDefault(this.ctx);
12501 this.ctx.rect(rect[0], rect[1], width, height);
12502 this.ctx.clip();
12503 this.endPath();
12504 }
12505 }
12506 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
12507 this.transform(...transform);
12508 this.transform(...matrix);
12509 }
12510 endAnnotation() {
12511 if (this.annotationCanvas) {
12512 this.ctx.restore();
12513 this.#drawFilter();
12514 this.ctx = this.annotationCanvas.savedCtx;
12515 delete this.annotationCanvas.savedCtx;
12516 delete this.annotationCanvas;
12517 }
12518 }
12519 paintImageMaskXObject(img) {
12520 if (!this.contentVisible) {
12521 return;
12522 }
12523 const count = img.count;
12524 img = this.getObject(img.data, img);
12525 img.count = count;
12526 const ctx = this.ctx;
12527 const glyph = this.processingType3;
12528 if (glyph) {
12529 if (glyph.compiled === undefined) {
12530 glyph.compiled = compileType3Glyph(img);
12531 }
12532 if (glyph.compiled) {
12533 glyph.compiled(ctx);
12534 return;
12535 }
12536 }
12537 const mask = this._createMaskCanvas(img);
12538 const maskCanvas = mask.canvas;
12539 ctx.save();
12540 ctx.setTransform(1, 0, 0, 1, 0, 0);
12541 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
12542 ctx.restore();
12543 this.compose();
12544 }
12545 paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
12546 if (!this.contentVisible) {
12547 return;
12548 }
12549 img = this.getObject(img.data, img);
12550 const ctx = this.ctx;
12551 ctx.save();
12552 const currentTransform = getCurrentTransform(ctx);
12553 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
12554 const mask = this._createMaskCanvas(img);
12555 ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
12556 for (let i = 0, ii = positions.length; i < ii; i += 2) {
12557 const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
12558 const [x, y] = Util.applyTransform([0, 0], trans);
12559 ctx.drawImage(mask.canvas, x, y);
12560 }
12561 ctx.restore();
12562 this.compose();
12563 }
12564 paintImageMaskXObjectGroup(images) {
12565 if (!this.contentVisible) {
12566 return;
12567 }
12568 const ctx = this.ctx;
12569 const fillColor = this.current.fillColor;
12570 const isPatternFill = this.current.patternFill;
12571 for (const image of images) {
12572 const {
12573 data,
12574 width,
12575 height,
12576 transform
12577 } = image;
12578 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
12579 const maskCtx = maskCanvas.context;
12580 maskCtx.save();
12581 const img = this.getObject(data, image);
12582 putBinaryImageMask(maskCtx, img);
12583 maskCtx.globalCompositeOperation = "source-in";
12584 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
12585 maskCtx.fillRect(0, 0, width, height);
12586 maskCtx.restore();
12587 ctx.save();
12588 ctx.transform(...transform);
12589 ctx.scale(1, -1);
12590 drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
12591 ctx.restore();
12592 }
12593 this.compose();
12594 }
12595 paintImageXObject(objId) {
12596 if (!this.contentVisible) {
12597 return;
12598 }
12599 const imgData = this.getObject(objId);
12600 if (!imgData) {
12601 warn("Dependent image isn't ready yet");
12602 return;
12603 }
12604 this.paintInlineImageXObject(imgData);
12605 }
12606 paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
12607 if (!this.contentVisible) {
12608 return;
12609 }
12610 const imgData = this.getObject(objId);
12611 if (!imgData) {
12612 warn("Dependent image isn't ready yet");
12613 return;
12614 }
12615 const width = imgData.width;
12616 const height = imgData.height;
12617 const map = [];
12618 for (let i = 0, ii = positions.length; i < ii; i += 2) {
12619 map.push({
12620 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
12621 x: 0,
12622 y: 0,
12623 w: width,
12624 h: height
12625 });
12626 }
12627 this.paintInlineImageXObjectGroup(imgData, map);
12628 }
12629 applyTransferMapsToCanvas(ctx) {
12630 if (this.current.transferMaps !== "none") {
12631 ctx.filter = this.current.transferMaps;
12632 ctx.drawImage(ctx.canvas, 0, 0);
12633 ctx.filter = "none";
12634 }
12635 return ctx.canvas;
12636 }
12637 applyTransferMapsToBitmap(imgData) {
12638 if (this.current.transferMaps === "none") {
12639 return imgData.bitmap;
12640 }
12641 const {
12642 bitmap,
12643 width,
12644 height
12645 } = imgData;
12646 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
12647 const tmpCtx = tmpCanvas.context;
12648 tmpCtx.filter = this.current.transferMaps;
12649 tmpCtx.drawImage(bitmap, 0, 0);
12650 tmpCtx.filter = "none";
12651 return tmpCanvas.canvas;
12652 }
12653 paintInlineImageXObject(imgData) {
12654 if (!this.contentVisible) {
12655 return;
12656 }
12657 const width = imgData.width;
12658 const height = imgData.height;
12659 const ctx = this.ctx;
12660 this.save();
12661 if (!isNodeJS) {
12662 const {
12663 filter
12664 } = ctx;
12665 if (filter !== "none" && filter !== "") {
12666 ctx.filter = "none";
12667 }
12668 }
12669 ctx.scale(1 / width, -1 / height);
12670 let imgToPaint;
12671 if (imgData.bitmap) {
12672 imgToPaint = this.applyTransferMapsToBitmap(imgData);
12673 } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
12674 imgToPaint = imgData;
12675 } else {
12676 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
12677 const tmpCtx = tmpCanvas.context;
12678 putBinaryImageData(tmpCtx, imgData);
12679 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
12680 }
12681 const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
12682 ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
12683 drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
12684 this.compose();
12685 this.restore();
12686 }
12687 paintInlineImageXObjectGroup(imgData, map) {
12688 if (!this.contentVisible) {
12689 return;
12690 }
12691 const ctx = this.ctx;
12692 let imgToPaint;
12693 if (imgData.bitmap) {
12694 imgToPaint = imgData.bitmap;
12695 } else {
12696 const w = imgData.width;
12697 const h = imgData.height;
12698 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
12699 const tmpCtx = tmpCanvas.context;
12700 putBinaryImageData(tmpCtx, imgData);
12701 imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
12702 }
12703 for (const entry of map) {
12704 ctx.save();
12705 ctx.transform(...entry.transform);
12706 ctx.scale(1, -1);
12707 drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
12708 ctx.restore();
12709 }
12710 this.compose();
12711 }
12712 paintSolidColorImageMask() {
12713 if (!this.contentVisible) {
12714 return;
12715 }
12716 this.ctx.fillRect(0, 0, 1, 1);
12717 this.compose();
12718 }
12719 markPoint(tag) {}
12720 markPointProps(tag, properties) {}
12721 beginMarkedContent(tag) {
12722 this.markedContentStack.push({
12723 visible: true
12724 });
12725 }
12726 beginMarkedContentProps(tag, properties) {
12727 if (tag === "OC") {
12728 this.markedContentStack.push({
12729 visible: this.optionalContentConfig.isVisible(properties)
12730 });
12731 } else {
12732 this.markedContentStack.push({
12733 visible: true
12734 });
12735 }
12736 this.contentVisible = this.isContentVisible();
12737 }
12738 endMarkedContent() {
12739 this.markedContentStack.pop();
12740 this.contentVisible = this.isContentVisible();
12741 }
12742 beginCompat() {}
12743 endCompat() {}
12744 consumePath(clipBox) {
12745 const isEmpty = this.current.isEmptyClip();
12746 if (this.pendingClip) {
12747 this.current.updateClipFromPath();
12748 }
12749 if (!this.pendingClip) {
12750 this.compose(clipBox);
12751 }
12752 const ctx = this.ctx;
12753 if (this.pendingClip) {
12754 if (!isEmpty) {
12755 if (this.pendingClip === EO_CLIP) {
12756 ctx.clip("evenodd");
12757 } else {
12758 ctx.clip();
12759 }
12760 }
12761 this.pendingClip = null;
12762 }
12763 this.current.startNewPathAndClipBox(this.current.clipBox);
12764 ctx.beginPath();
12765 }
12766 getSinglePixelWidth() {
12767 if (!this._cachedGetSinglePixelWidth) {
12768 const m = getCurrentTransform(this.ctx);
12769 if (m[1] === 0 && m[2] === 0) {
12770 this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
12771 } else {
12772 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
12773 const normX = Math.hypot(m[0], m[2]);
12774 const normY = Math.hypot(m[1], m[3]);
12775 this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
12776 }
12777 }
12778 return this._cachedGetSinglePixelWidth;
12779 }
12780 getScaleForStroking() {
12781 if (this._cachedScaleForStroking[0] === -1) {
12782 const {
12783 lineWidth
12784 } = this.current;
12785 const {
12786 a,
12787 b,
12788 c,
12789 d
12790 } = this.ctx.getTransform();
12791 let scaleX, scaleY;
12792 if (b === 0 && c === 0) {
12793 const normX = Math.abs(a);
12794 const normY = Math.abs(d);
12795 if (normX === normY) {
12796 if (lineWidth === 0) {
12797 scaleX = scaleY = 1 / normX;
12798 } else {
12799 const scaledLineWidth = normX * lineWidth;
12800 scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
12801 }
12802 } else if (lineWidth === 0) {
12803 scaleX = 1 / normX;
12804 scaleY = 1 / normY;
12805 } else {
12806 const scaledXLineWidth = normX * lineWidth;
12807 const scaledYLineWidth = normY * lineWidth;
12808 scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
12809 scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
12810 }
12811 } else {
12812 const absDet = Math.abs(a * d - b * c);
12813 const normX = Math.hypot(a, b);
12814 const normY = Math.hypot(c, d);
12815 if (lineWidth === 0) {
12816 scaleX = normY / absDet;
12817 scaleY = normX / absDet;
12818 } else {
12819 const baseArea = lineWidth * absDet;
12820 scaleX = normY > baseArea ? normY / baseArea : 1;
12821 scaleY = normX > baseArea ? normX / baseArea : 1;
12822 }
12823 }
12824 this._cachedScaleForStroking[0] = scaleX;
12825 this._cachedScaleForStroking[1] = scaleY;
12826 }
12827 return this._cachedScaleForStroking;
12828 }
12829 rescaleAndStroke(saveRestore) {
12830 const {
12831 ctx
12832 } = this;
12833 const {
12834 lineWidth
12835 } = this.current;
12836 const [scaleX, scaleY] = this.getScaleForStroking();
12837 ctx.lineWidth = lineWidth || 1;
12838 if (scaleX === 1 && scaleY === 1) {
12839 ctx.stroke();
12840 return;
12841 }
12842 const dashes = ctx.getLineDash();
12843 if (saveRestore) {
12844 ctx.save();
12845 }
12846 ctx.scale(scaleX, scaleY);
12847 if (dashes.length > 0) {
12848 const scale = Math.max(scaleX, scaleY);
12849 ctx.setLineDash(dashes.map(x => x / scale));
12850 ctx.lineDashOffset /= scale;
12851 }
12852 ctx.stroke();
12853 if (saveRestore) {
12854 ctx.restore();
12855 }
12856 }
12857 isContentVisible() {
12858 for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
12859 if (!this.markedContentStack[i].visible) {
12860 return false;
12861 }
12862 }
12863 return true;
12864 }
12865 }
12866 for (const op in OPS) {
12867 if (CanvasGraphics.prototype[op] !== undefined) {
12868 CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
12869 }
12870 }
12871
12872 ;// CONCATENATED MODULE: ./src/display/worker_options.js
12873 class GlobalWorkerOptions {
12874 static #port = null;
12875 static #src = "";
12876 static get workerPort() {
12877 return this.#port;
12878 }
12879 static set workerPort(val) {
12880 if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
12881 throw new Error("Invalid `workerPort` type.");
12882 }
12883 this.#port = val;
12884 }
12885 static get workerSrc() {
12886 return this.#src;
12887 }
12888 static set workerSrc(val) {
12889 if (typeof val !== "string") {
12890 throw new Error("Invalid `workerSrc` type.");
12891 }
12892 this.#src = val;
12893 }
12894 }
12895
12896 ;// CONCATENATED MODULE: ./src/shared/message_handler.js
12897
12898
12899 const CallbackKind = {
12900 UNKNOWN: 0,
12901 DATA: 1,
12902 ERROR: 2
12903 };
12904 const StreamKind = {
12905 UNKNOWN: 0,
12906 CANCEL: 1,
12907 CANCEL_COMPLETE: 2,
12908 CLOSE: 3,
12909 ENQUEUE: 4,
12910 ERROR: 5,
12911 PULL: 6,
12912 PULL_COMPLETE: 7,
12913 START_COMPLETE: 8
12914 };
12915 function wrapReason(reason) {
12916 if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
12917 unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
12918 }
12919 switch (reason.name) {
12920 case "AbortException":
12921 return new AbortException(reason.message);
12922 case "MissingPDFException":
12923 return new MissingPDFException(reason.message);
12924 case "PasswordException":
12925 return new PasswordException(reason.message, reason.code);
12926 case "UnexpectedResponseException":
12927 return new UnexpectedResponseException(reason.message, reason.status);
12928 case "UnknownErrorException":
12929 return new UnknownErrorException(reason.message, reason.details);
12930 default:
12931 return new UnknownErrorException(reason.message, reason.toString());
12932 }
12933 }
12934 class MessageHandler {
12935 constructor(sourceName, targetName, comObj) {
12936 this.sourceName = sourceName;
12937 this.targetName = targetName;
12938 this.comObj = comObj;
12939 this.callbackId = 1;
12940 this.streamId = 1;
12941 this.streamSinks = Object.create(null);
12942 this.streamControllers = Object.create(null);
12943 this.callbackCapabilities = Object.create(null);
12944 this.actionHandler = Object.create(null);
12945 this._onComObjOnMessage = event => {
12946 const data = event.data;
12947 if (data.targetName !== this.sourceName) {
12948 return;
12949 }
12950 if (data.stream) {
12951 this.#processStreamMessage(data);
12952 return;
12953 }
12954 if (data.callback) {
12955 const callbackId = data.callbackId;
12956 const capability = this.callbackCapabilities[callbackId];
12957 if (!capability) {
12958 throw new Error(`Cannot resolve callback ${callbackId}`);
12959 }
12960 delete this.callbackCapabilities[callbackId];
12961 if (data.callback === CallbackKind.DATA) {
12962 capability.resolve(data.data);
12963 } else if (data.callback === CallbackKind.ERROR) {
12964 capability.reject(wrapReason(data.reason));
12965 } else {
12966 throw new Error("Unexpected callback case");
12967 }
12968 return;
12969 }
12970 const action = this.actionHandler[data.action];
12971 if (!action) {
12972 throw new Error(`Unknown action from worker: ${data.action}`);
12973 }
12974 if (data.callbackId) {
12975 const cbSourceName = this.sourceName;
12976 const cbTargetName = data.sourceName;
12977 new Promise(function (resolve) {
12978 resolve(action(data.data));
12979 }).then(function (result) {
12980 comObj.postMessage({
12981 sourceName: cbSourceName,
12982 targetName: cbTargetName,
12983 callback: CallbackKind.DATA,
12984 callbackId: data.callbackId,
12985 data: result
12986 });
12987 }, function (reason) {
12988 comObj.postMessage({
12989 sourceName: cbSourceName,
12990 targetName: cbTargetName,
12991 callback: CallbackKind.ERROR,
12992 callbackId: data.callbackId,
12993 reason: wrapReason(reason)
12994 });
12995 });
12996 return;
12997 }
12998 if (data.streamId) {
12999 this.#createStreamSink(data);
13000 return;
13001 }
13002 action(data.data);
13003 };
13004 comObj.addEventListener("message", this._onComObjOnMessage);
13005 }
13006 on(actionName, handler) {
13007 const ah = this.actionHandler;
13008 if (ah[actionName]) {
13009 throw new Error(`There is already an actionName called "${actionName}"`);
13010 }
13011 ah[actionName] = handler;
13012 }
13013 send(actionName, data, transfers) {
13014 this.comObj.postMessage({
13015 sourceName: this.sourceName,
13016 targetName: this.targetName,
13017 action: actionName,
13018 data
13019 }, transfers);
13020 }
13021 sendWithPromise(actionName, data, transfers) {
13022 const callbackId = this.callbackId++;
13023 const capability = Promise.withResolvers();
13024 this.callbackCapabilities[callbackId] = capability;
13025 try {
13026 this.comObj.postMessage({
13027 sourceName: this.sourceName,
13028 targetName: this.targetName,
13029 action: actionName,
13030 callbackId,
13031 data
13032 }, transfers);
13033 } catch (ex) {
13034 capability.reject(ex);
13035 }
13036 return capability.promise;
13037 }
13038 sendWithStream(actionName, data, queueingStrategy, transfers) {
13039 const streamId = this.streamId++,
13040 sourceName = this.sourceName,
13041 targetName = this.targetName,
13042 comObj = this.comObj;
13043 return new ReadableStream({
13044 start: controller => {
13045 const startCapability = Promise.withResolvers();
13046 this.streamControllers[streamId] = {
13047 controller,
13048 startCall: startCapability,
13049 pullCall: null,
13050 cancelCall: null,
13051 isClosed: false
13052 };
13053 comObj.postMessage({
13054 sourceName,
13055 targetName,
13056 action: actionName,
13057 streamId,
13058 data,
13059 desiredSize: controller.desiredSize
13060 }, transfers);
13061 return startCapability.promise;
13062 },
13063 pull: controller => {
13064 const pullCapability = Promise.withResolvers();
13065 this.streamControllers[streamId].pullCall = pullCapability;
13066 comObj.postMessage({
13067 sourceName,
13068 targetName,
13069 stream: StreamKind.PULL,
13070 streamId,
13071 desiredSize: controller.desiredSize
13072 });
13073 return pullCapability.promise;
13074 },
13075 cancel: reason => {
13076 assert(reason instanceof Error, "cancel must have a valid reason");
13077 const cancelCapability = Promise.withResolvers();
13078 this.streamControllers[streamId].cancelCall = cancelCapability;
13079 this.streamControllers[streamId].isClosed = true;
13080 comObj.postMessage({
13081 sourceName,
13082 targetName,
13083 stream: StreamKind.CANCEL,
13084 streamId,
13085 reason: wrapReason(reason)
13086 });
13087 return cancelCapability.promise;
13088 }
13089 }, queueingStrategy);
13090 }
13091 #createStreamSink(data) {
13092 const streamId = data.streamId,
13093 sourceName = this.sourceName,
13094 targetName = data.sourceName,
13095 comObj = this.comObj;
13096 const self = this,
13097 action = this.actionHandler[data.action];
13098 const streamSink = {
13099 enqueue(chunk, size = 1, transfers) {
13100 if (this.isCancelled) {
13101 return;
13102 }
13103 const lastDesiredSize = this.desiredSize;
13104 this.desiredSize -= size;
13105 if (lastDesiredSize > 0 && this.desiredSize <= 0) {
13106 this.sinkCapability = Promise.withResolvers();
13107 this.ready = this.sinkCapability.promise;
13108 }
13109 comObj.postMessage({
13110 sourceName,
13111 targetName,
13112 stream: StreamKind.ENQUEUE,
13113 streamId,
13114 chunk
13115 }, transfers);
13116 },
13117 close() {
13118 if (this.isCancelled) {
13119 return;
13120 }
13121 this.isCancelled = true;
13122 comObj.postMessage({
13123 sourceName,
13124 targetName,
13125 stream: StreamKind.CLOSE,
13126 streamId
13127 });
13128 delete self.streamSinks[streamId];
13129 },
13130 error(reason) {
13131 assert(reason instanceof Error, "error must have a valid reason");
13132 if (this.isCancelled) {
13133 return;
13134 }
13135 this.isCancelled = true;
13136 comObj.postMessage({
13137 sourceName,
13138 targetName,
13139 stream: StreamKind.ERROR,
13140 streamId,
13141 reason: wrapReason(reason)
13142 });
13143 },
13144 sinkCapability: Promise.withResolvers(),
13145 onPull: null,
13146 onCancel: null,
13147 isCancelled: false,
13148 desiredSize: data.desiredSize,
13149 ready: null
13150 };
13151 streamSink.sinkCapability.resolve();
13152 streamSink.ready = streamSink.sinkCapability.promise;
13153 this.streamSinks[streamId] = streamSink;
13154 new Promise(function (resolve) {
13155 resolve(action(data.data, streamSink));
13156 }).then(function () {
13157 comObj.postMessage({
13158 sourceName,
13159 targetName,
13160 stream: StreamKind.START_COMPLETE,
13161 streamId,
13162 success: true
13163 });
13164 }, function (reason) {
13165 comObj.postMessage({
13166 sourceName,
13167 targetName,
13168 stream: StreamKind.START_COMPLETE,
13169 streamId,
13170 reason: wrapReason(reason)
13171 });
13172 });
13173 }
13174 #processStreamMessage(data) {
13175 const streamId = data.streamId,
13176 sourceName = this.sourceName,
13177 targetName = data.sourceName,
13178 comObj = this.comObj;
13179 const streamController = this.streamControllers[streamId],
13180 streamSink = this.streamSinks[streamId];
13181 switch (data.stream) {
13182 case StreamKind.START_COMPLETE:
13183 if (data.success) {
13184 streamController.startCall.resolve();
13185 } else {
13186 streamController.startCall.reject(wrapReason(data.reason));
13187 }
13188 break;
13189 case StreamKind.PULL_COMPLETE:
13190 if (data.success) {
13191 streamController.pullCall.resolve();
13192 } else {
13193 streamController.pullCall.reject(wrapReason(data.reason));
13194 }
13195 break;
13196 case StreamKind.PULL:
13197 if (!streamSink) {
13198 comObj.postMessage({
13199 sourceName,
13200 targetName,
13201 stream: StreamKind.PULL_COMPLETE,
13202 streamId,
13203 success: true
13204 });
13205 break;
13206 }
13207 if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
13208 streamSink.sinkCapability.resolve();
13209 }
13210 streamSink.desiredSize = data.desiredSize;
13211 new Promise(function (resolve) {
13212 resolve(streamSink.onPull?.());
13213 }).then(function () {
13214 comObj.postMessage({
13215 sourceName,
13216 targetName,
13217 stream: StreamKind.PULL_COMPLETE,
13218 streamId,
13219 success: true
13220 });
13221 }, function (reason) {
13222 comObj.postMessage({
13223 sourceName,
13224 targetName,
13225 stream: StreamKind.PULL_COMPLETE,
13226 streamId,
13227 reason: wrapReason(reason)
13228 });
13229 });
13230 break;
13231 case StreamKind.ENQUEUE:
13232 assert(streamController, "enqueue should have stream controller");
13233 if (streamController.isClosed) {
13234 break;
13235 }
13236 streamController.controller.enqueue(data.chunk);
13237 break;
13238 case StreamKind.CLOSE:
13239 assert(streamController, "close should have stream controller");
13240 if (streamController.isClosed) {
13241 break;
13242 }
13243 streamController.isClosed = true;
13244 streamController.controller.close();
13245 this.#deleteStreamController(streamController, streamId);
13246 break;
13247 case StreamKind.ERROR:
13248 assert(streamController, "error should have stream controller");
13249 streamController.controller.error(wrapReason(data.reason));
13250 this.#deleteStreamController(streamController, streamId);
13251 break;
13252 case StreamKind.CANCEL_COMPLETE:
13253 if (data.success) {
13254 streamController.cancelCall.resolve();
13255 } else {
13256 streamController.cancelCall.reject(wrapReason(data.reason));
13257 }
13258 this.#deleteStreamController(streamController, streamId);
13259 break;
13260 case StreamKind.CANCEL:
13261 if (!streamSink) {
13262 break;
13263 }
13264 new Promise(function (resolve) {
13265 resolve(streamSink.onCancel?.(wrapReason(data.reason)));
13266 }).then(function () {
13267 comObj.postMessage({
13268 sourceName,
13269 targetName,
13270 stream: StreamKind.CANCEL_COMPLETE,
13271 streamId,
13272 success: true
13273 });
13274 }, function (reason) {
13275 comObj.postMessage({
13276 sourceName,
13277 targetName,
13278 stream: StreamKind.CANCEL_COMPLETE,
13279 streamId,
13280 reason: wrapReason(reason)
13281 });
13282 });
13283 streamSink.sinkCapability.reject(wrapReason(data.reason));
13284 streamSink.isCancelled = true;
13285 delete this.streamSinks[streamId];
13286 break;
13287 default:
13288 throw new Error("Unexpected stream case");
13289 }
13290 }
13291 async #deleteStreamController(streamController, streamId) {
13292 await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
13293 delete this.streamControllers[streamId];
13294 }
13295 destroy() {
13296 this.comObj.removeEventListener("message", this._onComObjOnMessage);
13297 }
13298 }
13299
13300 ;// CONCATENATED MODULE: ./src/display/metadata.js
13301
13302 class Metadata {
13303 #metadataMap;
13304 #data;
13305 constructor({
13306 parsedData,
13307 rawData
13308 }) {
13309 this.#metadataMap = parsedData;
13310 this.#data = rawData;
13311 }
13312 getRaw() {
13313 return this.#data;
13314 }
13315 get(name) {
13316 return this.#metadataMap.get(name) ?? null;
13317 }
13318 getAll() {
13319 return objectFromMap(this.#metadataMap);
13320 }
13321 has(name) {
13322 return this.#metadataMap.has(name);
13323 }
13324 }
13325
13326 ;// CONCATENATED MODULE: ./src/display/optional_content_config.js
13327
13328
13329 const INTERNAL = Symbol("INTERNAL");
13330 class OptionalContentGroup {
13331 #isDisplay = false;
13332 #isPrint = false;
13333 #userSet = false;
13334 #visible = true;
13335 constructor(renderingIntent, {
13336 name,
13337 intent,
13338 usage
13339 }) {
13340 this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
13341 this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
13342 this.name = name;
13343 this.intent = intent;
13344 this.usage = usage;
13345 }
13346 get visible() {
13347 if (this.#userSet) {
13348 return this.#visible;
13349 }
13350 if (!this.#visible) {
13351 return false;
13352 }
13353 const {
13354 print,
13355 view
13356 } = this.usage;
13357 if (this.#isDisplay) {
13358 return view?.viewState !== "OFF";
13359 } else if (this.#isPrint) {
13360 return print?.printState !== "OFF";
13361 }
13362 return true;
13363 }
13364 _setVisible(internal, visible, userSet = false) {
13365 if (internal !== INTERNAL) {
13366 unreachable("Internal method `_setVisible` called.");
13367 }
13368 this.#userSet = userSet;
13369 this.#visible = visible;
13370 }
13371 }
13372 class OptionalContentConfig {
13373 #cachedGetHash = null;
13374 #groups = new Map();
13375 #initialHash = null;
13376 #order = null;
13377 constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
13378 this.renderingIntent = renderingIntent;
13379 this.name = null;
13380 this.creator = null;
13381 if (data === null) {
13382 return;
13383 }
13384 this.name = data.name;
13385 this.creator = data.creator;
13386 this.#order = data.order;
13387 for (const group of data.groups) {
13388 this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
13389 }
13390 if (data.baseState === "OFF") {
13391 for (const group of this.#groups.values()) {
13392 group._setVisible(INTERNAL, false);
13393 }
13394 }
13395 for (const on of data.on) {
13396 this.#groups.get(on)._setVisible(INTERNAL, true);
13397 }
13398 for (const off of data.off) {
13399 this.#groups.get(off)._setVisible(INTERNAL, false);
13400 }
13401 this.#initialHash = this.getHash();
13402 }
13403 #evaluateVisibilityExpression(array) {
13404 const length = array.length;
13405 if (length < 2) {
13406 return true;
13407 }
13408 const operator = array[0];
13409 for (let i = 1; i < length; i++) {
13410 const element = array[i];
13411 let state;
13412 if (Array.isArray(element)) {
13413 state = this.#evaluateVisibilityExpression(element);
13414 } else if (this.#groups.has(element)) {
13415 state = this.#groups.get(element).visible;
13416 } else {
13417 warn(`Optional content group not found: ${element}`);
13418 return true;
13419 }
13420 switch (operator) {
13421 case "And":
13422 if (!state) {
13423 return false;
13424 }
13425 break;
13426 case "Or":
13427 if (state) {
13428 return true;
13429 }
13430 break;
13431 case "Not":
13432 return !state;
13433 default:
13434 return true;
13435 }
13436 }
13437 return operator === "And";
13438 }
13439 isVisible(group) {
13440 if (this.#groups.size === 0) {
13441 return true;
13442 }
13443 if (!group) {
13444 info("Optional content group not defined.");
13445 return true;
13446 }
13447 if (group.type === "OCG") {
13448 if (!this.#groups.has(group.id)) {
13449 warn(`Optional content group not found: ${group.id}`);
13450 return true;
13451 }
13452 return this.#groups.get(group.id).visible;
13453 } else if (group.type === "OCMD") {
13454 if (group.expression) {
13455 return this.#evaluateVisibilityExpression(group.expression);
13456 }
13457 if (!group.policy || group.policy === "AnyOn") {
13458 for (const id of group.ids) {
13459 if (!this.#groups.has(id)) {
13460 warn(`Optional content group not found: ${id}`);
13461 return true;
13462 }
13463 if (this.#groups.get(id).visible) {
13464 return true;
13465 }
13466 }
13467 return false;
13468 } else if (group.policy === "AllOn") {
13469 for (const id of group.ids) {
13470 if (!this.#groups.has(id)) {
13471 warn(`Optional content group not found: ${id}`);
13472 return true;
13473 }
13474 if (!this.#groups.get(id).visible) {
13475 return false;
13476 }
13477 }
13478 return true;
13479 } else if (group.policy === "AnyOff") {
13480 for (const id of group.ids) {
13481 if (!this.#groups.has(id)) {
13482 warn(`Optional content group not found: ${id}`);
13483 return true;
13484 }
13485 if (!this.#groups.get(id).visible) {
13486 return true;
13487 }
13488 }
13489 return false;
13490 } else if (group.policy === "AllOff") {
13491 for (const id of group.ids) {
13492 if (!this.#groups.has(id)) {
13493 warn(`Optional content group not found: ${id}`);
13494 return true;
13495 }
13496 if (this.#groups.get(id).visible) {
13497 return false;
13498 }
13499 }
13500 return true;
13501 }
13502 warn(`Unknown optional content policy ${group.policy}.`);
13503 return true;
13504 }
13505 warn(`Unknown group type ${group.type}.`);
13506 return true;
13507 }
13508 setVisibility(id, visible = true) {
13509 const group = this.#groups.get(id);
13510 if (!group) {
13511 warn(`Optional content group not found: ${id}`);
13512 return;
13513 }
13514 group._setVisible(INTERNAL, !!visible, true);
13515 this.#cachedGetHash = null;
13516 }
13517 setOCGState({
13518 state,
13519 preserveRB
13520 }) {
13521 let operator;
13522 for (const elem of state) {
13523 switch (elem) {
13524 case "ON":
13525 case "OFF":
13526 case "Toggle":
13527 operator = elem;
13528 continue;
13529 }
13530 const group = this.#groups.get(elem);
13531 if (!group) {
13532 continue;
13533 }
13534 switch (operator) {
13535 case "ON":
13536 group._setVisible(INTERNAL, true);
13537 break;
13538 case "OFF":
13539 group._setVisible(INTERNAL, false);
13540 break;
13541 case "Toggle":
13542 group._setVisible(INTERNAL, !group.visible);
13543 break;
13544 }
13545 }
13546 this.#cachedGetHash = null;
13547 }
13548 get hasInitialVisibility() {
13549 return this.#initialHash === null || this.getHash() === this.#initialHash;
13550 }
13551 getOrder() {
13552 if (!this.#groups.size) {
13553 return null;
13554 }
13555 if (this.#order) {
13556 return this.#order.slice();
13557 }
13558 return [...this.#groups.keys()];
13559 }
13560 getGroups() {
13561 return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;
13562 }
13563 getGroup(id) {
13564 return this.#groups.get(id) || null;
13565 }
13566 getHash() {
13567 if (this.#cachedGetHash !== null) {
13568 return this.#cachedGetHash;
13569 }
13570 const hash = new MurmurHash3_64();
13571 for (const [id, group] of this.#groups) {
13572 hash.update(`${id}:${group.visible}`);
13573 }
13574 return this.#cachedGetHash = hash.hexdigest();
13575 }
13576 }
13577
13578 ;// CONCATENATED MODULE: ./src/display/transport_stream.js
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591 class PDFDataTransportStream {
13592 constructor(pdfDataRangeTransport, {
13593 disableRange = false,
13594 disableStream = false
13595 }) {
13596 assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
13597 const {
13598 length,
13599 initialData,
13600 progressiveDone,
13601 contentDispositionFilename
13602 } = pdfDataRangeTransport;
13603 this._queuedChunks = [];
13604 this._progressiveDone = progressiveDone;
13605 this._contentDispositionFilename = contentDispositionFilename;
13606 if (initialData?.length > 0) {
13607 const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
13608 this._queuedChunks.push(buffer);
13609 }
13610 this._pdfDataRangeTransport = pdfDataRangeTransport;
13611 this._isStreamingSupported = !disableStream;
13612 this._isRangeSupported = !disableRange;
13613 this._contentLength = length;
13614 this._fullRequestReader = null;
13615 this._rangeReaders = [];
13616 pdfDataRangeTransport.addRangeListener((begin, chunk) => {
13617 this._onReceiveData({
13618 begin,
13619 chunk
13620 });
13621 });
13622 pdfDataRangeTransport.addProgressListener((loaded, total) => {
13623 this._onProgress({
13624 loaded,
13625 total
13626 });
13627 });
13628 pdfDataRangeTransport.addProgressiveReadListener(chunk => {
13629 this._onReceiveData({
13630 chunk
13631 });
13632 });
13633 pdfDataRangeTransport.addProgressiveDoneListener(() => {
13634 this._onProgressiveDone();
13635 });
13636 pdfDataRangeTransport.transportReady();
13637 }
13638 _onReceiveData({
13639 begin,
13640 chunk
13641 }) {
13642 const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
13643 if (begin === undefined) {
13644 if (this._fullRequestReader) {
13645 this._fullRequestReader._enqueue(buffer);
13646 } else {
13647 this._queuedChunks.push(buffer);
13648 }
13649 } else {
13650 const found = this._rangeReaders.some(function (rangeReader) {
13651 if (rangeReader._begin !== begin) {
13652 return false;
13653 }
13654 rangeReader._enqueue(buffer);
13655 return true;
13656 });
13657 assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
13658 }
13659 }
13660 get _progressiveDataLength() {
13661 return this._fullRequestReader?._loaded ?? 0;
13662 }
13663 _onProgress(evt) {
13664 if (evt.total === undefined) {
13665 this._rangeReaders[0]?.onProgress?.({
13666 loaded: evt.loaded
13667 });
13668 } else {
13669 this._fullRequestReader?.onProgress?.({
13670 loaded: evt.loaded,
13671 total: evt.total
13672 });
13673 }
13674 }
13675 _onProgressiveDone() {
13676 this._fullRequestReader?.progressiveDone();
13677 this._progressiveDone = true;
13678 }
13679 _removeRangeReader(reader) {
13680 const i = this._rangeReaders.indexOf(reader);
13681 if (i >= 0) {
13682 this._rangeReaders.splice(i, 1);
13683 }
13684 }
13685 getFullReader() {
13686 assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
13687 const queuedChunks = this._queuedChunks;
13688 this._queuedChunks = null;
13689 return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
13690 }
13691 getRangeReader(begin, end) {
13692 if (end <= this._progressiveDataLength) {
13693 return null;
13694 }
13695 const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
13696 this._pdfDataRangeTransport.requestDataRange(begin, end);
13697 this._rangeReaders.push(reader);
13698 return reader;
13699 }
13700 cancelAllRequests(reason) {
13701 this._fullRequestReader?.cancel(reason);
13702 for (const reader of this._rangeReaders.slice(0)) {
13703 reader.cancel(reason);
13704 }
13705 this._pdfDataRangeTransport.abort();
13706 }
13707 }
13708 class PDFDataTransportStreamReader {
13709 constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
13710 this._stream = stream;
13711 this._done = progressiveDone || false;
13712 this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
13713 this._queuedChunks = queuedChunks || [];
13714 this._loaded = 0;
13715 for (const chunk of this._queuedChunks) {
13716 this._loaded += chunk.byteLength;
13717 }
13718 this._requests = [];
13719 this._headersReady = Promise.resolve();
13720 stream._fullRequestReader = this;
13721 this.onProgress = null;
13722 }
13723 _enqueue(chunk) {
13724 if (this._done) {
13725 return;
13726 }
13727 if (this._requests.length > 0) {
13728 const requestCapability = this._requests.shift();
13729 requestCapability.resolve({
13730 value: chunk,
13731 done: false
13732 });
13733 } else {
13734 this._queuedChunks.push(chunk);
13735 }
13736 this._loaded += chunk.byteLength;
13737 }
13738 get headersReady() {
13739 return this._headersReady;
13740 }
13741 get filename() {
13742 return this._filename;
13743 }
13744 get isRangeSupported() {
13745 return this._stream._isRangeSupported;
13746 }
13747 get isStreamingSupported() {
13748 return this._stream._isStreamingSupported;
13749 }
13750 get contentLength() {
13751 return this._stream._contentLength;
13752 }
13753 async read() {
13754 if (this._queuedChunks.length > 0) {
13755 const chunk = this._queuedChunks.shift();
13756 return {
13757 value: chunk,
13758 done: false
13759 };
13760 }
13761 if (this._done) {
13762 return {
13763 value: undefined,
13764 done: true
13765 };
13766 }
13767 const requestCapability = Promise.withResolvers();
13768 this._requests.push(requestCapability);
13769 return requestCapability.promise;
13770 }
13771 cancel(reason) {
13772 this._done = true;
13773 for (const requestCapability of this._requests) {
13774 requestCapability.resolve({
13775 value: undefined,
13776 done: true
13777 });
13778 }
13779 this._requests.length = 0;
13780 }
13781 progressiveDone() {
13782 if (this._done) {
13783 return;
13784 }
13785 this._done = true;
13786 }
13787 }
13788 class PDFDataTransportStreamRangeReader {
13789 constructor(stream, begin, end) {
13790 this._stream = stream;
13791 this._begin = begin;
13792 this._end = end;
13793 this._queuedChunk = null;
13794 this._requests = [];
13795 this._done = false;
13796 this.onProgress = null;
13797 }
13798 _enqueue(chunk) {
13799 if (this._done) {
13800 return;
13801 }
13802 if (this._requests.length === 0) {
13803 this._queuedChunk = chunk;
13804 } else {
13805 const requestsCapability = this._requests.shift();
13806 requestsCapability.resolve({
13807 value: chunk,
13808 done: false
13809 });
13810 for (const requestCapability of this._requests) {
13811 requestCapability.resolve({
13812 value: undefined,
13813 done: true
13814 });
13815 }
13816 this._requests.length = 0;
13817 }
13818 this._done = true;
13819 this._stream._removeRangeReader(this);
13820 }
13821 get isStreamingSupported() {
13822 return false;
13823 }
13824 async read() {
13825 if (this._queuedChunk) {
13826 const chunk = this._queuedChunk;
13827 this._queuedChunk = null;
13828 return {
13829 value: chunk,
13830 done: false
13831 };
13832 }
13833 if (this._done) {
13834 return {
13835 value: undefined,
13836 done: true
13837 };
13838 }
13839 const requestCapability = Promise.withResolvers();
13840 this._requests.push(requestCapability);
13841 return requestCapability.promise;
13842 }
13843 cancel(reason) {
13844 this._done = true;
13845 for (const requestCapability of this._requests) {
13846 requestCapability.resolve({
13847 value: undefined,
13848 done: true
13849 });
13850 }
13851 this._requests.length = 0;
13852 this._stream._removeRangeReader(this);
13853 }
13854 }
13855
13856 ;// CONCATENATED MODULE: ./src/display/content_disposition.js
13857
13858
13859
13860 function getFilenameFromContentDispositionHeader(contentDisposition) {
13861 let needsEncodingFixup = true;
13862 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
13863 if (tmp) {
13864 tmp = tmp[1];
13865 let filename = rfc2616unquote(tmp);
13866 filename = unescape(filename);
13867 filename = rfc5987decode(filename);
13868 filename = rfc2047decode(filename);
13869 return fixupEncoding(filename);
13870 }
13871 tmp = rfc2231getparam(contentDisposition);
13872 if (tmp) {
13873 const filename = rfc2047decode(tmp);
13874 return fixupEncoding(filename);
13875 }
13876 tmp = toParamRegExp("filename", "i").exec(contentDisposition);
13877 if (tmp) {
13878 tmp = tmp[1];
13879 let filename = rfc2616unquote(tmp);
13880 filename = rfc2047decode(filename);
13881 return fixupEncoding(filename);
13882 }
13883 function toParamRegExp(attributePattern, flags) {
13884 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
13885 }
13886 function textdecode(encoding, value) {
13887 if (encoding) {
13888 if (!/^[\x00-\xFF]+$/.test(value)) {
13889 return value;
13890 }
13891 try {
13892 const decoder = new TextDecoder(encoding, {
13893 fatal: true
13894 });
13895 const buffer = stringToBytes(value);
13896 value = decoder.decode(buffer);
13897 needsEncodingFixup = false;
13898 } catch {}
13899 }
13900 return value;
13901 }
13902 function fixupEncoding(value) {
13903 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
13904 value = textdecode("utf-8", value);
13905 if (needsEncodingFixup) {
13906 value = textdecode("iso-8859-1", value);
13907 }
13908 }
13909 return value;
13910 }
13911 function rfc2231getparam(contentDispositionStr) {
13912 const matches = [];
13913 let match;
13914 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
13915 while ((match = iter.exec(contentDispositionStr)) !== null) {
13916 let [, n, quot, part] = match;
13917 n = parseInt(n, 10);
13918 if (n in matches) {
13919 if (n === 0) {
13920 break;
13921 }
13922 continue;
13923 }
13924 matches[n] = [quot, part];
13925 }
13926 const parts = [];
13927 for (let n = 0; n < matches.length; ++n) {
13928 if (!(n in matches)) {
13929 break;
13930 }
13931 let [quot, part] = matches[n];
13932 part = rfc2616unquote(part);
13933 if (quot) {
13934 part = unescape(part);
13935 if (n === 0) {
13936 part = rfc5987decode(part);
13937 }
13938 }
13939 parts.push(part);
13940 }
13941 return parts.join("");
13942 }
13943 function rfc2616unquote(value) {
13944 if (value.startsWith('"')) {
13945 const parts = value.slice(1).split('\\"');
13946 for (let i = 0; i < parts.length; ++i) {
13947 const quotindex = parts[i].indexOf('"');
13948 if (quotindex !== -1) {
13949 parts[i] = parts[i].slice(0, quotindex);
13950 parts.length = i + 1;
13951 }
13952 parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
13953 }
13954 value = parts.join('"');
13955 }
13956 return value;
13957 }
13958 function rfc5987decode(extvalue) {
13959 const encodingend = extvalue.indexOf("'");
13960 if (encodingend === -1) {
13961 return extvalue;
13962 }
13963 const encoding = extvalue.slice(0, encodingend);
13964 const langvalue = extvalue.slice(encodingend + 1);
13965 const value = langvalue.replace(/^[^']*'/, "");
13966 return textdecode(encoding, value);
13967 }
13968 function rfc2047decode(value) {
13969 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
13970 return value;
13971 }
13972 return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
13973 if (encoding === "q" || encoding === "Q") {
13974 text = text.replaceAll("_", " ");
13975 text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
13976 return String.fromCharCode(parseInt(hex, 16));
13977 });
13978 return textdecode(charset, text);
13979 }
13980 try {
13981 text = atob(text);
13982 } catch {}
13983 return textdecode(charset, text);
13984 });
13985 }
13986 return "";
13987 }
13988
13989 ;// CONCATENATED MODULE: ./src/display/network_utils.js
13990
13991
13992
13993 function validateRangeRequestCapabilities({
13994 getResponseHeader,
13995 isHttp,
13996 rangeChunkSize,
13997 disableRange
13998 }) {
13999 const returnValues = {
14000 allowRangeRequests: false,
14001 suggestedLength: undefined
14002 };
14003 const length = parseInt(getResponseHeader("Content-Length"), 10);
14004 if (!Number.isInteger(length)) {
14005 return returnValues;
14006 }
14007 returnValues.suggestedLength = length;
14008 if (length <= 2 * rangeChunkSize) {
14009 return returnValues;
14010 }
14011 if (disableRange || !isHttp) {
14012 return returnValues;
14013 }
14014 if (getResponseHeader("Accept-Ranges") !== "bytes") {
14015 return returnValues;
14016 }
14017 const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
14018 if (contentEncoding !== "identity") {
14019 return returnValues;
14020 }
14021 returnValues.allowRangeRequests = true;
14022 return returnValues;
14023 }
14024 function extractFilenameFromHeader(getResponseHeader) {
14025 const contentDisposition = getResponseHeader("Content-Disposition");
14026 if (contentDisposition) {
14027 let filename = getFilenameFromContentDispositionHeader(contentDisposition);
14028 if (filename.includes("%")) {
14029 try {
14030 filename = decodeURIComponent(filename);
14031 } catch {}
14032 }
14033 if (isPdfFile(filename)) {
14034 return filename;
14035 }
14036 }
14037 return null;
14038 }
14039 function createResponseStatusError(status, url) {
14040 if (status === 404 || status === 0 && url.startsWith("file:")) {
14041 return new MissingPDFException('Missing PDF "' + url + '".');
14042 }
14043 return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
14044 }
14045 function validateResponseStatus(status) {
14046 return status === 200 || status === 206;
14047 }
14048
14049 ;// CONCATENATED MODULE: ./src/display/fetch_stream.js
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060 function createFetchOptions(headers, withCredentials, abortController) {
14061 return {
14062 method: "GET",
14063 headers,
14064 signal: abortController.signal,
14065 mode: "cors",
14066 credentials: withCredentials ? "include" : "same-origin",
14067 redirect: "follow"
14068 };
14069 }
14070 function createHeaders(httpHeaders) {
14071 const headers = new Headers();
14072 for (const property in httpHeaders) {
14073 const value = httpHeaders[property];
14074 if (value === undefined) {
14075 continue;
14076 }
14077 headers.append(property, value);
14078 }
14079 return headers;
14080 }
14081 function getArrayBuffer(val) {
14082 if (val instanceof Uint8Array) {
14083 return val.buffer;
14084 }
14085 if (val instanceof ArrayBuffer) {
14086 return val;
14087 }
14088 warn(`getArrayBuffer - unexpected data format: ${val}`);
14089 return new Uint8Array(val).buffer;
14090 }
14091 class PDFFetchStream {
14092 constructor(source) {
14093 this.source = source;
14094 this.isHttp = /^https?:/i.test(source.url);
14095 this.httpHeaders = this.isHttp && source.httpHeaders || {};
14096 this._fullRequestReader = null;
14097 this._rangeRequestReaders = [];
14098 }
14099 get _progressiveDataLength() {
14100 return this._fullRequestReader?._loaded ?? 0;
14101 }
14102 getFullReader() {
14103 assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
14104 this._fullRequestReader = new PDFFetchStreamReader(this);
14105 return this._fullRequestReader;
14106 }
14107 getRangeReader(begin, end) {
14108 if (end <= this._progressiveDataLength) {
14109 return null;
14110 }
14111 const reader = new PDFFetchStreamRangeReader(this, begin, end);
14112 this._rangeRequestReaders.push(reader);
14113 return reader;
14114 }
14115 cancelAllRequests(reason) {
14116 this._fullRequestReader?.cancel(reason);
14117 for (const reader of this._rangeRequestReaders.slice(0)) {
14118 reader.cancel(reason);
14119 }
14120 }
14121 }
14122 class PDFFetchStreamReader {
14123 constructor(stream) {
14124 this._stream = stream;
14125 this._reader = null;
14126 this._loaded = 0;
14127 this._filename = null;
14128 const source = stream.source;
14129 this._withCredentials = source.withCredentials || false;
14130 this._contentLength = source.length;
14131 this._headersCapability = Promise.withResolvers();
14132 this._disableRange = source.disableRange || false;
14133 this._rangeChunkSize = source.rangeChunkSize;
14134 if (!this._rangeChunkSize && !this._disableRange) {
14135 this._disableRange = true;
14136 }
14137 this._abortController = new AbortController();
14138 this._isStreamingSupported = !source.disableStream;
14139 this._isRangeSupported = !source.disableRange;
14140 this._headers = createHeaders(this._stream.httpHeaders);
14141 const url = source.url;
14142 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
14143 if (!validateResponseStatus(response.status)) {
14144 throw createResponseStatusError(response.status, url);
14145 }
14146 this._reader = response.body.getReader();
14147 this._headersCapability.resolve();
14148 const getResponseHeader = name => response.headers.get(name);
14149 const {
14150 allowRangeRequests,
14151 suggestedLength
14152 } = validateRangeRequestCapabilities({
14153 getResponseHeader,
14154 isHttp: this._stream.isHttp,
14155 rangeChunkSize: this._rangeChunkSize,
14156 disableRange: this._disableRange
14157 });
14158 this._isRangeSupported = allowRangeRequests;
14159 this._contentLength = suggestedLength || this._contentLength;
14160 this._filename = extractFilenameFromHeader(getResponseHeader);
14161 if (!this._isStreamingSupported && this._isRangeSupported) {
14162 this.cancel(new AbortException("Streaming is disabled."));
14163 }
14164 }).catch(this._headersCapability.reject);
14165 this.onProgress = null;
14166 }
14167 get headersReady() {
14168 return this._headersCapability.promise;
14169 }
14170 get filename() {
14171 return this._filename;
14172 }
14173 get contentLength() {
14174 return this._contentLength;
14175 }
14176 get isRangeSupported() {
14177 return this._isRangeSupported;
14178 }
14179 get isStreamingSupported() {
14180 return this._isStreamingSupported;
14181 }
14182 async read() {
14183 await this._headersCapability.promise;
14184 const {
14185 value,
14186 done
14187 } = await this._reader.read();
14188 if (done) {
14189 return {
14190 value,
14191 done
14192 };
14193 }
14194 this._loaded += value.byteLength;
14195 this.onProgress?.({
14196 loaded: this._loaded,
14197 total: this._contentLength
14198 });
14199 return {
14200 value: getArrayBuffer(value),
14201 done: false
14202 };
14203 }
14204 cancel(reason) {
14205 this._reader?.cancel(reason);
14206 this._abortController.abort();
14207 }
14208 }
14209 class PDFFetchStreamRangeReader {
14210 constructor(stream, begin, end) {
14211 this._stream = stream;
14212 this._reader = null;
14213 this._loaded = 0;
14214 const source = stream.source;
14215 this._withCredentials = source.withCredentials || false;
14216 this._readCapability = Promise.withResolvers();
14217 this._isStreamingSupported = !source.disableStream;
14218 this._abortController = new AbortController();
14219 this._headers = createHeaders(this._stream.httpHeaders);
14220 this._headers.append("Range", `bytes=${begin}-${end - 1}`);
14221 const url = source.url;
14222 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
14223 if (!validateResponseStatus(response.status)) {
14224 throw createResponseStatusError(response.status, url);
14225 }
14226 this._readCapability.resolve();
14227 this._reader = response.body.getReader();
14228 }).catch(this._readCapability.reject);
14229 this.onProgress = null;
14230 }
14231 get isStreamingSupported() {
14232 return this._isStreamingSupported;
14233 }
14234 async read() {
14235 await this._readCapability.promise;
14236 const {
14237 value,
14238 done
14239 } = await this._reader.read();
14240 if (done) {
14241 return {
14242 value,
14243 done
14244 };
14245 }
14246 this._loaded += value.byteLength;
14247 this.onProgress?.({
14248 loaded: this._loaded
14249 });
14250 return {
14251 value: getArrayBuffer(value),
14252 done: false
14253 };
14254 }
14255 cancel(reason) {
14256 this._reader?.cancel(reason);
14257 this._abortController.abort();
14258 }
14259 }
14260
14261 ;// CONCATENATED MODULE: ./src/display/network.js
14262
14263
14264
14265
14266 const OK_RESPONSE = 200;
14267 const PARTIAL_CONTENT_RESPONSE = 206;
14268 function network_getArrayBuffer(xhr) {
14269 const data = xhr.response;
14270 if (typeof data !== "string") {
14271 return data;
14272 }
14273 return stringToBytes(data).buffer;
14274 }
14275 class NetworkManager {
14276 constructor(url, args = {}) {
14277 this.url = url;
14278 this.isHttp = /^https?:/i.test(url);
14279 this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
14280 this.withCredentials = args.withCredentials || false;
14281 this.currXhrId = 0;
14282 this.pendingRequests = Object.create(null);
14283 }
14284 requestRange(begin, end, listeners) {
14285 const args = {
14286 begin,
14287 end
14288 };
14289 for (const prop in listeners) {
14290 args[prop] = listeners[prop];
14291 }
14292 return this.request(args);
14293 }
14294 requestFull(listeners) {
14295 return this.request(listeners);
14296 }
14297 request(args) {
14298 const xhr = new XMLHttpRequest();
14299 const xhrId = this.currXhrId++;
14300 const pendingRequest = this.pendingRequests[xhrId] = {
14301 xhr
14302 };
14303 xhr.open("GET", this.url);
14304 xhr.withCredentials = this.withCredentials;
14305 for (const property in this.httpHeaders) {
14306 const value = this.httpHeaders[property];
14307 if (value === undefined) {
14308 continue;
14309 }
14310 xhr.setRequestHeader(property, value);
14311 }
14312 if (this.isHttp && "begin" in args && "end" in args) {
14313 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
14314 pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
14315 } else {
14316 pendingRequest.expectedStatus = OK_RESPONSE;
14317 }
14318 xhr.responseType = "arraybuffer";
14319 if (args.onError) {
14320 xhr.onerror = function (evt) {
14321 args.onError(xhr.status);
14322 };
14323 }
14324 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
14325 xhr.onprogress = this.onProgress.bind(this, xhrId);
14326 pendingRequest.onHeadersReceived = args.onHeadersReceived;
14327 pendingRequest.onDone = args.onDone;
14328 pendingRequest.onError = args.onError;
14329 pendingRequest.onProgress = args.onProgress;
14330 xhr.send(null);
14331 return xhrId;
14332 }
14333 onProgress(xhrId, evt) {
14334 const pendingRequest = this.pendingRequests[xhrId];
14335 if (!pendingRequest) {
14336 return;
14337 }
14338 pendingRequest.onProgress?.(evt);
14339 }
14340 onStateChange(xhrId, evt) {
14341 const pendingRequest = this.pendingRequests[xhrId];
14342 if (!pendingRequest) {
14343 return;
14344 }
14345 const xhr = pendingRequest.xhr;
14346 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
14347 pendingRequest.onHeadersReceived();
14348 delete pendingRequest.onHeadersReceived;
14349 }
14350 if (xhr.readyState !== 4) {
14351 return;
14352 }
14353 if (!(xhrId in this.pendingRequests)) {
14354 return;
14355 }
14356 delete this.pendingRequests[xhrId];
14357 if (xhr.status === 0 && this.isHttp) {
14358 pendingRequest.onError?.(xhr.status);
14359 return;
14360 }
14361 const xhrStatus = xhr.status || OK_RESPONSE;
14362 const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
14363 if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
14364 pendingRequest.onError?.(xhr.status);
14365 return;
14366 }
14367 const chunk = network_getArrayBuffer(xhr);
14368 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
14369 const rangeHeader = xhr.getResponseHeader("Content-Range");
14370 const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
14371 pendingRequest.onDone({
14372 begin: parseInt(matches[1], 10),
14373 chunk
14374 });
14375 } else if (chunk) {
14376 pendingRequest.onDone({
14377 begin: 0,
14378 chunk
14379 });
14380 } else {
14381 pendingRequest.onError?.(xhr.status);
14382 }
14383 }
14384 getRequestXhr(xhrId) {
14385 return this.pendingRequests[xhrId].xhr;
14386 }
14387 isPendingRequest(xhrId) {
14388 return xhrId in this.pendingRequests;
14389 }
14390 abortRequest(xhrId) {
14391 const xhr = this.pendingRequests[xhrId].xhr;
14392 delete this.pendingRequests[xhrId];
14393 xhr.abort();
14394 }
14395 }
14396 class PDFNetworkStream {
14397 constructor(source) {
14398 this._source = source;
14399 this._manager = new NetworkManager(source.url, {
14400 httpHeaders: source.httpHeaders,
14401 withCredentials: source.withCredentials
14402 });
14403 this._rangeChunkSize = source.rangeChunkSize;
14404 this._fullRequestReader = null;
14405 this._rangeRequestReaders = [];
14406 }
14407 _onRangeRequestReaderClosed(reader) {
14408 const i = this._rangeRequestReaders.indexOf(reader);
14409 if (i >= 0) {
14410 this._rangeRequestReaders.splice(i, 1);
14411 }
14412 }
14413 getFullReader() {
14414 assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
14415 this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
14416 return this._fullRequestReader;
14417 }
14418 getRangeReader(begin, end) {
14419 const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
14420 reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
14421 this._rangeRequestReaders.push(reader);
14422 return reader;
14423 }
14424 cancelAllRequests(reason) {
14425 this._fullRequestReader?.cancel(reason);
14426 for (const reader of this._rangeRequestReaders.slice(0)) {
14427 reader.cancel(reason);
14428 }
14429 }
14430 }
14431 class PDFNetworkStreamFullRequestReader {
14432 constructor(manager, source) {
14433 this._manager = manager;
14434 const args = {
14435 onHeadersReceived: this._onHeadersReceived.bind(this),
14436 onDone: this._onDone.bind(this),
14437 onError: this._onError.bind(this),
14438 onProgress: this._onProgress.bind(this)
14439 };
14440 this._url = source.url;
14441 this._fullRequestId = manager.requestFull(args);
14442 this._headersReceivedCapability = Promise.withResolvers();
14443 this._disableRange = source.disableRange || false;
14444 this._contentLength = source.length;
14445 this._rangeChunkSize = source.rangeChunkSize;
14446 if (!this._rangeChunkSize && !this._disableRange) {
14447 this._disableRange = true;
14448 }
14449 this._isStreamingSupported = false;
14450 this._isRangeSupported = false;
14451 this._cachedChunks = [];
14452 this._requests = [];
14453 this._done = false;
14454 this._storedError = undefined;
14455 this._filename = null;
14456 this.onProgress = null;
14457 }
14458 _onHeadersReceived() {
14459 const fullRequestXhrId = this._fullRequestId;
14460 const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
14461 const getResponseHeader = name => fullRequestXhr.getResponseHeader(name);
14462 const {
14463 allowRangeRequests,
14464 suggestedLength
14465 } = validateRangeRequestCapabilities({
14466 getResponseHeader,
14467 isHttp: this._manager.isHttp,
14468 rangeChunkSize: this._rangeChunkSize,
14469 disableRange: this._disableRange
14470 });
14471 if (allowRangeRequests) {
14472 this._isRangeSupported = true;
14473 }
14474 this._contentLength = suggestedLength || this._contentLength;
14475 this._filename = extractFilenameFromHeader(getResponseHeader);
14476 if (this._isRangeSupported) {
14477 this._manager.abortRequest(fullRequestXhrId);
14478 }
14479 this._headersReceivedCapability.resolve();
14480 }
14481 _onDone(data) {
14482 if (data) {
14483 if (this._requests.length > 0) {
14484 const requestCapability = this._requests.shift();
14485 requestCapability.resolve({
14486 value: data.chunk,
14487 done: false
14488 });
14489 } else {
14490 this._cachedChunks.push(data.chunk);
14491 }
14492 }
14493 this._done = true;
14494 if (this._cachedChunks.length > 0) {
14495 return;
14496 }
14497 for (const requestCapability of this._requests) {
14498 requestCapability.resolve({
14499 value: undefined,
14500 done: true
14501 });
14502 }
14503 this._requests.length = 0;
14504 }
14505 _onError(status) {
14506 this._storedError = createResponseStatusError(status, this._url);
14507 this._headersReceivedCapability.reject(this._storedError);
14508 for (const requestCapability of this._requests) {
14509 requestCapability.reject(this._storedError);
14510 }
14511 this._requests.length = 0;
14512 this._cachedChunks.length = 0;
14513 }
14514 _onProgress(evt) {
14515 this.onProgress?.({
14516 loaded: evt.loaded,
14517 total: evt.lengthComputable ? evt.total : this._contentLength
14518 });
14519 }
14520 get filename() {
14521 return this._filename;
14522 }
14523 get isRangeSupported() {
14524 return this._isRangeSupported;
14525 }
14526 get isStreamingSupported() {
14527 return this._isStreamingSupported;
14528 }
14529 get contentLength() {
14530 return this._contentLength;
14531 }
14532 get headersReady() {
14533 return this._headersReceivedCapability.promise;
14534 }
14535 async read() {
14536 if (this._storedError) {
14537 throw this._storedError;
14538 }
14539 if (this._cachedChunks.length > 0) {
14540 const chunk = this._cachedChunks.shift();
14541 return {
14542 value: chunk,
14543 done: false
14544 };
14545 }
14546 if (this._done) {
14547 return {
14548 value: undefined,
14549 done: true
14550 };
14551 }
14552 const requestCapability = Promise.withResolvers();
14553 this._requests.push(requestCapability);
14554 return requestCapability.promise;
14555 }
14556 cancel(reason) {
14557 this._done = true;
14558 this._headersReceivedCapability.reject(reason);
14559 for (const requestCapability of this._requests) {
14560 requestCapability.resolve({
14561 value: undefined,
14562 done: true
14563 });
14564 }
14565 this._requests.length = 0;
14566 if (this._manager.isPendingRequest(this._fullRequestId)) {
14567 this._manager.abortRequest(this._fullRequestId);
14568 }
14569 this._fullRequestReader = null;
14570 }
14571 }
14572 class PDFNetworkStreamRangeRequestReader {
14573 constructor(manager, begin, end) {
14574 this._manager = manager;
14575 const args = {
14576 onDone: this._onDone.bind(this),
14577 onError: this._onError.bind(this),
14578 onProgress: this._onProgress.bind(this)
14579 };
14580 this._url = manager.url;
14581 this._requestId = manager.requestRange(begin, end, args);
14582 this._requests = [];
14583 this._queuedChunk = null;
14584 this._done = false;
14585 this._storedError = undefined;
14586 this.onProgress = null;
14587 this.onClosed = null;
14588 }
14589 _close() {
14590 this.onClosed?.(this);
14591 }
14592 _onDone(data) {
14593 const chunk = data.chunk;
14594 if (this._requests.length > 0) {
14595 const requestCapability = this._requests.shift();
14596 requestCapability.resolve({
14597 value: chunk,
14598 done: false
14599 });
14600 } else {
14601 this._queuedChunk = chunk;
14602 }
14603 this._done = true;
14604 for (const requestCapability of this._requests) {
14605 requestCapability.resolve({
14606 value: undefined,
14607 done: true
14608 });
14609 }
14610 this._requests.length = 0;
14611 this._close();
14612 }
14613 _onError(status) {
14614 this._storedError = createResponseStatusError(status, this._url);
14615 for (const requestCapability of this._requests) {
14616 requestCapability.reject(this._storedError);
14617 }
14618 this._requests.length = 0;
14619 this._queuedChunk = null;
14620 }
14621 _onProgress(evt) {
14622 if (!this.isStreamingSupported) {
14623 this.onProgress?.({
14624 loaded: evt.loaded
14625 });
14626 }
14627 }
14628 get isStreamingSupported() {
14629 return false;
14630 }
14631 async read() {
14632 if (this._storedError) {
14633 throw this._storedError;
14634 }
14635 if (this._queuedChunk !== null) {
14636 const chunk = this._queuedChunk;
14637 this._queuedChunk = null;
14638 return {
14639 value: chunk,
14640 done: false
14641 };
14642 }
14643 if (this._done) {
14644 return {
14645 value: undefined,
14646 done: true
14647 };
14648 }
14649 const requestCapability = Promise.withResolvers();
14650 this._requests.push(requestCapability);
14651 return requestCapability.promise;
14652 }
14653 cancel(reason) {
14654 this._done = true;
14655 for (const requestCapability of this._requests) {
14656 requestCapability.resolve({
14657 value: undefined,
14658 done: true
14659 });
14660 }
14661 this._requests.length = 0;
14662 if (this._manager.isPendingRequest(this._requestId)) {
14663 this._manager.abortRequest(this._requestId);
14664 }
14665 this._close();
14666 }
14667 }
14668
14669 ;// CONCATENATED MODULE: ./src/display/node_stream.js
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681 const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
14682 function parseUrl(sourceUrl) {
14683 const url = NodePackages.get("url");
14684 const parsedUrl = url.parse(sourceUrl);
14685 if (parsedUrl.protocol === "file:" || parsedUrl.host) {
14686 return parsedUrl;
14687 }
14688 if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
14689 return url.parse(`file:///${sourceUrl}`);
14690 }
14691 if (!parsedUrl.host) {
14692 parsedUrl.protocol = "file:";
14693 }
14694 return parsedUrl;
14695 }
14696 class PDFNodeStream {
14697 constructor(source) {
14698 this.source = source;
14699 this.url = parseUrl(source.url);
14700 this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
14701 this.isFsUrl = this.url.protocol === "file:";
14702 this.httpHeaders = this.isHttp && source.httpHeaders || {};
14703 this._fullRequestReader = null;
14704 this._rangeRequestReaders = [];
14705 }
14706 get _progressiveDataLength() {
14707 return this._fullRequestReader?._loaded ?? 0;
14708 }
14709 getFullReader() {
14710 assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
14711 this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
14712 return this._fullRequestReader;
14713 }
14714 getRangeReader(start, end) {
14715 if (end <= this._progressiveDataLength) {
14716 return null;
14717 }
14718 const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
14719 this._rangeRequestReaders.push(rangeReader);
14720 return rangeReader;
14721 }
14722 cancelAllRequests(reason) {
14723 this._fullRequestReader?.cancel(reason);
14724 for (const reader of this._rangeRequestReaders.slice(0)) {
14725 reader.cancel(reason);
14726 }
14727 }
14728 }
14729 class BaseFullReader {
14730 constructor(stream) {
14731 this._url = stream.url;
14732 this._done = false;
14733 this._storedError = null;
14734 this.onProgress = null;
14735 const source = stream.source;
14736 this._contentLength = source.length;
14737 this._loaded = 0;
14738 this._filename = null;
14739 this._disableRange = source.disableRange || false;
14740 this._rangeChunkSize = source.rangeChunkSize;
14741 if (!this._rangeChunkSize && !this._disableRange) {
14742 this._disableRange = true;
14743 }
14744 this._isStreamingSupported = !source.disableStream;
14745 this._isRangeSupported = !source.disableRange;
14746 this._readableStream = null;
14747 this._readCapability = Promise.withResolvers();
14748 this._headersCapability = Promise.withResolvers();
14749 }
14750 get headersReady() {
14751 return this._headersCapability.promise;
14752 }
14753 get filename() {
14754 return this._filename;
14755 }
14756 get contentLength() {
14757 return this._contentLength;
14758 }
14759 get isRangeSupported() {
14760 return this._isRangeSupported;
14761 }
14762 get isStreamingSupported() {
14763 return this._isStreamingSupported;
14764 }
14765 async read() {
14766 await this._readCapability.promise;
14767 if (this._done) {
14768 return {
14769 value: undefined,
14770 done: true
14771 };
14772 }
14773 if (this._storedError) {
14774 throw this._storedError;
14775 }
14776 const chunk = this._readableStream.read();
14777 if (chunk === null) {
14778 this._readCapability = Promise.withResolvers();
14779 return this.read();
14780 }
14781 this._loaded += chunk.length;
14782 this.onProgress?.({
14783 loaded: this._loaded,
14784 total: this._contentLength
14785 });
14786 const buffer = new Uint8Array(chunk).buffer;
14787 return {
14788 value: buffer,
14789 done: false
14790 };
14791 }
14792 cancel(reason) {
14793 if (!this._readableStream) {
14794 this._error(reason);
14795 return;
14796 }
14797 this._readableStream.destroy(reason);
14798 }
14799 _error(reason) {
14800 this._storedError = reason;
14801 this._readCapability.resolve();
14802 }
14803 _setReadableStream(readableStream) {
14804 this._readableStream = readableStream;
14805 readableStream.on("readable", () => {
14806 this._readCapability.resolve();
14807 });
14808 readableStream.on("end", () => {
14809 readableStream.destroy();
14810 this._done = true;
14811 this._readCapability.resolve();
14812 });
14813 readableStream.on("error", reason => {
14814 this._error(reason);
14815 });
14816 if (!this._isStreamingSupported && this._isRangeSupported) {
14817 this._error(new AbortException("streaming is disabled"));
14818 }
14819 if (this._storedError) {
14820 this._readableStream.destroy(this._storedError);
14821 }
14822 }
14823 }
14824 class BaseRangeReader {
14825 constructor(stream) {
14826 this._url = stream.url;
14827 this._done = false;
14828 this._storedError = null;
14829 this.onProgress = null;
14830 this._loaded = 0;
14831 this._readableStream = null;
14832 this._readCapability = Promise.withResolvers();
14833 const source = stream.source;
14834 this._isStreamingSupported = !source.disableStream;
14835 }
14836 get isStreamingSupported() {
14837 return this._isStreamingSupported;
14838 }
14839 async read() {
14840 await this._readCapability.promise;
14841 if (this._done) {
14842 return {
14843 value: undefined,
14844 done: true
14845 };
14846 }
14847 if (this._storedError) {
14848 throw this._storedError;
14849 }
14850 const chunk = this._readableStream.read();
14851 if (chunk === null) {
14852 this._readCapability = Promise.withResolvers();
14853 return this.read();
14854 }
14855 this._loaded += chunk.length;
14856 this.onProgress?.({
14857 loaded: this._loaded
14858 });
14859 const buffer = new Uint8Array(chunk).buffer;
14860 return {
14861 value: buffer,
14862 done: false
14863 };
14864 }
14865 cancel(reason) {
14866 if (!this._readableStream) {
14867 this._error(reason);
14868 return;
14869 }
14870 this._readableStream.destroy(reason);
14871 }
14872 _error(reason) {
14873 this._storedError = reason;
14874 this._readCapability.resolve();
14875 }
14876 _setReadableStream(readableStream) {
14877 this._readableStream = readableStream;
14878 readableStream.on("readable", () => {
14879 this._readCapability.resolve();
14880 });
14881 readableStream.on("end", () => {
14882 readableStream.destroy();
14883 this._done = true;
14884 this._readCapability.resolve();
14885 });
14886 readableStream.on("error", reason => {
14887 this._error(reason);
14888 });
14889 if (this._storedError) {
14890 this._readableStream.destroy(this._storedError);
14891 }
14892 }
14893 }
14894 function createRequestOptions(parsedUrl, headers) {
14895 return {
14896 protocol: parsedUrl.protocol,
14897 auth: parsedUrl.auth,
14898 host: parsedUrl.hostname,
14899 port: parsedUrl.port,
14900 path: parsedUrl.path,
14901 method: "GET",
14902 headers
14903 };
14904 }
14905 class PDFNodeStreamFullReader extends BaseFullReader {
14906 constructor(stream) {
14907 super(stream);
14908 const handleResponse = response => {
14909 if (response.statusCode === 404) {
14910 const error = new MissingPDFException(`Missing PDF "${this._url}".`);
14911 this._storedError = error;
14912 this._headersCapability.reject(error);
14913 return;
14914 }
14915 this._headersCapability.resolve();
14916 this._setReadableStream(response);
14917 const getResponseHeader = name => this._readableStream.headers[name.toLowerCase()];
14918 const {
14919 allowRangeRequests,
14920 suggestedLength
14921 } = validateRangeRequestCapabilities({
14922 getResponseHeader,
14923 isHttp: stream.isHttp,
14924 rangeChunkSize: this._rangeChunkSize,
14925 disableRange: this._disableRange
14926 });
14927 this._isRangeSupported = allowRangeRequests;
14928 this._contentLength = suggestedLength || this._contentLength;
14929 this._filename = extractFilenameFromHeader(getResponseHeader);
14930 };
14931 this._request = null;
14932 if (this._url.protocol === "http:") {
14933 const http = NodePackages.get("http");
14934 this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14935 } else {
14936 const https = NodePackages.get("https");
14937 this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14938 }
14939 this._request.on("error", reason => {
14940 this._storedError = reason;
14941 this._headersCapability.reject(reason);
14942 });
14943 this._request.end();
14944 }
14945 }
14946 class PDFNodeStreamRangeReader extends BaseRangeReader {
14947 constructor(stream, start, end) {
14948 super(stream);
14949 this._httpHeaders = {};
14950 for (const property in stream.httpHeaders) {
14951 const value = stream.httpHeaders[property];
14952 if (value === undefined) {
14953 continue;
14954 }
14955 this._httpHeaders[property] = value;
14956 }
14957 this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
14958 const handleResponse = response => {
14959 if (response.statusCode === 404) {
14960 const error = new MissingPDFException(`Missing PDF "${this._url}".`);
14961 this._storedError = error;
14962 return;
14963 }
14964 this._setReadableStream(response);
14965 };
14966 this._request = null;
14967 if (this._url.protocol === "http:") {
14968 const http = NodePackages.get("http");
14969 this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14970 } else {
14971 const https = NodePackages.get("https");
14972 this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14973 }
14974 this._request.on("error", reason => {
14975 this._storedError = reason;
14976 });
14977 this._request.end();
14978 }
14979 }
14980 class PDFNodeStreamFsFullReader extends BaseFullReader {
14981 constructor(stream) {
14982 super(stream);
14983 let path = decodeURIComponent(this._url.path);
14984 if (fileUriRegex.test(this._url.href)) {
14985 path = path.replace(/^\//, "");
14986 }
14987 const fs = NodePackages.get("fs");
14988 fs.promises.lstat(path).then(stat => {
14989 this._contentLength = stat.size;
14990 this._setReadableStream(fs.createReadStream(path));
14991 this._headersCapability.resolve();
14992 }, error => {
14993 if (error.code === "ENOENT") {
14994 error = new MissingPDFException(`Missing PDF "${path}".`);
14995 }
14996 this._storedError = error;
14997 this._headersCapability.reject(error);
14998 });
14999 }
15000 }
15001 class PDFNodeStreamFsRangeReader extends BaseRangeReader {
15002 constructor(stream, start, end) {
15003 super(stream);
15004 let path = decodeURIComponent(this._url.path);
15005 if (fileUriRegex.test(this._url.href)) {
15006 path = path.replace(/^\//, "");
15007 }
15008 const fs = NodePackages.get("fs");
15009 this._setReadableStream(fs.createReadStream(path, {
15010 start,
15011 end: end - 1
15012 }));
15013 }
15014 }
15015
15016 ;// CONCATENATED MODULE: ./src/display/text_layer.js
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028 const MAX_TEXT_DIVS_TO_RENDER = 100000;
15029 const DEFAULT_FONT_SIZE = 30;
15030 const DEFAULT_FONT_ASCENT = 0.8;
15031 class TextLayer {
15032 #capability = Promise.withResolvers();
15033 #container = null;
15034 #disableProcessItems = false;
15035 #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
15036 #lang = null;
15037 #layoutTextParams = null;
15038 #pageHeight = 0;
15039 #pageWidth = 0;
15040 #reader = null;
15041 #rootContainer = null;
15042 #rotation = 0;
15043 #scale = 0;
15044 #styleCache = Object.create(null);
15045 #textContentItemsStr = [];
15046 #textContentSource = null;
15047 #textDivs = [];
15048 #textDivProperties = new WeakMap();
15049 #transform = null;
15050 static #ascentCache = new Map();
15051 static #canvasContexts = new Map();
15052 static #pendingTextLayers = new Set();
15053 constructor({
15054 textContentSource,
15055 container,
15056 viewport
15057 }) {
15058 if (textContentSource instanceof ReadableStream) {
15059 this.#textContentSource = textContentSource;
15060 } else if (typeof textContentSource === "object") {
15061 this.#textContentSource = new ReadableStream({
15062 start(controller) {
15063 controller.enqueue(textContentSource);
15064 controller.close();
15065 }
15066 });
15067 } else {
15068 throw new Error('No "textContentSource" parameter specified.');
15069 }
15070 this.#container = this.#rootContainer = container;
15071 this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);
15072 this.#rotation = viewport.rotation;
15073 this.#layoutTextParams = {
15074 prevFontSize: null,
15075 prevFontFamily: null,
15076 div: null,
15077 properties: null,
15078 ctx: null
15079 };
15080 const {
15081 pageWidth,
15082 pageHeight,
15083 pageX,
15084 pageY
15085 } = viewport.rawDims;
15086 this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
15087 this.#pageWidth = pageWidth;
15088 this.#pageHeight = pageHeight;
15089 setLayerDimensions(container, viewport);
15090 this.#capability.promise.catch(() => {}).then(() => {
15091 TextLayer.#pendingTextLayers.delete(this);
15092 this.#layoutTextParams = null;
15093 this.#styleCache = null;
15094 });
15095 }
15096 render() {
15097 const pump = () => {
15098 this.#reader.read().then(({
15099 value,
15100 done
15101 }) => {
15102 if (done) {
15103 this.#capability.resolve();
15104 return;
15105 }
15106 this.#lang ??= value.lang;
15107 Object.assign(this.#styleCache, value.styles);
15108 this.#processItems(value.items);
15109 pump();
15110 }, this.#capability.reject);
15111 };
15112 this.#reader = this.#textContentSource.getReader();
15113 TextLayer.#pendingTextLayers.add(this);
15114 pump();
15115 return this.#capability.promise;
15116 }
15117 update({
15118 viewport,
15119 onBefore = null
15120 }) {
15121 const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
15122 const rotation = viewport.rotation;
15123 if (rotation !== this.#rotation) {
15124 onBefore?.();
15125 this.#rotation = rotation;
15126 setLayerDimensions(this.#rootContainer, {
15127 rotation
15128 });
15129 }
15130 if (scale !== this.#scale) {
15131 onBefore?.();
15132 this.#scale = scale;
15133 const params = {
15134 prevFontSize: null,
15135 prevFontFamily: null,
15136 div: null,
15137 properties: null,
15138 ctx: TextLayer.#getCtx(this.#lang)
15139 };
15140 for (const div of this.#textDivs) {
15141 params.properties = this.#textDivProperties.get(div);
15142 params.div = div;
15143 this.#layout(params);
15144 }
15145 }
15146 }
15147 cancel() {
15148 const abortEx = new AbortException("TextLayer task cancelled.");
15149 this.#reader?.cancel(abortEx).catch(() => {});
15150 this.#reader = null;
15151 this.#capability.reject(abortEx);
15152 }
15153 get textDivs() {
15154 return this.#textDivs;
15155 }
15156 get textContentItemsStr() {
15157 return this.#textContentItemsStr;
15158 }
15159 #processItems(items) {
15160 if (this.#disableProcessItems) {
15161 return;
15162 }
15163 this.#layoutTextParams.ctx ||= TextLayer.#getCtx(this.#lang);
15164 const textDivs = this.#textDivs,
15165 textContentItemsStr = this.#textContentItemsStr;
15166 for (const item of items) {
15167 if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
15168 warn("Ignoring additional textDivs for performance reasons.");
15169 this.#disableProcessItems = true;
15170 return;
15171 }
15172 if (item.str === undefined) {
15173 if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
15174 const parent = this.#container;
15175 this.#container = document.createElement("span");
15176 this.#container.classList.add("markedContent");
15177 if (item.id !== null) {
15178 this.#container.setAttribute("id", `${item.id}`);
15179 }
15180 parent.append(this.#container);
15181 } else if (item.type === "endMarkedContent") {
15182 this.#container = this.#container.parentNode;
15183 }
15184 continue;
15185 }
15186 textContentItemsStr.push(item.str);
15187 this.#appendText(item);
15188 }
15189 }
15190 #appendText(geom) {
15191 const textDiv = document.createElement("span");
15192 const textDivProperties = {
15193 angle: 0,
15194 canvasWidth: 0,
15195 hasText: geom.str !== "",
15196 hasEOL: geom.hasEOL,
15197 fontSize: 0
15198 };
15199 this.#textDivs.push(textDiv);
15200 const tx = Util.transform(this.#transform, geom.transform);
15201 let angle = Math.atan2(tx[1], tx[0]);
15202 const style = this.#styleCache[geom.fontName];
15203 if (style.vertical) {
15204 angle += Math.PI / 2;
15205 }
15206 const fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
15207 const fontHeight = Math.hypot(tx[2], tx[3]);
15208 const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);
15209 let left, top;
15210 if (angle === 0) {
15211 left = tx[4];
15212 top = tx[5] - fontAscent;
15213 } else {
15214 left = tx[4] + fontAscent * Math.sin(angle);
15215 top = tx[5] - fontAscent * Math.cos(angle);
15216 }
15217 const scaleFactorStr = "calc(var(--scale-factor)*";
15218 const divStyle = textDiv.style;
15219 if (this.#container === this.#rootContainer) {
15220 divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
15221 divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
15222 } else {
15223 divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
15224 divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
15225 }
15226 divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
15227 divStyle.fontFamily = fontFamily;
15228 textDivProperties.fontSize = fontHeight;
15229 textDiv.setAttribute("role", "presentation");
15230 textDiv.textContent = geom.str;
15231 textDiv.dir = geom.dir;
15232 if (this.#fontInspectorEnabled) {
15233 textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
15234 }
15235 if (angle !== 0) {
15236 textDivProperties.angle = angle * (180 / Math.PI);
15237 }
15238 let shouldScaleText = false;
15239 if (geom.str.length > 1) {
15240 shouldScaleText = true;
15241 } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
15242 const absScaleX = Math.abs(geom.transform[0]),
15243 absScaleY = Math.abs(geom.transform[3]);
15244 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
15245 shouldScaleText = true;
15246 }
15247 }
15248 if (shouldScaleText) {
15249 textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
15250 }
15251 this.#textDivProperties.set(textDiv, textDivProperties);
15252 this.#layoutTextParams.div = textDiv;
15253 this.#layoutTextParams.properties = textDivProperties;
15254 this.#layout(this.#layoutTextParams);
15255 if (textDivProperties.hasText) {
15256 this.#container.append(textDiv);
15257 }
15258 if (textDivProperties.hasEOL) {
15259 const br = document.createElement("br");
15260 br.setAttribute("role", "presentation");
15261 this.#container.append(br);
15262 }
15263 }
15264 #layout(params) {
15265 const {
15266 div,
15267 properties,
15268 ctx,
15269 prevFontSize,
15270 prevFontFamily
15271 } = params;
15272 const {
15273 style
15274 } = div;
15275 let transform = "";
15276 if (properties.canvasWidth !== 0 && properties.hasText) {
15277 const {
15278 fontFamily
15279 } = style;
15280 const {
15281 canvasWidth,
15282 fontSize
15283 } = properties;
15284 if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
15285 ctx.font = `${fontSize * this.#scale}px ${fontFamily}`;
15286 params.prevFontSize = fontSize;
15287 params.prevFontFamily = fontFamily;
15288 }
15289 const {
15290 width
15291 } = ctx.measureText(div.textContent);
15292 if (width > 0) {
15293 transform = `scaleX(${canvasWidth * this.#scale / width})`;
15294 }
15295 }
15296 if (properties.angle !== 0) {
15297 transform = `rotate(${properties.angle}deg) ${transform}`;
15298 }
15299 if (transform.length > 0) {
15300 style.transform = transform;
15301 }
15302 }
15303 static cleanup() {
15304 if (this.#pendingTextLayers.size > 0) {
15305 return;
15306 }
15307 this.#ascentCache.clear();
15308 for (const {
15309 canvas
15310 } of this.#canvasContexts.values()) {
15311 canvas.remove();
15312 }
15313 this.#canvasContexts.clear();
15314 }
15315 static #getCtx(lang = null) {
15316 let canvasContext = this.#canvasContexts.get(lang ||= "");
15317 if (!canvasContext) {
15318 const canvas = document.createElement("canvas");
15319 canvas.className = "hiddenCanvasElement";
15320 canvas.lang = lang;
15321 document.body.append(canvas);
15322 canvasContext = canvas.getContext("2d", {
15323 alpha: false
15324 });
15325 this.#canvasContexts.set(lang, canvasContext);
15326 }
15327 return canvasContext;
15328 }
15329 static #getAscent(fontFamily, lang) {
15330 const cachedAscent = this.#ascentCache.get(fontFamily);
15331 if (cachedAscent) {
15332 return cachedAscent;
15333 }
15334 const ctx = this.#getCtx(lang);
15335 const savedFont = ctx.font;
15336 ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
15337 ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
15338 const metrics = ctx.measureText("");
15339 let ascent = metrics.fontBoundingBoxAscent;
15340 let descent = Math.abs(metrics.fontBoundingBoxDescent);
15341 if (ascent) {
15342 const ratio = ascent / (ascent + descent);
15343 this.#ascentCache.set(fontFamily, ratio);
15344 ctx.canvas.width = ctx.canvas.height = 0;
15345 ctx.font = savedFont;
15346 return ratio;
15347 }
15348 ctx.strokeStyle = "red";
15349 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
15350 ctx.strokeText("g", 0, 0);
15351 let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
15352 descent = 0;
15353 for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
15354 if (pixels[i] > 0) {
15355 descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
15356 break;
15357 }
15358 }
15359 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
15360 ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
15361 pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
15362 ascent = 0;
15363 for (let i = 0, ii = pixels.length; i < ii; i += 4) {
15364 if (pixels[i] > 0) {
15365 ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
15366 break;
15367 }
15368 }
15369 ctx.canvas.width = ctx.canvas.height = 0;
15370 ctx.font = savedFont;
15371 const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;
15372 this.#ascentCache.set(fontFamily, ratio);
15373 return ratio;
15374 }
15375 }
15376 function renderTextLayer() {
15377 deprecated("`renderTextLayer`, please use `TextLayer` instead.");
15378 const {
15379 textContentSource,
15380 container,
15381 viewport,
15382 ...rest
15383 } = arguments[0];
15384 const restKeys = Object.keys(rest);
15385 if (restKeys.length > 0) {
15386 warn("Ignoring `renderTextLayer` parameters: " + restKeys.join(", "));
15387 }
15388 const textLayer = new TextLayer({
15389 textContentSource,
15390 container,
15391 viewport
15392 });
15393 const {
15394 textDivs,
15395 textContentItemsStr
15396 } = textLayer;
15397 const promise = textLayer.render();
15398 return {
15399 promise,
15400 textDivs,
15401 textContentItemsStr
15402 };
15403 }
15404 function updateTextLayer() {
15405 deprecated("`updateTextLayer`, please use `TextLayer` instead.");
15406 }
15407
15408 ;// CONCATENATED MODULE: ./src/display/xfa_text.js
15409
15410 class XfaText {
15411 static textContent(xfa) {
15412 const items = [];
15413 const output = {
15414 items,
15415 styles: Object.create(null)
15416 };
15417 function walk(node) {
15418 if (!node) {
15419 return;
15420 }
15421 let str = null;
15422 const name = node.name;
15423 if (name === "#text") {
15424 str = node.value;
15425 } else if (!XfaText.shouldBuildText(name)) {
15426 return;
15427 } else if (node?.attributes?.textContent) {
15428 str = node.attributes.textContent;
15429 } else if (node.value) {
15430 str = node.value;
15431 }
15432 if (str !== null) {
15433 items.push({
15434 str
15435 });
15436 }
15437 if (!node.children) {
15438 return;
15439 }
15440 for (const child of node.children) {
15441 walk(child);
15442 }
15443 }
15444 walk(xfa);
15445 return output;
15446 }
15447 static shouldBuildText(name) {
15448 return !(name === "textarea" || name === "input" || name === "option" || name === "select");
15449 }
15450 }
15451
15452 ;// CONCATENATED MODULE: ./src/display/api.js
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489 const DEFAULT_RANGE_CHUNK_SIZE = 65536;
15490 const RENDERING_CANCELLED_TIMEOUT = 100;
15491 const DELAYED_CLEANUP_TIMEOUT = 5000;
15492 const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory;
15493 const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory;
15494 const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory;
15495 const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory;
15496 function getDocument(src) {
15497 if (typeof src === "string" || src instanceof URL) {
15498 src = {
15499 url: src
15500 };
15501 } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
15502 src = {
15503 data: src
15504 };
15505 }
15506 if (typeof src !== "object") {
15507 throw new Error("Invalid parameter in getDocument, need parameter object.");
15508 }
15509 if (!src.url && !src.data && !src.range) {
15510 throw new Error("Invalid parameter object: need either .data, .range or .url");
15511 }
15512 const task = new PDFDocumentLoadingTask();
15513 const {
15514 docId
15515 } = task;
15516 const url = src.url ? getUrlProp(src.url) : null;
15517 const data = src.data ? getDataProp(src.data) : null;
15518 const httpHeaders = src.httpHeaders || null;
15519 const withCredentials = src.withCredentials === true;
15520 const password = src.password ?? null;
15521 const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
15522 const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
15523 let worker = src.worker instanceof PDFWorker ? src.worker : null;
15524 const verbosity = src.verbosity;
15525 const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
15526 const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
15527 const cMapPacked = src.cMapPacked !== false;
15528 const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
15529 const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
15530 const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
15531 const ignoreErrors = src.stopAtErrors !== true;
15532 const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
15533 const isEvalSupported = src.isEvalSupported !== false;
15534 const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
15535 const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
15536 const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
15537 const fontExtraProperties = src.fontExtraProperties === true;
15538 const enableXfa = src.enableXfa === true;
15539 const ownerDocument = src.ownerDocument || globalThis.document;
15540 const disableRange = src.disableRange === true;
15541 const disableStream = src.disableStream === true;
15542 const disableAutoFetch = src.disableAutoFetch === true;
15543 const pdfBug = src.pdfBug === true;
15544 const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
15545 const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
15546 const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI);
15547 const canvasFactory = src.canvasFactory || new DefaultCanvasFactory({
15548 ownerDocument
15549 });
15550 const filterFactory = src.filterFactory || new DefaultFilterFactory({
15551 docId,
15552 ownerDocument
15553 });
15554 const styleElement = null;
15555 setVerbosityLevel(verbosity);
15556 const transportFactory = {
15557 canvasFactory,
15558 filterFactory
15559 };
15560 if (!useWorkerFetch) {
15561 transportFactory.cMapReaderFactory = new CMapReaderFactory({
15562 baseUrl: cMapUrl,
15563 isCompressed: cMapPacked
15564 });
15565 transportFactory.standardFontDataFactory = new StandardFontDataFactory({
15566 baseUrl: standardFontDataUrl
15567 });
15568 }
15569 if (!worker) {
15570 const workerParams = {
15571 verbosity,
15572 port: GlobalWorkerOptions.workerPort
15573 };
15574 worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
15575 task._worker = worker;
15576 }
15577 const docParams = {
15578 docId,
15579 apiVersion: "4.3.136",
15580 data,
15581 password,
15582 disableAutoFetch,
15583 rangeChunkSize,
15584 length,
15585 docBaseUrl,
15586 enableXfa,
15587 evaluatorOptions: {
15588 maxImageSize,
15589 disableFontFace,
15590 ignoreErrors,
15591 isEvalSupported,
15592 isOffscreenCanvasSupported,
15593 canvasMaxAreaInBytes,
15594 fontExtraProperties,
15595 useSystemFonts,
15596 cMapUrl: useWorkerFetch ? cMapUrl : null,
15597 standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
15598 }
15599 };
15600 const transportParams = {
15601 disableFontFace,
15602 fontExtraProperties,
15603 ownerDocument,
15604 pdfBug,
15605 styleElement,
15606 loadingParams: {
15607 disableAutoFetch,
15608 enableXfa
15609 }
15610 };
15611 worker.promise.then(function () {
15612 if (task.destroyed) {
15613 throw new Error("Loading aborted");
15614 }
15615 if (worker.destroyed) {
15616 throw new Error("Worker was destroyed");
15617 }
15618 const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
15619 let networkStream;
15620 if (rangeTransport) {
15621 networkStream = new PDFDataTransportStream(rangeTransport, {
15622 disableRange,
15623 disableStream
15624 });
15625 } else if (!data) {
15626 const createPDFNetworkStream = params => {
15627 if (isNodeJS) {
15628 const isFetchSupported = function () {
15629 return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
15630 };
15631 return isFetchSupported() && isValidFetchUrl(params.url) ? new PDFFetchStream(params) : new PDFNodeStream(params);
15632 }
15633 return isValidFetchUrl(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params);
15634 };
15635 networkStream = createPDFNetworkStream({
15636 url,
15637 length,
15638 httpHeaders,
15639 withCredentials,
15640 rangeChunkSize,
15641 disableRange,
15642 disableStream
15643 });
15644 }
15645 return workerIdPromise.then(workerId => {
15646 if (task.destroyed) {
15647 throw new Error("Loading aborted");
15648 }
15649 if (worker.destroyed) {
15650 throw new Error("Worker was destroyed");
15651 }
15652 const messageHandler = new MessageHandler(docId, workerId, worker.port);
15653 const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
15654 task._transport = transport;
15655 messageHandler.send("Ready", null);
15656 });
15657 }).catch(task._capability.reject);
15658 return task;
15659 }
15660 function getUrlProp(val) {
15661 if (val instanceof URL) {
15662 return val.href;
15663 }
15664 try {
15665 return new URL(val, window.location).href;
15666 } catch {
15667 if (isNodeJS && typeof val === "string") {
15668 return val;
15669 }
15670 }
15671 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
15672 }
15673 function getDataProp(val) {
15674 if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
15675 throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
15676 }
15677 if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
15678 return val;
15679 }
15680 if (typeof val === "string") {
15681 return stringToBytes(val);
15682 }
15683 if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
15684 return new Uint8Array(val);
15685 }
15686 throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
15687 }
15688 function isRefProxy(ref) {
15689 return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0;
15690 }
15691 class PDFDocumentLoadingTask {
15692 static #docId = 0;
15693 constructor() {
15694 this._capability = Promise.withResolvers();
15695 this._transport = null;
15696 this._worker = null;
15697 this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
15698 this.destroyed = false;
15699 this.onPassword = null;
15700 this.onProgress = null;
15701 }
15702 get promise() {
15703 return this._capability.promise;
15704 }
15705 async destroy() {
15706 this.destroyed = true;
15707 try {
15708 if (this._worker?.port) {
15709 this._worker._pendingDestroy = true;
15710 }
15711 await this._transport?.destroy();
15712 } catch (ex) {
15713 if (this._worker?.port) {
15714 delete this._worker._pendingDestroy;
15715 }
15716 throw ex;
15717 }
15718 this._transport = null;
15719 if (this._worker) {
15720 this._worker.destroy();
15721 this._worker = null;
15722 }
15723 }
15724 }
15725 class PDFDataRangeTransport {
15726 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
15727 this.length = length;
15728 this.initialData = initialData;
15729 this.progressiveDone = progressiveDone;
15730 this.contentDispositionFilename = contentDispositionFilename;
15731 this._rangeListeners = [];
15732 this._progressListeners = [];
15733 this._progressiveReadListeners = [];
15734 this._progressiveDoneListeners = [];
15735 this._readyCapability = Promise.withResolvers();
15736 }
15737 addRangeListener(listener) {
15738 this._rangeListeners.push(listener);
15739 }
15740 addProgressListener(listener) {
15741 this._progressListeners.push(listener);
15742 }
15743 addProgressiveReadListener(listener) {
15744 this._progressiveReadListeners.push(listener);
15745 }
15746 addProgressiveDoneListener(listener) {
15747 this._progressiveDoneListeners.push(listener);
15748 }
15749 onDataRange(begin, chunk) {
15750 for (const listener of this._rangeListeners) {
15751 listener(begin, chunk);
15752 }
15753 }
15754 onDataProgress(loaded, total) {
15755 this._readyCapability.promise.then(() => {
15756 for (const listener of this._progressListeners) {
15757 listener(loaded, total);
15758 }
15759 });
15760 }
15761 onDataProgressiveRead(chunk) {
15762 this._readyCapability.promise.then(() => {
15763 for (const listener of this._progressiveReadListeners) {
15764 listener(chunk);
15765 }
15766 });
15767 }
15768 onDataProgressiveDone() {
15769 this._readyCapability.promise.then(() => {
15770 for (const listener of this._progressiveDoneListeners) {
15771 listener();
15772 }
15773 });
15774 }
15775 transportReady() {
15776 this._readyCapability.resolve();
15777 }
15778 requestDataRange(begin, end) {
15779 unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
15780 }
15781 abort() {}
15782 }
15783 class PDFDocumentProxy {
15784 constructor(pdfInfo, transport) {
15785 this._pdfInfo = pdfInfo;
15786 this._transport = transport;
15787 }
15788 get annotationStorage() {
15789 return this._transport.annotationStorage;
15790 }
15791 get filterFactory() {
15792 return this._transport.filterFactory;
15793 }
15794 get numPages() {
15795 return this._pdfInfo.numPages;
15796 }
15797 get fingerprints() {
15798 return this._pdfInfo.fingerprints;
15799 }
15800 get isPureXfa() {
15801 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
15802 }
15803 get allXfaHtml() {
15804 return this._transport._htmlForXfa;
15805 }
15806 getPage(pageNumber) {
15807 return this._transport.getPage(pageNumber);
15808 }
15809 getPageIndex(ref) {
15810 return this._transport.getPageIndex(ref);
15811 }
15812 getDestinations() {
15813 return this._transport.getDestinations();
15814 }
15815 getDestination(id) {
15816 return this._transport.getDestination(id);
15817 }
15818 getPageLabels() {
15819 return this._transport.getPageLabels();
15820 }
15821 getPageLayout() {
15822 return this._transport.getPageLayout();
15823 }
15824 getPageMode() {
15825 return this._transport.getPageMode();
15826 }
15827 getViewerPreferences() {
15828 return this._transport.getViewerPreferences();
15829 }
15830 getOpenAction() {
15831 return this._transport.getOpenAction();
15832 }
15833 getAttachments() {
15834 return this._transport.getAttachments();
15835 }
15836 getJSActions() {
15837 return this._transport.getDocJSActions();
15838 }
15839 getOutline() {
15840 return this._transport.getOutline();
15841 }
15842 getOptionalContentConfig({
15843 intent = "display"
15844 } = {}) {
15845 const {
15846 renderingIntent
15847 } = this._transport.getRenderingIntent(intent);
15848 return this._transport.getOptionalContentConfig(renderingIntent);
15849 }
15850 getPermissions() {
15851 return this._transport.getPermissions();
15852 }
15853 getMetadata() {
15854 return this._transport.getMetadata();
15855 }
15856 getMarkInfo() {
15857 return this._transport.getMarkInfo();
15858 }
15859 getData() {
15860 return this._transport.getData();
15861 }
15862 saveDocument() {
15863 return this._transport.saveDocument();
15864 }
15865 getDownloadInfo() {
15866 return this._transport.downloadInfoCapability.promise;
15867 }
15868 cleanup(keepLoadedFonts = false) {
15869 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
15870 }
15871 destroy() {
15872 return this.loadingTask.destroy();
15873 }
15874 cachedPageNumber(ref) {
15875 return this._transport.cachedPageNumber(ref);
15876 }
15877 get loadingParams() {
15878 return this._transport.loadingParams;
15879 }
15880 get loadingTask() {
15881 return this._transport.loadingTask;
15882 }
15883 getFieldObjects() {
15884 return this._transport.getFieldObjects();
15885 }
15886 hasJSActions() {
15887 return this._transport.hasJSActions();
15888 }
15889 getCalculationOrderIds() {
15890 return this._transport.getCalculationOrderIds();
15891 }
15892 }
15893 class PDFPageProxy {
15894 #delayedCleanupTimeout = null;
15895 #pendingCleanup = false;
15896 constructor(pageIndex, pageInfo, transport, pdfBug = false) {
15897 this._pageIndex = pageIndex;
15898 this._pageInfo = pageInfo;
15899 this._transport = transport;
15900 this._stats = pdfBug ? new StatTimer() : null;
15901 this._pdfBug = pdfBug;
15902 this.commonObjs = transport.commonObjs;
15903 this.objs = new PDFObjects();
15904 this._maybeCleanupAfterRender = false;
15905 this._intentStates = new Map();
15906 this.destroyed = false;
15907 }
15908 get pageNumber() {
15909 return this._pageIndex + 1;
15910 }
15911 get rotate() {
15912 return this._pageInfo.rotate;
15913 }
15914 get ref() {
15915 return this._pageInfo.ref;
15916 }
15917 get userUnit() {
15918 return this._pageInfo.userUnit;
15919 }
15920 get view() {
15921 return this._pageInfo.view;
15922 }
15923 getViewport({
15924 scale,
15925 rotation = this.rotate,
15926 offsetX = 0,
15927 offsetY = 0,
15928 dontFlip = false
15929 } = {}) {
15930 return new PageViewport({
15931 viewBox: this.view,
15932 scale,
15933 rotation,
15934 offsetX,
15935 offsetY,
15936 dontFlip
15937 });
15938 }
15939 getAnnotations({
15940 intent = "display"
15941 } = {}) {
15942 const {
15943 renderingIntent
15944 } = this._transport.getRenderingIntent(intent);
15945 return this._transport.getAnnotations(this._pageIndex, renderingIntent);
15946 }
15947 getJSActions() {
15948 return this._transport.getPageJSActions(this._pageIndex);
15949 }
15950 get filterFactory() {
15951 return this._transport.filterFactory;
15952 }
15953 get isPureXfa() {
15954 return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
15955 }
15956 async getXfa() {
15957 return this._transport._htmlForXfa?.children[this._pageIndex] || null;
15958 }
15959 render({
15960 canvasContext,
15961 viewport,
15962 intent = "display",
15963 annotationMode = AnnotationMode.ENABLE,
15964 transform = null,
15965 background = null,
15966 optionalContentConfigPromise = null,
15967 annotationCanvasMap = null,
15968 pageColors = null,
15969 printAnnotationStorage = null
15970 }) {
15971 this._stats?.time("Overall");
15972 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
15973 const {
15974 renderingIntent,
15975 cacheKey
15976 } = intentArgs;
15977 this.#pendingCleanup = false;
15978 this.#abortDelayedCleanup();
15979 optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
15980 let intentState = this._intentStates.get(cacheKey);
15981 if (!intentState) {
15982 intentState = Object.create(null);
15983 this._intentStates.set(cacheKey, intentState);
15984 }
15985 if (intentState.streamReaderCancelTimeout) {
15986 clearTimeout(intentState.streamReaderCancelTimeout);
15987 intentState.streamReaderCancelTimeout = null;
15988 }
15989 const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
15990 if (!intentState.displayReadyCapability) {
15991 intentState.displayReadyCapability = Promise.withResolvers();
15992 intentState.operatorList = {
15993 fnArray: [],
15994 argsArray: [],
15995 lastChunk: false,
15996 separateAnnots: null
15997 };
15998 this._stats?.time("Page Request");
15999 this._pumpOperatorList(intentArgs);
16000 }
16001 const complete = error => {
16002 intentState.renderTasks.delete(internalRenderTask);
16003 if (this._maybeCleanupAfterRender || intentPrint) {
16004 this.#pendingCleanup = true;
16005 }
16006 this.#tryCleanup(!intentPrint);
16007 if (error) {
16008 internalRenderTask.capability.reject(error);
16009 this._abortOperatorList({
16010 intentState,
16011 reason: error instanceof Error ? error : new Error(error)
16012 });
16013 } else {
16014 internalRenderTask.capability.resolve();
16015 }
16016 if (this._stats) {
16017 this._stats.timeEnd("Rendering");
16018 this._stats.timeEnd("Overall");
16019 if (globalThis.Stats?.enabled) {
16020 globalThis.Stats.add(this.pageNumber, this._stats);
16021 }
16022 }
16023 };
16024 const internalRenderTask = new InternalRenderTask({
16025 callback: complete,
16026 params: {
16027 canvasContext,
16028 viewport,
16029 transform,
16030 background
16031 },
16032 objs: this.objs,
16033 commonObjs: this.commonObjs,
16034 annotationCanvasMap,
16035 operatorList: intentState.operatorList,
16036 pageIndex: this._pageIndex,
16037 canvasFactory: this._transport.canvasFactory,
16038 filterFactory: this._transport.filterFactory,
16039 useRequestAnimationFrame: !intentPrint,
16040 pdfBug: this._pdfBug,
16041 pageColors
16042 });
16043 (intentState.renderTasks ||= new Set()).add(internalRenderTask);
16044 const renderTask = internalRenderTask.task;
16045 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
16046 if (this.destroyed) {
16047 complete();
16048 return;
16049 }
16050 this._stats?.time("Rendering");
16051 if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
16052 throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
16053 }
16054 internalRenderTask.initializeGraphics({
16055 transparency,
16056 optionalContentConfig
16057 });
16058 internalRenderTask.operatorListChanged();
16059 }).catch(complete);
16060 return renderTask;
16061 }
16062 getOperatorList({
16063 intent = "display",
16064 annotationMode = AnnotationMode.ENABLE,
16065 printAnnotationStorage = null
16066 } = {}) {
16067 function operatorListChanged() {
16068 if (intentState.operatorList.lastChunk) {
16069 intentState.opListReadCapability.resolve(intentState.operatorList);
16070 intentState.renderTasks.delete(opListTask);
16071 }
16072 }
16073 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
16074 let intentState = this._intentStates.get(intentArgs.cacheKey);
16075 if (!intentState) {
16076 intentState = Object.create(null);
16077 this._intentStates.set(intentArgs.cacheKey, intentState);
16078 }
16079 let opListTask;
16080 if (!intentState.opListReadCapability) {
16081 opListTask = Object.create(null);
16082 opListTask.operatorListChanged = operatorListChanged;
16083 intentState.opListReadCapability = Promise.withResolvers();
16084 (intentState.renderTasks ||= new Set()).add(opListTask);
16085 intentState.operatorList = {
16086 fnArray: [],
16087 argsArray: [],
16088 lastChunk: false,
16089 separateAnnots: null
16090 };
16091 this._stats?.time("Page Request");
16092 this._pumpOperatorList(intentArgs);
16093 }
16094 return intentState.opListReadCapability.promise;
16095 }
16096 streamTextContent({
16097 includeMarkedContent = false,
16098 disableNormalization = false
16099 } = {}) {
16100 const TEXT_CONTENT_CHUNK_SIZE = 100;
16101 return this._transport.messageHandler.sendWithStream("GetTextContent", {
16102 pageIndex: this._pageIndex,
16103 includeMarkedContent: includeMarkedContent === true,
16104 disableNormalization: disableNormalization === true
16105 }, {
16106 highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
16107 size(textContent) {
16108 return textContent.items.length;
16109 }
16110 });
16111 }
16112 getTextContent(params = {}) {
16113 if (this._transport._htmlForXfa) {
16114 return this.getXfa().then(xfa => XfaText.textContent(xfa));
16115 }
16116 const readableStream = this.streamTextContent(params);
16117 return new Promise(function (resolve, reject) {
16118 function pump() {
16119 reader.read().then(function ({
16120 value,
16121 done
16122 }) {
16123 if (done) {
16124 resolve(textContent);
16125 return;
16126 }
16127 textContent.lang ??= value.lang;
16128 Object.assign(textContent.styles, value.styles);
16129 textContent.items.push(...value.items);
16130 pump();
16131 }, reject);
16132 }
16133 const reader = readableStream.getReader();
16134 const textContent = {
16135 items: [],
16136 styles: Object.create(null),
16137 lang: null
16138 };
16139 pump();
16140 });
16141 }
16142 getStructTree() {
16143 return this._transport.getStructTree(this._pageIndex);
16144 }
16145 _destroy() {
16146 this.destroyed = true;
16147 const waitOn = [];
16148 for (const intentState of this._intentStates.values()) {
16149 this._abortOperatorList({
16150 intentState,
16151 reason: new Error("Page was destroyed."),
16152 force: true
16153 });
16154 if (intentState.opListReadCapability) {
16155 continue;
16156 }
16157 for (const internalRenderTask of intentState.renderTasks) {
16158 waitOn.push(internalRenderTask.completed);
16159 internalRenderTask.cancel();
16160 }
16161 }
16162 this.objs.clear();
16163 this.#pendingCleanup = false;
16164 this.#abortDelayedCleanup();
16165 return Promise.all(waitOn);
16166 }
16167 cleanup(resetStats = false) {
16168 this.#pendingCleanup = true;
16169 const success = this.#tryCleanup(false);
16170 if (resetStats && success) {
16171 this._stats &&= new StatTimer();
16172 }
16173 return success;
16174 }
16175 #tryCleanup(delayed = false) {
16176 this.#abortDelayedCleanup();
16177 if (!this.#pendingCleanup || this.destroyed) {
16178 return false;
16179 }
16180 if (delayed) {
16181 this.#delayedCleanupTimeout = setTimeout(() => {
16182 this.#delayedCleanupTimeout = null;
16183 this.#tryCleanup(false);
16184 }, DELAYED_CLEANUP_TIMEOUT);
16185 return false;
16186 }
16187 for (const {
16188 renderTasks,
16189 operatorList
16190 } of this._intentStates.values()) {
16191 if (renderTasks.size > 0 || !operatorList.lastChunk) {
16192 return false;
16193 }
16194 }
16195 this._intentStates.clear();
16196 this.objs.clear();
16197 this.#pendingCleanup = false;
16198 return true;
16199 }
16200 #abortDelayedCleanup() {
16201 if (this.#delayedCleanupTimeout) {
16202 clearTimeout(this.#delayedCleanupTimeout);
16203 this.#delayedCleanupTimeout = null;
16204 }
16205 }
16206 _startRenderPage(transparency, cacheKey) {
16207 const intentState = this._intentStates.get(cacheKey);
16208 if (!intentState) {
16209 return;
16210 }
16211 this._stats?.timeEnd("Page Request");
16212 intentState.displayReadyCapability?.resolve(transparency);
16213 }
16214 _renderPageChunk(operatorListChunk, intentState) {
16215 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
16216 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
16217 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
16218 }
16219 intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
16220 intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
16221 for (const internalRenderTask of intentState.renderTasks) {
16222 internalRenderTask.operatorListChanged();
16223 }
16224 if (operatorListChunk.lastChunk) {
16225 this.#tryCleanup(true);
16226 }
16227 }
16228 _pumpOperatorList({
16229 renderingIntent,
16230 cacheKey,
16231 annotationStorageSerializable
16232 }) {
16233 const {
16234 map,
16235 transfer
16236 } = annotationStorageSerializable;
16237 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
16238 pageIndex: this._pageIndex,
16239 intent: renderingIntent,
16240 cacheKey,
16241 annotationStorage: map
16242 }, transfer);
16243 const reader = readableStream.getReader();
16244 const intentState = this._intentStates.get(cacheKey);
16245 intentState.streamReader = reader;
16246 const pump = () => {
16247 reader.read().then(({
16248 value,
16249 done
16250 }) => {
16251 if (done) {
16252 intentState.streamReader = null;
16253 return;
16254 }
16255 if (this._transport.destroyed) {
16256 return;
16257 }
16258 this._renderPageChunk(value, intentState);
16259 pump();
16260 }, reason => {
16261 intentState.streamReader = null;
16262 if (this._transport.destroyed) {
16263 return;
16264 }
16265 if (intentState.operatorList) {
16266 intentState.operatorList.lastChunk = true;
16267 for (const internalRenderTask of intentState.renderTasks) {
16268 internalRenderTask.operatorListChanged();
16269 }
16270 this.#tryCleanup(true);
16271 }
16272 if (intentState.displayReadyCapability) {
16273 intentState.displayReadyCapability.reject(reason);
16274 } else if (intentState.opListReadCapability) {
16275 intentState.opListReadCapability.reject(reason);
16276 } else {
16277 throw reason;
16278 }
16279 });
16280 };
16281 pump();
16282 }
16283 _abortOperatorList({
16284 intentState,
16285 reason,
16286 force = false
16287 }) {
16288 if (!intentState.streamReader) {
16289 return;
16290 }
16291 if (intentState.streamReaderCancelTimeout) {
16292 clearTimeout(intentState.streamReaderCancelTimeout);
16293 intentState.streamReaderCancelTimeout = null;
16294 }
16295 if (!force) {
16296 if (intentState.renderTasks.size > 0) {
16297 return;
16298 }
16299 if (reason instanceof RenderingCancelledException) {
16300 let delay = RENDERING_CANCELLED_TIMEOUT;
16301 if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
16302 delay += reason.extraDelay;
16303 }
16304 intentState.streamReaderCancelTimeout = setTimeout(() => {
16305 intentState.streamReaderCancelTimeout = null;
16306 this._abortOperatorList({
16307 intentState,
16308 reason,
16309 force: true
16310 });
16311 }, delay);
16312 return;
16313 }
16314 }
16315 intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
16316 intentState.streamReader = null;
16317 if (this._transport.destroyed) {
16318 return;
16319 }
16320 for (const [curCacheKey, curIntentState] of this._intentStates) {
16321 if (curIntentState === intentState) {
16322 this._intentStates.delete(curCacheKey);
16323 break;
16324 }
16325 }
16326 this.cleanup();
16327 }
16328 get stats() {
16329 return this._stats;
16330 }
16331 }
16332 class LoopbackPort {
16333 #listeners = new Set();
16334 #deferred = Promise.resolve();
16335 postMessage(obj, transfer) {
16336 const event = {
16337 data: structuredClone(obj, transfer ? {
16338 transfer
16339 } : null)
16340 };
16341 this.#deferred.then(() => {
16342 for (const listener of this.#listeners) {
16343 listener.call(this, event);
16344 }
16345 });
16346 }
16347 addEventListener(name, listener) {
16348 this.#listeners.add(listener);
16349 }
16350 removeEventListener(name, listener) {
16351 this.#listeners.delete(listener);
16352 }
16353 terminate() {
16354 this.#listeners.clear();
16355 }
16356 }
16357 const PDFWorkerUtil = {
16358 isWorkerDisabled: false,
16359 fakeWorkerId: 0
16360 };
16361 {
16362 if (isNodeJS) {
16363 PDFWorkerUtil.isWorkerDisabled = true;
16364 GlobalWorkerOptions.workerSrc ||= "./pdf.worker.js";
16365 }
16366 PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
16367 let base;
16368 try {
16369 base = new URL(baseUrl);
16370 if (!base.origin || base.origin === "null") {
16371 return false;
16372 }
16373 } catch {
16374 return false;
16375 }
16376 const other = new URL(otherUrl, base);
16377 return base.origin === other.origin;
16378 };
16379 PDFWorkerUtil.createCDNWrapper = function (url) {
16380 const wrapper = `await import("${url}");`;
16381 return URL.createObjectURL(new Blob([wrapper], {
16382 type: "text/javascript"
16383 }));
16384 };
16385 }
16386 class PDFWorker {
16387 static #workerPorts;
16388 constructor({
16389 name = null,
16390 port = null,
16391 verbosity = getVerbosityLevel()
16392 } = {}) {
16393 this.name = name;
16394 this.destroyed = false;
16395 this.verbosity = verbosity;
16396 this._readyCapability = Promise.withResolvers();
16397 this._port = null;
16398 this._webWorker = null;
16399 this._messageHandler = null;
16400 if (port) {
16401 if (PDFWorker.#workerPorts?.has(port)) {
16402 throw new Error("Cannot use more than one PDFWorker per port.");
16403 }
16404 (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
16405 this._initializeFromPort(port);
16406 return;
16407 }
16408 this._initialize();
16409 }
16410 get promise() {
16411 if (isNodeJS) {
16412 return Promise.all([NodePackages.promise, this._readyCapability.promise]);
16413 }
16414 return this._readyCapability.promise;
16415 }
16416 get port() {
16417 return this._port;
16418 }
16419 get messageHandler() {
16420 return this._messageHandler;
16421 }
16422 _initializeFromPort(port) {
16423 this._port = port;
16424 this._messageHandler = new MessageHandler("main", "worker", port);
16425 this._messageHandler.on("ready", function () {});
16426 this._readyCapability.resolve();
16427 this._messageHandler.send("configure", {
16428 verbosity: this.verbosity
16429 });
16430 }
16431 _initialize() {
16432 if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker.#mainThreadWorkerMessageHandler) {
16433 let {
16434 workerSrc
16435 } = PDFWorker;
16436 try {
16437 if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
16438 workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
16439 }
16440 const worker = new Worker(workerSrc, {
16441 type: "module"
16442 });
16443 const messageHandler = new MessageHandler("main", "worker", worker);
16444 const terminateEarly = () => {
16445 worker.removeEventListener("error", onWorkerError);
16446 messageHandler.destroy();
16447 worker.terminate();
16448 if (this.destroyed) {
16449 this._readyCapability.reject(new Error("Worker was destroyed"));
16450 } else {
16451 this._setupFakeWorker();
16452 }
16453 };
16454 const onWorkerError = () => {
16455 if (!this._webWorker) {
16456 terminateEarly();
16457 }
16458 };
16459 worker.addEventListener("error", onWorkerError);
16460 messageHandler.on("test", data => {
16461 worker.removeEventListener("error", onWorkerError);
16462 if (this.destroyed) {
16463 terminateEarly();
16464 return;
16465 }
16466 if (data) {
16467 this._messageHandler = messageHandler;
16468 this._port = worker;
16469 this._webWorker = worker;
16470 this._readyCapability.resolve();
16471 messageHandler.send("configure", {
16472 verbosity: this.verbosity
16473 });
16474 } else {
16475 this._setupFakeWorker();
16476 messageHandler.destroy();
16477 worker.terminate();
16478 }
16479 });
16480 messageHandler.on("ready", data => {
16481 worker.removeEventListener("error", onWorkerError);
16482 if (this.destroyed) {
16483 terminateEarly();
16484 return;
16485 }
16486 try {
16487 sendTest();
16488 } catch {
16489 this._setupFakeWorker();
16490 }
16491 });
16492 const sendTest = () => {
16493 const testObj = new Uint8Array();
16494 messageHandler.send("test", testObj, [testObj.buffer]);
16495 };
16496 sendTest();
16497 return;
16498 } catch {
16499 info("The worker has been disabled.");
16500 }
16501 }
16502 this._setupFakeWorker();
16503 }
16504 _setupFakeWorker() {
16505 if (!PDFWorkerUtil.isWorkerDisabled) {
16506 warn("Setting up fake worker.");
16507 PDFWorkerUtil.isWorkerDisabled = true;
16508 }
16509 PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
16510 if (this.destroyed) {
16511 this._readyCapability.reject(new Error("Worker was destroyed"));
16512 return;
16513 }
16514 const port = new LoopbackPort();
16515 this._port = port;
16516 const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
16517 const workerHandler = new MessageHandler(id + "_worker", id, port);
16518 WorkerMessageHandler.setup(workerHandler, port);
16519 const messageHandler = new MessageHandler(id, id + "_worker", port);
16520 this._messageHandler = messageHandler;
16521 this._readyCapability.resolve();
16522 messageHandler.send("configure", {
16523 verbosity: this.verbosity
16524 });
16525 }).catch(reason => {
16526 this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
16527 });
16528 }
16529 destroy() {
16530 this.destroyed = true;
16531 if (this._webWorker) {
16532 this._webWorker.terminate();
16533 this._webWorker = null;
16534 }
16535 PDFWorker.#workerPorts?.delete(this._port);
16536 this._port = null;
16537 if (this._messageHandler) {
16538 this._messageHandler.destroy();
16539 this._messageHandler = null;
16540 }
16541 }
16542 static fromPort(params) {
16543 if (!params?.port) {
16544 throw new Error("PDFWorker.fromPort - invalid method signature.");
16545 }
16546 const cachedPort = this.#workerPorts?.get(params.port);
16547 if (cachedPort) {
16548 if (cachedPort._pendingDestroy) {
16549 throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
16550 }
16551 return cachedPort;
16552 }
16553 return new PDFWorker(params);
16554 }
16555 static get workerSrc() {
16556 if (GlobalWorkerOptions.workerSrc) {
16557 return GlobalWorkerOptions.workerSrc;
16558 }
16559 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
16560 }
16561 static get #mainThreadWorkerMessageHandler() {
16562 try {
16563 return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
16564 } catch {
16565 return null;
16566 }
16567 }
16568 static get _setupFakeWorkerGlobal() {
16569 const loader = async () => {
16570 if (this.#mainThreadWorkerMessageHandler) {
16571 return this.#mainThreadWorkerMessageHandler;
16572 }
16573 const worker = await import( /*webpackIgnore: true*/this.workerSrc);
16574 return worker.WorkerMessageHandler;
16575 };
16576 return shadow(this, "_setupFakeWorkerGlobal", loader());
16577 }
16578 }
16579 class WorkerTransport {
16580 #methodPromises = new Map();
16581 #pageCache = new Map();
16582 #pagePromises = new Map();
16583 #pageRefCache = new Map();
16584 #passwordCapability = null;
16585 constructor(messageHandler, loadingTask, networkStream, params, factory) {
16586 this.messageHandler = messageHandler;
16587 this.loadingTask = loadingTask;
16588 this.commonObjs = new PDFObjects();
16589 this.fontLoader = new FontLoader({
16590 ownerDocument: params.ownerDocument,
16591 styleElement: params.styleElement
16592 });
16593 this.loadingParams = params.loadingParams;
16594 this._params = params;
16595 this.canvasFactory = factory.canvasFactory;
16596 this.filterFactory = factory.filterFactory;
16597 this.cMapReaderFactory = factory.cMapReaderFactory;
16598 this.standardFontDataFactory = factory.standardFontDataFactory;
16599 this.destroyed = false;
16600 this.destroyCapability = null;
16601 this._networkStream = networkStream;
16602 this._fullReader = null;
16603 this._lastProgress = null;
16604 this.downloadInfoCapability = Promise.withResolvers();
16605 this.setupMessageHandler();
16606 }
16607 #cacheSimpleMethod(name, data = null) {
16608 const cachedPromise = this.#methodPromises.get(name);
16609 if (cachedPromise) {
16610 return cachedPromise;
16611 }
16612 const promise = this.messageHandler.sendWithPromise(name, data);
16613 this.#methodPromises.set(name, promise);
16614 return promise;
16615 }
16616 get annotationStorage() {
16617 return shadow(this, "annotationStorage", new AnnotationStorage());
16618 }
16619 getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
16620 let renderingIntent = RenderingIntentFlag.DISPLAY;
16621 let annotationStorageSerializable = SerializableEmpty;
16622 switch (intent) {
16623 case "any":
16624 renderingIntent = RenderingIntentFlag.ANY;
16625 break;
16626 case "display":
16627 break;
16628 case "print":
16629 renderingIntent = RenderingIntentFlag.PRINT;
16630 break;
16631 default:
16632 warn(`getRenderingIntent - invalid intent: ${intent}`);
16633 }
16634 switch (annotationMode) {
16635 case AnnotationMode.DISABLE:
16636 renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
16637 break;
16638 case AnnotationMode.ENABLE:
16639 break;
16640 case AnnotationMode.ENABLE_FORMS:
16641 renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
16642 break;
16643 case AnnotationMode.ENABLE_STORAGE:
16644 renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
16645 const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
16646 annotationStorageSerializable = annotationStorage.serializable;
16647 break;
16648 default:
16649 warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
16650 }
16651 if (isOpList) {
16652 renderingIntent += RenderingIntentFlag.OPLIST;
16653 }
16654 return {
16655 renderingIntent,
16656 cacheKey: `${renderingIntent}_${annotationStorageSerializable.hash}`,
16657 annotationStorageSerializable
16658 };
16659 }
16660 destroy() {
16661 if (this.destroyCapability) {
16662 return this.destroyCapability.promise;
16663 }
16664 this.destroyed = true;
16665 this.destroyCapability = Promise.withResolvers();
16666 this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
16667 const waitOn = [];
16668 for (const page of this.#pageCache.values()) {
16669 waitOn.push(page._destroy());
16670 }
16671 this.#pageCache.clear();
16672 this.#pagePromises.clear();
16673 this.#pageRefCache.clear();
16674 if (this.hasOwnProperty("annotationStorage")) {
16675 this.annotationStorage.resetModified();
16676 }
16677 const terminated = this.messageHandler.sendWithPromise("Terminate", null);
16678 waitOn.push(terminated);
16679 Promise.all(waitOn).then(() => {
16680 this.commonObjs.clear();
16681 this.fontLoader.clear();
16682 this.#methodPromises.clear();
16683 this.filterFactory.destroy();
16684 TextLayer.cleanup();
16685 this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
16686 if (this.messageHandler) {
16687 this.messageHandler.destroy();
16688 this.messageHandler = null;
16689 }
16690 this.destroyCapability.resolve();
16691 }, this.destroyCapability.reject);
16692 return this.destroyCapability.promise;
16693 }
16694 setupMessageHandler() {
16695 const {
16696 messageHandler,
16697 loadingTask
16698 } = this;
16699 messageHandler.on("GetReader", (data, sink) => {
16700 assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
16701 this._fullReader = this._networkStream.getFullReader();
16702 this._fullReader.onProgress = evt => {
16703 this._lastProgress = {
16704 loaded: evt.loaded,
16705 total: evt.total
16706 };
16707 };
16708 sink.onPull = () => {
16709 this._fullReader.read().then(function ({
16710 value,
16711 done
16712 }) {
16713 if (done) {
16714 sink.close();
16715 return;
16716 }
16717 assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
16718 sink.enqueue(new Uint8Array(value), 1, [value]);
16719 }).catch(reason => {
16720 sink.error(reason);
16721 });
16722 };
16723 sink.onCancel = reason => {
16724 this._fullReader.cancel(reason);
16725 sink.ready.catch(readyReason => {
16726 if (this.destroyed) {
16727 return;
16728 }
16729 throw readyReason;
16730 });
16731 };
16732 });
16733 messageHandler.on("ReaderHeadersReady", data => {
16734 const headersCapability = Promise.withResolvers();
16735 const fullReader = this._fullReader;
16736 fullReader.headersReady.then(() => {
16737 if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
16738 if (this._lastProgress) {
16739 loadingTask.onProgress?.(this._lastProgress);
16740 }
16741 fullReader.onProgress = evt => {
16742 loadingTask.onProgress?.({
16743 loaded: evt.loaded,
16744 total: evt.total
16745 });
16746 };
16747 }
16748 headersCapability.resolve({
16749 isStreamingSupported: fullReader.isStreamingSupported,
16750 isRangeSupported: fullReader.isRangeSupported,
16751 contentLength: fullReader.contentLength
16752 });
16753 }, headersCapability.reject);
16754 return headersCapability.promise;
16755 });
16756 messageHandler.on("GetRangeReader", (data, sink) => {
16757 assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
16758 const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
16759 if (!rangeReader) {
16760 sink.close();
16761 return;
16762 }
16763 sink.onPull = () => {
16764 rangeReader.read().then(function ({
16765 value,
16766 done
16767 }) {
16768 if (done) {
16769 sink.close();
16770 return;
16771 }
16772 assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
16773 sink.enqueue(new Uint8Array(value), 1, [value]);
16774 }).catch(reason => {
16775 sink.error(reason);
16776 });
16777 };
16778 sink.onCancel = reason => {
16779 rangeReader.cancel(reason);
16780 sink.ready.catch(readyReason => {
16781 if (this.destroyed) {
16782 return;
16783 }
16784 throw readyReason;
16785 });
16786 };
16787 });
16788 messageHandler.on("GetDoc", ({
16789 pdfInfo
16790 }) => {
16791 this._numPages = pdfInfo.numPages;
16792 this._htmlForXfa = pdfInfo.htmlForXfa;
16793 delete pdfInfo.htmlForXfa;
16794 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
16795 });
16796 messageHandler.on("DocException", function (ex) {
16797 let reason;
16798 switch (ex.name) {
16799 case "PasswordException":
16800 reason = new PasswordException(ex.message, ex.code);
16801 break;
16802 case "InvalidPDFException":
16803 reason = new InvalidPDFException(ex.message);
16804 break;
16805 case "MissingPDFException":
16806 reason = new MissingPDFException(ex.message);
16807 break;
16808 case "UnexpectedResponseException":
16809 reason = new UnexpectedResponseException(ex.message, ex.status);
16810 break;
16811 case "UnknownErrorException":
16812 reason = new UnknownErrorException(ex.message, ex.details);
16813 break;
16814 default:
16815 unreachable("DocException - expected a valid Error.");
16816 }
16817 loadingTask._capability.reject(reason);
16818 });
16819 messageHandler.on("PasswordRequest", exception => {
16820 this.#passwordCapability = Promise.withResolvers();
16821 if (loadingTask.onPassword) {
16822 const updatePassword = password => {
16823 if (password instanceof Error) {
16824 this.#passwordCapability.reject(password);
16825 } else {
16826 this.#passwordCapability.resolve({
16827 password
16828 });
16829 }
16830 };
16831 try {
16832 loadingTask.onPassword(updatePassword, exception.code);
16833 } catch (ex) {
16834 this.#passwordCapability.reject(ex);
16835 }
16836 } else {
16837 this.#passwordCapability.reject(new PasswordException(exception.message, exception.code));
16838 }
16839 return this.#passwordCapability.promise;
16840 });
16841 messageHandler.on("DataLoaded", data => {
16842 loadingTask.onProgress?.({
16843 loaded: data.length,
16844 total: data.length
16845 });
16846 this.downloadInfoCapability.resolve(data);
16847 });
16848 messageHandler.on("StartRenderPage", data => {
16849 if (this.destroyed) {
16850 return;
16851 }
16852 const page = this.#pageCache.get(data.pageIndex);
16853 page._startRenderPage(data.transparency, data.cacheKey);
16854 });
16855 messageHandler.on("commonobj", ([id, type, exportedData]) => {
16856 if (this.destroyed) {
16857 return null;
16858 }
16859 if (this.commonObjs.has(id)) {
16860 return null;
16861 }
16862 switch (type) {
16863 case "Font":
16864 const {
16865 disableFontFace,
16866 fontExtraProperties,
16867 pdfBug
16868 } = this._params;
16869 if ("error" in exportedData) {
16870 const exportedError = exportedData.error;
16871 warn(`Error during font loading: ${exportedError}`);
16872 this.commonObjs.resolve(id, exportedError);
16873 break;
16874 }
16875 const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
16876 const font = new FontFaceObject(exportedData, {
16877 disableFontFace,
16878 inspectFont
16879 });
16880 this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
16881 id
16882 })).finally(() => {
16883 if (!fontExtraProperties && font.data) {
16884 font.data = null;
16885 }
16886 this.commonObjs.resolve(id, font);
16887 });
16888 break;
16889 case "CopyLocalImage":
16890 const {
16891 imageRef
16892 } = exportedData;
16893 assert(imageRef, "The imageRef must be defined.");
16894 for (const pageProxy of this.#pageCache.values()) {
16895 for (const [, data] of pageProxy.objs) {
16896 if (data?.ref !== imageRef) {
16897 continue;
16898 }
16899 if (!data.dataLen) {
16900 return null;
16901 }
16902 this.commonObjs.resolve(id, structuredClone(data));
16903 return data.dataLen;
16904 }
16905 }
16906 break;
16907 case "FontPath":
16908 case "Image":
16909 case "Pattern":
16910 this.commonObjs.resolve(id, exportedData);
16911 break;
16912 default:
16913 throw new Error(`Got unknown common object type ${type}`);
16914 }
16915 return null;
16916 });
16917 messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
16918 if (this.destroyed) {
16919 return;
16920 }
16921 const pageProxy = this.#pageCache.get(pageIndex);
16922 if (pageProxy.objs.has(id)) {
16923 return;
16924 }
16925 if (pageProxy._intentStates.size === 0) {
16926 imageData?.bitmap?.close();
16927 return;
16928 }
16929 switch (type) {
16930 case "Image":
16931 pageProxy.objs.resolve(id, imageData);
16932 if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) {
16933 pageProxy._maybeCleanupAfterRender = true;
16934 }
16935 break;
16936 case "Pattern":
16937 pageProxy.objs.resolve(id, imageData);
16938 break;
16939 default:
16940 throw new Error(`Got unknown object type ${type}`);
16941 }
16942 });
16943 messageHandler.on("DocProgress", data => {
16944 if (this.destroyed) {
16945 return;
16946 }
16947 loadingTask.onProgress?.({
16948 loaded: data.loaded,
16949 total: data.total
16950 });
16951 });
16952 messageHandler.on("FetchBuiltInCMap", data => {
16953 if (this.destroyed) {
16954 return Promise.reject(new Error("Worker was destroyed."));
16955 }
16956 if (!this.cMapReaderFactory) {
16957 return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
16958 }
16959 return this.cMapReaderFactory.fetch(data);
16960 });
16961 messageHandler.on("FetchStandardFontData", data => {
16962 if (this.destroyed) {
16963 return Promise.reject(new Error("Worker was destroyed."));
16964 }
16965 if (!this.standardFontDataFactory) {
16966 return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
16967 }
16968 return this.standardFontDataFactory.fetch(data);
16969 });
16970 }
16971 getData() {
16972 return this.messageHandler.sendWithPromise("GetData", null);
16973 }
16974 saveDocument() {
16975 if (this.annotationStorage.size <= 0) {
16976 warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
16977 }
16978 const {
16979 map,
16980 transfer
16981 } = this.annotationStorage.serializable;
16982 return this.messageHandler.sendWithPromise("SaveDocument", {
16983 isPureXfa: !!this._htmlForXfa,
16984 numPages: this._numPages,
16985 annotationStorage: map,
16986 filename: this._fullReader?.filename ?? null
16987 }, transfer).finally(() => {
16988 this.annotationStorage.resetModified();
16989 });
16990 }
16991 getPage(pageNumber) {
16992 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
16993 return Promise.reject(new Error("Invalid page request."));
16994 }
16995 const pageIndex = pageNumber - 1,
16996 cachedPromise = this.#pagePromises.get(pageIndex);
16997 if (cachedPromise) {
16998 return cachedPromise;
16999 }
17000 const promise = this.messageHandler.sendWithPromise("GetPage", {
17001 pageIndex
17002 }).then(pageInfo => {
17003 if (this.destroyed) {
17004 throw new Error("Transport destroyed");
17005 }
17006 if (pageInfo.refStr) {
17007 this.#pageRefCache.set(pageInfo.refStr, pageNumber);
17008 }
17009 const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
17010 this.#pageCache.set(pageIndex, page);
17011 return page;
17012 });
17013 this.#pagePromises.set(pageIndex, promise);
17014 return promise;
17015 }
17016 getPageIndex(ref) {
17017 if (!isRefProxy(ref)) {
17018 return Promise.reject(new Error("Invalid pageIndex request."));
17019 }
17020 return this.messageHandler.sendWithPromise("GetPageIndex", {
17021 num: ref.num,
17022 gen: ref.gen
17023 });
17024 }
17025 getAnnotations(pageIndex, intent) {
17026 return this.messageHandler.sendWithPromise("GetAnnotations", {
17027 pageIndex,
17028 intent
17029 });
17030 }
17031 getFieldObjects() {
17032 return this.#cacheSimpleMethod("GetFieldObjects");
17033 }
17034 hasJSActions() {
17035 return this.#cacheSimpleMethod("HasJSActions");
17036 }
17037 getCalculationOrderIds() {
17038 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
17039 }
17040 getDestinations() {
17041 return this.messageHandler.sendWithPromise("GetDestinations", null);
17042 }
17043 getDestination(id) {
17044 if (typeof id !== "string") {
17045 return Promise.reject(new Error("Invalid destination request."));
17046 }
17047 return this.messageHandler.sendWithPromise("GetDestination", {
17048 id
17049 });
17050 }
17051 getPageLabels() {
17052 return this.messageHandler.sendWithPromise("GetPageLabels", null);
17053 }
17054 getPageLayout() {
17055 return this.messageHandler.sendWithPromise("GetPageLayout", null);
17056 }
17057 getPageMode() {
17058 return this.messageHandler.sendWithPromise("GetPageMode", null);
17059 }
17060 getViewerPreferences() {
17061 return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
17062 }
17063 getOpenAction() {
17064 return this.messageHandler.sendWithPromise("GetOpenAction", null);
17065 }
17066 getAttachments() {
17067 return this.messageHandler.sendWithPromise("GetAttachments", null);
17068 }
17069 getDocJSActions() {
17070 return this.#cacheSimpleMethod("GetDocJSActions");
17071 }
17072 getPageJSActions(pageIndex) {
17073 return this.messageHandler.sendWithPromise("GetPageJSActions", {
17074 pageIndex
17075 });
17076 }
17077 getStructTree(pageIndex) {
17078 return this.messageHandler.sendWithPromise("GetStructTree", {
17079 pageIndex
17080 });
17081 }
17082 getOutline() {
17083 return this.messageHandler.sendWithPromise("GetOutline", null);
17084 }
17085 getOptionalContentConfig(renderingIntent) {
17086 return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
17087 }
17088 getPermissions() {
17089 return this.messageHandler.sendWithPromise("GetPermissions", null);
17090 }
17091 getMetadata() {
17092 const name = "GetMetadata",
17093 cachedPromise = this.#methodPromises.get(name);
17094 if (cachedPromise) {
17095 return cachedPromise;
17096 }
17097 const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
17098 info: results[0],
17099 metadata: results[1] ? new Metadata(results[1]) : null,
17100 contentDispositionFilename: this._fullReader?.filename ?? null,
17101 contentLength: this._fullReader?.contentLength ?? null
17102 }));
17103 this.#methodPromises.set(name, promise);
17104 return promise;
17105 }
17106 getMarkInfo() {
17107 return this.messageHandler.sendWithPromise("GetMarkInfo", null);
17108 }
17109 async startCleanup(keepLoadedFonts = false) {
17110 if (this.destroyed) {
17111 return;
17112 }
17113 await this.messageHandler.sendWithPromise("Cleanup", null);
17114 for (const page of this.#pageCache.values()) {
17115 const cleanupSuccessful = page.cleanup();
17116 if (!cleanupSuccessful) {
17117 throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
17118 }
17119 }
17120 this.commonObjs.clear();
17121 if (!keepLoadedFonts) {
17122 this.fontLoader.clear();
17123 }
17124 this.#methodPromises.clear();
17125 this.filterFactory.destroy(true);
17126 TextLayer.cleanup();
17127 }
17128 cachedPageNumber(ref) {
17129 if (!isRefProxy(ref)) {
17130 return null;
17131 }
17132 const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
17133 return this.#pageRefCache.get(refStr) ?? null;
17134 }
17135 }
17136 const INITIAL_DATA = Symbol("INITIAL_DATA");
17137 class PDFObjects {
17138 #objs = Object.create(null);
17139 #ensureObj(objId) {
17140 return this.#objs[objId] ||= {
17141 ...Promise.withResolvers(),
17142 data: INITIAL_DATA
17143 };
17144 }
17145 get(objId, callback = null) {
17146 if (callback) {
17147 const obj = this.#ensureObj(objId);
17148 obj.promise.then(() => callback(obj.data));
17149 return null;
17150 }
17151 const obj = this.#objs[objId];
17152 if (!obj || obj.data === INITIAL_DATA) {
17153 throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
17154 }
17155 return obj.data;
17156 }
17157 has(objId) {
17158 const obj = this.#objs[objId];
17159 return !!obj && obj.data !== INITIAL_DATA;
17160 }
17161 resolve(objId, data = null) {
17162 const obj = this.#ensureObj(objId);
17163 obj.data = data;
17164 obj.resolve();
17165 }
17166 clear() {
17167 for (const objId in this.#objs) {
17168 const {
17169 data
17170 } = this.#objs[objId];
17171 data?.bitmap?.close();
17172 }
17173 this.#objs = Object.create(null);
17174 }
17175 *[Symbol.iterator]() {
17176 for (const objId in this.#objs) {
17177 const {
17178 data
17179 } = this.#objs[objId];
17180 if (data === INITIAL_DATA) {
17181 continue;
17182 }
17183 yield [objId, data];
17184 }
17185 }
17186 }
17187 class RenderTask {
17188 #internalRenderTask = null;
17189 constructor(internalRenderTask) {
17190 this.#internalRenderTask = internalRenderTask;
17191 this.onContinue = null;
17192 }
17193 get promise() {
17194 return this.#internalRenderTask.capability.promise;
17195 }
17196 cancel(extraDelay = 0) {
17197 this.#internalRenderTask.cancel(null, extraDelay);
17198 }
17199 get separateAnnots() {
17200 const {
17201 separateAnnots
17202 } = this.#internalRenderTask.operatorList;
17203 if (!separateAnnots) {
17204 return false;
17205 }
17206 const {
17207 annotationCanvasMap
17208 } = this.#internalRenderTask;
17209 return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
17210 }
17211 }
17212 class InternalRenderTask {
17213 static #canvasInUse = new WeakSet();
17214 constructor({
17215 callback,
17216 params,
17217 objs,
17218 commonObjs,
17219 annotationCanvasMap,
17220 operatorList,
17221 pageIndex,
17222 canvasFactory,
17223 filterFactory,
17224 useRequestAnimationFrame = false,
17225 pdfBug = false,
17226 pageColors = null
17227 }) {
17228 this.callback = callback;
17229 this.params = params;
17230 this.objs = objs;
17231 this.commonObjs = commonObjs;
17232 this.annotationCanvasMap = annotationCanvasMap;
17233 this.operatorListIdx = null;
17234 this.operatorList = operatorList;
17235 this._pageIndex = pageIndex;
17236 this.canvasFactory = canvasFactory;
17237 this.filterFactory = filterFactory;
17238 this._pdfBug = pdfBug;
17239 this.pageColors = pageColors;
17240 this.running = false;
17241 this.graphicsReadyCallback = null;
17242 this.graphicsReady = false;
17243 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
17244 this.cancelled = false;
17245 this.capability = Promise.withResolvers();
17246 this.task = new RenderTask(this);
17247 this._cancelBound = this.cancel.bind(this);
17248 this._continueBound = this._continue.bind(this);
17249 this._scheduleNextBound = this._scheduleNext.bind(this);
17250 this._nextBound = this._next.bind(this);
17251 this._canvas = params.canvasContext.canvas;
17252 }
17253 get completed() {
17254 return this.capability.promise.catch(function () {});
17255 }
17256 initializeGraphics({
17257 transparency = false,
17258 optionalContentConfig
17259 }) {
17260 if (this.cancelled) {
17261 return;
17262 }
17263 if (this._canvas) {
17264 if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
17265 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
17266 }
17267 InternalRenderTask.#canvasInUse.add(this._canvas);
17268 }
17269 if (this._pdfBug && globalThis.StepperManager?.enabled) {
17270 this.stepper = globalThis.StepperManager.create(this._pageIndex);
17271 this.stepper.init(this.operatorList);
17272 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
17273 }
17274 const {
17275 canvasContext,
17276 viewport,
17277 transform,
17278 background
17279 } = this.params;
17280 this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
17281 optionalContentConfig
17282 }, this.annotationCanvasMap, this.pageColors);
17283 this.gfx.beginDrawing({
17284 transform,
17285 viewport,
17286 transparency,
17287 background
17288 });
17289 this.operatorListIdx = 0;
17290 this.graphicsReady = true;
17291 this.graphicsReadyCallback?.();
17292 }
17293 cancel(error = null, extraDelay = 0) {
17294 this.running = false;
17295 this.cancelled = true;
17296 this.gfx?.endDrawing();
17297 InternalRenderTask.#canvasInUse.delete(this._canvas);
17298 this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
17299 }
17300 operatorListChanged() {
17301 if (!this.graphicsReady) {
17302 this.graphicsReadyCallback ||= this._continueBound;
17303 return;
17304 }
17305 this.stepper?.updateOperatorList(this.operatorList);
17306 if (this.running) {
17307 return;
17308 }
17309 this._continue();
17310 }
17311 _continue() {
17312 this.running = true;
17313 if (this.cancelled) {
17314 return;
17315 }
17316 if (this.task.onContinue) {
17317 this.task.onContinue(this._scheduleNextBound);
17318 } else {
17319 this._scheduleNext();
17320 }
17321 }
17322 _scheduleNext() {
17323 if (this._useRequestAnimationFrame) {
17324 window.requestAnimationFrame(() => {
17325 this._nextBound().catch(this._cancelBound);
17326 });
17327 } else {
17328 Promise.resolve().then(this._nextBound).catch(this._cancelBound);
17329 }
17330 }
17331 async _next() {
17332 if (this.cancelled) {
17333 return;
17334 }
17335 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
17336 if (this.operatorListIdx === this.operatorList.argsArray.length) {
17337 this.running = false;
17338 if (this.operatorList.lastChunk) {
17339 this.gfx.endDrawing();
17340 InternalRenderTask.#canvasInUse.delete(this._canvas);
17341 this.callback();
17342 }
17343 }
17344 }
17345 }
17346 const version = "4.3.136";
17347 const build = "0cec64437";
17348
17349 // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.flat-map.js
17350 var esnext_iterator_flat_map = __webpack_require__(670);
17351 ;// CONCATENATED MODULE: ./src/shared/scripting_utils.js
17352
17353 function makeColorComp(n) {
17354 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
17355 }
17356 function scaleAndClamp(x) {
17357 return Math.max(0, Math.min(255, 255 * x));
17358 }
17359 class ColorConverters {
17360 static CMYK_G([c, y, m, k]) {
17361 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
17362 }
17363 static G_CMYK([g]) {
17364 return ["CMYK", 0, 0, 0, 1 - g];
17365 }
17366 static G_RGB([g]) {
17367 return ["RGB", g, g, g];
17368 }
17369 static G_rgb([g]) {
17370 g = scaleAndClamp(g);
17371 return [g, g, g];
17372 }
17373 static G_HTML([g]) {
17374 const G = makeColorComp(g);
17375 return `#${G}${G}${G}`;
17376 }
17377 static RGB_G([r, g, b]) {
17378 return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
17379 }
17380 static RGB_rgb(color) {
17381 return color.map(scaleAndClamp);
17382 }
17383 static RGB_HTML(color) {
17384 return `#${color.map(makeColorComp).join("")}`;
17385 }
17386 static T_HTML() {
17387 return "#00000000";
17388 }
17389 static T_rgb() {
17390 return [null];
17391 }
17392 static CMYK_RGB([c, y, m, k]) {
17393 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
17394 }
17395 static CMYK_rgb([c, y, m, k]) {
17396 return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
17397 }
17398 static CMYK_HTML(components) {
17399 const rgb = this.CMYK_RGB(components).slice(1);
17400 return this.RGB_HTML(rgb);
17401 }
17402 static RGB_CMYK([r, g, b]) {
17403 const c = 1 - r;
17404 const m = 1 - g;
17405 const y = 1 - b;
17406 const k = Math.min(c, m, y);
17407 return ["CMYK", c, m, y, k];
17408 }
17409 }
17410
17411 ;// CONCATENATED MODULE: ./src/display/xfa_layer.js
17412
17413
17414 class XfaLayer {
17415 static setupStorage(html, id, element, storage, intent) {
17416 const storedData = storage.getValue(id, {
17417 value: null
17418 });
17419 switch (element.name) {
17420 case "textarea":
17421 if (storedData.value !== null) {
17422 html.textContent = storedData.value;
17423 }
17424 if (intent === "print") {
17425 break;
17426 }
17427 html.addEventListener("input", event => {
17428 storage.setValue(id, {
17429 value: event.target.value
17430 });
17431 });
17432 break;
17433 case "input":
17434 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
17435 if (storedData.value === element.attributes.xfaOn) {
17436 html.setAttribute("checked", true);
17437 } else if (storedData.value === element.attributes.xfaOff) {
17438 html.removeAttribute("checked");
17439 }
17440 if (intent === "print") {
17441 break;
17442 }
17443 html.addEventListener("change", event => {
17444 storage.setValue(id, {
17445 value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
17446 });
17447 });
17448 } else {
17449 if (storedData.value !== null) {
17450 html.setAttribute("value", storedData.value);
17451 }
17452 if (intent === "print") {
17453 break;
17454 }
17455 html.addEventListener("input", event => {
17456 storage.setValue(id, {
17457 value: event.target.value
17458 });
17459 });
17460 }
17461 break;
17462 case "select":
17463 if (storedData.value !== null) {
17464 html.setAttribute("value", storedData.value);
17465 for (const option of element.children) {
17466 if (option.attributes.value === storedData.value) {
17467 option.attributes.selected = true;
17468 } else if (option.attributes.hasOwnProperty("selected")) {
17469 delete option.attributes.selected;
17470 }
17471 }
17472 }
17473 html.addEventListener("input", event => {
17474 const options = event.target.options;
17475 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
17476 storage.setValue(id, {
17477 value
17478 });
17479 });
17480 break;
17481 }
17482 }
17483 static setAttributes({
17484 html,
17485 element,
17486 storage = null,
17487 intent,
17488 linkService
17489 }) {
17490 const {
17491 attributes
17492 } = element;
17493 const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
17494 if (attributes.type === "radio") {
17495 attributes.name = `${attributes.name}-${intent}`;
17496 }
17497 for (const [key, value] of Object.entries(attributes)) {
17498 if (value === null || value === undefined) {
17499 continue;
17500 }
17501 switch (key) {
17502 case "class":
17503 if (value.length) {
17504 html.setAttribute(key, value.join(" "));
17505 }
17506 break;
17507 case "dataId":
17508 break;
17509 case "id":
17510 html.setAttribute("data-element-id", value);
17511 break;
17512 case "style":
17513 Object.assign(html.style, value);
17514 break;
17515 case "textContent":
17516 html.textContent = value;
17517 break;
17518 default:
17519 if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
17520 html.setAttribute(key, value);
17521 }
17522 }
17523 }
17524 if (isHTMLAnchorElement) {
17525 linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
17526 }
17527 if (storage && attributes.dataId) {
17528 this.setupStorage(html, attributes.dataId, element, storage);
17529 }
17530 }
17531 static render(parameters) {
17532 const storage = parameters.annotationStorage;
17533 const linkService = parameters.linkService;
17534 const root = parameters.xfaHtml;
17535 const intent = parameters.intent || "display";
17536 const rootHtml = document.createElement(root.name);
17537 if (root.attributes) {
17538 this.setAttributes({
17539 html: rootHtml,
17540 element: root,
17541 intent,
17542 linkService
17543 });
17544 }
17545 const isNotForRichText = intent !== "richText";
17546 const rootDiv = parameters.div;
17547 rootDiv.append(rootHtml);
17548 if (parameters.viewport) {
17549 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
17550 rootDiv.style.transform = transform;
17551 }
17552 if (isNotForRichText) {
17553 rootDiv.setAttribute("class", "xfaLayer xfaFont");
17554 }
17555 const textDivs = [];
17556 if (root.children.length === 0) {
17557 if (root.value) {
17558 const node = document.createTextNode(root.value);
17559 rootHtml.append(node);
17560 if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
17561 textDivs.push(node);
17562 }
17563 }
17564 return {
17565 textDivs
17566 };
17567 }
17568 const stack = [[root, -1, rootHtml]];
17569 while (stack.length > 0) {
17570 const [parent, i, html] = stack.at(-1);
17571 if (i + 1 === parent.children.length) {
17572 stack.pop();
17573 continue;
17574 }
17575 const child = parent.children[++stack.at(-1)[1]];
17576 if (child === null) {
17577 continue;
17578 }
17579 const {
17580 name
17581 } = child;
17582 if (name === "#text") {
17583 const node = document.createTextNode(child.value);
17584 textDivs.push(node);
17585 html.append(node);
17586 continue;
17587 }
17588 const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
17589 html.append(childHtml);
17590 if (child.attributes) {
17591 this.setAttributes({
17592 html: childHtml,
17593 element: child,
17594 storage,
17595 intent,
17596 linkService
17597 });
17598 }
17599 if (child.children?.length > 0) {
17600 stack.push([child, -1, childHtml]);
17601 } else if (child.value) {
17602 const node = document.createTextNode(child.value);
17603 if (isNotForRichText && XfaText.shouldBuildText(name)) {
17604 textDivs.push(node);
17605 }
17606 childHtml.append(node);
17607 }
17608 }
17609 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
17610 el.setAttribute("readOnly", true);
17611 }
17612 return {
17613 textDivs
17614 };
17615 }
17616 static update(parameters) {
17617 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
17618 parameters.div.style.transform = transform;
17619 parameters.div.hidden = false;
17620 }
17621 }
17622
17623 ;// CONCATENATED MODULE: ./src/display/annotation_layer.js
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640 const DEFAULT_TAB_INDEX = 1000;
17641 const annotation_layer_DEFAULT_FONT_SIZE = 9;
17642 const GetElementsByNameSet = new WeakSet();
17643 function getRectDims(rect) {
17644 return {
17645 width: rect[2] - rect[0],
17646 height: rect[3] - rect[1]
17647 };
17648 }
17649 class AnnotationElementFactory {
17650 static create(parameters) {
17651 const subtype = parameters.data.annotationType;
17652 switch (subtype) {
17653 case AnnotationType.LINK:
17654 return new LinkAnnotationElement(parameters);
17655 case AnnotationType.TEXT:
17656 return new TextAnnotationElement(parameters);
17657 case AnnotationType.WIDGET:
17658 const fieldType = parameters.data.fieldType;
17659 switch (fieldType) {
17660 case "Tx":
17661 return new TextWidgetAnnotationElement(parameters);
17662 case "Btn":
17663 if (parameters.data.radioButton) {
17664 return new RadioButtonWidgetAnnotationElement(parameters);
17665 } else if (parameters.data.checkBox) {
17666 return new CheckboxWidgetAnnotationElement(parameters);
17667 }
17668 return new PushButtonWidgetAnnotationElement(parameters);
17669 case "Ch":
17670 return new ChoiceWidgetAnnotationElement(parameters);
17671 case "Sig":
17672 return new SignatureWidgetAnnotationElement(parameters);
17673 }
17674 return new WidgetAnnotationElement(parameters);
17675 case AnnotationType.POPUP:
17676 return new PopupAnnotationElement(parameters);
17677 case AnnotationType.FREETEXT:
17678 return new FreeTextAnnotationElement(parameters);
17679 case AnnotationType.LINE:
17680 return new LineAnnotationElement(parameters);
17681 case AnnotationType.SQUARE:
17682 return new SquareAnnotationElement(parameters);
17683 case AnnotationType.CIRCLE:
17684 return new CircleAnnotationElement(parameters);
17685 case AnnotationType.POLYLINE:
17686 return new PolylineAnnotationElement(parameters);
17687 case AnnotationType.CARET:
17688 return new CaretAnnotationElement(parameters);
17689 case AnnotationType.INK:
17690 return new InkAnnotationElement(parameters);
17691 case AnnotationType.POLYGON:
17692 return new PolygonAnnotationElement(parameters);
17693 case AnnotationType.HIGHLIGHT:
17694 return new HighlightAnnotationElement(parameters);
17695 case AnnotationType.UNDERLINE:
17696 return new UnderlineAnnotationElement(parameters);
17697 case AnnotationType.SQUIGGLY:
17698 return new SquigglyAnnotationElement(parameters);
17699 case AnnotationType.STRIKEOUT:
17700 return new StrikeOutAnnotationElement(parameters);
17701 case AnnotationType.STAMP:
17702 return new StampAnnotationElement(parameters);
17703 case AnnotationType.FILEATTACHMENT:
17704 return new FileAttachmentAnnotationElement(parameters);
17705 default:
17706 return new AnnotationElement(parameters);
17707 }
17708 }
17709 }
17710 class AnnotationElement {
17711 #updates = null;
17712 #hasBorder = false;
17713 #popupElement = null;
17714 constructor(parameters, {
17715 isRenderable = false,
17716 ignoreBorder = false,
17717 createQuadrilaterals = false
17718 } = {}) {
17719 this.isRenderable = isRenderable;
17720 this.data = parameters.data;
17721 this.layer = parameters.layer;
17722 this.linkService = parameters.linkService;
17723 this.downloadManager = parameters.downloadManager;
17724 this.imageResourcesPath = parameters.imageResourcesPath;
17725 this.renderForms = parameters.renderForms;
17726 this.svgFactory = parameters.svgFactory;
17727 this.annotationStorage = parameters.annotationStorage;
17728 this.enableScripting = parameters.enableScripting;
17729 this.hasJSActions = parameters.hasJSActions;
17730 this._fieldObjects = parameters.fieldObjects;
17731 this.parent = parameters.parent;
17732 if (isRenderable) {
17733 this.container = this._createContainer(ignoreBorder);
17734 }
17735 if (createQuadrilaterals) {
17736 this._createQuadrilaterals();
17737 }
17738 }
17739 static _hasPopupData({
17740 titleObj,
17741 contentsObj,
17742 richText
17743 }) {
17744 return !!(titleObj?.str || contentsObj?.str || richText?.str);
17745 }
17746 get hasPopupData() {
17747 return AnnotationElement._hasPopupData(this.data);
17748 }
17749 updateEdited(params) {
17750 if (!this.container) {
17751 return;
17752 }
17753 this.#updates ||= {
17754 rect: this.data.rect.slice(0)
17755 };
17756 const {
17757 rect
17758 } = params;
17759 if (rect) {
17760 this.#setRectEdited(rect);
17761 }
17762 this.#popupElement?.popup.updateEdited(params);
17763 }
17764 resetEdited() {
17765 if (!this.#updates) {
17766 return;
17767 }
17768 this.#setRectEdited(this.#updates.rect);
17769 this.#popupElement?.popup.resetEdited();
17770 this.#updates = null;
17771 }
17772 #setRectEdited(rect) {
17773 const {
17774 container: {
17775 style
17776 },
17777 data: {
17778 rect: currentRect,
17779 rotation
17780 },
17781 parent: {
17782 viewport: {
17783 rawDims: {
17784 pageWidth,
17785 pageHeight,
17786 pageX,
17787 pageY
17788 }
17789 }
17790 }
17791 } = this;
17792 currentRect?.splice(0, 4, ...rect);
17793 const {
17794 width,
17795 height
17796 } = getRectDims(rect);
17797 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
17798 style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
17799 if (rotation === 0) {
17800 style.width = `${100 * width / pageWidth}%`;
17801 style.height = `${100 * height / pageHeight}%`;
17802 } else {
17803 this.setRotation(rotation);
17804 }
17805 }
17806 _createContainer(ignoreBorder) {
17807 const {
17808 data,
17809 parent: {
17810 page,
17811 viewport
17812 }
17813 } = this;
17814 const container = document.createElement("section");
17815 container.setAttribute("data-annotation-id", data.id);
17816 if (!(this instanceof WidgetAnnotationElement)) {
17817 container.tabIndex = DEFAULT_TAB_INDEX;
17818 }
17819 const {
17820 style
17821 } = container;
17822 style.zIndex = this.parent.zIndex++;
17823 if (data.popupRef) {
17824 container.setAttribute("aria-haspopup", "dialog");
17825 }
17826 if (data.alternativeText) {
17827 container.title = data.alternativeText;
17828 }
17829 if (data.noRotate) {
17830 container.classList.add("norotate");
17831 }
17832 if (!data.rect || this instanceof PopupAnnotationElement) {
17833 const {
17834 rotation
17835 } = data;
17836 if (!data.hasOwnCanvas && rotation !== 0) {
17837 this.setRotation(rotation, container);
17838 }
17839 return container;
17840 }
17841 const {
17842 width,
17843 height
17844 } = getRectDims(data.rect);
17845 if (!ignoreBorder && data.borderStyle.width > 0) {
17846 style.borderWidth = `${data.borderStyle.width}px`;
17847 const horizontalRadius = data.borderStyle.horizontalCornerRadius;
17848 const verticalRadius = data.borderStyle.verticalCornerRadius;
17849 if (horizontalRadius > 0 || verticalRadius > 0) {
17850 const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
17851 style.borderRadius = radius;
17852 } else if (this instanceof RadioButtonWidgetAnnotationElement) {
17853 const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
17854 style.borderRadius = radius;
17855 }
17856 switch (data.borderStyle.style) {
17857 case AnnotationBorderStyleType.SOLID:
17858 style.borderStyle = "solid";
17859 break;
17860 case AnnotationBorderStyleType.DASHED:
17861 style.borderStyle = "dashed";
17862 break;
17863 case AnnotationBorderStyleType.BEVELED:
17864 warn("Unimplemented border style: beveled");
17865 break;
17866 case AnnotationBorderStyleType.INSET:
17867 warn("Unimplemented border style: inset");
17868 break;
17869 case AnnotationBorderStyleType.UNDERLINE:
17870 style.borderBottomStyle = "solid";
17871 break;
17872 default:
17873 break;
17874 }
17875 const borderColor = data.borderColor || null;
17876 if (borderColor) {
17877 this.#hasBorder = true;
17878 style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
17879 } else {
17880 style.borderWidth = 0;
17881 }
17882 }
17883 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]]);
17884 const {
17885 pageWidth,
17886 pageHeight,
17887 pageX,
17888 pageY
17889 } = viewport.rawDims;
17890 style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
17891 style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
17892 const {
17893 rotation
17894 } = data;
17895 if (data.hasOwnCanvas || rotation === 0) {
17896 style.width = `${100 * width / pageWidth}%`;
17897 style.height = `${100 * height / pageHeight}%`;
17898 } else {
17899 this.setRotation(rotation, container);
17900 }
17901 return container;
17902 }
17903 setRotation(angle, container = this.container) {
17904 if (!this.data.rect) {
17905 return;
17906 }
17907 const {
17908 pageWidth,
17909 pageHeight
17910 } = this.parent.viewport.rawDims;
17911 const {
17912 width,
17913 height
17914 } = getRectDims(this.data.rect);
17915 let elementWidth, elementHeight;
17916 if (angle % 180 === 0) {
17917 elementWidth = 100 * width / pageWidth;
17918 elementHeight = 100 * height / pageHeight;
17919 } else {
17920 elementWidth = 100 * height / pageWidth;
17921 elementHeight = 100 * width / pageHeight;
17922 }
17923 container.style.width = `${elementWidth}%`;
17924 container.style.height = `${elementHeight}%`;
17925 container.setAttribute("data-main-rotation", (360 - angle) % 360);
17926 }
17927 get _commonActions() {
17928 const setColor = (jsName, styleName, event) => {
17929 const color = event.detail[jsName];
17930 const colorType = color[0];
17931 const colorArray = color.slice(1);
17932 event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
17933 this.annotationStorage.setValue(this.data.id, {
17934 [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
17935 });
17936 };
17937 return shadow(this, "_commonActions", {
17938 display: event => {
17939 const {
17940 display
17941 } = event.detail;
17942 const hidden = display % 2 === 1;
17943 this.container.style.visibility = hidden ? "hidden" : "visible";
17944 this.annotationStorage.setValue(this.data.id, {
17945 noView: hidden,
17946 noPrint: display === 1 || display === 2
17947 });
17948 },
17949 print: event => {
17950 this.annotationStorage.setValue(this.data.id, {
17951 noPrint: !event.detail.print
17952 });
17953 },
17954 hidden: event => {
17955 const {
17956 hidden
17957 } = event.detail;
17958 this.container.style.visibility = hidden ? "hidden" : "visible";
17959 this.annotationStorage.setValue(this.data.id, {
17960 noPrint: hidden,
17961 noView: hidden
17962 });
17963 },
17964 focus: event => {
17965 setTimeout(() => event.target.focus({
17966 preventScroll: false
17967 }), 0);
17968 },
17969 userName: event => {
17970 event.target.title = event.detail.userName;
17971 },
17972 readonly: event => {
17973 event.target.disabled = event.detail.readonly;
17974 },
17975 required: event => {
17976 this._setRequired(event.target, event.detail.required);
17977 },
17978 bgColor: event => {
17979 setColor("bgColor", "backgroundColor", event);
17980 },
17981 fillColor: event => {
17982 setColor("fillColor", "backgroundColor", event);
17983 },
17984 fgColor: event => {
17985 setColor("fgColor", "color", event);
17986 },
17987 textColor: event => {
17988 setColor("textColor", "color", event);
17989 },
17990 borderColor: event => {
17991 setColor("borderColor", "borderColor", event);
17992 },
17993 strokeColor: event => {
17994 setColor("strokeColor", "borderColor", event);
17995 },
17996 rotation: event => {
17997 const angle = event.detail.rotation;
17998 this.setRotation(angle);
17999 this.annotationStorage.setValue(this.data.id, {
18000 rotation: angle
18001 });
18002 }
18003 });
18004 }
18005 _dispatchEventFromSandbox(actions, jsEvent) {
18006 const commonActions = this._commonActions;
18007 for (const name of Object.keys(jsEvent.detail)) {
18008 const action = actions[name] || commonActions[name];
18009 action?.(jsEvent);
18010 }
18011 }
18012 _setDefaultPropertiesFromJS(element) {
18013 if (!this.enableScripting) {
18014 return;
18015 }
18016 const storedData = this.annotationStorage.getRawValue(this.data.id);
18017 if (!storedData) {
18018 return;
18019 }
18020 const commonActions = this._commonActions;
18021 for (const [actionName, detail] of Object.entries(storedData)) {
18022 const action = commonActions[actionName];
18023 if (action) {
18024 const eventProxy = {
18025 detail: {
18026 [actionName]: detail
18027 },
18028 target: element
18029 };
18030 action(eventProxy);
18031 delete storedData[actionName];
18032 }
18033 }
18034 }
18035 _createQuadrilaterals() {
18036 if (!this.container) {
18037 return;
18038 }
18039 const {
18040 quadPoints
18041 } = this.data;
18042 if (!quadPoints) {
18043 return;
18044 }
18045 const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect;
18046 if (quadPoints.length === 1) {
18047 const [, {
18048 x: trX,
18049 y: trY
18050 }, {
18051 x: blX,
18052 y: blY
18053 }] = quadPoints[0];
18054 if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
18055 return;
18056 }
18057 }
18058 const {
18059 style
18060 } = this.container;
18061 let svgBuffer;
18062 if (this.#hasBorder) {
18063 const {
18064 borderColor,
18065 borderWidth
18066 } = style;
18067 style.borderWidth = 0;
18068 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}">`];
18069 this.container.classList.add("hasBorder");
18070 }
18071 const width = rectTrX - rectBlX;
18072 const height = rectTrY - rectBlY;
18073 const {
18074 svgFactory
18075 } = this;
18076 const svg = svgFactory.createElement("svg");
18077 svg.classList.add("quadrilateralsContainer");
18078 svg.setAttribute("width", 0);
18079 svg.setAttribute("height", 0);
18080 const defs = svgFactory.createElement("defs");
18081 svg.append(defs);
18082 const clipPath = svgFactory.createElement("clipPath");
18083 const id = `clippath_${this.data.id}`;
18084 clipPath.setAttribute("id", id);
18085 clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
18086 defs.append(clipPath);
18087 for (const [, {
18088 x: trX,
18089 y: trY
18090 }, {
18091 x: blX,
18092 y: blY
18093 }] of quadPoints) {
18094 const rect = svgFactory.createElement("rect");
18095 const x = (blX - rectBlX) / width;
18096 const y = (rectTrY - trY) / height;
18097 const rectWidth = (trX - blX) / width;
18098 const rectHeight = (trY - blY) / height;
18099 rect.setAttribute("x", x);
18100 rect.setAttribute("y", y);
18101 rect.setAttribute("width", rectWidth);
18102 rect.setAttribute("height", rectHeight);
18103 clipPath.append(rect);
18104 svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
18105 }
18106 if (this.#hasBorder) {
18107 svgBuffer.push(`</g></svg>')`);
18108 style.backgroundImage = svgBuffer.join("");
18109 }
18110 this.container.append(svg);
18111 this.container.style.clipPath = `url(#${id})`;
18112 }
18113 _createPopup() {
18114 const {
18115 container,
18116 data
18117 } = this;
18118 container.setAttribute("aria-haspopup", "dialog");
18119 const popup = this.#popupElement = new PopupAnnotationElement({
18120 data: {
18121 color: data.color,
18122 titleObj: data.titleObj,
18123 modificationDate: data.modificationDate,
18124 contentsObj: data.contentsObj,
18125 richText: data.richText,
18126 parentRect: data.rect,
18127 borderStyle: 0,
18128 id: `popup_${data.id}`,
18129 rotation: data.rotation
18130 },
18131 parent: this.parent,
18132 elements: [this]
18133 });
18134 this.parent.div.append(popup.render());
18135 }
18136 render() {
18137 unreachable("Abstract method `AnnotationElement.render` called");
18138 }
18139 _getElementsByName(name, skipId = null) {
18140 const fields = [];
18141 if (this._fieldObjects) {
18142 const fieldObj = this._fieldObjects[name];
18143 if (fieldObj) {
18144 for (const {
18145 page,
18146 id,
18147 exportValues
18148 } of fieldObj) {
18149 if (page === -1) {
18150 continue;
18151 }
18152 if (id === skipId) {
18153 continue;
18154 }
18155 const exportValue = typeof exportValues === "string" ? exportValues : null;
18156 const domElement = document.querySelector(`[data-element-id="${id}"]`);
18157 if (domElement && !GetElementsByNameSet.has(domElement)) {
18158 warn(`_getElementsByName - element not allowed: ${id}`);
18159 continue;
18160 }
18161 fields.push({
18162 id,
18163 exportValue,
18164 domElement
18165 });
18166 }
18167 }
18168 return fields;
18169 }
18170 for (const domElement of document.getElementsByName(name)) {
18171 const {
18172 exportValue
18173 } = domElement;
18174 const id = domElement.getAttribute("data-element-id");
18175 if (id === skipId) {
18176 continue;
18177 }
18178 if (!GetElementsByNameSet.has(domElement)) {
18179 continue;
18180 }
18181 fields.push({
18182 id,
18183 exportValue,
18184 domElement
18185 });
18186 }
18187 return fields;
18188 }
18189 show() {
18190 if (this.container) {
18191 this.container.hidden = false;
18192 }
18193 this.popup?.maybeShow();
18194 }
18195 hide() {
18196 if (this.container) {
18197 this.container.hidden = true;
18198 }
18199 this.popup?.forceHide();
18200 }
18201 getElementsToTriggerPopup() {
18202 return this.container;
18203 }
18204 addHighlightArea() {
18205 const triggers = this.getElementsToTriggerPopup();
18206 if (Array.isArray(triggers)) {
18207 for (const element of triggers) {
18208 element.classList.add("highlightArea");
18209 }
18210 } else {
18211 triggers.classList.add("highlightArea");
18212 }
18213 }
18214 get _isEditable() {
18215 return false;
18216 }
18217 _editOnDoubleClick() {
18218 if (!this._isEditable) {
18219 return;
18220 }
18221 const {
18222 annotationEditorType: mode,
18223 data: {
18224 id: editId
18225 }
18226 } = this;
18227 this.container.addEventListener("dblclick", () => {
18228 this.linkService.eventBus?.dispatch("switchannotationeditormode", {
18229 source: this,
18230 mode,
18231 editId
18232 });
18233 });
18234 }
18235 }
18236 class LinkAnnotationElement extends AnnotationElement {
18237 constructor(parameters, options = null) {
18238 super(parameters, {
18239 isRenderable: true,
18240 ignoreBorder: !!options?.ignoreBorder,
18241 createQuadrilaterals: true
18242 });
18243 this.isTooltipOnly = parameters.data.isTooltipOnly;
18244 }
18245 render() {
18246 const {
18247 data,
18248 linkService
18249 } = this;
18250 const link = document.createElement("a");
18251 link.setAttribute("data-element-id", data.id);
18252 let isBound = false;
18253 if (data.url) {
18254 linkService.addLinkAttributes(link, data.url, data.newWindow);
18255 isBound = true;
18256 } else if (data.action) {
18257 this._bindNamedAction(link, data.action);
18258 isBound = true;
18259 } else if (data.attachment) {
18260 this.#bindAttachment(link, data.attachment, data.attachmentDest);
18261 isBound = true;
18262 } else if (data.setOCGState) {
18263 this.#bindSetOCGState(link, data.setOCGState);
18264 isBound = true;
18265 } else if (data.dest) {
18266 this._bindLink(link, data.dest);
18267 isBound = true;
18268 } else {
18269 if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
18270 this._bindJSAction(link, data);
18271 isBound = true;
18272 }
18273 if (data.resetForm) {
18274 this._bindResetFormAction(link, data.resetForm);
18275 isBound = true;
18276 } else if (this.isTooltipOnly && !isBound) {
18277 this._bindLink(link, "");
18278 isBound = true;
18279 }
18280 }
18281 this.container.classList.add("linkAnnotation");
18282 if (isBound) {
18283 this.container.append(link);
18284 }
18285 return this.container;
18286 }
18287 #setInternalLink() {
18288 this.container.setAttribute("data-internal-link", "");
18289 }
18290 _bindLink(link, destination) {
18291 link.href = this.linkService.getDestinationHash(destination);
18292 link.onclick = () => {
18293 if (destination) {
18294 this.linkService.goToDestination(destination);
18295 }
18296 return false;
18297 };
18298 if (destination || destination === "") {
18299 this.#setInternalLink();
18300 }
18301 }
18302 _bindNamedAction(link, action) {
18303 link.href = this.linkService.getAnchorUrl("");
18304 link.onclick = () => {
18305 this.linkService.executeNamedAction(action);
18306 return false;
18307 };
18308 this.#setInternalLink();
18309 }
18310 #bindAttachment(link, attachment, dest = null) {
18311 link.href = this.linkService.getAnchorUrl("");
18312 if (attachment.description) {
18313 link.title = attachment.description;
18314 }
18315 link.onclick = () => {
18316 this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
18317 return false;
18318 };
18319 this.#setInternalLink();
18320 }
18321 #bindSetOCGState(link, action) {
18322 link.href = this.linkService.getAnchorUrl("");
18323 link.onclick = () => {
18324 this.linkService.executeSetOCGState(action);
18325 return false;
18326 };
18327 this.#setInternalLink();
18328 }
18329 _bindJSAction(link, data) {
18330 link.href = this.linkService.getAnchorUrl("");
18331 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
18332 for (const name of Object.keys(data.actions)) {
18333 const jsName = map.get(name);
18334 if (!jsName) {
18335 continue;
18336 }
18337 link[jsName] = () => {
18338 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18339 source: this,
18340 detail: {
18341 id: data.id,
18342 name
18343 }
18344 });
18345 return false;
18346 };
18347 }
18348 if (!link.onclick) {
18349 link.onclick = () => false;
18350 }
18351 this.#setInternalLink();
18352 }
18353 _bindResetFormAction(link, resetForm) {
18354 const otherClickAction = link.onclick;
18355 if (!otherClickAction) {
18356 link.href = this.linkService.getAnchorUrl("");
18357 }
18358 this.#setInternalLink();
18359 if (!this._fieldObjects) {
18360 warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
18361 if (!otherClickAction) {
18362 link.onclick = () => false;
18363 }
18364 return;
18365 }
18366 link.onclick = () => {
18367 otherClickAction?.();
18368 const {
18369 fields: resetFormFields,
18370 refs: resetFormRefs,
18371 include
18372 } = resetForm;
18373 const allFields = [];
18374 if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
18375 const fieldIds = new Set(resetFormRefs);
18376 for (const fieldName of resetFormFields) {
18377 const fields = this._fieldObjects[fieldName] || [];
18378 for (const {
18379 id
18380 } of fields) {
18381 fieldIds.add(id);
18382 }
18383 }
18384 for (const fields of Object.values(this._fieldObjects)) {
18385 for (const field of fields) {
18386 if (fieldIds.has(field.id) === include) {
18387 allFields.push(field);
18388 }
18389 }
18390 }
18391 } else {
18392 for (const fields of Object.values(this._fieldObjects)) {
18393 allFields.push(...fields);
18394 }
18395 }
18396 const storage = this.annotationStorage;
18397 const allIds = [];
18398 for (const field of allFields) {
18399 const {
18400 id
18401 } = field;
18402 allIds.push(id);
18403 switch (field.type) {
18404 case "text":
18405 {
18406 const value = field.defaultValue || "";
18407 storage.setValue(id, {
18408 value
18409 });
18410 break;
18411 }
18412 case "checkbox":
18413 case "radiobutton":
18414 {
18415 const value = field.defaultValue === field.exportValues;
18416 storage.setValue(id, {
18417 value
18418 });
18419 break;
18420 }
18421 case "combobox":
18422 case "listbox":
18423 {
18424 const value = field.defaultValue || "";
18425 storage.setValue(id, {
18426 value
18427 });
18428 break;
18429 }
18430 default:
18431 continue;
18432 }
18433 const domElement = document.querySelector(`[data-element-id="${id}"]`);
18434 if (!domElement) {
18435 continue;
18436 } else if (!GetElementsByNameSet.has(domElement)) {
18437 warn(`_bindResetFormAction - element not allowed: ${id}`);
18438 continue;
18439 }
18440 domElement.dispatchEvent(new Event("resetform"));
18441 }
18442 if (this.enableScripting) {
18443 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18444 source: this,
18445 detail: {
18446 id: "app",
18447 ids: allIds,
18448 name: "ResetForm"
18449 }
18450 });
18451 }
18452 return false;
18453 };
18454 }
18455 }
18456 class TextAnnotationElement extends AnnotationElement {
18457 constructor(parameters) {
18458 super(parameters, {
18459 isRenderable: true
18460 });
18461 }
18462 render() {
18463 this.container.classList.add("textAnnotation");
18464 const image = document.createElement("img");
18465 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
18466 image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
18467 image.setAttribute("data-l10n-args", JSON.stringify({
18468 type: this.data.name
18469 }));
18470 if (!this.data.popupRef && this.hasPopupData) {
18471 this._createPopup();
18472 }
18473 this.container.append(image);
18474 return this.container;
18475 }
18476 }
18477 class WidgetAnnotationElement extends AnnotationElement {
18478 render() {
18479 return this.container;
18480 }
18481 showElementAndHideCanvas(element) {
18482 if (this.data.hasOwnCanvas) {
18483 if (element.previousSibling?.nodeName === "CANVAS") {
18484 element.previousSibling.hidden = true;
18485 }
18486 element.hidden = false;
18487 }
18488 }
18489 _getKeyModifier(event) {
18490 return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
18491 }
18492 _setEventListener(element, elementData, baseName, eventName, valueGetter) {
18493 if (baseName.includes("mouse")) {
18494 element.addEventListener(baseName, event => {
18495 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18496 source: this,
18497 detail: {
18498 id: this.data.id,
18499 name: eventName,
18500 value: valueGetter(event),
18501 shift: event.shiftKey,
18502 modifier: this._getKeyModifier(event)
18503 }
18504 });
18505 });
18506 } else {
18507 element.addEventListener(baseName, event => {
18508 if (baseName === "blur") {
18509 if (!elementData.focused || !event.relatedTarget) {
18510 return;
18511 }
18512 elementData.focused = false;
18513 } else if (baseName === "focus") {
18514 if (elementData.focused) {
18515 return;
18516 }
18517 elementData.focused = true;
18518 }
18519 if (!valueGetter) {
18520 return;
18521 }
18522 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18523 source: this,
18524 detail: {
18525 id: this.data.id,
18526 name: eventName,
18527 value: valueGetter(event)
18528 }
18529 });
18530 });
18531 }
18532 }
18533 _setEventListeners(element, elementData, names, getter) {
18534 for (const [baseName, eventName] of names) {
18535 if (eventName === "Action" || this.data.actions?.[eventName]) {
18536 if (eventName === "Focus" || eventName === "Blur") {
18537 elementData ||= {
18538 focused: false
18539 };
18540 }
18541 this._setEventListener(element, elementData, baseName, eventName, getter);
18542 if (eventName === "Focus" && !this.data.actions?.Blur) {
18543 this._setEventListener(element, elementData, "blur", "Blur", null);
18544 } else if (eventName === "Blur" && !this.data.actions?.Focus) {
18545 this._setEventListener(element, elementData, "focus", "Focus", null);
18546 }
18547 }
18548 }
18549 }
18550 _setBackgroundColor(element) {
18551 const color = this.data.backgroundColor || null;
18552 element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
18553 }
18554 _setTextStyle(element) {
18555 const TEXT_ALIGNMENT = ["left", "center", "right"];
18556 const {
18557 fontColor
18558 } = this.data.defaultAppearanceData;
18559 const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
18560 const style = element.style;
18561 let computedFontSize;
18562 const BORDER_SIZE = 2;
18563 const roundToOneDecimal = x => Math.round(10 * x) / 10;
18564 if (this.data.multiLine) {
18565 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
18566 const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
18567 const lineHeight = height / numberOfLines;
18568 computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
18569 } else {
18570 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
18571 computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
18572 }
18573 style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
18574 style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
18575 if (this.data.textAlignment !== null) {
18576 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
18577 }
18578 }
18579 _setRequired(element, isRequired) {
18580 if (isRequired) {
18581 element.setAttribute("required", true);
18582 } else {
18583 element.removeAttribute("required");
18584 }
18585 element.setAttribute("aria-required", isRequired);
18586 }
18587 }
18588 class TextWidgetAnnotationElement extends WidgetAnnotationElement {
18589 constructor(parameters) {
18590 const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
18591 super(parameters, {
18592 isRenderable
18593 });
18594 }
18595 setPropertyOnSiblings(base, key, value, keyInStorage) {
18596 const storage = this.annotationStorage;
18597 for (const element of this._getElementsByName(base.name, base.id)) {
18598 if (element.domElement) {
18599 element.domElement[key] = value;
18600 }
18601 storage.setValue(element.id, {
18602 [keyInStorage]: value
18603 });
18604 }
18605 }
18606 render() {
18607 const storage = this.annotationStorage;
18608 const id = this.data.id;
18609 this.container.classList.add("textWidgetAnnotation");
18610 let element = null;
18611 if (this.renderForms) {
18612 const storedData = storage.getValue(id, {
18613 value: this.data.fieldValue
18614 });
18615 let textContent = storedData.value || "";
18616 const maxLen = storage.getValue(id, {
18617 charLimit: this.data.maxLen
18618 }).charLimit;
18619 if (maxLen && textContent.length > maxLen) {
18620 textContent = textContent.slice(0, maxLen);
18621 }
18622 let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
18623 if (fieldFormattedValues && this.data.comb) {
18624 fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
18625 }
18626 const elementData = {
18627 userValue: textContent,
18628 formattedValue: fieldFormattedValues,
18629 lastCommittedValue: null,
18630 commitKey: 1,
18631 focused: false
18632 };
18633 if (this.data.multiLine) {
18634 element = document.createElement("textarea");
18635 element.textContent = fieldFormattedValues ?? textContent;
18636 if (this.data.doNotScroll) {
18637 element.style.overflowY = "hidden";
18638 }
18639 } else {
18640 element = document.createElement("input");
18641 element.type = "text";
18642 element.setAttribute("value", fieldFormattedValues ?? textContent);
18643 if (this.data.doNotScroll) {
18644 element.style.overflowX = "hidden";
18645 }
18646 }
18647 if (this.data.hasOwnCanvas) {
18648 element.hidden = true;
18649 }
18650 GetElementsByNameSet.add(element);
18651 element.setAttribute("data-element-id", id);
18652 element.disabled = this.data.readOnly;
18653 element.name = this.data.fieldName;
18654 element.tabIndex = DEFAULT_TAB_INDEX;
18655 this._setRequired(element, this.data.required);
18656 if (maxLen) {
18657 element.maxLength = maxLen;
18658 }
18659 element.addEventListener("input", event => {
18660 storage.setValue(id, {
18661 value: event.target.value
18662 });
18663 this.setPropertyOnSiblings(element, "value", event.target.value, "value");
18664 elementData.formattedValue = null;
18665 });
18666 element.addEventListener("resetform", event => {
18667 const defaultValue = this.data.defaultFieldValue ?? "";
18668 element.value = elementData.userValue = defaultValue;
18669 elementData.formattedValue = null;
18670 });
18671 let blurListener = event => {
18672 const {
18673 formattedValue
18674 } = elementData;
18675 if (formattedValue !== null && formattedValue !== undefined) {
18676 event.target.value = formattedValue;
18677 }
18678 event.target.scrollLeft = 0;
18679 };
18680 if (this.enableScripting && this.hasJSActions) {
18681 element.addEventListener("focus", event => {
18682 if (elementData.focused) {
18683 return;
18684 }
18685 const {
18686 target
18687 } = event;
18688 if (elementData.userValue) {
18689 target.value = elementData.userValue;
18690 }
18691 elementData.lastCommittedValue = target.value;
18692 elementData.commitKey = 1;
18693 if (!this.data.actions?.Focus) {
18694 elementData.focused = true;
18695 }
18696 });
18697 element.addEventListener("updatefromsandbox", jsEvent => {
18698 this.showElementAndHideCanvas(jsEvent.target);
18699 const actions = {
18700 value(event) {
18701 elementData.userValue = event.detail.value ?? "";
18702 storage.setValue(id, {
18703 value: elementData.userValue.toString()
18704 });
18705 event.target.value = elementData.userValue;
18706 },
18707 formattedValue(event) {
18708 const {
18709 formattedValue
18710 } = event.detail;
18711 elementData.formattedValue = formattedValue;
18712 if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
18713 event.target.value = formattedValue;
18714 }
18715 storage.setValue(id, {
18716 formattedValue
18717 });
18718 },
18719 selRange(event) {
18720 event.target.setSelectionRange(...event.detail.selRange);
18721 },
18722 charLimit: event => {
18723 const {
18724 charLimit
18725 } = event.detail;
18726 const {
18727 target
18728 } = event;
18729 if (charLimit === 0) {
18730 target.removeAttribute("maxLength");
18731 return;
18732 }
18733 target.setAttribute("maxLength", charLimit);
18734 let value = elementData.userValue;
18735 if (!value || value.length <= charLimit) {
18736 return;
18737 }
18738 value = value.slice(0, charLimit);
18739 target.value = elementData.userValue = value;
18740 storage.setValue(id, {
18741 value
18742 });
18743 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18744 source: this,
18745 detail: {
18746 id,
18747 name: "Keystroke",
18748 value,
18749 willCommit: true,
18750 commitKey: 1,
18751 selStart: target.selectionStart,
18752 selEnd: target.selectionEnd
18753 }
18754 });
18755 }
18756 };
18757 this._dispatchEventFromSandbox(actions, jsEvent);
18758 });
18759 element.addEventListener("keydown", event => {
18760 elementData.commitKey = 1;
18761 let commitKey = -1;
18762 if (event.key === "Escape") {
18763 commitKey = 0;
18764 } else if (event.key === "Enter" && !this.data.multiLine) {
18765 commitKey = 2;
18766 } else if (event.key === "Tab") {
18767 elementData.commitKey = 3;
18768 }
18769 if (commitKey === -1) {
18770 return;
18771 }
18772 const {
18773 value
18774 } = event.target;
18775 if (elementData.lastCommittedValue === value) {
18776 return;
18777 }
18778 elementData.lastCommittedValue = value;
18779 elementData.userValue = value;
18780 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18781 source: this,
18782 detail: {
18783 id,
18784 name: "Keystroke",
18785 value,
18786 willCommit: true,
18787 commitKey,
18788 selStart: event.target.selectionStart,
18789 selEnd: event.target.selectionEnd
18790 }
18791 });
18792 });
18793 const _blurListener = blurListener;
18794 blurListener = null;
18795 element.addEventListener("blur", event => {
18796 if (!elementData.focused || !event.relatedTarget) {
18797 return;
18798 }
18799 if (!this.data.actions?.Blur) {
18800 elementData.focused = false;
18801 }
18802 const {
18803 value
18804 } = event.target;
18805 elementData.userValue = value;
18806 if (elementData.lastCommittedValue !== value) {
18807 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18808 source: this,
18809 detail: {
18810 id,
18811 name: "Keystroke",
18812 value,
18813 willCommit: true,
18814 commitKey: elementData.commitKey,
18815 selStart: event.target.selectionStart,
18816 selEnd: event.target.selectionEnd
18817 }
18818 });
18819 }
18820 _blurListener(event);
18821 });
18822 if (this.data.actions?.Keystroke) {
18823 element.addEventListener("beforeinput", event => {
18824 elementData.lastCommittedValue = null;
18825 const {
18826 data,
18827 target
18828 } = event;
18829 const {
18830 value,
18831 selectionStart,
18832 selectionEnd
18833 } = target;
18834 let selStart = selectionStart,
18835 selEnd = selectionEnd;
18836 switch (event.inputType) {
18837 case "deleteWordBackward":
18838 {
18839 const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
18840 if (match) {
18841 selStart -= match[0].length;
18842 }
18843 break;
18844 }
18845 case "deleteWordForward":
18846 {
18847 const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
18848 if (match) {
18849 selEnd += match[0].length;
18850 }
18851 break;
18852 }
18853 case "deleteContentBackward":
18854 if (selectionStart === selectionEnd) {
18855 selStart -= 1;
18856 }
18857 break;
18858 case "deleteContentForward":
18859 if (selectionStart === selectionEnd) {
18860 selEnd += 1;
18861 }
18862 break;
18863 }
18864 event.preventDefault();
18865 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
18866 source: this,
18867 detail: {
18868 id,
18869 name: "Keystroke",
18870 value,
18871 change: data || "",
18872 willCommit: false,
18873 selStart,
18874 selEnd
18875 }
18876 });
18877 });
18878 }
18879 this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
18880 }
18881 if (blurListener) {
18882 element.addEventListener("blur", blurListener);
18883 }
18884 if (this.data.comb) {
18885 const fieldWidth = this.data.rect[2] - this.data.rect[0];
18886 const combWidth = fieldWidth / maxLen;
18887 element.classList.add("comb");
18888 element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
18889 }
18890 } else {
18891 element = document.createElement("div");
18892 element.textContent = this.data.fieldValue;
18893 element.style.verticalAlign = "middle";
18894 element.style.display = "table-cell";
18895 if (this.data.hasOwnCanvas) {
18896 element.hidden = true;
18897 }
18898 }
18899 this._setTextStyle(element);
18900 this._setBackgroundColor(element);
18901 this._setDefaultPropertiesFromJS(element);
18902 this.container.append(element);
18903 return this.container;
18904 }
18905 }
18906 class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
18907 constructor(parameters) {
18908 super(parameters, {
18909 isRenderable: !!parameters.data.hasOwnCanvas
18910 });
18911 }
18912 }
18913 class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
18914 constructor(parameters) {
18915 super(parameters, {
18916 isRenderable: parameters.renderForms
18917 });
18918 }
18919 render() {
18920 const storage = this.annotationStorage;
18921 const data = this.data;
18922 const id = data.id;
18923 let value = storage.getValue(id, {
18924 value: data.exportValue === data.fieldValue
18925 }).value;
18926 if (typeof value === "string") {
18927 value = value !== "Off";
18928 storage.setValue(id, {
18929 value
18930 });
18931 }
18932 this.container.classList.add("buttonWidgetAnnotation", "checkBox");
18933 const element = document.createElement("input");
18934 GetElementsByNameSet.add(element);
18935 element.setAttribute("data-element-id", id);
18936 element.disabled = data.readOnly;
18937 this._setRequired(element, this.data.required);
18938 element.type = "checkbox";
18939 element.name = data.fieldName;
18940 if (value) {
18941 element.setAttribute("checked", true);
18942 }
18943 element.setAttribute("exportValue", data.exportValue);
18944 element.tabIndex = DEFAULT_TAB_INDEX;
18945 element.addEventListener("change", event => {
18946 const {
18947 name,
18948 checked
18949 } = event.target;
18950 for (const checkbox of this._getElementsByName(name, id)) {
18951 const curChecked = checked && checkbox.exportValue === data.exportValue;
18952 if (checkbox.domElement) {
18953 checkbox.domElement.checked = curChecked;
18954 }
18955 storage.setValue(checkbox.id, {
18956 value: curChecked
18957 });
18958 }
18959 storage.setValue(id, {
18960 value: checked
18961 });
18962 });
18963 element.addEventListener("resetform", event => {
18964 const defaultValue = data.defaultFieldValue || "Off";
18965 event.target.checked = defaultValue === data.exportValue;
18966 });
18967 if (this.enableScripting && this.hasJSActions) {
18968 element.addEventListener("updatefromsandbox", jsEvent => {
18969 const actions = {
18970 value(event) {
18971 event.target.checked = event.detail.value !== "Off";
18972 storage.setValue(id, {
18973 value: event.target.checked
18974 });
18975 }
18976 };
18977 this._dispatchEventFromSandbox(actions, jsEvent);
18978 });
18979 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);
18980 }
18981 this._setBackgroundColor(element);
18982 this._setDefaultPropertiesFromJS(element);
18983 this.container.append(element);
18984 return this.container;
18985 }
18986 }
18987 class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
18988 constructor(parameters) {
18989 super(parameters, {
18990 isRenderable: parameters.renderForms
18991 });
18992 }
18993 render() {
18994 this.container.classList.add("buttonWidgetAnnotation", "radioButton");
18995 const storage = this.annotationStorage;
18996 const data = this.data;
18997 const id = data.id;
18998 let value = storage.getValue(id, {
18999 value: data.fieldValue === data.buttonValue
19000 }).value;
19001 if (typeof value === "string") {
19002 value = value !== data.buttonValue;
19003 storage.setValue(id, {
19004 value
19005 });
19006 }
19007 if (value) {
19008 for (const radio of this._getElementsByName(data.fieldName, id)) {
19009 storage.setValue(radio.id, {
19010 value: false
19011 });
19012 }
19013 }
19014 const element = document.createElement("input");
19015 GetElementsByNameSet.add(element);
19016 element.setAttribute("data-element-id", id);
19017 element.disabled = data.readOnly;
19018 this._setRequired(element, this.data.required);
19019 element.type = "radio";
19020 element.name = data.fieldName;
19021 if (value) {
19022 element.setAttribute("checked", true);
19023 }
19024 element.tabIndex = DEFAULT_TAB_INDEX;
19025 element.addEventListener("change", event => {
19026 const {
19027 name,
19028 checked
19029 } = event.target;
19030 for (const radio of this._getElementsByName(name, id)) {
19031 storage.setValue(radio.id, {
19032 value: false
19033 });
19034 }
19035 storage.setValue(id, {
19036 value: checked
19037 });
19038 });
19039 element.addEventListener("resetform", event => {
19040 const defaultValue = data.defaultFieldValue;
19041 event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
19042 });
19043 if (this.enableScripting && this.hasJSActions) {
19044 const pdfButtonValue = data.buttonValue;
19045 element.addEventListener("updatefromsandbox", jsEvent => {
19046 const actions = {
19047 value: event => {
19048 const checked = pdfButtonValue === event.detail.value;
19049 for (const radio of this._getElementsByName(event.target.name)) {
19050 const curChecked = checked && radio.id === id;
19051 if (radio.domElement) {
19052 radio.domElement.checked = curChecked;
19053 }
19054 storage.setValue(radio.id, {
19055 value: curChecked
19056 });
19057 }
19058 }
19059 };
19060 this._dispatchEventFromSandbox(actions, jsEvent);
19061 });
19062 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);
19063 }
19064 this._setBackgroundColor(element);
19065 this._setDefaultPropertiesFromJS(element);
19066 this.container.append(element);
19067 return this.container;
19068 }
19069 }
19070 class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
19071 constructor(parameters) {
19072 super(parameters, {
19073 ignoreBorder: parameters.data.hasAppearance
19074 });
19075 }
19076 render() {
19077 const container = super.render();
19078 container.classList.add("buttonWidgetAnnotation", "pushButton");
19079 const linkElement = container.lastChild;
19080 if (this.enableScripting && this.hasJSActions && linkElement) {
19081 this._setDefaultPropertiesFromJS(linkElement);
19082 linkElement.addEventListener("updatefromsandbox", jsEvent => {
19083 this._dispatchEventFromSandbox({}, jsEvent);
19084 });
19085 }
19086 return container;
19087 }
19088 }
19089 class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
19090 constructor(parameters) {
19091 super(parameters, {
19092 isRenderable: parameters.renderForms
19093 });
19094 }
19095 render() {
19096 this.container.classList.add("choiceWidgetAnnotation");
19097 const storage = this.annotationStorage;
19098 const id = this.data.id;
19099 const storedData = storage.getValue(id, {
19100 value: this.data.fieldValue
19101 });
19102 const selectElement = document.createElement("select");
19103 GetElementsByNameSet.add(selectElement);
19104 selectElement.setAttribute("data-element-id", id);
19105 selectElement.disabled = this.data.readOnly;
19106 this._setRequired(selectElement, this.data.required);
19107 selectElement.name = this.data.fieldName;
19108 selectElement.tabIndex = DEFAULT_TAB_INDEX;
19109 let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
19110 if (!this.data.combo) {
19111 selectElement.size = this.data.options.length;
19112 if (this.data.multiSelect) {
19113 selectElement.multiple = true;
19114 }
19115 }
19116 selectElement.addEventListener("resetform", event => {
19117 const defaultValue = this.data.defaultFieldValue;
19118 for (const option of selectElement.options) {
19119 option.selected = option.value === defaultValue;
19120 }
19121 });
19122 for (const option of this.data.options) {
19123 const optionElement = document.createElement("option");
19124 optionElement.textContent = option.displayValue;
19125 optionElement.value = option.exportValue;
19126 if (storedData.value.includes(option.exportValue)) {
19127 optionElement.setAttribute("selected", true);
19128 addAnEmptyEntry = false;
19129 }
19130 selectElement.append(optionElement);
19131 }
19132 let removeEmptyEntry = null;
19133 if (addAnEmptyEntry) {
19134 const noneOptionElement = document.createElement("option");
19135 noneOptionElement.value = " ";
19136 noneOptionElement.setAttribute("hidden", true);
19137 noneOptionElement.setAttribute("selected", true);
19138 selectElement.prepend(noneOptionElement);
19139 removeEmptyEntry = () => {
19140 noneOptionElement.remove();
19141 selectElement.removeEventListener("input", removeEmptyEntry);
19142 removeEmptyEntry = null;
19143 };
19144 selectElement.addEventListener("input", removeEmptyEntry);
19145 }
19146 const getValue = isExport => {
19147 const name = isExport ? "value" : "textContent";
19148 const {
19149 options,
19150 multiple
19151 } = selectElement;
19152 if (!multiple) {
19153 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
19154 }
19155 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
19156 };
19157 let selectedValues = getValue(false);
19158 const getItems = event => {
19159 const options = event.target.options;
19160 return Array.prototype.map.call(options, option => ({
19161 displayValue: option.textContent,
19162 exportValue: option.value
19163 }));
19164 };
19165 if (this.enableScripting && this.hasJSActions) {
19166 selectElement.addEventListener("updatefromsandbox", jsEvent => {
19167 const actions = {
19168 value(event) {
19169 removeEmptyEntry?.();
19170 const value = event.detail.value;
19171 const values = new Set(Array.isArray(value) ? value : [value]);
19172 for (const option of selectElement.options) {
19173 option.selected = values.has(option.value);
19174 }
19175 storage.setValue(id, {
19176 value: getValue(true)
19177 });
19178 selectedValues = getValue(false);
19179 },
19180 multipleSelection(event) {
19181 selectElement.multiple = true;
19182 },
19183 remove(event) {
19184 const options = selectElement.options;
19185 const index = event.detail.remove;
19186 options[index].selected = false;
19187 selectElement.remove(index);
19188 if (options.length > 0) {
19189 const i = Array.prototype.findIndex.call(options, option => option.selected);
19190 if (i === -1) {
19191 options[0].selected = true;
19192 }
19193 }
19194 storage.setValue(id, {
19195 value: getValue(true),
19196 items: getItems(event)
19197 });
19198 selectedValues = getValue(false);
19199 },
19200 clear(event) {
19201 while (selectElement.length !== 0) {
19202 selectElement.remove(0);
19203 }
19204 storage.setValue(id, {
19205 value: null,
19206 items: []
19207 });
19208 selectedValues = getValue(false);
19209 },
19210 insert(event) {
19211 const {
19212 index,
19213 displayValue,
19214 exportValue
19215 } = event.detail.insert;
19216 const selectChild = selectElement.children[index];
19217 const optionElement = document.createElement("option");
19218 optionElement.textContent = displayValue;
19219 optionElement.value = exportValue;
19220 if (selectChild) {
19221 selectChild.before(optionElement);
19222 } else {
19223 selectElement.append(optionElement);
19224 }
19225 storage.setValue(id, {
19226 value: getValue(true),
19227 items: getItems(event)
19228 });
19229 selectedValues = getValue(false);
19230 },
19231 items(event) {
19232 const {
19233 items
19234 } = event.detail;
19235 while (selectElement.length !== 0) {
19236 selectElement.remove(0);
19237 }
19238 for (const item of items) {
19239 const {
19240 displayValue,
19241 exportValue
19242 } = item;
19243 const optionElement = document.createElement("option");
19244 optionElement.textContent = displayValue;
19245 optionElement.value = exportValue;
19246 selectElement.append(optionElement);
19247 }
19248 if (selectElement.options.length > 0) {
19249 selectElement.options[0].selected = true;
19250 }
19251 storage.setValue(id, {
19252 value: getValue(true),
19253 items: getItems(event)
19254 });
19255 selectedValues = getValue(false);
19256 },
19257 indices(event) {
19258 const indices = new Set(event.detail.indices);
19259 for (const option of event.target.options) {
19260 option.selected = indices.has(option.index);
19261 }
19262 storage.setValue(id, {
19263 value: getValue(true)
19264 });
19265 selectedValues = getValue(false);
19266 },
19267 editable(event) {
19268 event.target.disabled = !event.detail.editable;
19269 }
19270 };
19271 this._dispatchEventFromSandbox(actions, jsEvent);
19272 });
19273 selectElement.addEventListener("input", event => {
19274 const exportValue = getValue(true);
19275 const change = getValue(false);
19276 storage.setValue(id, {
19277 value: exportValue
19278 });
19279 event.preventDefault();
19280 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
19281 source: this,
19282 detail: {
19283 id,
19284 name: "Keystroke",
19285 value: selectedValues,
19286 change,
19287 changeEx: exportValue,
19288 willCommit: false,
19289 commitKey: 1,
19290 keyDown: false
19291 }
19292 });
19293 });
19294 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);
19295 } else {
19296 selectElement.addEventListener("input", function (event) {
19297 storage.setValue(id, {
19298 value: getValue(true)
19299 });
19300 });
19301 }
19302 if (this.data.combo) {
19303 this._setTextStyle(selectElement);
19304 } else {}
19305 this._setBackgroundColor(selectElement);
19306 this._setDefaultPropertiesFromJS(selectElement);
19307 this.container.append(selectElement);
19308 return this.container;
19309 }
19310 }
19311 class PopupAnnotationElement extends AnnotationElement {
19312 constructor(parameters) {
19313 const {
19314 data,
19315 elements
19316 } = parameters;
19317 super(parameters, {
19318 isRenderable: AnnotationElement._hasPopupData(data)
19319 });
19320 this.elements = elements;
19321 this.popup = null;
19322 }
19323 render() {
19324 this.container.classList.add("popupAnnotation");
19325 const popup = this.popup = new PopupElement({
19326 container: this.container,
19327 color: this.data.color,
19328 titleObj: this.data.titleObj,
19329 modificationDate: this.data.modificationDate,
19330 contentsObj: this.data.contentsObj,
19331 richText: this.data.richText,
19332 rect: this.data.rect,
19333 parentRect: this.data.parentRect || null,
19334 parent: this.parent,
19335 elements: this.elements,
19336 open: this.data.open
19337 });
19338 const elementIds = [];
19339 for (const element of this.elements) {
19340 element.popup = popup;
19341 elementIds.push(element.data.id);
19342 element.addHighlightArea();
19343 }
19344 this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
19345 return this.container;
19346 }
19347 }
19348 class PopupElement {
19349 #boundKeyDown = this.#keyDown.bind(this);
19350 #boundHide = this.#hide.bind(this);
19351 #boundShow = this.#show.bind(this);
19352 #boundToggle = this.#toggle.bind(this);
19353 #color = null;
19354 #container = null;
19355 #contentsObj = null;
19356 #dateObj = null;
19357 #elements = null;
19358 #parent = null;
19359 #parentRect = null;
19360 #pinned = false;
19361 #popup = null;
19362 #position = null;
19363 #rect = null;
19364 #richText = null;
19365 #titleObj = null;
19366 #updates = null;
19367 #wasVisible = false;
19368 constructor({
19369 container,
19370 color,
19371 elements,
19372 titleObj,
19373 modificationDate,
19374 contentsObj,
19375 richText,
19376 parent,
19377 rect,
19378 parentRect,
19379 open
19380 }) {
19381 this.#container = container;
19382 this.#titleObj = titleObj;
19383 this.#contentsObj = contentsObj;
19384 this.#richText = richText;
19385 this.#parent = parent;
19386 this.#color = color;
19387 this.#rect = rect;
19388 this.#parentRect = parentRect;
19389 this.#elements = elements;
19390 this.#dateObj = PDFDateString.toDateObject(modificationDate);
19391 this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
19392 for (const element of this.trigger) {
19393 element.addEventListener("click", this.#boundToggle);
19394 element.addEventListener("mouseenter", this.#boundShow);
19395 element.addEventListener("mouseleave", this.#boundHide);
19396 element.classList.add("popupTriggerArea");
19397 }
19398 for (const element of elements) {
19399 element.container?.addEventListener("keydown", this.#boundKeyDown);
19400 }
19401 this.#container.hidden = true;
19402 if (open) {
19403 this.#toggle();
19404 }
19405 }
19406 render() {
19407 if (this.#popup) {
19408 return;
19409 }
19410 const popup = this.#popup = document.createElement("div");
19411 popup.className = "popup";
19412 if (this.#color) {
19413 const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
19414 if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
19415 popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
19416 } else {
19417 const BACKGROUND_ENLIGHT = 0.7;
19418 popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
19419 }
19420 }
19421 const header = document.createElement("span");
19422 header.className = "header";
19423 const title = document.createElement("h1");
19424 header.append(title);
19425 ({
19426 dir: title.dir,
19427 str: title.textContent
19428 } = this.#titleObj);
19429 popup.append(header);
19430 if (this.#dateObj) {
19431 const modificationDate = document.createElement("span");
19432 modificationDate.classList.add("popupDate");
19433 modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-string");
19434 modificationDate.setAttribute("data-l10n-args", JSON.stringify({
19435 date: this.#dateObj.toLocaleDateString(),
19436 time: this.#dateObj.toLocaleTimeString()
19437 }));
19438 header.append(modificationDate);
19439 }
19440 const html = this.#html;
19441 if (html) {
19442 XfaLayer.render({
19443 xfaHtml: html,
19444 intent: "richText",
19445 div: popup
19446 });
19447 popup.lastChild.classList.add("richText", "popupContent");
19448 } else {
19449 const contents = this._formatContents(this.#contentsObj);
19450 popup.append(contents);
19451 }
19452 this.#container.append(popup);
19453 }
19454 get #html() {
19455 const richText = this.#richText;
19456 const contentsObj = this.#contentsObj;
19457 if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
19458 return this.#richText.html || null;
19459 }
19460 return null;
19461 }
19462 get #fontSize() {
19463 return this.#html?.attributes?.style?.fontSize || 0;
19464 }
19465 get #fontColor() {
19466 return this.#html?.attributes?.style?.color || null;
19467 }
19468 #makePopupContent(text) {
19469 const popupLines = [];
19470 const popupContent = {
19471 str: text,
19472 html: {
19473 name: "div",
19474 attributes: {
19475 dir: "auto"
19476 },
19477 children: [{
19478 name: "p",
19479 children: popupLines
19480 }]
19481 }
19482 };
19483 const lineAttributes = {
19484 style: {
19485 color: this.#fontColor,
19486 fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : ""
19487 }
19488 };
19489 for (const line of text.split("\n")) {
19490 popupLines.push({
19491 name: "span",
19492 value: line,
19493 attributes: lineAttributes
19494 });
19495 }
19496 return popupContent;
19497 }
19498 _formatContents({
19499 str,
19500 dir
19501 }) {
19502 const p = document.createElement("p");
19503 p.classList.add("popupContent");
19504 p.dir = dir;
19505 const lines = str.split(/(?:\r\n?|\n)/);
19506 for (let i = 0, ii = lines.length; i < ii; ++i) {
19507 const line = lines[i];
19508 p.append(document.createTextNode(line));
19509 if (i < ii - 1) {
19510 p.append(document.createElement("br"));
19511 }
19512 }
19513 return p;
19514 }
19515 #keyDown(event) {
19516 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
19517 return;
19518 }
19519 if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
19520 this.#toggle();
19521 }
19522 }
19523 updateEdited({
19524 rect,
19525 popupContent
19526 }) {
19527 this.#updates ||= {
19528 contentsObj: this.#contentsObj,
19529 richText: this.#richText
19530 };
19531 if (rect) {
19532 this.#position = null;
19533 }
19534 if (popupContent) {
19535 this.#richText = this.#makePopupContent(popupContent);
19536 this.#contentsObj = null;
19537 }
19538 this.#popup?.remove();
19539 this.#popup = null;
19540 }
19541 resetEdited() {
19542 if (!this.#updates) {
19543 return;
19544 }
19545 ({
19546 contentsObj: this.#contentsObj,
19547 richText: this.#richText
19548 } = this.#updates);
19549 this.#updates = null;
19550 this.#popup?.remove();
19551 this.#popup = null;
19552 this.#position = null;
19553 }
19554 #setPosition() {
19555 if (this.#position !== null) {
19556 return;
19557 }
19558 const {
19559 page: {
19560 view
19561 },
19562 viewport: {
19563 rawDims: {
19564 pageWidth,
19565 pageHeight,
19566 pageX,
19567 pageY
19568 }
19569 }
19570 } = this.#parent;
19571 let useParentRect = !!this.#parentRect;
19572 let rect = useParentRect ? this.#parentRect : this.#rect;
19573 for (const element of this.#elements) {
19574 if (!rect || Util.intersect(element.data.rect, rect) !== null) {
19575 rect = element.data.rect;
19576 useParentRect = true;
19577 break;
19578 }
19579 }
19580 const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
19581 const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
19582 const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
19583 const popupLeft = normalizedRect[0] + parentWidth;
19584 const popupTop = normalizedRect[1];
19585 this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
19586 const {
19587 style
19588 } = this.#container;
19589 style.left = `${this.#position[0]}%`;
19590 style.top = `${this.#position[1]}%`;
19591 }
19592 #toggle() {
19593 this.#pinned = !this.#pinned;
19594 if (this.#pinned) {
19595 this.#show();
19596 this.#container.addEventListener("click", this.#boundToggle);
19597 this.#container.addEventListener("keydown", this.#boundKeyDown);
19598 } else {
19599 this.#hide();
19600 this.#container.removeEventListener("click", this.#boundToggle);
19601 this.#container.removeEventListener("keydown", this.#boundKeyDown);
19602 }
19603 }
19604 #show() {
19605 if (!this.#popup) {
19606 this.render();
19607 }
19608 if (!this.isVisible) {
19609 this.#setPosition();
19610 this.#container.hidden = false;
19611 this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
19612 } else if (this.#pinned) {
19613 this.#container.classList.add("focused");
19614 }
19615 }
19616 #hide() {
19617 this.#container.classList.remove("focused");
19618 if (this.#pinned || !this.isVisible) {
19619 return;
19620 }
19621 this.#container.hidden = true;
19622 this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
19623 }
19624 forceHide() {
19625 this.#wasVisible = this.isVisible;
19626 if (!this.#wasVisible) {
19627 return;
19628 }
19629 this.#container.hidden = true;
19630 }
19631 maybeShow() {
19632 if (!this.#wasVisible) {
19633 return;
19634 }
19635 if (!this.#popup) {
19636 this.#show();
19637 }
19638 this.#wasVisible = false;
19639 this.#container.hidden = false;
19640 }
19641 get isVisible() {
19642 return this.#container.hidden === false;
19643 }
19644 }
19645 class FreeTextAnnotationElement extends AnnotationElement {
19646 constructor(parameters) {
19647 super(parameters, {
19648 isRenderable: true,
19649 ignoreBorder: true
19650 });
19651 this.textContent = parameters.data.textContent;
19652 this.textPosition = parameters.data.textPosition;
19653 this.annotationEditorType = AnnotationEditorType.FREETEXT;
19654 }
19655 render() {
19656 this.container.classList.add("freeTextAnnotation");
19657 if (this.textContent) {
19658 const content = document.createElement("div");
19659 content.classList.add("annotationTextContent");
19660 content.setAttribute("role", "comment");
19661 for (const line of this.textContent) {
19662 const lineSpan = document.createElement("span");
19663 lineSpan.textContent = line;
19664 content.append(lineSpan);
19665 }
19666 this.container.append(content);
19667 }
19668 if (!this.data.popupRef && this.hasPopupData) {
19669 this._createPopup();
19670 }
19671 this._editOnDoubleClick();
19672 return this.container;
19673 }
19674 get _isEditable() {
19675 return this.data.hasOwnCanvas;
19676 }
19677 }
19678 class LineAnnotationElement extends AnnotationElement {
19679 #line = null;
19680 constructor(parameters) {
19681 super(parameters, {
19682 isRenderable: true,
19683 ignoreBorder: true
19684 });
19685 }
19686 render() {
19687 this.container.classList.add("lineAnnotation");
19688 const data = this.data;
19689 const {
19690 width,
19691 height
19692 } = getRectDims(data.rect);
19693 const svg = this.svgFactory.create(width, height, true);
19694 const line = this.#line = this.svgFactory.createElement("svg:line");
19695 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
19696 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
19697 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
19698 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
19699 line.setAttribute("stroke-width", data.borderStyle.width || 1);
19700 line.setAttribute("stroke", "transparent");
19701 line.setAttribute("fill", "transparent");
19702 svg.append(line);
19703 this.container.append(svg);
19704 if (!data.popupRef && this.hasPopupData) {
19705 this._createPopup();
19706 }
19707 return this.container;
19708 }
19709 getElementsToTriggerPopup() {
19710 return this.#line;
19711 }
19712 addHighlightArea() {
19713 this.container.classList.add("highlightArea");
19714 }
19715 }
19716 class SquareAnnotationElement extends AnnotationElement {
19717 #square = null;
19718 constructor(parameters) {
19719 super(parameters, {
19720 isRenderable: true,
19721 ignoreBorder: true
19722 });
19723 }
19724 render() {
19725 this.container.classList.add("squareAnnotation");
19726 const data = this.data;
19727 const {
19728 width,
19729 height
19730 } = getRectDims(data.rect);
19731 const svg = this.svgFactory.create(width, height, true);
19732 const borderWidth = data.borderStyle.width;
19733 const square = this.#square = this.svgFactory.createElement("svg:rect");
19734 square.setAttribute("x", borderWidth / 2);
19735 square.setAttribute("y", borderWidth / 2);
19736 square.setAttribute("width", width - borderWidth);
19737 square.setAttribute("height", height - borderWidth);
19738 square.setAttribute("stroke-width", borderWidth || 1);
19739 square.setAttribute("stroke", "transparent");
19740 square.setAttribute("fill", "transparent");
19741 svg.append(square);
19742 this.container.append(svg);
19743 if (!data.popupRef && this.hasPopupData) {
19744 this._createPopup();
19745 }
19746 return this.container;
19747 }
19748 getElementsToTriggerPopup() {
19749 return this.#square;
19750 }
19751 addHighlightArea() {
19752 this.container.classList.add("highlightArea");
19753 }
19754 }
19755 class CircleAnnotationElement extends AnnotationElement {
19756 #circle = null;
19757 constructor(parameters) {
19758 super(parameters, {
19759 isRenderable: true,
19760 ignoreBorder: true
19761 });
19762 }
19763 render() {
19764 this.container.classList.add("circleAnnotation");
19765 const data = this.data;
19766 const {
19767 width,
19768 height
19769 } = getRectDims(data.rect);
19770 const svg = this.svgFactory.create(width, height, true);
19771 const borderWidth = data.borderStyle.width;
19772 const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
19773 circle.setAttribute("cx", width / 2);
19774 circle.setAttribute("cy", height / 2);
19775 circle.setAttribute("rx", width / 2 - borderWidth / 2);
19776 circle.setAttribute("ry", height / 2 - borderWidth / 2);
19777 circle.setAttribute("stroke-width", borderWidth || 1);
19778 circle.setAttribute("stroke", "transparent");
19779 circle.setAttribute("fill", "transparent");
19780 svg.append(circle);
19781 this.container.append(svg);
19782 if (!data.popupRef && this.hasPopupData) {
19783 this._createPopup();
19784 }
19785 return this.container;
19786 }
19787 getElementsToTriggerPopup() {
19788 return this.#circle;
19789 }
19790 addHighlightArea() {
19791 this.container.classList.add("highlightArea");
19792 }
19793 }
19794 class PolylineAnnotationElement extends AnnotationElement {
19795 #polyline = null;
19796 constructor(parameters) {
19797 super(parameters, {
19798 isRenderable: true,
19799 ignoreBorder: true
19800 });
19801 this.containerClassName = "polylineAnnotation";
19802 this.svgElementName = "svg:polyline";
19803 }
19804 render() {
19805 this.container.classList.add(this.containerClassName);
19806 const data = this.data;
19807 const {
19808 width,
19809 height
19810 } = getRectDims(data.rect);
19811 const svg = this.svgFactory.create(width, height, true);
19812 let points = [];
19813 for (const coordinate of data.vertices) {
19814 const x = coordinate.x - data.rect[0];
19815 const y = data.rect[3] - coordinate.y;
19816 points.push(x + "," + y);
19817 }
19818 points = points.join(" ");
19819 const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
19820 polyline.setAttribute("points", points);
19821 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
19822 polyline.setAttribute("stroke", "transparent");
19823 polyline.setAttribute("fill", "transparent");
19824 svg.append(polyline);
19825 this.container.append(svg);
19826 if (!data.popupRef && this.hasPopupData) {
19827 this._createPopup();
19828 }
19829 return this.container;
19830 }
19831 getElementsToTriggerPopup() {
19832 return this.#polyline;
19833 }
19834 addHighlightArea() {
19835 this.container.classList.add("highlightArea");
19836 }
19837 }
19838 class PolygonAnnotationElement extends PolylineAnnotationElement {
19839 constructor(parameters) {
19840 super(parameters);
19841 this.containerClassName = "polygonAnnotation";
19842 this.svgElementName = "svg:polygon";
19843 }
19844 }
19845 class CaretAnnotationElement extends AnnotationElement {
19846 constructor(parameters) {
19847 super(parameters, {
19848 isRenderable: true,
19849 ignoreBorder: true
19850 });
19851 }
19852 render() {
19853 this.container.classList.add("caretAnnotation");
19854 if (!this.data.popupRef && this.hasPopupData) {
19855 this._createPopup();
19856 }
19857 return this.container;
19858 }
19859 }
19860 class InkAnnotationElement extends AnnotationElement {
19861 #polylines = [];
19862 constructor(parameters) {
19863 super(parameters, {
19864 isRenderable: true,
19865 ignoreBorder: true
19866 });
19867 this.containerClassName = "inkAnnotation";
19868 this.svgElementName = "svg:polyline";
19869 this.annotationEditorType = AnnotationEditorType.INK;
19870 }
19871 render() {
19872 this.container.classList.add(this.containerClassName);
19873 const data = this.data;
19874 const {
19875 width,
19876 height
19877 } = getRectDims(data.rect);
19878 const svg = this.svgFactory.create(width, height, true);
19879 for (const inkList of data.inkLists) {
19880 let points = [];
19881 for (const coordinate of inkList) {
19882 const x = coordinate.x - data.rect[0];
19883 const y = data.rect[3] - coordinate.y;
19884 points.push(`${x},${y}`);
19885 }
19886 points = points.join(" ");
19887 const polyline = this.svgFactory.createElement(this.svgElementName);
19888 this.#polylines.push(polyline);
19889 polyline.setAttribute("points", points);
19890 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
19891 polyline.setAttribute("stroke", "transparent");
19892 polyline.setAttribute("fill", "transparent");
19893 if (!data.popupRef && this.hasPopupData) {
19894 this._createPopup();
19895 }
19896 svg.append(polyline);
19897 }
19898 this.container.append(svg);
19899 return this.container;
19900 }
19901 getElementsToTriggerPopup() {
19902 return this.#polylines;
19903 }
19904 addHighlightArea() {
19905 this.container.classList.add("highlightArea");
19906 }
19907 }
19908 class HighlightAnnotationElement extends AnnotationElement {
19909 constructor(parameters) {
19910 super(parameters, {
19911 isRenderable: true,
19912 ignoreBorder: true,
19913 createQuadrilaterals: true
19914 });
19915 }
19916 render() {
19917 if (!this.data.popupRef && this.hasPopupData) {
19918 this._createPopup();
19919 }
19920 this.container.classList.add("highlightAnnotation");
19921 return this.container;
19922 }
19923 }
19924 class UnderlineAnnotationElement extends AnnotationElement {
19925 constructor(parameters) {
19926 super(parameters, {
19927 isRenderable: true,
19928 ignoreBorder: true,
19929 createQuadrilaterals: true
19930 });
19931 }
19932 render() {
19933 if (!this.data.popupRef && this.hasPopupData) {
19934 this._createPopup();
19935 }
19936 this.container.classList.add("underlineAnnotation");
19937 return this.container;
19938 }
19939 }
19940 class SquigglyAnnotationElement extends AnnotationElement {
19941 constructor(parameters) {
19942 super(parameters, {
19943 isRenderable: true,
19944 ignoreBorder: true,
19945 createQuadrilaterals: true
19946 });
19947 }
19948 render() {
19949 if (!this.data.popupRef && this.hasPopupData) {
19950 this._createPopup();
19951 }
19952 this.container.classList.add("squigglyAnnotation");
19953 return this.container;
19954 }
19955 }
19956 class StrikeOutAnnotationElement extends AnnotationElement {
19957 constructor(parameters) {
19958 super(parameters, {
19959 isRenderable: true,
19960 ignoreBorder: true,
19961 createQuadrilaterals: true
19962 });
19963 }
19964 render() {
19965 if (!this.data.popupRef && this.hasPopupData) {
19966 this._createPopup();
19967 }
19968 this.container.classList.add("strikeoutAnnotation");
19969 return this.container;
19970 }
19971 }
19972 class StampAnnotationElement extends AnnotationElement {
19973 constructor(parameters) {
19974 super(parameters, {
19975 isRenderable: true,
19976 ignoreBorder: true
19977 });
19978 }
19979 render() {
19980 this.container.classList.add("stampAnnotation");
19981 if (!this.data.popupRef && this.hasPopupData) {
19982 this._createPopup();
19983 }
19984 return this.container;
19985 }
19986 }
19987 class FileAttachmentAnnotationElement extends AnnotationElement {
19988 #trigger = null;
19989 constructor(parameters) {
19990 super(parameters, {
19991 isRenderable: true
19992 });
19993 const {
19994 file
19995 } = this.data;
19996 this.filename = file.filename;
19997 this.content = file.content;
19998 this.linkService.eventBus?.dispatch("fileattachmentannotation", {
19999 source: this,
20000 ...file
20001 });
20002 }
20003 render() {
20004 this.container.classList.add("fileAttachmentAnnotation");
20005 const {
20006 container,
20007 data
20008 } = this;
20009 let trigger;
20010 if (data.hasAppearance || data.fillAlpha === 0) {
20011 trigger = document.createElement("div");
20012 } else {
20013 trigger = document.createElement("img");
20014 trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
20015 if (data.fillAlpha && data.fillAlpha < 1) {
20016 trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
20017 }
20018 }
20019 trigger.addEventListener("dblclick", this.#download.bind(this));
20020 this.#trigger = trigger;
20021 const {
20022 isMac
20023 } = util_FeatureTest.platform;
20024 container.addEventListener("keydown", evt => {
20025 if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
20026 this.#download();
20027 }
20028 });
20029 if (!data.popupRef && this.hasPopupData) {
20030 this._createPopup();
20031 } else {
20032 trigger.classList.add("popupTriggerArea");
20033 }
20034 container.append(trigger);
20035 return container;
20036 }
20037 getElementsToTriggerPopup() {
20038 return this.#trigger;
20039 }
20040 addHighlightArea() {
20041 this.container.classList.add("highlightArea");
20042 }
20043 #download() {
20044 this.downloadManager?.openOrDownloadData(this.content, this.filename);
20045 }
20046 }
20047 class AnnotationLayer {
20048 #accessibilityManager = null;
20049 #annotationCanvasMap = null;
20050 #editableAnnotations = new Map();
20051 constructor({
20052 div,
20053 accessibilityManager,
20054 annotationCanvasMap,
20055 annotationEditorUIManager,
20056 page,
20057 viewport
20058 }) {
20059 this.div = div;
20060 this.#accessibilityManager = accessibilityManager;
20061 this.#annotationCanvasMap = annotationCanvasMap;
20062 this.page = page;
20063 this.viewport = viewport;
20064 this.zIndex = 0;
20065 this._annotationEditorUIManager = annotationEditorUIManager;
20066 }
20067 #appendElement(element, id) {
20068 const contentElement = element.firstChild || element;
20069 contentElement.id = `${AnnotationPrefix}${id}`;
20070 this.div.append(element);
20071 this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
20072 }
20073 async render(params) {
20074 const {
20075 annotations
20076 } = params;
20077 const layer = this.div;
20078 setLayerDimensions(layer, this.viewport);
20079 const popupToElements = new Map();
20080 const elementParams = {
20081 data: null,
20082 layer,
20083 linkService: params.linkService,
20084 downloadManager: params.downloadManager,
20085 imageResourcesPath: params.imageResourcesPath || "",
20086 renderForms: params.renderForms !== false,
20087 svgFactory: new DOMSVGFactory(),
20088 annotationStorage: params.annotationStorage || new AnnotationStorage(),
20089 enableScripting: params.enableScripting === true,
20090 hasJSActions: params.hasJSActions,
20091 fieldObjects: params.fieldObjects,
20092 parent: this,
20093 elements: null
20094 };
20095 for (const data of annotations) {
20096 if (data.noHTML) {
20097 continue;
20098 }
20099 const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
20100 if (!isPopupAnnotation) {
20101 const {
20102 width,
20103 height
20104 } = getRectDims(data.rect);
20105 if (width <= 0 || height <= 0) {
20106 continue;
20107 }
20108 } else {
20109 const elements = popupToElements.get(data.id);
20110 if (!elements) {
20111 continue;
20112 }
20113 elementParams.elements = elements;
20114 }
20115 elementParams.data = data;
20116 const element = AnnotationElementFactory.create(elementParams);
20117 if (!element.isRenderable) {
20118 continue;
20119 }
20120 if (!isPopupAnnotation && data.popupRef) {
20121 const elements = popupToElements.get(data.popupRef);
20122 if (!elements) {
20123 popupToElements.set(data.popupRef, [element]);
20124 } else {
20125 elements.push(element);
20126 }
20127 }
20128 const rendered = element.render();
20129 if (data.hidden) {
20130 rendered.style.visibility = "hidden";
20131 }
20132 this.#appendElement(rendered, data.id);
20133 if (element.annotationEditorType > 0) {
20134 this.#editableAnnotations.set(element.data.id, element);
20135 this._annotationEditorUIManager?.renderAnnotationElement(element);
20136 }
20137 }
20138 this.#setAnnotationCanvasMap();
20139 }
20140 update({
20141 viewport
20142 }) {
20143 const layer = this.div;
20144 this.viewport = viewport;
20145 setLayerDimensions(layer, {
20146 rotation: viewport.rotation
20147 });
20148 this.#setAnnotationCanvasMap();
20149 layer.hidden = false;
20150 }
20151 #setAnnotationCanvasMap() {
20152 if (!this.#annotationCanvasMap) {
20153 return;
20154 }
20155 const layer = this.div;
20156 for (const [id, canvas] of this.#annotationCanvasMap) {
20157 const element = layer.querySelector(`[data-annotation-id="${id}"]`);
20158 if (!element) {
20159 continue;
20160 }
20161 canvas.className = "annotationContent";
20162 const {
20163 firstChild
20164 } = element;
20165 if (!firstChild) {
20166 element.append(canvas);
20167 } else if (firstChild.nodeName === "CANVAS") {
20168 firstChild.replaceWith(canvas);
20169 } else if (!firstChild.classList.contains("annotationContent")) {
20170 firstChild.before(canvas);
20171 } else {
20172 firstChild.after(canvas);
20173 }
20174 }
20175 this.#annotationCanvasMap.clear();
20176 }
20177 getEditableAnnotations() {
20178 return Array.from(this.#editableAnnotations.values());
20179 }
20180 getEditableAnnotation(id) {
20181 return this.#editableAnnotations.get(id);
20182 }
20183 }
20184
20185 ;// CONCATENATED MODULE: ./src/display/editor/freetext.js
20186
20187
20188
20189
20190
20191
20192
20193 const EOL_PATTERN = /\r\n?|\n/g;
20194 class FreeTextEditor extends AnnotationEditor {
20195 #boundEditorDivBlur = this.editorDivBlur.bind(this);
20196 #boundEditorDivFocus = this.editorDivFocus.bind(this);
20197 #boundEditorDivInput = this.editorDivInput.bind(this);
20198 #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
20199 #boundEditorDivPaste = this.editorDivPaste.bind(this);
20200 #color;
20201 #content = "";
20202 #editorDivId = `${this.id}-editor`;
20203 #fontSize;
20204 #initialData = null;
20205 static _freeTextDefaultContent = "";
20206 static _internalPadding = 0;
20207 static _defaultColor = null;
20208 static _defaultFontSize = 10;
20209 static get _keyboardManager() {
20210 const proto = FreeTextEditor.prototype;
20211 const arrowChecker = self => self.isEmpty();
20212 const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
20213 const big = AnnotationEditorUIManager.TRANSLATE_BIG;
20214 return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
20215 bubbles: true
20216 }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
20217 args: [-small, 0],
20218 checker: arrowChecker
20219 }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
20220 args: [-big, 0],
20221 checker: arrowChecker
20222 }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
20223 args: [small, 0],
20224 checker: arrowChecker
20225 }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
20226 args: [big, 0],
20227 checker: arrowChecker
20228 }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
20229 args: [0, -small],
20230 checker: arrowChecker
20231 }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
20232 args: [0, -big],
20233 checker: arrowChecker
20234 }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
20235 args: [0, small],
20236 checker: arrowChecker
20237 }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
20238 args: [0, big],
20239 checker: arrowChecker
20240 }]]));
20241 }
20242 static _type = "freetext";
20243 static _editorType = AnnotationEditorType.FREETEXT;
20244 constructor(params) {
20245 super({
20246 ...params,
20247 name: "freeTextEditor"
20248 });
20249 this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
20250 this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
20251 }
20252 static initialize(l10n, uiManager) {
20253 AnnotationEditor.initialize(l10n, uiManager, {
20254 strings: ["pdfjs-free-text-default-content"]
20255 });
20256 const style = getComputedStyle(document.documentElement);
20257 this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
20258 }
20259 static updateDefaultParams(type, value) {
20260 switch (type) {
20261 case AnnotationEditorParamsType.FREETEXT_SIZE:
20262 FreeTextEditor._defaultFontSize = value;
20263 break;
20264 case AnnotationEditorParamsType.FREETEXT_COLOR:
20265 FreeTextEditor._defaultColor = value;
20266 break;
20267 }
20268 }
20269 updateParams(type, value) {
20270 switch (type) {
20271 case AnnotationEditorParamsType.FREETEXT_SIZE:
20272 this.#updateFontSize(value);
20273 break;
20274 case AnnotationEditorParamsType.FREETEXT_COLOR:
20275 this.#updateColor(value);
20276 break;
20277 }
20278 }
20279 static get defaultPropertiesToUpdate() {
20280 return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
20281 }
20282 get propertiesToUpdate() {
20283 return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
20284 }
20285 #updateFontSize(fontSize) {
20286 const setFontsize = size => {
20287 this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
20288 this.translate(0, -(size - this.#fontSize) * this.parentScale);
20289 this.#fontSize = size;
20290 this.#setEditorDimensions();
20291 };
20292 const savedFontsize = this.#fontSize;
20293 this.addCommands({
20294 cmd: setFontsize.bind(this, fontSize),
20295 undo: setFontsize.bind(this, savedFontsize),
20296 post: this._uiManager.updateUI.bind(this._uiManager, this),
20297 mustExec: true,
20298 type: AnnotationEditorParamsType.FREETEXT_SIZE,
20299 overwriteIfSameType: true,
20300 keepUndo: true
20301 });
20302 }
20303 #updateColor(color) {
20304 const setColor = col => {
20305 this.#color = this.editorDiv.style.color = col;
20306 };
20307 const savedColor = this.#color;
20308 this.addCommands({
20309 cmd: setColor.bind(this, color),
20310 undo: setColor.bind(this, savedColor),
20311 post: this._uiManager.updateUI.bind(this._uiManager, this),
20312 mustExec: true,
20313 type: AnnotationEditorParamsType.FREETEXT_COLOR,
20314 overwriteIfSameType: true,
20315 keepUndo: true
20316 });
20317 }
20318 _translateEmpty(x, y) {
20319 this._uiManager.translateSelectedEditors(x, y, true);
20320 }
20321 getInitialTranslation() {
20322 const scale = this.parentScale;
20323 return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
20324 }
20325 rebuild() {
20326 if (!this.parent) {
20327 return;
20328 }
20329 super.rebuild();
20330 if (this.div === null) {
20331 return;
20332 }
20333 if (!this.isAttachedToDOM) {
20334 this.parent.add(this);
20335 }
20336 }
20337 enableEditMode() {
20338 if (this.isInEditMode()) {
20339 return;
20340 }
20341 this.parent.setEditingState(false);
20342 this.parent.updateToolbar(AnnotationEditorType.FREETEXT);
20343 super.enableEditMode();
20344 this.overlayDiv.classList.remove("enabled");
20345 this.editorDiv.contentEditable = true;
20346 this._isDraggable = false;
20347 this.div.removeAttribute("aria-activedescendant");
20348 this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
20349 this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
20350 this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
20351 this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
20352 this.editorDiv.addEventListener("paste", this.#boundEditorDivPaste);
20353 }
20354 disableEditMode() {
20355 if (!this.isInEditMode()) {
20356 return;
20357 }
20358 this.parent.setEditingState(true);
20359 super.disableEditMode();
20360 this.overlayDiv.classList.add("enabled");
20361 this.editorDiv.contentEditable = false;
20362 this.div.setAttribute("aria-activedescendant", this.#editorDivId);
20363 this._isDraggable = true;
20364 this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
20365 this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
20366 this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
20367 this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
20368 this.editorDiv.removeEventListener("paste", this.#boundEditorDivPaste);
20369 this.div.focus({
20370 preventScroll: true
20371 });
20372 this.isEditing = false;
20373 this.parent.div.classList.add("freetextEditing");
20374 }
20375 focusin(event) {
20376 if (!this._focusEventsAllowed) {
20377 return;
20378 }
20379 super.focusin(event);
20380 if (event.target !== this.editorDiv) {
20381 this.editorDiv.focus();
20382 }
20383 }
20384 onceAdded() {
20385 if (this.width) {
20386 return;
20387 }
20388 this.enableEditMode();
20389 this.editorDiv.focus();
20390 if (this._initialOptions?.isCentered) {
20391 this.center();
20392 }
20393 this._initialOptions = null;
20394 }
20395 isEmpty() {
20396 return !this.editorDiv || this.editorDiv.innerText.trim() === "";
20397 }
20398 remove() {
20399 this.isEditing = false;
20400 if (this.parent) {
20401 this.parent.setEditingState(true);
20402 this.parent.div.classList.add("freetextEditing");
20403 }
20404 super.remove();
20405 }
20406 #extractText() {
20407 const buffer = [];
20408 this.editorDiv.normalize();
20409 for (const child of this.editorDiv.childNodes) {
20410 buffer.push(FreeTextEditor.#getNodeContent(child));
20411 }
20412 return buffer.join("\n");
20413 }
20414 #setEditorDimensions() {
20415 const [parentWidth, parentHeight] = this.parentDimensions;
20416 let rect;
20417 if (this.isAttachedToDOM) {
20418 rect = this.div.getBoundingClientRect();
20419 } else {
20420 const {
20421 currentLayer,
20422 div
20423 } = this;
20424 const savedDisplay = div.style.display;
20425 const savedVisibility = div.classList.contains("hidden");
20426 div.classList.remove("hidden");
20427 div.style.display = "hidden";
20428 currentLayer.div.append(this.div);
20429 rect = div.getBoundingClientRect();
20430 div.remove();
20431 div.style.display = savedDisplay;
20432 div.classList.toggle("hidden", savedVisibility);
20433 }
20434 if (this.rotation % 180 === this.parentRotation % 180) {
20435 this.width = rect.width / parentWidth;
20436 this.height = rect.height / parentHeight;
20437 } else {
20438 this.width = rect.height / parentWidth;
20439 this.height = rect.width / parentHeight;
20440 }
20441 this.fixAndSetPosition();
20442 }
20443 commit() {
20444 if (!this.isInEditMode()) {
20445 return;
20446 }
20447 super.commit();
20448 this.disableEditMode();
20449 const savedText = this.#content;
20450 const newText = this.#content = this.#extractText().trimEnd();
20451 if (savedText === newText) {
20452 return;
20453 }
20454 const setText = text => {
20455 this.#content = text;
20456 if (!text) {
20457 this.remove();
20458 return;
20459 }
20460 this.#setContent();
20461 this._uiManager.rebuild(this);
20462 this.#setEditorDimensions();
20463 };
20464 this.addCommands({
20465 cmd: () => {
20466 setText(newText);
20467 },
20468 undo: () => {
20469 setText(savedText);
20470 },
20471 mustExec: false
20472 });
20473 this.#setEditorDimensions();
20474 }
20475 shouldGetKeyboardEvents() {
20476 return this.isInEditMode();
20477 }
20478 enterInEditMode() {
20479 this.enableEditMode();
20480 this.editorDiv.focus();
20481 }
20482 dblclick(event) {
20483 this.enterInEditMode();
20484 }
20485 keydown(event) {
20486 if (event.target === this.div && event.key === "Enter") {
20487 this.enterInEditMode();
20488 event.preventDefault();
20489 }
20490 }
20491 editorDivKeydown(event) {
20492 FreeTextEditor._keyboardManager.exec(this, event);
20493 }
20494 editorDivFocus(event) {
20495 this.isEditing = true;
20496 }
20497 editorDivBlur(event) {
20498 this.isEditing = false;
20499 }
20500 editorDivInput(event) {
20501 this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
20502 }
20503 disableEditing() {
20504 this.editorDiv.setAttribute("role", "comment");
20505 this.editorDiv.removeAttribute("aria-multiline");
20506 }
20507 enableEditing() {
20508 this.editorDiv.setAttribute("role", "textbox");
20509 this.editorDiv.setAttribute("aria-multiline", true);
20510 }
20511 render() {
20512 if (this.div) {
20513 return this.div;
20514 }
20515 let baseX, baseY;
20516 if (this.width) {
20517 baseX = this.x;
20518 baseY = this.y;
20519 }
20520 super.render();
20521 this.editorDiv = document.createElement("div");
20522 this.editorDiv.className = "internal";
20523 this.editorDiv.setAttribute("id", this.#editorDivId);
20524 this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text");
20525 this.enableEditing();
20526 AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
20527 this.editorDiv.contentEditable = true;
20528 const {
20529 style
20530 } = this.editorDiv;
20531 style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
20532 style.color = this.#color;
20533 this.div.append(this.editorDiv);
20534 this.overlayDiv = document.createElement("div");
20535 this.overlayDiv.classList.add("overlay", "enabled");
20536 this.div.append(this.overlayDiv);
20537 bindEvents(this, this.div, ["dblclick", "keydown"]);
20538 if (this.width) {
20539 const [parentWidth, parentHeight] = this.parentDimensions;
20540 if (this.annotationElementId) {
20541 const {
20542 position
20543 } = this.#initialData;
20544 let [tx, ty] = this.getInitialTranslation();
20545 [tx, ty] = this.pageTranslationToScreen(tx, ty);
20546 const [pageWidth, pageHeight] = this.pageDimensions;
20547 const [pageX, pageY] = this.pageTranslation;
20548 let posX, posY;
20549 switch (this.rotation) {
20550 case 0:
20551 posX = baseX + (position[0] - pageX) / pageWidth;
20552 posY = baseY + this.height - (position[1] - pageY) / pageHeight;
20553 break;
20554 case 90:
20555 posX = baseX + (position[0] - pageX) / pageWidth;
20556 posY = baseY - (position[1] - pageY) / pageHeight;
20557 [tx, ty] = [ty, -tx];
20558 break;
20559 case 180:
20560 posX = baseX - this.width + (position[0] - pageX) / pageWidth;
20561 posY = baseY - (position[1] - pageY) / pageHeight;
20562 [tx, ty] = [-tx, -ty];
20563 break;
20564 case 270:
20565 posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
20566 posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
20567 [tx, ty] = [-ty, tx];
20568 break;
20569 }
20570 this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
20571 } else {
20572 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
20573 }
20574 this.#setContent();
20575 this._isDraggable = true;
20576 this.editorDiv.contentEditable = false;
20577 } else {
20578 this._isDraggable = false;
20579 this.editorDiv.contentEditable = true;
20580 }
20581 return this.div;
20582 }
20583 static #getNodeContent(node) {
20584 return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
20585 }
20586 editorDivPaste(event) {
20587 const clipboardData = event.clipboardData || window.clipboardData;
20588 const {
20589 types
20590 } = clipboardData;
20591 if (types.length === 1 && types[0] === "text/plain") {
20592 return;
20593 }
20594 event.preventDefault();
20595 const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
20596 if (!paste) {
20597 return;
20598 }
20599 const selection = window.getSelection();
20600 if (!selection.rangeCount) {
20601 return;
20602 }
20603 this.editorDiv.normalize();
20604 selection.deleteFromDocument();
20605 const range = selection.getRangeAt(0);
20606 if (!paste.includes("\n")) {
20607 range.insertNode(document.createTextNode(paste));
20608 this.editorDiv.normalize();
20609 selection.collapseToStart();
20610 return;
20611 }
20612 const {
20613 startContainer,
20614 startOffset
20615 } = range;
20616 const bufferBefore = [];
20617 const bufferAfter = [];
20618 if (startContainer.nodeType === Node.TEXT_NODE) {
20619 const parent = startContainer.parentElement;
20620 bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
20621 if (parent !== this.editorDiv) {
20622 let buffer = bufferBefore;
20623 for (const child of this.editorDiv.childNodes) {
20624 if (child === parent) {
20625 buffer = bufferAfter;
20626 continue;
20627 }
20628 buffer.push(FreeTextEditor.#getNodeContent(child));
20629 }
20630 }
20631 bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
20632 } else if (startContainer === this.editorDiv) {
20633 let buffer = bufferBefore;
20634 let i = 0;
20635 for (const child of this.editorDiv.childNodes) {
20636 if (i++ === startOffset) {
20637 buffer = bufferAfter;
20638 }
20639 buffer.push(FreeTextEditor.#getNodeContent(child));
20640 }
20641 }
20642 this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
20643 this.#setContent();
20644 const newRange = new Range();
20645 let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0);
20646 for (const {
20647 firstChild
20648 } of this.editorDiv.childNodes) {
20649 if (firstChild.nodeType === Node.TEXT_NODE) {
20650 const length = firstChild.nodeValue.length;
20651 if (beforeLength <= length) {
20652 newRange.setStart(firstChild, beforeLength);
20653 newRange.setEnd(firstChild, beforeLength);
20654 break;
20655 }
20656 beforeLength -= length;
20657 }
20658 }
20659 selection.removeAllRanges();
20660 selection.addRange(newRange);
20661 }
20662 #setContent() {
20663 this.editorDiv.replaceChildren();
20664 if (!this.#content) {
20665 return;
20666 }
20667 for (const line of this.#content.split("\n")) {
20668 const div = document.createElement("div");
20669 div.append(line ? document.createTextNode(line) : document.createElement("br"));
20670 this.editorDiv.append(div);
20671 }
20672 }
20673 #serializeContent() {
20674 return this.#content.replaceAll("\xa0", " ");
20675 }
20676 static #deserializeContent(content) {
20677 return content.replaceAll(" ", "\xa0");
20678 }
20679 get contentDiv() {
20680 return this.editorDiv;
20681 }
20682 static deserialize(data, parent, uiManager) {
20683 let initialData = null;
20684 if (data instanceof FreeTextAnnotationElement) {
20685 const {
20686 data: {
20687 defaultAppearanceData: {
20688 fontSize,
20689 fontColor
20690 },
20691 rect,
20692 rotation,
20693 id
20694 },
20695 textContent,
20696 textPosition,
20697 parent: {
20698 page: {
20699 pageNumber
20700 }
20701 }
20702 } = data;
20703 if (!textContent || textContent.length === 0) {
20704 return null;
20705 }
20706 initialData = data = {
20707 annotationType: AnnotationEditorType.FREETEXT,
20708 color: Array.from(fontColor),
20709 fontSize,
20710 value: textContent.join("\n"),
20711 position: textPosition,
20712 pageIndex: pageNumber - 1,
20713 rect: rect.slice(0),
20714 rotation,
20715 id,
20716 deleted: false
20717 };
20718 }
20719 const editor = super.deserialize(data, parent, uiManager);
20720 editor.#fontSize = data.fontSize;
20721 editor.#color = Util.makeHexColor(...data.color);
20722 editor.#content = FreeTextEditor.#deserializeContent(data.value);
20723 editor.annotationElementId = data.id || null;
20724 editor.#initialData = initialData;
20725 return editor;
20726 }
20727 serialize(isForCopying = false) {
20728 if (this.isEmpty()) {
20729 return null;
20730 }
20731 if (this.deleted) {
20732 return {
20733 pageIndex: this.pageIndex,
20734 id: this.annotationElementId,
20735 deleted: true
20736 };
20737 }
20738 const padding = FreeTextEditor._internalPadding * this.parentScale;
20739 const rect = this.getRect(padding, padding);
20740 const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
20741 const serialized = {
20742 annotationType: AnnotationEditorType.FREETEXT,
20743 color,
20744 fontSize: this.#fontSize,
20745 value: this.#serializeContent(),
20746 pageIndex: this.pageIndex,
20747 rect,
20748 rotation: this.rotation,
20749 structTreeParentId: this._structTreeParentId
20750 };
20751 if (isForCopying) {
20752 return serialized;
20753 }
20754 if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
20755 return null;
20756 }
20757 serialized.id = this.annotationElementId;
20758 return serialized;
20759 }
20760 #hasElementChanged(serialized) {
20761 const {
20762 value,
20763 fontSize,
20764 color,
20765 pageIndex
20766 } = this.#initialData;
20767 return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
20768 }
20769 renderAnnotationElement(annotation) {
20770 const content = super.renderAnnotationElement(annotation);
20771 if (this.deleted) {
20772 return content;
20773 }
20774 const {
20775 style
20776 } = content;
20777 style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
20778 style.color = this.#color;
20779 content.replaceChildren();
20780 for (const line of this.#content.split("\n")) {
20781 const div = document.createElement("div");
20782 div.append(line ? document.createTextNode(line) : document.createElement("br"));
20783 content.append(div);
20784 }
20785 const padding = FreeTextEditor._internalPadding * this.parentScale;
20786 annotation.updateEdited({
20787 rect: this.getRect(padding, padding),
20788 popupContent: this.#content
20789 });
20790 return content;
20791 }
20792 resetAnnotationElement(annotation) {
20793 super.resetAnnotationElement(annotation);
20794 annotation.resetEdited();
20795 }
20796 }
20797
20798 ;// CONCATENATED MODULE: ./src/display/editor/outliner.js
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814 class Outliner {
20815 #box;
20816 #verticalEdges = [];
20817 #intervals = [];
20818 constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
20819 let minX = Infinity;
20820 let maxX = -Infinity;
20821 let minY = Infinity;
20822 let maxY = -Infinity;
20823 const NUMBER_OF_DIGITS = 4;
20824 const EPSILON = 10 ** -NUMBER_OF_DIGITS;
20825 for (const {
20826 x,
20827 y,
20828 width,
20829 height
20830 } of boxes) {
20831 const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
20832 const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
20833 const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
20834 const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
20835 const left = [x1, y1, y2, true];
20836 const right = [x2, y1, y2, false];
20837 this.#verticalEdges.push(left, right);
20838 minX = Math.min(minX, x1);
20839 maxX = Math.max(maxX, x2);
20840 minY = Math.min(minY, y1);
20841 maxY = Math.max(maxY, y2);
20842 }
20843 const bboxWidth = maxX - minX + 2 * innerMargin;
20844 const bboxHeight = maxY - minY + 2 * innerMargin;
20845 const shiftedMinX = minX - innerMargin;
20846 const shiftedMinY = minY - innerMargin;
20847 const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
20848 const lastPoint = [lastEdge[0], lastEdge[2]];
20849 for (const edge of this.#verticalEdges) {
20850 const [x, y1, y2] = edge;
20851 edge[0] = (x - shiftedMinX) / bboxWidth;
20852 edge[1] = (y1 - shiftedMinY) / bboxHeight;
20853 edge[2] = (y2 - shiftedMinY) / bboxHeight;
20854 }
20855 this.#box = {
20856 x: shiftedMinX,
20857 y: shiftedMinY,
20858 width: bboxWidth,
20859 height: bboxHeight,
20860 lastPoint
20861 };
20862 }
20863 getOutlines() {
20864 this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
20865 const outlineVerticalEdges = [];
20866 for (const edge of this.#verticalEdges) {
20867 if (edge[3]) {
20868 outlineVerticalEdges.push(...this.#breakEdge(edge));
20869 this.#insert(edge);
20870 } else {
20871 this.#remove(edge);
20872 outlineVerticalEdges.push(...this.#breakEdge(edge));
20873 }
20874 }
20875 return this.#getOutlines(outlineVerticalEdges);
20876 }
20877 #getOutlines(outlineVerticalEdges) {
20878 const edges = [];
20879 const allEdges = new Set();
20880 for (const edge of outlineVerticalEdges) {
20881 const [x, y1, y2] = edge;
20882 edges.push([x, y1, edge], [x, y2, edge]);
20883 }
20884 edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
20885 for (let i = 0, ii = edges.length; i < ii; i += 2) {
20886 const edge1 = edges[i][2];
20887 const edge2 = edges[i + 1][2];
20888 edge1.push(edge2);
20889 edge2.push(edge1);
20890 allEdges.add(edge1);
20891 allEdges.add(edge2);
20892 }
20893 const outlines = [];
20894 let outline;
20895 while (allEdges.size > 0) {
20896 const edge = allEdges.values().next().value;
20897 let [x, y1, y2, edge1, edge2] = edge;
20898 allEdges.delete(edge);
20899 let lastPointX = x;
20900 let lastPointY = y1;
20901 outline = [x, y2];
20902 outlines.push(outline);
20903 while (true) {
20904 let e;
20905 if (allEdges.has(edge1)) {
20906 e = edge1;
20907 } else if (allEdges.has(edge2)) {
20908 e = edge2;
20909 } else {
20910 break;
20911 }
20912 allEdges.delete(e);
20913 [x, y1, y2, edge1, edge2] = e;
20914 if (lastPointX !== x) {
20915 outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
20916 lastPointX = x;
20917 }
20918 lastPointY = lastPointY === y1 ? y2 : y1;
20919 }
20920 outline.push(lastPointX, lastPointY);
20921 }
20922 return new HighlightOutline(outlines, this.#box);
20923 }
20924 #binarySearch(y) {
20925 const array = this.#intervals;
20926 let start = 0;
20927 let end = array.length - 1;
20928 while (start <= end) {
20929 const middle = start + end >> 1;
20930 const y1 = array[middle][0];
20931 if (y1 === y) {
20932 return middle;
20933 }
20934 if (y1 < y) {
20935 start = middle + 1;
20936 } else {
20937 end = middle - 1;
20938 }
20939 }
20940 return end + 1;
20941 }
20942 #insert([, y1, y2]) {
20943 const index = this.#binarySearch(y1);
20944 this.#intervals.splice(index, 0, [y1, y2]);
20945 }
20946 #remove([, y1, y2]) {
20947 const index = this.#binarySearch(y1);
20948 for (let i = index; i < this.#intervals.length; i++) {
20949 const [start, end] = this.#intervals[i];
20950 if (start !== y1) {
20951 break;
20952 }
20953 if (start === y1 && end === y2) {
20954 this.#intervals.splice(i, 1);
20955 return;
20956 }
20957 }
20958 for (let i = index - 1; i >= 0; i--) {
20959 const [start, end] = this.#intervals[i];
20960 if (start !== y1) {
20961 break;
20962 }
20963 if (start === y1 && end === y2) {
20964 this.#intervals.splice(i, 1);
20965 return;
20966 }
20967 }
20968 }
20969 #breakEdge(edge) {
20970 const [x, y1, y2] = edge;
20971 const results = [[x, y1, y2]];
20972 const index = this.#binarySearch(y2);
20973 for (let i = 0; i < index; i++) {
20974 const [start, end] = this.#intervals[i];
20975 for (let j = 0, jj = results.length; j < jj; j++) {
20976 const [, y3, y4] = results[j];
20977 if (end <= y3 || y4 <= start) {
20978 continue;
20979 }
20980 if (y3 >= start) {
20981 if (y4 > end) {
20982 results[j][1] = end;
20983 } else {
20984 if (jj === 1) {
20985 return [];
20986 }
20987 results.splice(j, 1);
20988 j--;
20989 jj--;
20990 }
20991 continue;
20992 }
20993 results[j][2] = start;
20994 if (y4 > end) {
20995 results.push([x, end, y4]);
20996 }
20997 }
20998 }
20999 return results;
21000 }
21001 }
21002 class Outline {
21003 toSVGPath() {
21004 throw new Error("Abstract method `toSVGPath` must be implemented.");
21005 }
21006 get box() {
21007 throw new Error("Abstract getter `box` must be implemented.");
21008 }
21009 serialize(_bbox, _rotation) {
21010 throw new Error("Abstract method `serialize` must be implemented.");
21011 }
21012 get free() {
21013 return this instanceof FreeHighlightOutline;
21014 }
21015 }
21016 class HighlightOutline extends Outline {
21017 #box;
21018 #outlines;
21019 constructor(outlines, box) {
21020 super();
21021 this.#outlines = outlines;
21022 this.#box = box;
21023 }
21024 toSVGPath() {
21025 const buffer = [];
21026 for (const polygon of this.#outlines) {
21027 let [prevX, prevY] = polygon;
21028 buffer.push(`M${prevX} ${prevY}`);
21029 for (let i = 2; i < polygon.length; i += 2) {
21030 const x = polygon[i];
21031 const y = polygon[i + 1];
21032 if (x === prevX) {
21033 buffer.push(`V${y}`);
21034 prevY = y;
21035 } else if (y === prevY) {
21036 buffer.push(`H${x}`);
21037 prevX = x;
21038 }
21039 }
21040 buffer.push("Z");
21041 }
21042 return buffer.join(" ");
21043 }
21044 serialize([blX, blY, trX, trY], _rotation) {
21045 const outlines = [];
21046 const width = trX - blX;
21047 const height = trY - blY;
21048 for (const outline of this.#outlines) {
21049 const points = new Array(outline.length);
21050 for (let i = 0; i < outline.length; i += 2) {
21051 points[i] = blX + outline[i] * width;
21052 points[i + 1] = trY - outline[i + 1] * height;
21053 }
21054 outlines.push(points);
21055 }
21056 return outlines;
21057 }
21058 get box() {
21059 return this.#box;
21060 }
21061 }
21062 class FreeOutliner {
21063 #box;
21064 #bottom = [];
21065 #innerMargin;
21066 #isLTR;
21067 #top = [];
21068 #last = new Float64Array(18);
21069 #lastX;
21070 #lastY;
21071 #min;
21072 #min_dist;
21073 #scaleFactor;
21074 #thickness;
21075 #points = [];
21076 static #MIN_DIST = 8;
21077 static #MIN_DIFF = 2;
21078 static #MIN = FreeOutliner.#MIN_DIST + FreeOutliner.#MIN_DIFF;
21079 constructor({
21080 x,
21081 y
21082 }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
21083 this.#box = box;
21084 this.#thickness = thickness * scaleFactor;
21085 this.#isLTR = isLTR;
21086 this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
21087 this.#innerMargin = innerMargin;
21088 this.#min_dist = FreeOutliner.#MIN_DIST * scaleFactor;
21089 this.#min = FreeOutliner.#MIN * scaleFactor;
21090 this.#scaleFactor = scaleFactor;
21091 this.#points.push(x, y);
21092 }
21093 get free() {
21094 return true;
21095 }
21096 isEmpty() {
21097 return isNaN(this.#last[8]);
21098 }
21099 #getLastCoords() {
21100 const lastTop = this.#last.subarray(4, 6);
21101 const lastBottom = this.#last.subarray(16, 18);
21102 const [x, y, width, height] = this.#box;
21103 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];
21104 }
21105 add({
21106 x,
21107 y
21108 }) {
21109 this.#lastX = x;
21110 this.#lastY = y;
21111 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
21112 let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
21113 const diffX = x - x2;
21114 const diffY = y - y2;
21115 const d = Math.hypot(diffX, diffY);
21116 if (d < this.#min) {
21117 return false;
21118 }
21119 const diffD = d - this.#min_dist;
21120 const K = diffD / d;
21121 const shiftX = K * diffX;
21122 const shiftY = K * diffY;
21123 let x0 = x1;
21124 let y0 = y1;
21125 x1 = x2;
21126 y1 = y2;
21127 x2 += shiftX;
21128 y2 += shiftY;
21129 this.#points?.push(x, y);
21130 const nX = -shiftY / diffD;
21131 const nY = shiftX / diffD;
21132 const thX = nX * this.#thickness;
21133 const thY = nY * this.#thickness;
21134 this.#last.set(this.#last.subarray(2, 8), 0);
21135 this.#last.set([x2 + thX, y2 + thY], 4);
21136 this.#last.set(this.#last.subarray(14, 18), 12);
21137 this.#last.set([x2 - thX, y2 - thY], 16);
21138 if (isNaN(this.#last[6])) {
21139 if (this.#top.length === 0) {
21140 this.#last.set([x1 + thX, y1 + thY], 2);
21141 this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
21142 this.#last.set([x1 - thX, y1 - thY], 14);
21143 this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
21144 }
21145 this.#last.set([x0, y0, x1, y1, x2, y2], 6);
21146 return !this.isEmpty();
21147 }
21148 this.#last.set([x0, y0, x1, y1, x2, y2], 6);
21149 const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
21150 if (angle < Math.PI / 2) {
21151 [x1, y1, x2, y2] = this.#last.subarray(2, 6);
21152 this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
21153 [x1, y1, x0, y0] = this.#last.subarray(14, 18);
21154 this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
21155 return true;
21156 }
21157 [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
21158 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);
21159 [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
21160 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);
21161 return true;
21162 }
21163 toSVGPath() {
21164 if (this.isEmpty()) {
21165 return "";
21166 }
21167 const top = this.#top;
21168 const bottom = this.#bottom;
21169 const lastTop = this.#last.subarray(4, 6);
21170 const lastBottom = this.#last.subarray(16, 18);
21171 const [x, y, width, height] = this.#box;
21172 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
21173 if (isNaN(this.#last[6]) && !this.isEmpty()) {
21174 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`;
21175 }
21176 const buffer = [];
21177 buffer.push(`M${top[4]} ${top[5]}`);
21178 for (let i = 6; i < top.length; i += 6) {
21179 if (isNaN(top[i])) {
21180 buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
21181 } else {
21182 buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
21183 }
21184 }
21185 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}`);
21186 for (let i = bottom.length - 6; i >= 6; i -= 6) {
21187 if (isNaN(bottom[i])) {
21188 buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
21189 } else {
21190 buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
21191 }
21192 }
21193 buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
21194 return buffer.join(" ");
21195 }
21196 getOutlines() {
21197 const top = this.#top;
21198 const bottom = this.#bottom;
21199 const last = this.#last;
21200 const lastTop = last.subarray(4, 6);
21201 const lastBottom = last.subarray(16, 18);
21202 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
21203 const points = new Float64Array((this.#points?.length ?? 0) + 2);
21204 for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
21205 points[i] = (this.#points[i] - layerX) / layerWidth;
21206 points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
21207 }
21208 points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
21209 points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
21210 const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
21211 if (isNaN(last[6]) && !this.isEmpty()) {
21212 const outline = new Float64Array(36);
21213 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);
21214 return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
21215 }
21216 const outline = new Float64Array(this.#top.length + 24 + this.#bottom.length);
21217 let N = top.length;
21218 for (let i = 0; i < N; i += 2) {
21219 if (isNaN(top[i])) {
21220 outline[i] = outline[i + 1] = NaN;
21221 continue;
21222 }
21223 outline[i] = top[i];
21224 outline[i + 1] = top[i + 1];
21225 }
21226 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], N);
21227 N += 24;
21228 for (let i = bottom.length - 6; i >= 6; i -= 6) {
21229 for (let j = 0; j < 6; j += 2) {
21230 if (isNaN(bottom[i + j])) {
21231 outline[N] = outline[N + 1] = NaN;
21232 N += 2;
21233 continue;
21234 }
21235 outline[N] = bottom[i + j];
21236 outline[N + 1] = bottom[i + j + 1];
21237 N += 2;
21238 }
21239 }
21240 outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], N);
21241 return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
21242 }
21243 }
21244 class FreeHighlightOutline extends Outline {
21245 #box;
21246 #bbox = null;
21247 #innerMargin;
21248 #isLTR;
21249 #points;
21250 #scaleFactor;
21251 #outline;
21252 constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
21253 super();
21254 this.#outline = outline;
21255 this.#points = points;
21256 this.#box = box;
21257 this.#scaleFactor = scaleFactor;
21258 this.#innerMargin = innerMargin;
21259 this.#isLTR = isLTR;
21260 this.#computeMinMax(isLTR);
21261 const {
21262 x,
21263 y,
21264 width,
21265 height
21266 } = this.#bbox;
21267 for (let i = 0, ii = outline.length; i < ii; i += 2) {
21268 outline[i] = (outline[i] - x) / width;
21269 outline[i + 1] = (outline[i + 1] - y) / height;
21270 }
21271 for (let i = 0, ii = points.length; i < ii; i += 2) {
21272 points[i] = (points[i] - x) / width;
21273 points[i + 1] = (points[i + 1] - y) / height;
21274 }
21275 }
21276 toSVGPath() {
21277 const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
21278 for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
21279 if (isNaN(this.#outline[i])) {
21280 buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
21281 continue;
21282 }
21283 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]}`);
21284 }
21285 buffer.push("Z");
21286 return buffer.join(" ");
21287 }
21288 serialize([blX, blY, trX, trY], rotation) {
21289 const width = trX - blX;
21290 const height = trY - blY;
21291 let outline;
21292 let points;
21293 switch (rotation) {
21294 case 0:
21295 outline = this.#rescale(this.#outline, blX, trY, width, -height);
21296 points = this.#rescale(this.#points, blX, trY, width, -height);
21297 break;
21298 case 90:
21299 outline = this.#rescaleAndSwap(this.#outline, blX, blY, width, height);
21300 points = this.#rescaleAndSwap(this.#points, blX, blY, width, height);
21301 break;
21302 case 180:
21303 outline = this.#rescale(this.#outline, trX, blY, -width, height);
21304 points = this.#rescale(this.#points, trX, blY, -width, height);
21305 break;
21306 case 270:
21307 outline = this.#rescaleAndSwap(this.#outline, trX, trY, -width, -height);
21308 points = this.#rescaleAndSwap(this.#points, trX, trY, -width, -height);
21309 break;
21310 }
21311 return {
21312 outline: Array.from(outline),
21313 points: [Array.from(points)]
21314 };
21315 }
21316 #rescale(src, tx, ty, sx, sy) {
21317 const dest = new Float64Array(src.length);
21318 for (let i = 0, ii = src.length; i < ii; i += 2) {
21319 dest[i] = tx + src[i] * sx;
21320 dest[i + 1] = ty + src[i + 1] * sy;
21321 }
21322 return dest;
21323 }
21324 #rescaleAndSwap(src, tx, ty, sx, sy) {
21325 const dest = new Float64Array(src.length);
21326 for (let i = 0, ii = src.length; i < ii; i += 2) {
21327 dest[i] = tx + src[i + 1] * sx;
21328 dest[i + 1] = ty + src[i] * sy;
21329 }
21330 return dest;
21331 }
21332 #computeMinMax(isLTR) {
21333 const outline = this.#outline;
21334 let lastX = outline[4];
21335 let lastY = outline[5];
21336 let minX = lastX;
21337 let minY = lastY;
21338 let maxX = lastX;
21339 let maxY = lastY;
21340 let lastPointX = lastX;
21341 let lastPointY = lastY;
21342 const ltrCallback = isLTR ? Math.max : Math.min;
21343 for (let i = 6, ii = outline.length; i < ii; i += 6) {
21344 if (isNaN(outline[i])) {
21345 minX = Math.min(minX, outline[i + 4]);
21346 minY = Math.min(minY, outline[i + 5]);
21347 maxX = Math.max(maxX, outline[i + 4]);
21348 maxY = Math.max(maxY, outline[i + 5]);
21349 if (lastPointY < outline[i + 5]) {
21350 lastPointX = outline[i + 4];
21351 lastPointY = outline[i + 5];
21352 } else if (lastPointY === outline[i + 5]) {
21353 lastPointX = ltrCallback(lastPointX, outline[i + 4]);
21354 }
21355 } else {
21356 const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6));
21357 minX = Math.min(minX, bbox[0]);
21358 minY = Math.min(minY, bbox[1]);
21359 maxX = Math.max(maxX, bbox[2]);
21360 maxY = Math.max(maxY, bbox[3]);
21361 if (lastPointY < bbox[3]) {
21362 lastPointX = bbox[2];
21363 lastPointY = bbox[3];
21364 } else if (lastPointY === bbox[3]) {
21365 lastPointX = ltrCallback(lastPointX, bbox[2]);
21366 }
21367 }
21368 lastX = outline[i + 4];
21369 lastY = outline[i + 5];
21370 }
21371 const x = minX - this.#innerMargin,
21372 y = minY - this.#innerMargin,
21373 width = maxX - minX + 2 * this.#innerMargin,
21374 height = maxY - minY + 2 * this.#innerMargin;
21375 this.#bbox = {
21376 x,
21377 y,
21378 width,
21379 height,
21380 lastPoint: [lastPointX, lastPointY]
21381 };
21382 }
21383 get box() {
21384 return this.#bbox;
21385 }
21386 getNewOutline(thickness, innerMargin) {
21387 const {
21388 x,
21389 y,
21390 width,
21391 height
21392 } = this.#bbox;
21393 const [layerX, layerY, layerWidth, layerHeight] = this.#box;
21394 const sx = width * layerWidth;
21395 const sy = height * layerHeight;
21396 const tx = x * layerWidth + layerX;
21397 const ty = y * layerHeight + layerY;
21398 const outliner = new FreeOutliner({
21399 x: this.#points[0] * sx + tx,
21400 y: this.#points[1] * sy + ty
21401 }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
21402 for (let i = 2; i < this.#points.length; i += 2) {
21403 outliner.add({
21404 x: this.#points[i] * sx + tx,
21405 y: this.#points[i + 1] * sy + ty
21406 });
21407 }
21408 return outliner.getOutlines();
21409 }
21410 }
21411
21412 ;// CONCATENATED MODULE: ./src/display/editor/color_picker.js
21413
21414
21415
21416 class ColorPicker {
21417 #boundKeyDown = this.#keyDown.bind(this);
21418 #boundPointerDown = this.#pointerDown.bind(this);
21419 #button = null;
21420 #buttonSwatch = null;
21421 #defaultColor;
21422 #dropdown = null;
21423 #dropdownWasFromKeyboard = false;
21424 #isMainColorPicker = false;
21425 #editor = null;
21426 #eventBus;
21427 #uiManager = null;
21428 #type;
21429 static get _keyboardManager() {
21430 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]]));
21431 }
21432 constructor({
21433 editor = null,
21434 uiManager = null
21435 }) {
21436 if (editor) {
21437 this.#isMainColorPicker = false;
21438 this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
21439 this.#editor = editor;
21440 } else {
21441 this.#isMainColorPicker = true;
21442 this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
21443 }
21444 this.#uiManager = editor?._uiManager || uiManager;
21445 this.#eventBus = this.#uiManager._eventBus;
21446 this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
21447 }
21448 renderButton() {
21449 const button = this.#button = document.createElement("button");
21450 button.className = "colorPicker";
21451 button.tabIndex = "0";
21452 button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
21453 button.setAttribute("aria-haspopup", true);
21454 button.addEventListener("click", this.#openDropdown.bind(this));
21455 button.addEventListener("keydown", this.#boundKeyDown);
21456 const swatch = this.#buttonSwatch = document.createElement("span");
21457 swatch.className = "swatch";
21458 swatch.setAttribute("aria-hidden", true);
21459 swatch.style.backgroundColor = this.#defaultColor;
21460 button.append(swatch);
21461 return button;
21462 }
21463 renderMainDropdown() {
21464 const dropdown = this.#dropdown = this.#getDropdownRoot();
21465 dropdown.setAttribute("aria-orientation", "horizontal");
21466 dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
21467 return dropdown;
21468 }
21469 #getDropdownRoot() {
21470 const div = document.createElement("div");
21471 div.addEventListener("contextmenu", noContextMenu);
21472 div.className = "dropdown";
21473 div.role = "listbox";
21474 div.setAttribute("aria-multiselectable", false);
21475 div.setAttribute("aria-orientation", "vertical");
21476 div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
21477 for (const [name, color] of this.#uiManager.highlightColors) {
21478 const button = document.createElement("button");
21479 button.tabIndex = "0";
21480 button.role = "option";
21481 button.setAttribute("data-color", color);
21482 button.title = name;
21483 button.setAttribute("data-l10n-id", `pdfjs-editor-colorpicker-${name}`);
21484 const swatch = document.createElement("span");
21485 button.append(swatch);
21486 swatch.className = "swatch";
21487 swatch.style.backgroundColor = color;
21488 button.setAttribute("aria-selected", color === this.#defaultColor);
21489 button.addEventListener("click", this.#colorSelect.bind(this, color));
21490 div.append(button);
21491 }
21492 div.addEventListener("keydown", this.#boundKeyDown);
21493 return div;
21494 }
21495 #colorSelect(color, event) {
21496 event.stopPropagation();
21497 this.#eventBus.dispatch("switchannotationeditorparams", {
21498 source: this,
21499 type: this.#type,
21500 value: color
21501 });
21502 }
21503 _colorSelectFromKeyboard(event) {
21504 if (event.target === this.#button) {
21505 this.#openDropdown(event);
21506 return;
21507 }
21508 const color = event.target.getAttribute("data-color");
21509 if (!color) {
21510 return;
21511 }
21512 this.#colorSelect(color, event);
21513 }
21514 _moveToNext(event) {
21515 if (!this.#isDropdownVisible) {
21516 this.#openDropdown(event);
21517 return;
21518 }
21519 if (event.target === this.#button) {
21520 this.#dropdown.firstChild?.focus();
21521 return;
21522 }
21523 event.target.nextSibling?.focus();
21524 }
21525 _moveToPrevious(event) {
21526 if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
21527 if (this.#isDropdownVisible) {
21528 this._hideDropdownFromKeyboard();
21529 }
21530 return;
21531 }
21532 if (!this.#isDropdownVisible) {
21533 this.#openDropdown(event);
21534 }
21535 event.target.previousSibling?.focus();
21536 }
21537 _moveToBeginning(event) {
21538 if (!this.#isDropdownVisible) {
21539 this.#openDropdown(event);
21540 return;
21541 }
21542 this.#dropdown.firstChild?.focus();
21543 }
21544 _moveToEnd(event) {
21545 if (!this.#isDropdownVisible) {
21546 this.#openDropdown(event);
21547 return;
21548 }
21549 this.#dropdown.lastChild?.focus();
21550 }
21551 #keyDown(event) {
21552 ColorPicker._keyboardManager.exec(this, event);
21553 }
21554 #openDropdown(event) {
21555 if (this.#isDropdownVisible) {
21556 this.hideDropdown();
21557 return;
21558 }
21559 this.#dropdownWasFromKeyboard = event.detail === 0;
21560 window.addEventListener("pointerdown", this.#boundPointerDown);
21561 if (this.#dropdown) {
21562 this.#dropdown.classList.remove("hidden");
21563 return;
21564 }
21565 const root = this.#dropdown = this.#getDropdownRoot();
21566 this.#button.append(root);
21567 }
21568 #pointerDown(event) {
21569 if (this.#dropdown?.contains(event.target)) {
21570 return;
21571 }
21572 this.hideDropdown();
21573 }
21574 hideDropdown() {
21575 this.#dropdown?.classList.add("hidden");
21576 window.removeEventListener("pointerdown", this.#boundPointerDown);
21577 }
21578 get #isDropdownVisible() {
21579 return this.#dropdown && !this.#dropdown.classList.contains("hidden");
21580 }
21581 _hideDropdownFromKeyboard() {
21582 if (this.#isMainColorPicker) {
21583 return;
21584 }
21585 if (!this.#isDropdownVisible) {
21586 this.#editor?.unselect();
21587 return;
21588 }
21589 this.hideDropdown();
21590 this.#button.focus({
21591 preventScroll: true,
21592 focusVisible: this.#dropdownWasFromKeyboard
21593 });
21594 }
21595 updateColor(color) {
21596 if (this.#buttonSwatch) {
21597 this.#buttonSwatch.style.backgroundColor = color;
21598 }
21599 if (!this.#dropdown) {
21600 return;
21601 }
21602 const i = this.#uiManager.highlightColors.values();
21603 for (const child of this.#dropdown.children) {
21604 child.setAttribute("aria-selected", i.next().value === color);
21605 }
21606 }
21607 destroy() {
21608 this.#button?.remove();
21609 this.#button = null;
21610 this.#buttonSwatch = null;
21611 this.#dropdown?.remove();
21612 this.#dropdown = null;
21613 }
21614 }
21615
21616 ;// CONCATENATED MODULE: ./src/display/editor/highlight.js
21617
21618
21619
21620
21621
21622
21623
21624 class HighlightEditor extends AnnotationEditor {
21625 #anchorNode = null;
21626 #anchorOffset = 0;
21627 #boxes;
21628 #clipPathId = null;
21629 #colorPicker = null;
21630 #focusOutlines = null;
21631 #focusNode = null;
21632 #focusOffset = 0;
21633 #highlightDiv = null;
21634 #highlightOutlines = null;
21635 #id = null;
21636 #isFreeHighlight = false;
21637 #boundKeydown = this.#keydown.bind(this);
21638 #lastPoint = null;
21639 #opacity;
21640 #outlineId = null;
21641 #text = "";
21642 #thickness;
21643 #methodOfCreation = "";
21644 static _defaultColor = null;
21645 static _defaultOpacity = 1;
21646 static _defaultThickness = 12;
21647 static _l10nPromise;
21648 static _type = "highlight";
21649 static _editorType = AnnotationEditorType.HIGHLIGHT;
21650 static _freeHighlightId = -1;
21651 static _freeHighlight = null;
21652 static _freeHighlightClipId = "";
21653 static get _keyboardManager() {
21654 const proto = HighlightEditor.prototype;
21655 return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
21656 args: [0]
21657 }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
21658 args: [1]
21659 }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
21660 args: [2]
21661 }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
21662 args: [3]
21663 }]]));
21664 }
21665 constructor(params) {
21666 super({
21667 ...params,
21668 name: "highlightEditor"
21669 });
21670 this.color = params.color || HighlightEditor._defaultColor;
21671 this.#thickness = params.thickness || HighlightEditor._defaultThickness;
21672 this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
21673 this.#boxes = params.boxes || null;
21674 this.#methodOfCreation = params.methodOfCreation || "";
21675 this.#text = params.text || "";
21676 this._isDraggable = false;
21677 if (params.highlightId > -1) {
21678 this.#isFreeHighlight = true;
21679 this.#createFreeOutlines(params);
21680 this.#addToDrawLayer();
21681 } else {
21682 this.#anchorNode = params.anchorNode;
21683 this.#anchorOffset = params.anchorOffset;
21684 this.#focusNode = params.focusNode;
21685 this.#focusOffset = params.focusOffset;
21686 this.#createOutlines();
21687 this.#addToDrawLayer();
21688 this.rotate(this.rotation);
21689 }
21690 }
21691 get telemetryInitialData() {
21692 return {
21693 action: "added",
21694 type: this.#isFreeHighlight ? "free_highlight" : "highlight",
21695 color: this._uiManager.highlightColorNames.get(this.color),
21696 thickness: this.#thickness,
21697 methodOfCreation: this.#methodOfCreation
21698 };
21699 }
21700 get telemetryFinalData() {
21701 return {
21702 type: "highlight",
21703 color: this._uiManager.highlightColorNames.get(this.color)
21704 };
21705 }
21706 static computeTelemetryFinalData(data) {
21707 return {
21708 numberOfColors: data.get("color").size
21709 };
21710 }
21711 #createOutlines() {
21712 const outliner = new Outliner(this.#boxes, 0.001);
21713 this.#highlightOutlines = outliner.getOutlines();
21714 ({
21715 x: this.x,
21716 y: this.y,
21717 width: this.width,
21718 height: this.height
21719 } = this.#highlightOutlines.box);
21720 const outlinerForOutline = new Outliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
21721 this.#focusOutlines = outlinerForOutline.getOutlines();
21722 const {
21723 lastPoint
21724 } = this.#focusOutlines.box;
21725 this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
21726 }
21727 #createFreeOutlines({
21728 highlightOutlines,
21729 highlightId,
21730 clipPathId
21731 }) {
21732 this.#highlightOutlines = highlightOutlines;
21733 const extraThickness = 1.5;
21734 this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
21735 if (highlightId >= 0) {
21736 this.#id = highlightId;
21737 this.#clipPathId = clipPathId;
21738 this.parent.drawLayer.finalizeLine(highlightId, highlightOutlines);
21739 this.#outlineId = this.parent.drawLayer.highlightOutline(this.#focusOutlines);
21740 } else if (this.parent) {
21741 const angle = this.parent.viewport.rotation;
21742 this.parent.drawLayer.updateLine(this.#id, highlightOutlines);
21743 this.parent.drawLayer.updateBox(this.#id, HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360));
21744 this.parent.drawLayer.updateLine(this.#outlineId, this.#focusOutlines);
21745 this.parent.drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
21746 }
21747 const {
21748 x,
21749 y,
21750 width,
21751 height
21752 } = highlightOutlines.box;
21753 switch (this.rotation) {
21754 case 0:
21755 this.x = x;
21756 this.y = y;
21757 this.width = width;
21758 this.height = height;
21759 break;
21760 case 90:
21761 {
21762 const [pageWidth, pageHeight] = this.parentDimensions;
21763 this.x = y;
21764 this.y = 1 - x;
21765 this.width = width * pageHeight / pageWidth;
21766 this.height = height * pageWidth / pageHeight;
21767 break;
21768 }
21769 case 180:
21770 this.x = 1 - x;
21771 this.y = 1 - y;
21772 this.width = width;
21773 this.height = height;
21774 break;
21775 case 270:
21776 {
21777 const [pageWidth, pageHeight] = this.parentDimensions;
21778 this.x = 1 - y;
21779 this.y = x;
21780 this.width = width * pageHeight / pageWidth;
21781 this.height = height * pageWidth / pageHeight;
21782 break;
21783 }
21784 }
21785 const {
21786 lastPoint
21787 } = this.#focusOutlines.box;
21788 this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
21789 }
21790 static initialize(l10n, uiManager) {
21791 AnnotationEditor.initialize(l10n, uiManager);
21792 HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
21793 }
21794 static updateDefaultParams(type, value) {
21795 switch (type) {
21796 case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
21797 HighlightEditor._defaultColor = value;
21798 break;
21799 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
21800 HighlightEditor._defaultThickness = value;
21801 break;
21802 }
21803 }
21804 translateInPage(x, y) {}
21805 get toolbarPosition() {
21806 return this.#lastPoint;
21807 }
21808 updateParams(type, value) {
21809 switch (type) {
21810 case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
21811 this.#updateColor(value);
21812 break;
21813 case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
21814 this.#updateThickness(value);
21815 break;
21816 }
21817 }
21818 static get defaultPropertiesToUpdate() {
21819 return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
21820 }
21821 get propertiesToUpdate() {
21822 return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
21823 }
21824 #updateColor(color) {
21825 const setColor = col => {
21826 this.color = col;
21827 this.parent?.drawLayer.changeColor(this.#id, col);
21828 this.#colorPicker?.updateColor(col);
21829 };
21830 const savedColor = this.color;
21831 this.addCommands({
21832 cmd: setColor.bind(this, color),
21833 undo: setColor.bind(this, savedColor),
21834 post: this._uiManager.updateUI.bind(this._uiManager, this),
21835 mustExec: true,
21836 type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
21837 overwriteIfSameType: true,
21838 keepUndo: true
21839 });
21840 this._reportTelemetry({
21841 action: "color_changed",
21842 color: this._uiManager.highlightColorNames.get(color)
21843 }, true);
21844 }
21845 #updateThickness(thickness) {
21846 const savedThickness = this.#thickness;
21847 const setThickness = th => {
21848 this.#thickness = th;
21849 this.#changeThickness(th);
21850 };
21851 this.addCommands({
21852 cmd: setThickness.bind(this, thickness),
21853 undo: setThickness.bind(this, savedThickness),
21854 post: this._uiManager.updateUI.bind(this._uiManager, this),
21855 mustExec: true,
21856 type: AnnotationEditorParamsType.INK_THICKNESS,
21857 overwriteIfSameType: true,
21858 keepUndo: true
21859 });
21860 this._reportTelemetry({
21861 action: "thickness_changed",
21862 thickness
21863 }, true);
21864 }
21865 async addEditToolbar() {
21866 const toolbar = await super.addEditToolbar();
21867 if (!toolbar) {
21868 return null;
21869 }
21870 if (this._uiManager.highlightColors) {
21871 this.#colorPicker = new ColorPicker({
21872 editor: this
21873 });
21874 toolbar.addColorPicker(this.#colorPicker);
21875 }
21876 return toolbar;
21877 }
21878 disableEditing() {
21879 super.disableEditing();
21880 this.div.classList.toggle("disabled", true);
21881 }
21882 enableEditing() {
21883 super.enableEditing();
21884 this.div.classList.toggle("disabled", false);
21885 }
21886 fixAndSetPosition() {
21887 return super.fixAndSetPosition(this.#getRotation());
21888 }
21889 getBaseTranslation() {
21890 return [0, 0];
21891 }
21892 getRect(tx, ty) {
21893 return super.getRect(tx, ty, this.#getRotation());
21894 }
21895 onceAdded() {
21896 this.parent.addUndoableEditor(this);
21897 this.div.focus();
21898 }
21899 remove() {
21900 this.#cleanDrawLayer();
21901 this._reportTelemetry({
21902 action: "deleted"
21903 });
21904 super.remove();
21905 }
21906 rebuild() {
21907 if (!this.parent) {
21908 return;
21909 }
21910 super.rebuild();
21911 if (this.div === null) {
21912 return;
21913 }
21914 this.#addToDrawLayer();
21915 if (!this.isAttachedToDOM) {
21916 this.parent.add(this);
21917 }
21918 }
21919 setParent(parent) {
21920 let mustBeSelected = false;
21921 if (this.parent && !parent) {
21922 this.#cleanDrawLayer();
21923 } else if (parent) {
21924 this.#addToDrawLayer(parent);
21925 mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
21926 }
21927 super.setParent(parent);
21928 this.show(this._isVisible);
21929 if (mustBeSelected) {
21930 this.select();
21931 }
21932 }
21933 #changeThickness(thickness) {
21934 if (!this.#isFreeHighlight) {
21935 return;
21936 }
21937 this.#createFreeOutlines({
21938 highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
21939 });
21940 this.fixAndSetPosition();
21941 const [parentWidth, parentHeight] = this.parentDimensions;
21942 this.setDims(this.width * parentWidth, this.height * parentHeight);
21943 }
21944 #cleanDrawLayer() {
21945 if (this.#id === null || !this.parent) {
21946 return;
21947 }
21948 this.parent.drawLayer.remove(this.#id);
21949 this.#id = null;
21950 this.parent.drawLayer.remove(this.#outlineId);
21951 this.#outlineId = null;
21952 }
21953 #addToDrawLayer(parent = this.parent) {
21954 if (this.#id !== null) {
21955 return;
21956 }
21957 ({
21958 id: this.#id,
21959 clipPathId: this.#clipPathId
21960 } = parent.drawLayer.highlight(this.#highlightOutlines, this.color, this.#opacity));
21961 this.#outlineId = parent.drawLayer.highlightOutline(this.#focusOutlines);
21962 if (this.#highlightDiv) {
21963 this.#highlightDiv.style.clipPath = this.#clipPathId;
21964 }
21965 }
21966 static #rotateBbox({
21967 x,
21968 y,
21969 width,
21970 height
21971 }, angle) {
21972 switch (angle) {
21973 case 90:
21974 return {
21975 x: 1 - y - height,
21976 y: x,
21977 width: height,
21978 height: width
21979 };
21980 case 180:
21981 return {
21982 x: 1 - x - width,
21983 y: 1 - y - height,
21984 width,
21985 height
21986 };
21987 case 270:
21988 return {
21989 x: y,
21990 y: 1 - x - width,
21991 width: height,
21992 height: width
21993 };
21994 }
21995 return {
21996 x,
21997 y,
21998 width,
21999 height
22000 };
22001 }
22002 rotate(angle) {
22003 const {
22004 drawLayer
22005 } = this.parent;
22006 let box;
22007 if (this.#isFreeHighlight) {
22008 angle = (angle - this.rotation + 360) % 360;
22009 box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
22010 } else {
22011 box = HighlightEditor.#rotateBbox(this, angle);
22012 }
22013 drawLayer.rotate(this.#id, angle);
22014 drawLayer.rotate(this.#outlineId, angle);
22015 drawLayer.updateBox(this.#id, box);
22016 drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
22017 }
22018 render() {
22019 if (this.div) {
22020 return this.div;
22021 }
22022 const div = super.render();
22023 if (this.#text) {
22024 div.setAttribute("aria-label", this.#text);
22025 div.setAttribute("role", "mark");
22026 }
22027 if (this.#isFreeHighlight) {
22028 div.classList.add("free");
22029 } else {
22030 this.div.addEventListener("keydown", this.#boundKeydown);
22031 }
22032 const highlightDiv = this.#highlightDiv = document.createElement("div");
22033 div.append(highlightDiv);
22034 highlightDiv.setAttribute("aria-hidden", "true");
22035 highlightDiv.className = "internal";
22036 highlightDiv.style.clipPath = this.#clipPathId;
22037 const [parentWidth, parentHeight] = this.parentDimensions;
22038 this.setDims(this.width * parentWidth, this.height * parentHeight);
22039 bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
22040 this.enableEditing();
22041 return div;
22042 }
22043 pointerover() {
22044 this.parent.drawLayer.addClass(this.#outlineId, "hovered");
22045 }
22046 pointerleave() {
22047 this.parent.drawLayer.removeClass(this.#outlineId, "hovered");
22048 }
22049 #keydown(event) {
22050 HighlightEditor._keyboardManager.exec(this, event);
22051 }
22052 _moveCaret(direction) {
22053 this.parent.unselect(this);
22054 switch (direction) {
22055 case 0:
22056 case 2:
22057 this.#setCaret(true);
22058 break;
22059 case 1:
22060 case 3:
22061 this.#setCaret(false);
22062 break;
22063 }
22064 }
22065 #setCaret(start) {
22066 if (!this.#anchorNode) {
22067 return;
22068 }
22069 const selection = window.getSelection();
22070 if (start) {
22071 selection.setPosition(this.#anchorNode, this.#anchorOffset);
22072 } else {
22073 selection.setPosition(this.#focusNode, this.#focusOffset);
22074 }
22075 }
22076 select() {
22077 super.select();
22078 if (!this.#outlineId) {
22079 return;
22080 }
22081 this.parent?.drawLayer.removeClass(this.#outlineId, "hovered");
22082 this.parent?.drawLayer.addClass(this.#outlineId, "selected");
22083 }
22084 unselect() {
22085 super.unselect();
22086 if (!this.#outlineId) {
22087 return;
22088 }
22089 this.parent?.drawLayer.removeClass(this.#outlineId, "selected");
22090 if (!this.#isFreeHighlight) {
22091 this.#setCaret(false);
22092 }
22093 }
22094 get _mustFixPosition() {
22095 return !this.#isFreeHighlight;
22096 }
22097 show(visible = this._isVisible) {
22098 super.show(visible);
22099 if (this.parent) {
22100 this.parent.drawLayer.show(this.#id, visible);
22101 this.parent.drawLayer.show(this.#outlineId, visible);
22102 }
22103 }
22104 #getRotation() {
22105 return this.#isFreeHighlight ? this.rotation : 0;
22106 }
22107 #serializeBoxes() {
22108 if (this.#isFreeHighlight) {
22109 return null;
22110 }
22111 const [pageWidth, pageHeight] = this.pageDimensions;
22112 const boxes = this.#boxes;
22113 const quadPoints = new Array(boxes.length * 8);
22114 let i = 0;
22115 for (const {
22116 x,
22117 y,
22118 width,
22119 height
22120 } of boxes) {
22121 const sx = x * pageWidth;
22122 const sy = (1 - y - height) * pageHeight;
22123 quadPoints[i] = quadPoints[i + 4] = sx;
22124 quadPoints[i + 1] = quadPoints[i + 3] = sy;
22125 quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
22126 quadPoints[i + 5] = quadPoints[i + 7] = sy + height * pageHeight;
22127 i += 8;
22128 }
22129 return quadPoints;
22130 }
22131 #serializeOutlines(rect) {
22132 return this.#highlightOutlines.serialize(rect, this.#getRotation());
22133 }
22134 static startHighlighting(parent, isLTR, {
22135 target: textLayer,
22136 x,
22137 y
22138 }) {
22139 const {
22140 x: layerX,
22141 y: layerY,
22142 width: parentWidth,
22143 height: parentHeight
22144 } = textLayer.getBoundingClientRect();
22145 const pointerMove = e => {
22146 this.#highlightMove(parent, e);
22147 };
22148 const pointerDownOptions = {
22149 capture: true,
22150 passive: false
22151 };
22152 const pointerDown = e => {
22153 e.preventDefault();
22154 e.stopPropagation();
22155 };
22156 const pointerUpCallback = e => {
22157 textLayer.removeEventListener("pointermove", pointerMove);
22158 window.removeEventListener("blur", pointerUpCallback);
22159 window.removeEventListener("pointerup", pointerUpCallback);
22160 window.removeEventListener("pointerdown", pointerDown, pointerDownOptions);
22161 window.removeEventListener("contextmenu", noContextMenu);
22162 this.#endHighlight(parent, e);
22163 };
22164 window.addEventListener("blur", pointerUpCallback);
22165 window.addEventListener("pointerup", pointerUpCallback);
22166 window.addEventListener("pointerdown", pointerDown, pointerDownOptions);
22167 window.addEventListener("contextmenu", noContextMenu);
22168 textLayer.addEventListener("pointermove", pointerMove);
22169 this._freeHighlight = new FreeOutliner({
22170 x,
22171 y
22172 }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
22173 ({
22174 id: this._freeHighlightId,
22175 clipPathId: this._freeHighlightClipId
22176 } = parent.drawLayer.highlight(this._freeHighlight, this._defaultColor, this._defaultOpacity, true));
22177 }
22178 static #highlightMove(parent, event) {
22179 if (this._freeHighlight.add(event)) {
22180 parent.drawLayer.updatePath(this._freeHighlightId, this._freeHighlight);
22181 }
22182 }
22183 static #endHighlight(parent, event) {
22184 if (!this._freeHighlight.isEmpty()) {
22185 parent.createAndAddNewEditor(event, false, {
22186 highlightId: this._freeHighlightId,
22187 highlightOutlines: this._freeHighlight.getOutlines(),
22188 clipPathId: this._freeHighlightClipId,
22189 methodOfCreation: "main_toolbar"
22190 });
22191 } else {
22192 parent.drawLayer.removeFreeHighlight(this._freeHighlightId);
22193 }
22194 this._freeHighlightId = -1;
22195 this._freeHighlight = null;
22196 this._freeHighlightClipId = "";
22197 }
22198 static deserialize(data, parent, uiManager) {
22199 const editor = super.deserialize(data, parent, uiManager);
22200 const {
22201 rect: [blX, blY, trX, trY],
22202 color,
22203 quadPoints
22204 } = data;
22205 editor.color = Util.makeHexColor(...color);
22206 editor.#opacity = data.opacity;
22207 const [pageWidth, pageHeight] = editor.pageDimensions;
22208 editor.width = (trX - blX) / pageWidth;
22209 editor.height = (trY - blY) / pageHeight;
22210 const boxes = editor.#boxes = [];
22211 for (let i = 0; i < quadPoints.length; i += 8) {
22212 boxes.push({
22213 x: (quadPoints[4] - trX) / pageWidth,
22214 y: (trY - (1 - quadPoints[i + 5])) / pageHeight,
22215 width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
22216 height: (quadPoints[i + 5] - quadPoints[i + 1]) / pageHeight
22217 });
22218 }
22219 editor.#createOutlines();
22220 return editor;
22221 }
22222 serialize(isForCopying = false) {
22223 if (this.isEmpty() || isForCopying) {
22224 return null;
22225 }
22226 const rect = this.getRect(0, 0);
22227 const color = AnnotationEditor._colorManager.convert(this.color);
22228 return {
22229 annotationType: AnnotationEditorType.HIGHLIGHT,
22230 color,
22231 opacity: this.#opacity,
22232 thickness: this.#thickness,
22233 quadPoints: this.#serializeBoxes(),
22234 outlines: this.#serializeOutlines(rect),
22235 pageIndex: this.pageIndex,
22236 rect,
22237 rotation: this.#getRotation(),
22238 structTreeParentId: this._structTreeParentId
22239 };
22240 }
22241 static canCreateNewEmptyEditor() {
22242 return false;
22243 }
22244 }
22245
22246 ;// CONCATENATED MODULE: ./src/display/editor/ink.js
22247
22248
22249
22250
22251
22252
22253
22254 class InkEditor extends AnnotationEditor {
22255 #baseHeight = 0;
22256 #baseWidth = 0;
22257 #boundCanvasPointermove = this.canvasPointermove.bind(this);
22258 #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
22259 #boundCanvasPointerup = this.canvasPointerup.bind(this);
22260 #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
22261 #canvasContextMenuTimeoutId = null;
22262 #currentPath2D = new Path2D();
22263 #disableEditing = false;
22264 #hasSomethingToDraw = false;
22265 #isCanvasInitialized = false;
22266 #observer = null;
22267 #realWidth = 0;
22268 #realHeight = 0;
22269 #requestFrameCallback = null;
22270 static _defaultColor = null;
22271 static _defaultOpacity = 1;
22272 static _defaultThickness = 1;
22273 static _type = "ink";
22274 static _editorType = AnnotationEditorType.INK;
22275 constructor(params) {
22276 super({
22277 ...params,
22278 name: "inkEditor"
22279 });
22280 this.color = params.color || null;
22281 this.thickness = params.thickness || null;
22282 this.opacity = params.opacity || null;
22283 this.paths = [];
22284 this.bezierPath2D = [];
22285 this.allRawPaths = [];
22286 this.currentPath = [];
22287 this.scaleFactor = 1;
22288 this.translationX = this.translationY = 0;
22289 this.x = 0;
22290 this.y = 0;
22291 this._willKeepAspectRatio = true;
22292 }
22293 static initialize(l10n, uiManager) {
22294 AnnotationEditor.initialize(l10n, uiManager);
22295 }
22296 static updateDefaultParams(type, value) {
22297 switch (type) {
22298 case AnnotationEditorParamsType.INK_THICKNESS:
22299 InkEditor._defaultThickness = value;
22300 break;
22301 case AnnotationEditorParamsType.INK_COLOR:
22302 InkEditor._defaultColor = value;
22303 break;
22304 case AnnotationEditorParamsType.INK_OPACITY:
22305 InkEditor._defaultOpacity = value / 100;
22306 break;
22307 }
22308 }
22309 updateParams(type, value) {
22310 switch (type) {
22311 case AnnotationEditorParamsType.INK_THICKNESS:
22312 this.#updateThickness(value);
22313 break;
22314 case AnnotationEditorParamsType.INK_COLOR:
22315 this.#updateColor(value);
22316 break;
22317 case AnnotationEditorParamsType.INK_OPACITY:
22318 this.#updateOpacity(value);
22319 break;
22320 }
22321 }
22322 static get defaultPropertiesToUpdate() {
22323 return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
22324 }
22325 get propertiesToUpdate() {
22326 return [[AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
22327 }
22328 #updateThickness(thickness) {
22329 const setThickness = th => {
22330 this.thickness = th;
22331 this.#fitToContent();
22332 };
22333 const savedThickness = this.thickness;
22334 this.addCommands({
22335 cmd: setThickness.bind(this, thickness),
22336 undo: setThickness.bind(this, savedThickness),
22337 post: this._uiManager.updateUI.bind(this._uiManager, this),
22338 mustExec: true,
22339 type: AnnotationEditorParamsType.INK_THICKNESS,
22340 overwriteIfSameType: true,
22341 keepUndo: true
22342 });
22343 }
22344 #updateColor(color) {
22345 const setColor = col => {
22346 this.color = col;
22347 this.#redraw();
22348 };
22349 const savedColor = this.color;
22350 this.addCommands({
22351 cmd: setColor.bind(this, color),
22352 undo: setColor.bind(this, savedColor),
22353 post: this._uiManager.updateUI.bind(this._uiManager, this),
22354 mustExec: true,
22355 type: AnnotationEditorParamsType.INK_COLOR,
22356 overwriteIfSameType: true,
22357 keepUndo: true
22358 });
22359 }
22360 #updateOpacity(opacity) {
22361 const setOpacity = op => {
22362 this.opacity = op;
22363 this.#redraw();
22364 };
22365 opacity /= 100;
22366 const savedOpacity = this.opacity;
22367 this.addCommands({
22368 cmd: setOpacity.bind(this, opacity),
22369 undo: setOpacity.bind(this, savedOpacity),
22370 post: this._uiManager.updateUI.bind(this._uiManager, this),
22371 mustExec: true,
22372 type: AnnotationEditorParamsType.INK_OPACITY,
22373 overwriteIfSameType: true,
22374 keepUndo: true
22375 });
22376 }
22377 rebuild() {
22378 if (!this.parent) {
22379 return;
22380 }
22381 super.rebuild();
22382 if (this.div === null) {
22383 return;
22384 }
22385 if (!this.canvas) {
22386 this.#createCanvas();
22387 this.#createObserver();
22388 }
22389 if (!this.isAttachedToDOM) {
22390 this.parent.add(this);
22391 this.#setCanvasDims();
22392 }
22393 this.#fitToContent();
22394 }
22395 remove() {
22396 if (this.canvas === null) {
22397 return;
22398 }
22399 if (!this.isEmpty()) {
22400 this.commit();
22401 }
22402 this.canvas.width = this.canvas.height = 0;
22403 this.canvas.remove();
22404 this.canvas = null;
22405 if (this.#canvasContextMenuTimeoutId) {
22406 clearTimeout(this.#canvasContextMenuTimeoutId);
22407 this.#canvasContextMenuTimeoutId = null;
22408 }
22409 this.#observer.disconnect();
22410 this.#observer = null;
22411 super.remove();
22412 }
22413 setParent(parent) {
22414 if (!this.parent && parent) {
22415 this._uiManager.removeShouldRescale(this);
22416 } else if (this.parent && parent === null) {
22417 this._uiManager.addShouldRescale(this);
22418 }
22419 super.setParent(parent);
22420 }
22421 onScaleChanging() {
22422 const [parentWidth, parentHeight] = this.parentDimensions;
22423 const width = this.width * parentWidth;
22424 const height = this.height * parentHeight;
22425 this.setDimensions(width, height);
22426 }
22427 enableEditMode() {
22428 if (this.#disableEditing || this.canvas === null) {
22429 return;
22430 }
22431 super.enableEditMode();
22432 this._isDraggable = false;
22433 this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
22434 }
22435 disableEditMode() {
22436 if (!this.isInEditMode() || this.canvas === null) {
22437 return;
22438 }
22439 super.disableEditMode();
22440 this._isDraggable = !this.isEmpty();
22441 this.div.classList.remove("editing");
22442 this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
22443 }
22444 onceAdded() {
22445 this._isDraggable = !this.isEmpty();
22446 }
22447 isEmpty() {
22448 return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
22449 }
22450 #getInitialBBox() {
22451 const {
22452 parentRotation,
22453 parentDimensions: [width, height]
22454 } = this;
22455 switch (parentRotation) {
22456 case 90:
22457 return [0, height, height, width];
22458 case 180:
22459 return [width, height, width, height];
22460 case 270:
22461 return [width, 0, height, width];
22462 default:
22463 return [0, 0, width, height];
22464 }
22465 }
22466 #setStroke() {
22467 const {
22468 ctx,
22469 color,
22470 opacity,
22471 thickness,
22472 parentScale,
22473 scaleFactor
22474 } = this;
22475 ctx.lineWidth = thickness * parentScale / scaleFactor;
22476 ctx.lineCap = "round";
22477 ctx.lineJoin = "round";
22478 ctx.miterLimit = 10;
22479 ctx.strokeStyle = `${color}${opacityToHex(opacity)}`;
22480 }
22481 #startDrawing(x, y) {
22482 this.canvas.addEventListener("contextmenu", noContextMenu);
22483 this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
22484 this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
22485 this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
22486 this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
22487 this.isEditing = true;
22488 if (!this.#isCanvasInitialized) {
22489 this.#isCanvasInitialized = true;
22490 this.#setCanvasDims();
22491 this.thickness ||= InkEditor._defaultThickness;
22492 this.color ||= InkEditor._defaultColor || AnnotationEditor._defaultLineColor;
22493 this.opacity ??= InkEditor._defaultOpacity;
22494 }
22495 this.currentPath.push([x, y]);
22496 this.#hasSomethingToDraw = false;
22497 this.#setStroke();
22498 this.#requestFrameCallback = () => {
22499 this.#drawPoints();
22500 if (this.#requestFrameCallback) {
22501 window.requestAnimationFrame(this.#requestFrameCallback);
22502 }
22503 };
22504 window.requestAnimationFrame(this.#requestFrameCallback);
22505 }
22506 #draw(x, y) {
22507 const [lastX, lastY] = this.currentPath.at(-1);
22508 if (this.currentPath.length > 1 && x === lastX && y === lastY) {
22509 return;
22510 }
22511 const currentPath = this.currentPath;
22512 let path2D = this.#currentPath2D;
22513 currentPath.push([x, y]);
22514 this.#hasSomethingToDraw = true;
22515 if (currentPath.length <= 2) {
22516 path2D.moveTo(...currentPath[0]);
22517 path2D.lineTo(x, y);
22518 return;
22519 }
22520 if (currentPath.length === 3) {
22521 this.#currentPath2D = path2D = new Path2D();
22522 path2D.moveTo(...currentPath[0]);
22523 }
22524 this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y);
22525 }
22526 #endPath() {
22527 if (this.currentPath.length === 0) {
22528 return;
22529 }
22530 const lastPoint = this.currentPath.at(-1);
22531 this.#currentPath2D.lineTo(...lastPoint);
22532 }
22533 #stopDrawing(x, y) {
22534 this.#requestFrameCallback = null;
22535 x = Math.min(Math.max(x, 0), this.canvas.width);
22536 y = Math.min(Math.max(y, 0), this.canvas.height);
22537 this.#draw(x, y);
22538 this.#endPath();
22539 let bezier;
22540 if (this.currentPath.length !== 1) {
22541 bezier = this.#generateBezierPoints();
22542 } else {
22543 const xy = [x, y];
22544 bezier = [[xy, xy.slice(), xy.slice(), xy]];
22545 }
22546 const path2D = this.#currentPath2D;
22547 const currentPath = this.currentPath;
22548 this.currentPath = [];
22549 this.#currentPath2D = new Path2D();
22550 const cmd = () => {
22551 this.allRawPaths.push(currentPath);
22552 this.paths.push(bezier);
22553 this.bezierPath2D.push(path2D);
22554 this._uiManager.rebuild(this);
22555 };
22556 const undo = () => {
22557 this.allRawPaths.pop();
22558 this.paths.pop();
22559 this.bezierPath2D.pop();
22560 if (this.paths.length === 0) {
22561 this.remove();
22562 } else {
22563 if (!this.canvas) {
22564 this.#createCanvas();
22565 this.#createObserver();
22566 }
22567 this.#fitToContent();
22568 }
22569 };
22570 this.addCommands({
22571 cmd,
22572 undo,
22573 mustExec: true
22574 });
22575 }
22576 #drawPoints() {
22577 if (!this.#hasSomethingToDraw) {
22578 return;
22579 }
22580 this.#hasSomethingToDraw = false;
22581 const thickness = Math.ceil(this.thickness * this.parentScale);
22582 const lastPoints = this.currentPath.slice(-3);
22583 const x = lastPoints.map(xy => xy[0]);
22584 const y = lastPoints.map(xy => xy[1]);
22585 const xMin = Math.min(...x) - thickness;
22586 const xMax = Math.max(...x) + thickness;
22587 const yMin = Math.min(...y) - thickness;
22588 const yMax = Math.max(...y) + thickness;
22589 const {
22590 ctx
22591 } = this;
22592 ctx.save();
22593 ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
22594 for (const path of this.bezierPath2D) {
22595 ctx.stroke(path);
22596 }
22597 ctx.stroke(this.#currentPath2D);
22598 ctx.restore();
22599 }
22600 #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) {
22601 const prevX = (x0 + x1) / 2;
22602 const prevY = (y0 + y1) / 2;
22603 const x3 = (x1 + x2) / 2;
22604 const y3 = (y1 + y2) / 2;
22605 path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3);
22606 }
22607 #generateBezierPoints() {
22608 const path = this.currentPath;
22609 if (path.length <= 2) {
22610 return [[path[0], path[0], path.at(-1), path.at(-1)]];
22611 }
22612 const bezierPoints = [];
22613 let i;
22614 let [x0, y0] = path[0];
22615 for (i = 1; i < path.length - 2; i++) {
22616 const [x1, y1] = path[i];
22617 const [x2, y2] = path[i + 1];
22618 const x3 = (x1 + x2) / 2;
22619 const y3 = (y1 + y2) / 2;
22620 const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
22621 const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3];
22622 bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]);
22623 [x0, y0] = [x3, y3];
22624 }
22625 const [x1, y1] = path[i];
22626 const [x2, y2] = path[i + 1];
22627 const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
22628 const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3];
22629 bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]);
22630 return bezierPoints;
22631 }
22632 #redraw() {
22633 if (this.isEmpty()) {
22634 this.#updateTransform();
22635 return;
22636 }
22637 this.#setStroke();
22638 const {
22639 canvas,
22640 ctx
22641 } = this;
22642 ctx.setTransform(1, 0, 0, 1, 0, 0);
22643 ctx.clearRect(0, 0, canvas.width, canvas.height);
22644 this.#updateTransform();
22645 for (const path of this.bezierPath2D) {
22646 ctx.stroke(path);
22647 }
22648 }
22649 commit() {
22650 if (this.#disableEditing) {
22651 return;
22652 }
22653 super.commit();
22654 this.isEditing = false;
22655 this.disableEditMode();
22656 this.setInForeground();
22657 this.#disableEditing = true;
22658 this.div.classList.add("disabled");
22659 this.#fitToContent(true);
22660 this.select();
22661 this.parent.addInkEditorIfNeeded(true);
22662 this.moveInDOM();
22663 this.div.focus({
22664 preventScroll: true
22665 });
22666 }
22667 focusin(event) {
22668 if (!this._focusEventsAllowed) {
22669 return;
22670 }
22671 super.focusin(event);
22672 this.enableEditMode();
22673 }
22674 canvasPointerdown(event) {
22675 if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
22676 return;
22677 }
22678 this.setInForeground();
22679 event.preventDefault();
22680 if (!this.div.contains(document.activeElement)) {
22681 this.div.focus({
22682 preventScroll: true
22683 });
22684 }
22685 this.#startDrawing(event.offsetX, event.offsetY);
22686 }
22687 canvasPointermove(event) {
22688 event.preventDefault();
22689 this.#draw(event.offsetX, event.offsetY);
22690 }
22691 canvasPointerup(event) {
22692 event.preventDefault();
22693 this.#endDrawing(event);
22694 }
22695 canvasPointerleave(event) {
22696 this.#endDrawing(event);
22697 }
22698 #endDrawing(event) {
22699 this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
22700 this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
22701 this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
22702 this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
22703 if (this.#canvasContextMenuTimeoutId) {
22704 clearTimeout(this.#canvasContextMenuTimeoutId);
22705 }
22706 this.#canvasContextMenuTimeoutId = setTimeout(() => {
22707 this.#canvasContextMenuTimeoutId = null;
22708 this.canvas.removeEventListener("contextmenu", noContextMenu);
22709 }, 10);
22710 this.#stopDrawing(event.offsetX, event.offsetY);
22711 this.addToAnnotationStorage();
22712 this.setInBackground();
22713 }
22714 #createCanvas() {
22715 this.canvas = document.createElement("canvas");
22716 this.canvas.width = this.canvas.height = 0;
22717 this.canvas.className = "inkEditorCanvas";
22718 this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas");
22719 this.div.append(this.canvas);
22720 this.ctx = this.canvas.getContext("2d");
22721 }
22722 #createObserver() {
22723 this.#observer = new ResizeObserver(entries => {
22724 const rect = entries[0].contentRect;
22725 if (rect.width && rect.height) {
22726 this.setDimensions(rect.width, rect.height);
22727 }
22728 });
22729 this.#observer.observe(this.div);
22730 }
22731 get isResizable() {
22732 return !this.isEmpty() && this.#disableEditing;
22733 }
22734 render() {
22735 if (this.div) {
22736 return this.div;
22737 }
22738 let baseX, baseY;
22739 if (this.width) {
22740 baseX = this.x;
22741 baseY = this.y;
22742 }
22743 super.render();
22744 this.div.setAttribute("data-l10n-id", "pdfjs-ink");
22745 const [x, y, w, h] = this.#getInitialBBox();
22746 this.setAt(x, y, 0, 0);
22747 this.setDims(w, h);
22748 this.#createCanvas();
22749 if (this.width) {
22750 const [parentWidth, parentHeight] = this.parentDimensions;
22751 this.setAspectRatio(this.width * parentWidth, this.height * parentHeight);
22752 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
22753 this.#isCanvasInitialized = true;
22754 this.#setCanvasDims();
22755 this.setDims(this.width * parentWidth, this.height * parentHeight);
22756 this.#redraw();
22757 this.div.classList.add("disabled");
22758 } else {
22759 this.div.classList.add("editing");
22760 this.enableEditMode();
22761 }
22762 this.#createObserver();
22763 return this.div;
22764 }
22765 #setCanvasDims() {
22766 if (!this.#isCanvasInitialized) {
22767 return;
22768 }
22769 const [parentWidth, parentHeight] = this.parentDimensions;
22770 this.canvas.width = Math.ceil(this.width * parentWidth);
22771 this.canvas.height = Math.ceil(this.height * parentHeight);
22772 this.#updateTransform();
22773 }
22774 setDimensions(width, height) {
22775 const roundedWidth = Math.round(width);
22776 const roundedHeight = Math.round(height);
22777 if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
22778 return;
22779 }
22780 this.#realWidth = roundedWidth;
22781 this.#realHeight = roundedHeight;
22782 this.canvas.style.visibility = "hidden";
22783 const [parentWidth, parentHeight] = this.parentDimensions;
22784 this.width = width / parentWidth;
22785 this.height = height / parentHeight;
22786 this.fixAndSetPosition();
22787 if (this.#disableEditing) {
22788 this.#setScaleFactor(width, height);
22789 }
22790 this.#setCanvasDims();
22791 this.#redraw();
22792 this.canvas.style.visibility = "visible";
22793 this.fixDims();
22794 }
22795 #setScaleFactor(width, height) {
22796 const padding = this.#getPadding();
22797 const scaleFactorW = (width - padding) / this.#baseWidth;
22798 const scaleFactorH = (height - padding) / this.#baseHeight;
22799 this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
22800 }
22801 #updateTransform() {
22802 const padding = this.#getPadding() / 2;
22803 this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
22804 }
22805 static #buildPath2D(bezier) {
22806 const path2D = new Path2D();
22807 for (let i = 0, ii = bezier.length; i < ii; i++) {
22808 const [first, control1, control2, second] = bezier[i];
22809 if (i === 0) {
22810 path2D.moveTo(...first);
22811 }
22812 path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
22813 }
22814 return path2D;
22815 }
22816 static #toPDFCoordinates(points, rect, rotation) {
22817 const [blX, blY, trX, trY] = rect;
22818 switch (rotation) {
22819 case 0:
22820 for (let i = 0, ii = points.length; i < ii; i += 2) {
22821 points[i] += blX;
22822 points[i + 1] = trY - points[i + 1];
22823 }
22824 break;
22825 case 90:
22826 for (let i = 0, ii = points.length; i < ii; i += 2) {
22827 const x = points[i];
22828 points[i] = points[i + 1] + blX;
22829 points[i + 1] = x + blY;
22830 }
22831 break;
22832 case 180:
22833 for (let i = 0, ii = points.length; i < ii; i += 2) {
22834 points[i] = trX - points[i];
22835 points[i + 1] += blY;
22836 }
22837 break;
22838 case 270:
22839 for (let i = 0, ii = points.length; i < ii; i += 2) {
22840 const x = points[i];
22841 points[i] = trX - points[i + 1];
22842 points[i + 1] = trY - x;
22843 }
22844 break;
22845 default:
22846 throw new Error("Invalid rotation");
22847 }
22848 return points;
22849 }
22850 static #fromPDFCoordinates(points, rect, rotation) {
22851 const [blX, blY, trX, trY] = rect;
22852 switch (rotation) {
22853 case 0:
22854 for (let i = 0, ii = points.length; i < ii; i += 2) {
22855 points[i] -= blX;
22856 points[i + 1] = trY - points[i + 1];
22857 }
22858 break;
22859 case 90:
22860 for (let i = 0, ii = points.length; i < ii; i += 2) {
22861 const x = points[i];
22862 points[i] = points[i + 1] - blY;
22863 points[i + 1] = x - blX;
22864 }
22865 break;
22866 case 180:
22867 for (let i = 0, ii = points.length; i < ii; i += 2) {
22868 points[i] = trX - points[i];
22869 points[i + 1] -= blY;
22870 }
22871 break;
22872 case 270:
22873 for (let i = 0, ii = points.length; i < ii; i += 2) {
22874 const x = points[i];
22875 points[i] = trY - points[i + 1];
22876 points[i + 1] = trX - x;
22877 }
22878 break;
22879 default:
22880 throw new Error("Invalid rotation");
22881 }
22882 return points;
22883 }
22884 #serializePaths(s, tx, ty, rect) {
22885 const paths = [];
22886 const padding = this.thickness / 2;
22887 const shiftX = s * tx + padding;
22888 const shiftY = s * ty + padding;
22889 for (const bezier of this.paths) {
22890 const buffer = [];
22891 const points = [];
22892 for (let j = 0, jj = bezier.length; j < jj; j++) {
22893 const [first, control1, control2, second] = bezier[j];
22894 if (first[0] === second[0] && first[1] === second[1] && jj === 1) {
22895 const p0 = s * first[0] + shiftX;
22896 const p1 = s * first[1] + shiftY;
22897 buffer.push(p0, p1);
22898 points.push(p0, p1);
22899 break;
22900 }
22901 const p10 = s * first[0] + shiftX;
22902 const p11 = s * first[1] + shiftY;
22903 const p20 = s * control1[0] + shiftX;
22904 const p21 = s * control1[1] + shiftY;
22905 const p30 = s * control2[0] + shiftX;
22906 const p31 = s * control2[1] + shiftY;
22907 const p40 = s * second[0] + shiftX;
22908 const p41 = s * second[1] + shiftY;
22909 if (j === 0) {
22910 buffer.push(p10, p11);
22911 points.push(p10, p11);
22912 }
22913 buffer.push(p20, p21, p30, p31, p40, p41);
22914 points.push(p20, p21);
22915 if (j === jj - 1) {
22916 points.push(p40, p41);
22917 }
22918 }
22919 paths.push({
22920 bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation),
22921 points: InkEditor.#toPDFCoordinates(points, rect, this.rotation)
22922 });
22923 }
22924 return paths;
22925 }
22926 #getBbox() {
22927 let xMin = Infinity;
22928 let xMax = -Infinity;
22929 let yMin = Infinity;
22930 let yMax = -Infinity;
22931 for (const path of this.paths) {
22932 for (const [first, control1, control2, second] of path) {
22933 const bbox = Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
22934 xMin = Math.min(xMin, bbox[0]);
22935 yMin = Math.min(yMin, bbox[1]);
22936 xMax = Math.max(xMax, bbox[2]);
22937 yMax = Math.max(yMax, bbox[3]);
22938 }
22939 }
22940 return [xMin, yMin, xMax, yMax];
22941 }
22942 #getPadding() {
22943 return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
22944 }
22945 #fitToContent(firstTime = false) {
22946 if (this.isEmpty()) {
22947 return;
22948 }
22949 if (!this.#disableEditing) {
22950 this.#redraw();
22951 return;
22952 }
22953 const bbox = this.#getBbox();
22954 const padding = this.#getPadding();
22955 this.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
22956 this.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
22957 const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
22958 const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
22959 const [parentWidth, parentHeight] = this.parentDimensions;
22960 this.width = width / parentWidth;
22961 this.height = height / parentHeight;
22962 this.setAspectRatio(width, height);
22963 const prevTranslationX = this.translationX;
22964 const prevTranslationY = this.translationY;
22965 this.translationX = -bbox[0];
22966 this.translationY = -bbox[1];
22967 this.#setCanvasDims();
22968 this.#redraw();
22969 this.#realWidth = width;
22970 this.#realHeight = height;
22971 this.setDims(width, height);
22972 const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
22973 this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
22974 }
22975 static deserialize(data, parent, uiManager) {
22976 if (data instanceof InkAnnotationElement) {
22977 return null;
22978 }
22979 const editor = super.deserialize(data, parent, uiManager);
22980 editor.thickness = data.thickness;
22981 editor.color = Util.makeHexColor(...data.color);
22982 editor.opacity = data.opacity;
22983 const [pageWidth, pageHeight] = editor.pageDimensions;
22984 const width = editor.width * pageWidth;
22985 const height = editor.height * pageHeight;
22986 const scaleFactor = editor.parentScale;
22987 const padding = data.thickness / 2;
22988 editor.#disableEditing = true;
22989 editor.#realWidth = Math.round(width);
22990 editor.#realHeight = Math.round(height);
22991 const {
22992 paths,
22993 rect,
22994 rotation
22995 } = data;
22996 for (let {
22997 bezier
22998 } of paths) {
22999 bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation);
23000 const path = [];
23001 editor.paths.push(path);
23002 let p0 = scaleFactor * (bezier[0] - padding);
23003 let p1 = scaleFactor * (bezier[1] - padding);
23004 for (let i = 2, ii = bezier.length; i < ii; i += 6) {
23005 const p10 = scaleFactor * (bezier[i] - padding);
23006 const p11 = scaleFactor * (bezier[i + 1] - padding);
23007 const p20 = scaleFactor * (bezier[i + 2] - padding);
23008 const p21 = scaleFactor * (bezier[i + 3] - padding);
23009 const p30 = scaleFactor * (bezier[i + 4] - padding);
23010 const p31 = scaleFactor * (bezier[i + 5] - padding);
23011 path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
23012 p0 = p30;
23013 p1 = p31;
23014 }
23015 const path2D = this.#buildPath2D(path);
23016 editor.bezierPath2D.push(path2D);
23017 }
23018 const bbox = editor.#getBbox();
23019 editor.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
23020 editor.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
23021 editor.#setScaleFactor(width, height);
23022 return editor;
23023 }
23024 serialize() {
23025 if (this.isEmpty()) {
23026 return null;
23027 }
23028 const rect = this.getRect(0, 0);
23029 const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
23030 return {
23031 annotationType: AnnotationEditorType.INK,
23032 color,
23033 thickness: this.thickness,
23034 opacity: this.opacity,
23035 paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect),
23036 pageIndex: this.pageIndex,
23037 rect,
23038 rotation: this.rotation,
23039 structTreeParentId: this._structTreeParentId
23040 };
23041 }
23042 }
23043
23044 ;// CONCATENATED MODULE: ./src/display/editor/stamp.js
23045
23046
23047
23048
23049
23050
23051
23052 class StampEditor extends AnnotationEditor {
23053 #bitmap = null;
23054 #bitmapId = null;
23055 #bitmapPromise = null;
23056 #bitmapUrl = null;
23057 #bitmapFile = null;
23058 #bitmapFileName = "";
23059 #canvas = null;
23060 #observer = null;
23061 #resizeTimeoutId = null;
23062 #isSvg = false;
23063 #hasBeenAddedInUndoStack = false;
23064 static _type = "stamp";
23065 static _editorType = AnnotationEditorType.STAMP;
23066 constructor(params) {
23067 super({
23068 ...params,
23069 name: "stampEditor"
23070 });
23071 this.#bitmapUrl = params.bitmapUrl;
23072 this.#bitmapFile = params.bitmapFile;
23073 }
23074 static initialize(l10n, uiManager) {
23075 AnnotationEditor.initialize(l10n, uiManager);
23076 }
23077 static get supportedTypes() {
23078 const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
23079 return shadow(this, "supportedTypes", types.map(type => `image/${type}`));
23080 }
23081 static get supportedTypesStr() {
23082 return shadow(this, "supportedTypesStr", this.supportedTypes.join(","));
23083 }
23084 static isHandlingMimeForPasting(mime) {
23085 return this.supportedTypes.includes(mime);
23086 }
23087 static paste(item, parent) {
23088 parent.pasteEditor(AnnotationEditorType.STAMP, {
23089 bitmapFile: item.getAsFile()
23090 });
23091 }
23092 #getBitmapFetched(data, fromId = false) {
23093 if (!data) {
23094 this.remove();
23095 return;
23096 }
23097 this.#bitmap = data.bitmap;
23098 if (!fromId) {
23099 this.#bitmapId = data.id;
23100 this.#isSvg = data.isSvg;
23101 }
23102 if (data.file) {
23103 this.#bitmapFileName = data.file.name;
23104 }
23105 this.#createCanvas();
23106 }
23107 #getBitmapDone() {
23108 this.#bitmapPromise = null;
23109 this._uiManager.enableWaiting(false);
23110 if (this.#canvas) {
23111 this.div.focus();
23112 }
23113 }
23114 #getBitmap() {
23115 if (this.#bitmapId) {
23116 this._uiManager.enableWaiting(true);
23117 this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
23118 return;
23119 }
23120 if (this.#bitmapUrl) {
23121 const url = this.#bitmapUrl;
23122 this.#bitmapUrl = null;
23123 this._uiManager.enableWaiting(true);
23124 this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
23125 return;
23126 }
23127 if (this.#bitmapFile) {
23128 const file = this.#bitmapFile;
23129 this.#bitmapFile = null;
23130 this._uiManager.enableWaiting(true);
23131 this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
23132 return;
23133 }
23134 const input = document.createElement("input");
23135 input.type = "file";
23136 input.accept = StampEditor.supportedTypesStr;
23137 this.#bitmapPromise = new Promise(resolve => {
23138 input.addEventListener("change", async () => {
23139 if (!input.files || input.files.length === 0) {
23140 this.remove();
23141 } else {
23142 this._uiManager.enableWaiting(true);
23143 const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
23144 this.#getBitmapFetched(data);
23145 }
23146 resolve();
23147 });
23148 input.addEventListener("cancel", () => {
23149 this.remove();
23150 resolve();
23151 });
23152 }).finally(() => this.#getBitmapDone());
23153 input.click();
23154 }
23155 remove() {
23156 if (this.#bitmapId) {
23157 this.#bitmap = null;
23158 this._uiManager.imageManager.deleteId(this.#bitmapId);
23159 this.#canvas?.remove();
23160 this.#canvas = null;
23161 this.#observer?.disconnect();
23162 this.#observer = null;
23163 if (this.#resizeTimeoutId) {
23164 clearTimeout(this.#resizeTimeoutId);
23165 this.#resizeTimeoutId = null;
23166 }
23167 }
23168 super.remove();
23169 }
23170 rebuild() {
23171 if (!this.parent) {
23172 if (this.#bitmapId) {
23173 this.#getBitmap();
23174 }
23175 return;
23176 }
23177 super.rebuild();
23178 if (this.div === null) {
23179 return;
23180 }
23181 if (this.#bitmapId && this.#canvas === null) {
23182 this.#getBitmap();
23183 }
23184 if (!this.isAttachedToDOM) {
23185 this.parent.add(this);
23186 }
23187 }
23188 onceAdded() {
23189 this._isDraggable = true;
23190 this.div.focus();
23191 }
23192 isEmpty() {
23193 return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId);
23194 }
23195 get isResizable() {
23196 return true;
23197 }
23198 render() {
23199 if (this.div) {
23200 return this.div;
23201 }
23202 let baseX, baseY;
23203 if (this.width) {
23204 baseX = this.x;
23205 baseY = this.y;
23206 }
23207 super.render();
23208 this.div.hidden = true;
23209 this.addAltTextButton();
23210 if (this.#bitmap) {
23211 this.#createCanvas();
23212 } else {
23213 this.#getBitmap();
23214 }
23215 if (this.width) {
23216 const [parentWidth, parentHeight] = this.parentDimensions;
23217 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
23218 }
23219 return this.div;
23220 }
23221 #createCanvas() {
23222 const {
23223 div
23224 } = this;
23225 let {
23226 width,
23227 height
23228 } = this.#bitmap;
23229 const [pageWidth, pageHeight] = this.pageDimensions;
23230 const MAX_RATIO = 0.75;
23231 if (this.width) {
23232 width = this.width * pageWidth;
23233 height = this.height * pageHeight;
23234 } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
23235 const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
23236 width *= factor;
23237 height *= factor;
23238 }
23239 const [parentWidth, parentHeight] = this.parentDimensions;
23240 this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
23241 this._uiManager.enableWaiting(false);
23242 const canvas = this.#canvas = document.createElement("canvas");
23243 div.append(canvas);
23244 div.hidden = false;
23245 this.#drawBitmap(width, height);
23246 this.#createObserver();
23247 if (!this.#hasBeenAddedInUndoStack) {
23248 this.parent.addUndoableEditor(this);
23249 this.#hasBeenAddedInUndoStack = true;
23250 }
23251 this._reportTelemetry({
23252 action: "inserted_image"
23253 });
23254 if (this.#bitmapFileName) {
23255 canvas.setAttribute("aria-label", this.#bitmapFileName);
23256 }
23257 }
23258 #setDimensions(width, height) {
23259 const [parentWidth, parentHeight] = this.parentDimensions;
23260 this.width = width / parentWidth;
23261 this.height = height / parentHeight;
23262 this.setDims(width, height);
23263 if (this._initialOptions?.isCentered) {
23264 this.center();
23265 } else {
23266 this.fixAndSetPosition();
23267 }
23268 this._initialOptions = null;
23269 if (this.#resizeTimeoutId !== null) {
23270 clearTimeout(this.#resizeTimeoutId);
23271 }
23272 const TIME_TO_WAIT = 200;
23273 this.#resizeTimeoutId = setTimeout(() => {
23274 this.#resizeTimeoutId = null;
23275 this.#drawBitmap(width, height);
23276 }, TIME_TO_WAIT);
23277 }
23278 #scaleBitmap(width, height) {
23279 const {
23280 width: bitmapWidth,
23281 height: bitmapHeight
23282 } = this.#bitmap;
23283 let newWidth = bitmapWidth;
23284 let newHeight = bitmapHeight;
23285 let bitmap = this.#bitmap;
23286 while (newWidth > 2 * width || newHeight > 2 * height) {
23287 const prevWidth = newWidth;
23288 const prevHeight = newHeight;
23289 if (newWidth > 2 * width) {
23290 newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
23291 }
23292 if (newHeight > 2 * height) {
23293 newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
23294 }
23295 const offscreen = new OffscreenCanvas(newWidth, newHeight);
23296 const ctx = offscreen.getContext("2d");
23297 ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
23298 bitmap = offscreen.transferToImageBitmap();
23299 }
23300 return bitmap;
23301 }
23302 #drawBitmap(width, height) {
23303 width = Math.ceil(width);
23304 height = Math.ceil(height);
23305 const canvas = this.#canvas;
23306 if (!canvas || canvas.width === width && canvas.height === height) {
23307 return;
23308 }
23309 canvas.width = width;
23310 canvas.height = height;
23311 const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(width, height);
23312 if (this._uiManager.hasMLManager && !this.hasAltText()) {
23313 const offscreen = new OffscreenCanvas(width, height);
23314 const ctx = offscreen.getContext("2d");
23315 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height);
23316 this._uiManager.mlGuess({
23317 service: "image-to-text",
23318 request: {
23319 data: ctx.getImageData(0, 0, width, height).data,
23320 width,
23321 height,
23322 channels: 4
23323 }
23324 }).then(response => {
23325 const altText = response?.output || "";
23326 if (this.parent && altText && !this.hasAltText()) {
23327 this.altTextData = {
23328 altText,
23329 decorative: false
23330 };
23331 }
23332 });
23333 }
23334 const ctx = canvas.getContext("2d");
23335 ctx.filter = this._uiManager.hcmFilter;
23336 ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height);
23337 }
23338 getImageForAltText() {
23339 return this.#canvas;
23340 }
23341 #serializeBitmap(toUrl) {
23342 if (toUrl) {
23343 if (this.#isSvg) {
23344 const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
23345 if (url) {
23346 return url;
23347 }
23348 }
23349 const canvas = document.createElement("canvas");
23350 ({
23351 width: canvas.width,
23352 height: canvas.height
23353 } = this.#bitmap);
23354 const ctx = canvas.getContext("2d");
23355 ctx.drawImage(this.#bitmap, 0, 0);
23356 return canvas.toDataURL();
23357 }
23358 if (this.#isSvg) {
23359 const [pageWidth, pageHeight] = this.pageDimensions;
23360 const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
23361 const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
23362 const offscreen = new OffscreenCanvas(width, height);
23363 const ctx = offscreen.getContext("2d");
23364 ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
23365 return offscreen.transferToImageBitmap();
23366 }
23367 return structuredClone(this.#bitmap);
23368 }
23369 #createObserver() {
23370 this.#observer = new ResizeObserver(entries => {
23371 const rect = entries[0].contentRect;
23372 if (rect.width && rect.height) {
23373 this.#setDimensions(rect.width, rect.height);
23374 }
23375 });
23376 this.#observer.observe(this.div);
23377 }
23378 static deserialize(data, parent, uiManager) {
23379 if (data instanceof StampAnnotationElement) {
23380 return null;
23381 }
23382 const editor = super.deserialize(data, parent, uiManager);
23383 const {
23384 rect,
23385 bitmapUrl,
23386 bitmapId,
23387 isSvg,
23388 accessibilityData
23389 } = data;
23390 if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
23391 editor.#bitmapId = bitmapId;
23392 } else {
23393 editor.#bitmapUrl = bitmapUrl;
23394 }
23395 editor.#isSvg = isSvg;
23396 const [parentWidth, parentHeight] = editor.pageDimensions;
23397 editor.width = (rect[2] - rect[0]) / parentWidth;
23398 editor.height = (rect[3] - rect[1]) / parentHeight;
23399 if (accessibilityData) {
23400 editor.altTextData = accessibilityData;
23401 }
23402 return editor;
23403 }
23404 serialize(isForCopying = false, context = null) {
23405 if (this.isEmpty()) {
23406 return null;
23407 }
23408 const serialized = {
23409 annotationType: AnnotationEditorType.STAMP,
23410 bitmapId: this.#bitmapId,
23411 pageIndex: this.pageIndex,
23412 rect: this.getRect(0, 0),
23413 rotation: this.rotation,
23414 isSvg: this.#isSvg,
23415 structTreeParentId: this._structTreeParentId
23416 };
23417 if (isForCopying) {
23418 serialized.bitmapUrl = this.#serializeBitmap(true);
23419 serialized.accessibilityData = this.altTextData;
23420 return serialized;
23421 }
23422 const {
23423 decorative,
23424 altText
23425 } = this.altTextData;
23426 if (!decorative && altText) {
23427 serialized.accessibilityData = {
23428 type: "Figure",
23429 alt: altText
23430 };
23431 }
23432 if (context === null) {
23433 return serialized;
23434 }
23435 context.stamps ||= new Map();
23436 const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
23437 if (!context.stamps.has(this.#bitmapId)) {
23438 context.stamps.set(this.#bitmapId, {
23439 area,
23440 serialized
23441 });
23442 serialized.bitmap = this.#serializeBitmap(false);
23443 } else if (this.#isSvg) {
23444 const prevData = context.stamps.get(this.#bitmapId);
23445 if (area > prevData.area) {
23446 prevData.area = area;
23447 prevData.serialized.bitmap.close();
23448 prevData.serialized.bitmap = this.#serializeBitmap(false);
23449 }
23450 }
23451 return serialized;
23452 }
23453 }
23454
23455 ;// CONCATENATED MODULE: ./src/display/editor/annotation_editor_layer.js
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471 class AnnotationEditorLayer {
23472 #accessibilityManager;
23473 #allowClick = false;
23474 #annotationLayer = null;
23475 #boundPointerup = null;
23476 #boundPointerdown = null;
23477 #boundTextLayerPointerDown = null;
23478 #editorFocusTimeoutId = null;
23479 #editors = new Map();
23480 #hadPointerDown = false;
23481 #isCleaningUp = false;
23482 #isDisabling = false;
23483 #textLayer = null;
23484 #uiManager;
23485 static _initialized = false;
23486 static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type]));
23487 constructor({
23488 uiManager,
23489 pageIndex,
23490 div,
23491 accessibilityManager,
23492 annotationLayer,
23493 drawLayer,
23494 textLayer,
23495 viewport,
23496 l10n
23497 }) {
23498 const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
23499 if (!AnnotationEditorLayer._initialized) {
23500 AnnotationEditorLayer._initialized = true;
23501 for (const editorType of editorTypes) {
23502 editorType.initialize(l10n, uiManager);
23503 }
23504 }
23505 uiManager.registerEditorTypes(editorTypes);
23506 this.#uiManager = uiManager;
23507 this.pageIndex = pageIndex;
23508 this.div = div;
23509 this.#accessibilityManager = accessibilityManager;
23510 this.#annotationLayer = annotationLayer;
23511 this.viewport = viewport;
23512 this.#textLayer = textLayer;
23513 this.drawLayer = drawLayer;
23514 this.#uiManager.addLayer(this);
23515 }
23516 get isEmpty() {
23517 return this.#editors.size === 0;
23518 }
23519 get isInvisible() {
23520 return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
23521 }
23522 updateToolbar(mode) {
23523 this.#uiManager.updateToolbar(mode);
23524 }
23525 updateMode(mode = this.#uiManager.getMode()) {
23526 this.#cleanup();
23527 switch (mode) {
23528 case AnnotationEditorType.NONE:
23529 this.disableTextSelection();
23530 this.togglePointerEvents(false);
23531 this.toggleAnnotationLayerPointerEvents(true);
23532 this.disableClick();
23533 return;
23534 case AnnotationEditorType.INK:
23535 this.addInkEditorIfNeeded(false);
23536 this.disableTextSelection();
23537 this.togglePointerEvents(true);
23538 this.disableClick();
23539 break;
23540 case AnnotationEditorType.HIGHLIGHT:
23541 this.enableTextSelection();
23542 this.togglePointerEvents(false);
23543 this.disableClick();
23544 break;
23545 default:
23546 this.disableTextSelection();
23547 this.togglePointerEvents(true);
23548 this.enableClick();
23549 }
23550 this.toggleAnnotationLayerPointerEvents(false);
23551 const {
23552 classList
23553 } = this.div;
23554 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
23555 classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
23556 }
23557 this.div.hidden = false;
23558 }
23559 hasTextLayer(textLayer) {
23560 return textLayer === this.#textLayer?.div;
23561 }
23562 addInkEditorIfNeeded(isCommitting) {
23563 if (this.#uiManager.getMode() !== AnnotationEditorType.INK) {
23564 return;
23565 }
23566 if (!isCommitting) {
23567 for (const editor of this.#editors.values()) {
23568 if (editor.isEmpty()) {
23569 editor.setInBackground();
23570 return;
23571 }
23572 }
23573 }
23574 const editor = this.createAndAddNewEditor({
23575 offsetX: 0,
23576 offsetY: 0
23577 }, false);
23578 editor.setInBackground();
23579 }
23580 setEditingState(isEditing) {
23581 this.#uiManager.setEditingState(isEditing);
23582 }
23583 addCommands(params) {
23584 this.#uiManager.addCommands(params);
23585 }
23586 togglePointerEvents(enabled = false) {
23587 this.div.classList.toggle("disabled", !enabled);
23588 }
23589 toggleAnnotationLayerPointerEvents(enabled = false) {
23590 this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
23591 }
23592 enable() {
23593 this.div.tabIndex = 0;
23594 this.togglePointerEvents(true);
23595 const annotationElementIds = new Set();
23596 for (const editor of this.#editors.values()) {
23597 editor.enableEditing();
23598 editor.show(true);
23599 if (editor.annotationElementId) {
23600 this.#uiManager.removeChangedExistingAnnotation(editor);
23601 annotationElementIds.add(editor.annotationElementId);
23602 }
23603 }
23604 if (!this.#annotationLayer) {
23605 return;
23606 }
23607 const editables = this.#annotationLayer.getEditableAnnotations();
23608 for (const editable of editables) {
23609 editable.hide();
23610 if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
23611 continue;
23612 }
23613 if (annotationElementIds.has(editable.data.id)) {
23614 continue;
23615 }
23616 const editor = this.deserialize(editable);
23617 if (!editor) {
23618 continue;
23619 }
23620 this.addOrRebuild(editor);
23621 editor.enableEditing();
23622 }
23623 }
23624 disable() {
23625 this.#isDisabling = true;
23626 this.div.tabIndex = -1;
23627 this.togglePointerEvents(false);
23628 const changedAnnotations = new Map();
23629 const resetAnnotations = new Map();
23630 for (const editor of this.#editors.values()) {
23631 editor.disableEditing();
23632 if (!editor.annotationElementId) {
23633 continue;
23634 }
23635 if (editor.serialize() !== null) {
23636 changedAnnotations.set(editor.annotationElementId, editor);
23637 continue;
23638 } else {
23639 resetAnnotations.set(editor.annotationElementId, editor);
23640 }
23641 this.getEditableAnnotation(editor.annotationElementId)?.show();
23642 editor.remove();
23643 }
23644 if (this.#annotationLayer) {
23645 const editables = this.#annotationLayer.getEditableAnnotations();
23646 for (const editable of editables) {
23647 const {
23648 id
23649 } = editable.data;
23650 if (this.#uiManager.isDeletedAnnotationElement(id)) {
23651 continue;
23652 }
23653 let editor = resetAnnotations.get(id);
23654 if (editor) {
23655 editor.resetAnnotationElement(editable);
23656 editor.show(false);
23657 editable.show();
23658 continue;
23659 }
23660 editor = changedAnnotations.get(id);
23661 if (editor) {
23662 this.#uiManager.addChangedExistingAnnotation(editor);
23663 editor.renderAnnotationElement(editable);
23664 editor.show(false);
23665 }
23666 editable.show();
23667 }
23668 }
23669 this.#cleanup();
23670 if (this.isEmpty) {
23671 this.div.hidden = true;
23672 }
23673 const {
23674 classList
23675 } = this.div;
23676 for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
23677 classList.remove(`${editorType._type}Editing`);
23678 }
23679 this.disableTextSelection();
23680 this.toggleAnnotationLayerPointerEvents(true);
23681 this.#isDisabling = false;
23682 }
23683 getEditableAnnotation(id) {
23684 return this.#annotationLayer?.getEditableAnnotation(id) || null;
23685 }
23686 setActiveEditor(editor) {
23687 const currentActive = this.#uiManager.getActive();
23688 if (currentActive === editor) {
23689 return;
23690 }
23691 this.#uiManager.setActiveEditor(editor);
23692 }
23693 enableTextSelection() {
23694 this.div.tabIndex = -1;
23695 if (this.#textLayer?.div && !this.#boundTextLayerPointerDown) {
23696 this.#boundTextLayerPointerDown = this.#textLayerPointerDown.bind(this);
23697 this.#textLayer.div.addEventListener("pointerdown", this.#boundTextLayerPointerDown);
23698 this.#textLayer.div.classList.add("highlighting");
23699 }
23700 }
23701 disableTextSelection() {
23702 this.div.tabIndex = 0;
23703 if (this.#textLayer?.div && this.#boundTextLayerPointerDown) {
23704 this.#textLayer.div.removeEventListener("pointerdown", this.#boundTextLayerPointerDown);
23705 this.#boundTextLayerPointerDown = null;
23706 this.#textLayer.div.classList.remove("highlighting");
23707 }
23708 }
23709 #textLayerPointerDown(event) {
23710 this.#uiManager.unselectAll();
23711 if (event.target === this.#textLayer.div) {
23712 const {
23713 isMac
23714 } = util_FeatureTest.platform;
23715 if (event.button !== 0 || event.ctrlKey && isMac) {
23716 return;
23717 }
23718 this.#uiManager.showAllEditors("highlight", true, true);
23719 this.#textLayer.div.classList.add("free");
23720 HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", event);
23721 this.#textLayer.div.addEventListener("pointerup", () => {
23722 this.#textLayer.div.classList.remove("free");
23723 }, {
23724 once: true
23725 });
23726 event.preventDefault();
23727 }
23728 }
23729 enableClick() {
23730 if (this.#boundPointerdown) {
23731 return;
23732 }
23733 this.#boundPointerdown = this.pointerdown.bind(this);
23734 this.#boundPointerup = this.pointerup.bind(this);
23735 this.div.addEventListener("pointerdown", this.#boundPointerdown);
23736 this.div.addEventListener("pointerup", this.#boundPointerup);
23737 }
23738 disableClick() {
23739 if (!this.#boundPointerdown) {
23740 return;
23741 }
23742 this.div.removeEventListener("pointerdown", this.#boundPointerdown);
23743 this.div.removeEventListener("pointerup", this.#boundPointerup);
23744 this.#boundPointerdown = null;
23745 this.#boundPointerup = null;
23746 }
23747 attach(editor) {
23748 this.#editors.set(editor.id, editor);
23749 const {
23750 annotationElementId
23751 } = editor;
23752 if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
23753 this.#uiManager.removeDeletedAnnotationElement(editor);
23754 }
23755 }
23756 detach(editor) {
23757 this.#editors.delete(editor.id);
23758 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
23759 if (!this.#isDisabling && editor.annotationElementId) {
23760 this.#uiManager.addDeletedAnnotationElement(editor);
23761 }
23762 }
23763 remove(editor) {
23764 this.detach(editor);
23765 this.#uiManager.removeEditor(editor);
23766 editor.div.remove();
23767 editor.isAttachedToDOM = false;
23768 if (!this.#isCleaningUp) {
23769 this.addInkEditorIfNeeded(false);
23770 }
23771 }
23772 changeParent(editor) {
23773 if (editor.parent === this) {
23774 return;
23775 }
23776 if (editor.parent && editor.annotationElementId) {
23777 this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
23778 AnnotationEditor.deleteAnnotationElement(editor);
23779 editor.annotationElementId = null;
23780 }
23781 this.attach(editor);
23782 editor.parent?.detach(editor);
23783 editor.setParent(this);
23784 if (editor.div && editor.isAttachedToDOM) {
23785 editor.div.remove();
23786 this.div.append(editor.div);
23787 }
23788 }
23789 add(editor) {
23790 if (editor.parent === this && editor.isAttachedToDOM) {
23791 return;
23792 }
23793 this.changeParent(editor);
23794 this.#uiManager.addEditor(editor);
23795 this.attach(editor);
23796 if (!editor.isAttachedToDOM) {
23797 const div = editor.render();
23798 this.div.append(div);
23799 editor.isAttachedToDOM = true;
23800 }
23801 editor.fixAndSetPosition();
23802 editor.onceAdded();
23803 this.#uiManager.addToAnnotationStorage(editor);
23804 editor._reportTelemetry(editor.telemetryInitialData);
23805 }
23806 moveEditorInDOM(editor) {
23807 if (!editor.isAttachedToDOM) {
23808 return;
23809 }
23810 const {
23811 activeElement
23812 } = document;
23813 if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
23814 editor._focusEventsAllowed = false;
23815 this.#editorFocusTimeoutId = setTimeout(() => {
23816 this.#editorFocusTimeoutId = null;
23817 if (!editor.div.contains(document.activeElement)) {
23818 editor.div.addEventListener("focusin", () => {
23819 editor._focusEventsAllowed = true;
23820 }, {
23821 once: true
23822 });
23823 activeElement.focus();
23824 } else {
23825 editor._focusEventsAllowed = true;
23826 }
23827 }, 0);
23828 }
23829 editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
23830 }
23831 addOrRebuild(editor) {
23832 if (editor.needsToBeRebuilt()) {
23833 editor.parent ||= this;
23834 editor.rebuild();
23835 editor.show();
23836 } else {
23837 this.add(editor);
23838 }
23839 }
23840 addUndoableEditor(editor) {
23841 const cmd = () => editor._uiManager.rebuild(editor);
23842 const undo = () => {
23843 editor.remove();
23844 };
23845 this.addCommands({
23846 cmd,
23847 undo,
23848 mustExec: false
23849 });
23850 }
23851 getNextId() {
23852 return this.#uiManager.getId();
23853 }
23854 get #currentEditorType() {
23855 return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
23856 }
23857 #createNewEditor(params) {
23858 const editorType = this.#currentEditorType;
23859 return editorType ? new editorType.prototype.constructor(params) : null;
23860 }
23861 canCreateNewEmptyEditor() {
23862 return this.#currentEditorType?.canCreateNewEmptyEditor();
23863 }
23864 pasteEditor(mode, params) {
23865 this.#uiManager.updateToolbar(mode);
23866 this.#uiManager.updateMode(mode);
23867 const {
23868 offsetX,
23869 offsetY
23870 } = this.#getCenterPoint();
23871 const id = this.getNextId();
23872 const editor = this.#createNewEditor({
23873 parent: this,
23874 id,
23875 x: offsetX,
23876 y: offsetY,
23877 uiManager: this.#uiManager,
23878 isCentered: true,
23879 ...params
23880 });
23881 if (editor) {
23882 this.add(editor);
23883 }
23884 }
23885 deserialize(data) {
23886 return AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager) || null;
23887 }
23888 createAndAddNewEditor(event, isCentered, data = {}) {
23889 const id = this.getNextId();
23890 const editor = this.#createNewEditor({
23891 parent: this,
23892 id,
23893 x: event.offsetX,
23894 y: event.offsetY,
23895 uiManager: this.#uiManager,
23896 isCentered,
23897 ...data
23898 });
23899 if (editor) {
23900 this.add(editor);
23901 }
23902 return editor;
23903 }
23904 #getCenterPoint() {
23905 const {
23906 x,
23907 y,
23908 width,
23909 height
23910 } = this.div.getBoundingClientRect();
23911 const tlX = Math.max(0, x);
23912 const tlY = Math.max(0, y);
23913 const brX = Math.min(window.innerWidth, x + width);
23914 const brY = Math.min(window.innerHeight, y + height);
23915 const centerX = (tlX + brX) / 2 - x;
23916 const centerY = (tlY + brY) / 2 - y;
23917 const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
23918 return {
23919 offsetX,
23920 offsetY
23921 };
23922 }
23923 addNewEditor() {
23924 this.createAndAddNewEditor(this.#getCenterPoint(), true);
23925 }
23926 setSelected(editor) {
23927 this.#uiManager.setSelected(editor);
23928 }
23929 toggleSelected(editor) {
23930 this.#uiManager.toggleSelected(editor);
23931 }
23932 isSelected(editor) {
23933 return this.#uiManager.isSelected(editor);
23934 }
23935 unselect(editor) {
23936 this.#uiManager.unselect(editor);
23937 }
23938 pointerup(event) {
23939 const {
23940 isMac
23941 } = util_FeatureTest.platform;
23942 if (event.button !== 0 || event.ctrlKey && isMac) {
23943 return;
23944 }
23945 if (event.target !== this.div) {
23946 return;
23947 }
23948 if (!this.#hadPointerDown) {
23949 return;
23950 }
23951 this.#hadPointerDown = false;
23952 if (!this.#allowClick) {
23953 this.#allowClick = true;
23954 return;
23955 }
23956 if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) {
23957 this.#uiManager.unselectAll();
23958 return;
23959 }
23960 this.createAndAddNewEditor(event, false);
23961 }
23962 pointerdown(event) {
23963 if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
23964 this.enableTextSelection();
23965 }
23966 if (this.#hadPointerDown) {
23967 this.#hadPointerDown = false;
23968 return;
23969 }
23970 const {
23971 isMac
23972 } = util_FeatureTest.platform;
23973 if (event.button !== 0 || event.ctrlKey && isMac) {
23974 return;
23975 }
23976 if (event.target !== this.div) {
23977 return;
23978 }
23979 this.#hadPointerDown = true;
23980 const editor = this.#uiManager.getActive();
23981 this.#allowClick = !editor || editor.isEmpty();
23982 }
23983 findNewParent(editor, x, y) {
23984 const layer = this.#uiManager.findParent(x, y);
23985 if (layer === null || layer === this) {
23986 return false;
23987 }
23988 layer.changeParent(editor);
23989 return true;
23990 }
23991 destroy() {
23992 if (this.#uiManager.getActive()?.parent === this) {
23993 this.#uiManager.commitOrRemove();
23994 this.#uiManager.setActiveEditor(null);
23995 }
23996 if (this.#editorFocusTimeoutId) {
23997 clearTimeout(this.#editorFocusTimeoutId);
23998 this.#editorFocusTimeoutId = null;
23999 }
24000 for (const editor of this.#editors.values()) {
24001 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
24002 editor.setParent(null);
24003 editor.isAttachedToDOM = false;
24004 editor.div.remove();
24005 }
24006 this.div = null;
24007 this.#editors.clear();
24008 this.#uiManager.removeLayer(this);
24009 }
24010 #cleanup() {
24011 this.#isCleaningUp = true;
24012 for (const editor of this.#editors.values()) {
24013 if (editor.isEmpty()) {
24014 editor.remove();
24015 }
24016 }
24017 this.#isCleaningUp = false;
24018 }
24019 render({
24020 viewport
24021 }) {
24022 this.viewport = viewport;
24023 setLayerDimensions(this.div, viewport);
24024 for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
24025 this.add(editor);
24026 editor.rebuild();
24027 }
24028 this.updateMode();
24029 }
24030 update({
24031 viewport
24032 }) {
24033 this.#uiManager.commitOrRemove();
24034 this.#cleanup();
24035 const oldRotation = this.viewport.rotation;
24036 const rotation = viewport.rotation;
24037 this.viewport = viewport;
24038 setLayerDimensions(this.div, {
24039 rotation
24040 });
24041 if (oldRotation !== rotation) {
24042 for (const editor of this.#editors.values()) {
24043 editor.rotate(rotation);
24044 }
24045 }
24046 this.addInkEditorIfNeeded(false);
24047 }
24048 get pageDimensions() {
24049 const {
24050 pageWidth,
24051 pageHeight
24052 } = this.viewport.rawDims;
24053 return [pageWidth, pageHeight];
24054 }
24055 get scale() {
24056 return this.#uiManager.viewParameters.realScale;
24057 }
24058 }
24059
24060 ;// CONCATENATED MODULE: ./src/display/draw_layer.js
24061
24062
24063 class DrawLayer {
24064 #parent = null;
24065 #id = 0;
24066 #mapping = new Map();
24067 #toUpdate = new Map();
24068 constructor({
24069 pageIndex
24070 }) {
24071 this.pageIndex = pageIndex;
24072 }
24073 setParent(parent) {
24074 if (!this.#parent) {
24075 this.#parent = parent;
24076 return;
24077 }
24078 if (this.#parent !== parent) {
24079 if (this.#mapping.size > 0) {
24080 for (const root of this.#mapping.values()) {
24081 root.remove();
24082 parent.append(root);
24083 }
24084 }
24085 this.#parent = parent;
24086 }
24087 }
24088 static get _svgFactory() {
24089 return shadow(this, "_svgFactory", new DOMSVGFactory());
24090 }
24091 static #setBox(element, {
24092 x = 0,
24093 y = 0,
24094 width = 1,
24095 height = 1
24096 } = {}) {
24097 const {
24098 style
24099 } = element;
24100 style.top = `${100 * y}%`;
24101 style.left = `${100 * x}%`;
24102 style.width = `${100 * width}%`;
24103 style.height = `${100 * height}%`;
24104 }
24105 #createSVG(box) {
24106 const svg = DrawLayer._svgFactory.create(1, 1, true);
24107 this.#parent.append(svg);
24108 svg.setAttribute("aria-hidden", true);
24109 DrawLayer.#setBox(svg, box);
24110 return svg;
24111 }
24112 #createClipPath(defs, pathId) {
24113 const clipPath = DrawLayer._svgFactory.createElement("clipPath");
24114 defs.append(clipPath);
24115 const clipPathId = `clip_${pathId}`;
24116 clipPath.setAttribute("id", clipPathId);
24117 clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
24118 const clipPathUse = DrawLayer._svgFactory.createElement("use");
24119 clipPath.append(clipPathUse);
24120 clipPathUse.setAttribute("href", `#${pathId}`);
24121 clipPathUse.classList.add("clip");
24122 return clipPathId;
24123 }
24124 highlight(outlines, color, opacity, isPathUpdatable = false) {
24125 const id = this.#id++;
24126 const root = this.#createSVG(outlines.box);
24127 root.classList.add("highlight");
24128 if (outlines.free) {
24129 root.classList.add("free");
24130 }
24131 const defs = DrawLayer._svgFactory.createElement("defs");
24132 root.append(defs);
24133 const path = DrawLayer._svgFactory.createElement("path");
24134 defs.append(path);
24135 const pathId = `path_p${this.pageIndex}_${id}`;
24136 path.setAttribute("id", pathId);
24137 path.setAttribute("d", outlines.toSVGPath());
24138 if (isPathUpdatable) {
24139 this.#toUpdate.set(id, path);
24140 }
24141 const clipPathId = this.#createClipPath(defs, pathId);
24142 const use = DrawLayer._svgFactory.createElement("use");
24143 root.append(use);
24144 root.setAttribute("fill", color);
24145 root.setAttribute("fill-opacity", opacity);
24146 use.setAttribute("href", `#${pathId}`);
24147 this.#mapping.set(id, root);
24148 return {
24149 id,
24150 clipPathId: `url(#${clipPathId})`
24151 };
24152 }
24153 highlightOutline(outlines) {
24154 const id = this.#id++;
24155 const root = this.#createSVG(outlines.box);
24156 root.classList.add("highlightOutline");
24157 const defs = DrawLayer._svgFactory.createElement("defs");
24158 root.append(defs);
24159 const path = DrawLayer._svgFactory.createElement("path");
24160 defs.append(path);
24161 const pathId = `path_p${this.pageIndex}_${id}`;
24162 path.setAttribute("id", pathId);
24163 path.setAttribute("d", outlines.toSVGPath());
24164 path.setAttribute("vector-effect", "non-scaling-stroke");
24165 let maskId;
24166 if (outlines.free) {
24167 root.classList.add("free");
24168 const mask = DrawLayer._svgFactory.createElement("mask");
24169 defs.append(mask);
24170 maskId = `mask_p${this.pageIndex}_${id}`;
24171 mask.setAttribute("id", maskId);
24172 mask.setAttribute("maskUnits", "objectBoundingBox");
24173 const rect = DrawLayer._svgFactory.createElement("rect");
24174 mask.append(rect);
24175 rect.setAttribute("width", "1");
24176 rect.setAttribute("height", "1");
24177 rect.setAttribute("fill", "white");
24178 const use = DrawLayer._svgFactory.createElement("use");
24179 mask.append(use);
24180 use.setAttribute("href", `#${pathId}`);
24181 use.setAttribute("stroke", "none");
24182 use.setAttribute("fill", "black");
24183 use.setAttribute("fill-rule", "nonzero");
24184 use.classList.add("mask");
24185 }
24186 const use1 = DrawLayer._svgFactory.createElement("use");
24187 root.append(use1);
24188 use1.setAttribute("href", `#${pathId}`);
24189 if (maskId) {
24190 use1.setAttribute("mask", `url(#${maskId})`);
24191 }
24192 const use2 = use1.cloneNode();
24193 root.append(use2);
24194 use1.classList.add("mainOutline");
24195 use2.classList.add("secondaryOutline");
24196 this.#mapping.set(id, root);
24197 return id;
24198 }
24199 finalizeLine(id, line) {
24200 const path = this.#toUpdate.get(id);
24201 this.#toUpdate.delete(id);
24202 this.updateBox(id, line.box);
24203 path.setAttribute("d", line.toSVGPath());
24204 }
24205 updateLine(id, line) {
24206 const root = this.#mapping.get(id);
24207 const defs = root.firstChild;
24208 const path = defs.firstChild;
24209 path.setAttribute("d", line.toSVGPath());
24210 }
24211 removeFreeHighlight(id) {
24212 this.remove(id);
24213 this.#toUpdate.delete(id);
24214 }
24215 updatePath(id, line) {
24216 this.#toUpdate.get(id).setAttribute("d", line.toSVGPath());
24217 }
24218 updateBox(id, box) {
24219 DrawLayer.#setBox(this.#mapping.get(id), box);
24220 }
24221 show(id, visible) {
24222 this.#mapping.get(id).classList.toggle("hidden", !visible);
24223 }
24224 rotate(id, angle) {
24225 this.#mapping.get(id).setAttribute("data-main-rotation", angle);
24226 }
24227 changeColor(id, color) {
24228 this.#mapping.get(id).setAttribute("fill", color);
24229 }
24230 changeOpacity(id, opacity) {
24231 this.#mapping.get(id).setAttribute("fill-opacity", opacity);
24232 }
24233 addClass(id, className) {
24234 this.#mapping.get(id).classList.add(className);
24235 }
24236 removeClass(id, className) {
24237 this.#mapping.get(id).classList.remove(className);
24238 }
24239 remove(id) {
24240 if (this.#parent === null) {
24241 return;
24242 }
24243 this.#mapping.get(id).remove();
24244 this.#mapping.delete(id);
24245 }
24246 destroy() {
24247 this.#parent = null;
24248 for (const root of this.#mapping.values()) {
24249 root.remove();
24250 }
24251 this.#mapping.clear();
24252 }
24253 }
24254
24255 ;// CONCATENATED MODULE: ./src/pdf.js
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268 const pdfjsVersion = "4.3.136";
24269 const pdfjsBuild = "0cec64437";
24270
24271 })();
24272
24273 var __webpack_exports__AbortException = __webpack_exports__.AbortException;
24274 var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer;
24275 var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType;
24276 var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType;
24277 var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager;
24278 var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer;
24279 var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode;
24280 var __webpack_exports__CMapCompressionType = __webpack_exports__.CMapCompressionType;
24281 var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker;
24282 var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory;
24283 var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer;
24284 var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest;
24285 var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions;
24286 var __webpack_exports__ImageKind = __webpack_exports__.ImageKind;
24287 var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException;
24288 var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException;
24289 var __webpack_exports__OPS = __webpack_exports__.OPS;
24290 var __webpack_exports__Outliner = __webpack_exports__.Outliner;
24291 var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport;
24292 var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString;
24293 var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker;
24294 var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses;
24295 var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag;
24296 var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch;
24297 var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException;
24298 var __webpack_exports__TextLayer = __webpack_exports__.TextLayer;
24299 var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException;
24300 var __webpack_exports__Util = __webpack_exports__.Util;
24301 var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
24302 var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer;
24303 var __webpack_exports__build = __webpack_exports__.build;
24304 var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl;
24305 var __webpack_exports__fetchData = __webpack_exports__.fetchData;
24306 var __webpack_exports__getDocument = __webpack_exports__.getDocument;
24307 var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl;
24308 var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl;
24309 var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport;
24310 var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme;
24311 var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile;
24312 var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu;
24313 var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode;
24314 var __webpack_exports__renderTextLayer = __webpack_exports__.renderTextLayer;
24315 var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions;
24316 var __webpack_exports__shadow = __webpack_exports__.shadow;
24317 var __webpack_exports__updateTextLayer = __webpack_exports__.updateTextLayer;
24318 var __webpack_exports__version = __webpack_exports__.version;
24319 export { __webpack_exports__AbortException as AbortException, __webpack_exports__AnnotationEditorLayer as AnnotationEditorLayer, __webpack_exports__AnnotationEditorParamsType as AnnotationEditorParamsType, __webpack_exports__AnnotationEditorType as AnnotationEditorType, __webpack_exports__AnnotationEditorUIManager as AnnotationEditorUIManager, __webpack_exports__AnnotationLayer as AnnotationLayer, __webpack_exports__AnnotationMode as AnnotationMode, __webpack_exports__CMapCompressionType as CMapCompressionType, __webpack_exports__ColorPicker as ColorPicker, __webpack_exports__DOMSVGFactory as DOMSVGFactory, __webpack_exports__DrawLayer as DrawLayer, __webpack_exports__FeatureTest as FeatureTest, __webpack_exports__GlobalWorkerOptions as GlobalWorkerOptions, __webpack_exports__ImageKind as ImageKind, __webpack_exports__InvalidPDFException as InvalidPDFException, __webpack_exports__MissingPDFException as MissingPDFException, __webpack_exports__OPS as OPS, __webpack_exports__Outliner as Outliner, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__renderTextLayer as renderTextLayer, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__updateTextLayer as updateTextLayer, __webpack_exports__version as version };
24320
24321 //# sourceMappingURL=pdf.js.map