Compare commits
5 Commits
889c238c87
...
b5dde4e823
Author | SHA1 | Date | |
---|---|---|---|
b5dde4e823 | |||
a4f03c76eb | |||
4148d162e4 | |||
ebf0b230b1 | |||
f62254af26 |
3
.npmrc
Normal file
3
.npmrc
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
//npm.xiongxiao.me/:_authToken=${ME_NPM_TOKEN}
|
||||||
|
@abearxiong:registry=https://npm.pkg.github.com
|
||||||
|
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
|
99
demo/index.html
Normal file
99
demo/index.html
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Demo Page</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>Welcome to the Demo Page</h1>
|
||||||
|
<p>This is a basic HTML template.</p>
|
||||||
|
<script src="./src/index.ts" type="module"></script>
|
||||||
|
<form action="/submit" method="POST">
|
||||||
|
<label for="browser">选择浏览器:</label>
|
||||||
|
<input list="browsers" id="browser" name="browser" />
|
||||||
|
<datalist id="browsers">
|
||||||
|
<option value="Chrome">
|
||||||
|
<option value="Firefox">
|
||||||
|
<option value="Safari">
|
||||||
|
<option value="Edge">
|
||||||
|
</datalist>
|
||||||
|
<button type="submit">提交</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.custom-datalist-wrapper {
|
||||||
|
position: relative;
|
||||||
|
width: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-datalist-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-datalist-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: white;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
max-height: 150px;
|
||||||
|
overflow-y: auto;
|
||||||
|
display: none;
|
||||||
|
z-index: 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-datalist-dropdown.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-datalist-item {
|
||||||
|
padding: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-datalist-item:hover {
|
||||||
|
background-color: #f0f0f0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="custom-datalist-wrapper">
|
||||||
|
<input type="text" class="custom-datalist-input" placeholder="选择或输入..." oninput="filterDatalist(this)" />
|
||||||
|
<div class="custom-datalist-dropdown" id="datalist-dropdown">
|
||||||
|
<div class="custom-datalist-item" onclick="selectDatalistItem(this)">Apple</div>
|
||||||
|
<div class="custom-datalist-item" onclick="selectDatalistItem(this)">Banana</div>
|
||||||
|
<div class="custom-datalist-item" onclick="selectDatalistItem(this)">Cherry</div>
|
||||||
|
<div class="custom-datalist-item" onclick="selectDatalistItem(this)">Date</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function filterDatalist(input) {
|
||||||
|
const filter = input.value.toLowerCase();
|
||||||
|
const dropdown = document.getElementById('datalist-dropdown');
|
||||||
|
const items = dropdown.querySelectorAll('.custom-datalist-item');
|
||||||
|
|
||||||
|
dropdown.classList.add('active');
|
||||||
|
items.forEach(item => {
|
||||||
|
item.style.display = item.textContent.toLowerCase().includes(filter) ? 'block' : 'none';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectDatalistItem(item) {
|
||||||
|
const input = document.querySelector('.custom-datalist-input');
|
||||||
|
input.value = item.textContent;
|
||||||
|
|
||||||
|
const dropdown = document.getElementById('datalist-dropdown');
|
||||||
|
dropdown.classList.remove('active');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
16
demo/package.json
Normal file
16
demo/package.json
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"name": "demo",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "abearxiong <xiongxiao@xiongxiao.me>",
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
"dependencies": {
|
||||||
|
"@kevisual/store": "link:.."
|
||||||
|
}
|
||||||
|
}
|
23
demo/src/index.ts
Normal file
23
demo/src/index.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
console.log('index.js');
|
||||||
|
import { Page } from '@kevisual/store/page';
|
||||||
|
|
||||||
|
const page = new Page({
|
||||||
|
isListen: true,
|
||||||
|
});
|
||||||
|
page.addPage('/', 'home');
|
||||||
|
page.addPage('/:id', 'user');
|
||||||
|
page.subscribe(
|
||||||
|
'home',
|
||||||
|
(params, state) => {
|
||||||
|
console.log('home', params, 'state', state);
|
||||||
|
return;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
page.subscribe('user', (params, state) => {
|
||||||
|
console.log('user', params, 'state', state);
|
||||||
|
return;
|
||||||
|
});
|
||||||
|
|
||||||
|
// page.navigate('/c', { id: 3 });
|
||||||
|
// page.navigate('/c', { id: 2 });
|
||||||
|
// page.refresh();
|
44
package.json
44
package.json
@ -1,14 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "@kevisual/store",
|
"name": "@kevisual/store",
|
||||||
"version": "0.0.1-alpha.1",
|
"version": "0.0.1-alpha.5",
|
||||||
"main": "dist/index.js",
|
"main": "dist/store.js",
|
||||||
"module": "dist/index.js",
|
"module": "dist/store.js",
|
||||||
"types": "dist/index.d.ts",
|
"types": "dist/store.d.ts",
|
||||||
"private": false,
|
"private": false,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"dev": "rollup -c -w",
|
||||||
"build": "npm run clean && rollup -c",
|
"build": "npm run clean && rollup -c",
|
||||||
"test": "NODE_ENV=development node --experimental-vm-modules node_modules/jest/bin/jest.js --detectOpenHandles",
|
"build:app": "npm run build && rsync dist/* ../deploy/dist",
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@ -29,12 +30,13 @@
|
|||||||
"fast-deep-equal": "^3.1.3",
|
"fast-deep-equal": "^3.1.3",
|
||||||
"immer": "^10.1.1",
|
"immer": "^10.1.1",
|
||||||
"lodash-es": "^4.17.21",
|
"lodash-es": "^4.17.21",
|
||||||
"nanoid": "^5.0.7",
|
"nanoid": "^5.0.9",
|
||||||
"rollup": "^4.24.0",
|
"rollup": "^4.27.4",
|
||||||
|
"rollup-plugin-dts": "^6.1.1",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
"tslib": "^2.8.0",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.6.3",
|
"typescript": "^5.7.2",
|
||||||
"zustand": "^5.0.0"
|
"zustand": "^5.0.1"
|
||||||
},
|
},
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"access": "public"
|
"access": "public"
|
||||||
@ -47,6 +49,26 @@
|
|||||||
".": {
|
".": {
|
||||||
"import": "./dist/store.js",
|
"import": "./dist/store.js",
|
||||||
"require": "./dist/store.js"
|
"require": "./dist/store.js"
|
||||||
}
|
},
|
||||||
|
"./config": {
|
||||||
|
"import": "./dist/web-config.js",
|
||||||
|
"require": "./dist/web-config.js"
|
||||||
|
},
|
||||||
|
"./context": {
|
||||||
|
"import": "./dist/web-context.js",
|
||||||
|
"require": "./dist/web-context.js"
|
||||||
|
},
|
||||||
|
"./page": {
|
||||||
|
"import": "./dist/web-page.js",
|
||||||
|
"require": "./dist/web-page.js"
|
||||||
|
},
|
||||||
|
"./web": {
|
||||||
|
"import": "./dist/web.js",
|
||||||
|
"require": "./dist/web.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"eventemitter3": "^5.0.1",
|
||||||
|
"path-to-regexp": "^8.2.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,25 +3,94 @@
|
|||||||
import typescript from '@rollup/plugin-typescript';
|
import typescript from '@rollup/plugin-typescript';
|
||||||
import resolve from '@rollup/plugin-node-resolve';
|
import resolve from '@rollup/plugin-node-resolve';
|
||||||
import commonjs from '@rollup/plugin-commonjs';
|
import commonjs from '@rollup/plugin-commonjs';
|
||||||
|
import { dts } from 'rollup-plugin-dts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {import('rollup').RollupOptions}
|
* @type {import('rollup').RollupOptions}
|
||||||
*/
|
*/
|
||||||
export default [
|
export default [
|
||||||
{
|
{
|
||||||
input: 'src/index.ts', // TypeScript 入口文件
|
input: 'src/store.ts', // TypeScript 入口文件
|
||||||
output: {
|
output: {
|
||||||
file: 'dist/store.js', // 输出文件
|
file: 'dist/store.js', // 输出文件
|
||||||
format: 'es', // 输出格式设置为 ES 模块
|
format: 'es', // 输出格式设置为 ES 模块
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
|
resolve({ browser: true }), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
|
||||||
commonjs(), // 使用 @rollup/plugin-commonjs 解析 CommonJS 模块
|
commonjs(), // 使用 @rollup/plugin-commonjs 解析 CommonJS 模块
|
||||||
typescript({
|
typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
|
||||||
allowImportingTsExtensions: true,
|
|
||||||
noEmit: true,
|
|
||||||
exclude: [],
|
|
||||||
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
input: 'src/store.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/store.d.ts',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [dts()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web-config.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-config.js',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [resolve({ browser: true }), commonjs(), typescript()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web-config.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-config.d.ts',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [dts()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web-context.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-context.js',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [resolve({ browser: true }), commonjs(), typescript()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web-context.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-context.d.ts',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [dts()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/page.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-page.js',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [resolve({ browser: true }), commonjs(), typescript()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/page.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web-page.d.ts',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [dts()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web.js',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [resolve({ browser: true }), commonjs(), typescript()],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: 'src/web.ts',
|
||||||
|
output: {
|
||||||
|
file: 'dist/web.d.ts',
|
||||||
|
format: 'es',
|
||||||
|
},
|
||||||
|
plugins: [dts()],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
201
src/page.ts
Normal file
201
src/page.ts
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
import { getPathKey } from '@/utils/path-key.ts';
|
||||||
|
import { match } from 'path-to-regexp';
|
||||||
|
import deepEqual from 'fast-deep-equal';
|
||||||
|
|
||||||
|
type PageOptions = {
|
||||||
|
path?: string;
|
||||||
|
key?: string;
|
||||||
|
basename?: string;
|
||||||
|
isListen?: boolean;
|
||||||
|
};
|
||||||
|
type PageModule = {
|
||||||
|
// 模块的key,如 user,定义模块的唯一标识
|
||||||
|
key: string;
|
||||||
|
// 模块的path路径,如 /user/:id,match的时候会用到
|
||||||
|
path: string;
|
||||||
|
};
|
||||||
|
type CallFn = (params: Record<string, any>, state?: any, e?: any) => any;
|
||||||
|
type CallbackInfo = {
|
||||||
|
fn: CallFn;
|
||||||
|
id: string;
|
||||||
|
} & PageModule;
|
||||||
|
export class Page {
|
||||||
|
pageModule = new Map<string, PageModule>();
|
||||||
|
// pathname的第一个路径
|
||||||
|
path: string;
|
||||||
|
// pathname的第二个路径
|
||||||
|
key: string;
|
||||||
|
basename: string;
|
||||||
|
isListen: boolean;
|
||||||
|
callbacks = [] as CallbackInfo[];
|
||||||
|
constructor(opts?: PageOptions) {
|
||||||
|
const pathKey = getPathKey();
|
||||||
|
this.path = opts?.path ?? pathKey.path;
|
||||||
|
this.key = opts?.key ?? pathKey.key;
|
||||||
|
this.basename = opts?.basename ?? `/${this.path}/${this.key}`;
|
||||||
|
const isListen = opts?.isListen ?? true;
|
||||||
|
if (isListen) {
|
||||||
|
this.listen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
popstate(event?: PopStateEvent, manualOpts?: { id?: string; type: 'singal' | 'all' }) {
|
||||||
|
const pathname = window.location.pathname;
|
||||||
|
if (manualOpts) {
|
||||||
|
if (manualOpts.type === 'singal') {
|
||||||
|
const item = this.callbacks.find((item) => item.id === manualOpts.id);
|
||||||
|
if (item) {
|
||||||
|
const result = this.check(item.key, pathname);
|
||||||
|
result && item.fn?.(result.params, event.state, { event });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// manual 为true时,表示手动调用,不需要检查是否相等
|
||||||
|
this.callbacks.forEach((item) => {
|
||||||
|
const result = this.check(item.key, pathname);
|
||||||
|
result && item.fn?.(result.params, event.state, { event, manualOpts });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
listen() {
|
||||||
|
this.isListen = true;
|
||||||
|
window.addEventListener('popstate', this.popstate.bind(this), false);
|
||||||
|
}
|
||||||
|
unlisten() {
|
||||||
|
this.isListen = false;
|
||||||
|
window.removeEventListener('popstate', this.popstate.bind(this), false);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param path 路径
|
||||||
|
* @param key
|
||||||
|
*/
|
||||||
|
addPage(path: string, key?: string) {
|
||||||
|
this.pageModule.set(key, { path, key });
|
||||||
|
}
|
||||||
|
addObjectPages(pages: Record<string, string>) {
|
||||||
|
Object.keys(pages).forEach((key) => {
|
||||||
|
this.addPage(pages[key], key);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
addPages(pages: { path: string; key?: string }[]) {
|
||||||
|
pages.forEach((item) => {
|
||||||
|
this.addPage(item.path, item.key);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 检查当前路径是否匹配
|
||||||
|
* @param key
|
||||||
|
* @param pathname
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
check(key: string, pathname?: string): false | { pathname: string; params: Record<string, any> } {
|
||||||
|
const has = this.pageModule.has(key);
|
||||||
|
if (!has) {
|
||||||
|
console.error(`PageModule ${key} not found`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pageModule = this.pageModule.get(key);
|
||||||
|
if (!pageModule) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const location = window.location;
|
||||||
|
const _pathname = pathname || location.pathname;
|
||||||
|
const cur = _pathname.replace(this.basename, '');
|
||||||
|
const routeMatch = match(pageModule.path, { decode: decodeURIComponent });
|
||||||
|
const result = routeMatch(cur);
|
||||||
|
let params = {};
|
||||||
|
if (result) {
|
||||||
|
result.path;
|
||||||
|
params = result.params;
|
||||||
|
return { pathname: _pathname, params };
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 订阅path监听事件
|
||||||
|
* @param key
|
||||||
|
* @param fn
|
||||||
|
* @param opts
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
subscribe(key: string, fn?: CallFn, opts?: { pathname?: string; runImmediately?: boolean; id?: string }) {
|
||||||
|
const runImmediately = opts?.runImmediately ?? true; // 默认立即执行
|
||||||
|
const id = opts?.id ?? Math.random().toString(36).slice(2);
|
||||||
|
const path = this.pageModule.get(key)?.path;
|
||||||
|
if (!path) {
|
||||||
|
console.error(`PageModule ${key} not found`);
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
|
this.callbacks.push({ key, fn, id: id, path });
|
||||||
|
if (runImmediately) {
|
||||||
|
const location = window.location;
|
||||||
|
const pathname = opts?.pathname ?? location.pathname;
|
||||||
|
const result = this.check(key, pathname);
|
||||||
|
if (result) {
|
||||||
|
this.popstate({ state: window.history.state } as any, { id, type: 'singal' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
this.callbacks = this.callbacks.filter((item) => item.id !== id);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 返回当前路径,不包含basename
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
getPath() {
|
||||||
|
const location = window.location;
|
||||||
|
const pathname = location.pathname;
|
||||||
|
return pathname.replace(this.basename, '');
|
||||||
|
}
|
||||||
|
getAppPath() {
|
||||||
|
return this.path;
|
||||||
|
}
|
||||||
|
getAppKey() {
|
||||||
|
return this.key;
|
||||||
|
}
|
||||||
|
decodePath(path: string) {
|
||||||
|
return decodeURIComponent(path);
|
||||||
|
}
|
||||||
|
encodePath(path: string) {
|
||||||
|
return encodeURIComponent(path);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 如果state 和 pathname都相等,则不执行popstate
|
||||||
|
* @param path
|
||||||
|
* @param state
|
||||||
|
* @param check
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
navigate(path: string | number, state?: any, check?: boolean) {
|
||||||
|
if (typeof path === 'number') {
|
||||||
|
window.history.go(path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const location = window.location;
|
||||||
|
const pathname = location.pathname;
|
||||||
|
|
||||||
|
const newPathname = new URL(this.basename + path, location.href).pathname;
|
||||||
|
if (pathname === newPathname) {
|
||||||
|
if (deepEqual(state, window.history.state)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.history.pushState(state, '', this.basename + path);
|
||||||
|
let _check = check ?? true;
|
||||||
|
if (_check) {
|
||||||
|
this.popstate({ state } as any, { type: 'all' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
replace(path: string, state?: any, check?: boolean) {
|
||||||
|
let _check = check ?? true;
|
||||||
|
window.history.replaceState(state, '', this.basename + path);
|
||||||
|
if (_check) {
|
||||||
|
this.popstate({ state } as any, { type: 'all' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refresh() {
|
||||||
|
const state = window.history.state;
|
||||||
|
this.popstate({ state } as any, { type: 'all' });
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,11 @@ import { shallow } from 'zustand/shallow';
|
|||||||
import { get } from 'lodash-es';
|
import { get } from 'lodash-es';
|
||||||
import deepEqual from 'fast-deep-equal';
|
import deepEqual from 'fast-deep-equal';
|
||||||
|
|
||||||
|
export const create = createZutandStore;
|
||||||
|
export type { StateCreator, StoreApi };
|
||||||
|
|
||||||
type Listener = (state: any, prevState: any) => void;
|
type Listener = (state: any, prevState: any) => void;
|
||||||
|
|
||||||
export class StoreManager {
|
export class StoreManager {
|
||||||
stores: Record<string, any>;
|
stores: Record<string, any>;
|
||||||
constructor() {
|
constructor() {
|
||||||
@ -14,7 +18,7 @@ export class StoreManager {
|
|||||||
return this.stores[key];
|
return this.stores[key];
|
||||||
}
|
}
|
||||||
this.stores[key] = createZutandStore(initialStore);
|
this.stores[key] = createZutandStore(initialStore);
|
||||||
return this.stores[key];
|
return this.stores[key] as StoreApi<T>;
|
||||||
}
|
}
|
||||||
create<T = any, U extends T = any>(initialStore: StateCreator<T, [], [], U>, key: string) {
|
create<T = any, U extends T = any>(initialStore: StateCreator<T, [], [], U>, key: string) {
|
||||||
return this.createStore(initialStore, key);
|
return this.createStore(initialStore, key);
|
||||||
@ -31,8 +35,14 @@ export class StoreManager {
|
|||||||
shallow(objA: any, objB: any) {
|
shallow(objA: any, objB: any) {
|
||||||
return shallow(objA, objB);
|
return shallow(objA, objB);
|
||||||
}
|
}
|
||||||
subscribe(fn: Listener, { key, path, deep }: { key: string; path: string; deep?: boolean }) {
|
/**
|
||||||
const _store = this.stores[key] as StoreApi<any>;
|
* path 为可以是 '.a.b.c'的形式
|
||||||
|
* @param fn
|
||||||
|
* @param param1
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
subscribe(fn: Listener, { key, path, deep, store }: { key: string; path: string; deep?: boolean; store?: StoreApi<any> }) {
|
||||||
|
const _store = store || (this.stores[key] as StoreApi<any>);
|
||||||
if (!_store) {
|
if (!_store) {
|
||||||
console.error('no store', key);
|
console.error('no store', key);
|
||||||
return;
|
return;
|
||||||
@ -59,7 +69,40 @@ export class StoreManager {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// export const store = new StoreManager();
|
||||||
|
|
||||||
export const store = new StoreManager();
|
type FnListener<T = any> = (state: T, prevState: T) => void;
|
||||||
|
type SubOptions = {
|
||||||
|
path?: string;
|
||||||
|
deep?: boolean;
|
||||||
|
store?: StoreApi<any>;
|
||||||
|
};
|
||||||
|
export const sub = <T = any>(fn: FnListener<T>, { path, deep, store }: SubOptions) => {
|
||||||
|
if (!store) {
|
||||||
|
console.error('no store');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return store.subscribe((newState: T, oldState: T) => {
|
||||||
|
try {
|
||||||
|
const newPath = get(newState, path);
|
||||||
|
const oldPath = get(oldState, path);
|
||||||
|
if (!newPath && !oldPath) {
|
||||||
|
// 都不存在
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (deep) {
|
||||||
|
if (!deepEqual(newPath, oldPath)) {
|
||||||
|
fn?.(newState, oldState);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!shallow(newPath, oldPath)) {
|
||||||
|
fn?.(newState, oldState);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('subscribe error', e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export { shallow, deepEqual };
|
export { shallow, deepEqual };
|
7
src/utils/path-key.ts
Normal file
7
src/utils/path-key.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
export const getPathKey = () => {
|
||||||
|
// 从localtion.href的路径中,/a/b 中 a为path,b为key
|
||||||
|
const pathname = location.pathname;
|
||||||
|
const paths = pathname.split('/');
|
||||||
|
const [path, key] = paths.slice(1);
|
||||||
|
return { path, key, id: path + '---' + key, prefix: `/${path}/${key}` };
|
||||||
|
};
|
41
src/web-config.ts
Normal file
41
src/web-config.ts
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import { getPathKey } from './utils/path-key.ts';
|
||||||
|
|
||||||
|
type GlobalConfig = {
|
||||||
|
name?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
export const useConfig = (initConfig?: GlobalConfig) => {
|
||||||
|
const config: GlobalConfig = (window as any).config;
|
||||||
|
const _config = config || initConfig;
|
||||||
|
!config && ((window as any)['config'] = _config);
|
||||||
|
return _config;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useConfigKey = <T>(key: string, init?: () => T): T => {
|
||||||
|
const _config = useConfig({});
|
||||||
|
if (key && init) {
|
||||||
|
_config[key] = init();
|
||||||
|
return _config[key] as any;
|
||||||
|
}
|
||||||
|
if (key) {
|
||||||
|
return _config[key];
|
||||||
|
}
|
||||||
|
return _config as any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useConfigKeySync = async <T = any>(key: string, init?: () => Promise<T>): Promise<T> => {
|
||||||
|
const _config = useConfig({});
|
||||||
|
if (key && init) {
|
||||||
|
_config[key] = await init();
|
||||||
|
return _config[key] as any;
|
||||||
|
}
|
||||||
|
if (key) {
|
||||||
|
return _config[key];
|
||||||
|
}
|
||||||
|
return _config as any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const usePageConfig = (init?: () => {}) => {
|
||||||
|
const { id } = getPathKey();
|
||||||
|
return useConfigKey(id, init);
|
||||||
|
};
|
41
src/web-context.ts
Normal file
41
src/web-context.ts
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import { getPathKey } from './utils/path-key.ts';
|
||||||
|
|
||||||
|
type GlobalContext = {
|
||||||
|
name?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
export const useContext = (initContext?: GlobalContext) => {
|
||||||
|
const context: GlobalContext = (window as any).context;
|
||||||
|
const _context = context || initContext;
|
||||||
|
!context && ((window as any)['context'] = _context);
|
||||||
|
return _context;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useContextKey = <T>(key: string, init?: () => T): T => {
|
||||||
|
const _context = useContext({});
|
||||||
|
if (key && init) {
|
||||||
|
_context[key] = init();
|
||||||
|
return _context[key] as any;
|
||||||
|
}
|
||||||
|
if (key) {
|
||||||
|
return _context[key];
|
||||||
|
}
|
||||||
|
return _context as any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useContextKeySync = async <T = any>(key: string, init?: () => Promise<T>): Promise<T> => {
|
||||||
|
const _context = useContext({});
|
||||||
|
if (key && init) {
|
||||||
|
_context[key] = await init();
|
||||||
|
return _context[key] as any;
|
||||||
|
}
|
||||||
|
if (key) {
|
||||||
|
return _context[key];
|
||||||
|
}
|
||||||
|
return _context as any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const usePageContext = (init?: () => {}) => {
|
||||||
|
const { id } = getPathKey();
|
||||||
|
return useContextKey(id, init);
|
||||||
|
};
|
8
src/web.ts
Normal file
8
src/web.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export * from './page.ts';
|
||||||
|
export * from './web-context.ts';
|
||||||
|
export * from './web-config.ts';
|
||||||
|
|
||||||
|
export * from 'nanoid';
|
||||||
|
export * from 'path-to-regexp';
|
||||||
|
|
||||||
|
export * from 'eventemitter3';
|
@ -11,7 +11,7 @@
|
|||||||
"typeRoots": [
|
"typeRoots": [
|
||||||
"node_modules/@types",
|
"node_modules/@types",
|
||||||
],
|
],
|
||||||
"declaration": true,
|
"declaration": false,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"moduleResolution": "NodeNext",
|
"moduleResolution": "NodeNext",
|
||||||
|
Loading…
x
Reference in New Issue
Block a user