able-baker/hmr-signal.tsx

47 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2023-10-14 23:47:20 -04:00
import * as SignalsParts from "signals-original";
2023-10-23 11:00:00 -04:00
import DeepEqual from "https://esm.sh/deep-eql@4.1.3";
2023-10-14 23:47:20 -04:00
2023-10-16 12:33:07 -04:00
type Entry<T> = [signal:SignalsParts.Signal<T>, initArg:T];
2023-10-14 23:47:20 -04:00
2023-10-16 12:33:07 -04:00
function ProxyGroup<T>(inFunc:(initArg:T)=>SignalsParts.Signal<T>)
2023-10-16 10:27:22 -04:00
{
2023-10-16 12:33:07 -04:00
let recordEntry:Entry<T>[] = [];
let recordEntryNew:Entry<T>[] = [];
let recordIndex = 0;
const reset =()=> recordIndex = 0;
const swap =()=>
2023-10-16 10:27:22 -04:00
{
2023-10-16 12:33:07 -04:00
recordEntry = recordEntryNew;
recordEntryNew = [] as Entry<T>[];
};
const proxy =(arg:T)=>
2023-10-16 10:27:22 -04:00
{
2023-10-16 12:33:07 -04:00
const lookupOld = recordEntry[recordIndex];
2023-10-23 11:00:00 -04:00
if(lookupOld && DeepEqual(lookupOld[1], arg))
2023-10-16 12:33:07 -04:00
{
recordEntryNew[recordIndex] = lookupOld;
recordIndex++;
return lookupOld[0];
}
else
{
const sig = inFunc(arg);
recordEntryNew[recordIndex] = [sig, arg];
recordEntry[recordIndex] = [sig, arg];
recordIndex++;
return sig;
}
};
return {reset, swap, proxy};
}
export const GroupSignal = ProxyGroup(SignalsParts.signal);
export const GroupSignalHook = ProxyGroup(SignalsParts.useSignal);
2023-10-16 10:27:22 -04:00
2023-10-16 12:33:07 -04:00
const proxySignal = GroupSignal.proxy;
const proxySignalHook = GroupSignalHook.proxy;
2023-10-14 23:47:20 -04:00
export * from "signals-original";
2023-10-16 12:33:07 -04:00
export { proxySignal as signal, proxySignalHook as useSignal };
export default {...SignalsParts, signal:proxySignal, useSignal:proxySignalHook};