Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reload websocket #46

Merged
merged 6 commits into from
Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ const render = async (
Object.keys(helmet)
.map((i) => helmet[i].toString())
.join("")
}<script type="module" defer>import { createElement } from "${
}<script type="module" defer>${
isDev && socket(root)
}import { createElement } from "${
importmap.imports["react"]
}";import { hydrateRoot } from "${
importmap.imports["react-dom"]
Expand Down Expand Up @@ -239,3 +241,15 @@ const staticLocationHook = (
hook.history = [path];
return hook;
};

const socket = (root: string) => {
const url = new URL(root);
return `
const _ultra_socket = new WebSocket("ws://${url.host}/_ultra_socket");
_ultra_socket.addEventListener("message", (e) => {
if (e.data === "reload") {
location.reload();
}
});
`;
};
26 changes: 26 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,26 @@ const server = async (
const fileRootUri = `file://${Deno.cwd()}/${dir}`;
const link = await ultraloader({ importmap, cache });
const serverStart = Math.ceil(+new Date() / 100);
const listeners = new Set<WebSocket>();

const handler = async (request: Request) => {
const requestStart = Math.ceil(+new Date() / 100);
const cacheBuster = isDev ? requestStart : serverStart;
const { raw, transpile } = await assets(dir);
const url = new URL(request.url);

// web socket listener
if (isDev) {
if (url.pathname == "/_ultra_socket") {
const { socket, response } = Deno.upgradeWebSocket(request);
listeners.add(socket);
socket.onclose = () => {
listeners.delete(socket);
};
return response;
}
}

// static assets
if (raw.has(`${dir}${url.pathname}`)) {
const contentType = raw.get(`${dir}${url.pathname}`);
Expand Down Expand Up @@ -140,6 +153,19 @@ const server = async (
);
};

// async file watcher to send socket messages
if (isDev) {
(async () => {
for await (const { kind } of Deno.watchFs(dir, { recursive: true })) {
if (kind === "modify") {
for (const socket of listeners) {
socket.send("reload");
}
}
}
})();
}

console.log(`Ultra running ${root}`);
//@ts-ignore any
return serve(handler, { port: +port });
Expand Down