UNPKG

mt-flowbite-react

Version:

Official React components built for Flowbite and Tailwind CSS

53 lines (52 loc) 1.8 kB
'use client'; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { createContext, useContext, useRef } from 'react'; import { create, useStore } from 'zustand'; import { persist, subscribeWithSelector } from 'zustand/middleware'; export const createViewSlice = (set, get, store) => { return { ...store, }; }; export const createViewStore = (initProps) => { return create()(persist(subscribeWithSelector((...a) => ({ ...createViewSlice(...a), ...initProps, })), { name: `view-${initProps?.slug || initProps?.view?.id || 'unknow-view'}`, version: 1, skipHydration: true, onRehydrateStorage(state) { }, migrate(persistedState, version) { // console.log("version", version, persistedState) return persistedState; }, })); }; //------------------------------------------------------------------------------------------- // 一般情况下 的Context 及其 hook const Context = createContext(null); export function ViewProvider({ children, ...props }) { const storeRef = useRef(); if (!storeRef.current) { // console.log("create store:", props.id) storeRef.current = createViewStore(props); } return (_jsxs(Context.Provider, { value: storeRef.current, children: [children, _jsx(SubscriptionSetup, {})] })); } function SubscriptionSetup() { const store = useViewStore(); return _jsx("div", { className: "bg-blue-500" }); } export function useViewStore(selector, equals) { const store = useContext(Context); if (!store) throw new Error('Missing ViewProvider'); if (selector) { // eslint-disable-next-line return useStore(store, selector, equals); } else { return store; } }