104 lines
2.2 KiB
JavaScript
104 lines
2.2 KiB
JavaScript
//@ts-check
|
|
|
|
const Gateway = globalThis.Gateway = {
|
|
Time: 0,
|
|
/** @type {Record<string, string>} */
|
|
Temp:{},
|
|
Tick()
|
|
{
|
|
for(const k in Gateway.Temp)
|
|
{
|
|
localStorage.setItem(k, Gateway.Temp[k]);
|
|
}
|
|
Gateway.Temp = {};
|
|
Gateway.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 = localStorage.getItem(key);
|
|
console.log("LOAD", key, value);
|
|
return value;
|
|
}
|
|
}
|
|
|
|
const context = {
|
|
/** @type {string|undefined} */
|
|
_ID: undefined,
|
|
_index: 0,
|
|
/** @type {(id:string|undefined = undefined)=>void} */
|
|
StartID(id)
|
|
{
|
|
this._index = 0;
|
|
this._ID = id;
|
|
},
|
|
CurrentID()
|
|
{
|
|
return this._ID ? this._ID + "_" + (this._index++) + "_" : "";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* HMR Wrapper for Van.state
|
|
* @template T
|
|
* @param {T} value - initial value
|
|
* @param {string} key - Storage ID
|
|
* @returns {Van.State<T>}
|
|
*/
|
|
export const State =(value, key="")=>
|
|
{
|
|
const type = typeof value;
|
|
let reader =d=>d;
|
|
let writer =d=>d.toString();
|
|
|
|
if(type === "object")
|
|
{
|
|
reader = JSON.parse;
|
|
writer = JSON.stringify;
|
|
}
|
|
else if(type === "number")
|
|
{
|
|
reader = parseFloat;
|
|
}
|
|
else if(type === "boolean")
|
|
{
|
|
reader =(data)=> data === "true";
|
|
}
|
|
/*
|
|
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 = context.CurrentID() + key
|
|
const stringValue = Gateway.Load(fullKey);
|
|
const signal = Van.state(/**@type{T}*/(stringValue ? reader(stringValue) : value));
|
|
Van.derive(()=>Gateway.Save(fullKey, writer(signal.val)));
|
|
|
|
return signal;
|
|
}
|
|
|
|
export const Reactive =(obj, id)=>
|
|
{
|
|
context.StartID(id);
|
|
VanX.reactive(obj);
|
|
context.StartID();
|
|
} |