Skip to content

Commit

Permalink
Merge pull request #19136 from Snuffleupagus/WorkerMessageHandler-this
Browse files Browse the repository at this point in the history
Shorten the `WorkerMessageHandler` class a little bit
  • Loading branch information
timvandermeij authored Dec 1, 2024
2 parents 1bc6b76 + ede589d commit 9f90bc9
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions src/core/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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 };

0 comments on commit 9f90bc9

Please sign in to comment.