able-baker/hmr-listen.tsx

31 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-10-16 10:27:22 -04:00
import { HMR } from "./hmr-react.tsx";
2023-10-16 12:33:07 -04:00
import { GroupSignal, GroupSignalHook } from "./hmr-signal.tsx";
2023-06-17 14:48:39 -04:00
const FileListeners = new Map() as Map<string, Array<(module:unknown)=>void>>;
2023-06-15 17:13:51 -04:00
export const FileListen =(inPath:string, inHandler:()=>void)=>
{
const members = FileListeners.get(inPath)??[];
members.push(inHandler);
FileListeners.set(inPath, members);
};
2023-06-06 22:48:45 -04:00
2023-06-15 17:13:51 -04:00
const Socket:WebSocket = new WebSocket("ws://"+document.location.host);
2023-06-17 14:48:39 -04:00
Socket.addEventListener('message', async(event:{data:string})=>
2023-06-06 22:48:45 -04:00
{
2023-06-17 14:48:39 -04:00
// When a file changes, dynamically re-import it to get the updated members
// send the updated members to any listeners for that file
2023-10-16 10:27:22 -04:00
2023-10-16 12:33:07 -04:00
GroupSignal.reset();
2023-10-16 10:27:22 -04:00
2023-07-08 12:21:58 -04:00
const reImport = await import(document.location.origin+event.data+"?reload="+Math.random());
2023-06-18 14:37:13 -04:00
FileListeners.get(event.data)?.forEach(reExport=>reExport(reImport));
2023-10-16 10:27:22 -04:00
2023-10-16 12:33:07 -04:00
GroupSignal.swap();
GroupSignalHook.reset();
2023-10-16 10:27:22 -04:00
HMR.update();
2023-10-16 12:33:07 -04:00
GroupSignalHook.reset();
2023-10-16 10:27:22 -04:00
2023-06-06 22:48:45 -04:00
});
2023-06-18 07:36:55 -04:00
Socket.addEventListener("error", ()=>{clearInterval(SocketTimer); console.log("HMR socket lost")})
2023-10-14 12:09:06 -04:00
const SocketTimer = setInterval(()=>{Socket.send("ping")}, 5000);