diff --git a/package.json b/package.json index e46ccd0..77b2a47 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/store", - "version": "0.0.3", + "version": "0.0.4", "main": "dist/store.js", "module": "dist/store.js", "types": "dist/store.d.ts", @@ -63,7 +63,7 @@ "import": "./dist/web-context.js", "require": "./dist/web-context.js" }, - "./page": { + "./web-page.js": { "import": "./dist/web-page.js", "require": "./dist/web-page.js" }, diff --git a/react/src/Store.tsx b/react/src/Store.tsx index 59d1f19..81ca711 100644 --- a/react/src/Store.tsx +++ b/react/src/Store.tsx @@ -40,7 +40,7 @@ export const StoreContextProvider = ({ type SimpleObject = Record; -export const useStore = (selector: any): any => { +export const useStore = function (selector: any): any { const store = useContext(StoreContext); const allState = store.getState(); const selectedState = selector ? selector(allState) : allState; @@ -58,5 +58,34 @@ export const useStore = (selector: any): any => { return state; }; - -export type BoundStore = UseBoundStore>; +useStore.getState = function (id: string) { + const store = useContextKey('store'); + if (!store) { + console.error('store not found'); + return null; + } + return store.getStore(id).getState(); +}; +useStore.setState = function (id: string, state: any) { + const store = useContextKey('store'); + if (!store) { + console.error('store not found'); + return null; + } + store.getStore(id).setState(state); +}; +useStore.subscribe = function (fn: any) { + const store = useContextKey('store'); + if (!store) { + console.error('store not found'); + return null; + } + return store.subscribe(fn); +}; +export type BoundStore = UseBoundStore> & { + getState: (id: string) => T; + setState: (id: string, state: T) => void; + subscribe: (fn: (state: T) => void) => () => void; + createStore: (stateCreator: StateCreator) => void; + createIfNotExists: (stateCreator: StateCreator) => void; +}; diff --git a/src/page.ts b/src/page.ts index 70c4fe8..2fe1f25 100644 --- a/src/page.ts +++ b/src/page.ts @@ -199,3 +199,31 @@ export class Page { this.popstate({ state } as any, { type: 'all' }); } } +/** + * 获取history state + * @returns + */ +export const getHistoryState = >() => { + const history = window.history; + const state = history.state || {}; + return state as T; +}; + +/** + * 设置history state + * @param state + */ +export const setHistoryState = (state: any) => { + const history = window.history; + const oldState = getHistoryState(); + // 只更新 state 而不改变 URL + history.replaceState({ ...oldState, ...state }, '', window.location.href); +}; + +/** + * 清除history state + */ +export const clearHistoryState = () => { + const history = window.history; + history.replaceState({}, '', window.location.href); +};