1
0
Fork 0
mirror of https://github.com/mozilla/pdf.js.git synced 2025-04-23 08:38:06 +02:00

Shorten the WorkerMessageHandler class a little bit

- Use `this` in all scopes where that's possible, to avoid having to spell out `WorkerMessageHandler` everywhere.

 - Inline the `isMessagePort` helper function, since there's only a single call-site.

 - Use a static initialization block to move more code into the `WorkerMessageHandler` class itself.
This commit is contained in:
Jonas Jenwald 2024-11-30 12:50:53 +01:00
parent 8f08ca2150
commit ede589dd6e

View file

@ -70,9 +70,23 @@ class WorkerTask {
}
class WorkerMessageHandler {
static {
// Worker thread (and not Node.js)?
if (
typeof window === "undefined" &&
!isNodeJS &&
typeof self !== "undefined" &&
/* isMessagePort = */
typeof self.postMessage === "function" &&
"onmessage" in self
) {
this.initializeFromPort(self);
}
}
static setup(handler, port) {
let testMessageProcessed = false;
handler.on("test", function (data) {
handler.on("test", data => {
if (testMessageProcessed) {
return; // we already processed 'test' message once
}
@ -82,13 +96,11 @@ class WorkerMessageHandler {
handler.send("test", data instanceof Uint8Array);
});
handler.on("configure", function (data) {
handler.on("configure", data => {
setVerbosityLevel(data.verbosity);
});
handler.on("GetDocRequest", function (data) {
return WorkerMessageHandler.createDocumentHandler(data, port);
});
handler.on("GetDocRequest", data => this.createDocumentHandler(data, port));
}
static createDocumentHandler(docParams, port) {
@ -879,25 +891,9 @@ class WorkerMessageHandler {
static initializeFromPort(port) {
const handler = new MessageHandler("worker", "main", port);
WorkerMessageHandler.setup(handler, port);
this.setup(handler, port);
handler.send("ready", null);
}
}
function isMessagePort(maybePort) {
return (
typeof maybePort.postMessage === "function" && "onmessage" in maybePort
);
}
// Worker thread (and not Node.js)?
if (
typeof window === "undefined" &&
!isNodeJS &&
typeof self !== "undefined" &&
isMessagePort(self)
) {
WorkerMessageHandler.initializeFromPort(self);
}
export { WorkerMessageHandler, WorkerTask };