base_viewer.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PagesCountLimit = exports.PDFPageViewBuffer = exports.BaseViewer = void 0;
  27. var _pdf = require("../pdf");
  28. var _ui_utils = require("./ui_utils.js");
  29. var _annotation_layer_builder = require("./annotation_layer_builder.js");
  30. var _l10n_utils = require("./l10n_utils.js");
  31. var _pdf_page_view = require("./pdf_page_view.js");
  32. var _pdf_rendering_queue = require("./pdf_rendering_queue.js");
  33. var _pdf_link_service = require("./pdf_link_service.js");
  34. var _struct_tree_layer_builder = require("./struct_tree_layer_builder.js");
  35. var _text_highlighter = require("./text_highlighter.js");
  36. var _text_layer_builder = require("./text_layer_builder.js");
  37. var _xfa_layer_builder = require("./xfa_layer_builder.js");
  38. const DEFAULT_CACHE_SIZE = 10;
  39. const ENABLE_PERMISSIONS_CLASS = "enablePermissions";
  40. const PagesCountLimit = {
  41. FORCE_SCROLL_MODE_PAGE: 15000,
  42. FORCE_LAZY_PAGE_INIT: 7500,
  43. PAUSE_EAGER_PAGE_INIT: 250
  44. };
  45. exports.PagesCountLimit = PagesCountLimit;
  46. class PDFPageViewBuffer {
  47. #buf = new Set();
  48. #size = 0;
  49. constructor(size) {
  50. this.#size = size;
  51. }
  52. push(view) {
  53. const buf = this.#buf;
  54. if (buf.has(view)) {
  55. buf.delete(view);
  56. }
  57. buf.add(view);
  58. if (buf.size > this.#size) {
  59. this.#destroyFirstView();
  60. }
  61. }
  62. resize(newSize, idsToKeep = null) {
  63. this.#size = newSize;
  64. const buf = this.#buf;
  65. if (idsToKeep) {
  66. const ii = buf.size;
  67. let i = 1;
  68. for (const view of buf) {
  69. if (idsToKeep.has(view.id)) {
  70. buf.delete(view);
  71. buf.add(view);
  72. }
  73. if (++i > ii) {
  74. break;
  75. }
  76. }
  77. }
  78. while (buf.size > this.#size) {
  79. this.#destroyFirstView();
  80. }
  81. }
  82. has(view) {
  83. return this.#buf.has(view);
  84. }
  85. [Symbol.iterator]() {
  86. return this.#buf.keys();
  87. }
  88. #destroyFirstView() {
  89. const firstView = this.#buf.keys().next().value;
  90. firstView?.destroy();
  91. this.#buf.delete(firstView);
  92. }
  93. }
  94. exports.PDFPageViewBuffer = PDFPageViewBuffer;
  95. class BaseViewer {
  96. #buffer = null;
  97. #annotationMode = _pdf.AnnotationMode.ENABLE_FORMS;
  98. #previousAnnotationMode = null;
  99. #enablePermissions = false;
  100. #previousContainerHeight = 0;
  101. #scrollModePageState = null;
  102. #onVisibilityChange = null;
  103. constructor(options) {
  104. if (this.constructor === BaseViewer) {
  105. throw new Error("Cannot initialize BaseViewer.");
  106. }
  107. const viewerVersion = '2.14.305';
  108. if (_pdf.version !== viewerVersion) {
  109. throw new Error(`The API version "${_pdf.version}" does not match the Viewer version "${viewerVersion}".`);
  110. }
  111. this.container = options.container;
  112. this.viewer = options.viewer || options.container.firstElementChild;
  113. if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) {
  114. throw new Error("Invalid `container` and/or `viewer` option.");
  115. }
  116. if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") {
  117. throw new Error("The `container` must be absolutely positioned.");
  118. }
  119. this.eventBus = options.eventBus;
  120. this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();
  121. this.downloadManager = options.downloadManager || null;
  122. this.findController = options.findController || null;
  123. this._scriptingManager = options.scriptingManager || null;
  124. this.removePageBorders = options.removePageBorders || false;
  125. this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  126. this.#annotationMode = options.annotationMode ?? _pdf.AnnotationMode.ENABLE_FORMS;
  127. this.imageResourcesPath = options.imageResourcesPath || "";
  128. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  129. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  130. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  131. this.maxCanvasPixels = options.maxCanvasPixels;
  132. this.l10n = options.l10n || _l10n_utils.NullL10n;
  133. this.#enablePermissions = options.enablePermissions || false;
  134. this.pageColors = options.pageColors || null;
  135. if (options.pageColors && (!CSS.supports("color", options.pageColors.background) || !CSS.supports("color", options.pageColors.foreground))) {
  136. if (options.pageColors.background || options.pageColors.foreground) {
  137. console.warn("Ignoring `pageColors`-option, since the browser doesn't support the values used.");
  138. }
  139. this.pageColors = null;
  140. }
  141. this.defaultRenderingQueue = !options.renderingQueue;
  142. if (this.defaultRenderingQueue) {
  143. this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  144. this.renderingQueue.setViewer(this);
  145. } else {
  146. this.renderingQueue = options.renderingQueue;
  147. }
  148. this._doc = document.documentElement;
  149. this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this));
  150. this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN;
  151. this._onBeforeDraw = this._onAfterDraw = null;
  152. this._resetView();
  153. if (this.removePageBorders) {
  154. this.viewer.classList.add("removePageBorders");
  155. }
  156. this.updateContainerHeightCss();
  157. Promise.resolve().then(() => {
  158. this.eventBus.dispatch("baseviewerinit", {
  159. source: this
  160. });
  161. });
  162. }
  163. get pagesCount() {
  164. return this._pages.length;
  165. }
  166. getPageView(index) {
  167. return this._pages[index];
  168. }
  169. get pageViewsReady() {
  170. if (!this._pagesCapability.settled) {
  171. return false;
  172. }
  173. return this._pages.every(function (pageView) {
  174. return pageView?.pdfPage;
  175. });
  176. }
  177. get renderForms() {
  178. return this.#annotationMode === _pdf.AnnotationMode.ENABLE_FORMS;
  179. }
  180. get enableScripting() {
  181. return !!this._scriptingManager;
  182. }
  183. get currentPageNumber() {
  184. return this._currentPageNumber;
  185. }
  186. set currentPageNumber(val) {
  187. if (!Number.isInteger(val)) {
  188. throw new Error("Invalid page number.");
  189. }
  190. if (!this.pdfDocument) {
  191. return;
  192. }
  193. if (!this._setCurrentPageNumber(val, true)) {
  194. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  195. }
  196. }
  197. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  198. if (this._currentPageNumber === val) {
  199. if (resetCurrentPageView) {
  200. this.#resetCurrentPageView();
  201. }
  202. return true;
  203. }
  204. if (!(0 < val && val <= this.pagesCount)) {
  205. return false;
  206. }
  207. const previous = this._currentPageNumber;
  208. this._currentPageNumber = val;
  209. this.eventBus.dispatch("pagechanging", {
  210. source: this,
  211. pageNumber: val,
  212. pageLabel: this._pageLabels?.[val - 1] ?? null,
  213. previous
  214. });
  215. if (resetCurrentPageView) {
  216. this.#resetCurrentPageView();
  217. }
  218. return true;
  219. }
  220. get currentPageLabel() {
  221. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  222. }
  223. set currentPageLabel(val) {
  224. if (!this.pdfDocument) {
  225. return;
  226. }
  227. let page = val | 0;
  228. if (this._pageLabels) {
  229. const i = this._pageLabels.indexOf(val);
  230. if (i >= 0) {
  231. page = i + 1;
  232. }
  233. }
  234. if (!this._setCurrentPageNumber(page, true)) {
  235. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  236. }
  237. }
  238. get currentScale() {
  239. return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE;
  240. }
  241. set currentScale(val) {
  242. if (isNaN(val)) {
  243. throw new Error("Invalid numeric scale.");
  244. }
  245. if (!this.pdfDocument) {
  246. return;
  247. }
  248. this._setScale(val, false);
  249. }
  250. get currentScaleValue() {
  251. return this._currentScaleValue;
  252. }
  253. set currentScaleValue(val) {
  254. if (!this.pdfDocument) {
  255. return;
  256. }
  257. this._setScale(val, false);
  258. }
  259. get pagesRotation() {
  260. return this._pagesRotation;
  261. }
  262. set pagesRotation(rotation) {
  263. if (!(0, _ui_utils.isValidRotation)(rotation)) {
  264. throw new Error("Invalid pages rotation angle.");
  265. }
  266. if (!this.pdfDocument) {
  267. return;
  268. }
  269. rotation %= 360;
  270. if (rotation < 0) {
  271. rotation += 360;
  272. }
  273. if (this._pagesRotation === rotation) {
  274. return;
  275. }
  276. this._pagesRotation = rotation;
  277. const pageNumber = this._currentPageNumber;
  278. const updateArgs = {
  279. rotation
  280. };
  281. for (const pageView of this._pages) {
  282. pageView.update(updateArgs);
  283. }
  284. if (this._currentScaleValue) {
  285. this._setScale(this._currentScaleValue, true);
  286. }
  287. this.eventBus.dispatch("rotationchanging", {
  288. source: this,
  289. pagesRotation: rotation,
  290. pageNumber
  291. });
  292. if (this.defaultRenderingQueue) {
  293. this.update();
  294. }
  295. }
  296. get firstPagePromise() {
  297. return this.pdfDocument ? this._firstPageCapability.promise : null;
  298. }
  299. get onePageRendered() {
  300. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  301. }
  302. get pagesPromise() {
  303. return this.pdfDocument ? this._pagesCapability.promise : null;
  304. }
  305. #initializePermissions(permissions) {
  306. if (!permissions) {
  307. return;
  308. }
  309. if (!permissions.includes(_pdf.PermissionFlag.COPY)) {
  310. this.viewer.classList.add(ENABLE_PERMISSIONS_CLASS);
  311. }
  312. if (!permissions.includes(_pdf.PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(_pdf.PermissionFlag.FILL_INTERACTIVE_FORMS)) {
  313. if (this.#annotationMode === _pdf.AnnotationMode.ENABLE_FORMS) {
  314. this.#previousAnnotationMode = this.#annotationMode;
  315. this.#annotationMode = _pdf.AnnotationMode.ENABLE;
  316. }
  317. }
  318. }
  319. #onePageRenderedOrForceFetch() {
  320. if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  321. return Promise.resolve();
  322. }
  323. const visibilityChangePromise = new Promise(resolve => {
  324. this.#onVisibilityChange = () => {
  325. if (document.visibilityState !== "hidden") {
  326. return;
  327. }
  328. resolve();
  329. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  330. this.#onVisibilityChange = null;
  331. };
  332. document.addEventListener("visibilitychange", this.#onVisibilityChange);
  333. });
  334. return Promise.race([this._onePageRenderedCapability.promise, visibilityChangePromise]);
  335. }
  336. setDocument(pdfDocument) {
  337. if (this.pdfDocument) {
  338. this.eventBus.dispatch("pagesdestroy", {
  339. source: this
  340. });
  341. this._cancelRendering();
  342. this._resetView();
  343. if (this.findController) {
  344. this.findController.setDocument(null);
  345. }
  346. if (this._scriptingManager) {
  347. this._scriptingManager.setDocument(null);
  348. }
  349. }
  350. this.pdfDocument = pdfDocument;
  351. if (!pdfDocument) {
  352. return;
  353. }
  354. const isPureXfa = pdfDocument.isPureXfa;
  355. const pagesCount = pdfDocument.numPages;
  356. const firstPagePromise = pdfDocument.getPage(1);
  357. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  358. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  359. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  360. console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");
  361. const mode = this._scrollMode = _ui_utils.ScrollMode.PAGE;
  362. this.eventBus.dispatch("scrollmodechanged", {
  363. source: this,
  364. mode
  365. });
  366. }
  367. this._pagesCapability.promise.then(() => {
  368. this.eventBus.dispatch("pagesloaded", {
  369. source: this,
  370. pagesCount
  371. });
  372. }, () => {});
  373. this._onBeforeDraw = evt => {
  374. const pageView = this._pages[evt.pageNumber - 1];
  375. if (!pageView) {
  376. return;
  377. }
  378. this.#buffer.push(pageView);
  379. };
  380. this.eventBus._on("pagerender", this._onBeforeDraw);
  381. this._onAfterDraw = evt => {
  382. if (evt.cssTransform || this._onePageRenderedCapability.settled) {
  383. return;
  384. }
  385. this._onePageRenderedCapability.resolve({
  386. timestamp: evt.timestamp
  387. });
  388. this.eventBus._off("pagerendered", this._onAfterDraw);
  389. this._onAfterDraw = null;
  390. if (this.#onVisibilityChange) {
  391. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  392. this.#onVisibilityChange = null;
  393. }
  394. };
  395. this.eventBus._on("pagerendered", this._onAfterDraw);
  396. Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => {
  397. if (pdfDocument !== this.pdfDocument) {
  398. return;
  399. }
  400. this._firstPageCapability.resolve(firstPdfPage);
  401. this._optionalContentConfigPromise = optionalContentConfigPromise;
  402. this.#initializePermissions(permissions);
  403. const viewerElement = this._scrollMode === _ui_utils.ScrollMode.PAGE ? null : this.viewer;
  404. const scale = this.currentScale;
  405. const viewport = firstPdfPage.getViewport({
  406. scale: scale * _pdf.PixelsPerInch.PDF_TO_CSS_UNITS
  407. });
  408. const textLayerFactory = this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !isPureXfa ? this : null;
  409. const annotationLayerFactory = this.#annotationMode !== _pdf.AnnotationMode.DISABLE ? this : null;
  410. const xfaLayerFactory = isPureXfa ? this : null;
  411. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  412. const pageView = new _pdf_page_view.PDFPageView({
  413. container: viewerElement,
  414. eventBus: this.eventBus,
  415. id: pageNum,
  416. scale,
  417. defaultViewport: viewport.clone(),
  418. optionalContentConfigPromise,
  419. renderingQueue: this.renderingQueue,
  420. textLayerFactory,
  421. textLayerMode: this.textLayerMode,
  422. annotationLayerFactory,
  423. annotationMode: this.#annotationMode,
  424. xfaLayerFactory,
  425. textHighlighterFactory: this,
  426. structTreeLayerFactory: this,
  427. imageResourcesPath: this.imageResourcesPath,
  428. renderer: this.renderer,
  429. useOnlyCssZoom: this.useOnlyCssZoom,
  430. maxCanvasPixels: this.maxCanvasPixels,
  431. pageColors: this.pageColors,
  432. l10n: this.l10n
  433. });
  434. this._pages.push(pageView);
  435. }
  436. const firstPageView = this._pages[0];
  437. if (firstPageView) {
  438. firstPageView.setPdfPage(firstPdfPage);
  439. this.linkService.cachePageRef(1, firstPdfPage.ref);
  440. }
  441. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  442. this.#ensurePageViewVisible();
  443. } else if (this._spreadMode !== _ui_utils.SpreadMode.NONE) {
  444. this._updateSpreadMode();
  445. }
  446. this.#onePageRenderedOrForceFetch().then(async () => {
  447. if (this.findController) {
  448. this.findController.setDocument(pdfDocument);
  449. }
  450. if (this._scriptingManager) {
  451. this._scriptingManager.setDocument(pdfDocument);
  452. }
  453. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  454. this._pagesCapability.resolve();
  455. return;
  456. }
  457. let getPagesLeft = pagesCount - 1;
  458. if (getPagesLeft <= 0) {
  459. this._pagesCapability.resolve();
  460. return;
  461. }
  462. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  463. const promise = pdfDocument.getPage(pageNum).then(pdfPage => {
  464. const pageView = this._pages[pageNum - 1];
  465. if (!pageView.pdfPage) {
  466. pageView.setPdfPage(pdfPage);
  467. }
  468. this.linkService.cachePageRef(pageNum, pdfPage.ref);
  469. if (--getPagesLeft === 0) {
  470. this._pagesCapability.resolve();
  471. }
  472. }, reason => {
  473. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  474. if (--getPagesLeft === 0) {
  475. this._pagesCapability.resolve();
  476. }
  477. });
  478. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  479. await promise;
  480. }
  481. }
  482. });
  483. this.eventBus.dispatch("pagesinit", {
  484. source: this
  485. });
  486. pdfDocument.getMetadata().then(({
  487. info
  488. }) => {
  489. if (pdfDocument !== this.pdfDocument) {
  490. return;
  491. }
  492. if (info.Language) {
  493. this.viewer.lang = info.Language;
  494. }
  495. });
  496. if (this.defaultRenderingQueue) {
  497. this.update();
  498. }
  499. }).catch(reason => {
  500. console.error("Unable to initialize viewer", reason);
  501. this._pagesCapability.reject(reason);
  502. });
  503. }
  504. setPageLabels(labels) {
  505. if (!this.pdfDocument) {
  506. return;
  507. }
  508. if (!labels) {
  509. this._pageLabels = null;
  510. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  511. this._pageLabels = null;
  512. console.error(`setPageLabels: Invalid page labels.`);
  513. } else {
  514. this._pageLabels = labels;
  515. }
  516. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  517. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  518. }
  519. }
  520. _resetView() {
  521. this._pages = [];
  522. this._currentPageNumber = 1;
  523. this._currentScale = _ui_utils.UNKNOWN_SCALE;
  524. this._currentScaleValue = null;
  525. this._pageLabels = null;
  526. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  527. this._location = null;
  528. this._pagesRotation = 0;
  529. this._optionalContentConfigPromise = null;
  530. this._firstPageCapability = (0, _pdf.createPromiseCapability)();
  531. this._onePageRenderedCapability = (0, _pdf.createPromiseCapability)();
  532. this._pagesCapability = (0, _pdf.createPromiseCapability)();
  533. this._scrollMode = _ui_utils.ScrollMode.VERTICAL;
  534. this._previousScrollMode = _ui_utils.ScrollMode.UNKNOWN;
  535. this._spreadMode = _ui_utils.SpreadMode.NONE;
  536. this.#scrollModePageState = {
  537. previousPageNumber: 1,
  538. scrollDown: true,
  539. pages: []
  540. };
  541. if (this._onBeforeDraw) {
  542. this.eventBus._off("pagerender", this._onBeforeDraw);
  543. this._onBeforeDraw = null;
  544. }
  545. if (this._onAfterDraw) {
  546. this.eventBus._off("pagerendered", this._onAfterDraw);
  547. this._onAfterDraw = null;
  548. }
  549. if (this.#onVisibilityChange) {
  550. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  551. this.#onVisibilityChange = null;
  552. }
  553. this.viewer.textContent = "";
  554. this._updateScrollMode();
  555. this.viewer.removeAttribute("lang");
  556. this.viewer.classList.remove(ENABLE_PERMISSIONS_CLASS);
  557. if (this.#previousAnnotationMode !== null) {
  558. this.#annotationMode = this.#previousAnnotationMode;
  559. this.#previousAnnotationMode = null;
  560. }
  561. }
  562. #ensurePageViewVisible() {
  563. if (this._scrollMode !== _ui_utils.ScrollMode.PAGE) {
  564. throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");
  565. }
  566. const pageNumber = this._currentPageNumber,
  567. state = this.#scrollModePageState,
  568. viewer = this.viewer;
  569. viewer.textContent = "";
  570. state.pages.length = 0;
  571. if (this._spreadMode === _ui_utils.SpreadMode.NONE && !this.isInPresentationMode) {
  572. const pageView = this._pages[pageNumber - 1];
  573. viewer.appendChild(pageView.div);
  574. state.pages.push(pageView);
  575. } else {
  576. const pageIndexSet = new Set(),
  577. parity = this._spreadMode - 1;
  578. if (parity === -1) {
  579. pageIndexSet.add(pageNumber - 1);
  580. } else if (pageNumber % 2 !== parity) {
  581. pageIndexSet.add(pageNumber - 1);
  582. pageIndexSet.add(pageNumber);
  583. } else {
  584. pageIndexSet.add(pageNumber - 2);
  585. pageIndexSet.add(pageNumber - 1);
  586. }
  587. const spread = document.createElement("div");
  588. spread.className = "spread";
  589. if (this.isInPresentationMode) {
  590. const dummyPage = document.createElement("div");
  591. dummyPage.className = "dummyPage";
  592. spread.appendChild(dummyPage);
  593. }
  594. for (const i of pageIndexSet) {
  595. const pageView = this._pages[i];
  596. if (!pageView) {
  597. continue;
  598. }
  599. spread.appendChild(pageView.div);
  600. state.pages.push(pageView);
  601. }
  602. viewer.appendChild(spread);
  603. }
  604. state.scrollDown = pageNumber >= state.previousPageNumber;
  605. state.previousPageNumber = pageNumber;
  606. }
  607. _scrollUpdate() {
  608. if (this.pagesCount === 0) {
  609. return;
  610. }
  611. this.update();
  612. }
  613. #scrollIntoView(pageView, pageSpot = null) {
  614. const {
  615. div,
  616. id
  617. } = pageView;
  618. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  619. this._setCurrentPageNumber(id);
  620. this.#ensurePageViewVisible();
  621. this.update();
  622. }
  623. if (!pageSpot && !this.isInPresentationMode) {
  624. const left = div.offsetLeft + div.clientLeft,
  625. right = left + div.clientWidth;
  626. const {
  627. scrollLeft,
  628. clientWidth
  629. } = this.container;
  630. if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  631. pageSpot = {
  632. left: 0,
  633. top: 0
  634. };
  635. }
  636. }
  637. (0, _ui_utils.scrollIntoView)(div, pageSpot);
  638. }
  639. #isSameScale(newScale) {
  640. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  641. }
  642. _setScaleUpdatePages(newScale, newValue, noScroll = false, preset = false) {
  643. this._currentScaleValue = newValue.toString();
  644. if (this.#isSameScale(newScale)) {
  645. if (preset) {
  646. this.eventBus.dispatch("scalechanging", {
  647. source: this,
  648. scale: newScale,
  649. presetValue: newValue
  650. });
  651. }
  652. return;
  653. }
  654. this._doc.style.setProperty("--zoom-factor", newScale);
  655. const updateArgs = {
  656. scale: newScale
  657. };
  658. for (const pageView of this._pages) {
  659. pageView.update(updateArgs);
  660. }
  661. this._currentScale = newScale;
  662. if (!noScroll) {
  663. let page = this._currentPageNumber,
  664. dest;
  665. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  666. page = this._location.pageNumber;
  667. dest = [null, {
  668. name: "XYZ"
  669. }, this._location.left, this._location.top, null];
  670. }
  671. this.scrollPageIntoView({
  672. pageNumber: page,
  673. destArray: dest,
  674. allowNegativeOffset: true
  675. });
  676. }
  677. this.eventBus.dispatch("scalechanging", {
  678. source: this,
  679. scale: newScale,
  680. presetValue: preset ? newValue : undefined
  681. });
  682. if (this.defaultRenderingQueue) {
  683. this.update();
  684. }
  685. this.updateContainerHeightCss();
  686. }
  687. get _pageWidthScaleFactor() {
  688. if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL) {
  689. return 2;
  690. }
  691. return 1;
  692. }
  693. _setScale(value, noScroll = false) {
  694. let scale = parseFloat(value);
  695. if (scale > 0) {
  696. this._setScaleUpdatePages(scale, value, noScroll, false);
  697. } else {
  698. const currentPage = this._pages[this._currentPageNumber - 1];
  699. if (!currentPage) {
  700. return;
  701. }
  702. let hPadding = _ui_utils.SCROLLBAR_PADDING,
  703. vPadding = _ui_utils.VERTICAL_PADDING;
  704. if (this.isInPresentationMode) {
  705. hPadding = vPadding = 4;
  706. } else if (this.removePageBorders) {
  707. hPadding = vPadding = 0;
  708. } else if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL) {
  709. [hPadding, vPadding] = [vPadding, hPadding];
  710. }
  711. const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor;
  712. const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  713. switch (value) {
  714. case "page-actual":
  715. scale = 1;
  716. break;
  717. case "page-width":
  718. scale = pageWidthScale;
  719. break;
  720. case "page-height":
  721. scale = pageHeightScale;
  722. break;
  723. case "page-fit":
  724. scale = Math.min(pageWidthScale, pageHeightScale);
  725. break;
  726. case "auto":
  727. const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale);
  728. scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale);
  729. break;
  730. default:
  731. console.error(`_setScale: "${value}" is an unknown zoom value.`);
  732. return;
  733. }
  734. this._setScaleUpdatePages(scale, value, noScroll, true);
  735. }
  736. }
  737. #resetCurrentPageView() {
  738. const pageView = this._pages[this._currentPageNumber - 1];
  739. if (this.isInPresentationMode) {
  740. this._setScale(this._currentScaleValue, true);
  741. }
  742. this.#scrollIntoView(pageView);
  743. }
  744. pageLabelToPageNumber(label) {
  745. if (!this._pageLabels) {
  746. return null;
  747. }
  748. const i = this._pageLabels.indexOf(label);
  749. if (i < 0) {
  750. return null;
  751. }
  752. return i + 1;
  753. }
  754. scrollPageIntoView({
  755. pageNumber,
  756. destArray = null,
  757. allowNegativeOffset = false,
  758. ignoreDestinationZoom = false
  759. }) {
  760. if (!this.pdfDocument) {
  761. return;
  762. }
  763. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  764. if (!pageView) {
  765. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  766. return;
  767. }
  768. if (this.isInPresentationMode || !destArray) {
  769. this._setCurrentPageNumber(pageNumber, true);
  770. return;
  771. }
  772. let x = 0,
  773. y = 0;
  774. let width = 0,
  775. height = 0,
  776. widthScale,
  777. heightScale;
  778. const changeOrientation = pageView.rotation % 180 !== 0;
  779. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  780. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  781. let scale = 0;
  782. switch (destArray[1].name) {
  783. case "XYZ":
  784. x = destArray[2];
  785. y = destArray[3];
  786. scale = destArray[4];
  787. x = x !== null ? x : 0;
  788. y = y !== null ? y : pageHeight;
  789. break;
  790. case "Fit":
  791. case "FitB":
  792. scale = "page-fit";
  793. break;
  794. case "FitH":
  795. case "FitBH":
  796. y = destArray[2];
  797. scale = "page-width";
  798. if (y === null && this._location) {
  799. x = this._location.left;
  800. y = this._location.top;
  801. } else if (typeof y !== "number" || y < 0) {
  802. y = pageHeight;
  803. }
  804. break;
  805. case "FitV":
  806. case "FitBV":
  807. x = destArray[2];
  808. width = pageWidth;
  809. height = pageHeight;
  810. scale = "page-height";
  811. break;
  812. case "FitR":
  813. x = destArray[2];
  814. y = destArray[3];
  815. width = destArray[4] - x;
  816. height = destArray[5] - y;
  817. const hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING;
  818. const vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING;
  819. widthScale = (this.container.clientWidth - hPadding) / width / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  820. heightScale = (this.container.clientHeight - vPadding) / height / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  821. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  822. break;
  823. default:
  824. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  825. return;
  826. }
  827. if (!ignoreDestinationZoom) {
  828. if (scale && scale !== this._currentScale) {
  829. this.currentScaleValue = scale;
  830. } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) {
  831. this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  832. }
  833. }
  834. if (scale === "page-fit" && !destArray[4]) {
  835. this.#scrollIntoView(pageView);
  836. return;
  837. }
  838. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  839. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  840. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  841. if (!allowNegativeOffset) {
  842. left = Math.max(left, 0);
  843. top = Math.max(top, 0);
  844. }
  845. this.#scrollIntoView(pageView, {
  846. left,
  847. top
  848. });
  849. }
  850. _updateLocation(firstPage) {
  851. const currentScale = this._currentScale;
  852. const currentScaleValue = this._currentScaleValue;
  853. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  854. const pageNumber = firstPage.id;
  855. const currentPageView = this._pages[pageNumber - 1];
  856. const container = this.container;
  857. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  858. const intLeft = Math.round(topLeft[0]);
  859. const intTop = Math.round(topLeft[1]);
  860. let pdfOpenParams = `#page=${pageNumber}`;
  861. if (!this.isInPresentationMode) {
  862. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  863. }
  864. this._location = {
  865. pageNumber,
  866. scale: normalizedScaleValue,
  867. top: intTop,
  868. left: intLeft,
  869. rotation: this._pagesRotation,
  870. pdfOpenParams
  871. };
  872. }
  873. update() {
  874. const visible = this._getVisiblePages();
  875. const visiblePages = visible.views,
  876. numVisiblePages = visiblePages.length;
  877. if (numVisiblePages === 0) {
  878. return;
  879. }
  880. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  881. this.#buffer.resize(newCacheSize, visible.ids);
  882. this.renderingQueue.renderHighestPriority(visible);
  883. const isSimpleLayout = this._spreadMode === _ui_utils.SpreadMode.NONE && (this._scrollMode === _ui_utils.ScrollMode.PAGE || this._scrollMode === _ui_utils.ScrollMode.VERTICAL);
  884. const currentId = this._currentPageNumber;
  885. let stillFullyVisible = false;
  886. for (const page of visiblePages) {
  887. if (page.percent < 100) {
  888. break;
  889. }
  890. if (page.id === currentId && isSimpleLayout) {
  891. stillFullyVisible = true;
  892. break;
  893. }
  894. }
  895. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  896. this._updateLocation(visible.first);
  897. this.eventBus.dispatch("updateviewarea", {
  898. source: this,
  899. location: this._location
  900. });
  901. }
  902. containsElement(element) {
  903. return this.container.contains(element);
  904. }
  905. focus() {
  906. this.container.focus();
  907. }
  908. get _isContainerRtl() {
  909. return getComputedStyle(this.container).direction === "rtl";
  910. }
  911. get isInPresentationMode() {
  912. return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN;
  913. }
  914. get isChangingPresentationMode() {
  915. return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING;
  916. }
  917. get isHorizontalScrollbarEnabled() {
  918. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  919. }
  920. get isVerticalScrollbarEnabled() {
  921. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  922. }
  923. _getVisiblePages() {
  924. const views = this._scrollMode === _ui_utils.ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  925. horizontal = this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL,
  926. rtl = horizontal && this._isContainerRtl;
  927. return (0, _ui_utils.getVisibleElements)({
  928. scrollEl: this.container,
  929. views,
  930. sortByVisibility: true,
  931. horizontal,
  932. rtl
  933. });
  934. }
  935. isPageVisible(pageNumber) {
  936. if (!this.pdfDocument) {
  937. return false;
  938. }
  939. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  940. console.error(`isPageVisible: "${pageNumber}" is not a valid page.`);
  941. return false;
  942. }
  943. return this._getVisiblePages().ids.has(pageNumber);
  944. }
  945. isPageCached(pageNumber) {
  946. if (!this.pdfDocument) {
  947. return false;
  948. }
  949. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  950. console.error(`isPageCached: "${pageNumber}" is not a valid page.`);
  951. return false;
  952. }
  953. const pageView = this._pages[pageNumber - 1];
  954. return this.#buffer.has(pageView);
  955. }
  956. cleanup() {
  957. for (const pageView of this._pages) {
  958. if (pageView.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  959. pageView.reset();
  960. }
  961. }
  962. }
  963. _cancelRendering() {
  964. for (const pageView of this._pages) {
  965. pageView.cancelRendering();
  966. }
  967. }
  968. async #ensurePdfPageLoaded(pageView) {
  969. if (pageView.pdfPage) {
  970. return pageView.pdfPage;
  971. }
  972. try {
  973. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  974. if (!pageView.pdfPage) {
  975. pageView.setPdfPage(pdfPage);
  976. }
  977. if (!this.linkService._cachedPageNumber?.(pdfPage.ref)) {
  978. this.linkService.cachePageRef(pageView.id, pdfPage.ref);
  979. }
  980. return pdfPage;
  981. } catch (reason) {
  982. console.error("Unable to get page for page view", reason);
  983. return null;
  984. }
  985. }
  986. #getScrollAhead(visible) {
  987. if (visible.first?.id === 1) {
  988. return true;
  989. } else if (visible.last?.id === this.pagesCount) {
  990. return false;
  991. }
  992. switch (this._scrollMode) {
  993. case _ui_utils.ScrollMode.PAGE:
  994. return this.#scrollModePageState.scrollDown;
  995. case _ui_utils.ScrollMode.HORIZONTAL:
  996. return this.scroll.right;
  997. }
  998. return this.scroll.down;
  999. }
  1000. #toggleLoadingIconSpinner(visibleIds) {
  1001. for (const id of visibleIds) {
  1002. const pageView = this._pages[id - 1];
  1003. pageView?.toggleLoadingIconSpinner(true);
  1004. }
  1005. for (const pageView of this.#buffer) {
  1006. if (visibleIds.has(pageView.id)) {
  1007. continue;
  1008. }
  1009. pageView.toggleLoadingIconSpinner(false);
  1010. }
  1011. }
  1012. forceRendering(currentlyVisiblePages) {
  1013. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  1014. const scrollAhead = this.#getScrollAhead(visiblePages);
  1015. const preRenderExtra = this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL;
  1016. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra);
  1017. this.#toggleLoadingIconSpinner(visiblePages.ids);
  1018. if (pageView) {
  1019. this.#ensurePdfPageLoaded(pageView).then(() => {
  1020. this.renderingQueue.renderView(pageView);
  1021. });
  1022. return true;
  1023. }
  1024. return false;
  1025. }
  1026. createTextLayerBuilder(textLayerDiv, pageIndex, viewport, enhanceTextSelection = false, eventBus, highlighter) {
  1027. return new _text_layer_builder.TextLayerBuilder({
  1028. textLayerDiv,
  1029. eventBus,
  1030. pageIndex,
  1031. viewport,
  1032. enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection,
  1033. highlighter
  1034. });
  1035. }
  1036. createTextHighlighter(pageIndex, eventBus) {
  1037. return new _text_highlighter.TextHighlighter({
  1038. eventBus,
  1039. pageIndex,
  1040. findController: this.isInPresentationMode ? null : this.findController
  1041. });
  1042. }
  1043. createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderForms = true, l10n = _l10n_utils.NullL10n, enableScripting = null, hasJSActionsPromise = null, mouseState = null, fieldObjectsPromise = null, annotationCanvasMap = null) {
  1044. return new _annotation_layer_builder.AnnotationLayerBuilder({
  1045. pageDiv,
  1046. pdfPage,
  1047. annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage,
  1048. imageResourcesPath,
  1049. renderForms,
  1050. linkService: this.linkService,
  1051. downloadManager: this.downloadManager,
  1052. l10n,
  1053. enableScripting: enableScripting ?? this.enableScripting,
  1054. hasJSActionsPromise: hasJSActionsPromise || this.pdfDocument?.hasJSActions(),
  1055. fieldObjectsPromise: fieldObjectsPromise || this.pdfDocument?.getFieldObjects(),
  1056. mouseState: mouseState || this._scriptingManager?.mouseState,
  1057. annotationCanvasMap
  1058. });
  1059. }
  1060. createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null) {
  1061. return new _xfa_layer_builder.XfaLayerBuilder({
  1062. pageDiv,
  1063. pdfPage,
  1064. annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage,
  1065. linkService: this.linkService
  1066. });
  1067. }
  1068. createStructTreeLayerBuilder(pdfPage) {
  1069. return new _struct_tree_layer_builder.StructTreeLayerBuilder({
  1070. pdfPage
  1071. });
  1072. }
  1073. get hasEqualPageSizes() {
  1074. const firstPageView = this._pages[0];
  1075. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  1076. const pageView = this._pages[i];
  1077. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  1078. return false;
  1079. }
  1080. }
  1081. return true;
  1082. }
  1083. getPagesOverview() {
  1084. return this._pages.map(pageView => {
  1085. const viewport = pageView.pdfPage.getViewport({
  1086. scale: 1
  1087. });
  1088. if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) {
  1089. return {
  1090. width: viewport.width,
  1091. height: viewport.height,
  1092. rotation: viewport.rotation
  1093. };
  1094. }
  1095. return {
  1096. width: viewport.height,
  1097. height: viewport.width,
  1098. rotation: (viewport.rotation - 90) % 360
  1099. };
  1100. });
  1101. }
  1102. get optionalContentConfigPromise() {
  1103. if (!this.pdfDocument) {
  1104. return Promise.resolve(null);
  1105. }
  1106. if (!this._optionalContentConfigPromise) {
  1107. return this.pdfDocument.getOptionalContentConfig();
  1108. }
  1109. return this._optionalContentConfigPromise;
  1110. }
  1111. set optionalContentConfigPromise(promise) {
  1112. if (!(promise instanceof Promise)) {
  1113. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  1114. }
  1115. if (!this.pdfDocument) {
  1116. return;
  1117. }
  1118. if (!this._optionalContentConfigPromise) {
  1119. return;
  1120. }
  1121. this._optionalContentConfigPromise = promise;
  1122. const updateArgs = {
  1123. optionalContentConfigPromise: promise
  1124. };
  1125. for (const pageView of this._pages) {
  1126. pageView.update(updateArgs);
  1127. }
  1128. this.update();
  1129. this.eventBus.dispatch("optionalcontentconfigchanged", {
  1130. source: this,
  1131. promise
  1132. });
  1133. }
  1134. get scrollMode() {
  1135. return this._scrollMode;
  1136. }
  1137. set scrollMode(mode) {
  1138. if (this._scrollMode === mode) {
  1139. return;
  1140. }
  1141. if (!(0, _ui_utils.isValidScrollMode)(mode)) {
  1142. throw new Error(`Invalid scroll mode: ${mode}`);
  1143. }
  1144. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  1145. return;
  1146. }
  1147. this._previousScrollMode = this._scrollMode;
  1148. this._scrollMode = mode;
  1149. this.eventBus.dispatch("scrollmodechanged", {
  1150. source: this,
  1151. mode
  1152. });
  1153. this._updateScrollMode(this._currentPageNumber);
  1154. }
  1155. _updateScrollMode(pageNumber = null) {
  1156. const scrollMode = this._scrollMode,
  1157. viewer = this.viewer;
  1158. viewer.classList.toggle("scrollHorizontal", scrollMode === _ui_utils.ScrollMode.HORIZONTAL);
  1159. viewer.classList.toggle("scrollWrapped", scrollMode === _ui_utils.ScrollMode.WRAPPED);
  1160. if (!this.pdfDocument || !pageNumber) {
  1161. return;
  1162. }
  1163. if (scrollMode === _ui_utils.ScrollMode.PAGE) {
  1164. this.#ensurePageViewVisible();
  1165. } else if (this._previousScrollMode === _ui_utils.ScrollMode.PAGE) {
  1166. this._updateSpreadMode();
  1167. }
  1168. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  1169. this._setScale(this._currentScaleValue, true);
  1170. }
  1171. this._setCurrentPageNumber(pageNumber, true);
  1172. this.update();
  1173. }
  1174. get spreadMode() {
  1175. return this._spreadMode;
  1176. }
  1177. set spreadMode(mode) {
  1178. if (this._spreadMode === mode) {
  1179. return;
  1180. }
  1181. if (!(0, _ui_utils.isValidSpreadMode)(mode)) {
  1182. throw new Error(`Invalid spread mode: ${mode}`);
  1183. }
  1184. this._spreadMode = mode;
  1185. this.eventBus.dispatch("spreadmodechanged", {
  1186. source: this,
  1187. mode
  1188. });
  1189. this._updateSpreadMode(this._currentPageNumber);
  1190. }
  1191. _updateSpreadMode(pageNumber = null) {
  1192. if (!this.pdfDocument) {
  1193. return;
  1194. }
  1195. const viewer = this.viewer,
  1196. pages = this._pages;
  1197. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  1198. this.#ensurePageViewVisible();
  1199. } else {
  1200. viewer.textContent = "";
  1201. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  1202. for (const pageView of this._pages) {
  1203. viewer.appendChild(pageView.div);
  1204. }
  1205. } else {
  1206. const parity = this._spreadMode - 1;
  1207. let spread = null;
  1208. for (let i = 0, ii = pages.length; i < ii; ++i) {
  1209. if (spread === null) {
  1210. spread = document.createElement("div");
  1211. spread.className = "spread";
  1212. viewer.appendChild(spread);
  1213. } else if (i % 2 === parity) {
  1214. spread = spread.cloneNode(false);
  1215. viewer.appendChild(spread);
  1216. }
  1217. spread.appendChild(pages[i].div);
  1218. }
  1219. }
  1220. }
  1221. if (!pageNumber) {
  1222. return;
  1223. }
  1224. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  1225. this._setScale(this._currentScaleValue, true);
  1226. }
  1227. this._setCurrentPageNumber(pageNumber, true);
  1228. this.update();
  1229. }
  1230. _getPageAdvance(currentPageNumber, previous = false) {
  1231. switch (this._scrollMode) {
  1232. case _ui_utils.ScrollMode.WRAPPED:
  1233. {
  1234. const {
  1235. views
  1236. } = this._getVisiblePages(),
  1237. pageLayout = new Map();
  1238. for (const {
  1239. id,
  1240. y,
  1241. percent,
  1242. widthPercent
  1243. } of views) {
  1244. if (percent === 0 || widthPercent < 100) {
  1245. continue;
  1246. }
  1247. let yArray = pageLayout.get(y);
  1248. if (!yArray) {
  1249. pageLayout.set(y, yArray ||= []);
  1250. }
  1251. yArray.push(id);
  1252. }
  1253. for (const yArray of pageLayout.values()) {
  1254. const currentIndex = yArray.indexOf(currentPageNumber);
  1255. if (currentIndex === -1) {
  1256. continue;
  1257. }
  1258. const numPages = yArray.length;
  1259. if (numPages === 1) {
  1260. break;
  1261. }
  1262. if (previous) {
  1263. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  1264. const currentId = yArray[i],
  1265. expectedId = yArray[i + 1] - 1;
  1266. if (currentId < expectedId) {
  1267. return currentPageNumber - expectedId;
  1268. }
  1269. }
  1270. } else {
  1271. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  1272. const currentId = yArray[i],
  1273. expectedId = yArray[i - 1] + 1;
  1274. if (currentId > expectedId) {
  1275. return expectedId - currentPageNumber;
  1276. }
  1277. }
  1278. }
  1279. if (previous) {
  1280. const firstId = yArray[0];
  1281. if (firstId < currentPageNumber) {
  1282. return currentPageNumber - firstId + 1;
  1283. }
  1284. } else {
  1285. const lastId = yArray[numPages - 1];
  1286. if (lastId > currentPageNumber) {
  1287. return lastId - currentPageNumber + 1;
  1288. }
  1289. }
  1290. break;
  1291. }
  1292. break;
  1293. }
  1294. case _ui_utils.ScrollMode.HORIZONTAL:
  1295. {
  1296. break;
  1297. }
  1298. case _ui_utils.ScrollMode.PAGE:
  1299. case _ui_utils.ScrollMode.VERTICAL:
  1300. {
  1301. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  1302. break;
  1303. }
  1304. const parity = this._spreadMode - 1;
  1305. if (previous && currentPageNumber % 2 !== parity) {
  1306. break;
  1307. } else if (!previous && currentPageNumber % 2 === parity) {
  1308. break;
  1309. }
  1310. const {
  1311. views
  1312. } = this._getVisiblePages(),
  1313. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  1314. for (const {
  1315. id,
  1316. percent,
  1317. widthPercent
  1318. } of views) {
  1319. if (id !== expectedId) {
  1320. continue;
  1321. }
  1322. if (percent > 0 && widthPercent === 100) {
  1323. return 2;
  1324. }
  1325. break;
  1326. }
  1327. break;
  1328. }
  1329. }
  1330. return 1;
  1331. }
  1332. nextPage() {
  1333. const currentPageNumber = this._currentPageNumber,
  1334. pagesCount = this.pagesCount;
  1335. if (currentPageNumber >= pagesCount) {
  1336. return false;
  1337. }
  1338. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  1339. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  1340. return true;
  1341. }
  1342. previousPage() {
  1343. const currentPageNumber = this._currentPageNumber;
  1344. if (currentPageNumber <= 1) {
  1345. return false;
  1346. }
  1347. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  1348. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  1349. return true;
  1350. }
  1351. increaseScale(steps = 1) {
  1352. let newScale = this._currentScale;
  1353. do {
  1354. newScale = (newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  1355. newScale = Math.ceil(newScale * 10) / 10;
  1356. newScale = Math.min(_ui_utils.MAX_SCALE, newScale);
  1357. } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE);
  1358. this.currentScaleValue = newScale;
  1359. }
  1360. decreaseScale(steps = 1) {
  1361. let newScale = this._currentScale;
  1362. do {
  1363. newScale = (newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  1364. newScale = Math.floor(newScale * 10) / 10;
  1365. newScale = Math.max(_ui_utils.MIN_SCALE, newScale);
  1366. } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE);
  1367. this.currentScaleValue = newScale;
  1368. }
  1369. updateContainerHeightCss() {
  1370. const height = this.container.clientHeight;
  1371. if (height !== this.#previousContainerHeight) {
  1372. this.#previousContainerHeight = height;
  1373. this._doc.style.setProperty("--viewer-container-height", `${height}px`);
  1374. }
  1375. }
  1376. }
  1377. exports.BaseViewer = BaseViewer;