Skip to content
Open
Changes from all 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
18 changes: 18 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ const INITIAL_WAIT_TIME = 250

const STYLE_TAG_ERROR = `Purview: expected element with ID ${STYLE_TAG_ID} to be a style tag generated by purview`

export type PurviewEvent = {
type: 'websocket:open' | 'websocket:close' | 'websocket:message' | 'websocket:error' | 'component:update';
detail?: any;
}

export const dispatchPurviewEvent = (event: PurviewEvent) => {
window.dispatchEvent(new CustomEvent('purview', { detail: event }));
};

export function connectWebSocket(location: Location): WebSocket {
// For more context, see comment in src/browser.ts where we wait for the DOM to load.
if (document.readyState === "loading") {
Expand Down Expand Up @@ -74,6 +83,7 @@ function addWebSocketHandlers(state: WebSocketState, location: Location): void {

let interval: ReturnType<typeof setInterval> | null = null
ws.addEventListener("open", () => {
dispatchPurviewEvent({ type: 'websocket:open' });
const rootElems = Array.from(document.querySelectorAll("[data-root]"))
const rootIDs = rootElems.map(elem => {
return elem.getAttribute("data-component-id") as string
Expand Down Expand Up @@ -128,11 +138,19 @@ function addWebSocketHandlers(state: WebSocketState, location: Location): void {
}
})

ws.addEventListener("error", (error) => {
dispatchPurviewEvent({
type: 'websocket:error',
detail: { error }
});
});

ws.addEventListener("close", () => {
if (interval) {
clearInterval(interval)
interval = null
}
dispatchPurviewEvent({ type: 'websocket:close', detail: { retries: state.numRetries } });

if (state.numRetries === MAX_RETRIES) {
location.reload()

@denpoly-orum denpoly-orum Jan 23, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd also consider adding a log event here too, so we have a record of the refresh 😎

Expand Down