import { Selector } from "../data/Selector"; import { BindingObject, isBindingObject } from "../data/Binding"; import { expression } from "../data/Expression"; import { getSelector } from "../data/getSelector"; import { Ref } from "../data/Ref"; import { stringTemplate } from "../data/StringTemplate"; import { View } from "../data/View"; import { getCurrentInstance } from "../ui/createFunctionalComponent"; import { GetSet, Prop } from "../ui/Prop"; import { hasFunctionAtKey, hasStringAtKey } from "../util/hasKey"; import { isObject } from "../util/isObject"; export function useStore(): View { return getCurrentInstance().store; } export function useStoreMethods(): ReturnType { return getCurrentInstance().store.getMethods(); } export type RefInput = Prop | Ref; export function ref(input: BindingObject): GetSet; export function ref(input: Ref): GetSet; export function ref(input: Prop): Selector; export function ref(info: unknown): GetSet | Selector { if (isObject(info)) { if (isBindingObject(info)) return useStore().ref(info.bind, info.defaultValue); if (hasFunctionAtKey(info, "get")) return info as unknown as Ref; if (hasFunctionAtKey(info, "memoize")) return info as unknown as Selector; if (hasStringAtKey(info, "expr")) { let store = useStore(); let selector = expression(info.expr).memoize(); return new Ref({ get: () => selector(store.getData()), set: (info as any).set }) as unknown as Selector; } if (hasStringAtKey(info, "tpl")) { let store = useStore(); let selector = stringTemplate(info.tpl).memoize(); return new Ref({ get: () => selector(store.getData()) as T, set: (info as any).set, }) as unknown as Selector; } } return getSelector(info); }