2
0

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 2021 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 (!this._isValidPage(pageNumber)) {
  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 (!this._isValidPage(pageNumber)) {
  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. dest: null,
  192. hash: `page=${pageNumber}`,
  193. page: pageNumber,
  194. rotation: this.linkService.rotation
  195. });
  196. if (!this._popStateInProgress) {
  197. this._popStateInProgress = true;
  198. Promise.resolve().then(() => {
  199. this._popStateInProgress = false;
  200. });
  201. }
  202. }
  203. pushCurrentPosition() {
  204. if (!this._initialized || this._popStateInProgress) {
  205. return;
  206. }
  207. this._tryPushCurrentPosition();
  208. }
  209. back() {
  210. if (!this._initialized || this._popStateInProgress) {
  211. return;
  212. }
  213. const state = window.history.state;
  214. if (this._isValidState(state) && state.uid > 0) {
  215. window.history.back();
  216. }
  217. }
  218. forward() {
  219. if (!this._initialized || this._popStateInProgress) {
  220. return;
  221. }
  222. const state = window.history.state;
  223. if (this._isValidState(state) && state.uid < this._maxUid) {
  224. window.history.forward();
  225. }
  226. }
  227. get popStateInProgress() {
  228. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  229. }
  230. get initialBookmark() {
  231. return this._initialized ? this._initialBookmark : null;
  232. }
  233. get initialRotation() {
  234. return this._initialized ? this._initialRotation : null;
  235. }
  236. _pushOrReplaceState(destination, forceReplace = false) {
  237. const shouldReplace = forceReplace || !this._destination;
  238. const newState = {
  239. fingerprint: this._fingerprint,
  240. uid: shouldReplace ? this._uid : this._uid + 1,
  241. destination
  242. };
  243. this._updateInternalState(destination, newState.uid);
  244. let newUrl;
  245. if (this._updateUrl && destination?.hash) {
  246. const baseUrl = document.location.href.split("#")[0];
  247. if (!baseUrl.startsWith("file://")) {
  248. newUrl = `${baseUrl}#${destination.hash}`;
  249. }
  250. }
  251. if (shouldReplace) {
  252. window.history.replaceState(newState, "", newUrl);
  253. } else {
  254. window.history.pushState(newState, "", newUrl);
  255. }
  256. }
  257. _tryPushCurrentPosition(temporary = false) {
  258. if (!this._position) {
  259. return;
  260. }
  261. let position = this._position;
  262. if (temporary) {
  263. position = Object.assign(Object.create(null), this._position);
  264. position.temporary = true;
  265. }
  266. if (!this._destination) {
  267. this._pushOrReplaceState(position);
  268. return;
  269. }
  270. if (this._destination.temporary) {
  271. this._pushOrReplaceState(position, true);
  272. return;
  273. }
  274. if (this._destination.hash === position.hash) {
  275. return;
  276. }
  277. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  278. return;
  279. }
  280. let forceReplace = false;
  281. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  282. if (this._destination.dest !== undefined || !this._destination.first) {
  283. return;
  284. }
  285. forceReplace = true;
  286. }
  287. this._pushOrReplaceState(position, forceReplace);
  288. }
  289. _isValidPage(val) {
  290. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  291. }
  292. _isValidState(state, checkReload = false) {
  293. if (!state) {
  294. return false;
  295. }
  296. if (state.fingerprint !== this._fingerprint) {
  297. if (checkReload) {
  298. if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) {
  299. return false;
  300. }
  301. const [perfEntry] = performance.getEntriesByType("navigation");
  302. if (perfEntry?.type !== "reload") {
  303. return false;
  304. }
  305. } else {
  306. return false;
  307. }
  308. }
  309. if (!Number.isInteger(state.uid) || state.uid < 0) {
  310. return false;
  311. }
  312. if (state.destination === null || typeof state.destination !== "object") {
  313. return false;
  314. }
  315. return true;
  316. }
  317. _updateInternalState(destination, uid, removeTemporary = false) {
  318. if (this._updateViewareaTimeout) {
  319. clearTimeout(this._updateViewareaTimeout);
  320. this._updateViewareaTimeout = null;
  321. }
  322. if (removeTemporary && destination?.temporary) {
  323. delete destination.temporary;
  324. }
  325. this._destination = destination;
  326. this._uid = uid;
  327. this._maxUid = Math.max(this._maxUid, uid);
  328. this._numPositionUpdates = 0;
  329. }
  330. _parseCurrentHash(checkNameddest = false) {
  331. const hash = unescape(getCurrentHash()).substring(1);
  332. const params = (0, _ui_utils.parseQueryString)(hash);
  333. const nameddest = params.nameddest || "";
  334. let page = params.page | 0;
  335. if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) {
  336. page = null;
  337. }
  338. return {
  339. hash,
  340. page,
  341. rotation: this.linkService.rotation
  342. };
  343. }
  344. _updateViewarea({
  345. location
  346. }) {
  347. if (this._updateViewareaTimeout) {
  348. clearTimeout(this._updateViewareaTimeout);
  349. this._updateViewareaTimeout = null;
  350. }
  351. this._position = {
  352. hash: this._isViewerInPresentationMode ? `page=${location.pageNumber}` : location.pdfOpenParams.substring(1),
  353. page: this.linkService.page,
  354. first: location.pageNumber,
  355. rotation: location.rotation
  356. };
  357. if (this._popStateInProgress) {
  358. return;
  359. }
  360. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  361. this._numPositionUpdates++;
  362. }
  363. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  364. this._updateViewareaTimeout = setTimeout(() => {
  365. if (!this._popStateInProgress) {
  366. this._tryPushCurrentPosition(true);
  367. }
  368. this._updateViewareaTimeout = null;
  369. }, UPDATE_VIEWAREA_TIMEOUT);
  370. }
  371. }
  372. _popState({
  373. state
  374. }) {
  375. const newHash = getCurrentHash(),
  376. hashChanged = this._currentHash !== newHash;
  377. this._currentHash = newHash;
  378. if (!state) {
  379. this._uid++;
  380. const {
  381. hash,
  382. page,
  383. rotation
  384. } = this._parseCurrentHash();
  385. this._pushOrReplaceState({
  386. hash,
  387. page,
  388. rotation
  389. }, true);
  390. return;
  391. }
  392. if (!this._isValidState(state)) {
  393. return;
  394. }
  395. this._popStateInProgress = true;
  396. if (hashChanged) {
  397. this._blockHashChange++;
  398. (0, _ui_utils.waitOnEventOrTimeout)({
  399. target: window,
  400. name: "hashchange",
  401. delay: HASH_CHANGE_TIMEOUT
  402. }).then(() => {
  403. this._blockHashChange--;
  404. });
  405. }
  406. const destination = state.destination;
  407. this._updateInternalState(destination, state.uid, true);
  408. if ((0, _ui_utils.isValidRotation)(destination.rotation)) {
  409. this.linkService.rotation = destination.rotation;
  410. }
  411. if (destination.dest) {
  412. this.linkService.goToDestination(destination.dest);
  413. } else if (destination.hash) {
  414. this.linkService.setHash(destination.hash);
  415. } else if (destination.page) {
  416. this.linkService.page = destination.page;
  417. }
  418. Promise.resolve().then(() => {
  419. this._popStateInProgress = false;
  420. });
  421. }
  422. _pageHide() {
  423. if (!this._destination || this._destination.temporary) {
  424. this._tryPushCurrentPosition();
  425. }
  426. }
  427. _bindEvents() {
  428. if (this._boundEvents) {
  429. return;
  430. }
  431. this._boundEvents = {
  432. updateViewarea: this._updateViewarea.bind(this),
  433. popState: this._popState.bind(this),
  434. pageHide: this._pageHide.bind(this)
  435. };
  436. this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea);
  437. window.addEventListener("popstate", this._boundEvents.popState);
  438. window.addEventListener("pagehide", this._boundEvents.pageHide);
  439. }
  440. _unbindEvents() {
  441. if (!this._boundEvents) {
  442. return;
  443. }
  444. this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea);
  445. window.removeEventListener("popstate", this._boundEvents.popState);
  446. window.removeEventListener("pagehide", this._boundEvents.pageHide);
  447. this._boundEvents = null;
  448. }
  449. }
  450. exports.PDFHistory = PDFHistory;
  451. function isDestHashesEqual(destHash, pushHash) {
  452. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  453. return false;
  454. }
  455. if (destHash === pushHash) {
  456. return true;
  457. }
  458. const {
  459. nameddest
  460. } = (0, _ui_utils.parseQueryString)(destHash);
  461. if (nameddest === pushHash) {
  462. return true;
  463. }
  464. return false;
  465. }
  466. function isDestArraysEqual(firstDest, secondDest) {
  467. function isEntryEqual(first, second) {
  468. if (typeof first !== typeof second) {
  469. return false;
  470. }
  471. if (Array.isArray(first) || Array.isArray(second)) {
  472. return false;
  473. }
  474. if (first !== null && typeof first === "object" && second !== null) {
  475. if (Object.keys(first).length !== Object.keys(second).length) {
  476. return false;
  477. }
  478. for (const key in first) {
  479. if (!isEntryEqual(first[key], second[key])) {
  480. return false;
  481. }
  482. }
  483. return true;
  484. }
  485. return first === second || Number.isNaN(first) && Number.isNaN(second);
  486. }
  487. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  488. return false;
  489. }
  490. if (firstDest.length !== secondDest.length) {
  491. return false;
  492. }
  493. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  494. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  495. return false;
  496. }
  497. }
  498. return true;
  499. }