add history

This commit is contained in:
abearxiong 2025-03-29 17:48:38 +08:00
parent 415f008209
commit 69784e8ed4
3 changed files with 62 additions and 5 deletions

View File

@ -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"
},

View File

@ -40,7 +40,7 @@ export const StoreContextProvider = ({
type SimpleObject = Record<string, any>;
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<T> = UseBoundStore<StoreApi<T>>;
useStore.getState = function (id: string) {
const store = useContextKey<any>('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<any>('store');
if (!store) {
console.error('store not found');
return null;
}
store.getStore(id).setState(state);
};
useStore.subscribe = function (fn: any) {
const store = useContextKey<any>('store');
if (!store) {
console.error('store not found');
return null;
}
return store.subscribe(fn);
};
export type BoundStore<T> = UseBoundStore<StoreApi<T>> & {
getState: (id: string) => T;
setState: (id: string, state: T) => void;
subscribe: (fn: (state: T) => void) => () => void;
createStore: (stateCreator: StateCreator<any, [], [], any>) => void;
createIfNotExists: (stateCreator: StateCreator<any, [], [], any>) => void;
};

View File

@ -199,3 +199,31 @@ export class Page {
this.popstate({ state } as any, { type: 'all' });
}
}
/**
* history state
* @returns
*/
export const getHistoryState = <T = Record<string, any>>() => {
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);
};