van-hmr/hmr.js

93 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2025-02-07 09:58:54 -05:00
//@ts-check
2025-02-07 15:17:25 -05:00
// hmr
const HMR = globalThis.HMR = {
2025-02-07 09:58:54 -05:00
Time: 0,
/** @type {Record<string, string>} */
Temp:{},
Tick()
{
2025-02-07 15:17:25 -05:00
for(const k in HMR.Temp)
2025-02-07 09:58:54 -05:00
{
2025-02-07 15:17:25 -05:00
sessionStorage.setItem(k, HMR.Temp[k]);
2025-02-07 09:58:54 -05:00
}
2025-02-07 15:17:25 -05:00
HMR.Temp = {};
HMR.Time = 0;
2025-02-07 09:58:54 -05:00
},
/** @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)
{
2025-02-07 15:17:25 -05:00
const value = sessionStorage.getItem(key);
2025-02-07 09:58:54 -05:00
console.log("LOAD", key, value);
return value;
2025-02-07 15:17:25 -05:00
},
2025-02-07 09:58:54 -05:00
/** @type {string|undefined} */
_ID: undefined,
_index: 0,
/** @type {(id:string|undefined = undefined)=>void} */
StartID(id)
{
this._index = 0;
this._ID = id;
},
2025-02-07 15:17:25 -05:00
NextID()
2025-02-07 09:58:54 -05:00
{
return this._ID ? this._ID + "_" + (this._index++) + "_" : "";
2025-02-07 15:17:25 -05:00
},
2025-02-07 09:58:54 -05:00
2025-02-07 15:17:25 -05:00
BindVan()
2025-02-07 09:58:54 -05:00
{
2025-02-07 15:17:25 -05:00
//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()
2025-02-07 09:58:54 -05:00
{
2025-02-07 15:17:25 -05:00
//bind VanX
const originalReactive = globalThis.vanX.reactive;
globalThis.vanX.reactive =(obj, id)=>
{
HMR.StartID(id);
const state = originalReactive(obj);
HMR.StartID();
return state;
}
2025-02-07 09:58:54 -05:00
}
}