@e7w/easy-model 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,42 +1,533 @@
1
1
  # easy-model
2
2
 
3
- 一个简单的react状态管理库
3
+ 一个功能强大的 React 状态管理库,集成了状态管理、IoC 容器、观察者模式和加载器等功能。
4
4
 
5
- ## 示例
5
+ ## 特性
6
+
7
+ - 🚀 **简单易用** - 基于类的状态管理,直观的 API 设计
8
+ - 🔄 **响应式** - 自动观察状态变化,精确更新组件
9
+ - 💉 **IoC 容器** - 内置依赖注入容器,支持命名空间隔离
10
+ - 🎯 **类型安全** - 完整的 TypeScript 支持,基于 Zod 的运行时类型验证
11
+ - ⚡ **性能优化** - 智能缓存和垃圾回收机制
12
+ - 🔧 **加载状态管理** - 内置异步操作加载状态管理
13
+ - 🧩 **模块化** - 可按需使用各个功能模块
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ npm install @e7w/easy-model
19
+ # 或
20
+ yarn add @e7w/easy-model
21
+ # 或
22
+ pnpm add @e7w/easy-model
23
+ ```
24
+
25
+ ## 核心概念
26
+
27
+ ### 1. 状态管理
28
+
29
+ 基于类的状态管理,支持自动观察和响应式更新。
6
30
 
7
31
  ```tsx
8
32
  import { useModel } from "@e7w/easy-model";
9
33
 
