@taicode/common-web 1.0.5 → 1.1.1

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.
Files changed (80) hide show
  1. package/output/helpers/cache-api/cache-api.d.ts +13 -0
  2. package/output/helpers/cache-api/cache-api.d.ts.map +1 -0
  3. package/{source/utils/cache/aside.js → output/helpers/cache-api/cache-api.js} +54 -46
  4. package/output/helpers/cache-api/cache-api.test.d.ts +2 -0
  5. package/output/helpers/cache-api/cache-api.test.d.ts.map +1 -0
  6. package/output/helpers/cache-api/cache-api.test.js +348 -0
  7. package/output/helpers/cache-api/index.d.ts +2 -0
  8. package/output/helpers/cache-api/index.d.ts.map +1 -0
  9. package/output/helpers/cache-api/index.js +1 -0
  10. package/output/helpers/service/index.d.ts +1 -0
  11. package/output/helpers/service/index.d.ts.map +1 -0
  12. package/output/helpers/service/index.js +1 -0
  13. package/output/helpers/service/service.d.ts +5 -0
  14. package/output/helpers/service/service.d.ts.map +1 -0
  15. package/output/helpers/service/service.js +2 -0
  16. package/output/helpers/side-cache/index.d.ts +2 -0
  17. package/output/helpers/side-cache/index.d.ts.map +1 -0
  18. package/output/helpers/side-cache/index.js +1 -0
  19. package/output/helpers/side-cache/side-cache.d.ts +10 -0
  20. package/output/helpers/side-cache/side-cache.d.ts.map +1 -0
  21. package/output/{utils/cache/aside.js → helpers/side-cache/side-cache.js} +51 -20
  22. package/output/helpers/side-cache/side-cache.test.d.ts +2 -0
  23. package/output/helpers/side-cache/side-cache.test.d.ts.map +1 -0
  24. package/output/helpers/side-cache/side-cache.test.js +179 -0
  25. package/output/helpers/use-observer/index.d.ts +2 -0
  26. package/output/helpers/use-observer/index.d.ts.map +1 -0
  27. package/output/helpers/use-observer/index.js +1 -0
  28. package/output/{hooks/mobx.d.ts → helpers/use-observer/use-observer.d.ts} +1 -1
  29. package/output/helpers/use-observer/use-observer.d.ts.map +1 -0
  30. package/output/helpers/use-observer/use-observer.test.d.ts +2 -0
  31. package/output/helpers/use-observer/use-observer.test.d.ts.map +1 -0
  32. package/output/helpers/use-observer/use-observer.test.jsx +134 -0
  33. package/package.json +24 -16
  34. package/output/hooks/mobx.d.ts.map +0 -1
  35. package/output/utils/cache/aside.d.ts +0 -7
  36. package/output/utils/cache/aside.d.ts.map +0 -1
  37. package/output/utils/cache/index.d.ts +0 -2
  38. package/output/utils/cache/index.d.ts.map +0 -1
  39. package/output/utils/cache/index.js +0 -1
  40. package/source/catalyst/CHANGELOG.md +0 -136
  41. package/source/catalyst/README.md +0 -65
  42. package/source/catalyst/alert.tsx +0 -95
  43. package/source/catalyst/auth-layout.tsx +0 -11
  44. package/source/catalyst/avatar.tsx +0 -84
  45. package/source/catalyst/badge.tsx +0 -82
  46. package/source/catalyst/button.tsx +0 -204
  47. package/source/catalyst/checkbox.tsx +0 -157
  48. package/source/catalyst/combobox.tsx +0 -188
  49. package/source/catalyst/description-list.tsx +0 -37
  50. package/source/catalyst/dialog.tsx +0 -86
  51. package/source/catalyst/divider.tsx +0 -20
  52. package/source/catalyst/dropdown.tsx +0 -183
  53. package/source/catalyst/fieldset.tsx +0 -91
  54. package/source/catalyst/heading.tsx +0 -27
  55. package/source/catalyst/input.tsx +0 -94
  56. package/source/catalyst/link.tsx +0 -21
  57. package/source/catalyst/listbox.tsx +0 -177
  58. package/source/catalyst/navbar.tsx +0 -96
  59. package/source/catalyst/pagination.tsx +0 -98
  60. package/source/catalyst/radio.tsx +0 -142
  61. package/source/catalyst/select.tsx +0 -68
  62. package/source/catalyst/sidebar-layout.tsx +0 -82
  63. package/source/catalyst/sidebar.tsx +0 -142
  64. package/source/catalyst/stacked-layout.tsx +0 -79
  65. package/source/catalyst/switch.tsx +0 -195
  66. package/source/catalyst/table.tsx +0 -124
  67. package/source/catalyst/text.tsx +0 -40
  68. package/source/catalyst/textarea.tsx +0 -54
  69. package/source/hooks/mobx.d.ts +0 -3
  70. package/source/hooks/mobx.d.ts.map +0 -1
  71. package/source/hooks/mobx.js +0 -16
  72. package/source/hooks/mobx.ts +0 -24
  73. package/source/utils/cache/aside.d.ts +0 -7
  74. package/source/utils/cache/aside.d.ts.map +0 -1
  75. package/source/utils/cache/aside.ts +0 -39
  76. package/source/utils/cache/index.d.ts +0 -2
  77. package/source/utils/cache/index.d.ts.map +0 -1
  78. package/source/utils/cache/index.js +0 -1
  79. package/source/utils/cache/index.ts +0 -1
  80. /package/output/{hooks/mobx.js → helpers/use-observer/use-observer.js} +0 -0
