import { Container } from "../packages"; type Var = { [key in string]: any }; type Key = Container; const stackMap = new WeakMap(); const getStack = (key: Key) => { const stack = stackMap.get(key); return stack || null; }; const getCurrentVar = (key: Key) => { const stack = getStack(key); if (stack) { return stack[stack.length - 1]; } else { throw "当前 key 不存在变量桟"; } }; export const varMount = (key: Key) => { const stack = getStack(key); if (!stack) { stackMap.set(key, []); } else { throw "当前 key 已挂载变量"; } }; export const varPush = (key: Key, data: Var) => { const stack = getStack(key); if (stack) { stack.push(data); } }; export const varPop = (key: Key) => { const stack = getStack(key); if (stack?.length) { stack.pop(); } }; export const varAdd = (key: Key, k: string, v: any) => { const current = getCurrentVar(key); if (k in current) { throw `${key}变量已存在${current}`; } else { current[k] = v; } }; export const varSet = (key: Key, k: string, v: any) => { const current = getCurrentVar(key); if (k in current) { throw `${key}变量已存在${current}`; } else { current[k] = v; } }; export const varDel = (key: Key, k: string) => { const current = getCurrentVar(key); if (!(k in current)) { throw `${key}变量不存在${current}`; } else { delete current[k]; } }; const keyStack: Key[] = []; export let currentVar: Var; export const useVar = (key: Key) => { keyStack.push(key); currentVar = getCurrentVar(keyStack[keyStack.length - 1]); return () => { keyStack.pop(); if (keyStack.length) { currentVar = getCurrentVar(keyStack[keyStack.length - 1]); } else { currentVar = null; } }; };