|
18 | 18 | * and passing it back to the external service. |
19 | 19 | */ |
20 | 20 | class PdfTextExtractor { |
21 | | - /** @type {PDFViewer} */ |
22 | | - #pdfViewer; |
23 | | - |
| 21 | + /** @type {BaseExternalServices} */ |
24 | 22 | #externalServices; |
25 | 23 |
|
26 | | - /** |
27 | | - * @type {?Promise<string>} |
28 | | - */ |
| 24 | + /** @type {?Promise<string>} */ |
29 | 25 | #textPromise; |
30 | 26 |
|
31 | | - #pendingRequests = new Set(); |
| 27 | + #capability = Promise.withResolvers(); |
32 | 28 |
|
33 | | - constructor(externalServices) { |
| 29 | + constructor(externalServices, pdfViewer, eventBus) { |
34 | 30 | this.#externalServices = externalServices; |
35 | 31 |
|
| 32 | + eventBus._on("pagesinit", () => { |
| 33 | + this.#capability.resolve(pdfViewer); |
| 34 | + }); |
| 35 | + eventBus._on("pagesdestroy", () => { |
| 36 | + this.#capability.reject(new Error("pagesdestroy")); |
| 37 | + this.#textPromise = null; |
| 38 | + |
| 39 | + this.#capability = Promise.withResolvers(); |
| 40 | + }); |
| 41 | + |
36 | 42 | window.addEventListener("requestTextContent", ({ detail }) => { |
37 | 43 | this.extractTextContent(detail.requestId); |
38 | 44 | }); |
39 | 45 | } |
40 | 46 |
|
41 | | - /** |
42 | | - * The PDF viewer is required to get the page text. |
43 | | - * |
44 | | - * @param {PDFViewer | null} |
45 | | - */ |
46 | | - setViewer(pdfViewer) { |
47 | | - this.#pdfViewer = pdfViewer; |
48 | | - if (this.#pdfViewer && this.#pendingRequests.size) { |
49 | | - // Handle any pending requests that came in while things were loading. |
50 | | - for (const pendingRequest of this.#pendingRequests) { |
51 | | - this.extractTextContent(pendingRequest); |
52 | | - } |
53 | | - this.#pendingRequests.clear(); |
54 | | - } |
55 | | - } |
56 | | - |
57 | 47 | /** |
58 | 48 | * Builds up all of the text from a PDF. |
59 | 49 | * |
60 | 50 | * @param {number} requestId |
61 | 51 | */ |
62 | 52 | async extractTextContent(requestId) { |
63 | | - if (!this.#pdfViewer) { |
64 | | - this.#pendingRequests.add(requestId); |
65 | | - return; |
66 | | - } |
67 | | - |
68 | 53 | if (!this.#textPromise) { |
69 | | - const textPromise = (this.#textPromise = this.#pdfViewer.getAllText()); |
| 54 | + const textPromise = (this.#textPromise = this.#capability.promise.then( |
| 55 | + pdfViewer => pdfViewer.getAllText() |
| 56 | + )); |
70 | 57 |
|
71 | 58 | // After the text resolves, cache the text for a little bit in case |
72 | 59 | // multiple consumers call it. |
|
0 commit comments