@@ -44,10 +44,16 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
44
44
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
45
45
  };
46
46
  import { action, computed, observable, runInAction } from 'mobx';
47
- let AsideCache = (() => {
48
- var _a, _AsideCache_currentKey_accessor_storage, _AsideCache_cache_accessor_storage;
47
+ function isPromiseLike(value) {
48
+ return value != null && typeof value.then === 'function';
49
+ }
50
+ let SideCache = (() => {
51
+ var _a, _SideCache_emptyFlag_accessor_storage, _SideCache_currentKey_accessor_storage, _SideCache_cache_accessor_storage;
49
52
  var _b, _c;
50
53
  let _instanceExtraInitializers = [];
54
+ let _emptyFlag_decorators;
55
+ let _emptyFlag_initializers = [];
56
+ let _emptyFlag_extraInitializers = [];
51
57
  let _currentKey_decorators;
52
58
  let _currentKey_initializers = [];
53
59
  let _currentKey_extraInitializers = [];
@@ -55,25 +61,44 @@ let AsideCache = (() => {
55
61
  let _cache_initializers = [];
56
62
  let _cache_extraInitializers = [];
57
63
  let _get_value_decorators;
64
+ let _get_empty_decorators;
58
65
  let _handle_decorators;
59
- return _a = class AsideCache {
60
- get currentKey() { return __classPrivateFieldGet(this, _AsideCache_currentKey_accessor_storage, "f"); }
61
- set currentKey(value) { __classPrivateFieldSet(this, _AsideCache_currentKey_accessor_storage, value, "f"); }
62
- get cache() { return __classPrivateFieldGet(this, _AsideCache_cache_accessor_storage, "f"); }
63
- set cache(value) { __classPrivateFieldSet(this, _AsideCache_cache_accessor_storage, value, "f"); }
66
+ return _a = class SideCache {
67
+ get emptyFlag() { return __classPrivateFieldGet(this, _SideCache_emptyFlag_accessor_storage, "f"); }
68
+ set emptyFlag(value) { __classPrivateFieldSet(this, _SideCache_emptyFlag_accessor_storage, value, "f"); }
69
+ get currentKey() { return __classPrivateFieldGet(this, _SideCache_currentKey_accessor_storage, "f"); }
70
+ set currentKey(value) { __classPrivateFieldSet(this, _SideCache_currentKey_accessor_storage, value, "f"); }
71
+ get cache() { return __classPrivateFieldGet(this, _SideCache_cache_accessor_storage, "f"); }
72
+ set cache(value) { __classPrivateFieldSet(this, _SideCache_cache_accessor_storage, value, "f"); }
64
73
  get value() {
65
- var _b;
66
74
  if (this.currentKey == null)
67
- return null;
68
- return ((_b = this.cache[this.currentKey]) === null || _b === void 0 ? void 0 : _b.data) || null;
75
+ return undefined;
76
+ const cacheItem = this.cache[this.currentKey];
77
+ return cacheItem ? cacheItem.data : undefined;
78
+ }
79
+ get empty() {
80
+ return this.emptyFlag;
69
81
  }
70
- async handle(key, func) {
71
- const keyStringify = JSON.stringify(key); // 不需要跨设备、软件一致,所以直接用 JSON.stringify
82
+ handle(key, func) {
83
+ var _b;
84
+ // 不需要跨设备、软件一致,所以直接用 JSON.stringify
85
+ // 但需要处理 JSON.stringify(undefined) 返回 undefined 的情况
86
+ const keyStringify = (_b = JSON.stringify(key)) !== null && _b !== void 0 ? _b : 'undefined';
87
+ // 这会让外面立马可以拿到之前缓存的值,如果存在的话
72
88
  runInAction(() => this.currentKey = keyStringify);
73
- const funcReturn = await func();
74
- if (funcReturn == null)
75
- return funcReturn;
89
+ const funcReturn = func();
90
+ if (isPromiseLike(funcReturn)) {
91
+ return funcReturn.then(result => runInAction(() => {
92
+ this.emptyFlag = false;
93
+ this.cache = Object.assign(Object.assign({}, this.cache), { [keyStringify]: {
94
+ data: result,
95
+ createTime: new Date().toISOString()
96
+ } });
97
+ return result;
98
+ }));
99
+ }
76
100
  runInAction(() => {
101
+ this.emptyFlag = false;
77
102
  this.cache = Object.assign(Object.assign({}, this.cache), { [keyStringify]: {
78
103
  data: funcReturn,
79
104
  createTime: new Date().toISOString()
@@ -82,25 +107,31 @@ let AsideCache = (() => {
82
107
  return funcReturn;
83
108
  }
84
109
  constructor() {
85
- _AsideCache_currentKey_accessor_storage.set(this, (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _currentKey_initializers, null)));
86
- _AsideCache_cache_accessor_storage.set(this, (__runInitializers(this, _currentKey_extraInitializers), __runInitializers(this, _cache_initializers, {})));
110
+ _SideCache_emptyFlag_accessor_storage.set(this, (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _emptyFlag_initializers, true)));
111
+ _SideCache_currentKey_accessor_storage.set(this, (__runInitializers(this, _emptyFlag_extraInitializers), __runInitializers(this, _currentKey_initializers, void 0)));
112
+ _SideCache_cache_accessor_storage.set(this, (__runInitializers(this, _currentKey_extraInitializers), __runInitializers(this, _cache_initializers, {})));
87
113
  __runInitializers(this, _cache_extraInitializers);
88
114
  }
89
115
  },
90
- _AsideCache_currentKey_accessor_storage = new WeakMap(),
91
- _AsideCache_cache_accessor_storage = new WeakMap(),
116
+ _SideCache_emptyFlag_accessor_storage = new WeakMap(),
117
+ _SideCache_currentKey_accessor_storage = new WeakMap(),
118
+ _SideCache_cache_accessor_storage = new WeakMap(),
92
119
  (() => {
93
120
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
121
+ _emptyFlag_decorators = [observable];
94
122
  _currentKey_decorators = [observable];
95
123
  _cache_decorators = [(_b = observable).ref.bind(_b)];
96
124
  _get_value_decorators = [computed];
125
+ _get_empty_decorators = [computed];
97
126
  _handle_decorators = [(_c = action).bound.bind(_c)];
127
+ __esDecorate(_a, null, _emptyFlag_decorators, { kind: "accessor", name: "emptyFlag", static: false, private: false, access: { has: obj => "emptyFlag" in obj, get: obj => obj.emptyFlag, set: (obj, value) => { obj.emptyFlag = value; } }, metadata: _metadata }, _emptyFlag_initializers, _emptyFlag_extraInitializers);
98
128
  __esDecorate(_a, null, _currentKey_decorators, { kind: "accessor", name: "currentKey", static: false, private: false, access: { has: obj => "currentKey" in obj, get: obj => obj.currentKey, set: (obj, value) => { obj.currentKey = value; } }, metadata: _metadata }, _currentKey_initializers, _currentKey_extraInitializers);
99
129
  __esDecorate(_a, null, _cache_decorators, { kind: "accessor", name: "cache", static: false, private: false, access: { has: obj => "cache" in obj, get: obj => obj.cache, set: (obj, value) => { obj.cache = value; } }, metadata: _metadata }, _cache_initializers, _cache_extraInitializers);
100
130
  __esDecorate(_a, null, _get_value_decorators, { kind: "getter", name: "value", static: false, private: false, access: { has: obj => "value" in obj, get: obj => obj.value }, metadata: _metadata }, null, _instanceExtraInitializers);
131
+ __esDecorate(_a, null, _get_empty_decorators, { kind: "getter", name: "empty", static: false, private: false, access: { has: obj => "empty" in obj, get: obj => obj.empty }, metadata: _metadata }, null, _instanceExtraInitializers);
101
132
  __esDecorate(_a, null, _handle_decorators, { kind: "method", name: "handle", static: false, private: false, access: { has: obj => "handle" in obj, get: obj => obj.handle }, metadata: _metadata }, null, _instanceExtraInitializers);
102
133
  if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
103
134
  })(),
104
135
  _a;
105
136
  })();
106
- export { AsideCache };
137
+ export { SideCache };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=side-cache.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"side-cache.test.d.ts","sourceRoot":"","sources":["../../../source/helpers/side-cache/side-cache.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,179 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { SideCache } from './side-cache';
3
+ describe('SideCache', () => {
4
+ let cache;
5
+ beforeEach(() => {
6
+ cache = new SideCache();
7
+ });
8
+ describe('初始状态', () => {
9
+ it('应该初始化为空状态', () => {
10
+ expect(cache.empty).toBe(true);
11
+ expect(cache.value).toBe(undefined);
12
+ });
13
+ });
14
+ describe('同步缓存', () => {
15
+ it('应该能够缓存同步函数的结果', () => {
16
+ const mockFunc = vi.fn(() => 'test-result');
17
+ const key = 'test-key';
18
+ const result = cache.handle(key, mockFunc);
19
+ expect(result).toBe('test-result');
20
+ expect(mockFunc).toHaveBeenCalledTimes(1);
21
+ expect(cache.empty).toBe(false);
22
+ expect(cache.value).toBe('test-result');
23
+ });
24
+ it('应该对相同 key 返回缓存的结果', () => {
25
+ const mockFunc = vi.fn(() => 'cached-result');
26
+ const key = 'same-key';
27
+ // 第一次调用
28
+ const result1 = cache.handle(key, mockFunc);
29
+ expect(result1).toBe('cached-result');
30
+ expect(mockFunc).toHaveBeenCalledTimes(1);
31
+ // 第二次调用相同 key,应该直接返回缓存
32
+ const result2 = cache.handle(key, mockFunc);
33
+ expect(result2).toBe('cached-result');
34
+ expect(mockFunc).toHaveBeenCalledTimes(2); // 函数仍会被调用,但会更新缓存
35
+ expect(cache.value).toBe('cached-result');
36
+ });
37
+ it('应该对不同 key 分别缓存', () => {
38
+ const mockFunc1 = vi.fn(() => 'result1');
39
+ const mockFunc2 = vi.fn(() => 'result2');
40
+ cache.handle('key1', mockFunc1);
41
+ expect(cache.value).toBe('result1');
42
+ cache.handle('key2', mockFunc2);
43
+ expect(cache.value).toBe('result2');
44
+ // 切换回 key1
45
+ cache.handle('key1', mockFunc1);
46
+ expect(cache.value).toBe('result1');
47
+ });
48
+ });
49
+ describe('异步缓存', () => {
50
+ it('应该能够缓存异步函数的结果', async () => {
51
+ const mockAsyncFunc = vi.fn(async () => 'async-result');
52
+ const key = 'async-key';
53
+ const promise = cache.handle(key, mockAsyncFunc);
54
+ expect(promise).toBeInstanceOf(Promise);
55
+ const result = await promise;
56
+ expect(result).toBe('async-result');
57
+ expect(mockAsyncFunc).toHaveBeenCalledTimes(1);
58
+ expect(cache.empty).toBe(false);
59
+ expect(cache.value).toBe('async-result');
60
+ });
61
+ it('应该在异步函数执行期间立即设置 currentKey', async () => {
62
+ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
63
+ const mockAsyncFunc = vi.fn(async () => {
64
+ await delay(10);
65
+ return 'delayed-result';
66
+ });
67
+ const key = 'delayed-key';
68
+ // 在异步函数开始执行时,currentKey 应该已经设置
69
+ const promise = cache.handle(key, mockAsyncFunc);
70
+ // 此时异步函数还在执行,但 currentKey 已设置
71
+ // 如果之前有缓存,value 应该能立即获取到
72
+ const result = await promise;
73
+ expect(result).toBe('delayed-result');
74
+ expect(cache.value).toBe('delayed-result');
75
+ });
76
+ it('应该处理异步函数的错误', async () => {
77
+ const error = new Error('Async error');
78
+ const mockAsyncFunc = vi.fn(async () => {
79
+ throw error;
80
+ });
81
+ const key = 'error-key';
82
+ await expect(cache.handle(key, mockAsyncFunc)).rejects.toThrow('Async error');
83
+ expect(mockAsyncFunc).toHaveBeenCalledTimes(1);
84
+ });
85
+ });
86
+ describe('key 序列化', () => {
87
+ it('应该正确处理不同类型的 key', () => {
88
+ const mockFunc = vi.fn(() => 'result');
89
+ // 字符串 key
90
+ cache.handle('string-key', mockFunc);
91
+ expect(cache.value).toBe('result');
92
+ // 数字 key
93
+ cache.handle(123, mockFunc);
94
+ expect(cache.value).toBe('result');
95
+ // 对象 key
96
+ cache.handle({ id: 1, name: 'test' }, mockFunc);
97
+ expect(cache.value).toBe('result');
98
+ // 数组 key
99
+ cache.handle([1, 2, 3], mockFunc);
100
+ expect(cache.value).toBe('result');
101
+ });
102
+ it('相同内容的对象 key 应该被视为相同', () => {
103
+ const mockFunc = vi.fn(() => 'object-result');
104
+ const key1 = { id: 1, name: 'test' };
105
+ const key2 = { id: 1, name: 'test' };
106
+ cache.handle(key1, mockFunc);
107
+ const result1 = cache.value;
108
+ cache.handle(key2, mockFunc);
109
+ const result2 = cache.value;
110
+ expect(result1).toBe(result2);
111
+ expect(result1).toBe('object-result');
112
+ });
113
+ });
114
+ describe('缓存时间戳', () => {
115
+ it('应该为缓存项添加创建时间', () => {
116
+ const mockFunc = vi.fn(() => 'timestamped-result');
117
+ const key = 'timestamp-key';
118
+ const beforeTime = new Date().toISOString();
119
+ cache.handle(key, mockFunc);
120
+ const afterTime = new Date().toISOString();
121
+ // 访问私有属性进行测试(仅用于测试目的)
122
+ const cacheData = cache.cache;
123
+ const cachedItem = cacheData[JSON.stringify(key)];
124
+ expect(cachedItem).toBeDefined();
125
+ expect(cachedItem.data).toBe('timestamped-result');
126
+ expect(cachedItem.createTime).toBeDefined();
127
+ expect(typeof cachedItem.createTime).toBe('string');
128
+ // 验证时间戳在合理范围内
129
+ expect(cachedItem.createTime >= beforeTime).toBe(true);
130
+ expect(cachedItem.createTime <= afterTime).toBe(true);
131
+ });
132
+ });
133
+ describe('边界情况', () => {
134
+ it('应该处理 null 和 undefined key', () => {
135
+ const mockFunc1 = vi.fn(() => 'null-key-result');
136
+ const mockFunc2 = vi.fn(() => 'undefined-key-result');
137
+ cache.handle(null, mockFunc1);
138
+ expect(cache.value).toBe('null-key-result');
139
+ cache.handle(undefined, mockFunc2);
140
+ expect(cache.value).toBe('undefined-key-result');
141
+ });
142
+ it('应该处理返回 null 或 undefined 的函数', () => {
143
+ const nullFunc = vi.fn(() => null);
144
+ const undefinedFunc = vi.fn(() => undefined);
145
+ cache.handle('null-key', nullFunc);
146
+ expect(cache.value).toBe(null);
147
+ expect(cache.empty).toBe(false);
148
+ cache.handle('undefined-key', undefinedFunc);
149
+ expect(cache.value).toBe(undefined);
150
+ expect(cache.empty).toBe(false);
151
+ });
152
+ it('应该处理返回 Promise.resolve(null) 的异步函数', async () => {
153
+ const nullAsyncFunc = vi.fn(async () => null);
154
+ const result = await cache.handle('async-null', nullAsyncFunc);
155
+ expect(result).toBe(null);
156
+ expect(cache.value).toBe(null);
157
+ expect(cache.empty).toBe(false);
158
+ });
159
+ });
160
+ describe('类型检查', () => {
161
+ it('应该正确识别 Promise-like 对象', async () => {
162
+ let thenCallback;
163
+ const promiseLike = {
164
+ then: vi.fn((callback) => {
165
+ thenCallback = callback;
166
+ return promiseLike;
167
+ })
168
+ };
169
+ const mockFunc = vi.fn(() => promiseLike);
170
+ const result = cache.handle('promise-like', mockFunc);
171
+ expect(result).toBe(promiseLike);
172
+ expect(promiseLike.then).toHaveBeenCalled();
173
+ // 模拟 Promise 完成
174
+ if (thenCallback) {
175
+ thenCallback('resolved-value');
176
+ }
177
+ });
178
+ });
179
+ });
@@ -0,0 +1,2 @@
1
+ export { useObserver } from './use-observer';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/helpers/use-observer/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA"}
@@ -0,0 +1 @@
1
+ export { useObserver } from './use-observer';
@@ -1,3 +1,3 @@
1
1
  export declare function useObserver<T>(initialValue: T): T;
2
2
  export declare function useObserver<T, U>(initialValue: T, selector: (v: T) => U): U;
3
- //# sourceMappingURL=mobx.d.ts.map
3
+ //# sourceMappingURL=use-observer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-observer.d.ts","sourceRoot":"","sources":["../../../source/helpers/use-observer/use-observer.ts"],"names":[],"mappings":"AAGA,wBAAgB,WAAW,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,GAAG,CAAC,CAAA;AAClD,wBAAgB,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=use-observer.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-observer.test.d.ts","sourceRoot":"","sources":["../../../source/helpers/use-observer/use-observer.test.tsx"],"names":[],"mappings":""}
@@ -0,0 +1,134 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { renderHook, act } from '@testing-library/react';
3
+ import { observable, action } from 'mobx';
4
+ import { useObserver } from './use-observer';
5
+ describe('useObserver', () => {
6
+ it('应该返回初始值当没有selector时', () => {
7
+ const initialValue = '初始值';
8
+ const { result } = renderHook(() => useObserver(initialValue));
9
+ expect(result.current).toBe(initialValue);
10
+ });
11
+ it('应该使用selector转换值', () => {
12
+ const initialValue = { count: 5 };
13
+ const selector = (value) => value.count * 2;
14
+ const { result } = renderHook(() => useObserver(initialValue, selector));
15
+ expect(result.current).toBe(10);
16
+ });
17
+ it('应该在观察对象变化时重新渲染', async () => {
18
+ const observableStore = observable({
19
+ count: 0,
20
+ increment: action(() => {
21
+ observableStore.count++;
22
+ })
23
+ });
24
+ const { result } = renderHook(() => useObserver(observableStore, (store) => store.count));
25
+ expect(result.current).toBe(0);
26
+ // 改变observable的值
27
+ act(() => {
28
+ observableStore.increment();
29
+ });
30
+ // 等待React更新
31
+ await new Promise(resolve => setTimeout(resolve, 0));
32
+ expect(result.current).toBe(1);
33
+ });
34
+ it('应该处理复杂的selector函数', () => {
35
+ const store = observable({
36
+ users: [
37
+ { id: 1, name: '张三', active: true },
38
+ { id: 2, name: '李四', active: false },
39
+ { id: 3, name: '王五', active: true }
40
+ ]
41
+ });
42
+ const selector = (store) => store.users.filter((user) => user.active).map((user) => user.name);
43
+ const { result } = renderHook(() => useObserver(store, selector));
44
+ expect(result.current).toEqual(['张三', '王五']);
45
+ });
46
+ it('应该在observable数组变化时重新渲染', async () => {
47
+ const store = observable({
48
+ items: ['项目1', '项目2'],
49
+ addItem: action((item) => {
50
+ store.items.push(item);
51
+ })
52
+ });
53
+ const { result } = renderHook(() => useObserver(store, (store) => store.items.length));
54
+ expect(result.current).toBe(2);
55
+ act(() => {
56
+ store.addItem('项目3');
57
+ });
58
+ await new Promise(resolve => setTimeout(resolve, 0));
59
+ expect(result.current).toBe(3);
60
+ });
61
+ it('应该处理null值的初始值', () => {
62
+ const { result } = renderHook(() => useObserver(null));
63
+ expect(result.current).toBeNull();
64
+ });
65
+ it('应该处理undefined值的初始值', () => {
66
+ const { result } = renderHook(() => useObserver(undefined));
67
+ expect(result.current).toBeUndefined();
68
+ });
69
+ it('应该在selector为null时返回原值', () => {
70
+ const initialValue = { data: '测试数据' };
71
+ const { result } = renderHook(() => useObserver(initialValue, null));
72
+ expect(result.current).toBe(initialValue);
73
+ });
74
+ it('应该处理嵌套observable对象', async () => {
75
+ const store = observable({
76
+ user: {
77
+ profile: {
78
+ name: '测试用户',
79
+ email: 'test@example.com'
80
+ }
81
+ },
82
+ updateName: action((name) => {
83
+ store.user.profile.name = name;
84
+ })
85
+ });
86
+ const { result } = renderHook(() => useObserver(store, (store) => store.user.profile.name));
87
+ expect(result.current).toBe('测试用户');
88
+ act(() => {
89
+ store.updateName('新用户名');
90
+ });
91
+ await new Promise(resolve => setTimeout(resolve, 0));
92
+ expect(result.current).toBe('新用户名');
93
+ });
94
+ it('应该处理多个observable属性的变化', async () => {
95
+ const store = observable({
96
+ firstName: '张',
97
+ lastName: '三',
98
+ updateFirstName: action((name) => {
99
+ store.firstName = name;
100
+ }),
101
+ updateLastName: action((name) => {
102
+ store.lastName = name;
103
+ })
104
+ });
105
+ const { result } = renderHook(() => useObserver(store, (store) => `${store.firstName}${store.lastName}`));
106
+ expect(result.current).toBe('张三');
107
+ act(() => {
108
+ store.updateFirstName('李');
109
+ });
110
+ await new Promise(resolve => setTimeout(resolve, 0));
111
+ expect(result.current).toBe('李三');
112
+ act(() => {
113
+ store.updateLastName('四');
114
+ });
115
+ await new Promise(resolve => setTimeout(resolve, 0));
116
+ expect(result.current).toBe('李四');
117
+ });
118
+ it('应该在组件卸载时清理reaction', () => {
119
+ const store = observable({ count: 0 });
120
+ const { unmount } = renderHook(() => useObserver(store, (store) => store.count));
121
+ // 卸载组件应该不会抛出错误
122
+ expect(() => unmount()).not.toThrow();
123
+ });
124
+ it('应该处理boolean类型的返回值', () => {
125
+ const store = observable({ isActive: true });
126
+ const { result } = renderHook(() => useObserver(store, (store) => store.isActive));
127
+ expect(result.current).toBe(true);
128
+ });
129
+ it('应该处理数字类型的返回值', () => {
130
+ const store = observable({ count: 42 });
131
+ const { result } = renderHook(() => useObserver(store, (store) => store.count));
132
+ expect(result.current).toBe(42);
133
+ });
134
+ });
package/package.json CHANGED
@@ -1,36 +1,44 @@
1
1
  {
2
2
  "name": "@taicode/common-web",
3
- "version": "1.0.5",
3
+ "version": "1.1.1",
4
4
  "author": "Alain",
5
5
  "license": "ISC",
6
6
  "description": "",
7
+ "exports": {
8
+ "./*": {
9
+ "types": "./output/*/index.d.ts",
10
+ "import": "./output/*/index.js",
11
+ "require": "./output/*/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "output"
16
+ ],
7
17
  "scripts": {
18
+ "test": "vitest",
19
+ "test:ui": "vitest --ui",
20
+ "test:run": "vitest run",
21
+ "prepublishOnly": "npm run build",
8
22
  "build": "tsc -p tsconfig.json",
9
23
  "dev": "tsc -p tsconfig.json --watch"
10
24
  },
11
25
  "peerDependencies": {
26
+ "@taicode/common-base": ">=1.1.0",
27
+ "@needle-di/core": ">=1.0.0",
12
28
  "@types/react": ">=18",
13
29
  "mobx": ">=6",
14
30
  "react": ">=18"
15
31
  },
16
- "files": [
17
- "output",
18
- "source"
19
- ],
20
- "exports": {
21
- "./utils/*": [
22
- "./output/utils/*"
23
- ],
24
- "./hooks/*": [
25
- "./output/hooks/*"
26
- ],
27
- "./catalyst/*": [
28
- "./output/catalyst/*"
29
- ]
30
- },
31
32
  "dependencies": {
32
33
  "@headlessui/react": "^2.2.4",
33
34
  "framer-motion": "^12.19.2",
34
35
  "clsx": "^2.1.1"
36
+ },
37
+ "devDependencies": {
38
+ "@testing-library/react": "^14.0.0",
39
+ "@testing-library/jest-dom": "^6.1.0",
40
+ "jsdom": "^23.0.0",
41
+ "vitest": "^1.0.0",
42
+ "@vitest/ui": "^1.0.0"
35
43
  }
36
44
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"mobx.d.ts","sourceRoot":"","sources":["../../source/hooks/mobx.ts"],"names":[],"mappings":"AAGA,wBAAgB,WAAW,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,GAAG,CAAC,CAAA;AAClD,wBAAgB,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA"}
@@ -1,7 +0,0 @@
1
- export declare class AsideCache<T> {
2
- private accessor currentKey;
3
- private accessor cache;
4
- get value(): T | null;
5
- handle<F extends ((...args: unknown[]) => Promise<T | null>)>(key: unknown, func: F): Promise<T | null>;
6
- }
7
- //# sourceMappingURL=aside.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aside.d.ts","sourceRoot":"","sources":["../../../source/utils/cache/aside.ts"],"names":[],"mappings":"AAOA,qBAAa,UAAU,CAAC,CAAC;IAEvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAsB;IAGjD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;IAE1D,IACW,KAAK,IAAI,CAAC,GAAG,IAAI,CAG3B;IAGY,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;CAiBrH"}
@@ -1,2 +0,0 @@
1
- export { AsideCache } from './aside';
2
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/utils/cache/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA"}
@@ -1 +0,0 @@
1
- export { AsideCache } from './aside';