Skip to content

Commit

Permalink
chore: update example
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Feb 26, 2024
1 parent a6879bd commit 0ce11c5
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 44 deletions.
43 changes: 36 additions & 7 deletions examples/h3/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,33 +34,56 @@
});
};

const format = async () => {
for (const message of store.messages) {
if (!message._fmt && message.text.startsWith("{")) {
message._fmt = true;
const { codeToHtml } = await import("https://esm.sh/[email protected]");
const str = JSON.stringify(JSON.parse(message.text), null, 2);
message.formattedText = await codeToHtml(str, {
lang: "json",
theme: "dark-plus",
});
}
}
};

const log = (user, ...args) => {
console.log("[ws]", user, ...args);
store.messages.push({
text: args.join(" "),
formattedText: "",
user: user,
date: new Date().toLocaleString(),
});
scroll();
format();
};

const connect = async () => {
const isSecure = location.protocol === "https:";
const url = (isSecure ? "wss://" : "ws://") + location.host + "/_ws";
if (ws) {
log("system", "closing");
log("system", "Closing previous connection before reconnecting...");
ws.close();
clear();
}

log("system", "Connecting to", url, "...");
ws = new WebSocket(url);

ws.addEventListener("message", (event) => {
log("server", event.data);
const { user = "system", message = "" } = event.data.startsWith("{")
? JSON.parse(event.data)
: { message: event.data };
log(
user,
typeof message === "string" ? message : JSON.stringify(message),
);
});

log("system", "Waiting for connection...");
await new Promise((resolve) => ws.addEventListener("open", resolve));
log("system", "Connected!");
};

const clear = () => {
Expand All @@ -71,7 +94,6 @@
const send = () => {
console.log("sending message...");
if (store.message) {
log("you", store.message);
ws.send(store.message);
}
store.message = "";
Expand All @@ -92,7 +114,6 @@

await connect();
ping();
send("foo");
</script>
</head>
<body class="h-screen flex flex-col justify-between">
Expand All @@ -108,8 +129,16 @@
alt="Avatar"
class="w-8 h-8 rounded-full"
/>
<div class="ml-2 bg-gray-800 rounded-lg p-2">
<p class="text-white">{{ message.text }}</p>
<div
class="ml-2 bg-gray-800 rounded-lg p-2"
style="max-width: 33.33vw"
>
<p
v-if="message.formattedText"
class="overflow-x-scroll"
v-html="message.formattedText"
></p>
<p v-else class="text-white">{{ message.text }}</p>
</div>
</div>
<p class="text-gray-500 mt-1 text-xs ml-10">{{ message.date }}</p>
Expand Down
49 changes: 40 additions & 9 deletions playground/_index.html.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export default /* html */ `<!doctype html>
export default /* html */ `
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<title>CrossWS Test Page</title>
Expand Down Expand Up @@ -34,33 +35,56 @@ export default /* html */ `<!doctype html>
});
};
const format = async () => {
for (const message of store.messages) {
if (!message._fmt && message.text.startsWith("{")) {
message._fmt = true;
const { codeToHtml } = await import("https://esm.sh/[email protected]");
const str = JSON.stringify(JSON.parse(message.text), null, 2);
message.formattedText = await codeToHtml(str, {
lang: "json",
theme: "dark-plus",
});
}
}
};
const log = (user, ...args) => {
console.log("[ws]", user, ...args);
store.messages.push({
text: args.join(" "),
formattedText: "",
user: user,
date: new Date().toLocaleString(),
});
scroll();
format();
};
const connect = async () => {
const isSecure = location.protocol === "https:";
const url = (isSecure ? "wss://" : "ws://") + location.host + "/_ws";
if (ws) {
log("system", "closing");
log("system", "Closing previous connection before reconnecting...");
ws.close();
clear();
}
log("system", "Connecting to", url, "...");
ws = new WebSocket(url);
ws.addEventListener("message", (event) => {
log("server", event.data);
const { user = "system", message = "" } = event.data.startsWith("{")
? JSON.parse(event.data)
: { message: event.data };
log(
user,
typeof message === "string" ? message : JSON.stringify(message),
);
});
log("system", "Waiting for connection...");
await new Promise((resolve) => ws.addEventListener("open", resolve));
log("system", "Connected!");
};
const clear = () => {
Expand All @@ -71,7 +95,6 @@ export default /* html */ `<!doctype html>
const send = () => {
console.log("sending message...");
if (store.message) {
log("you", store.message);
ws.send(store.message);
}
store.message = "";
Expand All @@ -92,7 +115,6 @@ export default /* html */ `<!doctype html>
await connect();
ping();
send("foo");
</script>
</head>
<body class="h-screen flex flex-col justify-between">
Expand All @@ -108,8 +130,16 @@ export default /* html */ `<!doctype html>
alt="Avatar"
class="w-8 h-8 rounded-full"
/>
<div class="ml-2 bg-gray-800 rounded-lg p-2">
<p class="text-white">{{ message.text }}</p>
<div
class="ml-2 bg-gray-800 rounded-lg p-2"
style="max-width: 33.33vw"
>
<p
v-if="message.formattedText"
class="overflow-x-scroll"
v-html="message.formattedText"
></p>
<p v-else class="text-white">{{ message.text }}</p>
</div>
</div>
<p class="text-gray-500 mt-1 text-xs ml-10">{{ message.date }}</p>
Expand Down Expand Up @@ -155,4 +185,5 @@ export default /* html */ `<!doctype html>
</div>
</main>
</body>
</html>`;
</html>
`.trim();
46 changes: 18 additions & 28 deletions playground/_shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,20 @@ export function createDemo<T extends Adapter<any, any>>(
);
},
open(peer) {
peer.send("Welcome to the server!");
peer.subscribe("welcome");
peer.publish("welcome", `New user joined! ${peer}`);
peer.send({ user: "system", message: `Welcome to the server ${peer}!` });
peer.subscribe("chat");
peer.publish("chat", { user: "system", message: `${peer} joined!` });
},
message(peer, message) {
if (message.text() === "ping") {
peer.send("pong");
peer.send({ user: "system", message: "pong" });
} else {
const _message = {
user: peer.toString(),
message: message.text(),
};
peer.send(_message);
peer.publish("chat", _message);
}
},
upgrade(req) {
Expand All @@ -33,34 +40,17 @@ export function createDemo<T extends Adapter<any, any>>(
},
});

// open(peer) {
// // Send welcome to the new client
// peer.send("Welcome to the server!");

// // Join new client to the "chat" channel
// peer.subscribe("chat");

// // Notify every other connected client
// peer.publish("chat", `[system] ${peer} joined!`);
// },

// message(peer, message) {
// // The server re-broadcasts incoming messages to everyone
// peer.publish("chat", `[${peer}] ${message}`);
// },

// close(peer) {
// peer.publish("chat", `[system] ${peer} has left the chat!`);
// peer.unsubscribe("chat");
// },

const resolve: ResolveHooks = (info) => {
return {
open: (peer) => {
peer.send({
url: info.url,
headers:
info.headers && Object.fromEntries(new Headers(info.headers)),
message: {
info: {
url: info.url,
headers:
info.headers && Object.fromEntries(new Headers(info.headers)),
},
},
});
},
};
Expand Down

0 comments on commit 0ce11c5

Please sign in to comment.