2
0

pdf_link_service.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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.SimpleLinkService = exports.PDFLinkService = exports.LinkTarget = void 0;
  27. var _ui_utils = require("./ui_utils.js");
  28. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  29. const LinkTarget = {
  30. NONE: 0,
  31. SELF: 1,
  32. BLANK: 2,
  33. PARENT: 3,
  34. TOP: 4
  35. };
  36. exports.LinkTarget = LinkTarget;
  37. function addLinkAttributes(link, {
  38. url,
  39. target,
  40. rel,
  41. enabled = true
  42. } = {}) {
  43. if (!url || typeof url !== "string") {
  44. throw new Error('A valid "url" parameter must provided.');
  45. }
  46. const urlNullRemoved = (0, _ui_utils.removeNullCharacters)(url);
  47. if (enabled) {
  48. link.href = link.title = urlNullRemoved;
  49. } else {
  50. link.href = "";
  51. link.title = `Disabled: ${urlNullRemoved}`;
  52. link.onclick = () => {
  53. return false;
  54. };
  55. }
  56. let targetStr = "";
  57. switch (target) {
  58. case LinkTarget.NONE:
  59. break;
  60. case LinkTarget.SELF:
  61. targetStr = "_self";
  62. break;
  63. case LinkTarget.BLANK:
  64. targetStr = "_blank";
  65. break;
  66. case LinkTarget.PARENT:
  67. targetStr = "_parent";
  68. break;
  69. case LinkTarget.TOP:
  70. targetStr = "_top";
  71. break;
  72. }
  73. link.target = targetStr;
  74. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  75. }
  76. class PDFLinkService {
  77. #pagesRefCache = new Map();
  78. constructor({
  79. eventBus,
  80. externalLinkTarget = null,
  81. externalLinkRel = null,
  82. ignoreDestinationZoom = false
  83. } = {}) {
  84. this.eventBus = eventBus;
  85. this.externalLinkTarget = externalLinkTarget;
  86. this.externalLinkRel = externalLinkRel;
  87. this.externalLinkEnabled = true;
  88. this._ignoreDestinationZoom = ignoreDestinationZoom;
  89. this.baseUrl = null;
  90. this.pdfDocument = null;
  91. this.pdfViewer = null;
  92. this.pdfHistory = null;
  93. }
  94. setDocument(pdfDocument, baseUrl = null) {
  95. this.baseUrl = baseUrl;
  96. this.pdfDocument = pdfDocument;
  97. this.#pagesRefCache.clear();
  98. }
  99. setViewer(pdfViewer) {
  100. this.pdfViewer = pdfViewer;
  101. }
  102. setHistory(pdfHistory) {
  103. this.pdfHistory = pdfHistory;
  104. }
  105. get pagesCount() {
  106. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  107. }
  108. get page() {
  109. return this.pdfViewer.currentPageNumber;
  110. }
  111. set page(value) {
  112. this.pdfViewer.currentPageNumber = value;
  113. }
  114. get rotation() {
  115. return this.pdfViewer.pagesRotation;
  116. }
  117. set rotation(value) {
  118. this.pdfViewer.pagesRotation = value;
  119. }
  120. get isInPresentationMode() {
  121. return this.pdfViewer.isInPresentationMode;
  122. }
  123. #goToDestinationHelper(rawDest, namedDest = null, explicitDest) {
  124. const destRef = explicitDest[0];
  125. let pageNumber;
  126. if (typeof destRef === "object" && destRef !== null) {
  127. pageNumber = this._cachedPageNumber(destRef);
  128. if (!pageNumber) {
  129. this.pdfDocument.getPageIndex(destRef).then(pageIndex => {
  130. this.cachePageRef(pageIndex + 1, destRef);
  131. this.#goToDestinationHelper(rawDest, namedDest, explicitDest);
  132. }).catch(() => {
  133. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid page reference, for dest="${rawDest}".`);
  134. });
  135. return;
  136. }
  137. } else if (Number.isInteger(destRef)) {
  138. pageNumber = destRef + 1;
  139. } else {
  140. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid destination reference, for dest="${rawDest}".`);
  141. return;
  142. }
  143. if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
  144. console.error(`PDFLinkService.#goToDestinationHelper: "${pageNumber}" is not ` + `a valid page number, for dest="${rawDest}".`);
  145. return;
  146. }
  147. if (this.pdfHistory) {
  148. this.pdfHistory.pushCurrentPosition();
  149. this.pdfHistory.push({
  150. namedDest,
  151. explicitDest,
  152. pageNumber
  153. });
  154. }
  155. this.pdfViewer.scrollPageIntoView({
  156. pageNumber,
  157. destArray: explicitDest,
  158. ignoreDestinationZoom: this._ignoreDestinationZoom
  159. });
  160. }
  161. async goToDestination(dest) {
  162. if (!this.pdfDocument) {
  163. return;
  164. }
  165. let namedDest, explicitDest;
  166. if (typeof dest === "string") {
  167. namedDest = dest;
  168. explicitDest = await this.pdfDocument.getDestination(dest);
  169. } else {
  170. namedDest = null;
  171. explicitDest = await dest;
  172. }
  173. if (!Array.isArray(explicitDest)) {
  174. console.error(`PDFLinkService.goToDestination: "${explicitDest}" is not ` + `a valid destination array, for dest="${dest}".`);
  175. return;
  176. }
  177. this.#goToDestinationHelper(dest, namedDest, explicitDest);
  178. }
  179. goToPage(val) {
  180. if (!this.pdfDocument) {
  181. return;
  182. }
  183. const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0;
  184. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  185. console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
  186. return;
  187. }
  188. if (this.pdfHistory) {
  189. this.pdfHistory.pushCurrentPosition();
  190. this.pdfHistory.pushPage(pageNumber);
  191. }
  192. this.pdfViewer.scrollPageIntoView({
  193. pageNumber
  194. });
  195. }
  196. addLinkAttributes(link, url, newWindow = false) {
  197. addLinkAttributes(link, {
  198. url,
  199. target: newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
  200. rel: this.externalLinkRel,
  201. enabled: this.externalLinkEnabled
  202. });
  203. }
  204. getDestinationHash(dest) {
  205. if (typeof dest === "string") {
  206. if (dest.length > 0) {
  207. return this.getAnchorUrl("#" + escape(dest));
  208. }
  209. } else if (Array.isArray(dest)) {
  210. const str = JSON.stringify(dest);
  211. if (str.length > 0) {
  212. return this.getAnchorUrl("#" + escape(str));
  213. }
  214. }
  215. return this.getAnchorUrl("");
  216. }
  217. getAnchorUrl(anchor) {
  218. return (this.baseUrl || "") + anchor;
  219. }
  220. setHash(hash) {
  221. if (!this.pdfDocument) {
  222. return;
  223. }
  224. let pageNumber, dest;
  225. if (hash.includes("=")) {
  226. const params = (0, _ui_utils.parseQueryString)(hash);
  227. if (params.has("search")) {
  228. this.eventBus.dispatch("findfromurlhash", {
  229. source: this,
  230. query: params.get("search").replace(/"/g, ""),
  231. phraseSearch: params.get("phrase") === "true"
  232. });
  233. }
  234. if (params.has("page")) {
  235. pageNumber = params.get("page") | 0 || 1;
  236. }
  237. if (params.has("zoom")) {
  238. const zoomArgs = params.get("zoom").split(",");
  239. const zoomArg = zoomArgs[0];
  240. const zoomArgNumber = parseFloat(zoomArg);
  241. if (!zoomArg.includes("Fit")) {
  242. dest = [null, {
  243. name: "XYZ"
  244. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg];
  245. } else {
  246. if (zoomArg === "Fit" || zoomArg === "FitB") {
  247. dest = [null, {
  248. name: zoomArg
  249. }];
  250. } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") {
  251. dest = [null, {
  252. name: zoomArg
  253. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null];
  254. } else if (zoomArg === "FitR") {
  255. if (zoomArgs.length !== 5) {
  256. console.error('PDFLinkService.setHash: Not enough parameters for "FitR".');
  257. } else {
  258. dest = [null, {
  259. name: zoomArg
  260. }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0];
  261. }
  262. } else {
  263. console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`);
  264. }
  265. }
  266. }
  267. if (dest) {
  268. this.pdfViewer.scrollPageIntoView({
  269. pageNumber: pageNumber || this.page,
  270. destArray: dest,
  271. allowNegativeOffset: true
  272. });
  273. } else if (pageNumber) {
  274. this.page = pageNumber;
  275. }
  276. if (params.has("pagemode")) {
  277. this.eventBus.dispatch("pagemode", {
  278. source: this,
  279. mode: params.get("pagemode")
  280. });
  281. }
  282. if (params.has("nameddest")) {
  283. this.goToDestination(params.get("nameddest"));
  284. }
  285. } else {
  286. dest = unescape(hash);
  287. try {
  288. dest = JSON.parse(dest);
  289. if (!Array.isArray(dest)) {
  290. dest = dest.toString();
  291. }
  292. } catch (ex) {}
  293. if (typeof dest === "string" || PDFLinkService.#isValidExplicitDestination(dest)) {
  294. this.goToDestination(dest);
  295. return;
  296. }
  297. console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`);
  298. }
  299. }
  300. executeNamedAction(action) {
  301. switch (action) {
  302. case "GoBack":
  303. this.pdfHistory?.back();
  304. break;
  305. case "GoForward":
  306. this.pdfHistory?.forward();
  307. break;
  308. case "NextPage":
  309. this.pdfViewer.nextPage();
  310. break;
  311. case "PrevPage":
  312. this.pdfViewer.previousPage();
  313. break;
  314. case "LastPage":
  315. this.page = this.pagesCount;
  316. break;
  317. case "FirstPage":
  318. this.page = 1;
  319. break;
  320. default:
  321. break;
  322. }
  323. this.eventBus.dispatch("namedaction", {
  324. source: this,
  325. action
  326. });
  327. }
  328. async executeSetOCGState(action) {
  329. const pdfDocument = this.pdfDocument;
  330. const optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
  331. if (pdfDocument !== this.pdfDocument) {
  332. return;
  333. }
  334. let operator;
  335. for (const elem of action.state) {
  336. switch (elem) {
  337. case "ON":
  338. case "OFF":
  339. case "Toggle":
  340. operator = elem;
  341. continue;
  342. }
  343. switch (operator) {
  344. case "ON":
  345. optionalContentConfig.setVisibility(elem, true);
  346. break;
  347. case "OFF":
  348. optionalContentConfig.setVisibility(elem, false);
  349. break;
  350. case "Toggle":
  351. const group = optionalContentConfig.getGroup(elem);
  352. if (group) {
  353. optionalContentConfig.setVisibility(elem, !group.visible);
  354. }
  355. break;
  356. }
  357. }
  358. this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig);
  359. }
  360. cachePageRef(pageNum, pageRef) {
  361. if (!pageRef) {
  362. return;
  363. }
  364. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  365. this.#pagesRefCache.set(refStr, pageNum);
  366. }
  367. _cachedPageNumber(pageRef) {
  368. if (!pageRef) {
  369. return null;
  370. }
  371. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  372. return this.#pagesRefCache.get(refStr) || null;
  373. }
  374. isPageVisible(pageNumber) {
  375. return this.pdfViewer.isPageVisible(pageNumber);
  376. }
  377. isPageCached(pageNumber) {
  378. return this.pdfViewer.isPageCached(pageNumber);
  379. }
  380. static #isValidExplicitDestination(dest) {
  381. if (!Array.isArray(dest)) {
  382. return false;
  383. }
  384. const destLength = dest.length;
  385. if (destLength < 2) {
  386. return false;
  387. }
  388. const page = dest[0];
  389. if (!(typeof page === "object" && Number.isInteger(page.num) && Number.isInteger(page.gen)) && !(Number.isInteger(page) && page >= 0)) {
  390. return false;
  391. }
  392. const zoom = dest[1];
  393. if (!(typeof zoom === "object" && typeof zoom.name === "string")) {
  394. return false;
  395. }
  396. let allowNull = true;
  397. switch (zoom.name) {
  398. case "XYZ":
  399. if (destLength !== 5) {
  400. return false;
  401. }
  402. break;
  403. case "Fit":
  404. case "FitB":
  405. return destLength === 2;
  406. case "FitH":
  407. case "FitBH":
  408. case "FitV":
  409. case "FitBV":
  410. if (destLength !== 3) {
  411. return false;
  412. }
  413. break;
  414. case "FitR":
  415. if (destLength !== 6) {
  416. return false;
  417. }
  418. allowNull = false;
  419. break;
  420. default:
  421. return false;
  422. }
  423. for (let i = 2; i < destLength; i++) {
  424. const param = dest[i];
  425. if (!(typeof param === "number" || allowNull && param === null)) {
  426. return false;
  427. }
  428. }
  429. return true;
  430. }
  431. }
  432. exports.PDFLinkService = PDFLinkService;
  433. class SimpleLinkService {
  434. constructor() {
  435. this.externalLinkEnabled = true;
  436. }
  437. get pagesCount() {
  438. return 0;
  439. }
  440. get page() {
  441. return 0;
  442. }
  443. set page(value) {}
  444. get rotation() {
  445. return 0;
  446. }
  447. set rotation(value) {}
  448. get isInPresentationMode() {
  449. return false;
  450. }
  451. async goToDestination(dest) {}
  452. goToPage(val) {}
  453. addLinkAttributes(link, url, newWindow = false) {
  454. addLinkAttributes(link, {
  455. url,
  456. enabled: this.externalLinkEnabled
  457. });
  458. }
  459. getDestinationHash(dest) {
  460. return "#";
  461. }
  462. getAnchorUrl(hash) {
  463. return "#";
  464. }
  465. setHash(hash) {}
  466. executeNamedAction(action) {}
  467. executeSetOCGState(action) {}
  468. cachePageRef(pageNum, pageRef) {}
  469. isPageVisible(pageNumber) {
  470. return true;
  471. }
  472. isPageCached(pageNumber) {
  473. return true;
  474. }
  475. }
  476. exports.SimpleLinkService = SimpleLinkService;