(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["ClipboardJS"] = factory(); else root["ClipboardJS"] = factory(); })(this, function() { return /******/ (function() { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 686: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; // EXPORTS __webpack_require__.d(__webpack_exports__, { "default": function() { return /* binding */ clipboard; } }); // EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js var tiny_emitter = __webpack_require__(279); var tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter); // EXTERNAL MODULE: ./node_modules/good-listener/src/listen.js var listen = __webpack_require__(370); var listen_default = /*#__PURE__*/__webpack_require__.n(listen); // EXTERNAL MODULE: ./node_modules/select/src/select.js var src_select = __webpack_require__(817); var select_default = /*#__PURE__*/__webpack_require__.n(src_select); ;// CONCATENATED MODULE: ./src/common/command.js /** * Executes a given operation type. * @param {String} type * @return {Boolean} */ function command(type) { try { return document.execCommand(type); } catch (err) { return false; } } ;// CONCATENATED MODULE: ./src/actions/cut.js /** * Cut action wrapper. * @param {String|HTMLElement} target * @return {String} */ var ClipboardActionCut = function ClipboardActionCut(target) { var selectedText = select_default()(target); command('cut'); return selectedText; }; /* harmony default export */ var actions_cut = (ClipboardActionCut); ;// CONCATENATED MODULE: ./src/common/create-fake-element.js /** * Creates a fake textarea element with a value. * @param {String} value * @return {HTMLElement} */ function createFakeElement(value) { var isRTL = document.documentElement.getAttribute('dir') === 'rtl'; var fakeElement = document.createElement('textarea'); // Prevent zooming on iOS fakeElement.style.fontSize = '12pt'; // Reset box model fakeElement.style.border = '0'; fakeElement.style.padding = '0'; fakeElement.style.margin = '0'; // Move element out of screen horizontally fakeElement.style.position = 'absolute'; fakeElement.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; fakeElement.style.top = "".concat(yPosition, "px"); fakeElement.setAttribute('readonly', ''); fakeElement.value = value; return fakeElement; } ;// CONCATENATED MODULE: ./src/actions/copy.js /** * Create fake copy action wrapper using a fake element. * @param {String} target * @param {Object} options * @return {String} */ var fakeCopyAction = function fakeCopyAction(value, options) { var fakeElement = createFakeElement(value); options.container.appendChild(fakeElement); var selectedText = select_default()(fakeElement); command('copy'); fakeElement.remove(); return selectedText; }; /** * Copy action wrapper. * @param {String|HTMLElement} target * @param {Object} options * @return {String} */ var ClipboardActionCopy = function ClipboardActionCopy(target) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { container: document.body }; var selectedText = ''; if (typeof target === 'string') { selectedText = fakeCopyAction(target, options); } else if (target instanceof HTMLInputElement && !['text', 'search', 'url', 'tel', 'password'].includes(target === null || target === void 0 ? void 0 : target.type)) { // If input type doesn't support `setSelectionRange`. Simulate it. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange selectedText = fakeCopyAction(target.value, options); } else { selectedText = select_default()(target); command('copy'); } return selectedText; }; /* harmony default export */ var actions_copy = (ClipboardActionCopy); ;// CONCATENATED MODULE: ./src/actions/default.js function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Inner function which performs selection from either `text` or `target` * properties and then executes copy or cut operations. * @param {Object} options */ var ClipboardActionDefault = function ClipboardActionDefault() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // Defines base properties passed from constructor. var _options$action = options.action, action = _options$action === void 0 ? 'copy' : _options$action, container = options.container, target = options.target, text = options.text; // Sets the `action` to be performed which can be either 'copy' or 'cut'. if (action !== 'copy' && action !== 'cut') { throw new Error('Invalid "action" value, use either "copy" or "cut"'); } // Sets the `target` property using an element that will be have its content copied. if (target !== undefined) { if (target && _typeof(target) === 'object' && target.nodeType === 1) { if (action === 'copy' && target.hasAttribute('disabled')) { throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); } if (action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); } } else { throw new Error('Invalid "target" value, use a valid Element'); } } // Define selection strategy based on `text` property. if (text) { return actions_copy(text, { container: container }); } // Defines which selection strategy based on `target` property. if (target) { return action === 'cut' ? actions_cut(target) : actions_copy(target, { container: container }); } }; /* harmony default export */ var actions_default = (ClipboardActionDefault); ;// CONCATENATED MODULE: ./src/clipboard.js function clipboard_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { clipboard_typeof = function _typeof(obj) { return typeof obj; }; } else { clipboard_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return clipboard_typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (clipboard_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * Helper function to retrieve attribute value. * @param {String} suffix * @param {Element} element */ function getAttributeValue(suffix, element) { var attribute = "data-clipboard-".concat(suffix); if (!element.hasAttribute(attribute)) { return; } return element.getAttribute(attribute); } /** * Base class which takes one or more elements, adds event listeners to them, * and instantiates a new `ClipboardAction` on each click. */ var Clipboard = /*#__PURE__*/function (_Emitter) { _inherits(Clipboard, _Emitter); var _super = _createSuper(Clipboard); /** * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ function Clipboard(trigger, options) { var _this; _classCallCheck(this, Clipboard); _this = _super.call(this); _this.resolveOptions(options); _this.listenClick(trigger); return _this; } /** * Defines if attributes would be resolved using internal setter functions * or custom functions that were passed in the constructor. * @param {Object} options */ _createClass(Clipboard, [{ key: "resolveOptions", value: function resolveOptions() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = typeof options.action === 'function' ? options.action : this.defaultAction; this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; this.text = typeof options.text === 'function' ? options.text : this.defaultText; this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body; } /** * Adds a click event listener to the passed trigger. * @param {String|HTMLElement|HTMLCollection|NodeList} trigger */ }, { key: "listenClick", value: function listenClick(trigger) { var _this2 = this; this.listener = listen_default()(trigger, 'click', function (e) { return _this2.onClick(e); }); } /** * Defines a new `ClipboardAction` on each click event. * @param {Event} e */ }, { key: "onClick", value: function onClick(e) { var trigger = e.delegateTarget || e.currentTarget; var action = this.action(trigger) || 'copy'; var text = actions_default({ action: action, container: this.container, target: this.target(trigger), text: this.text(trigger) }); // Fires an event based on the copy operation result. this.emit(text ? 'success' : 'error', { action: action, text: text, trigger: trigger, clearSelection: function clearSelection() { if (trigger) { trigger.focus(); } window.getSelection().removeAllRanges(); } }); } /** * Default `action` lookup function. * @param {Element} trigger */ }, { key: "defaultAction", value: function defaultAction(trigger) { return getAttributeValue('action', trigger); } /** * Default `target` lookup function. * @param {Element} trigger */ }, { key: "defaultTarget", value: function defaultTarget(trigger) { var selector = getAttributeValue('target', trigger); if (selector) { return document.querySelector(selector); } } /** * Allow fire programmatically a copy action * @param {String|HTMLElement} target * @param {Object} options * @returns Text copied. */ }, { key: "defaultText", /** * Default `text` lookup function. * @param {Element} trigger */ value: function defaultText(trigger) { return getAttributeValue('text', trigger); } /** * Destroy lifecycle. */ }, { key: "destroy", value: function destroy() { this.listener.destroy(); } }], [{ key: "copy", value: function copy(target) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { container: document.body }; return actions_copy(target, options); } /** * Allow fire programmatically a cut action * @param {String|HTMLElement} target * @returns Text cutted. */ }, { key: "cut", value: function cut(target) { return actions_cut(target); } /** * Returns the support of the given action, or all actions if no action is * given. * @param {String} [action] */ }, { key: "isSupported", value: function isSupported() { var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; var actions = typeof action === 'string' ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { support = support && !!document.queryCommandSupported(action); }); return support; } }]); return Clipboard; }((tiny_emitter_default())); /* harmony default export */ var clipboard = (Clipboard); /***/ }), /***/ 828: /***/ (function(module) { var DOCUMENT_NODE_TYPE = 9; /** * A polyfill for Element.matches() */ if (typeof Element !== 'undefined' && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; } /** * Finds the closest parent that matches a selector. * * @param {Element} element * @param {String} selector * @return {Function} */ function closest (element, selector) { while (element && element.nodeType !== DOCUMENT_NODE_TYPE) { if (typeof element.matches === 'function' && element.matches(selector)) { return element; } element = element.parentNode; } } module.exports = closest; /***/ }), /***/ 438: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var closest = __webpack_require__(828); /** * Delegates event to a selector. * * @param {Element} element * @param {String} selector * @param {String} type * @param {Function} callback * @param {Boolean} useCapture * @return {Object} */ function _delegate(element, selector, type, callback, useCapture) { var listenerFn = listener.apply(this, arguments); element.addEventListener(type, listenerFn, useCapture); return { destroy: function() { element.removeEventListener(type, listenerFn, useCapture); } } } /** * Delegates event to a selector. * * @param {Element|String|Array} [elements] * @param {String} selector * @param {String} type * @param {Function} callback * @param {Boolean} useCapture * @return {Object} */ function delegate(elements, selector, type, callback, useCapture) { // Handle the regular Element usage if (typeof elements.addEventListener === 'function') { return _delegate.apply(null, arguments); } // Handle Element-less usage, it defaults to global delegation if (typeof type === 'function') { // Use `document` as the first parameter, then apply arguments // This is a short way to .unshift `arguments` without running into deoptimizations return _delegate.bind(null, document).apply(null, arguments); } // Handle Selector-based usage if (typeof elements === 'string') { elements = document.querySelectorAll(elements); } // Handle Array-like based usage return Array.prototype.map.call(elements, function (element) { return _delegate(element, selector, type, callback, useCapture); }); } /** * Finds closest match and invokes callback. * * @param {Element} element * @param {String} selector * @param {String} type * @param {Function} callback * @return {Function} */ function listener(element, selector, type, callback) { return function(e) { e.delegateTarget = closest(e.target, selector); if (e.delegateTarget) { callback.call(element, e); } } } module.exports = delegate; /***/ }), /***/ 879: /***/ (function(__unused_webpack_module, exports) { /** * Check if argument is a HTML element. * * @param {Object} value * @return {Boolean} */ exports.node = function(value) { return value !== undefined && value instanceof HTMLElement && value.nodeType === 1; }; /** * Check if argument is a list of HTML elements. * * @param {Object} value * @return {Boolean} */ exports.nodeList = function(value) { var type = Object.prototype.toString.call(value); return value !== undefined && (type === '[object NodeList]' || type === '[object HTMLCollection]') && ('length' in value) && (value.length === 0 || exports.node(value[0])); }; /** * Check if argument is a string. * * @param {Object} value * @return {Boolean} */ exports.string = function(value) { return typeof value === 'string' || value instanceof String; }; /** * Check if argument is a function. * * @param {Object} value * @return {Boolean} */ exports.fn = function(value) { var type = Object.prototype.toString.call(value); return type === '[object Function]'; }; /***/ }), /***/ 370: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var is = __webpack_require__(879); var delegate = __webpack_require__(438); /** * Validates all params and calls the right * listener function based on its target type. * * @param {String|HTMLElement|HTMLCollection|NodeList} target * @param {String} type * @param {Function} callback * @return {Object} */ function listen(target, type, callback) { if (!target && !type && !callback) { throw new Error('Missing required arguments'); } if (!is.string(type)) { throw new TypeError('Second argument must be a String'); } if (!is.fn(callback)) { throw new TypeError('Third argument must be a Function'); } if (is.node(target)) { return listenNode(target, type, callback); } else if (is.nodeList(target)) { return listenNodeList(target, type, callback); } else if (is.string(target)) { return listenSelector(target, type, callback); } else { throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList'); } } /** * Adds an event listener to a HTML element * and returns a remove listener function. * * @param {HTMLElement} node * @param {String} type * @param {Function} callback * @return {Object} */ function listenNode(node, type, callback) { node.addEventListener(type, callback); return { destroy: function() { node.removeEventListener(type, callback); } } } /** * Add an event listener to a list of HTML elements * and returns a remove listener function. * * @param {NodeList|HTMLCollection} nodeList * @param {String} type * @param {Function} callback * @return {Object} */ function listenNodeList(nodeList, type, callback) { Array.prototype.forEach.call(nodeList, function(node) { node.addEventListener(type, callback); }); return { destroy: function() { Array.prototype.forEach.call(nodeList, function(node) { node.removeEventListener(type, callback); }); } } } /** * Add an event listener to a selector * and returns a remove listener function. * * @param {String} selector * @param {String} type * @param {Function} callback * @return {Object} */ function listenSelector(selector, type, callback) { return delegate(document.body, selector, type, callback); } module.exports = listen; /***/ }), /***/ 817: /***/ (function(module) { function select(element) { var selectedText; if (element.nodeName === 'SELECT') { element.focus(); selectedText = element.value; } else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { var isReadOnly = element.hasAttribute('readonly'); if (!isReadOnly) { element.setAttribute('readonly', ''); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { element.removeAttribute('readonly'); } selectedText = element.value; } else { if (element.hasAttribute('contenteditable')) { element.focus(); } var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); selectedText = selection.toString(); } return selectedText; } module.exports = select; /***/ }), /***/ 279: /***/ (function(module) { function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } E.prototype = { on: function (name, callback, ctx) { var e = this.e || (this.e = {}); (e[name] || (e[name] = [])).push({ fn: callback, ctx: ctx }); return this; }, once: function (name, callback, ctx) { var self = this; function listener () { self.off(name, listener); callback.apply(ctx, arguments); }; listener._ = callback return this.on(name, listener, ctx); }, emit: function (name) { var data = [].slice.call(arguments, 1); var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); var i = 0; var len = evtArr.length; for (i; i < len; i++) { evtArr[i].fn.apply(evtArr[i].ctx, data); } return this; }, off: function (name, callback) { var e = this.e || (this.e = {}); var evts = e[name]; var liveEvents = []; if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]); } } // Remove event from queue to prevent memory leak // Suggested by https://github.com/lazd // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 (liveEvents.length) ? e[name] = liveEvents : delete e[name]; return this; } }; module.exports = E; module.exports.TinyEmitter = E; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(__webpack_module_cache__[moduleId]) { /******/ return __webpack_module_cache__[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ !function() { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function() { return module['default']; } : /******/ function() { return module; }; /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /******/ }(); /******/ /************************************************************************/ /******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ return __webpack_require__(686); /******/ })() .default; });// JavaScript Document const __defaultOptions = { annotationEditorMode: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, annotationMode: { value: 2, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, cursorToolOnLoad: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, defaultZoomValue: { value: "", kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, disableHistory: { value: false, kind: OptionKind.VIEWER }, disablePageLabels: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enablePermissions: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enablePrintAutoRotate: { value: true, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enableScripting: { value: true, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, externalLinkRel: { value: "noopener noreferrer nofollow", kind: OptionKind.VIEWER }, externalLinkTarget: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, historyUpdateUrl: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, ignoreDestinationZoom: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, imageResourcesPath: { value: "./images/", kind: OptionKind.VIEWER }, maxCanvasPixels: { value: 16777216, kind: OptionKind.VIEWER }, forcePageColors: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, pageColorsBackground: { value: "Canvas", kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, pageColorsForeground: { value: "CanvasText", kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, pdfBugEnabled: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, printResolution: { value: 150, kind: OptionKind.VIEWER }, sidebarViewOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, scrollModeOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, spreadModeOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, textLayerMode: { value: 1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, useOnlyCssZoom: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, viewerCssTheme: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, viewOnLoad: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, cMapPacked: { value: true, kind: OptionKind.API }, cMapUrl: { value: "../web/cmaps/", kind: OptionKind.API }, disableAutoFetch: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableFontFace: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableRange: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableStream: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, docBaseUrl: { value: "", kind: OptionKind.API }, enableXfa: { value: true, kind: OptionKind.API + OptionKind.PREFERENCE }, fontExtraProperties: { value: false, kind: OptionKind.API }, isEvalSupported: { value: true, kind: OptionKind.API }, maxImageSize: { value: -1, kind: OptionKind.API }, pdfBug: { value: false, kind: OptionKind.API }, standardFontDataUrl: { value: "../web/standard_fonts/", kind: OptionKind.API }, verbosity: { value: 1, kind: OptionKind.API }, workerPort: { value: null, kind: OptionKind.WORKER }, workerSrc: { value: "../build/pdf.worker.js", kind: OptionKind.WORKER } }; { defaultOptions.defaultUrl = { value: OptionKind.VIEWER+ OptionKind.PREFERENCE, kind: OptionKind.VIEWER }; defaultOptions.disablePreferences = { value: false, kind: OptionKind.VIEWER }; defaultOptions.locale = { value: navigator.language || "en-US", kind: OptionKind.VIEWER }; defaultOptions.renderer = { value: "canvas", kind: OptionKind.VIEWER + OptionKind.PREFERENCE }; defaultOptions.sandboxBundleSrc = { value: "../build/pdf.sandbox.js", kind: OptionKind.VIEWER }; } { function webViewerPageRendered({ pageNumber, error }) { if (pageNumber === PDFViewerApplication.page) { PDFViewerApplication.toolbar.updateLoadingIndicatorState(false); } if (PDFViewerApplication.pdfSidebar.visibleView === _ui_utils.SidebarView.THUMBS) { const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1); const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageNumber - 1); if (pageView && thumbnailView) { thumbnailView.setImage(pageView); } } if (error) { PDFViewerApplication.l10n.get("rendering_error").then(msg => { PDFViewerApplication._otherError(msg, error); }); } PDFViewerApplication._reportDocumentStatsTelemetry(); } function webViewerPageMode({ mode }) { let view; switch (mode) { case "thumbs": view = _ui_utils.SidebarView.THUMBS; break; case "bookmarks": case "outline": view = _ui_utils.SidebarView.OUTLINE; break; case "attachments": view = _ui_utils.SidebarView.ATTACHMENTS; break; case "layers": view = _ui_utils.SidebarView.LAYERS; break; case "none": view = _ui_utils.SidebarView.NONE; break; default: console.error('Invalid "pagemode" hash parameter: ' + mode); return; } PDFViewerApplication.pdfSidebar.switchView(view, true); } function webViewerNamedAction(evt) { switch (evt.action) { case "GoToPage": PDFViewerApplication.appConfig.toolbar.pageNumber.select(); break; case "Find": if (!PDFViewerApplication.supportsIntegratedFind) { PDFViewerApplication.findBar.toggle(); } break; case "Print": PDFViewerApplication.triggerPrinting(); break; case "SaveAs": PDFViewerApplication.downloadOrSave(); break; } } function webViewerPresentationModeChanged(evt) { PDFViewerApplication.pdfViewer.presentationModeState = evt.state; } function webViewerSidebarViewChanged({ view }) { PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = view === _ui_utils.SidebarView.THUMBS; if (PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.store?.set("sidebarView", view).catch(() => {}); } } function webViewerUpdateViewarea({ location }) { if (PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.store?.setMultiple({ page: location.pageNumber, zoom: location.scale, scrollLeft: location.left, scrollTop: location.top, rotation: location.rotation }).catch(() => {}); } const href = PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams); PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href; PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href; const currentPage = PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1); const loading = currentPage?.renderingState !== _ui_utils.RenderingStates.FINISHED; PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading); } function webViewerScrollModeChanged(evt) { if (PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.store?.set("scrollMode", evt.mode).catch(() => {}); } } function webViewerSpreadModeChanged(evt) { if (PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.store?.set("spreadMode", evt.mode).catch(() => {}); } } function webViewerResize() { const { pdfDocument, pdfViewer, pdfRenderingQueue } = PDFViewerApplication; if (pdfRenderingQueue.printing && window.matchMedia("print").matches) { return; } pdfViewer.updateContainerHeightCss(); if (!pdfDocument) { return; } const currentScaleValue = pdfViewer.currentScaleValue; if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") { pdfViewer.currentScaleValue = currentScaleValue; } pdfViewer.update(); } function webViewerHashchange(evt) { const hash = evt.hash; if (!hash) { return; } if (!PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.initialBookmark = hash; } else if (!PDFViewerApplication.pdfHistory?.popStateInProgress) { PDFViewerApplication.pdfLinkService.setHash(hash); } } { var webViewerFileInputChange = function (evt) { if (PDFViewerApplication.pdfViewer?.isInPresentationMode) { return; } const file = evt.fileInput.files[0]; let url = URL.createObjectURL(file); if (file.name) { url = { url, originalUrl: file.name }; } PDFViewerApplication.open(url); }; var webViewerOpenFile = function (evt) { const fileInput = PDFViewerApplication.appConfig.openFileInput; fileInput.click(); }; } function webViewerPresentationMode() { PDFViewerApplication.requestPresentationMode(); } function webViewerSwitchAnnotationEditorMode(evt) { PDFViewerApplication.pdfViewer.annotationEditorMode = evt.mode; } function webViewerSwitchAnnotationEditorParams(evt) { PDFViewerApplication.pdfViewer.annotationEditorParams = evt; } function webViewerPrint() { PDFViewerApplication.triggerPrinting(); } function webViewerDownload() { PDFViewerApplication.downloadOrSave(); } function webViewerFirstPage() { if (PDFViewerApplication.pdfDocument) { PDFViewerApplication.page = 1; } } function webViewerLastPage() { if (PDFViewerApplication.pdfDocument) { PDFViewerApplication.page = PDFViewerApplication.pagesCount; } } function webViewerNextPage() { PDFViewerApplication.pdfViewer.nextPage(); } function webViewerPreviousPage() { PDFViewerApplication.pdfViewer.previousPage(); } function webViewerZoomIn() { PDFViewerApplication.zoomIn(); } function webViewerZoomOut() { PDFViewerApplication.zoomOut(); } function webViewerZoomReset() { PDFViewerApplication.zoomReset(); } function webViewerPageNumberChanged(evt) { const pdfViewer = PDFViewerApplication.pdfViewer; if (evt.value !== "") { PDFViewerApplication.pdfLinkService.goToPage(evt.value); } if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) { PDFViewerApplication.toolbar.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel); } } function webViewerScaleChanged(evt) { PDFViewerApplication.pdfViewer.currentScaleValue = evt.value; } function webViewerRotateCw() { PDFViewerApplication.rotatePages(90); } function webViewerRotateCcw() { PDFViewerApplication.rotatePages(-90); } function webViewerOptionalContentConfig(evt) { PDFViewerApplication.pdfViewer.optionalContentConfigPromise = evt.promise; } function webViewerSwitchScrollMode(evt) { PDFViewerApplication.pdfViewer.scrollMode = evt.mode; } function webViewerSwitchSpreadMode(evt) { PDFViewerApplication.pdfViewer.spreadMode = evt.mode; } function webViewerDocumentProperties() { PDFViewerApplication.pdfDocumentProperties.open(); } function webViewerFindFromUrlHash(evt) { PDFViewerApplication.eventBus.dispatch("find", { source: evt.source, type: "", query: evt.query, phraseSearch: evt.phraseSearch, caseSensitive: false, entireWord: false, highlightAll: true, findPrevious: false, matchDiacritics: true }); } function webViewerUpdateFindMatchesCount({ matchesCount }) { if (PDFViewerApplication.supportsIntegratedFind) { PDFViewerApplication.externalServices.updateFindMatchesCount(matchesCount); } else { PDFViewerApplication.findBar.updateResultsCount(matchesCount); } } function webViewerUpdateFindControlState({ state, previous, matchesCount, rawQuery }) { if (PDFViewerApplication.supportsIntegratedFind) { PDFViewerApplication.externalServices.updateFindControlState({ result: state, findPrevious: previous, matchesCount, rawQuery }); } else { PDFViewerApplication.findBar.updateUIState(state, previous, matchesCount); } } function webViewerScaleChanging(evt) { PDFViewerApplication.toolbar.setPageScale(evt.presetValue, evt.scale); PDFViewerApplication.pdfViewer.update(); } function webViewerRotationChanging(evt) { PDFViewerApplication.pdfThumbnailViewer.pagesRotation = evt.pagesRotation; PDFViewerApplication.forceRendering(); PDFViewerApplication.pdfViewer.currentPageNumber = evt.pageNumber; } function webViewerPageChanging({ pageNumber, pageLabel }) { PDFViewerApplication.toolbar.setPageNumber(pageNumber, pageLabel); PDFViewerApplication.secondaryToolbar.setPageNumber(pageNumber); if (PDFViewerApplication.pdfSidebar.visibleView === _ui_utils.SidebarView.THUMBS) { PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(pageNumber); } } function webViewerResolutionChange(evt) { PDFViewerApplication.pdfViewer.refresh(); } function webViewerVisibilityChange(evt) { if (document.visibilityState === "visible") { setZoomDisabledTimeout(); } } let zoomDisabledTimeout = null; function setZoomDisabledTimeout() { if (zoomDisabledTimeout) { clearTimeout(zoomDisabledTimeout); } zoomDisabledTimeout = setTimeout(function () { zoomDisabledTimeout = null; }, WHEEL_ZOOM_DISABLED_TIMEOUT); } function webViewerWheel(evt) { const { pdfViewer, supportedMouseWheelZoomModifierKeys } = PDFViewerApplication; if (pdfViewer.isInPresentationMode) { return; } if (evt.ctrlKey && supportedMouseWheelZoomModifierKeys.ctrlKey || evt.metaKey && supportedMouseWheelZoomModifierKeys.metaKey) { evt.preventDefault(); if (zoomDisabledTimeout || document.visibilityState === "hidden") { return; } const deltaMode = evt.deltaMode; const delta = (0, _ui_utils.normalizeWheelEventDirection)(evt); const previousScale = pdfViewer.currentScale; let ticks = 0; if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) { if (Math.abs(delta) >= 1) { ticks = Math.sign(delta); } else { ticks = PDFViewerApplication.accumulateWheelTicks(delta); } } else { const PIXELS_PER_LINE_SCALE = 30; ticks = PDFViewerApplication.accumulateWheelTicks(delta / PIXELS_PER_LINE_SCALE); } if (ticks < 0) { PDFViewerApplication.zoomOut(-ticks); } else if (ticks > 0) { PDFViewerApplication.zoomIn(ticks); } const currentScale = pdfViewer.currentScale; if (previousScale !== currentScale) { const scaleCorrectionFactor = currentScale / previousScale - 1; const rect = pdfViewer.container.getBoundingClientRect(); const dx = evt.clientX - rect.left; const dy = evt.clientY - rect.top; pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor; pdfViewer.container.scrollTop += dy * scaleCorrectionFactor; } } else { setZoomDisabledTimeout(); } } function webViewerTouchStart(evt) { if (evt.touches.length > 1) { evt.preventDefault(); } } function webViewerClick(evt) { if (!PDFViewerApplication.secondaryToolbar.isOpen) { return; } const appConfig = PDFViewerApplication.appConfig; if (PDFViewerApplication.pdfViewer.containsElement(evt.target) || appConfig.toolbar.container.contains(evt.target) && evt.target !== appConfig.secondaryToolbar.toggleButton) { PDFViewerApplication.secondaryToolbar.close(); } } function webViewerKeyDown(evt) { if (PDFViewerApplication.overlayManager.active) { return; } const { eventBus, pdfViewer } = PDFViewerApplication; const isViewerInPresentationMode = pdfViewer.isInPresentationMode; let handled = false, ensureViewerFocused = false; const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0); if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) { switch (evt.keyCode) { case 70: if (!PDFViewerApplication.supportsIntegratedFind && !evt.shiftKey) { PDFViewerApplication.findBar.open(); handled = true; } break; case 71: if (!PDFViewerApplication.supportsIntegratedFind) { const { state } = PDFViewerApplication.findController; if (state) { const eventState = Object.assign(Object.create(null), state, { source: window, type: "again", findPrevious: cmd === 5 || cmd === 12 }); eventBus.dispatch("find", eventState); } handled = true; } break; case 61: case 107: case 187: case 171: if (!isViewerInPresentationMode) { PDFViewerApplication.zoomIn(); } handled = true; break; case 173: case 109: case 189: if (!isViewerInPresentationMode) { PDFViewerApplication.zoomOut(); } handled = true; break; case 48: case 96: if (!isViewerInPresentationMode) { setTimeout(function () { PDFViewerApplication.zoomReset(); }); handled = false; } break; case 38: if (isViewerInPresentationMode || PDFViewerApplication.page > 1) { PDFViewerApplication.page = 1; handled = true; ensureViewerFocused = true; } break; case 40: if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) { PDFViewerApplication.page = PDFViewerApplication.pagesCount; handled = true; ensureViewerFocused = true; } break; } } if (cmd === 1 || cmd === 8) { switch (evt.keyCode) { case 83: eventBus.dispatch("download", { source: window }); handled = true; break; case 79: { eventBus.dispatch("openfile", { source: window }); handled = true; } break; } } if (cmd === 3 || cmd === 10) { switch (evt.keyCode) { case 80: PDFViewerApplication.requestPresentationMode(); handled = true; break; case 71: PDFViewerApplication.appConfig.toolbar.pageNumber.select(); handled = true; break; } } if (handled) { if (ensureViewerFocused && !isViewerInPresentationMode) { pdfViewer.focus(); } evt.preventDefault(); return; } const curElement = (0, _ui_utils.getActiveOrFocusedElement)(); const curElementTagName = curElement?.tagName.toUpperCase(); if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElement?.isContentEditable) { if (evt.keyCode !== 27) { return; } } if (cmd === 0) { let turnPage = 0, turnOnlyIfPageFit = false; switch (evt.keyCode) { case 38: case 33: if (pdfViewer.isVerticalScrollbarEnabled) { turnOnlyIfPageFit = true; } turnPage = -1; break; case 8: if (!isViewerInPresentationMode) { turnOnlyIfPageFit = true; } turnPage = -1; break; case 37: if (pdfViewer.isHorizontalScrollbarEnabled) { turnOnlyIfPageFit = true; } case 75: case 80: turnPage = -1; break; case 27: if (PDFViewerApplication.secondaryToolbar.isOpen) { PDFViewerApplication.secondaryToolbar.close(); handled = true; } if (!PDFViewerApplication.supportsIntegratedFind && PDFViewerApplication.findBar.opened) { PDFViewerApplication.findBar.close(); handled = true; } break; case 40: case 34: if (pdfViewer.isVerticalScrollbarEnabled) { turnOnlyIfPageFit = true; } turnPage = 1; break; case 13: case 32: if (!isViewerInPresentationMode) { turnOnlyIfPageFit = true; } turnPage = 1; break; case 39: if (pdfViewer.isHorizontalScrollbarEnabled) { turnOnlyIfPageFit = true; } case 74: case 78: turnPage = 1; break; case 36: if (isViewerInPresentationMode || PDFViewerApplication.page > 1) { PDFViewerApplication.page = 1; handled = true; ensureViewerFocused = true; } break; case 35: if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) { PDFViewerApplication.page = PDFViewerApplication.pagesCount; handled = true; ensureViewerFocused = true; } break; case 83: PDFViewerApplication.pdfCursorTools.switchTool(_pdf_cursor_tools.CursorTool.SELECT); break; case 72: PDFViewerApplication.pdfCursorTools.switchTool(_pdf_cursor_tools.CursorTool.HAND); break; case 82: PDFViewerApplication.rotatePages(90); break; case 115: PDFViewerApplication.pdfSidebar.toggle(); break; } if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) { if (turnPage > 0) { pdfViewer.nextPage(); } else { pdfViewer.previousPage(); } handled = true; } } if (cmd === 4) { switch (evt.keyCode) { case 13: case 32: if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") { break; } pdfViewer.previousPage(); handled = true; break; case 82: PDFViewerApplication.rotatePages(-90); break; } } if (!handled && !isViewerInPresentationMode) { if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") { ensureViewerFocused = true; } } if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) { pdfViewer.focus(); } if (handled) { evt.preventDefault(); } } function beforeUnload(evt) { evt.preventDefault(); evt.returnValue = ""; return false; } function webViewerAnnotationEditorStatesChanged(data) { PDFViewerApplication.externalServices.updateEditorStates(data); } const PDFPrintServiceFactory = { instance: { supportsPrinting: false, createPrintService() { throw new Error("Not implemented: createPrintService"); } } }; exports.PDFPrintServiceFactory = PDFPrintServiceFactory; /***/ }), /* 5 */ /***/ ((module) => { let pdfjsLib; if (typeof window !== "undefined" && window["pdfjs-dist/build/pdf"]) { pdfjsLib = window["pdfjs-dist/build/pdf"]; } else { pdfjsLib = require("../build/pdf.js"); } module.exports = pdfjsLib; /***/ }), /* 6 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WaitOnType = exports.EventBus = exports.AutomationEventBus = void 0; exports.waitOnEventOrTimeout = waitOnEventOrTimeout; const WaitOnType = { EVENT: "event", TIMEOUT: "timeout" }; exports.WaitOnType = WaitOnType; function waitOnEventOrTimeout({ target, name, delay = 0 }) { return new Promise(function (resolve, reject) { if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { throw new Error("waitOnEventOrTimeout - invalid parameters."); } function handler(type) { if (target instanceof EventBus) { target._off(name, eventHandler); } else { target.removeEventListener(name, eventHandler); } if (timeout) { clearTimeout(timeout); } resolve(type); } const eventHandler = handler.bind(null, WaitOnType.EVENT); if (target instanceof EventBus) { target._on(name, eventHandler); } else { target.addEventListener(name, eventHandler); } const timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT); const timeout = setTimeout(timeoutHandler, delay); }); } class EventBus { constructor() { this._listeners = Object.create(null); } on(eventName, listener, options = null) { this._on(eventName, listener, { external: true, once: options?.once }); } off(eventName, listener, options = null) { this._off(eventName, listener, { external: true, once: options?.once }); } dispatch(eventName, data) { const eventListeners = this._listeners[eventName]; if (!eventListeners || eventListeners.length === 0) { return; } let externalListeners; for (const { listener, external, once } of eventListeners.slice(0)) { if (once) { this._off(eventName, listener); } if (external) { (externalListeners ||= []).push(listener); continue; } listener(data); } if (externalListeners) { for (const listener of externalListeners) { listener(data); } externalListeners = null; } } _on(eventName, listener, options = null) { const eventListeners = this._listeners[eventName] ||= []; eventListeners.push({ listener, external: options?.external === true, once: options?.once === true }); } _off(eventName, listener, options = null) { const eventListeners = this._listeners[eventName]; if (!eventListeners) { return; } for (let i = 0, ii = eventListeners.length; i < ii; i++) { if (eventListeners[i].listener === listener) { eventListeners.splice(i, 1); return; } } } } exports.EventBus = EventBus; class AutomationEventBus extends EventBus { dispatch(eventName, data) { throw new Error("Not implemented: AutomationEventBus.dispatch"); } } exports.AutomationEventBus = AutomationEventBus; /***/ }), /* 7 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFCursorTools = exports.CursorTool = void 0; var _grab_to_pan = __webpack_require__(8); var _ui_utils = __webpack_require__(1); const CursorTool = { SELECT: 0, HAND: 1, ZOOM: 2 }; exports.CursorTool = CursorTool; class PDFCursorTools { constructor({ container, eventBus, cursorToolOnLoad = CursorTool.SELECT }) { this.container = container; this.eventBus = eventBus; this.active = CursorTool.SELECT; this.activeBeforePresentationMode = null; this.handTool = new _grab_to_pan.GrabToPan({ element: this.container }); this.#addEventListeners(); Promise.resolve().then(() => { this.switchTool(cursorToolOnLoad); }); } get activeTool() { return this.active; } switchTool(tool) { if (this.activeBeforePresentationMode !== null) { return; } if (tool === this.active) { return; } const disableActiveTool = () => { switch (this.active) { case CursorTool.SELECT: break; case CursorTool.HAND: this.handTool.deactivate(); break; case CursorTool.ZOOM: } }; switch (tool) { case CursorTool.SELECT: disableActiveTool(); break; case CursorTool.HAND: disableActiveTool(); this.handTool.activate(); break; case CursorTool.ZOOM: default: console.error(`switchTool: "${tool}" is an unsupported value.`); return; } this.active = tool; this.#dispatchEvent(); } #dispatchEvent() { this.eventBus.dispatch("cursortoolchanged", { source: this, tool: this.active }); } #addEventListeners() { this.eventBus._on("switchcursortool", evt => { this.switchTool(evt.tool); }); this.eventBus._on("presentationmodechanged", evt => { switch (evt.state) { case _ui_utils.PresentationModeState.FULLSCREEN: { const previouslyActive = this.active; this.switchTool(CursorTool.SELECT); this.activeBeforePresentationMode = previouslyActive; break; } case _ui_utils.PresentationModeState.NORMAL: { const previouslyActive = this.activeBeforePresentationMode; this.activeBeforePresentationMode = null; this.switchTool(previouslyActive); break; } } }); } } exports.PDFCursorTools = PDFCursorTools; /***/ }), /* 8 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GrabToPan = void 0; const CSS_CLASS_GRAB = "grab-to-pan-grab"; class GrabToPan { constructor(options) { this.element = options.element; this.document = options.element.ownerDocument; if (typeof options.ignoreTarget === "function") { this.ignoreTarget = options.ignoreTarget; } this.onActiveChanged = options.onActiveChanged; this.activate = this.activate.bind(this); this.deactivate = this.deactivate.bind(this); this.toggle = this.toggle.bind(this); this._onMouseDown = this.#onMouseDown.bind(this); this._onMouseMove = this.#onMouseMove.bind(this); this._endPan = this.#endPan.bind(this); const overlay = this.overlay = document.createElement("div"); overlay.className = "grab-to-pan-grabbing"; } activate() { if (!this.active) { this.active = true; this.element.addEventListener("mousedown", this._onMouseDown, true); this.element.classList.add(CSS_CLASS_GRAB); this.onActiveChanged?.(true); } } deactivate() { if (this.active) { this.active = false; this.element.removeEventListener("mousedown", this._onMouseDown, true); this._endPan(); this.element.classList.remove(CSS_CLASS_GRAB); this.onActiveChanged?.(false); } } toggle() { if (this.active) { this.deactivate(); } else { this.activate(); } } ignoreTarget(node) { return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option"); } #onMouseDown(event) { if (event.button !== 0 || this.ignoreTarget(event.target)) { return; } if (event.originalTarget) { try { event.originalTarget.tagName; } catch (e) { return; } } this.scrollLeftStart = this.element.scrollLeft; this.scrollTopStart = this.element.scrollTop; this.clientXStart = event.clientX; this.clientYStart = event.clientY; this.document.addEventListener("mousemove", this._onMouseMove, true); this.document.addEventListener("mouseup", this._endPan, true); this.element.addEventListener("scroll", this._endPan, true); event.preventDefault(); event.stopPropagation(); const focusedElement = document.activeElement; if (focusedElement && !focusedElement.contains(event.target)) { focusedElement.blur(); } } #onMouseMove(event) { this.element.removeEventListener("scroll", this._endPan, true); if (!(event.buttons & 1)) { this._endPan(); return; } const xDiff = event.clientX - this.clientXStart; const yDiff = event.clientY - this.clientYStart; const scrollTop = this.scrollTopStart - yDiff; const scrollLeft = this.scrollLeftStart - xDiff; if (this.element.scrollTo) { this.element.scrollTo({ top: scrollTop, left: scrollLeft, behavior: "instant" }); } else { this.element.scrollTop = scrollTop; this.element.scrollLeft = scrollLeft; } if (!this.overlay.parentNode) { document.body.append(this.overlay); } } #endPan() { this.element.removeEventListener("scroll", this._endPan, true); this.document.removeEventListener("mousemove", this._onMouseMove, true); this.document.removeEventListener("mouseup", this._endPan, true); this.overlay.remove(); } } exports.GrabToPan = GrabToPan; /***/ }), /* 9 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AnnotationEditorParams = void 0; var _pdfjsLib = __webpack_require__(5); class AnnotationEditorParams { constructor(options, eventBus) { this.eventBus = eventBus; this.#bindListeners(options); } #bindListeners({ editorFreeTextFontSize, editorFreeTextColor, editorInkColor, editorInkThickness, editorInkOpacity }) { editorFreeTextFontSize.addEventListener("input", evt => { this.eventBus.dispatch("switchannotationeditorparams", { source: this, type: _pdfjsLib.AnnotationEditorParamsType.FREETEXT_SIZE, value: editorFreeTextFontSize.valueAsNumber }); }); editorFreeTextColor.addEventListener("input", evt => { this.eventBus.dispatch("switchannotationeditorparams", { source: this, type: _pdfjsLib.AnnotationEditorParamsType.FREETEXT_COLOR, value: editorFreeTextColor.value }); }); editorInkColor.addEventListener("input", evt => { this.eventBus.dispatch("switchannotationeditorparams", { source: this, type: _pdfjsLib.AnnotationEditorParamsType.INK_COLOR, value: editorInkColor.value }); }); editorInkThickness.addEventListener("input", evt => { this.eventBus.dispatch("switchannotationeditorparams", { source: this, type: _pdfjsLib.AnnotationEditorParamsType.INK_THICKNESS, value: editorInkThickness.valueAsNumber }); }); editorInkOpacity.addEventListener("input", evt => { this.eventBus.dispatch("switchannotationeditorparams", { source: this, type: _pdfjsLib.AnnotationEditorParamsType.INK_OPACITY, value: editorInkOpacity.valueAsNumber }); }); this.eventBus._on("annotationeditorparamschanged", evt => { for (const [type, value] of evt.details) { switch (type) { case _pdfjsLib.AnnotationEditorParamsType.FREETEXT_SIZE: editorFreeTextFontSize.value = value; break; case _pdfjsLib.AnnotationEditorParamsType.FREETEXT_COLOR: editorFreeTextColor.value = value; break; case _pdfjsLib.AnnotationEditorParamsType.INK_COLOR: editorInkColor.value = value; break; case _pdfjsLib.AnnotationEditorParamsType.INK_THICKNESS: editorInkThickness.value = value; break; case _pdfjsLib.AnnotationEditorParamsType.INK_OPACITY: editorInkOpacity.value = value; break; } } }); } } exports.AnnotationEditorParams = AnnotationEditorParams; /***/ }), /* 10 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OverlayManager = void 0; class OverlayManager { #overlays = new WeakMap(); #active = null; get active() { return this.#active; } async register(dialog, canForceClose = false) { if (typeof dialog !== "object") { throw new Error("Not enough parameters."); } else if (this.#overlays.has(dialog)) { throw new Error("The overlay is already registered."); } this.#overlays.set(dialog, { canForceClose }); dialog.addEventListener("cancel", evt => { this.#active = null; }); } async unregister(dialog) { if (!this.#overlays.has(dialog)) { throw new Error("The overlay does not exist."); } else if (this.#active === dialog) { throw new Error("The overlay cannot be removed while it is active."); } this.#overlays.delete(dialog); } async open(dialog) { if (!this.#overlays.has(dialog)) { throw new Error("The overlay does not exist."); } else if (this.#active) { if (this.#active === dialog) { throw new Error("The overlay is already active."); } else if (this.#overlays.get(dialog).canForceClose) { await this.close(); } else { throw new Error("Another overlay is currently active."); } } this.#active = dialog; dialog.showModal(); } async close(dialog = this.#active) { if (!this.#overlays.has(dialog)) { throw new Error("The overlay does not exist."); } else if (!this.#active) { throw new Error("The overlay is currently not active."); } else if (this.#active !== dialog) { throw new Error("Another overlay is currently active."); } dialog.close(); this.#active = null; } } exports.OverlayManager = OverlayManager; /***/ }), /* 11 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PasswordPrompt = void 0; var _pdfjsLib = __webpack_require__(5); class PasswordPrompt { #activeCapability = null; #updateCallback = null; #reason = null; constructor(options, overlayManager, l10n, isViewerEmbedded = false) { this.dialog = options.dialog; this.label = options.label; this.input = options.input; this.submitButton = options.submitButton; this.cancelButton = options.cancelButton; this.overlayManager = overlayManager; this.l10n = l10n; this._isViewerEmbedded = isViewerEmbedded; this.submitButton.addEventListener("click", this.#verify.bind(this)); this.cancelButton.addEventListener("click", this.close.bind(this)); this.input.addEventListener("keydown", e => { if (e.keyCode === 13) { this.#verify(); } }); this.overlayManager.register(this.dialog, true); this.dialog.addEventListener("close", this.#cancel.bind(this)); } async open() { if (this.#activeCapability) { await this.#activeCapability.promise; } this.#activeCapability = (0, _pdfjsLib.createPromiseCapability)(); try { await this.overlayManager.open(this.dialog); } catch (ex) { this.#activeCapability = null; throw ex; } const passwordIncorrect = this.#reason === _pdfjsLib.PasswordResponses.INCORRECT_PASSWORD; if (!this._isViewerEmbedded || passwordIncorrect) { this.input.focus(); } this.label.textContent = await this.l10n.get(`password_${passwordIncorrect ? "invalid" : "label"}`); } async close() { if (this.overlayManager.active === this.dialog) { this.overlayManager.close(this.dialog); } } #verify() { const password = this.input.value; if (password?.length > 0) { this.#invokeCallback(password); } } #cancel() { this.#invokeCallback(new Error("PasswordPrompt cancelled.")); this.#activeCapability.resolve(); } #invokeCallback(password) { if (!this.#updateCallback) { return; } this.close(); this.input.value = ""; this.#updateCallback(password); this.#updateCallback = null; } async setUpdateCallback(updateCallback, reason) { if (this.#activeCapability) { await this.#activeCapability.promise; } this.#updateCallback = updateCallback; this.#reason = reason; } } exports.PasswordPrompt = PasswordPrompt; /***/ }), /* 12 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFAttachmentViewer = void 0; var _pdfjsLib = __webpack_require__(5); var _base_tree_viewer = __webpack_require__(13); var _event_utils = __webpack_require__(6); class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { super(options); this.downloadManager = options.downloadManager; this.eventBus._on("fileattachmentannotation", this.#appendAttachment.bind(this)); } reset(keepRenderedCapability = false) { super.reset(); this._attachments = null; if (!keepRenderedCapability) { this._renderedCapability = (0, _pdfjsLib.createPromiseCapability)(); } this._pendingDispatchEvent = false; } async _dispatchEvent(attachmentsCount) { this._renderedCapability.resolve(); if (attachmentsCount === 0 && !this._pendingDispatchEvent) { this._pendingDispatchEvent = true; await (0, _event_utils.waitOnEventOrTimeout)({ target: this.eventBus, name: "annotationlayerrendered", delay: 1000 }); if (!this._pendingDispatchEvent) { return; } } this._pendingDispatchEvent = false; this.eventBus.dispatch("attachmentsloaded", { source: this, attachmentsCount }); } _bindLink(element, { content, filename }) { element.onclick = () => { this.downloadManager.openOrDownloadData(element, content, filename); return false; }; } render({ attachments, keepRenderedCapability = false }) { if (this._attachments) { this.reset(keepRenderedCapability); } this._attachments = attachments || null; if (!attachments) { this._dispatchEvent(0); return; } const names = Object.keys(attachments).sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); const fragment = document.createDocumentFragment(); let attachmentsCount = 0; for (const name of names) { const item = attachments[name]; const content = item.content, filename = (0, _pdfjsLib.getFilenameFromUrl)(item.filename); const div = document.createElement("div"); div.className = "treeItem"; const element = document.createElement("a"); this._bindLink(element, { content, filename }); element.textContent = this._normalizeTextContent(filename); div.append(element); fragment.append(div); attachmentsCount++; } this._finishRendering(fragment, attachmentsCount); } #appendAttachment({ filename, content }) { const renderedPromise = this._renderedCapability.promise; renderedPromise.then(() => { if (renderedPromise !== this._renderedCapability.promise) { return; } const attachments = this._attachments || Object.create(null); for (const name in attachments) { if (filename === name) { return; } } attachments[filename] = { filename, content }; this.render({ attachments, keepRenderedCapability: true }); }); } } exports.PDFAttachmentViewer = PDFAttachmentViewer; /***/ }), /* 13 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseTreeViewer = void 0; var _ui_utils = __webpack_require__(1); const TREEITEM_OFFSET_TOP = -100; const TREEITEM_SELECTED_CLASS = "selected"; class BaseTreeViewer { constructor(options) { if (this.constructor === BaseTreeViewer) { throw new Error("Cannot initialize BaseTreeViewer."); } this.container = options.container; this.eventBus = options.eventBus; this.reset(); } reset() { this._pdfDocument = null; this._lastToggleIsShow = true; this._currentTreeItem = null; this.container.textContent = ""; this.container.classList.remove("treeWithDeepNesting"); } _dispatchEvent(count) { throw new Error("Not implemented: _dispatchEvent"); } _bindLink(element, params) { throw new Error("Not implemented: _bindLink"); } _normalizeTextContent(str) { return (0, _ui_utils.removeNullCharacters)(str, true) || "\u2013"; } _addToggleButton(div, hidden = false) { const toggler = document.createElement("div"); toggler.className = "treeItemToggler"; if (hidden) { toggler.classList.add("treeItemsHidden"); } toggler.onclick = evt => { evt.stopPropagation(); toggler.classList.toggle("treeItemsHidden"); if (evt.shiftKey) { const shouldShowAll = !toggler.classList.contains("treeItemsHidden"); this._toggleTreeItem(div, shouldShowAll); } }; div.prepend(toggler); } _toggleTreeItem(root, show = false) { this._lastToggleIsShow = show; for (const toggler of root.querySelectorAll(".treeItemToggler")) { toggler.classList.toggle("treeItemsHidden", !show); } } _toggleAllTreeItems() { this._toggleTreeItem(this.container, !this._lastToggleIsShow); } _finishRendering(fragment, count, hasAnyNesting = false) { if (hasAnyNesting) { this.container.classList.add("treeWithDeepNesting"); this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden"); } this.container.append(fragment); this._dispatchEvent(count); } render(params) { throw new Error("Not implemented: render"); } _updateCurrentTreeItem(treeItem = null) { if (this._currentTreeItem) { this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS); this._currentTreeItem = null; } if (treeItem) { treeItem.classList.add(TREEITEM_SELECTED_CLASS); this._currentTreeItem = treeItem; } } _scrollToCurrentTreeItem(treeItem) { if (!treeItem) { return; } let currentNode = treeItem.parentNode; while (currentNode && currentNode !== this.container) { if (currentNode.classList.contains("treeItem")) { const toggler = currentNode.firstElementChild; toggler?.classList.remove("treeItemsHidden"); } currentNode = currentNode.parentNode; } this._updateCurrentTreeItem(treeItem); this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP); } } exports.BaseTreeViewer = BaseTreeViewer; /***/ }), /* 14 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFDocumentProperties = void 0; var _pdfjsLib = __webpack_require__(5); var _ui_utils = __webpack_require__(1); const DEFAULT_FIELD_CONTENT = "-"; const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"]; const US_PAGE_NAMES = { "8.5x11": "Letter", "8.5x14": "Legal" }; const METRIC_PAGE_NAMES = { "297x420": "A3", "210x297": "A4" }; function getPageName(size, isPortrait, pageNames) { const width = isPortrait ? size.width : size.height; const height = isPortrait ? size.height : size.width; return pageNames[`${width}x${height}`]; } class PDFDocumentProperties { #fieldData = null; constructor({ dialog, fields, closeButton }, overlayManager, eventBus, l10n, fileNameLookup) { this.dialog = dialog; this.fields = fields; this.overlayManager = overlayManager; this.l10n = l10n; this._fileNameLookup = fileNameLookup; this.#reset(); closeButton.addEventListener("click", this.close.bind(this)); this.overlayManager.register(this.dialog); eventBus._on("pagechanging", evt => { this._currentPageNumber = evt.pageNumber; }); eventBus._on("rotationchanging", evt => { this._pagesRotation = evt.pagesRotation; }); this._isNonMetricLocale = true; l10n.getLanguage().then(locale => { this._isNonMetricLocale = NON_METRIC_LOCALES.includes(locale); }); } async open() { await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]); const currentPageNumber = this._currentPageNumber; const pagesRotation = this._pagesRotation; if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) { this.#updateUI(); return; } const { info, contentLength } = await this.pdfDocument.getMetadata(); const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), this.#parseFileSize(contentLength), this.#parseDate(info.CreationDate), this.#parseDate(info.ModDate), this.pdfDocument.getPage(currentPageNumber).then(pdfPage => { return this.#parsePageSize((0, _ui_utils.getPageSizeInches)(pdfPage), pagesRotation); }), this.#parseLinearization(info.IsLinearized)]); this.#fieldData = Object.freeze({ fileName, fileSize, title: info.Title, author: info.Author, subject: info.Subject, keywords: info.Keywords, creationDate, modificationDate, creator: info.Creator, producer: info.Producer, version: info.PDFFormatVersion, pageCount: this.pdfDocument.numPages, pageSize, linearized: isLinearized, _currentPageNumber: currentPageNumber, _pagesRotation: pagesRotation }); this.#updateUI(); const { length } = await this.pdfDocument.getDownloadInfo(); if (contentLength === length) { return; } const data = Object.assign(Object.create(null), this.#fieldData); data.fileSize = await this.#parseFileSize(length); this.#fieldData = Object.freeze(data); this.#updateUI(); } async close() { this.overlayManager.close(this.dialog); } setDocument(pdfDocument) { if (this.pdfDocument) { this.#reset(); this.#updateUI(true); } if (!pdfDocument) { return; } this.pdfDocument = pdfDocument; this._dataAvailableCapability.resolve(); } #reset() { this.pdfDocument = null; this.#fieldData = null; this._dataAvailableCapability = (0, _pdfjsLib.createPromiseCapability)(); this._currentPageNumber = 1; this._pagesRotation = 0; } #updateUI(reset = false) { if (reset || !this.#fieldData) { for (const id in this.fields) { this.fields[id].textContent = DEFAULT_FIELD_CONTENT; } return; } if (this.overlayManager.active !== this.dialog) { return; } for (const id in this.fields) { const content = this.#fieldData[id]; this.fields[id].textContent = content || content === 0 ? content : DEFAULT_FIELD_CONTENT; } } async #parseFileSize(fileSize = 0) { const kb = fileSize / 1024, mb = kb / 1024; if (!kb) { return undefined; } return this.l10n.get(`document_properties_${mb >= 1 ? "mb" : "kb"}`, { size_mb: mb >= 1 && (+mb.toPrecision(3)).toLocaleString(), size_kb: mb < 1 && (+kb.toPrecision(3)).toLocaleString(), size_b: fileSize.toLocaleString() }); } async #parsePageSize(pageSizeInches, pagesRotation) { if (!pageSizeInches) { return undefined; } if (pagesRotation % 180 !== 0) { pageSizeInches = { width: pageSizeInches.height, height: pageSizeInches.width }; } const isPortrait = (0, _ui_utils.isPortraitOrientation)(pageSizeInches); let sizeInches = { width: Math.round(pageSizeInches.width * 100) / 100, height: Math.round(pageSizeInches.height * 100) / 100 }; let sizeMillimeters = { width: Math.round(pageSizeInches.width * 25.4 * 10) / 10, height: Math.round(pageSizeInches.height * 25.4 * 10) / 10 }; let rawName = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES); if (!rawName && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) { const exactMillimeters = { width: pageSizeInches.width * 25.4, height: pageSizeInches.height * 25.4 }; const intMillimeters = { width: Math.round(sizeMillimeters.width), height: Math.round(sizeMillimeters.height) }; if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) { rawName = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES); if (rawName) { sizeInches = { width: Math.round(intMillimeters.width / 25.4 * 100) / 100, height: Math.round(intMillimeters.height / 25.4 * 100) / 100 }; sizeMillimeters = intMillimeters; } } } const [{ width, height }, unit, name, orientation] = await Promise.all([this._isNonMetricLocale ? sizeInches : sizeMillimeters, this.l10n.get(`document_properties_page_size_unit_${this._isNonMetricLocale ? "inches" : "millimeters"}`), rawName && this.l10n.get(`document_properties_page_size_name_${rawName.toLowerCase()}`), this.l10n.get(`document_properties_page_size_orientation_${isPortrait ? "portrait" : "landscape"}`)]); return this.l10n.get(`document_properties_page_size_dimension_${name ? "name_" : ""}string`, { width: width.toLocaleString(), height: height.toLocaleString(), unit, name, orientation }); } async #parseDate(inputDate) { const dateObject = _pdfjsLib.PDFDateString.toDateObject(inputDate); if (!dateObject) { return undefined; } return this.l10n.get("document_properties_date_string", { date: dateObject.toLocaleDateString(), time: dateObject.toLocaleTimeString() }); } #parseLinearization(isLinearized) { return this.l10n.get(`document_properties_linearized_${isLinearized ? "yes" : "no"}`); } } exports.PDFDocumentProperties = PDFDocumentProperties; /***/ }), /* 15 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFFindBar = void 0; var _pdf_find_controller = __webpack_require__(16); const MATCHES_COUNT_LIMIT = 1000; class PDFFindBar { constructor(options, eventBus, l10n) { this.opened = false; this.bar = options.bar; this.toggleButton = options.toggleButton; this.findField = options.findField; this.highlightAll = options.highlightAllCheckbox; this.caseSensitive = options.caseSensitiveCheckbox; this.matchDiacritics = options.matchDiacriticsCheckbox; this.entireWord = options.entireWordCheckbox; this.findMsg = options.findMsg; this.findResultsCount = options.findResultsCount; this.findPreviousButton = options.findPreviousButton; this.findNextButton = options.findNextButton; this.eventBus = eventBus; this.l10n = l10n; this.toggleButton.addEventListener("click", () => { this.toggle(); }); this.findField.addEventListener("input", () => { this.dispatchEvent(""); }); this.bar.addEventListener("keydown", e => { switch (e.keyCode) { case 13: if (e.target === this.findField) { this.dispatchEvent("again", e.shiftKey); } break; case 27: this.close(); break; } }); this.findPreviousButton.addEventListener("click", () => { this.dispatchEvent("again", true); }); this.findNextButton.addEventListener("click", () => { this.dispatchEvent("again", false); }); this.highlightAll.addEventListener("click", () => { this.dispatchEvent("highlightallchange"); }); this.caseSensitive.addEventListener("click", () => { this.dispatchEvent("casesensitivitychange"); }); this.entireWord.addEventListener("click", () => { this.dispatchEvent("entirewordchange"); }); this.matchDiacritics.addEventListener("click", () => { this.dispatchEvent("diacriticmatchingchange"); }); this.eventBus._on("resize", this.#adjustWidth.bind(this)); } reset() { this.updateUIState(); } dispatchEvent(type, findPrev = false) { this.eventBus.dispatch("find", { source: this, type, query: this.findField.value, phraseSearch: true, caseSensitive: this.caseSensitive.checked, entireWord: this.entireWord.checked, highlightAll: this.highlightAll.checked, findPrevious: findPrev, matchDiacritics: this.matchDiacritics.checked }); } updateUIState(state, previous, matchesCount) { let findMsg = Promise.resolve(""); let status = ""; switch (state) { case _pdf_find_controller.FindState.FOUND: break; case _pdf_find_controller.FindState.PENDING: status = "pending"; break; case _pdf_find_controller.FindState.NOT_FOUND: findMsg = this.l10n.get("find_not_found"); status = "notFound"; break; case _pdf_find_controller.FindState.WRAPPED: findMsg = this.l10n.get(`find_reached_${previous ? "top" : "bottom"}`); break; } this.findField.setAttribute("data-status", status); this.findField.setAttribute("aria-invalid", state === _pdf_find_controller.FindState.NOT_FOUND); findMsg.then(msg => { this.findMsg.textContent = msg; this.#adjustWidth(); }); this.updateResultsCount(matchesCount); } updateResultsCount({ current = 0, total = 0 } = {}) { const limit = MATCHES_COUNT_LIMIT; let matchCountMsg = Promise.resolve(""); if (total > 0) { if (total > limit) { let key = "find_match_count_limit"; matchCountMsg = this.l10n.get(key, { limit }); } else { let key = "find_match_count"; matchCountMsg = this.l10n.get(key, { current, total }); } } matchCountMsg.then(msg => { this.findResultsCount.textContent = msg; this.#adjustWidth(); }); } open() { if (!this.opened) { this.opened = true; this.toggleButton.classList.add("toggled"); this.toggleButton.setAttribute("aria-expanded", "true"); this.bar.classList.remove("hidden"); } this.findField.select(); this.findField.focus(); this.#adjustWidth(); } close() { if (!this.opened) { return; } this.opened = false; this.toggleButton.classList.remove("toggled"); this.toggleButton.setAttribute("aria-expanded", "false"); this.bar.classList.add("hidden"); this.eventBus.dispatch("findbarclose", { source: this }); } toggle() { if (this.opened) { this.close(); } else { this.open(); } } #adjustWidth() { if (!this.opened) { return; } this.bar.classList.remove("wrapContainers"); const findbarHeight = this.bar.clientHeight; const inputContainerHeight = this.bar.firstElementChild.clientHeight; if (findbarHeight > inputContainerHeight) { this.bar.classList.add("wrapContainers"); } } } exports.PDFFindBar = PDFFindBar; /***/ }), /* 16 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFFindController = exports.FindState = void 0; var _ui_utils = __webpack_require__(1); var _pdfjsLib = __webpack_require__(5); var _pdf_find_utils = __webpack_require__(17); const FindState = { FOUND: 0, NOT_FOUND: 1, WRAPPED: 2, PENDING: 3 }; exports.FindState = FindState; const FIND_TIMEOUT = 250; const MATCH_SCROLL_OFFSET_TOP = -50; const MATCH_SCROLL_OFFSET_LEFT = -400; const CHARACTERS_TO_NORMALIZE = { "\u2010": "-", "\u2018": "'", "\u2019": "'", "\u201A": "'", "\u201B": "'", "\u201C": '"', "\u201D": '"', "\u201E": '"', "\u201F": '"', "\u00BC": "1/4", "\u00BD": "1/2", "\u00BE": "3/4" }; const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); const DIACRITICS_EXCEPTION_STR = [...DIACRITICS_EXCEPTION.values()].map(x => String.fromCharCode(x)).join(""); const DIACRITICS_REG_EXP = /\p{M}+/gu; const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; const SYLLABLES_LENGTHS = new Map(); const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; let noSyllablesRegExp = null; let withSyllablesRegExp = null; function normalize(text) { const syllablePositions = []; let m; while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { let { index } = m; for (const char of m[0]) { let len = SYLLABLES_LENGTHS.get(char); if (!len) { len = char.normalize("NFD").length; SYLLABLES_LENGTHS.set(char, len); } syllablePositions.push([len, index++]); } } let normalizationRegex; if (syllablePositions.length === 0 && noSyllablesRegExp) { normalizationRegex = noSyllablesRegExp; } else if (syllablePositions.length > 0 && withSyllablesRegExp) { normalizationRegex = withSyllablesRegExp; } else { const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); const regexp = `([${replace}])|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(\\n)`; if (syllablePositions.length === 0) { normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); } else { normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); } } const rawDiacriticsPositions = []; while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { rawDiacriticsPositions.push([m[0].length, m.index]); } let normalized = text.normalize("NFD"); const positions = [[0, 0]]; let rawDiacriticsIndex = 0; let syllableIndex = 0; let shift = 0; let shiftOrigin = 0; let eol = 0; let hasDiacritics = false; normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, i) => { i -= shiftOrigin; if (p1) { const replacement = CHARACTERS_TO_NORMALIZE[match]; const jj = replacement.length; for (let j = 1; j < jj; j++) { positions.push([i - shift + j, shift - j]); } shift -= jj - 1; return replacement; } if (p2) { const hasTrailingDashEOL = p2.endsWith("\n"); const len = hasTrailingDashEOL ? p2.length - 2 : p2.length; hasDiacritics = true; let jj = len; if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; ++rawDiacriticsIndex; } for (let j = 1; j <= jj; j++) { positions.push([i - 1 - shift + j, shift - j]); } shift -= jj; shiftOrigin += jj; if (hasTrailingDashEOL) { i += len - 1; positions.push([i - shift + 1, 1 + shift]); shift += 1; shiftOrigin += 1; eol += 1; return p2.slice(0, len); } return p2; } if (p3) { positions.push([i - shift + 1, 1 + shift]); shift += 1; shiftOrigin += 1; eol += 1; return p3.charAt(0); } if (p4) { positions.push([i - shift + 1, shift - 1]); shift -= 1; shiftOrigin += 1; eol += 1; return " "; } if (i + eol === syllablePositions[syllableIndex]?.[1]) { const newCharLen = syllablePositions[syllableIndex][0] - 1; ++syllableIndex; for (let j = 1; j <= newCharLen; j++) { positions.push([i - (shift - j), shift - j]); } shift -= newCharLen; shiftOrigin += newCharLen; } return p5; }); positions.push([normalized.length, shift]); return [normalized, positions, hasDiacritics]; } function getOriginalIndex(diffs, pos, len) { if (!diffs) { return [pos, len]; } const start = pos; const end = pos + len; let i = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= start); if (diffs[i][0] > start) { --i; } let j = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= end, i); if (diffs[j][0] > end) { --j; } return [start + diffs[i][1], len + diffs[j][1] - diffs[i][1]]; } class PDFFindController { constructor({ linkService, eventBus }) { this._linkService = linkService; this._eventBus = eventBus; this.#reset(); eventBus._on("find", this.#onFind.bind(this)); eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); } get highlightMatches() { return this._highlightMatches; } get pageMatches() { return this._pageMatches; } get pageMatchesLength() { return this._pageMatchesLength; } get selected() { return this._selected; } get state() { return this._state; } setDocument(pdfDocument) { if (this._pdfDocument) { this.#reset(); } if (!pdfDocument) { return; } this._pdfDocument = pdfDocument; this._firstPageCapability.resolve(); } #onFind(state) { if (!state) { return; } const pdfDocument = this._pdfDocument; const { type } = state; if (this._state === null || this.#shouldDirtyMatch(state)) { this._dirtyMatch = true; } this._state = state; if (type !== "highlightallchange") { this.#updateUIState(FindState.PENDING); } this._firstPageCapability.promise.then(() => { if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { return; } this.#extractText(); const findbarClosed = !this._highlightMatches; const pendingTimeout = !!this._findTimeout; if (this._findTimeout) { clearTimeout(this._findTimeout); this._findTimeout = null; } if (!type) { this._findTimeout = setTimeout(() => { this.#nextMatch(); this._findTimeout = null; }, FIND_TIMEOUT); } else if (this._dirtyMatch) { this.#nextMatch(); } else if (type === "again") { this.#nextMatch(); if (findbarClosed && this._state.highlightAll) { this.#updateAllPages(); } } else if (type === "highlightallchange") { if (pendingTimeout) { this.#nextMatch(); } else { this._highlightMatches = true; } this.#updateAllPages(); } else { this.#nextMatch(); } }); } scrollMatchIntoView({ element = null, selectedLeft = 0, pageIndex = -1, matchIndex = -1 }) { if (!this._scrollMatches || !element) { return; } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { return; } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { return; } this._scrollMatches = false; const spot = { top: MATCH_SCROLL_OFFSET_TOP, left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT }; (0, _ui_utils.scrollIntoView)(element, spot, true); } #reset() { this._highlightMatches = false; this._scrollMatches = false; this._pdfDocument = null; this._pageMatches = []; this._pageMatchesLength = []; this._state = null; this._selected = { pageIdx: -1, matchIdx: -1 }; this._offset = { pageIdx: null, matchIdx: null, wrapped: false }; this._extractTextPromises = []; this._pageContents = []; this._pageDiffs = []; this._hasDiacritics = []; this._matchesCountTotal = 0; this._pagesToSearch = null; this._pendingFindMatches = new Set(); this._resumePageIdx = null; this._dirtyMatch = false; clearTimeout(this._findTimeout); this._findTimeout = null; this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)(); } get #query() { if (this._state.query !== this._rawQuery) { this._rawQuery = this._state.query; [this._normalizedQuery] = normalize(this._state.query); } return this._normalizedQuery; } #shouldDirtyMatch(state) { if (state.query !== this._state.query) { return true; } switch (state.type) { case "again": const pageNumber = this._selected.pageIdx + 1; const linkService = this._linkService; if (pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !linkService.isPageVisible(pageNumber)) { return true; } return false; case "highlightallchange": return false; } return true; } #isEntireWord(content, startIdx, length) { let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); if (match) { const first = content.charCodeAt(startIdx); const limit = match[1].charCodeAt(0); if ((0, _pdf_find_utils.getCharacterType)(first) === (0, _pdf_find_utils.getCharacterType)(limit)) { return false; } } match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); if (match) { const last = content.charCodeAt(startIdx + length - 1); const limit = match[1].charCodeAt(0); if ((0, _pdf_find_utils.getCharacterType)(last) === (0, _pdf_find_utils.getCharacterType)(limit)) { return false; } } return true; } #calculateRegExpMatch(query, entireWord, pageIndex, pageContent) { const matches = [], matchesLength = []; const diffs = this._pageDiffs[pageIndex]; let match; while ((match = query.exec(pageContent)) !== null) { if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { continue; } const [matchPos, matchLen] = getOriginalIndex(diffs, match.index, match[0].length); if (matchLen) { matches.push(matchPos); matchesLength.push(matchLen); } } this._pageMatches[pageIndex] = matches; this._pageMatchesLength[pageIndex] = matchesLength; } #convertToRegExpString(query, hasDiacritics) { const { matchDiacritics } = this._state; let isUnicode = false; query = query.replace(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { if (p1) { return `[ ]*\\${p1}[ ]*`; } if (p2) { return `[ ]*${p2}[ ]*`; } if (p3) { return "[ ]+"; } if (matchDiacritics) { return p4 || p5; } if (p4) { return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; } if (hasDiacritics) { isUnicode = true; return `${p5}\\p{M}*`; } return p5; }); const trailingSpaces = "[ ]*"; if (query.endsWith(trailingSpaces)) { query = query.slice(0, query.length - trailingSpaces.length); } if (matchDiacritics) { if (hasDiacritics) { isUnicode = true; query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; } } return [isUnicode, query]; } #calculateMatch(pageIndex) { let query = this.#query; if (query.length === 0) { return; } const { caseSensitive, entireWord, phraseSearch } = this._state; const pageContent = this._pageContents[pageIndex]; const hasDiacritics = this._hasDiacritics[pageIndex]; let isUnicode = false; if (phraseSearch) { [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); } else { const match = query.match(/\S+/g); if (match) { query = match.sort().reverse().map(q => { const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); isUnicode ||= isUnicodePart; return `(${queryPart})`; }).join("|"); } } const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; query = new RegExp(query, flags); this.#calculateRegExpMatch(query, entireWord, pageIndex, pageContent); if (this._state.highlightAll) { this.#updatePage(pageIndex); } if (this._resumePageIdx === pageIndex) { this._resumePageIdx = null; this.#nextPageMatch(); } const pageMatchesCount = this._pageMatches[pageIndex].length; if (pageMatchesCount > 0) { this._matchesCountTotal += pageMatchesCount; this.#updateUIResultsCount(); } } #extractText() { if (this._extractTextPromises.length > 0) { return; } let promise = Promise.resolve(); for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { const extractTextCapability = (0, _pdfjsLib.createPromiseCapability)(); this._extractTextPromises[i] = extractTextCapability.promise; promise = promise.then(() => { return this._pdfDocument.getPage(i + 1).then(pdfPage => { return pdfPage.getTextContent(); }).then(textContent => { const strBuf = []; for (const textItem of textContent.items) { strBuf.push(textItem.str); if (textItem.hasEOL) { strBuf.push("\n"); } } [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); extractTextCapability.resolve(); }, reason => { console.error(`Unable to get text content for page ${i + 1}`, reason); this._pageContents[i] = ""; this._pageDiffs[i] = null; this._hasDiacritics[i] = false; extractTextCapability.resolve(); }); }); } } #updatePage(index) { if (this._scrollMatches && this._selected.pageIdx === index) { this._linkService.page = index + 1; } this._eventBus.dispatch("updatetextlayermatches", { source: this, pageIndex: index }); } #updateAllPages() { this._eventBus.dispatch("updatetextlayermatches", { source: this, pageIndex: -1 }); } #nextMatch() { const previous = this._state.findPrevious; const currentPageIndex = this._linkService.page - 1; const numPages = this._linkService.pagesCount; this._highlightMatches = true; if (this._dirtyMatch) { this._dirtyMatch = false; this._selected.pageIdx = this._selected.matchIdx = -1; this._offset.pageIdx = currentPageIndex; this._offset.matchIdx = null; this._offset.wrapped = false; this._resumePageIdx = null; this._pageMatches.length = 0; this._pageMatchesLength.length = 0; this._matchesCountTotal = 0; this.#updateAllPages(); for (let i = 0; i < numPages; i++) { if (this._pendingFindMatches.has(i)) { continue; } this._pendingFindMatches.add(i); this._extractTextPromises[i].then(() => { this._pendingFindMatches.delete(i); this.#calculateMatch(i); }); } } if (this.#query === "") { this.#updateUIState(FindState.FOUND); return; } if (this._resumePageIdx) { return; } const offset = this._offset; this._pagesToSearch = numPages; if (offset.matchIdx !== null) { const numPageMatches = this._pageMatches[offset.pageIdx].length; if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; this.#updateMatch(true); return; } this.#advanceOffsetPage(previous); } this.#nextPageMatch(); } #matchesReady(matches) { const offset = this._offset; const numMatches = matches.length; const previous = this._state.findPrevious; if (numMatches) { offset.matchIdx = previous ? numMatches - 1 : 0; this.#updateMatch(true); return true; } this.#advanceOffsetPage(previous); if (offset.wrapped) { offset.matchIdx = null; if (this._pagesToSearch < 0) { this.#updateMatch(false); return true; } } return false; } #nextPageMatch() { if (this._resumePageIdx !== null) { console.error("There can only be one pending page."); } let matches = null; do { const pageIdx = this._offset.pageIdx; matches = this._pageMatches[pageIdx]; if (!matches) { this._resumePageIdx = pageIdx; break; } } while (!this.#matchesReady(matches)); } #advanceOffsetPage(previous) { const offset = this._offset; const numPages = this._linkService.pagesCount; offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; offset.matchIdx = null; this._pagesToSearch--; if (offset.pageIdx >= numPages || offset.pageIdx < 0) { offset.pageIdx = previous ? numPages - 1 : 0; offset.wrapped = true; } } #updateMatch(found = false) { let state = FindState.NOT_FOUND; const wrapped = this._offset.wrapped; this._offset.wrapped = false; if (found) { const previousPage = this._selected.pageIdx; this._selected.pageIdx = this._offset.pageIdx; this._selected.matchIdx = this._offset.matchIdx; state = wrapped ? FindState.WRAPPED : FindState.FOUND; if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { this.#updatePage(previousPage); } } this.#updateUIState(state, this._state.findPrevious); if (this._selected.pageIdx !== -1) { this._scrollMatches = true; this.#updatePage(this._selected.pageIdx); } } #onFindBarClose(evt) { const pdfDocument = this._pdfDocument; this._firstPageCapability.promise.then(() => { if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { return; } if (this._findTimeout) { clearTimeout(this._findTimeout); this._findTimeout = null; } if (this._resumePageIdx) { this._resumePageIdx = null; this._dirtyMatch = true; } this.#updateUIState(FindState.FOUND); this._highlightMatches = false; this.#updateAllPages(); }); } #requestMatchesCount() { const { pageIdx, matchIdx } = this._selected; let current = 0, total = this._matchesCountTotal; if (matchIdx !== -1) { for (let i = 0; i < pageIdx; i++) { current += this._pageMatches[i]?.length || 0; } current += matchIdx + 1; } if (current < 1 || current > total) { current = total = 0; } return { current, total }; } #updateUIResultsCount() { this._eventBus.dispatch("updatefindmatchescount", { source: this, matchesCount: this.#requestMatchesCount() }); } #updateUIState(state, previous = false) { this._eventBus.dispatch("updatefindcontrolstate", { source: this, state, previous, matchesCount: this.#requestMatchesCount(), rawQuery: this._state?.query ?? null }); } } exports.PDFFindController = PDFFindController; /***/ }), /* 17 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CharacterType = void 0; exports.getCharacterType = getCharacterType; const CharacterType = { SPACE: 0, ALPHA_LETTER: 1, PUNCT: 2, HAN_LETTER: 3, KATAKANA_LETTER: 4, HIRAGANA_LETTER: 5, HALFWIDTH_KATAKANA_LETTER: 6, THAI_LETTER: 7 }; exports.CharacterType = CharacterType; function isAlphabeticalScript(charCode) { return charCode < 0x2e80; } function isAscii(charCode) { return (charCode & 0xff80) === 0; } function isAsciiAlpha(charCode) { return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; } function isAsciiDigit(charCode) { return charCode >= 0x30 && charCode <= 0x39; } function isAsciiSpace(charCode) { return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; } function isHan(charCode) { return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; } function isKatakana(charCode) { return charCode >= 0x30a0 && charCode <= 0x30ff; } function isHiragana(charCode) { return charCode >= 0x3040 && charCode <= 0x309f; } function isHalfwidthKatakana(charCode) { return charCode >= 0xff60 && charCode <= 0xff9f; } function isThai(charCode) { return (charCode & 0xff80) === 0x0e00; } function getCharacterType(charCode) { if (isAlphabeticalScript(charCode)) { if (isAscii(charCode)) { if (isAsciiSpace(charCode)) { return CharacterType.SPACE; } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { return CharacterType.ALPHA_LETTER; } return CharacterType.PUNCT; } else if (isThai(charCode)) { return CharacterType.THAI_LETTER; } else if (charCode === 0xa0) { return CharacterType.SPACE; } return CharacterType.ALPHA_LETTER; } if (isHan(charCode)) { return CharacterType.HAN_LETTER; } else if (isKatakana(charCode)) { return CharacterType.KATAKANA_LETTER; } else if (isHiragana(charCode)) { return CharacterType.HIRAGANA_LETTER; } else if (isHalfwidthKatakana(charCode)) { return CharacterType.HALFWIDTH_KATAKANA_LETTER; } return CharacterType.ALPHA_LETTER; } /***/ }), /* 18 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFHistory = void 0; exports.isDestArraysEqual = isDestArraysEqual; exports.isDestHashesEqual = isDestHashesEqual; var _ui_utils = __webpack_require__(1); var _event_utils = __webpack_require__(6); const HASH_CHANGE_TIMEOUT = 1000; const POSITION_UPDATED_THRESHOLD = 50; const UPDATE_VIEWAREA_TIMEOUT = 1000; function getCurrentHash() { return document.location.hash; } class PDFHistory { constructor({ linkService, eventBus }) { this.linkService = linkService; this.eventBus = eventBus; this._initialized = false; this._fingerprint = ""; this.reset(); this._boundEvents = null; this.eventBus._on("pagesinit", () => { this._isPagesLoaded = false; this.eventBus._on("pagesloaded", evt => { this._isPagesLoaded = !!evt.pagesCount; }, { once: true }); }); } initialize({ fingerprint, resetHistory = false, updateUrl = false }) { if (!fingerprint || typeof fingerprint !== "string") { console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); return; } if (this._initialized) { this.reset(); } const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; this._fingerprint = fingerprint; this._updateUrl = updateUrl === true; this._initialized = true; this._bindEvents(); const state = window.history.state; this._popStateInProgress = false; this._blockHashChange = 0; this._currentHash = getCurrentHash(); this._numPositionUpdates = 0; this._uid = this._maxUid = 0; this._destination = null; this._position = null; if (!this._isValidState(state, true) || resetHistory) { const { hash, page, rotation } = this._parseCurrentHash(true); if (!hash || reInitialized || resetHistory) { this._pushOrReplaceState(null, true); return; } this._pushOrReplaceState({ hash, page, rotation }, true); return; } const destination = state.destination; this._updateInternalState(destination, state.uid, true); if (destination.rotation !== undefined) { this._initialRotation = destination.rotation; } if (destination.dest) { this._initialBookmark = JSON.stringify(destination.dest); this._destination.page = null; } else if (destination.hash) { this._initialBookmark = destination.hash; } else if (destination.page) { this._initialBookmark = `page=${destination.page}`; } } reset() { if (this._initialized) { this._pageHide(); this._initialized = false; this._unbindEvents(); } if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } this._initialBookmark = null; this._initialRotation = null; } push({ namedDest = null, explicitDest, pageNumber }) { if (!this._initialized) { return; } if (namedDest && typeof namedDest !== "string") { console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); return; } else if (!Array.isArray(explicitDest)) { console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); return; } else if (!this._isValidPage(pageNumber)) { if (pageNumber !== null || this._destination) { console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); return; } } const hash = namedDest || JSON.stringify(explicitDest); if (!hash) { return; } let forceReplace = false; if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { if (this._destination.page) { return; } forceReplace = true; } if (this._popStateInProgress && !forceReplace) { return; } this._pushOrReplaceState({ dest: explicitDest, hash, page: pageNumber, rotation: this.linkService.rotation }, forceReplace); if (!this._popStateInProgress) { this._popStateInProgress = true; Promise.resolve().then(() => { this._popStateInProgress = false; }); } } pushPage(pageNumber) { if (!this._initialized) { return; } if (!this._isValidPage(pageNumber)) { console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); return; } if (this._destination?.page === pageNumber) { return; } if (this._popStateInProgress) { return; } this._pushOrReplaceState({ dest: null, hash: `page=${pageNumber}`, page: pageNumber, rotation: this.linkService.rotation }); if (!this._popStateInProgress) { this._popStateInProgress = true; Promise.resolve().then(() => { this._popStateInProgress = false; }); } } pushCurrentPosition() { if (!this._initialized || this._popStateInProgress) { return; } this._tryPushCurrentPosition(); } back() { if (!this._initialized || this._popStateInProgress) { return; } const state = window.history.state; if (this._isValidState(state) && state.uid > 0) { window.history.back(); } } forward() { if (!this._initialized || this._popStateInProgress) { return; } const state = window.history.state; if (this._isValidState(state) && state.uid < this._maxUid) { window.history.forward(); } } get popStateInProgress() { return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); } get initialBookmark() { return this._initialized ? this._initialBookmark : null; } get initialRotation() { return this._initialized ? this._initialRotation : null; } _pushOrReplaceState(destination, forceReplace = false) { const shouldReplace = forceReplace || !this._destination; const newState = { fingerprint: this._fingerprint, uid: shouldReplace ? this._uid : this._uid + 1, destination }; this._updateInternalState(destination, newState.uid); let newUrl; if (this._updateUrl && destination?.hash) { const baseUrl = document.location.href.split("#")[0]; if (!baseUrl.startsWith("file://")) { newUrl = `${baseUrl}#${destination.hash}`; } } if (shouldReplace) { window.history.replaceState(newState, "", newUrl); } else { window.history.pushState(newState, "", newUrl); } } _tryPushCurrentPosition(temporary = false) { if (!this._position) { return; } let position = this._position; if (temporary) { position = Object.assign(Object.create(null), this._position); position.temporary = true; } if (!this._destination) { this._pushOrReplaceState(position); return; } if (this._destination.temporary) { this._pushOrReplaceState(position, true); return; } if (this._destination.hash === position.hash) { return; } if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { return; } let forceReplace = false; if (this._destination.page >= position.first && this._destination.page <= position.page) { if (this._destination.dest !== undefined || !this._destination.first) { return; } forceReplace = true; } this._pushOrReplaceState(position, forceReplace); } _isValidPage(val) { return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; } _isValidState(state, checkReload = false) { if (!state) { return false; } if (state.fingerprint !== this._fingerprint) { if (checkReload) { if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { return false; } const [perfEntry] = performance.getEntriesByType("navigation"); if (perfEntry?.type !== "reload") { return false; } } else { return false; } } if (!Number.isInteger(state.uid) || state.uid < 0) { return false; } if (state.destination === null || typeof state.destination !== "object") { return false; } return true; } _updateInternalState(destination, uid, removeTemporary = false) { if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } if (removeTemporary && destination?.temporary) { delete destination.temporary; } this._destination = destination; this._uid = uid; this._maxUid = Math.max(this._maxUid, uid); this._numPositionUpdates = 0; } _parseCurrentHash(checkNameddest = false) { const hash = unescape(getCurrentHash()).substring(1); const params = (0, _ui_utils.parseQueryString)(hash); const nameddest = params.get("nameddest") || ""; let page = params.get("page") | 0; if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) { page = null; } return { hash, page, rotation: this.linkService.rotation }; } _updateViewarea({ location }) { if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } this._position = { hash: location.pdfOpenParams.substring(1), page: this.linkService.page, first: location.pageNumber, rotation: location.rotation }; if (this._popStateInProgress) { return; } if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { this._numPositionUpdates++; } if (UPDATE_VIEWAREA_TIMEOUT > 0) { this._updateViewareaTimeout = setTimeout(() => { if (!this._popStateInProgress) { this._tryPushCurrentPosition(true); } this._updateViewareaTimeout = null; }, UPDATE_VIEWAREA_TIMEOUT); } } _popState({ state }) { const newHash = getCurrentHash(), hashChanged = this._currentHash !== newHash; this._currentHash = newHash; if (!state) { this._uid++; const { hash, page, rotation } = this._parseCurrentHash(); this._pushOrReplaceState({ hash, page, rotation }, true); return; } if (!this._isValidState(state)) { return; } this._popStateInProgress = true; if (hashChanged) { this._blockHashChange++; (0, _event_utils.waitOnEventOrTimeout)({ target: window, name: "hashchange", delay: HASH_CHANGE_TIMEOUT }).then(() => { this._blockHashChange--; }); } const destination = state.destination; this._updateInternalState(destination, state.uid, true); if ((0, _ui_utils.isValidRotation)(destination.rotation)) { this.linkService.rotation = destination.rotation; } if (destination.dest) { this.linkService.goToDestination(destination.dest); } else if (destination.hash) { this.linkService.setHash(destination.hash); } else if (destination.page) { this.linkService.page = destination.page; } Promise.resolve().then(() => { this._popStateInProgress = false; }); } _pageHide() { if (!this._destination || this._destination.temporary) { this._tryPushCurrentPosition(); } } _bindEvents() { if (this._boundEvents) { return; } this._boundEvents = { updateViewarea: this._updateViewarea.bind(this), popState: this._popState.bind(this), pageHide: this._pageHide.bind(this) }; this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea); window.addEventListener("popstate", this._boundEvents.popState); window.addEventListener("pagehide", this._boundEvents.pageHide); } _unbindEvents() { if (!this._boundEvents) { return; } this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea); window.removeEventListener("popstate", this._boundEvents.popState); window.removeEventListener("pagehide", this._boundEvents.pageHide); this._boundEvents = null; } } exports.PDFHistory = PDFHistory; function isDestHashesEqual(destHash, pushHash) { if (typeof destHash !== "string" || typeof pushHash !== "string") { return false; } if (destHash === pushHash) { return true; } const nameddest = (0, _ui_utils.parseQueryString)(destHash).get("nameddest"); if (nameddest === pushHash) { return true; } return false; } function isDestArraysEqual(firstDest, secondDest) { function isEntryEqual(first, second) { if (typeof first !== typeof second) { return false; } if (Array.isArray(first) || Array.isArray(second)) { return false; } if (first !== null && typeof first === "object" && second !== null) { if (Object.keys(first).length !== Object.keys(second).length) { return false; } for (const key in first) { if (!isEntryEqual(first[key], second[key])) { return false; } } return true; } return first === second || Number.isNaN(first) && Number.isNaN(second); } if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { return false; } if (firstDest.length !== secondDest.length) { return false; } for (let i = 0, ii = firstDest.length; i < ii; i++) { if (!isEntryEqual(firstDest[i], secondDest[i])) { return false; } } return true; } /***/ }), /* 19 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFLayerViewer = void 0; var _base_tree_viewer = __webpack_require__(13); class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { super(options); this.l10n = options.l10n; this.eventBus._on("resetlayers", this._resetLayers.bind(this)); this.eventBus._on("togglelayerstree", this._toggleAllTreeItems.bind(this)); } reset() { super.reset(); this._optionalContentConfig = null; } _dispatchEvent(layersCount) { this.eventBus.dispatch("layersloaded", { source: this, layersCount }); } _bindLink(element, { groupId, input }) { const setVisibility = () => { this._optionalContentConfig.setVisibility(groupId, input.checked); this.eventBus.dispatch("optionalcontentconfig", { source: this, promise: Promise.resolve(this._optionalContentConfig) }); }; element.onclick = evt => { if (evt.target === input) { setVisibility(); return true; } else if (evt.target !== element) { return true; } input.checked = !input.checked; setVisibility(); return false; }; } async _setNestedName(element, { name = null }) { if (typeof name === "string") { element.textContent = this._normalizeTextContent(name); return; } element.textContent = await this.l10n.get("additional_layers"); element.style.fontStyle = "italic"; } _addToggleButton(div, { name = null }) { super._addToggleButton(div, name === null); } _toggleAllTreeItems() { if (!this._optionalContentConfig) { return; } super._toggleAllTreeItems(); } render({ optionalContentConfig, pdfDocument }) { if (this._optionalContentConfig) { this.reset(); } this._optionalContentConfig = optionalContentConfig || null; this._pdfDocument = pdfDocument || null; const groups = optionalContentConfig?.getOrder(); if (!groups) { this._dispatchEvent(0); return; } const fragment = document.createDocumentFragment(), queue = [{ parent: fragment, groups }]; let layersCount = 0, hasAnyNesting = false; while (queue.length > 0) { const levelData = queue.shift(); for (const groupId of levelData.groups) { const div = document.createElement("div"); div.className = "treeItem"; const element = document.createElement("a"); div.append(element); if (typeof groupId === "object") { hasAnyNesting = true; this._addToggleButton(div, groupId); this._setNestedName(element, groupId); const itemsDiv = document.createElement("div"); itemsDiv.className = "treeItems"; div.append(itemsDiv); queue.push({ parent: itemsDiv, groups: groupId.order }); } else { const group = optionalContentConfig.getGroup(groupId); const input = document.createElement("input"); this._bindLink(element, { groupId, input }); input.type = "checkbox"; input.checked = group.visible; const label = document.createElement("label"); label.textContent = this._normalizeTextContent(group.name); label.append(input); element.append(label); layersCount++; } levelData.parent.append(div); } } this._finishRendering(fragment, layersCount, hasAnyNesting); } async _resetLayers() { if (!this._optionalContentConfig) { return; } const optionalContentConfig = await this._pdfDocument.getOptionalContentConfig(); this.eventBus.dispatch("optionalcontentconfig", { source: this, promise: Promise.resolve(optionalContentConfig) }); this.render({ optionalContentConfig, pdfDocument: this._pdfDocument }); } } exports.PDFLayerViewer = PDFLayerViewer; /***/ }), /* 20 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFOutlineViewer = void 0; var _base_tree_viewer = __webpack_require__(13); var _pdfjsLib = __webpack_require__(5); var _ui_utils = __webpack_require__(1); class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { super(options); this.linkService = options.linkService; this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this)); this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this)); this.eventBus._on("pagechanging", evt => { this._currentPageNumber = evt.pageNumber; }); this.eventBus._on("pagesloaded", evt => { this._isPagesLoaded = !!evt.pagesCount; if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) { this._currentOutlineItemCapability.resolve(this._isPagesLoaded); } }); this.eventBus._on("sidebarviewchanged", evt => { this._sidebarView = evt.view; }); } reset() { super.reset(); this._outline = null; this._pageNumberToDestHashCapability = null; this._currentPageNumber = 1; this._isPagesLoaded = null; if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) { this._currentOutlineItemCapability.resolve(false); } this._currentOutlineItemCapability = null; } _dispatchEvent(outlineCount) { this._currentOutlineItemCapability = (0, _pdfjsLib.createPromiseCapability)(); if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) { this._currentOutlineItemCapability.resolve(false); } else if (this._isPagesLoaded !== null) { this._currentOutlineItemCapability.resolve(this._isPagesLoaded); } this.eventBus.dispatch("outlineloaded", { source: this, outlineCount, currentOutlineItemPromise: this._currentOutlineItemCapability.promise }); } _bindLink(element, { url, newWindow, dest }) { const { linkService } = this; if (url) { linkService.addLinkAttributes(element, url, newWindow); return; } element.href = linkService.getDestinationHash(dest); element.onclick = evt => { this._updateCurrentTreeItem(evt.target.parentNode); if (dest) { linkService.goToDestination(dest); } return false; }; } _setStyles(element, { bold, italic }) { if (bold) { element.style.fontWeight = "bold"; } if (italic) { element.style.fontStyle = "italic"; } } _addToggleButton(div, { count, items }) { let hidden = false; if (count < 0) { let totalCount = items.length; if (totalCount > 0) { const queue = [...items]; while (queue.length > 0) { const { count: nestedCount, items: nestedItems } = queue.shift(); if (nestedCount > 0 && nestedItems.length > 0) { totalCount += nestedItems.length; queue.push(...nestedItems); } } } if (Math.abs(count) === totalCount) { hidden = true; } } super._addToggleButton(div, hidden); } _toggleAllTreeItems() { if (!this._outline) { return; } super._toggleAllTreeItems(); } render({ outline, pdfDocument }) { if (this._outline) { this.reset(); } this._outline = outline || null; this._pdfDocument = pdfDocument || null; if (!outline) { this._dispatchEvent(0); return; } const fragment = document.createDocumentFragment(); const queue = [{ parent: fragment, items: outline }]; let outlineCount = 0, hasAnyNesting = false; while (queue.length > 0) { const levelData = queue.shift(); for (const item of levelData.items) { const div = document.createElement("div"); div.className = "treeItem"; const element = document.createElement("a"); this._bindLink(element, item); this._setStyles(element, item); element.textContent = this._normalizeTextContent(item.title); div.append(element); if (item.items.length > 0) { hasAnyNesting = true; this._addToggleButton(div, item); const itemsDiv = document.createElement("div"); itemsDiv.className = "treeItems"; div.append(itemsDiv); queue.push({ parent: itemsDiv, items: item.items }); } levelData.parent.append(div); outlineCount++; } } this._finishRendering(fragment, outlineCount, hasAnyNesting); } async _currentOutlineItem() { if (!this._isPagesLoaded) { throw new Error("_currentOutlineItem: All pages have not been loaded."); } if (!this._outline || !this._pdfDocument) { return; } const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument); if (!pageNumberToDestHash) { return; } this._updateCurrentTreeItem(null); if (this._sidebarView !== _ui_utils.SidebarView.OUTLINE) { return; } for (let i = this._currentPageNumber; i > 0; i--) { const destHash = pageNumberToDestHash.get(i); if (!destHash) { continue; } const linkElement = this.container.querySelector(`a[href="${destHash}"]`); if (!linkElement) { continue; } this._scrollToCurrentTreeItem(linkElement.parentNode); break; } } async _getPageNumberToDestHash(pdfDocument) { if (this._pageNumberToDestHashCapability) { return this._pageNumberToDestHashCapability.promise; } this._pageNumberToDestHashCapability = (0, _pdfjsLib.createPromiseCapability)(); const pageNumberToDestHash = new Map(), pageNumberNesting = new Map(); const queue = [{ nesting: 0, items: this._outline }]; while (queue.length > 0) { const levelData = queue.shift(), currentNesting = levelData.nesting; for (const { dest, items } of levelData.items) { let explicitDest, pageNumber; if (typeof dest === "string") { explicitDest = await pdfDocument.getDestination(dest); if (pdfDocument !== this._pdfDocument) { return null; } } else { explicitDest = dest; } if (Array.isArray(explicitDest)) { const [destRef] = explicitDest; if (typeof destRef === "object" && destRef !== null) { pageNumber = this.linkService._cachedPageNumber(destRef); if (!pageNumber) { try { pageNumber = (await pdfDocument.getPageIndex(destRef)) + 1; if (pdfDocument !== this._pdfDocument) { return null; } this.linkService.cachePageRef(pageNumber, destRef); } catch (ex) {} } } else if (Number.isInteger(destRef)) { pageNumber = destRef + 1; } if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) { const destHash = this.linkService.getDestinationHash(dest); pageNumberToDestHash.set(pageNumber, destHash); pageNumberNesting.set(pageNumber, currentNesting); } } if (items.length > 0) { queue.push({ nesting: currentNesting + 1, items }); } } } this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null); return this._pageNumberToDestHashCapability.promise; } } exports.PDFOutlineViewer = PDFOutlineViewer; /***/ }), /* 21 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFPresentationMode = void 0; var _ui_utils = __webpack_require__(1); var _pdfjsLib = __webpack_require__(5); const DELAY_BEFORE_HIDING_CONTROLS = 3000; const ACTIVE_SELECTOR = "pdfPresentationMode"; const CONTROLS_SELECTOR = "pdfPresentationModeControls"; const MOUSE_SCROLL_COOLDOWN_TIME = 50; const PAGE_SWITCH_THRESHOLD = 0.1; const SWIPE_MIN_DISTANCE_THRESHOLD = 50; const SWIPE_ANGLE_THRESHOLD = Math.PI / 6; class PDFPresentationMode { #state = _ui_utils.PresentationModeState.UNKNOWN; #args = null; constructor({ container, pdfViewer, eventBus }) { this.container = container; this.pdfViewer = pdfViewer; this.eventBus = eventBus; this.contextMenuOpen = false; this.mouseScrollTimeStamp = 0; this.mouseScrollDelta = 0; this.touchSwipeState = null; } async request() { const { container, pdfViewer } = this; if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) { return false; } this.#addFullscreenChangeListeners(); this.#notifyStateChange(_ui_utils.PresentationModeState.CHANGING); const promise = container.requestFullscreen(); this.#args = { pageNumber: pdfViewer.currentPageNumber, scaleValue: pdfViewer.currentScaleValue, scrollMode: pdfViewer.scrollMode, spreadMode: null, annotationEditorMode: null }; if (pdfViewer.spreadMode !== _ui_utils.SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) { console.warn("Ignoring Spread modes when entering PresentationMode, " + "since the document may contain varying page sizes."); this.#args.spreadMode = pdfViewer.spreadMode; } if (pdfViewer.annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) { this.#args.annotationEditorMode = pdfViewer.annotationEditorMode; } try { await promise; pdfViewer.focus(); return true; } catch (reason) { this.#removeFullscreenChangeListeners(); this.#notifyStateChange(_ui_utils.PresentationModeState.NORMAL); } return false; } get active() { return this.#state === _ui_utils.PresentationModeState.CHANGING || this.#state === _ui_utils.PresentationModeState.FULLSCREEN; } #mouseWheel(evt) { if (!this.active) { return; } evt.preventDefault(); const delta = (0, _ui_utils.normalizeWheelEventDelta)(evt); const currentTime = Date.now(); const storedTime = this.mouseScrollTimeStamp; if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) { return; } if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) { this.#resetMouseScrollState(); } this.mouseScrollDelta += delta; if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) { const totalDelta = this.mouseScrollDelta; this.#resetMouseScrollState(); const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage(); if (success) { this.mouseScrollTimeStamp = currentTime; } } } #notifyStateChange(state) { this.#state = state; this.eventBus.dispatch("presentationmodechanged", { source: this, state }); } #enter() { this.#notifyStateChange(_ui_utils.PresentationModeState.FULLSCREEN); this.container.classList.add(ACTIVE_SELECTOR); setTimeout(() => { this.pdfViewer.scrollMode = _ui_utils.ScrollMode.PAGE; if (this.#args.spreadMode !== null) { this.pdfViewer.spreadMode = _ui_utils.SpreadMode.NONE; } this.pdfViewer.currentPageNumber = this.#args.pageNumber; this.pdfViewer.currentScaleValue = "page-fit"; if (this.#args.annotationEditorMode !== null) { this.pdfViewer.annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE; } }, 0); this.#addWindowListeners(); this.#showControls(); this.contextMenuOpen = false; window.getSelection().removeAllRanges(); } #exit() { const pageNumber = this.pdfViewer.currentPageNumber; this.container.classList.remove(ACTIVE_SELECTOR); setTimeout(() => { this.#removeFullscreenChangeListeners(); this.#notifyStateChange(_ui_utils.PresentationModeState.NORMAL); this.pdfViewer.scrollMode = this.#args.scrollMode; if (this.#args.spreadMode !== null) { this.pdfViewer.spreadMode = this.#args.spreadMode; } this.pdfViewer.currentScaleValue = this.#args.scaleValue; this.pdfViewer.currentPageNumber = pageNumber; if (this.#args.annotationEditorMode !== null) { this.pdfViewer.annotationEditorMode = this.#args.annotationEditorMode; } this.#args = null; }, 0); this.#removeWindowListeners(); this.#hideControls(); this.#resetMouseScrollState(); this.contextMenuOpen = false; } #mouseDown(evt) { if (this.contextMenuOpen) { this.contextMenuOpen = false; evt.preventDefault(); return; } if (evt.button === 0) { const isInternalLink = evt.target.href && evt.target.classList.contains("internalLink"); if (!isInternalLink) { evt.preventDefault(); if (evt.shiftKey) { this.pdfViewer.previousPage(); } else { this.pdfViewer.nextPage(); } } } } #contextMenu() { this.contextMenuOpen = true; } #showControls() { if (this.controlsTimeout) { clearTimeout(this.controlsTimeout); } else { this.container.classList.add(CONTROLS_SELECTOR); } this.controlsTimeout = setTimeout(() => { this.container.classList.remove(CONTROLS_SELECTOR); delete this.controlsTimeout; }, DELAY_BEFORE_HIDING_CONTROLS); } #hideControls() { if (!this.controlsTimeout) { return; } clearTimeout(this.controlsTimeout); this.container.classList.remove(CONTROLS_SELECTOR); delete this.controlsTimeout; } #resetMouseScrollState() { this.mouseScrollTimeStamp = 0; this.mouseScrollDelta = 0; } #touchSwipe(evt) { if (!this.active) { return; } if (evt.touches.length > 1) { this.touchSwipeState = null; return; } switch (evt.type) { case "touchstart": this.touchSwipeState = { startX: evt.touches[0].pageX, startY: evt.touches[0].pageY, endX: evt.touches[0].pageX, endY: evt.touches[0].pageY }; break; case "touchmove": if (this.touchSwipeState === null) { return; } this.touchSwipeState.endX = evt.touches[0].pageX; this.touchSwipeState.endY = evt.touches[0].pageY; evt.preventDefault(); break; case "touchend": if (this.touchSwipeState === null) { return; } let delta = 0; const dx = this.touchSwipeState.endX - this.touchSwipeState.startX; const dy = this.touchSwipeState.endY - this.touchSwipeState.startY; const absAngle = Math.abs(Math.atan2(dy, dx)); if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) { delta = dx; } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) { delta = dy; } if (delta > 0) { this.pdfViewer.previousPage(); } else if (delta < 0) { this.pdfViewer.nextPage(); } break; } } #addWindowListeners() { this.showControlsBind = this.#showControls.bind(this); this.mouseDownBind = this.#mouseDown.bind(this); this.mouseWheelBind = this.#mouseWheel.bind(this); this.resetMouseScrollStateBind = this.#resetMouseScrollState.bind(this); this.contextMenuBind = this.#contextMenu.bind(this); this.touchSwipeBind = this.#touchSwipe.bind(this); window.addEventListener("mousemove", this.showControlsBind); window.addEventListener("mousedown", this.mouseDownBind); window.addEventListener("wheel", this.mouseWheelBind, { passive: false }); window.addEventListener("keydown", this.resetMouseScrollStateBind); window.addEventListener("contextmenu", this.contextMenuBind); window.addEventListener("touchstart", this.touchSwipeBind); window.addEventListener("touchmove", this.touchSwipeBind); window.addEventListener("touchend", this.touchSwipeBind); } #removeWindowListeners() { window.removeEventListener("mousemove", this.showControlsBind); window.removeEventListener("mousedown", this.mouseDownBind); window.removeEventListener("wheel", this.mouseWheelBind, { passive: false }); window.removeEventListener("keydown", this.resetMouseScrollStateBind); window.removeEventListener("contextmenu", this.contextMenuBind); window.removeEventListener("touchstart", this.touchSwipeBind); window.removeEventListener("touchmove", this.touchSwipeBind); window.removeEventListener("touchend", this.touchSwipeBind); delete this.showControlsBind; delete this.mouseDownBind; delete this.mouseWheelBind; delete this.resetMouseScrollStateBind; delete this.contextMenuBind; delete this.touchSwipeBind; } #fullscreenChange() { if (document.fullscreenElement) { this.#enter(); } else { this.#exit(); } } #addFullscreenChangeListeners() { this.fullscreenChangeBind = this.#fullscreenChange.bind(this); window.addEventListener("fullscreenchange", this.fullscreenChangeBind); } #removeFullscreenChangeListeners() { window.removeEventListener("fullscreenchange", this.fullscreenChangeBind); delete this.fullscreenChangeBind; } } exports.PDFPresentationMode = PDFPresentationMode; /***/ }), /* 22 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFRenderingQueue = void 0; var _pdfjsLib = __webpack_require__(5); var _ui_utils = __webpack_require__(1); const CLEANUP_TIMEOUT = 30000; class PDFRenderingQueue { constructor() { this.pdfViewer = null; this.pdfThumbnailViewer = null; this.onIdle = null; this.highestPriorityPage = null; this.idleTimeout = null; this.printing = false; this.isThumbnailViewEnabled = false; } setViewer(pdfViewer) { this.pdfViewer = pdfViewer; } setThumbnailViewer(pdfThumbnailViewer) { this.pdfThumbnailViewer = pdfThumbnailViewer; } isHighestPriority(view) { return this.highestPriorityPage === view.renderingId; } hasViewer() { return !!this.pdfViewer; } renderHighestPriority(currentlyVisiblePages) { if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; } if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { return; } if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { return; } if (this.printing) { return; } if (this.onIdle) { this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); } } getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { const visibleViews = visible.views, numVisible = visibleViews.length; if (numVisible === 0) { return null; } for (let i = 0; i < numVisible; i++) { const view = visibleViews[i].view; if (!this.isViewFinished(view)) { return view; } } const firstId = visible.first.id, lastId = visible.last.id; if (lastId - firstId + 1 > numVisible) { const visibleIds = visible.ids; for (let i = 1, ii = lastId - firstId; i < ii; i++) { const holeId = scrolledDown ? firstId + i : lastId - i; if (visibleIds.has(holeId)) { continue; } const holeView = views[holeId - 1]; if (!this.isViewFinished(holeView)) { return holeView; } } } let preRenderIndex = scrolledDown ? lastId : firstId - 2; let preRenderView = views[preRenderIndex]; if (preRenderView && !this.isViewFinished(preRenderView)) { return preRenderView; } if (preRenderExtra) { preRenderIndex += scrolledDown ? 1 : -1; preRenderView = views[preRenderIndex]; if (preRenderView && !this.isViewFinished(preRenderView)) { return preRenderView; } } return null; } isViewFinished(view) { return view.renderingState === _ui_utils.RenderingStates.FINISHED; } renderView(view) { switch (view.renderingState) { case _ui_utils.RenderingStates.FINISHED: return false; case _ui_utils.RenderingStates.PAUSED: this.highestPriorityPage = view.renderingId; view.resume(); break; case _ui_utils.RenderingStates.RUNNING: this.highestPriorityPage = view.renderingId; break; case _ui_utils.RenderingStates.INITIAL: this.highestPriorityPage = view.renderingId; view.draw().finally(() => { this.renderHighestPriority(); }).catch(reason => { if (reason instanceof _pdfjsLib.RenderingCancelledException) { return; } console.error(`renderView: "${reason}"`); }); break; } return true; } } exports.PDFRenderingQueue = PDFRenderingQueue; /***/ }), /* 23 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFScriptingManager = void 0; var _ui_utils = __webpack_require__(1); var _pdfjsLib = __webpack_require__(5); class PDFScriptingManager { constructor({ eventBus, sandboxBundleSrc = null, scriptingFactory = null, docPropertiesLookup = null }) { this._pdfDocument = null; this._pdfViewer = null; this._closeCapability = null; this._destroyCapability = null; this._scripting = null; this._mouseState = Object.create(null); this._ready = false; this._eventBus = eventBus; this._sandboxBundleSrc = sandboxBundleSrc; this._scriptingFactory = scriptingFactory; this._docPropertiesLookup = docPropertiesLookup; } setViewer(pdfViewer) { this._pdfViewer = pdfViewer; } async setDocument(pdfDocument) { if (this._pdfDocument) { await this._destroyScripting(); } this._pdfDocument = pdfDocument; if (!pdfDocument) { return; } const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); if (!objects && !docActions) { await this._destroyScripting(); return; } if (pdfDocument !== this._pdfDocument) { return; } try { this._scripting = this._createScripting(); } catch (error) { console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); await this._destroyScripting(); return; } this._internalEvents.set("updatefromsandbox", event => { if (event?.source !== window) { return; } this._updateFromSandbox(event.detail); }); this._internalEvents.set("dispatcheventinsandbox", event => { this._scripting?.dispatchEventInSandbox(event.detail); }); this._internalEvents.set("pagechanging", ({ pageNumber, previous }) => { if (pageNumber === previous) { return; } this._dispatchPageClose(previous); this._dispatchPageOpen(pageNumber); }); this._internalEvents.set("pagerendered", ({ pageNumber }) => { if (!this._pageOpenPending.has(pageNumber)) { return; } if (pageNumber !== this._pdfViewer.currentPageNumber) { return; } this._dispatchPageOpen(pageNumber); }); this._internalEvents.set("pagesdestroy", async event => { await this._dispatchPageClose(this._pdfViewer.currentPageNumber); await this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillClose" }); this._closeCapability?.resolve(); }); this._domEvents.set("mousedown", event => { this._mouseState.isDown = true; }); this._domEvents.set("mouseup", event => { this._mouseState.isDown = false; }); for (const [name, listener] of this._internalEvents) { this._eventBus._on(name, listener); } for (const [name, listener] of this._domEvents) { window.addEventListener(name, listener, true); } try { const docProperties = await this._getDocProperties(); if (pdfDocument !== this._pdfDocument) { return; } await this._scripting.createSandbox({ objects, calculationOrder, appInfo: { platform: navigator.platform, language: navigator.language }, docInfo: { ...docProperties, actions: docActions } }); this._eventBus.dispatch("sandboxcreated", { source: this }); } catch (error) { console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); await this._destroyScripting(); return; } await this._scripting?.dispatchEventInSandbox({ id: "doc", name: "Open" }); await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true); Promise.resolve().then(() => { if (pdfDocument === this._pdfDocument) { this._ready = true; } }); } async dispatchWillSave(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillSave" }); } async dispatchDidSave(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "DidSave" }); } async dispatchWillPrint(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillPrint" }); } async dispatchDidPrint(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "DidPrint" }); } get mouseState() { return this._mouseState; } get destroyPromise() { return this._destroyCapability?.promise || null; } get ready() { return this._ready; } get _internalEvents() { return (0, _pdfjsLib.shadow)(this, "_internalEvents", new Map()); } get _domEvents() { return (0, _pdfjsLib.shadow)(this, "_domEvents", new Map()); } get _pageOpenPending() { return (0, _pdfjsLib.shadow)(this, "_pageOpenPending", new Set()); } get _visitedPages() { return (0, _pdfjsLib.shadow)(this, "_visitedPages", new Map()); } async _updateFromSandbox(detail) { const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode; const { id, siblings, command, value } = detail; if (!id) { switch (command) { case "clear": console.clear(); break; case "error": console.error(value); break; case "layout": if (isInPresentationMode) { return; } const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(value); this._pdfViewer.spreadMode = modes.spreadMode; break; case "page-num": this._pdfViewer.currentPageNumber = value + 1; break; case "print": await this._pdfViewer.pagesPromise; this._eventBus.dispatch("print", { source: this }); break; case "println": console.log(value); break; case "zoom": if (isInPresentationMode) { return; } this._pdfViewer.currentScaleValue = value; break; case "SaveAs": this._eventBus.dispatch("download", { source: this }); break; case "FirstPage": this._pdfViewer.currentPageNumber = 1; break; case "LastPage": this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount; break; case "NextPage": this._pdfViewer.nextPage(); break; case "PrevPage": this._pdfViewer.previousPage(); break; case "ZoomViewIn": if (isInPresentationMode) { return; } this._pdfViewer.increaseScale(); break; case "ZoomViewOut": if (isInPresentationMode) { return; } this._pdfViewer.decreaseScale(); break; } return; } if (isInPresentationMode) { if (detail.focus) { return; } } delete detail.id; delete detail.siblings; const ids = siblings ? [id, ...siblings] : [id]; for (const elementId of ids) { const element = document.querySelector(`[data-element-id="${elementId}"]`); if (element) { element.dispatchEvent(new CustomEvent("updatefromsandbox", { detail })); } else { this._pdfDocument?.annotationStorage.setValue(elementId, detail); } } } async _dispatchPageOpen(pageNumber, initialize = false) { const pdfDocument = this._pdfDocument, visitedPages = this._visitedPages; if (initialize) { this._closeCapability = (0, _pdfjsLib.createPromiseCapability)(); } if (!this._closeCapability) { return; } const pageView = this._pdfViewer.getPageView(pageNumber - 1); if (pageView?.renderingState !== _ui_utils.RenderingStates.FINISHED) { this._pageOpenPending.add(pageNumber); return; } this._pageOpenPending.delete(pageNumber); const actionsPromise = (async () => { const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); if (pdfDocument !== this._pdfDocument) { return; } await this._scripting?.dispatchEventInSandbox({ id: "page", name: "PageOpen", pageNumber, actions }); })(); visitedPages.set(pageNumber, actionsPromise); } async _dispatchPageClose(pageNumber) { const pdfDocument = this._pdfDocument, visitedPages = this._visitedPages; if (!this._closeCapability) { return; } if (this._pageOpenPending.has(pageNumber)) { return; } const actionsPromise = visitedPages.get(pageNumber); if (!actionsPromise) { return; } visitedPages.set(pageNumber, null); await actionsPromise; if (pdfDocument !== this._pdfDocument) { return; } await this._scripting?.dispatchEventInSandbox({ id: "page", name: "PageClose", pageNumber }); } async _getDocProperties() { if (this._docPropertiesLookup) { return this._docPropertiesLookup(this._pdfDocument); } throw new Error("_getDocProperties: Unable to lookup properties."); } _createScripting() { this._destroyCapability = (0, _pdfjsLib.createPromiseCapability)(); if (this._scripting) { throw new Error("_createScripting: Scripting already exists."); } if (this._scriptingFactory) { return this._scriptingFactory.createScripting({ sandboxBundleSrc: this._sandboxBundleSrc }); } throw new Error("_createScripting: Cannot create scripting."); } async _destroyScripting() { if (!this._scripting) { this._pdfDocument = null; this._destroyCapability?.resolve(); return; } if (this._closeCapability) { await Promise.race([this._closeCapability.promise, new Promise(resolve => { setTimeout(resolve, 1000); })]).catch(reason => {}); this._closeCapability = null; } this._pdfDocument = null; try { await this._scripting.destroySandbox(); } catch (ex) {} for (const [name, listener] of this._internalEvents) { this._eventBus._off(name, listener); } this._internalEvents.clear(); for (const [name, listener] of this._domEvents) { window.removeEventListener(name, listener, true); } this._domEvents.clear(); this._pageOpenPending.clear(); this._visitedPages.clear(); this._scripting = null; delete this._mouseState.isDown; this._ready = false; this._destroyCapability?.resolve(); } } exports.PDFScriptingManager = PDFScriptingManager; /***/ }), /* 24 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFSidebar = void 0; var _ui_utils = __webpack_require__(1); const UI_NOTIFICATION_CLASS = "pdfSidebarNotification"; class PDFSidebar { constructor({ elements, pdfViewer, pdfThumbnailViewer, eventBus, l10n }) { this.isOpen = false; this.active = _ui_utils.SidebarView.THUMBS; this.isInitialViewSet = false; this.isInitialEventDispatched = false; this.onToggled = null; this.pdfViewer = pdfViewer; this.pdfThumbnailViewer = pdfThumbnailViewer; this.outerContainer = elements.outerContainer; this.sidebarContainer = elements.sidebarContainer; this.toggleButton = elements.toggleButton; this.thumbnailButton = elements.thumbnailButton; this.outlineButton = elements.outlineButton; this.attachmentsButton = elements.attachmentsButton; this.layersButton = elements.layersButton; this.thumbnailView = elements.thumbnailView; this.outlineView = elements.outlineView; this.attachmentsView = elements.attachmentsView; this.layersView = elements.layersView; this._outlineOptionsContainer = elements.outlineOptionsContainer; this._currentOutlineItemButton = elements.currentOutlineItemButton; this.eventBus = eventBus; this.l10n = l10n; this.#addEventListeners(); } reset() { this.isInitialViewSet = false; this.isInitialEventDispatched = false; this.#hideUINotification(true); this.switchView(_ui_utils.SidebarView.THUMBS); this.outlineButton.disabled = false; this.attachmentsButton.disabled = false; this.layersButton.disabled = false; this._currentOutlineItemButton.disabled = true; } get visibleView() { return this.isOpen ? this.active : _ui_utils.SidebarView.NONE; } setInitialView(view = _ui_utils.SidebarView.NONE) { if (this.isInitialViewSet) { return; } this.isInitialViewSet = true; if (view === _ui_utils.SidebarView.NONE || view === _ui_utils.SidebarView.UNKNOWN) { this.#dispatchEvent(); return; } this.switchView(view, true); if (!this.isInitialEventDispatched) { this.#dispatchEvent(); } } switchView(view, forceOpen = false) { const isViewChanged = view !== this.active; let shouldForceRendering = false; switch (view) { case _ui_utils.SidebarView.NONE: if (this.isOpen) { this.close(); } return; case _ui_utils.SidebarView.THUMBS: if (this.isOpen && isViewChanged) { shouldForceRendering = true; } break; case _ui_utils.SidebarView.OUTLINE: if (this.outlineButton.disabled) { return; } break; case _ui_utils.SidebarView.ATTACHMENTS: if (this.attachmentsButton.disabled) { return; } break; case _ui_utils.SidebarView.LAYERS: if (this.layersButton.disabled) { return; } break; default: console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`); return; } this.active = view; const isThumbs = view === _ui_utils.SidebarView.THUMBS, isOutline = view === _ui_utils.SidebarView.OUTLINE, isAttachments = view === _ui_utils.SidebarView.ATTACHMENTS, isLayers = view === _ui_utils.SidebarView.LAYERS; this.thumbnailButton.classList.toggle("toggled", isThumbs); this.outlineButton.classList.toggle("toggled", isOutline); this.attachmentsButton.classList.toggle("toggled", isAttachments); this.layersButton.classList.toggle("toggled", isLayers); this.thumbnailButton.setAttribute("aria-checked", isThumbs); this.outlineButton.setAttribute("aria-checked", isOutline); this.attachmentsButton.setAttribute("aria-checked", isAttachments); this.layersButton.setAttribute("aria-checked", isLayers); this.thumbnailView.classList.toggle("hidden", !isThumbs); this.outlineView.classList.toggle("hidden", !isOutline); this.attachmentsView.classList.toggle("hidden", !isAttachments); this.layersView.classList.toggle("hidden", !isLayers); this._outlineOptionsContainer.classList.toggle("hidden", !isOutline); if (forceOpen && !this.isOpen) { this.open(); return; } if (shouldForceRendering) { this.#updateThumbnailViewer(); this.#forceRendering(); } if (isViewChanged) { this.#dispatchEvent(); } } open() { if (this.isOpen) { return; } this.isOpen = true; this.toggleButton.classList.add("toggled"); this.toggleButton.setAttribute("aria-expanded", "true"); this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); if (this.active === _ui_utils.SidebarView.THUMBS) { this.#updateThumbnailViewer(); } this.#forceRendering(); this.#dispatchEvent(); this.#hideUINotification(); } close() { if (!this.isOpen) { return; } this.isOpen = false; this.toggleButton.classList.remove("toggled"); this.toggleButton.setAttribute("aria-expanded", "false"); this.outerContainer.classList.add("sidebarMoving"); this.outerContainer.classList.remove("sidebarOpen"); this.#forceRendering(); this.#dispatchEvent(); } toggle() { if (this.isOpen) { this.close(); } else { this.open(); } } #dispatchEvent() { if (this.isInitialViewSet && !this.isInitialEventDispatched) { this.isInitialEventDispatched = true; } this.eventBus.dispatch("sidebarviewchanged", { source: this, view: this.visibleView }); } #forceRendering() { if (this.onToggled) { this.onToggled(); } else { this.pdfViewer.forceRendering(); this.pdfThumbnailViewer.forceRendering(); } } #updateThumbnailViewer() { const { pdfViewer, pdfThumbnailViewer } = this; const pagesCount = pdfViewer.pagesCount; for (let pageIndex = 0; pageIndex < pagesCount; pageIndex++) { const pageView = pdfViewer.getPageView(pageIndex); if (pageView?.renderingState === _ui_utils.RenderingStates.FINISHED) { const thumbnailView = pdfThumbnailViewer.getThumbnail(pageIndex); thumbnailView.setImage(pageView); } } pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); } #showUINotification() { this.l10n.get("toggle_sidebar_notification2.title").then(msg => { this.toggleButton.title = msg; }); if (!this.isOpen) { this.toggleButton.classList.add(UI_NOTIFICATION_CLASS); } } #hideUINotification(reset = false) { if (this.isOpen || reset) { this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); } if (reset) { this.l10n.get("toggle_sidebar.title").then(msg => { this.toggleButton.title = msg; }); } } #addEventListeners() { this.sidebarContainer.addEventListener("transitionend", evt => { if (evt.target === this.sidebarContainer) { this.outerContainer.classList.remove("sidebarMoving"); } }); this.toggleButton.addEventListener("click", () => { this.toggle(); }); this.thumbnailButton.addEventListener("click", () => { this.switchView(_ui_utils.SidebarView.THUMBS); }); this.outlineButton.addEventListener("click", () => { this.switchView(_ui_utils.SidebarView.OUTLINE); }); this.outlineButton.addEventListener("dblclick", () => { this.eventBus.dispatch("toggleoutlinetree", { source: this }); }); this.attachmentsButton.addEventListener("click", () => { this.switchView(_ui_utils.SidebarView.ATTACHMENTS); }); this.layersButton.addEventListener("click", () => { this.switchView(_ui_utils.SidebarView.LAYERS); }); this.layersButton.addEventListener("dblclick", () => { this.eventBus.dispatch("resetlayers", { source: this }); }); this._currentOutlineItemButton.addEventListener("click", () => { this.eventBus.dispatch("currentoutlineitem", { source: this }); }); const onTreeLoaded = (count, button, view) => { button.disabled = !count; if (count) { this.#showUINotification(); } else if (this.active === view) { this.switchView(_ui_utils.SidebarView.THUMBS); } }; this.eventBus._on("outlineloaded", evt => { onTreeLoaded(evt.outlineCount, this.outlineButton, _ui_utils.SidebarView.OUTLINE); evt.currentOutlineItemPromise.then(enabled => { if (!this.isInitialViewSet) { return; } this._currentOutlineItemButton.disabled = !enabled; }); }); this.eventBus._on("attachmentsloaded", evt => { onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, _ui_utils.SidebarView.ATTACHMENTS); }); this.eventBus._on("layersloaded", evt => { onTreeLoaded(evt.layersCount, this.layersButton, _ui_utils.SidebarView.LAYERS); }); this.eventBus._on("presentationmodechanged", evt => { if (evt.state === _ui_utils.PresentationModeState.NORMAL && this.visibleView === _ui_utils.SidebarView.THUMBS) { this.#updateThumbnailViewer(); } }); } } exports.PDFSidebar = PDFSidebar; /***/ }), /* 25 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFSidebarResizer = void 0; var _ui_utils = __webpack_require__(1); const SIDEBAR_WIDTH_VAR = "--sidebar-width"; const SIDEBAR_MIN_WIDTH = 200; const SIDEBAR_RESIZING_CLASS = "sidebarResizing"; class PDFSidebarResizer { constructor(options, eventBus, l10n) { this.isRTL = false; this.sidebarOpen = false; this._width = null; this._outerContainerWidth = null; this._boundEvents = Object.create(null); this.outerContainer = options.outerContainer; this.resizer = options.resizer; this.eventBus = eventBus; l10n.getDirection().then(dir => { this.isRTL = dir === "rtl"; }); this._addEventListeners(); } get outerContainerWidth() { return this._outerContainerWidth ||= this.outerContainer.clientWidth; } _updateWidth(width = 0) { const maxWidth = Math.floor(this.outerContainerWidth / 2); if (width > maxWidth) { width = maxWidth; } if (width < SIDEBAR_MIN_WIDTH) { width = SIDEBAR_MIN_WIDTH; } if (width === this._width) { return false; } this._width = width; _ui_utils.docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); return true; } _mouseMove(evt) { let width = evt.clientX; if (this.isRTL) { width = this.outerContainerWidth - width; } this._updateWidth(width); } _mouseUp(evt) { this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); this.eventBus.dispatch("resize", { source: this }); const _boundEvents = this._boundEvents; window.removeEventListener("mousemove", _boundEvents.mouseMove); window.removeEventListener("mouseup", _boundEvents.mouseUp); } _addEventListeners() { const _boundEvents = this._boundEvents; _boundEvents.mouseMove = this._mouseMove.bind(this); _boundEvents.mouseUp = this._mouseUp.bind(this); this.resizer.addEventListener("mousedown", evt => { if (evt.button !== 0) { return; } this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); window.addEventListener("mousemove", _boundEvents.mouseMove); window.addEventListener("mouseup", _boundEvents.mouseUp); }); this.eventBus._on("sidebarviewchanged", evt => { this.sidebarOpen = !!evt?.view; }); this.eventBus._on("resize", evt => { if (evt?.source !== window) { return; } this._outerContainerWidth = null; if (!this._width) { return; } if (!this.sidebarOpen) { this._updateWidth(this._width); return; } this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); const updated = this._updateWidth(this._width); Promise.resolve().then(() => { this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); if (updated) { this.eventBus.dispatch("resize", { source: this }); } }); }); } } exports.PDFSidebarResizer = PDFSidebarResizer; /***/ }), /* 26 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFThumbnailViewer = void 0; var _ui_utils = __webpack_require__(1); var _pdf_thumbnail_view = __webpack_require__(27); const THUMBNAIL_SCROLL_MARGIN = -19; const THUMBNAIL_SELECTED_CLASS = "selected"; class PDFThumbnailViewer { constructor({ container, eventBus, linkService, renderingQueue, l10n, pageColors }) { this.container = container; this.linkService = linkService; this.renderingQueue = renderingQueue; this.l10n = l10n; this.pageColors = pageColors || null; if (this.pageColors && !(CSS.supports("color", this.pageColors.background) && CSS.supports("color", this.pageColors.foreground))) { if (this.pageColors.background || this.pageColors.foreground) { console.warn("PDFThumbnailViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used."); } this.pageColors = null; } this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdated.bind(this)); this._resetView(); } _scrollUpdated() { this.renderingQueue.renderHighestPriority(); } getThumbnail(index) { return this._thumbnails[index]; } _getVisibleThumbs() { return (0, _ui_utils.getVisibleElements)({ scrollEl: this.container, views: this._thumbnails }); } scrollThumbnailIntoView(pageNumber) { if (!this.pdfDocument) { return; } const thumbnailView = this._thumbnails[pageNumber - 1]; if (!thumbnailView) { console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.'); return; } if (pageNumber !== this._currentPageNumber) { const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1]; prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS); thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); } const { first, last, views } = this._getVisibleThumbs(); if (views.length > 0) { let shouldScroll = false; if (pageNumber <= first.id || pageNumber >= last.id) { shouldScroll = true; } else { for (const { id, percent } of views) { if (id !== pageNumber) { continue; } shouldScroll = percent < 100; break; } } if (shouldScroll) { (0, _ui_utils.scrollIntoView)(thumbnailView.div, { top: THUMBNAIL_SCROLL_MARGIN }); } } this._currentPageNumber = pageNumber; } get pagesRotation() { return this._pagesRotation; } set pagesRotation(rotation) { if (!(0, _ui_utils.isValidRotation)(rotation)) { throw new Error("Invalid thumbnails rotation angle."); } if (!this.pdfDocument) { return; } if (this._pagesRotation === rotation) { return; } this._pagesRotation = rotation; const updateArgs = { rotation }; for (const thumbnail of this._thumbnails) { thumbnail.update(updateArgs); } } cleanup() { for (const thumbnail of this._thumbnails) { if (thumbnail.renderingState !== _ui_utils.RenderingStates.FINISHED) { thumbnail.reset(); } } _pdf_thumbnail_view.TempImageFactory.destroyCanvas(); } _resetView() { this._thumbnails = []; this._currentPageNumber = 1; this._pageLabels = null; this._pagesRotation = 0; this.container.textContent = ""; } setDocument(pdfDocument) { if (this.pdfDocument) { this._cancelRendering(); this._resetView(); } this.pdfDocument = pdfDocument; if (!pdfDocument) { return; } const firstPagePromise = pdfDocument.getPage(1); const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig(); firstPagePromise.then(firstPdfPage => { const pagesCount = pdfDocument.numPages; const viewport = firstPdfPage.getViewport({ scale: 1 }); for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { const thumbnail = new _pdf_thumbnail_view.PDFThumbnailView({ container: this.container, id: pageNum, defaultViewport: viewport.clone(), optionalContentConfigPromise, linkService: this.linkService, renderingQueue: this.renderingQueue, l10n: this.l10n, pageColors: this.pageColors }); this._thumbnails.push(thumbnail); } const firstThumbnailView = this._thumbnails[0]; if (firstThumbnailView) { firstThumbnailView.setPdfPage(firstPdfPage); } const thumbnailView = this._thumbnails[this._currentPageNumber - 1]; thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); }).catch(reason => { console.error("Unable to initialize thumbnail viewer", reason); }); } _cancelRendering() { for (const thumbnail of this._thumbnails) { thumbnail.cancelRendering(); } } setPageLabels(labels) { if (!this.pdfDocument) { return; } if (!labels) { this._pageLabels = null; } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { this._pageLabels = null; console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels."); } else { this._pageLabels = labels; } for (let i = 0, ii = this._thumbnails.length; i < ii; i++) { this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null); } } async #ensurePdfPageLoaded(thumbView) { if (thumbView.pdfPage) { return thumbView.pdfPage; } try { const pdfPage = await this.pdfDocument.getPage(thumbView.id); if (!thumbView.pdfPage) { thumbView.setPdfPage(pdfPage); } return pdfPage; } catch (reason) { console.error("Unable to get page for thumb view", reason); return null; } } #getScrollAhead(visible) { if (visible.first?.id === 1) { return true; } else if (visible.last?.id === this._thumbnails.length) { return false; } return this.scroll.down; } forceRendering() { const visibleThumbs = this._getVisibleThumbs(); const scrollAhead = this.#getScrollAhead(visibleThumbs); const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead); if (thumbView) { this.#ensurePdfPageLoaded(thumbView).then(() => { this.renderingQueue.renderView(thumbView); }); return true; } return false; } } exports.PDFThumbnailViewer = PDFThumbnailViewer; /***/ }), /* 27 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TempImageFactory = exports.PDFThumbnailView = void 0; var _ui_utils = __webpack_require__(1); var _pdfjsLib = __webpack_require__(5); const DRAW_UPSCALE_FACTOR = 2; const MAX_NUM_SCALING_STEPS = 3; const THUMBNAIL_CANVAS_BORDER_WIDTH = 1; const THUMBNAIL_WIDTH = 98; class TempImageFactory { static #tempCanvas = null; static getCanvas(width, height) { const tempCanvas = this.#tempCanvas ||= document.createElement("canvas"); tempCanvas.width = width; tempCanvas.height = height; const ctx = tempCanvas.getContext("2d", { alpha: false }); ctx.save(); ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillRect(0, 0, width, height); ctx.restore(); return [tempCanvas, tempCanvas.getContext("2d")]; } static destroyCanvas() { const tempCanvas = this.#tempCanvas; if (tempCanvas) { tempCanvas.width = 0; tempCanvas.height = 0; } this.#tempCanvas = null; } } exports.TempImageFactory = TempImageFactory; class PDFThumbnailView { constructor({ container, id, defaultViewport, optionalContentConfigPromise, linkService, renderingQueue, l10n, pageColors }) { this.id = id; this.renderingId = "thumbnail" + id; this.pageLabel = null; this.pdfPage = null; this.rotation = 0; this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; this._optionalContentConfigPromise = optionalContentConfigPromise || null; this.pageColors = pageColors || null; this.linkService = linkService; this.renderingQueue = renderingQueue; this.renderTask = null; this.renderingState = _ui_utils.RenderingStates.INITIAL; this.resume = null; const pageWidth = this.viewport.width, pageHeight = this.viewport.height, pageRatio = pageWidth / pageHeight; this.canvasWidth = THUMBNAIL_WIDTH; this.canvasHeight = this.canvasWidth / pageRatio | 0; this.scale = this.canvasWidth / pageWidth; this.l10n = l10n; const anchor = document.createElement("a"); anchor.href = linkService.getAnchorUrl("#page=" + id); this._thumbPageTitle.then(msg => { anchor.title = msg; }); anchor.onclick = function () { linkService.goToPage(id); return false; }; this.anchor = anchor; const div = document.createElement("div"); div.className = "thumbnail"; div.setAttribute("data-page-number", this.id); this.div = div; const ring = document.createElement("div"); ring.className = "thumbnailSelectionRing"; const borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH; ring.style.width = this.canvasWidth + borderAdjustment + "px"; ring.style.height = this.canvasHeight + borderAdjustment + "px"; this.ring = ring; div.append(ring); anchor.append(div); container.append(anchor); } setPdfPage(pdfPage) { this.pdfPage = pdfPage; this.pdfPageRotate = pdfPage.rotate; const totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = pdfPage.getViewport({ scale: 1, rotation: totalRotation }); this.reset(); } reset() { this.cancelRendering(); this.renderingState = _ui_utils.RenderingStates.INITIAL; const pageWidth = this.viewport.width, pageHeight = this.viewport.height, pageRatio = pageWidth / pageHeight; this.canvasHeight = this.canvasWidth / pageRatio | 0; this.scale = this.canvasWidth / pageWidth; this.div.removeAttribute("data-loaded"); const ring = this.ring; ring.textContent = ""; const borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH; ring.style.width = this.canvasWidth + borderAdjustment + "px"; ring.style.height = this.canvasHeight + borderAdjustment + "px"; if (this.canvas) { this.canvas.width = 0; this.canvas.height = 0; delete this.canvas; } if (this.image) { this.image.removeAttribute("src"); delete this.image; } } update({ rotation = null }) { if (typeof rotation === "number") { this.rotation = rotation; } const totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = this.viewport.clone({ scale: 1, rotation: totalRotation }); this.reset(); } cancelRendering() { if (this.renderTask) { this.renderTask.cancel(); this.renderTask = null; } this.resume = null; } _getPageDrawContext(upscaleFactor = 1) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d", { alpha: false }); const outputScale = new _ui_utils.OutputScale(); canvas.width = upscaleFactor * this.canvasWidth * outputScale.sx | 0; canvas.height = upscaleFactor * this.canvasHeight * outputScale.sy | 0; const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; return { ctx, canvas, transform }; } _convertCanvasToImage(canvas) { if (this.renderingState !== _ui_utils.RenderingStates.FINISHED) { throw new Error("_convertCanvasToImage: Rendering has not finished."); } const reducedCanvas = this._reduceImage(canvas); const image = document.createElement("img"); image.className = "thumbnailImage"; this._thumbPageCanvas.then(msg => { image.setAttribute("aria-label", msg); }); image.style.width = this.canvasWidth + "px"; image.style.height = this.canvasHeight + "px"; image.src = reducedCanvas.toDataURL(); this.image = image; this.div.setAttribute("data-loaded", true); this.ring.append(image); reducedCanvas.width = 0; reducedCanvas.height = 0; } draw() { if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) { console.error("Must be in new state before drawing"); return Promise.resolve(); } const { pdfPage } = this; if (!pdfPage) { this.renderingState = _ui_utils.RenderingStates.FINISHED; return Promise.reject(new Error("pdfPage is not loaded")); } this.renderingState = _ui_utils.RenderingStates.RUNNING; const finishRenderTask = async (error = null) => { if (renderTask === this.renderTask) { this.renderTask = null; } if (error instanceof _pdfjsLib.RenderingCancelledException) { return; } this.renderingState = _ui_utils.RenderingStates.FINISHED; this._convertCanvasToImage(canvas); if (error) { throw error; } }; const { ctx, canvas, transform } = this._getPageDrawContext(DRAW_UPSCALE_FACTOR); const drawViewport = this.viewport.clone({ scale: DRAW_UPSCALE_FACTOR * this.scale }); const renderContinueCallback = cont => { if (!this.renderingQueue.isHighestPriority(this)) { this.renderingState = _ui_utils.RenderingStates.PAUSED; this.resume = () => { this.renderingState = _ui_utils.RenderingStates.RUNNING; cont(); }; return; } cont(); }; const renderContext = { canvasContext: ctx, transform, viewport: drawViewport, optionalContentConfigPromise: this._optionalContentConfigPromise, pageColors: this.pageColors }; const renderTask = this.renderTask = pdfPage.render(renderContext); renderTask.onContinue = renderContinueCallback; const resultPromise = renderTask.promise.then(function () { return finishRenderTask(null); }, function (error) { return finishRenderTask(error); }); resultPromise.finally(() => { canvas.width = 0; canvas.height = 0; const pageCached = this.linkService.isPageCached(this.id); if (!pageCached) { this.pdfPage?.cleanup(); } }); return resultPromise; } setImage(pageView) { if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) { return; } const { thumbnailCanvas: canvas, pdfPage, scale } = pageView; if (!canvas) { return; } if (!this.pdfPage) { this.setPdfPage(pdfPage); } if (scale < this.scale) { return; } this.renderingState = _ui_utils.RenderingStates.FINISHED; this._convertCanvasToImage(canvas); } _reduceImage(img) { const { ctx, canvas } = this._getPageDrawContext(); if (img.width <= 2 * canvas.width) { ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); return canvas; } let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS; let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS; const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight); while (reducedWidth > img.width || reducedHeight > img.height) { reducedWidth >>= 1; reducedHeight >>= 1; } reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight); while (reducedWidth > 2 * canvas.width) { reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1); reducedWidth >>= 1; reducedHeight >>= 1; } ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height); return canvas; } get _thumbPageTitle() { return this.l10n.get("thumb_page_title", { page: this.pageLabel ?? this.id }); } get _thumbPageCanvas() { return this.l10n.get("thumb_page_canvas", { page: this.pageLabel ?? this.id }); } setPageLabel(label) { this.pageLabel = typeof label === "string" ? label : null; this._thumbPageTitle.then(msg => { this.anchor.title = msg; }); if (this.renderingState !== _ui_utils.RenderingStates.FINISHED) { return; } this._thumbPageCanvas.then(msg => { this.image?.setAttribute("aria-label", msg); }); } } exports.PDFThumbnailView = PDFThumbnailView; /***/ }), /* 28 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFViewer = exports.PDFSinglePageViewer = void 0; var _ui_utils = __webpack_require__(1); var _base_viewer = __webpack_require__(29); class PDFViewer extends _base_viewer.BaseViewer {} exports.PDFViewer = PDFViewer; class PDFSinglePageViewer extends _base_viewer.BaseViewer { _resetView() { super._resetView(); this._scrollMode = _ui_utils.ScrollMode.PAGE; this._spreadMode = _ui_utils.SpreadMode.NONE; } set scrollMode(mode) {} _updateScrollMode() {} set spreadMode(mode) {} _updateSpreadMode() {} } exports.PDFSinglePageViewer = PDFSinglePageViewer; /***/ }), /* 29 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PagesCountLimit = exports.PDFPageViewBuffer = exports.BaseViewer = void 0; var _pdfjsLib = __webpack_require__(5); var _ui_utils = __webpack_require__(1); var _annotation_editor_layer_builder = __webpack_require__(30); var _annotation_layer_builder = __webpack_require__(32); var _l10n_utils = __webpack_require__(31); var _pdf_page_view = __webpack_require__(33); var _pdf_rendering_queue = __webpack_require__(22); var _pdf_link_service = __webpack_require__(3); var _struct_tree_layer_builder = __webpack_require__(35); var _text_highlighter = __webpack_require__(36); var _text_layer_builder = __webpack_require__(37); var _xfa_layer_builder = __webpack_require__(38); const DEFAULT_CACHE_SIZE = 10; const ENABLE_PERMISSIONS_CLASS = "enablePermissions"; const PagesCountLimit = { FORCE_SCROLL_MODE_PAGE: 15000, FORCE_LAZY_PAGE_INIT: 7500, PAUSE_EAGER_PAGE_INIT: 250 }; exports.PagesCountLimit = PagesCountLimit; function isValidAnnotationEditorMode(mode) { return Object.values(_pdfjsLib.AnnotationEditorType).includes(mode) && mode !== _pdfjsLib.AnnotationEditorType.DISABLE; } class PDFPageViewBuffer { #buf = new Set(); #size = 0; constructor(size) { this.#size = size; } push(view) { const buf = this.#buf; if (buf.has(view)) { buf.delete(view); } buf.add(view); if (buf.size > this.#size) { this.#destroyFirstView(); } } resize(newSize, idsToKeep = null) { this.#size = newSize; const buf = this.#buf; if (idsToKeep) { const ii = buf.size; let i = 1; for (const view of buf) { if (idsToKeep.has(view.id)) { buf.delete(view); buf.add(view); } if (++i > ii) { break; } } } while (buf.size > this.#size) { this.#destroyFirstView(); } } has(view) { return this.#buf.has(view); } [Symbol.iterator]() { return this.#buf.keys(); } #destroyFirstView() { const firstView = this.#buf.keys().next().value; firstView?.destroy(); this.#buf.delete(firstView); } } exports.PDFPageViewBuffer = PDFPageViewBuffer; class BaseViewer { #buffer = null; #annotationEditorMode = _pdfjsLib.AnnotationEditorType.DISABLE; #annotationEditorUIManager = null; #annotationMode = _pdfjsLib.AnnotationMode.ENABLE_FORMS; #enablePermissions = false; #previousContainerHeight = 0; #scrollModePageState = null; #onVisibilityChange = null; constructor(options) { if (this.constructor === BaseViewer) { throw new Error("Cannot initialize BaseViewer."); } const viewerVersion = '2.16.105'; if (_pdfjsLib.version !== viewerVersion) { throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`); } this.container = options.container; this.viewer = options.viewer || options.container.firstElementChild; if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) { throw new Error("Invalid `container` and/or `viewer` option."); } if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { throw new Error("The `container` must be absolutely positioned."); } this.eventBus = options.eventBus; this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService(); this.downloadManager = options.downloadManager || null; this.findController = options.findController || null; this._scriptingManager = options.scriptingManager || null; this.removePageBorders = options.removePageBorders || false; this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE; this.#annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS; this.#annotationEditorMode = options.annotationEditorMode ?? _pdfjsLib.AnnotationEditorType.DISABLE; this.imageResourcesPath = options.imageResourcesPath || ""; this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; this.renderer = options.renderer || _ui_utils.RendererType.CANVAS; this.useOnlyCssZoom = options.useOnlyCssZoom || false; this.maxCanvasPixels = options.maxCanvasPixels; this.l10n = options.l10n || _l10n_utils.NullL10n; this.#enablePermissions = options.enablePermissions || false; this.pageColors = options.pageColors || null; if (this.pageColors && !(CSS.supports("color", this.pageColors.background) && CSS.supports("color", this.pageColors.foreground))) { if (this.pageColors.background || this.pageColors.foreground) { console.warn("BaseViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used."); } this.pageColors = null; } this.defaultRenderingQueue = !options.renderingQueue; if (this.defaultRenderingQueue) { this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue(); this.renderingQueue.setViewer(this); } else { this.renderingQueue = options.renderingQueue; } this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this)); this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN; this._onBeforeDraw = this._onAfterDraw = null; this._resetView(); if (this.removePageBorders) { this.viewer.classList.add("removePageBorders"); } this.updateContainerHeightCss(); } get pagesCount() { return this._pages.length; } getPageView(index) { return this._pages[index]; } get pageViewsReady() { if (!this._pagesCapability.settled) { return false; } return this._pages.every(function (pageView) { return pageView?.pdfPage; }); } get renderForms() { return this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS; } get enableScripting() { return !!this._scriptingManager; } get currentPageNumber() { return this._currentPageNumber; } set currentPageNumber(val) { if (!Number.isInteger(val)) { throw new Error("Invalid page number."); } if (!this.pdfDocument) { return; } if (!this._setCurrentPageNumber(val, true)) { console.error(`currentPageNumber: "${val}" is not a valid page.`); } } _setCurrentPageNumber(val, resetCurrentPageView = false) { if (this._currentPageNumber === val) { if (resetCurrentPageView) { this.#resetCurrentPageView(); } return true; } if (!(0 < val && val <= this.pagesCount)) { return false; } const previous = this._currentPageNumber; this._currentPageNumber = val; this.eventBus.dispatch("pagechanging", { source: this, pageNumber: val, pageLabel: this._pageLabels?.[val - 1] ?? null, previous }); if (resetCurrentPageView) { this.#resetCurrentPageView(); } return true; } get currentPageLabel() { return this._pageLabels?.[this._currentPageNumber - 1] ?? null; } set currentPageLabel(val) { if (!this.pdfDocument) { return; } let page = val | 0; if (this._pageLabels) { const i = this._pageLabels.indexOf(val); if (i >= 0) { page = i + 1; } } if (!this._setCurrentPageNumber(page, true)) { console.error(`currentPageLabel: "${val}" is not a valid page.`); } } get currentScale() { return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE; } set currentScale(val) { if (isNaN(val)) { throw new Error("Invalid numeric scale."); } if (!this.pdfDocument) { return; } this._setScale(val, false); } get currentScaleValue() { return this._currentScaleValue; } set currentScaleValue(val) { if (!this.pdfDocument) { return; } this._setScale(val, false); } get pagesRotation() { return this._pagesRotation; } set pagesRotation(rotation) { if (!(0, _ui_utils.isValidRotation)(rotation)) { throw new Error("Invalid pages rotation angle."); } if (!this.pdfDocument) { return; } rotation %= 360; if (rotation < 0) { rotation += 360; } if (this._pagesRotation === rotation) { return; } this._pagesRotation = rotation; const pageNumber = this._currentPageNumber; const updateArgs = { rotation }; for (const pageView of this._pages) { pageView.update(updateArgs); } if (this._currentScaleValue) { this._setScale(this._currentScaleValue, true); } this.eventBus.dispatch("rotationchanging", { source: this, pagesRotation: rotation, pageNumber }); if (this.defaultRenderingQueue) { this.update(); } } get firstPagePromise() { return this.pdfDocument ? this._firstPageCapability.promise : null; } get onePageRendered() { return this.pdfDocument ? this._onePageRenderedCapability.promise : null; } get pagesPromise() { return this.pdfDocument ? this._pagesCapability.promise : null; } #initializePermissions(permissions) { const params = { annotationEditorMode: this.#annotationEditorMode, annotationMode: this.#annotationMode, textLayerMode: this.textLayerMode }; if (!permissions) { return params; } if (!permissions.includes(_pdfjsLib.PermissionFlag.COPY)) { this.viewer.classList.add(ENABLE_PERMISSIONS_CLASS); } if (!permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_CONTENTS)) { params.annotationEditorMode = _pdfjsLib.AnnotationEditorType.DISABLE; } if (!permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(_pdfjsLib.PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS) { params.annotationMode = _pdfjsLib.AnnotationMode.ENABLE; } return params; } #onePageRenderedOrForceFetch() { if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { return Promise.resolve(); } const visibilityChangePromise = new Promise(resolve => { this.#onVisibilityChange = () => { if (document.visibilityState !== "hidden") { return; } resolve(); document.removeEventListener("visibilitychange", this.#onVisibilityChange); this.#onVisibilityChange = null; }; document.addEventListener("visibilitychange", this.#onVisibilityChange); }); return Promise.race([this._onePageRenderedCapability.promise, visibilityChangePromise]); } setDocument(pdfDocument) { if (this.pdfDocument) { this.eventBus.dispatch("pagesdestroy", { source: this }); this._cancelRendering(); this._resetView(); if (this.findController) { this.findController.setDocument(null); } if (this._scriptingManager) { this._scriptingManager.setDocument(null); } if (this.#annotationEditorUIManager) { this.#annotationEditorUIManager.destroy(); this.#annotationEditorUIManager = null; } } this.pdfDocument = pdfDocument; if (!pdfDocument) { return; } const isPureXfa = pdfDocument.isPureXfa; const pagesCount = pdfDocument.numPages; const firstPagePromise = pdfDocument.getPage(1); const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig(); const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); const mode = this._scrollMode = _ui_utils.ScrollMode.PAGE; this.eventBus.dispatch("scrollmodechanged", { source: this, mode }); } this._pagesCapability.promise.then(() => { this.eventBus.dispatch("pagesloaded", { source: this, pagesCount }); }, () => {}); this._onBeforeDraw = evt => { const pageView = this._pages[evt.pageNumber - 1]; if (!pageView) { return; } this.#buffer.push(pageView); }; this.eventBus._on("pagerender", this._onBeforeDraw); this._onAfterDraw = evt => { if (evt.cssTransform || this._onePageRenderedCapability.settled) { return; } this._onePageRenderedCapability.resolve({ timestamp: evt.timestamp }); this.eventBus._off("pagerendered", this._onAfterDraw); this._onAfterDraw = null; if (this.#onVisibilityChange) { document.removeEventListener("visibilitychange", this.#onVisibilityChange); this.#onVisibilityChange = null; } }; this.eventBus._on("pagerendered", this._onAfterDraw); Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { if (pdfDocument !== this.pdfDocument) { return; } this._firstPageCapability.resolve(firstPdfPage); this._optionalContentConfigPromise = optionalContentConfigPromise; const { annotationEditorMode, annotationMode, textLayerMode } = this.#initializePermissions(permissions); if (annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) { const mode = annotationEditorMode; if (isPureXfa) { console.warn("Warning: XFA-editing is not implemented."); } else if (isValidAnnotationEditorMode(mode)) { this.#annotationEditorUIManager = new _pdfjsLib.AnnotationEditorUIManager(this.container, this.eventBus); if (mode !== _pdfjsLib.AnnotationEditorType.NONE) { this.#annotationEditorUIManager.updateMode(mode); } } else { console.error(`Invalid AnnotationEditor mode: ${mode}`); } } const viewerElement = this._scrollMode === _ui_utils.ScrollMode.PAGE ? null : this.viewer; const scale = this.currentScale; const viewport = firstPdfPage.getViewport({ scale: scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS }); const textLayerFactory = textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !isPureXfa ? this : null; const annotationLayerFactory = annotationMode !== _pdfjsLib.AnnotationMode.DISABLE ? this : null; const xfaLayerFactory = isPureXfa ? this : null; const annotationEditorLayerFactory = this.#annotationEditorUIManager ? this : null; for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { const pageView = new _pdf_page_view.PDFPageView({ container: viewerElement, eventBus: this.eventBus, id: pageNum, scale, defaultViewport: viewport.clone(), optionalContentConfigPromise, renderingQueue: this.renderingQueue, textLayerFactory, textLayerMode, annotationLayerFactory, annotationMode, xfaLayerFactory, annotationEditorLayerFactory, textHighlighterFactory: this, structTreeLayerFactory: this, imageResourcesPath: this.imageResourcesPath, renderer: this.renderer, useOnlyCssZoom: this.useOnlyCssZoom, maxCanvasPixels: this.maxCanvasPixels, pageColors: this.pageColors, l10n: this.l10n }); this._pages.push(pageView); } const firstPageView = this._pages[0]; if (firstPageView) { firstPageView.setPdfPage(firstPdfPage); this.linkService.cachePageRef(1, firstPdfPage.ref); } if (this._scrollMode === _ui_utils.ScrollMode.PAGE) { this.#ensurePageViewVisible(); } else if (this._spreadMode !== _ui_utils.SpreadMode.NONE) { this._updateSpreadMode(); } this.#onePageRenderedOrForceFetch().then(async () => { if (this.findController) { this.findController.setDocument(pdfDocument); } if (this._scriptingManager) { this._scriptingManager.setDocument(pdfDocument); } if (this.#annotationEditorUIManager) { this.eventBus.dispatch("annotationeditormodechanged", { source: this, mode: this.#annotationEditorMode }); } if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { this._pagesCapability.resolve(); return; } let getPagesLeft = pagesCount - 1; if (getPagesLeft <= 0) { this._pagesCapability.resolve(); return; } for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { const promise = pdfDocument.getPage(pageNum).then(pdfPage => { const pageView = this._pages[pageNum - 1]; if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } this.linkService.cachePageRef(pageNum, pdfPage.ref); if (--getPagesLeft === 0) { this._pagesCapability.resolve(); } }, reason => { console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); if (--getPagesLeft === 0) { this._pagesCapability.resolve(); } }); if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { await promise; } } }); this.eventBus.dispatch("pagesinit", { source: this }); pdfDocument.getMetadata().then(({ info }) => { if (pdfDocument !== this.pdfDocument) { return; } if (info.Language) { this.viewer.lang = info.Language; } }); if (this.defaultRenderingQueue) { this.update(); } }).catch(reason => { console.error("Unable to initialize viewer", reason); this._pagesCapability.reject(reason); }); } setPageLabels(labels) { if (!this.pdfDocument) { return; } if (!labels) { this._pageLabels = null; } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { this._pageLabels = null; console.error(`setPageLabels: Invalid page labels.`); } else { this._pageLabels = labels; } for (let i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); } } _resetView() { this._pages = []; this._currentPageNumber = 1; this._currentScale = _ui_utils.UNKNOWN_SCALE; this._currentScaleValue = null; this._pageLabels = null; this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); this._location = null; this._pagesRotation = 0; this._optionalContentConfigPromise = null; this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)(); this._onePageRenderedCapability = (0, _pdfjsLib.createPromiseCapability)(); this._pagesCapability = (0, _pdfjsLib.createPromiseCapability)(); this._scrollMode = _ui_utils.ScrollMode.VERTICAL; this._previousScrollMode = _ui_utils.ScrollMode.UNKNOWN; this._spreadMode = _ui_utils.SpreadMode.NONE; this.#scrollModePageState = { previousPageNumber: 1, scrollDown: true, pages: [] }; if (this._onBeforeDraw) { this.eventBus._off("pagerender", this._onBeforeDraw); this._onBeforeDraw = null; } if (this._onAfterDraw) { this.eventBus._off("pagerendered", this._onAfterDraw); this._onAfterDraw = null; } if (this.#onVisibilityChange) { document.removeEventListener("visibilitychange", this.#onVisibilityChange); this.#onVisibilityChange = null; } this.viewer.textContent = ""; this._updateScrollMode(); this.viewer.removeAttribute("lang"); this.viewer.classList.remove(ENABLE_PERMISSIONS_CLASS); } #ensurePageViewVisible() { if (this._scrollMode !== _ui_utils.ScrollMode.PAGE) { throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); } const pageNumber = this._currentPageNumber, state = this.#scrollModePageState, viewer = this.viewer; viewer.textContent = ""; state.pages.length = 0; if (this._spreadMode === _ui_utils.SpreadMode.NONE && !this.isInPresentationMode) { const pageView = this._pages[pageNumber - 1]; viewer.append(pageView.div); state.pages.push(pageView); } else { const pageIndexSet = new Set(), parity = this._spreadMode - 1; if (parity === -1) { pageIndexSet.add(pageNumber - 1); } else if (pageNumber % 2 !== parity) { pageIndexSet.add(pageNumber - 1); pageIndexSet.add(pageNumber); } else { pageIndexSet.add(pageNumber - 2); pageIndexSet.add(pageNumber - 1); } const spread = document.createElement("div"); spread.className = "spread"; if (this.isInPresentationMode) { const dummyPage = document.createElement("div"); dummyPage.className = "dummyPage"; spread.append(dummyPage); } for (const i of pageIndexSet) { const pageView = this._pages[i]; if (!pageView) { continue; } spread.append(pageView.div); state.pages.push(pageView); } viewer.append(spread); } state.scrollDown = pageNumber >= state.previousPageNumber; state.previousPageNumber = pageNumber; } _scrollUpdate() { if (this.pagesCount === 0) { return; } this.update(); } #scrollIntoView(pageView, pageSpot = null) { const { div, id } = pageView; if (this._scrollMode === _ui_utils.ScrollMode.PAGE) { this._setCurrentPageNumber(id); this.#ensurePageViewVisible(); this.update(); } if (!pageSpot && !this.isInPresentationMode) { const left = div.offsetLeft + div.clientLeft, right = left + div.clientWidth; const { scrollLeft, clientWidth } = this.container; if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { pageSpot = { left: 0, top: 0 }; } } (0, _ui_utils.scrollIntoView)(div, pageSpot); } #isSameScale(newScale) { return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; } _setScaleUpdatePages(newScale, newValue, noScroll = false, preset = false) { this._currentScaleValue = newValue.toString(); if (this.#isSameScale(newScale)) { if (preset) { this.eventBus.dispatch("scalechanging", { source: this, scale: newScale, presetValue: newValue }); } return; } _ui_utils.docStyle.setProperty("--scale-factor", newScale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS); const updateArgs = { scale: newScale }; for (const pageView of this._pages) { pageView.update(updateArgs); } this._currentScale = newScale; if (!noScroll) { let page = this._currentPageNumber, dest; if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { page = this._location.pageNumber; dest = [null, { name: "XYZ" }, this._location.left, this._location.top, null]; } this.scrollPageIntoView({ pageNumber: page, destArray: dest, allowNegativeOffset: true }); } this.eventBus.dispatch("scalechanging", { source: this, scale: newScale, presetValue: preset ? newValue : undefined }); if (this.defaultRenderingQueue) { this.update(); } this.updateContainerHeightCss(); } get _pageWidthScaleFactor() { if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL) { return 2; } return 1; } _setScale(value, noScroll = false) { let scale = parseFloat(value); if (scale > 0) { this._setScaleUpdatePages(scale, value, noScroll, false); } else { const currentPage = this._pages[this._currentPageNumber - 1]; if (!currentPage) { return; } let hPadding = _ui_utils.SCROLLBAR_PADDING, vPadding = _ui_utils.VERTICAL_PADDING; if (this.isInPresentationMode) { hPadding = vPadding = 4; } else if (this.removePageBorders) { hPadding = vPadding = 0; } else if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL) { [hPadding, vPadding] = [vPadding, hPadding]; } const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor; const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; switch (value) { case "page-actual": scale = 1; break; case "page-width": scale = pageWidthScale; break; case "page-height": scale = pageHeightScale; break; case "page-fit": scale = Math.min(pageWidthScale, pageHeightScale); break; case "auto": const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale); break; default: console.error(`_setScale: "${value}" is an unknown zoom value.`); return; } this._setScaleUpdatePages(scale, value, noScroll, true); } } #resetCurrentPageView() { const pageView = this._pages[this._currentPageNumber - 1]; if (this.isInPresentationMode) { this._setScale(this._currentScaleValue, true); } this.#scrollIntoView(pageView); } pageLabelToPageNumber(label) { if (!this._pageLabels) { return null; } const i = this._pageLabels.indexOf(label); if (i < 0) { return null; } return i + 1; } scrollPageIntoView({ pageNumber, destArray = null, allowNegativeOffset = false, ignoreDestinationZoom = false }) { if (!this.pdfDocument) { return; } const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; if (!pageView) { console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); return; } if (this.isInPresentationMode || !destArray) { this._setCurrentPageNumber(pageNumber, true); return; } let x = 0, y = 0; let width = 0, height = 0, widthScale, heightScale; const changeOrientation = pageView.rotation % 180 !== 0; const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; let scale = 0; switch (destArray[1].name) { case "XYZ": x = destArray[2]; y = destArray[3]; scale = destArray[4]; x = x !== null ? x : 0; y = y !== null ? y : pageHeight; break; case "Fit": case "FitB": scale = "page-fit"; break; case "FitH": case "FitBH": y = destArray[2]; scale = "page-width"; if (y === null && this._location) { x = this._location.left; y = this._location.top; } else if (typeof y !== "number" || y < 0) { y = pageHeight; } break; case "FitV": case "FitBV": x = destArray[2]; width = pageWidth; height = pageHeight; scale = "page-height"; break; case "FitR": x = destArray[2]; y = destArray[3]; width = destArray[4] - x; height = destArray[5] - y; const hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING; const vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING; widthScale = (this.container.clientWidth - hPadding) / width / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; heightScale = (this.container.clientHeight - vPadding) / height / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); break; default: console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); return; } if (!ignoreDestinationZoom) { if (scale && scale !== this._currentScale) { this.currentScaleValue = scale; } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) { this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE; } } if (scale === "page-fit" && !destArray[4]) { this.#scrollIntoView(pageView); return; } const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; let left = Math.min(boundingRect[0][0], boundingRect[1][0]); let top = Math.min(boundingRect[0][1], boundingRect[1][1]); if (!allowNegativeOffset) { left = Math.max(left, 0); top = Math.max(top, 0); } this.#scrollIntoView(pageView, { left, top }); } _updateLocation(firstPage) { const currentScale = this._currentScale; const currentScaleValue = this._currentScaleValue; const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; const pageNumber = firstPage.id; const currentPageView = this._pages[pageNumber - 1]; const container = this.container; const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); const intLeft = Math.round(topLeft[0]); const intTop = Math.round(topLeft[1]); let pdfOpenParams = `#page=${pageNumber}`; if (!this.isInPresentationMode) { pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; } this._location = { pageNumber, scale: normalizedScaleValue, top: intTop, left: intLeft, rotation: this._pagesRotation, pdfOpenParams }; } update() { const visible = this._getVisiblePages(); const visiblePages = visible.views, numVisiblePages = visiblePages.length; if (numVisiblePages === 0) { return; } const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); this.#buffer.resize(newCacheSize, visible.ids); this.renderingQueue.renderHighestPriority(visible); const isSimpleLayout = this._spreadMode === _ui_utils.SpreadMode.NONE && (this._scrollMode === _ui_utils.ScrollMode.PAGE || this._scrollMode === _ui_utils.ScrollMode.VERTICAL); const currentId = this._currentPageNumber; let stillFullyVisible = false; for (const page of visiblePages) { if (page.percent < 100) { break; } if (page.id === currentId && isSimpleLayout) { stillFullyVisible = true; break; } } this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); this._updateLocation(visible.first); this.eventBus.dispatch("updateviewarea", { source: this, location: this._location }); } containsElement(element) { return this.container.contains(element); } focus() { this.container.focus(); } get _isContainerRtl() { return getComputedStyle(this.container).direction === "rtl"; } get isInPresentationMode() { return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN; } get isChangingPresentationMode() { return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING; } get isHorizontalScrollbarEnabled() { return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; } get isVerticalScrollbarEnabled() { return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; } _getVisiblePages() { const views = this._scrollMode === _ui_utils.ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, horizontal = this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL, rtl = horizontal && this._isContainerRtl; return (0, _ui_utils.getVisibleElements)({ scrollEl: this.container, views, sortByVisibility: true, horizontal, rtl }); } isPageVisible(pageNumber) { if (!this.pdfDocument) { return false; } if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { console.error(`isPageVisible: "${pageNumber}" is not a valid page.`); return false; } return this._getVisiblePages().ids.has(pageNumber); } isPageCached(pageNumber) { if (!this.pdfDocument) { return false; } if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { console.error(`isPageCached: "${pageNumber}" is not a valid page.`); return false; } const pageView = this._pages[pageNumber - 1]; return this.#buffer.has(pageView); } cleanup() { for (const pageView of this._pages) { if (pageView.renderingState !== _ui_utils.RenderingStates.FINISHED) { pageView.reset(); } } } _cancelRendering() { for (const pageView of this._pages) { pageView.cancelRendering(); } } async #ensurePdfPageLoaded(pageView) { if (pageView.pdfPage) { return pageView.pdfPage; } try { const pdfPage = await this.pdfDocument.getPage(pageView.id); if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } if (!this.linkService._cachedPageNumber?.(pdfPage.ref)) { this.linkService.cachePageRef(pageView.id, pdfPage.ref); } return pdfPage; } catch (reason) { console.error("Unable to get page for page view", reason); return null; } } #getScrollAhead(visible) { if (visible.first?.id === 1) { return true; } else if (visible.last?.id === this.pagesCount) { return false; } switch (this._scrollMode) { case _ui_utils.ScrollMode.PAGE: return this.#scrollModePageState.scrollDown; case _ui_utils.ScrollMode.HORIZONTAL: return this.scroll.right; } return this.scroll.down; } #toggleLoadingIconSpinner(visibleIds) { for (const id of visibleIds) { const pageView = this._pages[id - 1]; pageView?.toggleLoadingIconSpinner(true); } for (const pageView of this.#buffer) { if (visibleIds.has(pageView.id)) { continue; } pageView.toggleLoadingIconSpinner(false); } } forceRendering(currentlyVisiblePages) { const visiblePages = currentlyVisiblePages || this._getVisiblePages(); const scrollAhead = this.#getScrollAhead(visiblePages); const preRenderExtra = this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL; const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); this.#toggleLoadingIconSpinner(visiblePages.ids); if (pageView) { this.#ensurePdfPageLoaded(pageView).then(() => { this.renderingQueue.renderView(pageView); }); return true; } return false; } createTextLayerBuilder({ textLayerDiv, pageIndex, viewport, enhanceTextSelection = false, eventBus, highlighter, accessibilityManager = null }) { return new _text_layer_builder.TextLayerBuilder({ textLayerDiv, eventBus, pageIndex, viewport, enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection, highlighter, accessibilityManager }); } createTextHighlighter({ pageIndex, eventBus }) { return new _text_highlighter.TextHighlighter({ eventBus, pageIndex, findController: this.isInPresentationMode ? null : this.findController }); } createAnnotationLayerBuilder({ pageDiv, pdfPage, annotationStorage = this.pdfDocument?.annotationStorage, imageResourcesPath = "", renderForms = true, l10n = _l10n_utils.NullL10n, enableScripting = this.enableScripting, hasJSActionsPromise = this.pdfDocument?.hasJSActions(), mouseState = this._scriptingManager?.mouseState, fieldObjectsPromise = this.pdfDocument?.getFieldObjects(), annotationCanvasMap = null, accessibilityManager = null }) { return new _annotation_layer_builder.AnnotationLayerBuilder({ pageDiv, pdfPage, annotationStorage, imageResourcesPath, renderForms, linkService: this.linkService, downloadManager: this.downloadManager, l10n, enableScripting, hasJSActionsPromise, mouseState, fieldObjectsPromise, annotationCanvasMap, accessibilityManager }); } createAnnotationEditorLayerBuilder({ uiManager = this.#annotationEditorUIManager, pageDiv, pdfPage, accessibilityManager = null, l10n, annotationStorage = this.pdfDocument?.annotationStorage }) { return new _annotation_editor_layer_builder.AnnotationEditorLayerBuilder({ uiManager, pageDiv, pdfPage, annotationStorage, accessibilityManager, l10n }); } createXfaLayerBuilder({ pageDiv, pdfPage, annotationStorage = this.pdfDocument?.annotationStorage }) { return new _xfa_layer_builder.XfaLayerBuilder({ pageDiv, pdfPage, annotationStorage, linkService: this.linkService }); } createStructTreeLayerBuilder({ pdfPage }) { return new _struct_tree_layer_builder.StructTreeLayerBuilder({ pdfPage }); } get hasEqualPageSizes() { const firstPageView = this._pages[0]; for (let i = 1, ii = this._pages.length; i < ii; ++i) { const pageView = this._pages[i]; if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { return false; } } return true; } getPagesOverview() { return this._pages.map(pageView => { const viewport = pageView.pdfPage.getViewport({ scale: 1 }); if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) { return { width: viewport.width, height: viewport.height, rotation: viewport.rotation }; } return { width: viewport.height, height: viewport.width, rotation: (viewport.rotation - 90) % 360 }; }); } get optionalContentConfigPromise() { if (!this.pdfDocument) { return Promise.resolve(null); } if (!this._optionalContentConfigPromise) { console.error("optionalContentConfigPromise: Not initialized yet."); return this.pdfDocument.getOptionalContentConfig(); } return this._optionalContentConfigPromise; } set optionalContentConfigPromise(promise) { if (!(promise instanceof Promise)) { throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); } if (!this.pdfDocument) { return; } if (!this._optionalContentConfigPromise) { return; } this._optionalContentConfigPromise = promise; const updateArgs = { optionalContentConfigPromise: promise }; for (const pageView of this._pages) { pageView.update(updateArgs); } this.update(); this.eventBus.dispatch("optionalcontentconfigchanged", { source: this, promise }); } get scrollMode() { return this._scrollMode; } set scrollMode(mode) { if (this._scrollMode === mode) { return; } if (!(0, _ui_utils.isValidScrollMode)(mode)) { throw new Error(`Invalid scroll mode: ${mode}`); } if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { return; } this._previousScrollMode = this._scrollMode; this._scrollMode = mode; this.eventBus.dispatch("scrollmodechanged", { source: this, mode }); this._updateScrollMode(this._currentPageNumber); } _updateScrollMode(pageNumber = null) { const scrollMode = this._scrollMode, viewer = this.viewer; viewer.classList.toggle("scrollHorizontal", scrollMode === _ui_utils.ScrollMode.HORIZONTAL); viewer.classList.toggle("scrollWrapped", scrollMode === _ui_utils.ScrollMode.WRAPPED); if (!this.pdfDocument || !pageNumber) { return; } if (scrollMode === _ui_utils.ScrollMode.PAGE) { this.#ensurePageViewVisible(); } else if (this._previousScrollMode === _ui_utils.ScrollMode.PAGE) { this._updateSpreadMode(); } if (this._currentScaleValue && isNaN(this._currentScaleValue)) { this._setScale(this._currentScaleValue, true); } this._setCurrentPageNumber(pageNumber, true); this.update(); } get spreadMode() { return this._spreadMode; } set spreadMode(mode) { if (this._spreadMode === mode) { return; } if (!(0, _ui_utils.isValidSpreadMode)(mode)) { throw new Error(`Invalid spread mode: ${mode}`); } this._spreadMode = mode; this.eventBus.dispatch("spreadmodechanged", { source: this, mode }); this._updateSpreadMode(this._currentPageNumber); } _updateSpreadMode(pageNumber = null) { if (!this.pdfDocument) { return; } const viewer = this.viewer, pages = this._pages; if (this._scrollMode === _ui_utils.ScrollMode.PAGE) { this.#ensurePageViewVisible(); } else { viewer.textContent = ""; if (this._spreadMode === _ui_utils.SpreadMode.NONE) { for (const pageView of this._pages) { viewer.append(pageView.div); } } else { const parity = this._spreadMode - 1; let spread = null; for (let i = 0, ii = pages.length; i < ii; ++i) { if (spread === null) { spread = document.createElement("div"); spread.className = "spread"; viewer.append(spread); } else if (i % 2 === parity) { spread = spread.cloneNode(false); viewer.append(spread); } spread.append(pages[i].div); } } } if (!pageNumber) { return; } if (this._currentScaleValue && isNaN(this._currentScaleValue)) { this._setScale(this._currentScaleValue, true); } this._setCurrentPageNumber(pageNumber, true); this.update(); } _getPageAdvance(currentPageNumber, previous = false) { switch (this._scrollMode) { case _ui_utils.ScrollMode.WRAPPED: { const { views } = this._getVisiblePages(), pageLayout = new Map(); for (const { id, y, percent, widthPercent } of views) { if (percent === 0 || widthPercent < 100) { continue; } let yArray = pageLayout.get(y); if (!yArray) { pageLayout.set(y, yArray ||= []); } yArray.push(id); } for (const yArray of pageLayout.values()) { const currentIndex = yArray.indexOf(currentPageNumber); if (currentIndex === -1) { continue; } const numPages = yArray.length; if (numPages === 1) { break; } if (previous) { for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { const currentId = yArray[i], expectedId = yArray[i + 1] - 1; if (currentId < expectedId) { return currentPageNumber - expectedId; } } } else { for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { const currentId = yArray[i], expectedId = yArray[i - 1] + 1; if (currentId > expectedId) { return expectedId - currentPageNumber; } } } if (previous) { const firstId = yArray[0]; if (firstId < currentPageNumber) { return currentPageNumber - firstId + 1; } } else { const lastId = yArray[numPages - 1]; if (lastId > currentPageNumber) { return lastId - currentPageNumber + 1; } } break; } break; } case _ui_utils.ScrollMode.HORIZONTAL: { break; } case _ui_utils.ScrollMode.PAGE: case _ui_utils.ScrollMode.VERTICAL: { if (this._spreadMode === _ui_utils.SpreadMode.NONE) { break; } const parity = this._spreadMode - 1; if (previous && currentPageNumber % 2 !== parity) { break; } else if (!previous && currentPageNumber % 2 === parity) { break; } const { views } = this._getVisiblePages(), expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; for (const { id, percent, widthPercent } of views) { if (id !== expectedId) { continue; } if (percent > 0 && widthPercent === 100) { return 2; } break; } break; } } return 1; } nextPage() { const currentPageNumber = this._currentPageNumber, pagesCount = this.pagesCount; if (currentPageNumber >= pagesCount) { return false; } const advance = this._getPageAdvance(currentPageNumber, false) || 1; this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); return true; } previousPage() { const currentPageNumber = this._currentPageNumber; if (currentPageNumber <= 1) { return false; } const advance = this._getPageAdvance(currentPageNumber, true) || 1; this.currentPageNumber = Math.max(currentPageNumber - advance, 1); return true; } increaseScale(steps = 1) { let newScale = this._currentScale; do { newScale = (newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.ceil(newScale * 10) / 10; newScale = Math.min(_ui_utils.MAX_SCALE, newScale); } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE); this.currentScaleValue = newScale; } decreaseScale(steps = 1) { let newScale = this._currentScale; do { newScale = (newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.floor(newScale * 10) / 10; newScale = Math.max(_ui_utils.MIN_SCALE, newScale); } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE); this.currentScaleValue = newScale; } updateContainerHeightCss() { const height = this.container.clientHeight; if (height !== this.#previousContainerHeight) { this.#previousContainerHeight = height; _ui_utils.docStyle.setProperty("--viewer-container-height", `${height}px`); } } get annotationEditorMode() { return this.#annotationEditorUIManager ? this.#annotationEditorMode : _pdfjsLib.AnnotationEditorType.DISABLE; } set annotationEditorMode(mode) { if (!this.#annotationEditorUIManager) { throw new Error(`The AnnotationEditor is not enabled.`); } if (this.#annotationEditorMode === mode) { return; } if (!isValidAnnotationEditorMode(mode)) { throw new Error(`Invalid AnnotationEditor mode: ${mode}`); } if (!this.pdfDocument) { return; } this.#annotationEditorMode = mode; this.eventBus.dispatch("annotationeditormodechanged", { source: this, mode }); this.#annotationEditorUIManager.updateMode(mode); } set annotationEditorParams({ type, value }) { if (!this.#annotationEditorUIManager) { throw new Error(`The AnnotationEditor is not enabled.`); } this.#annotationEditorUIManager.updateParams(type, value); } refresh() { if (!this.pdfDocument) { return; } const updateArgs = {}; for (const pageView of this._pages) { pageView.update(updateArgs); } this.update(); } } exports.BaseViewer = BaseViewer; /***/ }), /* 30 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AnnotationEditorLayerBuilder = void 0; var _pdfjsLib = __webpack_require__(5); var _l10n_utils = __webpack_require__(31); class AnnotationEditorLayerBuilder { #uiManager; constructor(options) { this.pageDiv = options.pageDiv; this.pdfPage = options.pdfPage; this.annotationStorage = options.annotationStorage || null; this.accessibilityManager = options.accessibilityManager; this.l10n = options.l10n || _l10n_utils.NullL10n; this.annotationEditorLayer = null; this.div = null; this._cancelled = false; this.#uiManager = options.uiManager; } async render(viewport, intent = "display") { if (intent !== "display") { return; } if (this._cancelled) { return; } const clonedViewport = viewport.clone({ dontFlip: true }); if (this.div) { this.annotationEditorLayer.update({ viewport: clonedViewport }); this.show(); return; } this.div = document.createElement("div"); this.div.className = "annotationEditorLayer"; this.div.tabIndex = 0; this.pageDiv.append(this.div); this.annotationEditorLayer = new _pdfjsLib.AnnotationEditorLayer({ uiManager: this.#uiManager, div: this.div, annotationStorage: this.annotationStorage, accessibilityManager: this.accessibilityManager, pageIndex: this.pdfPage._pageIndex, l10n: this.l10n, viewport: clonedViewport }); const parameters = { viewport: clonedViewport, div: this.div, annotations: null, intent }; this.annotationEditorLayer.render(parameters); } cancel() { this._cancelled = true; this.destroy(); } hide() { if (!this.div) { return; } this.div.hidden = true; } show() { if (!this.div) { return; } this.div.hidden = false; } destroy() { if (!this.div) { return; } this.pageDiv = null; this.annotationEditorLayer.destroy(); this.div.remove(); } } exports.AnnotationEditorLayerBuilder = AnnotationEditorLayerBuilder; /***/ }), /* 31 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NullL10n = void 0; exports.fixupLangCode = fixupLangCode; exports.getL10nFallback = getL10nFallback; const DEFAULT_L10N_STRINGS = { of_pages: "of {{pagesCount}}", page_of_pages: "({{pageNumber}} of {{pagesCount}})", document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)", document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)", document_properties_date_string: "{{date}}, {{time}}", document_properties_page_size_unit_inches: "in", document_properties_page_size_unit_millimeters: "mm", document_properties_page_size_orientation_portrait: "portrait", document_properties_page_size_orientation_landscape: "landscape", document_properties_page_size_name_a3: "A3", document_properties_page_size_name_a4: "A4", document_properties_page_size_name_letter: "Letter", document_properties_page_size_name_legal: "Legal", document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})", document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})", document_properties_linearized_yes: "Yes", document_properties_linearized_no: "No", print_progress_percent: "{{progress}}%", "toggle_sidebar.title": "Toggle Sidebar", "toggle_sidebar_notification2.title": "Toggle Sidebar (document contains outline/attachments/layers)", additional_layers: "Additional Layers", page_landmark: "Page {{page}}", thumb_page_title: "Page {{page}}", thumb_page_canvas: "Thumbnail of Page {{page}}", find_reached_top: "Reached top of document, continued from bottom", find_reached_bottom: "Reached end of document, continued from top", "find_match_count[one]": "{{current}} of {{total}} match", "find_match_count[other]": "{{current}} of {{total}} matches", "find_match_count_limit[one]": "More than {{limit}} match", "find_match_count_limit[other]": "More than {{limit}} matches", find_not_found: "Phrase not found", error_version_info: "PDF.js v{{version}} (build: {{build}})", error_message: "Message: {{message}}", error_stack: "Stack: {{stack}}", error_file: "File: {{file}}", error_line: "Line: {{line}}", rendering_error: "An error occurred while rendering the page.", page_scale_width: "Page Width", page_scale_fit: "Page Fit", page_scale_auto: "Automatic Zoom", page_scale_actual: "Actual Size", page_scale_percent: "{{scale}}%", loading: "Loading…", loading_error: "An error occurred while loading the PDF.", invalid_file_error: "Invalid or corrupted PDF file.", missing_file_error: "Missing PDF file.", unexpected_response_error: "Unexpected server response.", printing_not_supported: "Warning: Printing is not fully supported by this browser.", printing_not_ready: "Warning: The PDF is not fully loaded for printing.", web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts.", free_text_default_content: "Enter text…", editor_free_text_aria_label: "FreeText Editor", editor_ink_aria_label: "Ink Editor", editor_ink_canvas_aria_label: "User-created image" }; }