import React, { createContext, useCallback, useContext, type FC, type ReactNode } from 'react'; import type { ArrayPath, Path, PathValue } from 'react-hook-form'; import { get, set } from '@wener/utils'; import { create as produce } from 'mutative'; import { createStore, useStore, type StoreApi } from 'zustand'; const DefaultContextStore = createStore(() => { return {}; }); const Context = createContext | undefined>(undefined); export const ContextStoreProvider: FC<{ value: StoreApi; children?: ReactNode }> = ({ value, children }) => { return {children}; }; function getContextStore() { return DefaultContextStore; } export function useContextStore>(): UseContextStoreReturn { const store = useContext(Context) ?? DefaultContextStore; return { store, set(path: string, value: any) { store.setState( produce((s: any) => { set(s, path, value, false); }), ); }, get(path: string): any { return get(store.getState(), path); }, useWatch(path: string): any { return useStore( store, useCallback((s) => get(s, path), [path]), ); }, }; } export interface UseContextStoreReturn = Record> { store: StoreApi; set

| ArrayPath, V extends PathValue>(type: P, payload: V): void; get

| ArrayPath, V extends PathValue>(path: P): V; useWatch

| ArrayPath, V extends PathValue>(path: P): V; }