Skip to content

Commit

Permalink
web worker
Browse files Browse the repository at this point in the history
  • Loading branch information
kondaurovDev committed Dec 22, 2024
1 parent ada3067 commit cceddbe
Show file tree
Hide file tree
Showing 12 changed files with 107 additions and 26 deletions.
9 changes: 6 additions & 3 deletions docs/telegram-bot-playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<title>Telegram Bot Playground</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script defer src="https://cdn.jsdelivr.net/npm/@monaco-editor/[email protected]/lib/umd/monaco-loader.min.js"></script>
<script defer src="./scripts/init.js?v=1ce1qg" type="module"></script>
<script defer src="./scripts/main.js?v=w50ikz" type="module"></script>
<script defer src="./scripts/init.js?v=79sgsn" type="module"></script>
<script defer src="./scripts/main.js?v=s4vhmf" type="module"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>

<link rel="stylesheet" href="styles.css?v=xa8dtw">
Expand All @@ -23,7 +23,10 @@
}
}"
x-init="
playground.start();
await playground.start();
playground.onCodeChange(() => {
console.log('Code was changed')
});
playground.worker.onmessage = (e) => {
console.log('got message from worker', e.data);
if (!e?.data) return;
Expand Down
6 changes: 6 additions & 0 deletions docs/telegram-bot-playground/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"styles.css": "xa8dtw",
"init.js": "79sgsn",
"main.js": "s4vhmf",
"web-worker.js": "eb7q23"
}
15 changes: 10 additions & 5 deletions docs/telegram-bot-playground/scripts/init.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
// src/tg-bot-playground/init.ts
var worker = new Worker("./scripts/web-worker.js", { type: "module" });
worker.addEventListener("message", (msg) => {
console.log("From worker", msg.data);
});
window.playground = {};
window.playground.worker = worker;
var version = await fetch("./metadata.json", { cache: "no-cache" }).then((_) => _.json()).then((_) => _["web-worker.js"]);
if (version) {
const worker = new Worker(`./scripts/web-worker.js?v=${version}`, { type: "module" });
worker.addEventListener("message", (msg) => {
console.log("From worker", msg.data);
});
window.playground.worker = worker;
} else {
console.warn("web worker not initiated");
}
setFavicon("\u{1F916}");
function setFavicon(emoji) {
const canvas = document.createElement("canvas");
Expand Down
26 changes: 25 additions & 1 deletion docs/telegram-bot-playground/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ var serialize = (input) => {
};

// src/tg-bot-playground/main.ts
console.log("loading main");
window.playground.start = () => {
const container = document.getElementById("container");
if (!container) {
Expand All @@ -66,7 +67,7 @@ window.playground.start = () => {
vs: "https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs"
}
});
Promise.all([
return Promise.all([
window.monaco_loader.init(),
fetchText("./example/empty.ts")
]).then(([monaco, emptyExample]) => {
Expand Down Expand Up @@ -118,3 +119,26 @@ window.playground.checkToken = (state) => {
console.warn("check token error", error);
});
};
window.playground.onCodeChange = (f) => {
let timeoutId;
const debounceDelay = 1e3;
const editor = window.playground.editor;
if (!editor) {
console.warn("Cannot attach onDidChangeModel");
return;
}
editor.onDidChangeModelContent(() => {
if (timeoutId !== void 0) {
clearTimeout(timeoutId);
}
timeoutId = window.setTimeout(() => {
const model = window.playground.tsModel;
if (model) {
const markers = window.monaco.editor.getModelMarkers({ resource: model.uri });
if (!markers.find((_) => _.severity.valueOf() == 8)) {
f();
}
}
}, debounceDelay);
});
};
2 changes: 1 addition & 1 deletion docs/telegram-bot-playground/scripts/web-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3719,7 +3719,7 @@ var deserialize = (input) => {
};

// src/tg-bot-playground/web-worker.ts
console.log("loading worker");
console.log("loading worker...");
var logId = 1;
var notifyParent = (input) => {
self.postMessage({
Expand Down
10 changes: 8 additions & 2 deletions scripts/prep-page.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ const files = [
];

const indexPagePath = "./docs/telegram-bot-playground/index.html";
const metaPath = "./docs/telegram-bot-playground/metadata.json";

let html = await readFile(indexPagePath, "utf-8");

const metadata = {}

for (const relativePath of files) {

const absolutePath = Path.join("./docs/telegram-bot-playground", relativePath);
Expand All @@ -25,14 +28,17 @@ for (const relativePath of files) {
const content = await readFile(absolutePath, "utf-8");
const hash = getShortHash(content);

const filename = Path.basename(relativePath).replace(".", "\\.");
const filename = Path.basename(relativePath);

const regex = new RegExp(`(${filename}\\?v=)\\w*`, "g");
const regex = new RegExp(`(${filename.replace(".", "\\.")}\\?v=)\\w*`, "g");
html = html.replace(regex, `$1${hash}`);

metadata[filename] = hash;

}

await writeFile(indexPagePath, html, "utf-8");
await writeFile(metaPath, JSON.stringify(metadata, undefined, 2), "utf-8");

function getShortHash(str) {
let hash = 0;
Expand Down
3 changes: 2 additions & 1 deletion src/globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ interface Window {
playground: {
worker?: Worker
tsModel?: import("monaco-editor").editor.ITextModel
start?: typeof import("./tg-bot-playground/main.js").startPlayground
start?: () => Promise<unknown> | void
editor?: import("monaco-editor").editor.IStandaloneCodeEditor
loadExample?: (name: string) => void
runBot?: (_: BotState) => void
checkToken?: (_: BotState) => void
onCodeChange?: (_: () => void) => void
}
}
21 changes: 15 additions & 6 deletions src/tg-bot-playground/init.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
const worker = new Worker('./scripts/web-worker.js', { type: "module" });
window.playground = {};

worker.addEventListener("message", msg => {
console.log("From worker", msg.data);
});
const version: string = await (
fetch("./metadata.json", { cache: "no-cache" }).then(_ => _.json()).then(_ => _["web-worker.js"])
);

window.playground = {};
window.playground.worker = worker;
if (version) {
const worker = new Worker(`./scripts/web-worker.js?v=${version}`, { type: "module" });

worker.addEventListener("message", msg => {
console.log("From worker", msg.data);
});

window.playground.worker = worker;
} else {
console.warn("web worker not initiated")
}

setFavicon("🤖");

Expand Down
33 changes: 31 additions & 2 deletions src/tg-bot-playground/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { BotState } from "./types.js";
import { fetchText, getJsCode, setupDts } from "./utils.js";

console.log("loading main");

window.playground.start = () => {

const container = document.getElementById('container');
Expand All @@ -15,7 +17,7 @@ window.playground.start = () => {
}
});

Promise.all([
return Promise.all([
window.monaco_loader.init(),
fetchText("./example/empty.ts")
]).then(([monaco, emptyExample]) => {
Expand All @@ -31,7 +33,7 @@ window.playground.start = () => {
contextmenu: false,
minimap: {
enabled: false
}
},
});

}).catch(error => console.warn("init error", error));
Expand Down Expand Up @@ -95,3 +97,30 @@ window.playground.checkToken =
});

}

window.playground.onCodeChange =
(f) => {
let timeoutId: number | undefined;
const debounceDelay = 1000;

const editor = window.playground.editor;

if (!editor) {
console.warn("Cannot attach onDidChangeModel");
return;
}

editor.onDidChangeModelContent(() => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}

timeoutId = window.setTimeout(() => {
const model = window.playground.tsModel;
if (model) {
const markers = window.monaco.editor.getModelMarkers({ resource: model.uri });
if (!markers.find(_ => _.severity.valueOf() == 8)) { f() }
}
}, debounceDelay);
});
}
2 changes: 1 addition & 1 deletion src/tg-bot-playground/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,4 @@ export const deserialize = (input: string) => {
}

return Object.fromEntries(result);
}
}
2 changes: 1 addition & 1 deletion src/tg-bot-playground/web-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { runTgChatBot } from "@effect-ak/tg-bot-client"
import { deserialize } from "./utils.js"
import type { BotState } from "./types.js"

console.log("loading worker")
console.log("loading worker...");

type RunBot = {
command: "run-bot"
Expand Down
4 changes: 1 addition & 3 deletions test/worker.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { describe, expect, it } from "vitest";
import * as Path from "path";
import { Worker } from "worker_threads";
import assert from "assert";
import { existsSync } from "fs";

describe("web worker", () => {

it("create", async () => {
it.skip("create", async () => {

const path =
Path.join(__dirname, "..", "docs", "telegram-bot-playground", "scripts", "web-workers.js");
Expand Down

0 comments on commit cceddbe

Please sign in to comment.