forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdf_link_service.js
552 lines (500 loc) · 14.8 KB
/
pdf_link_service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/* Copyright 2015 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @typedef {import("./event_utils").EventBus} EventBus */
/** @typedef {import("./interfaces").IPDFLinkService} IPDFLinkService */
import { parseQueryString } from "./ui_utils.js";
const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
const LinkTarget = {
NONE: 0, // Default value.
SELF: 1,
BLANK: 2,
PARENT: 3,
TOP: 4,
};
/**
* @typedef {Object} PDFLinkServiceOptions
* @property {EventBus} eventBus - The application event bus.
* @property {number} [externalLinkTarget] - Specifies the `target` attribute
* for external links. Must use one of the values from {LinkTarget}.
* Defaults to using no target.
* @property {string} [externalLinkRel] - Specifies the `rel` attribute for
* external links. Defaults to stripping the referrer.
* @property {boolean} [ignoreDestinationZoom] - Ignores the zoom argument,
* thus preserving the current zoom level in the viewer, when navigating
* to internal destinations. The default value is `false`.
*/
/**
* Performs navigation functions inside PDF, such as opening specified page,
* or destination.
* @implements {IPDFLinkService}
*/
class PDFLinkService {
externalLinkEnabled = true;
/**
* @param {PDFLinkServiceOptions} options
*/
constructor({
eventBus,
externalLinkTarget = null,
externalLinkRel = null,
ignoreDestinationZoom = false,
} = {}) {
this.eventBus = eventBus;
this.externalLinkTarget = externalLinkTarget;
this.externalLinkRel = externalLinkRel;
this._ignoreDestinationZoom = ignoreDestinationZoom;
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
}
setDocument(pdfDocument, baseUrl = null) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
}
setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
}
setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
}
/**
* @type {number}
*/
get pagesCount() {
return this.pdfDocument ? this.pdfDocument.numPages : 0;
}
/**
* @type {number}
*/
get page() {
return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1;
}
/**
* @param {number} value
*/
set page(value) {
if (this.pdfDocument) {
this.pdfViewer.currentPageNumber = value;
}
}
/**
* @type {number}
*/
get rotation() {
return this.pdfDocument ? this.pdfViewer.pagesRotation : 0;
}
/**
* @param {number} value
*/
set rotation(value) {
if (this.pdfDocument) {
this.pdfViewer.pagesRotation = value;
}
}
/**
* @type {boolean}
*/
get isInPresentationMode() {
return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false;
}
/**
* This method will, when available, also update the browser history.
*
* @param {string|Array} dest - The named, or explicit, PDF destination.
*/
async goToDestination(dest) {
if (!this.pdfDocument) {
return;
}
let namedDest, explicitDest, pageNumber;
if (typeof dest === "string") {
namedDest = dest;
explicitDest = await this.pdfDocument.getDestination(dest);
} else {
namedDest = null;
explicitDest = await dest;
}
if (!Array.isArray(explicitDest)) {
console.error(
`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`
);
return;
}
// Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
const [destRef] = explicitDest;
if (destRef && typeof destRef === "object") {
pageNumber = this.pdfDocument.cachedPageNumber(destRef);
if (!pageNumber) {
// Fetch the page reference if it's not yet available. This could
// only occur during loading, before all pages have been resolved.
try {
pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1;
} catch {
console.error(
`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`
);
return;
}
}
} else if (Number.isInteger(destRef)) {
pageNumber = destRef + 1;
}
if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
console.error(
`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`
);
return;
}
if (this.pdfHistory) {
// Update the browser history before scrolling the new destination into
// view, to be able to accurately capture the current document position.
this.pdfHistory.pushCurrentPosition();
this.pdfHistory.push({ namedDest, explicitDest, pageNumber });
}
this.pdfViewer.scrollPageIntoView({
pageNumber,
destArray: explicitDest,
ignoreDestinationZoom: this._ignoreDestinationZoom,
});
}
/**
* This method will, when available, also update the browser history.
*
* @param {number|string} val - The page number, or page label.
*/
goToPage(val) {
if (!this.pdfDocument) {
return;
}
const pageNumber =
(typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val)) ||
val | 0;
if (
!(
Number.isInteger(pageNumber) &&
pageNumber > 0 &&
pageNumber <= this.pagesCount
)
) {
console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
return;
}
if (this.pdfHistory) {
// Update the browser history before scrolling the new page into view,
// to be able to accurately capture the current document position.
this.pdfHistory.pushCurrentPosition();
this.pdfHistory.pushPage(pageNumber);
}
this.pdfViewer.scrollPageIntoView({ pageNumber });
}
/**
* Adds various attributes (href, title, target, rel) to hyperlinks.
* @param {HTMLAnchorElement} link
* @param {string} url
* @param {boolean} [newWindow]
*/
addLinkAttributes(link, url, newWindow = false) {
if (!url || typeof url !== "string") {
throw new Error('A valid "url" parameter must provided.');
}
const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
rel = this.externalLinkRel;
if (this.externalLinkEnabled) {
link.href = link.title = url;
} else {
link.href = "";
link.title = `Disabled: ${url}`;
link.onclick = () => false;
}
let targetStr = ""; // LinkTarget.NONE
switch (target) {
case LinkTarget.NONE:
break;
case LinkTarget.SELF:
targetStr = "_self";
break;
case LinkTarget.BLANK:
targetStr = "_blank";
break;
case LinkTarget.PARENT:
targetStr = "_parent";
break;
case LinkTarget.TOP:
targetStr = "_top";
break;
}
link.target = targetStr;
link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
}
/**
* @param {string|Array} dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash(dest) {
if (typeof dest === "string") {
if (dest.length > 0) {
return this.getAnchorUrl("#" + escape(dest));
}
} else if (Array.isArray(dest)) {
const str = JSON.stringify(dest);
if (str.length > 0) {
return this.getAnchorUrl("#" + escape(str));
}
}
return this.getAnchorUrl("");
}
/**
* Prefix the full url on anchor links to make sure that links are resolved
* relative to the current URL instead of the one defined in <base href>.
* @param {string} anchor - The anchor hash, including the #.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl(anchor) {
return this.baseUrl ? this.baseUrl + anchor : anchor;
}
/**
* @param {string} hash
*/
setHash(hash) {
if (!this.pdfDocument) {
return;
}
let pageNumber, dest;
if (hash.includes("=")) {
const params = parseQueryString(hash);
if (params.has("search")) {
const query = params.get("search").replaceAll('"', ""),
phrase = params.get("phrase") === "true";
this.eventBus.dispatch("findfromurlhash", {
source: this,
query: phrase ? query : query.match(/\S+/g),
});
}
// borrowing syntax from "Parameters for Opening PDF Files"
if (params.has("page")) {
pageNumber = params.get("page") | 0 || 1;
}
if (params.has("zoom")) {
// Build the destination array.
const zoomArgs = params.get("zoom").split(","); // scale,left,top
const zoomArg = zoomArgs[0];
const zoomArgNumber = parseFloat(zoomArg);
if (!zoomArg.includes("Fit")) {
// If the zoomArg is a number, it has to get divided by 100. If it's
// a string, it should stay as it is.
dest = [
null,
{ name: "XYZ" },
zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,
zoomArgNumber ? zoomArgNumber / 100 : zoomArg,
];
} else if (zoomArg === "Fit" || zoomArg === "FitB") {
dest = [null, { name: zoomArg }];
} else if (
zoomArg === "FitH" ||
zoomArg === "FitBH" ||
zoomArg === "FitV" ||
zoomArg === "FitBV"
) {
dest = [
null,
{ name: zoomArg },
zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
];
} else if (zoomArg === "FitR") {
if (zoomArgs.length !== 5) {
console.error(
'PDFLinkService.setHash: Not enough parameters for "FitR".'
);
} else {
dest = [
null,
{ name: zoomArg },
zoomArgs[1] | 0,
zoomArgs[2] | 0,
zoomArgs[3] | 0,
zoomArgs[4] | 0,
];
}
} else {
console.error(
`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`
);
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView({
pageNumber: pageNumber || this.page,
destArray: dest,
allowNegativeOffset: true,
});
} else if (pageNumber) {
this.page = pageNumber; // simple page
}
if (params.has("pagemode")) {
this.eventBus.dispatch("pagemode", {
source: this,
mode: params.get("pagemode"),
});
}
// Ensure that this parameter is *always* handled last, in order to
// guarantee that it won't be overridden (e.g. by the "page" parameter).
if (params.has("nameddest")) {
this.goToDestination(params.get("nameddest"));
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
return;
}
// Support opening of PDF attachments in the Firefox PDF Viewer,
// which uses a couple of non-standard hash parameters; refer to
// `DownloadManager.openOrDownloadData` in the firefoxcom.js file.
if (!params.has("filename") || !params.has("filedest")) {
return;
}
hash = params.get("filedest");
}
// Named (or explicit) destination.
dest = unescape(hash);
try {
dest = JSON.parse(dest);
if (!Array.isArray(dest)) {
// Avoid incorrectly rejecting a valid named destination, such as
// e.g. "4.3" or "true", because `JSON.parse` converted its type.
dest = dest.toString();
}
} catch {}
if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) {
this.goToDestination(dest);
return;
}
console.error(
`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`
);
}
/**
* @param {string} action
*/
executeNamedAction(action) {
if (!this.pdfDocument) {
return;
}
// See PDF reference, table 8.45 - Named action
switch (action) {
case "GoBack":
this.pdfHistory?.back();
break;
case "GoForward":
this.pdfHistory?.forward();
break;
case "NextPage":
this.pdfViewer.nextPage();
break;
case "PrevPage":
this.pdfViewer.previousPage();
break;
case "LastPage":
this.page = this.pagesCount;
break;
case "FirstPage":
this.page = 1;
break;
default:
break; // No action according to spec
}
this.eventBus.dispatch("namedaction", {
source: this,
action,
});
}
/**
* @param {Object} action
*/
async executeSetOCGState(action) {
if (!this.pdfDocument) {
return;
}
const pdfDocument = this.pdfDocument,
optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
if (pdfDocument !== this.pdfDocument) {
return; // The document was closed while the optional content resolved.
}
optionalContentConfig.setOCGState(action);
this.pdfViewer.optionalContentConfigPromise = Promise.resolve(
optionalContentConfig
);
}
static #isValidExplicitDest(dest) {
if (!Array.isArray(dest) || dest.length < 2) {
return false;
}
const [page, zoom, ...args] = dest;
if (
!(
typeof page === "object" &&
Number.isInteger(page?.num) &&
Number.isInteger(page?.gen)
) &&
!Number.isInteger(page)
) {
return false;
}
if (!(typeof zoom === "object" && typeof zoom?.name === "string")) {
return false;
}
const argsLen = args.length;
let allowNull = true;
switch (zoom.name) {
case "XYZ":
if (argsLen < 2 || argsLen > 3) {
return false;
}
break;
case "Fit":
case "FitB":
return argsLen === 0;
case "FitH":
case "FitBH":
case "FitV":
case "FitBV":
if (argsLen > 1) {
return false;
}
break;
case "FitR":
if (argsLen !== 4) {
return false;
}
allowNull = false;
break;
default:
return false;
}
for (const arg of args) {
if (!(typeof arg === "number" || (allowNull && arg === null))) {
return false;
}
}
return true;
}
}
/**
* @implements {IPDFLinkService}
*/
class SimpleLinkService extends PDFLinkService {
setDocument(pdfDocument, baseUrl = null) {}
}
export { LinkTarget, PDFLinkService, SimpleLinkService };