feat: add page

This commit is contained in:
熊潇 2025-01-02 23:04:01 +08:00
parent 7cb42edc5f
commit c855c7d3d5
3 changed files with 30 additions and 8 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@kevisual/store",
"version": "0.0.1-alpha.8",
"version": "0.0.1-alpha.9",
"main": "dist/store.js",
"module": "dist/store.js",
"types": "dist/store.d.ts",

View File

@ -1,13 +1,14 @@
// 当前的功能把所有的模块注入到windows对象当中
import { useConfigKey, useContextKey } from './web-env.ts';
import { useConfigKey, useConfigKeySync, useContextKeySync, useContextKey } from './web-env.ts';
import { QueryRouterServer } from '@kevisual/router/browser';
import { Page } from './page.ts';
// bind to window, 必须要的获取全局的环境变量
window.useConfigKey = useConfigKey;
window.useConfigKeySync = useConfigKeySync;
window.useContextKey = useContextKey;
window.useContextKeySync = useContextKeySync;
window.Page = Page;
window.QueryRouterServer = QueryRouterServer;
// bind to window, 获取路由对象
useContextKey('app', () => new QueryRouterServer());

View File

@ -7,8 +7,17 @@ const generateRandom = () => {
return crypto.randomUUID();
};
type PageOptions = {
/**
*
*/
path?: string;
/**
* key
*/
key?: string;
/**
* basename
*/
basename?: string;
isListen?: boolean;
};
@ -23,7 +32,9 @@ type CallbackInfo = {
fn: CallFn;
id: string;
} & PageModule;
let currentUrl = location.href;
/**
* basename,path和key
*/
export class Page {
pageModule = new Map<string, PageModule>();
// pathname的第一个路径
@ -43,9 +54,8 @@ export class Page {
this.listen();
}
}
popstate(event?: PopStateEvent, manualOpts?: { id?: string; type: 'singal' | 'all' }) {
const pathname = window.location.pathname;
console.log('popstate', event);
popstate(event?: PopStateEvent, manualOpts?: { id?: string; type: 'singal' | 'all'; pathname?: string }) {
const pathname = manualOpts?.pathname ?? window.location.pathname;
if (manualOpts) {
if (manualOpts.type === 'singal') {
const item = this.callbacks.find((item) => item.id === manualOpts.id);
@ -62,7 +72,17 @@ export class Page {
result && item.fn?.(result.params, event.state, { event, manualOpts });
});
}
/**
* callback中id或者pathname的函数, id优先级高于pathnamelocation.pathname中获取
* @param opts
*/
call(opts?: { id?: string; pathname?: string }) {
this.popstate({ state: window.history.state } as any, { ...opts, type: 'all' });
}
listen() {
if (this.isListen) {
return;
}
this.isListen = true;
window.addEventListener('popstate', this.popstate.bind(this), false);
}
@ -89,7 +109,7 @@ export class Page {
});
}
/**
*
* , pathnamepathname
* @param key
* @param pathname
* @returns
@ -138,6 +158,7 @@ export class Page {
const pathname = opts?.pathname ?? location.pathname;
const result = this.check(key, pathname);
if (result) {
// 如果是手动调用则不需要检查是否相等直接执行而且是执行当前的subscribe的函数
this.popstate({ state: window.history.state } as any, { id, type: 'singal' });
}
}