van-hmr/hmr.js
2025-02-07 15:24:17 -05:00

93 lines
2.3 KiB
JavaScript

//@ts-check
// hmr
const HMR = globalThis.HMR = {
Time: 0,
/** @type {Record<string, string>} */
Temp:{},
Tick()
{
for(const k in HMR.Temp)
{
sessionStorage.setItem(k, HMR.Temp[k]);
}
HMR.Temp = {};
HMR.Time = 0;
},
/** @type {(key:string, value:string)=>void} */
Save(key, value)
{
this.Temp[key] = value;
if(!this.Time)
{
this.Time = setTimeout(this.Tick, 500);
}
console.log("SAVE", key, value);
},
/** @type {(key:string)=>string|null} */
Load(key)
{
const value = sessionStorage.getItem(key);
console.log("LOAD", key, value);
return value;
},
/** @type {string|undefined} */
_ID: undefined,
_index: 0,
/** @type {(id:string|undefined = undefined)=>void} */
StartID(id)
{
this._index = 0;
this._ID = id;
},
NextID()
{
return this._ID ? this._ID + "_" + (this._index++) + "_" : "";
},
BindVan()
{
//bind Van
const origninalState = globalThis.van.state;
globalThis.van.state =(value, key="")=>
{
const type = typeof value;
let reader =d=>d;
let writer =d=>d?.toString() || null;
switch(type)
{
case "boolean" :
reader =(data)=> data === "true"; break;
case "number" :
reader = parseFloat; break;
case "object" :
reader = JSON.parse;
writer = JSON.stringify;
break;
}
const fullKey = "HMR_" + HMR.NextID() + key;
const stringValue = HMR.Load(fullKey);
const signal = origninalState(/**@type{T}*/(stringValue ? reader(stringValue) : value));
van.derive(()=>HMR.Save(fullKey, writer(signal.val)));
return signal;
};
},
BindVanX()
{
//bind VanX
const originalReactive = globalThis.vanX.reactive;
globalThis.vanX.reactive =(obj, id)=>
{
HMR.StartID(id);
const state = originalReactive(obj);
HMR.StartID();
return state;
}
}
}