10
- class MTest {
34
+ class CounterModel {
11
35
  constructor(public name: string) {}
12
36
 
13
- value = 0;
37
+ count = 0;
38
+
39
+ increment() {
40
+ this.count++;
41
+ }
42
+
43
+ decrement() {
44
+ this.count--;
45
+ }
46
+
47
+ reset() {
48
+ this.count = 0;
49
+ }
50
+ }
51
+
52
+ function Counter() {
53
+ const { count, increment, decrement, reset } = useModel(CounterModel, [
54
+ "main",
55
+ ]);
56
+
57
+ return (
58
+ <div>
59
+ <h2>计数器: {count}</h2>
60
+ <button onClick={increment}>+1</button>
61
+ <button onClick={decrement}>-1</button>
62
+ <button onClick={reset}>重置</button>
63
+ </div>
64
+ );
65
+ }
66
+ ```
67
+
68
+ ### 2. IoC 容器
69
+
70
+ 内置的依赖注入容器,支持值注入、构造函数注入和装饰器注入。
71
+
72
+ ```tsx
73
+ import { Container, VInjection, CInjection, inject } from "@e7w/easy-model";
74
+ import { z } from "zod";
75
+
76
+ // 定义配置 schema
77
+ const configSchema = z.object({
78
+ apiUrl: z.string(),
79
+ timeout: z.number(),
80
+ });
81
+
82
+ const loggerSchema = z.object({
83
+ log: z.function(),
84
+ });
85
+
86
+ // 定义服务类
87
+ class Logger {
88
+ log(message: string) {
89
+ console.log(`[LOG] ${message}`);
90
+ }
91
+ }
92
+
93
+ class ApiService {
94
+ @inject(configSchema)
95
+ config: z.infer<typeof configSchema> = { apiUrl: "", timeout: 0 };
96
+
97
+ @inject(loggerSchema)
98
+ logger: Logger | undefined;
99
+
100
+ async fetchData() {
101
+ this.logger?.log(`Fetching data from ${this.config.apiUrl}`);
102
+ // 实际的 API 调用逻辑
103
+ }
104
+ }
105
+
106
+ function App() {
107
+ return (
108
+ <Container namespace="app">
109
+ {/* 注入配置值 */}
110
+ <VInjection
111
+ schema={configSchema}
112
+ val={{ apiUrl: "https://api.example.com", timeout: 5000 }}
113
+ />
114
+
115
+ {/* 注入构造函数 */}
116
+ <CInjection schema={loggerSchema} ctor={Logger} />
117
+
118
+ <YourComponents />
119
+ </Container>
120
+ );
121
+ }
122
+ ```
123
+
124
+ ### 3. 观察者模式
125
+
126
+ 手动观察对象变化,适用于非 React 环境。注意:`observe` 函数是内部实现,不对外导出。
127
+
128
+ ```tsx
129
+ import { watch } from "@e7w/easy-model";
130
+
131
+ // 注意:observe 函数未导出,这里仅作为概念说明
132
+ // 实际使用中,观察功能已集成在 useModel 和 useInstance 中
133
+
134
+ // 监听对象变化的概念示例(实际需要通过 useModel 等方式)
135
+ const unwatch = watch(someObservableObject, (path, oldValue, newValue) => {
136
+ console.log(`属性 ${path.join(".")} 从 ${oldValue} 变为 ${newValue}`);
137
+ });
138
+
139
+ // 取消监听
140
+ unwatch();
141
+ ```
142
+
143
+ ### 4. 加载状态管理
144
+
145
+ 内置的异步操作加载状态管理,支持全局和局部加载状态。
146
+
147
+ ```tsx
148
+ import { loader } from "@e7w/easy-model";
149
+
150
+ class DataService {
151
+ data: any[] = [];
152
+
153
+ @loader.load(true) // true 表示全局加载状态
154
+ async fetchData() {
155
+ const response = await fetch("/api/data");
156
+ this.data = await response.json();
157
+ return this.data;
158
+ }
159
+
160
+ @loader.load() // 局部加载状态
161
+ async updateItem(id: string, updates: any) {
162
+ const response = await fetch(`/api/data/${id}`, {
163
+ method: "PUT",
164
+ body: JSON.stringify(updates),
165
+ });
166
+ return response.json();
167
+ }
168
+
169
+ @loader.once() // 只执行一次的异步操作
170
+ async initializeApp() {
171
+ // 初始化逻辑
172
+ }
173
+ }
174
+
175
+ function DataComponent() {
176
+ const service = useModel(DataService, []);
177
+ const { globalLoading } = useModel(loader, []);
178
+
179
+ return (
180
+ <div>
181
+ {globalLoading > 0 && <div>全局加载中...</div>}
182
+ <button onClick={() => service.fetchData()}>加载数据</button>
183
+ {service.data.map(item => (
184
+ <div key={item.id}>{item.name}</div>
185
+ ))}
186
+ </div>
187
+ );
188
+ }
189
+ ```
190
+
191
+ ## API 参考
192
+
193
+ ### 状态管理
194
+
195
+ #### `useModel<T>(Constructor: T, args: ConstructorParameters<T>): InstanceType<T>`
196
+
197
+ 创建或获取模型实例,自动观察状态变化并更新组件。
198
+
199
+ **参数:**
200
+
201
+ - `Constructor`: 模型类构造函数
202
+ - `args`: 构造函数参数数组
203
+
204
+ **返回值:** 模型实例,包含所有属性和方法
205
+
206
+ #### `useInstance<T>(instance: T): T`
207
+
208
+ 直接使用现有实例,自动观察状态变化。
209
+
210
+ **参数:**
211
+
212
+ - `instance`: 要观察的对象实例
213
+
214
+ **返回值:** 观察后的实例
215
+
216
+ #### `provide<T>(Constructor: T): T`
217
+
218
+ 为类提供实例缓存和观察功能。
219
+
220
+ **参数:**
221
+
222
+ - `Constructor`: 要包装的类构造函数
223
+
224
+ **返回值:** 包装后的构造函数,支持实例缓存
225
+
226
+ ### IoC 容器
227
+
228
+ #### `Container`
229
+
230
+ IoC 容器组件,提供依赖注入的上下文环境。
231
+
232
+ **Props:**
233
+
234
+ - `namespace?: string` - 命名空间,用于隔离不同的依赖注入环境
235
+ - `children: ReactNode` - 子组件
236
+
237
+ #### `VInjection<T>`
238
+
239
+ 值注入组件,将值注入到容器中。
240
+
241
+ **Props:**
242
+
243
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
244
+ - `val: T` - 要注入的值
245
+
246
+ #### `CInjection<T>`
247
+
248
+ 构造函数注入组件,将构造函数注入到容器中。
249
+
250
+ **Props:**
251
+
252
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
253
+ - `ctor: new () => T` - 要注入的构造函数
254
+
255
+ #### `inject<T>(schema: ZodType<T>, namespace?: string)`
256
+
257
+ 装饰器函数,用于从容器中注入依赖到类属性。
258
+
259
+ **参数:**
260
+
261
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
262
+ - `namespace?: string` - 可选的命名空间
263
+
264
+ **返回值:** 装饰器函数
265
+
266
+ ### 观察者模式
267
+
268
+ #### `watch(target: object, callback: WatchCallback): () => void`
269
+
270
+ 监听对象的变化。
14
271
 
15
- random() {
16
- this.value = Math.random();
272
+ **参数:**
273
+
274
+ - `target: object` - 要监听的对象
275
+ - `callback: WatchCallback` - 变化时的回调函数
276
+
277
+ **返回值:** 取消监听的函数
278
+
279
+ **WatchCallback 类型:**
280
+
281
+ ```typescript
282
+ type WatchCallback = (
283
+ path: Array<string | symbol>,
284
+ oldValue: any,
285
+ newValue: any
286
+ ) => void;
287
+ ```
288
+
289
+ ### 加载器
290
+
291
+ #### `loader.load(isGlobal?: boolean)`
292
+
293
+ 异步方法装饰器,自动管理加载状态。
294
+
295
+ **参数:**
296
+
297
+ - `isGlobal?: boolean` - 是否影响全局加载状态,默认为 false
298
+
299
+ **返回值:** 方法装饰器
300
+
301
+ #### `loader.once()`
302
+
303
+ 确保异步方法只执行一次的装饰器。
304
+
305
+ **返回值:** 方法装饰器
306
+
307
+ #### `loader.isLoading(target: Function): boolean`
308
+
309
+ 检查指定方法是否正在加载中。
310
+
311
+ **参数:**
312
+
313
+ - `target: Function` - 要检查的方法
314
+
315
+ **返回值:** 是否正在加载
316
+
317
+ #### `loader.isGlobalLoading: boolean`
318
+
319
+ 获取全局加载状态。
320
+
321
+ **返回值:** 是否有全局加载正在进行
322
+
323
+ #### `loader.globalLoading: number`
324
+
325
+ 获取当前全局加载的数量。
326
+
327
+ **返回值:** 正在进行的全局加载数量
328
+
329
+ #### `finalizationRegistry(model: object)`
330
+
331
+ 为模型注册垃圾回收回调。
332
+
333
+ **参数:**
334
+
335
+ - `model: object` - 要监听垃圾回收的对象
336
+
337
+ **返回值:** 包含 `register` 和 `unregister` 方法的对象
338
+
339
+ ## 高级用法
340
+
341
+ ### 组件间通信
342
+
343
+ ```tsx
344
+ // 全局状态模型
345
+ class AppState {
346
+ user: User | null = null;
347
+ theme: "light" | "dark" = "light";
348
+
349
+ setUser(user: User) {
350
+ this.user = user;
351
+ }
352
+
353
+ toggleTheme() {
354
+ this.theme = this.theme === "light" ? "dark" : "light";
17
355
  }
18
356
  }
19
357
 
20
- function TestComA() {
21
- const { value, random } = useModel(MTest, ["test"]);
358
+ // 在任何组件中使用
359
+ function Header() {
360
+ const { user, theme, toggleTheme } = useModel(AppState, []);
361
+
362
+ return (
363
+ <header className={theme}>
364
+ <span>欢迎, {user?.name}</span>
365
+ <button onClick={toggleTheme}>切换主题</button>
366
+ </header>
367
+ );
368
+ }
369
+
370
+ function Sidebar() {
371
+ const { user } = useModel(AppState, []); // 同一个实例
372
+
373
+ return <aside>{user && <UserProfile user={user} />}</aside>;
374
+ }
375
+ ```
376
+
377
+ ### 嵌套模型
378
+
379
+ ```tsx
380
+ class UserModel {
381
+ constructor(public id: string) {}
382
+
383
+ name = "";
384
+ email = "";
385
+
386
+ updateProfile(data: Partial<UserModel>) {
387
+ Object.assign(this, data);
388
+ }
389
+ }
390
+
391
+ class TeamModel {
392
+ members: UserModel[] = [];
393
+
394
+ addMember(userId: string) {
395
+ const user = provide(UserModel)(userId);
396
+ this.members.push(user);
397
+ }
398
+
399
+ removeMember(userId: string) {
400
+ this.members = this.members.filter(m => m.id !== userId);
401
+ }
402
+ }
403
+
404
+ function TeamManagement() {
405
+ const team = useModel(TeamModel, ["team-1"]);
406
+
407
+ return (
408
+ <div>
409
+ <h2>团队成员</h2>
410
+ {team.members.map(member => (
411
+ <UserCard key={member.id} user={member} />
412
+ ))}
413
+ </div>
414
+ );
415
+ }
416
+
417
+ function UserCard({ user }: { user: UserModel }) {
418
+ const observedUser = useInstance(user);
419
+
22
420
  return (
23
421
  <div>
24
- <span>{value}</span>
25
- <button onClick={random}>changeValue</button>
422
+ <span>{observedUser.name}</span>
423
+ <span>{observedUser.email}</span>
26
424
  </div>
27
425
  );
28
426
  }
427
+ ```
428
+
429
+ ### 命名空间隔离
430
+
431
+ ```tsx
432
+ function App() {
433
+ return (
434
+ <div>
435
+ {/* 开发环境配置 */}
436
+ <Container namespace="dev">
437
+ <VInjection schema={configSchema} val={devConfig} />
438
+ <DevTools />
439
+ </Container>
440
+
441
+ {/* 生产环境配置 */}
442
+ <Container namespace="prod">
443
+ <VInjection schema={configSchema} val={prodConfig} />
444
+ <MainApp />
445
+ </Container>
446
+ </div>
447
+ );
448
+ }
449
+ ```
450
+
451
+ ## 最佳实践
452
+
453
+ ### 1. 模型设计
454
+
455
+ - **单一职责**: 每个模型类应该只负责一个特定的业务领域
456
+ - **不可变更新**: 尽量使用不可变的方式更新状态
457
+ - **类型安全**: 充分利用 TypeScript 的类型系统
458
+
459
+ ```tsx
460
+ // ✅ 好的实践
461
+ class UserModel {
462
+ constructor(public id: string) {}
463
+
464
+ private _profile: UserProfile | null = null;
465
+
466
+ get profile() {
467
+ return this._profile;
468
+ }
469
+
470
+ updateProfile(updates: Partial<UserProfile>) {
471
+ this._profile = { ...this._profile, ...updates };
472
+ }
473
+ }
29
474
 
30
- function TestComB() {
31
- const { value } = useModel(MTest, ["test"]);
32
- return <span>{value}</span>;
475
+ // 避免的实践
476
+ class BadModel {
477
+ // 避免在模型中直接操作 DOM
478
+ updateUI() {
479
+ document.getElementById("user-name")!.textContent = this.name;
480
+ }
33
481
  }
482
+ ```
483
+
484
+ ### 2. 依赖注入
485
+
486
+ - **明确依赖**: 使用 Zod schema 明确定义依赖的类型
487
+ - **命名空间**: 使用命名空间隔离不同环境的配置
488
+ - **懒加载**: 只在需要时注入依赖
489
+
490
+ ### 3. 性能优化
491
+
492
+ - **合理使用参数**: 相同参数会返回相同实例,利用这一点进行优化
493
+ - **避免过度观察**: 不要观察不必要的对象
494
+ - **及时清理**: 使用 `finalizationRegistry` 进行资源清理
495
+
496
+ ## 类型定义
34
497
 
35
- render(
36
- <div>
37
- <TestComA />
38
- <TestComB />
39
- </div>
40
- );
41
- // 当点击ComA的div时,两个组件都会更新
498
+ ```typescript
499
+ // 主要导出的类型
500
+ export interface WatchCallback {
501
+ (path: Array<string | symbol>, oldValue: any, newValue: any): void;
502
+ }
503
+
504
+ export interface FinalizationRegistry {
505
+ register(callback: () => void): void;
506
+ unregister(): void;
507
+ }
508
+
509
+ export interface LoaderInstance {
510
+ loading: Record<symbol, [Function, Promise<unknown>]>;
511
+ globalLoading: number;
512
+ load(isGlobal?: boolean): MethodDecorator;
513
+ once(): MethodDecorator;
514
+ }
42
515
  ```
516
+
517
+ ## 兼容性
518
+
519
+ - **React**: >= 17.0.0
520
+ - **TypeScript**: >= 4.5.0
521
+ - **Zod**: ^4.1.5
522
+
523
+ ## 许可证
524
+
525
+ MIT License - 详见 [LICENSE.md](./LICENSE.md)
526
+
527
+ ## 贡献
528
+
529
+ 欢迎提交 Issue 和 Pull Request!
530
+
531
+ ## 更新日志
532
+
533
+ 详见 [CHANGELOG.md](./CHANGELOG.md)
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ import { FC, PropsWithChildren, ReactNode } from 'react';
4
+ import { ZodType } from 'zod';
5
+
3
6
  export type WatchCallback = (path: Array<string | symbol>, oldValue: any, newValue: any) => void;
4
7
  export declare function watch(target: object, callback: WatchCallback): () => void;
5
8
  export declare function provide<T extends new (...args: any[]) => InstanceType<T>>(ctor: T): T & ((...args: ConstructorParameters<T>) => InstanceType<T>);
@@ -10,5 +13,78 @@ export declare function finalizationRegistry(model: object): {
10
13
  export declare function useModel<T extends new (...args: any[]) => InstanceType<T>>(Ctor: T, args: ConstructorParameters<T>): InstanceType<T>;
11
14
  export declare function useModel<T extends new (...args: any[]) => InstanceType<T>>(Ctor: T, args: ConstructorParameters<T> | null): InstanceType<T> | Partial<InstanceType<T>>;
12
15
  export declare function useInstance<T extends object>(model: T): T;
16
+ export type Fn = (...args: any[]) => unknown;
17
+ export type AsyncFn<T = unknown> = (...args: any[]) => Promise<T>;
18
+ declare class MLoader {
19
+ loading: Record<symbol, [
20
+ Fn,
21
+ Promise<unknown>
22
+ ]>;
23
+ globalLoading: number;
24
+ onceTokens: WeakMap<AsyncFn, symbol>;
25
+ oncePool: Record<symbol, Promise<unknown>>;
26
+ addGlobalLoading(): void;
27
+ subGlobalLoading(): void;
28
+ load(isGlobal?: boolean): <T extends AsyncFn>(target: T, { name }: ClassMethodDecoratorContext) => T;
29
+ once<T extends AsyncFn>(target: T, { name }: ClassMethodDecoratorContext): T;
30
+ isLoading<T extends AsyncFn>(target: T): boolean;
31
+ get isGlobalLoading(): boolean;
32
+ }
33
+ export declare const loader: MLoader;
34
+ export declare const useLoader: () => {
35
+ isGlobalLoading: boolean;
36
+ isLoading: <T extends AsyncFn>(target: T) => boolean;
37
+ };
38
+ /**
39
+ * IoC 容器组件,提供依赖注入的上下文环境
40
+ *
41
+ * @param namespace - 命名空间,用于隔离不同的依赖注入环境
42
+ * @param children - 子组件
43
+ */
44
+ export declare const Container: FC<PropsWithChildren<{
45
+ namespace?: string;
46
+ }>>;
47
+ /**
48
+ * 构造函数注入组件,将构造函数注入到容器中
49
+ *
50
+ * @param schema - Zod schema,用于类型验证和作为依赖标识
51
+ * @param ctor - 要注入的构造函数
52
+ */
53
+ export declare function CInjection<T extends ZodType, P extends new () => ReturnType<T["parse"]>>({ schema, ctor }: {
54
+ schema: T;
55
+ ctor: P;
56
+ }): ReactNode;
57
+ /**
58
+ * 值注入组件,将值注入到容器中
59
+ *
60
+ * @param schema - Zod schema,用于类型验证和作为依赖标识
61
+ * @param val - 要注入的值
62
+ */
63
+ export declare function VInjection<T extends ZodType>({ schema, val, }: {
64
+ schema: T;
65
+ val: ReturnType<T["parse"]>;
66
+ }): ReactNode;
67
+ /**
68
+ * 依赖注入装饰器,从容器中获取实例或值
69
+ *
70
+ * @param schema - Zod schema,用于类型验证和作为依赖标识
71
+ * @param namespace - 命名空间,默认为空字符串
72
+ * @returns 装饰器函数
73
+ */
74
+ export declare function inject<T extends ZodType>(schema: T, namespace?: string): (_: unknown, { static: isStatic, kind }: ClassFieldDecoratorContext) => <P extends ReturnType<T["parse"]> | undefined>(initVal: P) => P;
75
+ /**
76
+ * 清理指定命名空间的所有依赖
77
+ *
78
+ * @param namespace - 要清理的命名空间
79
+ */
80
+ export declare function clearNamespace(namespace: string): void;
81
+ /**
82
+ * 检查指定的 schema 是否已在命名空间中注册
83
+ *
84
+ * @param schema - 要检查的 schema
85
+ * @param namespace - 命名空间
86
+ * @returns 是否已注册
87
+ */
88
+ export declare function isRegistered<T extends ZodType>(schema: T, namespace?: string): boolean;
13
89
 
14
90
  export {};