pdf_history.js 15 KB

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