2
0

pdf_history.js 14 KB

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