pdf_history.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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.PDFHistory = void 0;
  27. exports.isDestArraysEqual = isDestArraysEqual;
  28. exports.isDestHashesEqual = isDestHashesEqual;
  29. var _ui_utils = require("./ui_utils.js");
  30. var _event_utils = require("./event_utils.js");
  31. const HASH_CHANGE_TIMEOUT = 1000;
  32. const POSITION_UPDATED_THRESHOLD = 50;
  33. const UPDATE_VIEWAREA_TIMEOUT = 1000;
  34. function getCurrentHash() {
  35. return document.location.hash;
  36. }
  37. class PDFHistory {
  38. constructor({
  39. linkService,
  40. eventBus
  41. }) {
  42. this.linkService = linkService;
  43. this.eventBus = eventBus;
  44. this._initialized = false;
  45. this._fingerprint = "";
  46. this.reset();
  47. this._boundEvents = null;
  48. this._isViewerInPresentationMode = false;
  49. this.eventBus._on("presentationmodechanged", evt => {
  50. this._isViewerInPresentationMode = evt.state !== _ui_utils.PresentationModeState.NORMAL;
  51. });
  52. this.eventBus._on("pagesinit", () => {
  53. this._isPagesLoaded = false;
  54. this.eventBus._on("pagesloaded", evt => {
  55. this._isPagesLoaded = !!evt.pagesCount;
  56. }, {
  57. once: true
  58. });
  59. });
  60. }
  61. initialize({
  62. fingerprint,
  63. resetHistory = false,
  64. updateUrl = false
  65. }) {
  66. if (!fingerprint || typeof fingerprint !== "string") {
  67. console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');
  68. return;
  69. }
  70. if (this._initialized) {
  71. this.reset();
  72. }
  73. const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint;
  74. this._fingerprint = fingerprint;
  75. this._updateUrl = updateUrl === true;
  76. this._initialized = true;
  77. this._bindEvents();
  78. const state = window.history.state;
  79. this._popStateInProgress = false;
  80. this._blockHashChange = 0;
  81. this._currentHash = getCurrentHash();
  82. this._numPositionUpdates = 0;
  83. this._uid = this._maxUid = 0;
  84. this._destination = null;
  85. this._position = null;
  86. if (!this._isValidState(state, true) || resetHistory) {
  87. const {
  88. hash,
  89. page,
  90. rotation
  91. } = this._parseCurrentHash(true);
  92. if (!hash || reInitialized || resetHistory) {
  93. this._pushOrReplaceState(null, true);
  94. return;
  95. }
  96. this._pushOrReplaceState({
  97. hash,
  98. page,
  99. rotation
  100. }, true);
  101. return;
  102. }
  103. const destination = state.destination;
  104. this._updateInternalState(destination, state.uid, true);
  105. if (destination.rotation !== undefined) {
  106. this._initialRotation = destination.rotation;
  107. }
  108. if (destination.dest) {
  109. this._initialBookmark = JSON.stringify(destination.dest);
  110. this._destination.page = null;
  111. } else if (destination.hash) {
  112. this._initialBookmark = destination.hash;
  113. } else if (destination.page) {
  114. this._initialBookmark = `page=${destination.page}`;
  115. }
  116. }
  117. reset() {
  118. if (this._initialized) {
  119. this._pageHide();
  120. this._initialized = false;
  121. this._unbindEvents();
  122. }
  123. if (this._updateViewareaTimeout) {
  124. clearTimeout(this._updateViewareaTimeout);
  125. this._updateViewareaTimeout = null;
  126. }
  127. this._initialBookmark = null;
  128. this._initialRotation = null;
  129. }
  130. push({
  131. namedDest = null,
  132. explicitDest,
  133. pageNumber
  134. }) {
  135. if (!this._initialized) {
  136. return;
  137. }
  138. if (namedDest && typeof namedDest !== "string") {
  139. console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`);
  140. return;
  141. } else if (!Array.isArray(explicitDest)) {
  142. console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`);
  143. return;
  144. } else if (!this._isValidPage(pageNumber)) {
  145. if (pageNumber !== null || this._destination) {
  146. console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`);
  147. return;
  148. }
  149. }
  150. const hash = namedDest || JSON.stringify(explicitDest);
  151. if (!hash) {
  152. return;
  153. }
  154. let forceReplace = false;
  155. if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) {
  156. if (this._destination.page) {
  157. return;
  158. }
  159. forceReplace = true;
  160. }
  161. if (this._popStateInProgress && !forceReplace) {
  162. return;
  163. }
  164. this._pushOrReplaceState({
  165. dest: explicitDest,
  166. hash,
  167. page: pageNumber,
  168. rotation: this.linkService.rotation
  169. }, forceReplace);
  170. if (!this._popStateInProgress) {
  171. this._popStateInProgress = true;
  172. Promise.resolve().then(() => {
  173. this._popStateInProgress = false;
  174. });
  175. }
  176. }
  177. pushPage(pageNumber) {
  178. if (!this._initialized) {
  179. return;
  180. }
  181. if (!this._isValidPage(pageNumber)) {
  182. console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`);
  183. return;
  184. }
  185. if (this._destination?.page === pageNumber) {
  186. return;
  187. }
  188. if (this._popStateInProgress) {
  189. return;
  190. }
  191. this._pushOrReplaceState({
  192. dest: null,
  193. hash: `page=${pageNumber}`,
  194. page: pageNumber,
  195. rotation: this.linkService.rotation
  196. });
  197. if (!this._popStateInProgress) {
  198. this._popStateInProgress = true;
  199. Promise.resolve().then(() => {
  200. this._popStateInProgress = false;
  201. });
  202. }
  203. }
  204. pushCurrentPosition() {
  205. if (!this._initialized || this._popStateInProgress) {
  206. return;
  207. }
  208. this._tryPushCurrentPosition();
  209. }
  210. back() {
  211. if (!this._initialized || this._popStateInProgress) {
  212. return;
  213. }
  214. const state = window.history.state;
  215. if (this._isValidState(state) && state.uid > 0) {
  216. window.history.back();
  217. }
  218. }
  219. forward() {
  220. if (!this._initialized || this._popStateInProgress) {
  221. return;
  222. }
  223. const state = window.history.state;
  224. if (this._isValidState(state) && state.uid < this._maxUid) {
  225. window.history.forward();
  226. }
  227. }
  228. get popStateInProgress() {
  229. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  230. }
  231. get initialBookmark() {
  232. return this._initialized ? this._initialBookmark : null;
  233. }
  234. get initialRotation() {
  235. return this._initialized ? this._initialRotation : null;
  236. }
  237. _pushOrReplaceState(destination, forceReplace = false) {
  238. const shouldReplace = forceReplace || !this._destination;
  239. const newState = {
  240. fingerprint: this._fingerprint,
  241. uid: shouldReplace ? this._uid : this._uid + 1,
  242. destination
  243. };
  244. this._updateInternalState(destination, newState.uid);
  245. let newUrl;
  246. if (this._updateUrl && destination?.hash) {
  247. const baseUrl = document.location.href.split("#")[0];
  248. if (!baseUrl.startsWith("file://")) {
  249. newUrl = `${baseUrl}#${destination.hash}`;
  250. }
  251. }
  252. if (shouldReplace) {
  253. window.history.replaceState(newState, "", newUrl);
  254. } else {
  255. window.history.pushState(newState, "", newUrl);
  256. }
  257. }
  258. _tryPushCurrentPosition(temporary = false) {
  259. if (!this._position) {
  260. return;
  261. }
  262. let position = this._position;
  263. if (temporary) {
  264. position = Object.assign(Object.create(null), this._position);
  265. position.temporary = true;
  266. }
  267. if (!this._destination) {
  268. this._pushOrReplaceState(position);
  269. return;
  270. }
  271. if (this._destination.temporary) {
  272. this._pushOrReplaceState(position, true);
  273. return;
  274. }
  275. if (this._destination.hash === position.hash) {
  276. return;
  277. }
  278. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  279. return;
  280. }
  281. let forceReplace = false;
  282. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  283. if (this._destination.dest !== undefined || !this._destination.first) {
  284. return;
  285. }
  286. forceReplace = true;
  287. }
  288. this._pushOrReplaceState(position, forceReplace);
  289. }
  290. _isValidPage(val) {
  291. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  292. }
  293. _isValidState(state, checkReload = false) {
  294. if (!state) {
  295. return false;
  296. }
  297. if (state.fingerprint !== this._fingerprint) {
  298. if (checkReload) {
  299. if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) {
  300. return false;
  301. }
  302. const [perfEntry] = performance.getEntriesByType("navigation");
  303. if (perfEntry?.type !== "reload") {
  304. return false;
  305. }
  306. } else {
  307. return false;
  308. }
  309. }
  310. if (!Number.isInteger(state.uid) || state.uid < 0) {
  311. return false;
  312. }
  313. if (state.destination === null || typeof state.destination !== "object") {
  314. return false;
  315. }
  316. return true;
  317. }
  318. _updateInternalState(destination, uid, removeTemporary = false) {
  319. if (this._updateViewareaTimeout) {
  320. clearTimeout(this._updateViewareaTimeout);
  321. this._updateViewareaTimeout = null;
  322. }
  323. if (removeTemporary && destination?.temporary) {
  324. delete destination.temporary;
  325. }
  326. this._destination = destination;
  327. this._uid = uid;
  328. this._maxUid = Math.max(this._maxUid, uid);
  329. this._numPositionUpdates = 0;
  330. }
  331. _parseCurrentHash(checkNameddest = false) {
  332. const hash = unescape(getCurrentHash()).substring(1);
  333. const params = (0, _ui_utils.parseQueryString)(hash);
  334. const nameddest = params.get("nameddest") || "";
  335. let page = params.get("page") | 0;
  336. if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) {
  337. page = null;
  338. }
  339. return {
  340. hash,
  341. page,
  342. rotation: this.linkService.rotation
  343. };
  344. }
  345. _updateViewarea({
  346. location
  347. }) {
  348. if (this._updateViewareaTimeout) {
  349. clearTimeout(this._updateViewareaTimeout);
  350. this._updateViewareaTimeout = null;
  351. }
  352. this._position = {
  353. hash: this._isViewerInPresentationMode ? `page=${location.pageNumber}` : location.pdfOpenParams.substring(1),
  354. page: this.linkService.page,
  355. first: location.pageNumber,
  356. rotation: location.rotation
  357. };
  358. if (this._popStateInProgress) {
  359. return;
  360. }
  361. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  362. this._numPositionUpdates++;
  363. }
  364. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  365. this._updateViewareaTimeout = setTimeout(() => {
  366. if (!this._popStateInProgress) {
  367. this._tryPushCurrentPosition(true);
  368. }
  369. this._updateViewareaTimeout = null;
  370. }, UPDATE_VIEWAREA_TIMEOUT);
  371. }
  372. }
  373. _popState({
  374. state
  375. }) {
  376. const newHash = getCurrentHash(),
  377. hashChanged = this._currentHash !== newHash;
  378. this._currentHash = newHash;
  379. if (!state) {
  380. this._uid++;
  381. const {
  382. hash,
  383. page,
  384. rotation
  385. } = this._parseCurrentHash();
  386. this._pushOrReplaceState({
  387. hash,
  388. page,
  389. rotation
  390. }, true);
  391. return;
  392. }
  393. if (!this._isValidState(state)) {
  394. return;
  395. }
  396. this._popStateInProgress = true;
  397. if (hashChanged) {
  398. this._blockHashChange++;
  399. (0, _event_utils.waitOnEventOrTimeout)({
  400. target: window,
  401. name: "hashchange",
  402. delay: HASH_CHANGE_TIMEOUT
  403. }).then(() => {
  404. this._blockHashChange--;
  405. });
  406. }
  407. const destination = state.destination;
  408. this._updateInternalState(destination, state.uid, true);
  409. if ((0, _ui_utils.isValidRotation)(destination.rotation)) {
  410. this.linkService.rotation = destination.rotation;
  411. }
  412. if (destination.dest) {
  413. this.linkService.goToDestination(destination.dest);
  414. } else if (destination.hash) {
  415. this.linkService.setHash(destination.hash);
  416. } else if (destination.page) {
  417. this.linkService.page = destination.page;
  418. }
  419. Promise.resolve().then(() => {
  420. this._popStateInProgress = false;
  421. });
  422. }
  423. _pageHide() {
  424. if (!this._destination || this._destination.temporary) {
  425. this._tryPushCurrentPosition();
  426. }
  427. }
  428. _bindEvents() {
  429. if (this._boundEvents) {
  430. return;
  431. }
  432. this._boundEvents = {
  433. updateViewarea: this._updateViewarea.bind(this),
  434. popState: this._popState.bind(this),
  435. pageHide: this._pageHide.bind(this)
  436. };
  437. this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea);
  438. window.addEventListener("popstate", this._boundEvents.popState);
  439. window.addEventListener("pagehide", this._boundEvents.pageHide);
  440. }
  441. _unbindEvents() {
  442. if (!this._boundEvents) {
  443. return;
  444. }
  445. this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea);
  446. window.removeEventListener("popstate", this._boundEvents.popState);
  447. window.removeEventListener("pagehide", this._boundEvents.pageHide);
  448. this._boundEvents = null;
  449. }
  450. }
  451. exports.PDFHistory = PDFHistory;
  452. function isDestHashesEqual(destHash, pushHash) {
  453. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  454. return false;
  455. }
  456. if (destHash === pushHash) {
  457. return true;
  458. }
  459. const nameddest = (0, _ui_utils.parseQueryString)(destHash).get("nameddest");
  460. if (nameddest === pushHash) {
  461. return true;
  462. }
  463. return false;
  464. }
  465. function isDestArraysEqual(firstDest, secondDest) {
  466. function isEntryEqual(first, second) {
  467. if (typeof first !== typeof second) {
  468. return false;
  469. }
  470. if (Array.isArray(first) || Array.isArray(second)) {
  471. return false;
  472. }
  473. if (first !== null && typeof first === "object" && second !== null) {
  474. if (Object.keys(first).length !== Object.keys(second).length) {
  475. return false;
  476. }
  477. for (const key in first) {
  478. if (!isEntryEqual(first[key], second[key])) {
  479. return false;
  480. }
  481. }
  482. return true;
  483. }
  484. return first === second || Number.isNaN(first) && Number.isNaN(second);
  485. }
  486. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  487. return false;
  488. }
  489. if (firstDest.length !== secondDest.length) {
  490. return false;
  491. }
  492. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  493. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  494. return false;
  495. }
  496. }
  497. return true;
  498. }