12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import { computed, shallowReactive, isRef, watch } from "vue";
- import type { ComputedRef, UnwrapRef } from "vue";
- export type Stack<T> = {
- push: (raw: T) => () => void;
- pop: () => T;
- length: ComputedRef<number>;
- current: ComputedRef<T>;
- };
- // 栈构建
- export const stackFactory = <T>(initVal?: T, debug?: boolean): Stack<T> => {
- const stack = shallowReactive([]) as Array<T>;
- if (initVal !== void 0) {
- stack.push(initVal);
- }
- return {
- push(raw: T) {
- stack.push(raw);
- if (debug) {
- console.warn('push', raw)
- }
- return () => {
- const index = stack.indexOf(raw);
- ~index && stack.splice(index, 1);
- if (debug) {
- console.warn('pop', raw)
- console.warn('current', stack)
- }
- };
- },
- pop() {
- let ret = stack[stack.length-- - 1];
- if (debug) {
- console.warn('pop current', stack)
- }
- return ret;
- },
- current: computed(() => {
- return stack[stack.length - 1];
- }),
- length: computed(() => stack.length),
- };
- };
- export const flatStacksValue = <T extends { [key in any]: Stack<any> }>(
- stacks: T
- ) => {
- const result = {} as {
- [key in keyof T]: UnwrapRef<T[key]["current"]["value"]>;
- };
- const keys = Object.keys(stacks) as Array<keyof T>;
- const proxy = new Proxy(result, {
- get(_, key: keyof T) {
- if (keys.includes(key)) {
- return isRef(stacks[key].current.value)
- ? (stacks[key].current.value as any).value
- : stacks[key].current.value;
- } else {
- return stacks[key];
- }
- },
- set(_, key: keyof T, val) {
- if (isRef(stacks[key].current.value)) {
- (stacks[key].current.value as any).value = val;
- } else {
- (stacks[key].current.value as any) = val;
- }
- return true;
- },
- });
- return proxy;
- };
|