able-baker/_lib_/hmr.tsx

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-06-15 17:13:51 -04:00
type FileHandler = (module:unknown)=>void
const FileListeners = new Map() as Map<string, Array<FileHandler>>;
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);
Socket.addEventListener('message', (event:{data:string})=>
2023-06-06 22:48:45 -04:00
{
2023-06-15 17:13:51 -04:00
const handlers = FileListeners.get(event.data)??[];
SocketReloads++;
2023-06-06 22:48:45 -04:00
Promise.all(
2023-06-15 17:13:51 -04:00
handlers.map((handler)=>
2023-06-06 22:48:45 -04:00
{
2023-06-15 17:13:51 -04:00
return import(event.data+"?reload="+SocketReloads)
2023-06-06 22:48:45 -04:00
.then(updatedModule=>handler(updatedModule));
})
2023-06-15 17:50:55 -04:00
).then(()=>HMR.update());
2023-06-06 22:48:45 -04:00
});
2023-06-15 17:13:51 -04:00
let SocketReloads = 0;
// heartbeat
const SocketTimer = setInterval(()=>{Socket.send("ping")}, 5000);
2023-06-06 22:48:45 -04:00
const HMR = {
reloads:0,
2023-06-15 17:50:55 -04:00
createdElements: new Map() as Map<string, ()=>void>,
2023-06-06 22:48:45 -04:00
states: new Map(),
statesOld: new Map(),
wireframe: false,
2023-06-15 17:50:55 -04:00
onChange(reactID:string, value:()=>void):void
2023-06-06 22:48:45 -04:00
{
2023-06-15 17:50:55 -04:00
this.createdElements.set(reactID, value);
2023-06-06 22:48:45 -04:00
},
update()
{
this.reloads++;
2023-06-15 17:50:55 -04:00
this.createdElements.forEach(handler=>handler());
this.createdElements.clear();
2023-06-06 22:48:45 -04:00
this.statesOld = this.states;
this.states = new Map();
this.echoState();
},
echoState()
{
let output = [];
for(const[key, val] of HMR.statesOld)
{
output[key] = val.state+"--"+val.reload;
}
console.log(output);
output = [];
for(const[key, val] of HMR.states)
{
output[key] = val.state+"--"+val.reload;
}
console.log(output);
}
};
export {HMR};
export const MapAt =(inMap, inIndex)=>
{
let index = 0;
for(const kvp of inMap)
{
if(index == inIndex)
{
return kvp;
}
index++;
}
return false;
};