pdf_history.js 14 KB

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