airx 0.3.1 → 0.7.0

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 (108) hide show
  1. package/README.md +247 -63
  2. package/output/app/app.d.ts +11 -0
  3. package/output/app/app.d.ts.map +1 -0
  4. package/output/app/app.test.d.ts +2 -0
  5. package/output/app/app.test.d.ts.map +1 -0
  6. package/output/app/index.d.ts +2 -0
  7. package/output/app/index.d.ts.map +1 -0
  8. package/output/{esm → element}/element.d.ts +3 -2
  9. package/output/element/element.d.ts.map +1 -0
  10. package/output/element/element.test.d.ts +2 -0
  11. package/output/element/element.test.d.ts.map +1 -0
  12. package/output/element/index.d.ts +2 -0
  13. package/output/element/index.d.ts.map +1 -0
  14. package/output/index.d.ts +6 -0
  15. package/output/index.d.ts.map +1 -0
  16. package/output/index.js +711 -0
  17. package/output/index.umd.cjs +1 -0
  18. package/output/logger/index.d.ts +2 -0
  19. package/output/logger/index.d.ts.map +1 -0
  20. package/output/{esm → logger}/logger.d.ts +1 -0
  21. package/output/logger/logger.d.ts.map +1 -0
  22. package/output/logger/logger.test.d.ts +2 -0
  23. package/output/logger/logger.test.d.ts.map +1 -0
  24. package/output/{esm/render/common/index.d.ts → render/basic/common.d.ts} +3 -2
  25. package/output/render/basic/common.d.ts.map +1 -0
  26. package/output/render/basic/common.test.d.ts +2 -0
  27. package/output/render/basic/common.test.d.ts.map +1 -0
  28. package/output/{umd/render/common → render/basic/hooks}/hooks.d.ts +2 -1
  29. package/output/render/basic/hooks/hooks.d.ts.map +1 -0
  30. package/output/render/basic/hooks/hooks.test.d.ts +2 -0
  31. package/output/render/basic/hooks/hooks.test.d.ts.map +1 -0
  32. package/output/render/basic/hooks/index.d.ts +2 -0
  33. package/output/render/basic/hooks/index.d.ts.map +1 -0
  34. package/output/render/basic/index.d.ts +2 -0
  35. package/output/render/basic/index.d.ts.map +1 -0
  36. package/output/{esm/render/common/plugins → render/basic/plugins/context}/context.d.ts +2 -1
  37. package/output/render/basic/plugins/context/context.d.ts.map +1 -0
  38. package/output/render/basic/plugins/context/context.test.d.ts +2 -0
  39. package/output/render/basic/plugins/context/context.test.d.ts.map +1 -0
  40. package/output/render/basic/plugins/context/index.d.ts +2 -0
  41. package/output/render/basic/plugins/context/index.d.ts.map +1 -0
  42. package/output/render/basic/plugins/index.d.ts +3 -0
  43. package/output/render/basic/plugins/index.d.ts.map +1 -0
  44. package/output/{umd/render/common/plugins/internal → render/basic/plugins/internal/basic}/basic.d.ts +4 -3
  45. package/output/render/basic/plugins/internal/basic/basic.d.ts.map +1 -0
  46. package/output/render/basic/plugins/internal/basic/basic.test.d.ts +2 -0
  47. package/output/render/basic/plugins/internal/basic/basic.test.d.ts.map +1 -0
  48. package/output/render/basic/plugins/internal/basic/index.d.ts +2 -0
  49. package/output/render/basic/plugins/internal/basic/index.d.ts.map +1 -0
  50. package/output/render/basic/plugins/internal/inject/index.d.ts +2 -0
  51. package/output/render/basic/plugins/internal/inject/index.d.ts.map +1 -0
  52. package/output/{esm/render/common/plugins/internal → render/basic/plugins/internal/inject}/inject.d.ts +3 -2
  53. package/output/render/basic/plugins/internal/inject/inject.d.ts.map +1 -0
  54. package/output/render/basic/plugins/internal/inject/inject.test.d.ts +2 -0
  55. package/output/render/basic/plugins/internal/inject/inject.test.d.ts.map +1 -0
  56. package/output/{umd/render/common/plugins/index.d.ts → render/basic/plugins/plugin.d.ts} +2 -2
  57. package/output/render/basic/plugins/plugin.d.ts.map +1 -0
  58. package/output/render/basic/plugins/plugin.test.d.ts +2 -0
  59. package/output/render/basic/plugins/plugin.test.d.ts.map +1 -0
  60. package/output/{esm/render → render/browser}/browser.d.ts +4 -3
  61. package/output/render/browser/browser.d.ts.map +1 -0
  62. package/output/render/browser/browser.test.d.ts +2 -0
  63. package/output/render/browser/browser.test.d.ts.map +1 -0
  64. package/output/render/browser/index.d.ts +2 -0
  65. package/output/render/browser/index.d.ts.map +1 -0
  66. package/output/render/index.d.ts +5 -0
  67. package/output/render/index.d.ts.map +1 -0
  68. package/output/render/server/index.d.ts +2 -0
  69. package/output/render/server/index.d.ts.map +1 -0
  70. package/output/{umd/render → render/server}/server.d.ts +3 -2
  71. package/output/render/server/server.d.ts.map +1 -0
  72. package/output/render/server/server.test.d.ts +2 -0
  73. package/output/render/server/server.test.d.ts.map +1 -0
  74. package/output/signal/index.d.ts +4 -0
  75. package/output/signal/index.d.ts.map +1 -0
  76. package/output/{esm/signal/index.d.ts → signal/signal.d.ts} +2 -2
  77. package/output/signal/signal.d.ts.map +1 -0
  78. package/output/signal/signal.test.d.ts +5 -0
  79. package/output/signal/signal.test.d.ts.map +1 -0
  80. package/output/symbol/index.d.ts +2 -0
  81. package/output/symbol/index.d.ts.map +1 -0
  82. package/output/types/index.d.ts +2 -0
  83. package/output/types/index.d.ts.map +1 -0
  84. package/output/{esm → types}/types.d.ts +17 -11
  85. package/output/types/types.d.ts.map +1 -0
  86. package/package.json +35 -11
  87. package/output/esm/index.d.ts +0 -14
  88. package/output/esm/index.js +0 -1268
  89. package/output/esm/index.js.map +0 -1
  90. package/output/esm/render/common/hooks.d.ts +0 -10
  91. package/output/esm/render/common/plugins/index.d.ts +0 -19
  92. package/output/esm/render/common/plugins/internal/basic.d.ts +0 -10
  93. package/output/esm/render/index.d.ts +0 -4
  94. package/output/esm/render/server.d.ts +0 -5
  95. package/output/esm/symbol.d.ts +0 -2
  96. package/output/umd/element.d.ts +0 -48
  97. package/output/umd/index.d.ts +0 -14
  98. package/output/umd/index.js +0 -1283
  99. package/output/umd/index.js.map +0 -1
  100. package/output/umd/logger.d.ts +0 -3
  101. package/output/umd/render/browser.d.ts +0 -7
  102. package/output/umd/render/common/index.d.ts +0 -64
  103. package/output/umd/render/common/plugins/context.d.ts +0 -5
  104. package/output/umd/render/common/plugins/internal/inject.d.ts +0 -6
  105. package/output/umd/render/index.d.ts +0 -4
  106. package/output/umd/signal/index.d.ts +0 -6
  107. package/output/umd/symbol.d.ts +0 -2
  108. package/output/umd/types.d.ts +0 -1169
@@ -1,1268 +0,0 @@
1
- const globalContext = {
2
- current: null
3
- };
4
- function useContext() {
5
- if (globalContext.current == null) {
6
- throw new Error('Unable to find a valid component context');
7
- }
8
- return globalContext.current;
9
- }
10
- const onMounted = (listener) => {
11
- return useContext().onMounted(listener);
12
- };
13
- const onUnmounted = (listener) => {
14
- return useContext().onUnmounted(listener);
15
- };
16
- const inject = (key) => {
17
- return useContext().inject(key);
18
- };
19
- const provide = (key, value) => {
20
- return useContext().provide(key, value);
21
- };
22
-
23
- const isPrintLogs = typeof process != 'undefined'
24
- && process?.env?.NODE_ENV === 'development'
25
- && process?.env?.AIRX_DEBUG === 'true';
26
- function createLogger(name) {
27
- function getPrintPrefix() {
28
- const date = new Date().toLocaleString();
29
- return `[${date}][${name}]`;
30
- }
31
- function debug(...args) {
32
- if (isPrintLogs)
33
- console.log(getPrintPrefix(), ...args);
34
- }
35
- return { debug };
36
- }
37
-
38
- let firstSignal = undefined;
39
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- const globalNS = (function () {
41
- // the only reliable means to get the global object is
42
- // `Function('return this')()`
43
- // However, this causes CSP violations in Chrome apps.
44
- if (typeof self !== 'undefined') {
45
- return self;
46
- }
47
- if (typeof window !== 'undefined') {
48
- return window;
49
- }
50
- if (typeof global !== 'undefined') {
51
- return global;
52
- }
53
- throw new Error('unable to locate global object');
54
- })();
55
- // 通过函数包装来延迟加载 Signal
56
- // 这对使用 Polyfill 的应用来说更友好
57
- function getSignal() {
58
- const globalSignal = globalNS['Signal'];
59
- if (globalSignal == null)
60
- throw new Error('Signal is undefined');
61
- if (firstSignal == null)
62
- firstSignal = globalSignal;
63
- if (firstSignal !== globalSignal)
64
- throw new Error('Signal have multiple instances');
65
- return globalSignal;
66
- }
67
- function createWatch(notify) {
68
- const signal = getSignal();
69
- return new signal.subtle.Watcher(notify);
70
- }
71
- function createComputed(computation, options) {
72
- const signal = getSignal();
73
- return new signal.Computed(computation, options);
74
- }
75
- function isState(target) {
76
- const signal = getSignal();
77
- return target instanceof signal.State;
78
- }
79
-
80
- const airxElementSymbol = Symbol('airx-element');
81
-
82
- /**
83
- * createElement 是用于创建 AirxElement 的工具函数
84
- */
85
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
- function createElement(type, props, ...children) {
87
- const localChildren = children.length > 0
88
- ? children
89
- : props.children;
90
- return {
91
- type,
92
- props: {
93
- ...props,
94
- children: localChildren
95
- },
96
- [airxElementSymbol]: true
97
- };
98
- }
99
- function isValidElement(element) {
100
- return typeof element === 'object'
101
- && element !== null
102
- && Reflect.get(element, airxElementSymbol);
103
- }
104
- function Fragment(props) {
105
- return () => props.children;
106
- }
107
- function component(comp) {
108
- return comp;
109
- }
110
- function createErrorRender(error) {
111
- console.error(error);
112
- const handleClick = () => {
113
- // 点击输出错误是为了避免
114
- // 页面上多个组件同时出错时
115
- // 无法定位错误与之对应的组件
116
- console.error(error);
117
- };
118
- const formattingError = () => {
119
- if (error == null)
120
- return 'Unknown rendering error';
121
- if (error instanceof Error)
122
- return error.message;
123
- return JSON.stringify(error);
124
- };
125
- const errorBlockStyle = {
126
- padding: '8px',
127
- fontSize: '20px',
128
- color: 'rgb(255,255,255)',
129
- backgroundColor: 'rgb(255, 0, 0)',
130
- };
131
- return () => createElement('div', { style: errorBlockStyle, onClick: handleClick }, formattingError());
132
- }
133
-
134
- class InnerAirxComponentContext {
135
- instance;
136
- disposers = new Set();
137
- providedMap = new Map();
138
- injectedMap = new Map();
139
- mountListeners = new Set();
140
- unmountedListeners = new Set();
141
- triggerMounted() {
142
- this.mountListeners.forEach(listener => {
143
- let disposer = undefined;
144
- try {
145
- disposer = listener();
146
- }
147
- catch (err) {
148
- console.error(err, listener);
149
- }
150
- if (typeof disposer === 'function') {
151
- this.addDisposer(disposer);
152
- }
153
- });
154
- // 生命周期只会调用一次
155
- this.mountListeners.clear();
156
- }
157
- triggerUnmounted() {
158
- // 递归的调用子 child 的 Unmounted
159
- if (this.instance?.child != null) {
160
- this.instance.child.context.triggerUnmounted();
161
- }
162
- // 处理自己
163
- this.unmountedListeners.forEach(listener => {
164
- try {
165
- listener();
166
- }
167
- catch (err) {
168
- console.error(err, listener);
169
- }
170
- });
171
- // 处理兄弟节点
172
- if (this.instance?.sibling != null) {
173
- this.instance.sibling.context.triggerUnmounted();
174
- }
175
- this.dispose();
176
- }
177
- onMounted(listener) {
178
- this.mountListeners.add(listener);
179
- }
180
- onUnmounted(listener) {
181
- this.unmountedListeners.add(listener);
182
- }
183
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
184
- provide(key, value) {
185
- this.providedMap.set(key, value);
186
- return v => {
187
- if (typeof v === 'function') {
188
- const old = this.providedMap.get(key);
189
- const func = v;
190
- this.providedMap.set(key, func(old));
191
- return;
192
- }
193
- this.providedMap.set(key, v);
194
- };
195
- }
196
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
- inject(key) {
198
- const getProvideValueForParent = (instance, key) => {
199
- if (instance && instance.context) {
200
- const value = instance.context.providedMap.get(key);
201
- if (value != undefined)
202
- return value;
203
- if (instance.parent)
204
- return getProvideValueForParent(instance.parent, key);
205
- }
206
- return undefined;
207
- };
208
- const currentParentValue = getProvideValueForParent(this.instance.parent, key);
209
- this.injectedMap.set(key, currentParentValue); // 更新本地值
210
- return this.injectedMap.get(key);
211
- }
212
- addDisposer(...disposers) {
213
- disposers.forEach(disposer => {
214
- this.disposers.add(disposer);
215
- });
216
- }
217
- dispose() {
218
- this.disposers.forEach((disposer) => {
219
- try {
220
- disposer();
221
- }
222
- catch (err) {
223
- // eslint-disable-next-line no-console
224
- console.error(err, disposer);
225
- }
226
- });
227
- this.disposers.clear();
228
- this.injectedMap.clear();
229
- this.providedMap.clear();
230
- this.mountListeners.clear();
231
- this.unmountedListeners.clear();
232
- }
233
- /**
234
- * 当 context 传递给外部消费时,隐藏内部实现,仅暴露接口定义的内容
235
- * @returns 和 AirxComponentContext 接口完全一致的对象
236
- */
237
- getSafeContext() {
238
- return {
239
- inject: k => this.inject(k),
240
- provide: (k, v) => this.provide(k, v),
241
- onMounted: listener => this.onMounted(listener),
242
- onUnmounted: listener => this.onUnmounted(listener)
243
- };
244
- }
245
- }
246
- /**
247
- * 更新 children
248
- * @param parentInstance 当前正在处理的组件的实例
249
- * @param children 当前组件的子节点
250
- */
251
- function reconcileChildren(appContext, parentInstance, childrenElementArray) {
252
- const logger = createLogger('reconcileChildren');
253
- logger.debug('reconcileChildren', parentInstance, childrenElementArray);
254
- // parentInstance ←--------
255
- // | ↑ ↑
256
- // child parent parent
257
- // ↓ | |
258
- // instance -sibling→ instance -→ ....
259
- /**
260
- * 内部通过 index 生成 element 的 key
261
- * 通过前缀来避免和用户手动设置的 key 发生冲突
262
- * @param index
263
- * @returns 生成的 key
264
- */
265
- function getInnerElementIndexKey(index) {
266
- return `airx-element-inner-key:${index}`;
267
- }
268
- /**
269
- * 将 children 实例链转成 Map 便于此处消费
270
- * @param firstChild children 实例的第一个元素
271
- * @returns 从 firstChild 开始之后的所有 sibling 实例组成的 Map
272
- */
273
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
274
- function getChildrenInstanceMap(firstChild) {
275
- // 不使用递归是因为递归容易爆栈
276
- let nextIndex = 0;
277
- let nextChild = firstChild;
278
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
279
- const map = new Map();
280
- while (nextChild) {
281
- /* 如果有 key,则将 key 作为 map key,否则将 index 作为 key */
282
- if (nextChild.element?.props.key != null) {
283
- map.set(nextChild.element?.props.key, nextChild);
284
- }
285
- else {
286
- map.set(getInnerElementIndexKey(nextIndex), nextChild);
287
- }
288
- nextChild = nextChild.sibling;
289
- nextIndex += 1;
290
- }
291
- return map;
292
- }
293
- const newChildrenInstanceArray = [];
294
- const childrenInstanceMap = getChildrenInstanceMap(parentInstance.child);
295
- function getChildInstance(child, index) {
296
- if (child.props.key != null) {
297
- const key = child.props.key;
298
- const instance = childrenInstanceMap.get(key) || null;
299
- return [instance, () => childrenInstanceMap.delete(key)];
300
- }
301
- const innerKey = getInnerElementIndexKey(index);
302
- const instance = childrenInstanceMap.get(innerKey) || null;
303
- return [instance, () => childrenInstanceMap.delete(innerKey)];
304
- }
305
- /** 是否复用实例 */
306
- function isReuseInstance(instance, nextElement) {
307
- for (const plugin of appContext.plugins) {
308
- if (typeof plugin.isReuseInstance === 'function') {
309
- const result = plugin.isReuseInstance(instance, nextElement);
310
- // 任意一个插件要求不复用就不复用
311
- if (result === false)
312
- return false;
313
- }
314
- }
315
- return true;
316
- }
317
- function updateMemoProps(instance) {
318
- if (instance.element == null)
319
- return;
320
- if (instance.memoProps == null)
321
- instance.memoProps = {};
322
- // 简单来说就是以下几件事情
323
- // 始终保持 props 的引用不变
324
- // 1. 创建一个新对象来保存 beforeElement props 的状态
325
- // 2. 将新的 element 上的 props 引用设置为之前的 props
326
- // 3. 将新的 element 上的 props 更新到之前的 props 上去
327
- if (instance.memoProps != null) {
328
- for (const key in instance.memoProps) {
329
- delete instance.memoProps[key];
330
- }
331
- }
332
- // 将新的 props 更新上去
333
- for (const key in instance.element.props) {
334
- const value = instance.element.props[key];
335
- instance.memoProps[key] = value;
336
- }
337
- }
338
- function isNeedReRender(instance) {
339
- for (const plugin of appContext.plugins) {
340
- if (typeof plugin.isReRender === 'function') {
341
- const result = plugin.isReRender(instance);
342
- // 任意一个插件要求重新渲染就重新渲染
343
- if (result === true)
344
- return true;
345
- }
346
- }
347
- return false;
348
- }
349
- function getElementNamespace(element) {
350
- const ns = Object.keys(element.props)
351
- .filter(key => (key === 'xmlns' || key.startsWith('xmlns:')))
352
- .sort((a, b) => a.length - b.length);
353
- if (ns.length > 1) {
354
- console.log('airx currently does not support setting multiple xmlns');
355
- return '';
356
- }
357
- if (ns.some(i => i.startsWith('xmlns:'))) {
358
- console.log('airx does not currently support setting named namespaces,only supports default');
359
- return '';
360
- }
361
- // 原则上来说 html 仅支持设置默认的 namespace
362
- return element.props[ns[0]];
363
- }
364
- // 依次遍历 child 并和 instance 对比
365
- for (let index = 0; index < childrenElementArray.length; index++) {
366
- const element = childrenElementArray[index];
367
- const [instance, seize] = getChildInstance(element, index);
368
- if (instance && isReuseInstance(instance, element)) {
369
- seize(); // 从 childrenInstanceMap 中释放
370
- newChildrenInstanceArray.push(instance);
371
- instance.beforeElement = instance.element;
372
- instance.element = element;
373
- updateMemoProps(instance);
374
- // 如果父组件更新了,子组件全部都要更新
375
- if (instance.needReRender !== true && typeof element.type === 'function') {
376
- instance.needReRender = parentInstance.needReRender || isNeedReRender(instance);
377
- }
378
- }
379
- else {
380
- const context = new InnerAirxComponentContext();
381
- const elementNamespace = getElementNamespace(element);
382
- const instance = { element, context, elementNamespace };
383
- newChildrenInstanceArray.push(instance);
384
- context.instance = instance;
385
- updateMemoProps(instance);
386
- // 添加 ref 处理
387
- if ('ref' in instance.memoProps) {
388
- context.onMounted(() => {
389
- const ref = instance.memoProps.ref;
390
- // 如果组件有自己的 dom 并且 ref 为 state
391
- if (instance.domRef && isState(ref)) {
392
- ref.set(instance.domRef);
393
- return () => ref.set(undefined);
394
- }
395
- });
396
- }
397
- }
398
- }
399
- // 新的 node
400
- for (let index = 0; index < newChildrenInstanceArray.length; index++) {
401
- const instance = newChildrenInstanceArray[index];
402
- // 确保链的干净
403
- instance.parent = parentInstance;
404
- if (index === 0)
405
- parentInstance.child = instance;
406
- if (index > 0)
407
- newChildrenInstanceArray[index - 1].sibling = instance;
408
- if (index === newChildrenInstanceArray.length - 1)
409
- delete instance.sibling;
410
- // 处理 ElementNS: 继承父级 namespace
411
- if (!instance.elementNamespace && instance.parent?.elementNamespace) {
412
- // SVG 中 foreignObject 代表外来对象,起到隔离 namespace 的作用
413
- if (instance.parent.element?.type !== 'foreignObject') {
414
- instance.elementNamespace = instance.parent.elementNamespace;
415
- }
416
- }
417
- }
418
- // 剩余的是需要移除的
419
- if (childrenInstanceMap.size > 0) {
420
- if (parentInstance.deletions == null) {
421
- parentInstance.deletions = new Set();
422
- }
423
- childrenInstanceMap.forEach(instance => {
424
- parentInstance.deletions?.add(instance);
425
- });
426
- }
427
- logger.debug('parentInstance', parentInstance);
428
- }
429
- /**
430
- * 处理单个 instance
431
- * @param instance 当前处理的实例
432
- * @returns 返回下一个需要处理的 instance
433
- */
434
- function performUnitOfWork(pluginContext, instance, onUpdateRequire) {
435
- const element = instance.element;
436
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
437
- function childrenAsElements(children) {
438
- const childrenAsArray = Array.isArray(children) ? children : [children];
439
- function isComment(element) {
440
- if (element === '')
441
- return true;
442
- if (element == null)
443
- return true;
444
- if (element === false)
445
- return true;
446
- return false;
447
- }
448
- return childrenAsArray.flat(3).map(element => {
449
- if (isValidElement(element))
450
- return element;
451
- const elementType = isComment(element) ? 'comment' : 'text';
452
- const textContent = element === '' ? 'empty-string' : String(element);
453
- return createElement(elementType, { textContent });
454
- });
455
- }
456
- // airx 组件
457
- if (typeof element?.type === 'function') {
458
- if (instance.signalWatcher == null) {
459
- // Watch 是惰性的,只有当 Signal 被读取时才会触发 --!
460
- const signalWatcher = createWatch(async () => {
461
- instance.needReRender = true;
462
- onUpdateRequire?.(instance);
463
- queueMicrotask(() => {
464
- signalWatcher.watch();
465
- const paddings = signalWatcher.getPending();
466
- for (const padding of paddings)
467
- padding.get();
468
- });
469
- });
470
- instance.signalWatcher = signalWatcher;
471
- instance.context.addDisposer(() => signalWatcher.unwatch());
472
- }
473
- if (instance.childrenRender == null) {
474
- const component = element.type;
475
- const beforeContext = globalContext.current;
476
- globalContext.current = instance.context.getSafeContext();
477
- let componentReturnValue = undefined;
478
- try {
479
- componentReturnValue = component(instance.memoProps);
480
- }
481
- catch (error) {
482
- componentReturnValue = createErrorRender(error);
483
- }
484
- if (typeof componentReturnValue !== 'function') {
485
- const error = new Error('Component must return a render function');
486
- componentReturnValue = createErrorRender(error.message);
487
- }
488
- // restore context
489
- globalContext.current = beforeContext;
490
- instance.childrenRender = componentReturnValue;
491
- const childrenComputed = createComputed(() => {
492
- try {
493
- return instance.childrenRender();
494
- }
495
- catch (error) {
496
- return createErrorRender(error)();
497
- }
498
- });
499
- instance.signalWatcher.watch(childrenComputed);
500
- const children = childrenComputed.get();
501
- reconcileChildren(pluginContext, instance, childrenAsElements(children));
502
- }
503
- if (instance.needReRender) {
504
- let children;
505
- try {
506
- // 如果是由于父组件导致的子组件渲染
507
- // 直接使用 childrenComputed.get() 将读取到缓存值
508
- // 因此这里使用 childrenRender 来更新 children 的值
509
- children = instance.childrenRender();
510
- }
511
- catch (error) {
512
- children = createErrorRender(error)();
513
- }
514
- reconcileChildren(pluginContext, instance, childrenAsElements(children));
515
- delete instance.needReRender;
516
- }
517
- }
518
- // 浏览器组件/标签
519
- if (typeof element?.type === 'string') {
520
- if ('children' in element.props && Array.isArray(element.props.children)) {
521
- reconcileChildren(pluginContext, instance, childrenAsElements(element.props.children));
522
- }
523
- }
524
- // 优先处理 child
525
- if (instance.child) {
526
- return instance.child;
527
- }
528
- /**
529
- * 递归向上查找可用的兄弟 instance
530
- * @param instance
531
- * @returns 返回下一个需要处理的兄弟 instance
532
- */
533
- function returnSibling(instance) {
534
- if (instance.sibling) {
535
- return instance.sibling;
536
- }
537
- if (instance.parent) {
538
- return returnSibling(instance.parent);
539
- }
540
- return null;
541
- }
542
- return returnSibling(instance);
543
- }
544
-
545
- function camelToKebab(str) {
546
- return str.replace(/([A-Z])/g, (match, p1, offset) => {
547
- if (offset === 0) {
548
- return p1.toLowerCase();
549
- }
550
- else {
551
- return '-' + p1.toLowerCase();
552
- }
553
- });
554
- }
555
- class ServerElement {
556
- nodeName;
557
- static createTextNode(content) {
558
- const dom = new ServerElement('#text');
559
- dom.content = content;
560
- return dom;
561
- }
562
- static createComment(content) {
563
- const dom = new ServerElement('#comment');
564
- dom.content = content;
565
- return dom;
566
- }
567
- static createElement(tag) {
568
- return new ServerElement(tag);
569
- }
570
- constructor(nodeName) {
571
- this.nodeName = nodeName;
572
- this.style = {};
573
- this.content = '';
574
- this.children = [];
575
- this.className = '';
576
- this.attributes = new Map();
577
- }
578
- firstChild;
579
- nextSibling;
580
- parentNode;
581
- className;
582
- style;
583
- content;
584
- children;
585
- attributes;
586
- removeChild(dom) {
587
- /* eslint-disable @typescript-eslint/ban-ts-comment */
588
- const index = this.children.findIndex(v => v === dom);
589
- if (index != -1)
590
- this.children.splice(index, 1);
591
- // @ts-ignore
592
- this.firstChild = undefined;
593
- // @ts-ignore
594
- this.nextSibling = undefined;
595
- // @ts-ignore
596
- this.parentNode = undefined;
597
- /* eslint-enable @typescript-eslint/ban-ts-comment */
598
- }
599
- appendChild(dom) {
600
- /* eslint-disable @typescript-eslint/ban-ts-comment */
601
- // @ts-ignore
602
- dom.parentNode = this;
603
- if (this.children.length > 0) {
604
- // @ts-ignore
605
- this.children[this.children.length - 1].nextSibling = dom;
606
- }
607
- // @ts-ignore
608
- this.firstChild = this.children[0];
609
- this.children.push(dom);
610
- /* eslint-enable @typescript-eslint/ban-ts-comment */
611
- }
612
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
613
- setAttribute(name, value) {
614
- if (value === '')
615
- return this.attributes.delete(name);
616
- /* eslint-disable @typescript-eslint/ban-ts-comment */
617
- // @ts-ignore
618
- if (name === 'class')
619
- return this.className = value;
620
- // @ts-ignore
621
- if (name === 'style')
622
- return this.style = value;
623
- /* eslint-enable @typescript-eslint/ban-ts-comment */
624
- this.attributes.set(name, value);
625
- }
626
- removeAttribute(name) {
627
- this.attributes.delete(name);
628
- }
629
- toString() {
630
- if (this.nodeName === '#text')
631
- return this.content;
632
- if (this.nodeName === '#comment')
633
- return this.content;
634
- const styleString = Object.entries(this.style)
635
- .map(([key, value]) => `${camelToKebab(key)}:${value}`)
636
- .join(';');
637
- const attributes = [...this.attributes.entries()];
638
- if (styleString.length > 0)
639
- attributes.push(['style', styleString]);
640
- if (this.className.length > 0)
641
- attributes.push(['class', this.className]);
642
- const attributesString = attributes.map(([name, value]) => ` ${name}="${value}"`).join('');
643
- return `<${this.nodeName}${attributesString}>${this.children.map(child => child.toString()).join('')}</${this.nodeName}>`;
644
- }
645
- }
646
- function render$1(pluginContext, element, onComplete) {
647
- const rootInstance = {
648
- domRef: ServerElement.createElement('div'),
649
- context: new InnerAirxComponentContext()
650
- };
651
- rootInstance.context.instance = rootInstance;
652
- const context = {
653
- rootInstance,
654
- nextUnitOfWork: null,
655
- needCommitDom: false
656
- };
657
- const appInstance = {
658
- element,
659
- parent: context.rootInstance,
660
- memoProps: { ...element.props },
661
- context: new InnerAirxComponentContext()
662
- };
663
- appInstance.context.instance = appInstance;
664
- context.rootInstance.child = appInstance;
665
- context.nextUnitOfWork = appInstance;
666
- /**
667
- * 提交 Dom 变化
668
- */
669
- function commitDom(rootInstance, rootNode) {
670
- const logger = createLogger('commitDom');
671
- logger.debug('commitDom', rootInstance);
672
- function updateDomProperties(dom, nextProps, prevProps = {}) {
673
- const isKey = (key) => key === 'key';
674
- const isRef = (key) => key === 'ref';
675
- const isStyle = (key) => key === 'style';
676
- const isClass = (key) => key === 'class';
677
- const isEvent = (key) => key.startsWith("on");
678
- const isChildren = (key) => key === 'children';
679
- const isGone = (_prev, next) => (key) => !(key in next);
680
- const isNew = (prev, next) => (key) => prev[key] !== next[key];
681
- const isProperty = (key) => !isChildren(key) && !isEvent(key) && !isStyle(key) && !isClass(key) && !isKey(key) && !isRef(key);
682
- // https://developer.mozilla.org/zh-CN/docs/Web/API/Node
683
- if (dom.nodeName === '#text' || dom.nodeName === '#comment') {
684
- const textNode = dom;
685
- if (textNode.nodeValue !== nextProps.textContent) {
686
- textNode.nodeValue = String(nextProps.textContent);
687
- }
688
- return;
689
- }
690
- // remove old style
691
- const oldStyle = prevProps?.style;
692
- if (typeof oldStyle === 'object' && oldStyle != null) {
693
- Object.keys(oldStyle).forEach(key => {
694
- /* eslint-disable @typescript-eslint/no-explicit-any */
695
- delete dom.style[key];
696
- /* eslint-enable @typescript-eslint/no-explicit-any */
697
- });
698
- }
699
- // add new style
700
- const newStyle = nextProps?.style;
701
- if (typeof newStyle === 'object' && newStyle != null) {
702
- Object.keys(newStyle).forEach((key) => {
703
- /* eslint-disable @typescript-eslint/no-explicit-any */
704
- const value = newStyle?.[key];
705
- dom.style[key] = value == null ? '' : value;
706
- /* eslint-enable @typescript-eslint/no-explicit-any */
707
- });
708
- }
709
- if (dom.className !== nextProps?.class) {
710
- if (!nextProps?.class) {
711
- dom.removeAttribute('class');
712
- }
713
- else if (typeof nextProps?.class === 'string') {
714
- dom.setAttribute('class', nextProps?.class);
715
- }
716
- }
717
- // Remove old properties
718
- Object.keys(prevProps)
719
- .filter(isProperty)
720
- .filter(isGone(prevProps, nextProps))
721
- .forEach(name => dom.removeAttribute(name));
722
- // Set new or changed properties
723
- Object.keys(nextProps)
724
- .filter(isProperty)
725
- .filter(isNew(prevProps, nextProps))
726
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
727
- .forEach(name => dom.setAttribute(name, nextProps[name]));
728
- }
729
- function getParentDom(instance) {
730
- if (instance.parent?.domRef != null) {
731
- return instance.parent.domRef;
732
- }
733
- if (instance.parent) {
734
- return getParentDom(instance.parent);
735
- }
736
- throw new Error('Cant find dom');
737
- }
738
- /**
739
- * 查找 instance 下所有的一级 dom
740
- * @param instance
741
- * @returns
742
- */
743
- function getChildDoms(instance) {
744
- const domList = [];
745
- const todoList = [instance];
746
- while (todoList.length > 0) {
747
- const current = todoList.pop();
748
- // 找到真实 dom 直接提交
749
- if (current?.domRef != null) {
750
- domList.push(current.domRef);
751
- }
752
- // 有子节点但是无真实 dom,向下继续查找
753
- if (current?.domRef == null) {
754
- if (current?.child != null) {
755
- todoList.push(current.child);
756
- }
757
- }
758
- // 可能有兄弟节点,则需要继续查找
759
- if (current?.sibling != null) {
760
- todoList.push(current.sibling);
761
- }
762
- }
763
- return domList;
764
- }
765
- function commitInstanceDom(nextInstance, oldNode) {
766
- // 移除标删元素
767
- if (nextInstance.deletions) {
768
- for (const deletion of nextInstance.deletions) {
769
- const domList = getChildDoms(deletion);
770
- for (let index = 0; index < domList.length; index++) {
771
- const dom = domList[index];
772
- if (dom && dom.parentNode)
773
- dom.parentNode.removeChild(dom);
774
- }
775
- deletion.context.triggerUnmounted();
776
- }
777
- nextInstance.deletions.clear();
778
- }
779
- // 创建 dom
780
- if (nextInstance.domRef == null) {
781
- if (nextInstance.element == null)
782
- throw new Error('???');
783
- if (typeof nextInstance.element.type === 'string') {
784
- if (nextInstance.element.type === 'text') {
785
- const textContent = nextInstance.element.props.textContent;
786
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
787
- nextInstance.domRef = ServerElement.createTextNode(textContent);
788
- }
789
- else if (nextInstance.element.type === 'comment') {
790
- const textContent = nextInstance.element.props.textContent;
791
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
792
- nextInstance.domRef = ServerElement.createComment(textContent);
793
- }
794
- else {
795
- nextInstance.domRef = ServerElement.createElement(nextInstance.element.type);
796
- }
797
- }
798
- }
799
- // 更新属性
800
- if (nextInstance.domRef != null && nextInstance.element != null) {
801
- updateDomProperties(nextInstance.domRef, nextInstance.element.props, nextInstance.beforeElement?.props);
802
- }
803
- // 插入 parent
804
- // TODO: 针对仅移动时优化
805
- if (nextInstance.domRef != null) {
806
- if (oldNode !== nextInstance.domRef) {
807
- if (nextInstance.domRef.parentNode) {
808
- nextInstance.domRef.parentNode.removeChild(nextInstance.domRef);
809
- }
810
- const parentDom = getParentDom(nextInstance);
811
- parentDom.appendChild(nextInstance.domRef);
812
- }
813
- }
814
- }
815
- function commitWalkV2(initInstance, initNode) {
816
- // 创建一个栈,将根节点压入栈中
817
- const stack = [[initInstance, initNode]];
818
- while (stack.length > 0) {
819
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
820
- const stackLayer = stack.pop();
821
- if (typeof stackLayer === 'function') {
822
- stackLayer();
823
- continue;
824
- }
825
- const [instance, node] = stackLayer;
826
- commitInstanceDom(instance, node);
827
- // stack 是先入后出
828
- // 实际上是先渲染 child
829
- // 这里然后再渲染 sibling
830
- // 执行生命周期的 Mount
831
- stack.push(() => instance.context.triggerMounted());
832
- // 更新下一个兄弟节点
833
- if (instance.sibling != null) {
834
- const siblingNode = instance.domRef
835
- ? instance.domRef.nextSibling
836
- : node?.nextSibling;
837
- stack.push([instance.sibling, siblingNode || undefined]);
838
- }
839
- // 更新下一个子节点
840
- if (instance.child != null) {
841
- const childNode = instance.domRef
842
- ? instance.domRef.firstChild
843
- : node;
844
- stack.push([instance.child, childNode || undefined]);
845
- }
846
- }
847
- }
848
- commitWalkV2(rootInstance, rootNode);
849
- }
850
- while (context.nextUnitOfWork) {
851
- context.nextUnitOfWork = performUnitOfWork(pluginContext, context.nextUnitOfWork);
852
- }
853
- commitDom(context.rootInstance.child, context.rootInstance.domRef?.firstChild || undefined);
854
- onComplete(context.rootInstance.domRef?.toString() || '');
855
- }
856
-
857
- function render(pluginContext, element, domRef) {
858
- const rootInstance = {
859
- domRef,
860
- context: new InnerAirxComponentContext()
861
- };
862
- rootInstance.context.instance = rootInstance;
863
- const context = {
864
- rootInstance,
865
- nextUnitOfWork: null,
866
- needCommitDom: false
867
- };
868
- const appInstance = {
869
- element,
870
- parent: context.rootInstance,
871
- memoProps: { ...element.props },
872
- context: new InnerAirxComponentContext()
873
- };
874
- appInstance.context.instance = appInstance;
875
- context.rootInstance.child = appInstance;
876
- context.nextUnitOfWork = appInstance;
877
- /**
878
- * 提交 Dom 变化
879
- */
880
- function commitDom(rootInstance, rootNode) {
881
- const logger = createLogger('commitDom');
882
- logger.debug('commitDom', rootInstance);
883
- function updateDomProperties(dom, nextProps, prevProps = {}) {
884
- for (const plugin of pluginContext.plugins) {
885
- if (plugin.updateDom)
886
- plugin.updateDom(dom, nextProps, prevProps);
887
- }
888
- }
889
- function getParentDom(instance) {
890
- if (instance.parent?.domRef != null) {
891
- return instance.parent.domRef;
892
- }
893
- if (instance.parent) {
894
- return getParentDom(instance.parent);
895
- }
896
- throw new Error('Cant find dom');
897
- }
898
- /**
899
- * 查找 instance 下所有的一级 dom
900
- * @param instance
901
- * @returns
902
- */
903
- function getChildDoms(instance) {
904
- const domList = [];
905
- const todoList = [instance];
906
- while (todoList.length > 0) {
907
- const current = todoList.pop();
908
- // 找到真实 dom 直接提交
909
- if (current?.domRef != null) {
910
- domList.push(current.domRef);
911
- }
912
- // 有子节点但是无真实 dom,向下继续查找
913
- if (current?.domRef == null) {
914
- if (current?.child != null) {
915
- todoList.push(current.child);
916
- }
917
- }
918
- // 可能有兄弟节点,则需要继续查找
919
- if (current?.sibling != null) {
920
- todoList.push(current.sibling);
921
- }
922
- }
923
- return domList;
924
- }
925
- function commitInstanceDom(nextInstance, oldNode) {
926
- // 移除标删元素
927
- if (nextInstance.deletions) {
928
- for (const deletion of nextInstance.deletions) {
929
- const domList = getChildDoms(deletion);
930
- for (let index = 0; index < domList.length; index++) {
931
- const dom = domList[index];
932
- if (dom && dom.parentNode)
933
- dom.parentNode.removeChild(dom);
934
- }
935
- deletion.context.triggerUnmounted();
936
- }
937
- nextInstance.deletions.clear();
938
- }
939
- // 创建 dom
940
- if (nextInstance.domRef == null) {
941
- if (nextInstance.element == null)
942
- throw new Error('???');
943
- if (typeof nextInstance.element.type === 'string') {
944
- if (nextInstance.element.type === 'text') {
945
- const textContent = nextInstance.element.props.textContent;
946
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
947
- nextInstance.domRef = document.createTextNode(textContent);
948
- }
949
- else if (nextInstance.element.type === 'comment') {
950
- const textContent = nextInstance.element.props.textContent;
951
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
952
- nextInstance.domRef = document.createComment(textContent);
953
- }
954
- else {
955
- nextInstance.domRef = nextInstance.elementNamespace
956
- ? document.createElementNS(nextInstance.elementNamespace, nextInstance.element.type)
957
- : document.createElement(nextInstance.element.type);
958
- }
959
- if (nextInstance.domRef) {
960
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
961
- nextInstance.domRef.airxInstance = nextInstance;
962
- }
963
- }
964
- }
965
- // 更新属性
966
- if (nextInstance.domRef != null && nextInstance.element != null) {
967
- updateDomProperties(nextInstance.domRef, nextInstance.element.props, nextInstance.beforeElement?.props);
968
- }
969
- // 插入 parent
970
- // TODO: 针对仅移动时优化
971
- if (nextInstance.domRef != null) {
972
- if (oldNode !== nextInstance.domRef) {
973
- if (nextInstance.domRef.parentNode) {
974
- nextInstance.domRef.parentNode.removeChild(nextInstance.domRef);
975
- }
976
- const parentDom = getParentDom(nextInstance);
977
- parentDom.appendChild(nextInstance.domRef);
978
- }
979
- }
980
- }
981
- function commitWalkV2(initInstance, initNode) {
982
- // 创建一个栈,将根节点压入栈中
983
- const stack = [[initInstance, initNode]];
984
- while (stack.length > 0) {
985
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
986
- const stackLayer = stack.pop();
987
- if (typeof stackLayer === 'function') {
988
- stackLayer();
989
- continue;
990
- }
991
- const [instance, node] = stackLayer;
992
- commitInstanceDom(instance, node);
993
- // stack 是先入后出
994
- // 实际上是先渲染 child
995
- // 这里然后再渲染 sibling
996
- // 执行生命周期的 Mount
997
- stack.push(() => instance.context.triggerMounted());
998
- // 更新下一个兄弟节点
999
- if (instance.sibling != null) {
1000
- const siblingNode = instance.domRef
1001
- ? instance.domRef.nextSibling
1002
- : node?.nextSibling;
1003
- stack.push([instance.sibling, siblingNode || undefined]);
1004
- }
1005
- // 更新下一个子节点
1006
- if (instance.child != null) {
1007
- const childNode = instance.domRef
1008
- ? instance.domRef.firstChild
1009
- : node;
1010
- stack.push([instance.child, childNode || undefined]);
1011
- }
1012
- }
1013
- }
1014
- commitWalkV2(rootInstance, rootNode);
1015
- }
1016
- function onUpdateRequire() {
1017
- if (context.nextUnitOfWork == null && context.rootInstance.child) {
1018
- context.nextUnitOfWork = context.rootInstance.child;
1019
- }
1020
- }
1021
- /**
1022
- * 调度
1023
- */
1024
- function workLoop(deadline) {
1025
- let shouldYield = false;
1026
- const logger = createLogger('workLoop');
1027
- while (context.nextUnitOfWork && !shouldYield) {
1028
- logger.debug('nextUnitOfWork', context.nextUnitOfWork);
1029
- context.nextUnitOfWork = performUnitOfWork(pluginContext, context.nextUnitOfWork, onUpdateRequire);
1030
- if (context.nextUnitOfWork == null)
1031
- context.needCommitDom = true;
1032
- if (deadline)
1033
- shouldYield = deadline.timeRemaining() < 1;
1034
- }
1035
- if (context.needCommitDom && context.rootInstance.child) {
1036
- commitDom(context.rootInstance.child, context.rootInstance.domRef?.firstChild || undefined);
1037
- context.needCommitDom = false;
1038
- }
1039
- // TODO: 兼容性
1040
- requestIdleCallback(workLoop);
1041
- }
1042
- // 开始调度
1043
- workLoop();
1044
- return context.rootInstance;
1045
- }
1046
-
1047
- class BasicLogic {
1048
- logger = createLogger('basicLogicPlugin');
1049
- isSameProps(preProps, nextProps) {
1050
- if (Object.is(nextProps, preProps)) {
1051
- return true;
1052
- }
1053
- if (typeof preProps !== 'object'
1054
- || typeof nextProps !== 'object'
1055
- || preProps === null
1056
- || nextProps === null) {
1057
- this.logger.debug('props must be an object');
1058
- return false;
1059
- }
1060
- // 对应 key 的值不相同返回 false
1061
- const prevKeys = Object.keys(preProps);
1062
- for (let index = 0; index < prevKeys.length; index++) {
1063
- const key = prevKeys[index];
1064
- if (key !== 'children' && key !== 'key') {
1065
- if (!Object.hasOwn(nextProps, key))
1066
- return false;
1067
- if (!Object.is(preProps[key], nextProps[key]))
1068
- return false;
1069
- }
1070
- if (key === 'children') {
1071
- const prevChildren = preProps['children'];
1072
- const nextChildren = nextProps['children'];
1073
- // children 都是空的,则无需更新
1074
- if (prevChildren.length === 0 && nextChildren.length === 0)
1075
- return true;
1076
- // 简单比较一下 child 的引用
1077
- for (let index = 0; index < prevChildren.length; index++) {
1078
- const prevChild = prevChildren[index];
1079
- const nextChild = nextChildren[index];
1080
- if (prevChild !== nextChild)
1081
- return false;
1082
- if (typeof prevChild !== typeof nextChild)
1083
- return false;
1084
- }
1085
- }
1086
- return true;
1087
- }
1088
- return false;
1089
- }
1090
- isReRender(instance) {
1091
- const nextProps = instance.element?.props;
1092
- const preProps = instance.beforeElement?.props;
1093
- if (!this.isSameProps(preProps, nextProps))
1094
- return true;
1095
- }
1096
- updateDom(dom, nextProps, prevProps = {}) {
1097
- this.logger.debug('updateDom', dom, nextProps, prevProps);
1098
- const isKey = (key) => key === 'key';
1099
- const isRef = (key) => key === 'ref';
1100
- const isStyle = (key) => key === 'style';
1101
- const isClass = (key) => key === 'class';
1102
- const isEvent = (key) => key.startsWith("on");
1103
- const isChildren = (key) => key === 'children';
1104
- const isGone = (_prev, next) => (key) => !(key in next);
1105
- const isNew = (prev, next) => (key) => prev[key] !== next[key];
1106
- const isProperty = (key) => !isChildren(key) && !isEvent(key) && !isStyle(key) && !isClass(key) && !isKey(key) && !isRef(key);
1107
- // https://developer.mozilla.org/zh-CN/docs/Web/API/Node
1108
- if (dom.nodeName === '#text' || dom.nodeName === '#comment') {
1109
- const textNode = dom;
1110
- if (textNode.nodeValue !== nextProps.textContent) {
1111
- textNode.nodeValue = String(nextProps.textContent);
1112
- }
1113
- return;
1114
- }
1115
- // remove old style
1116
- const oldStyle = prevProps?.style;
1117
- if (typeof oldStyle === 'object' && oldStyle != null) {
1118
- if (!('style' in dom) || !dom.style)
1119
- return;
1120
- Object.keys(oldStyle).forEach(key => {
1121
- /* eslint-disable @typescript-eslint/no-explicit-any */
1122
- if ('style' in dom && dom.style) {
1123
- delete dom.style[key];
1124
- /* eslint-enable @typescript-eslint/no-explicit-any */
1125
- }
1126
- });
1127
- }
1128
- // add new style
1129
- const newStyle = nextProps?.style;
1130
- if (typeof newStyle === 'object' && newStyle != null) {
1131
- if (!('style' in dom) || !dom.style)
1132
- return;
1133
- Object.keys(newStyle).forEach((key) => {
1134
- /* eslint-disable @typescript-eslint/no-explicit-any */
1135
- const value = newStyle?.[key];
1136
- dom.style[key] = value == null ? '' : value;
1137
- /* eslint-enable @typescript-eslint/no-explicit-any */
1138
- });
1139
- }
1140
- if (dom.className !== nextProps?.class) {
1141
- if (!nextProps?.class) {
1142
- dom.removeAttribute('class');
1143
- }
1144
- else if (typeof nextProps?.class === 'string') {
1145
- dom.setAttribute('class', nextProps?.class);
1146
- }
1147
- }
1148
- //Remove old or changed event listeners
1149
- Object.keys(prevProps)
1150
- .filter(isEvent)
1151
- .filter(key => !(key in nextProps) ||
1152
- isNew(prevProps, nextProps)(key))
1153
- .forEach(name => {
1154
- const eventType = name
1155
- .toLowerCase()
1156
- .substring(2);
1157
- if (prevProps[name] == null)
1158
- return;
1159
- if (typeof prevProps[name] !== 'function') {
1160
- console.error('EventListener is not a function');
1161
- }
1162
- else {
1163
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1164
- dom.removeEventListener(eventType, prevProps[name]);
1165
- }
1166
- });
1167
- // Add event listeners
1168
- Object.keys(nextProps)
1169
- .filter(isEvent)
1170
- .filter(isNew(prevProps, nextProps))
1171
- .forEach(name => {
1172
- const eventType = name
1173
- .toLowerCase()
1174
- .substring(2);
1175
- if (nextProps[name] == null)
1176
- return;
1177
- if (typeof nextProps[name] !== 'function') {
1178
- console.error('EventListener is not a function');
1179
- }
1180
- else {
1181
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1182
- dom.addEventListener(eventType, nextProps[name]);
1183
- }
1184
- });
1185
- // Remove old properties
1186
- Object.keys(prevProps)
1187
- .filter(isProperty)
1188
- .filter(isGone(prevProps, nextProps))
1189
- .forEach(name => dom.removeAttribute(name));
1190
- // Set new or changed properties
1191
- Object.keys(nextProps)
1192
- .filter(isProperty)
1193
- .filter(isNew(prevProps, nextProps))
1194
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1195
- .forEach(name => dom.setAttribute(name, nextProps[name]));
1196
- }
1197
- isReuseInstance(instance, nextElement) {
1198
- if (instance && instance.element && instance.element.type !== nextElement.type) {
1199
- return false;
1200
- }
1201
- }
1202
- }
1203
-
1204
- class InjectSystem {
1205
- getProvideValueForParent(instance, key) {
1206
- if (instance && instance.context) {
1207
- const value = instance.context.providedMap.get(key);
1208
- if (value != undefined)
1209
- return value;
1210
- if (instance.parent) {
1211
- return this.getProvideValueForParent(instance.parent, key);
1212
- }
1213
- }
1214
- return undefined;
1215
- }
1216
- isReuseInstance(instance) {
1217
- const injectedKeys = [...instance.context.injectedMap.keys()];
1218
- for (let index = 0; index < injectedKeys.length; index++) {
1219
- const key = injectedKeys[index];
1220
- const currentValue = instance.context.injectedMap.get(key);
1221
- const parentValue = this.getProvideValueForParent(instance.parent, key);
1222
- // 如果发现任何值发生变化,则重建实例
1223
- if (parentValue !== currentValue)
1224
- return false;
1225
- }
1226
- }
1227
- }
1228
-
1229
- class PluginContext {
1230
- plugins = [
1231
- new BasicLogic(),
1232
- new InjectSystem()
1233
- ];
1234
- registerPlugin(...plugins) {
1235
- this.plugins.push(...plugins);
1236
- }
1237
- }
1238
-
1239
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1240
- function createApp(element) {
1241
- const appContext = new PluginContext();
1242
- const ensureAsElement = (element) => {
1243
- if (typeof element === 'function') {
1244
- return createElement(element, {});
1245
- }
1246
- return element;
1247
- };
1248
- const app = {
1249
- plugin: (...plugins) => {
1250
- appContext.registerPlugin(...plugins);
1251
- return app;
1252
- },
1253
- mount: (container) => {
1254
- container.innerHTML = ''; // 先清空再说
1255
- render(appContext, ensureAsElement(element), container);
1256
- return app;
1257
- },
1258
- renderToHTML: () => {
1259
- return new Promise(resolve => {
1260
- render$1(appContext, ensureAsElement(element), resolve);
1261
- });
1262
- }
1263
- };
1264
- return app;
1265
- }
1266
-
1267
- export { Fragment, component, createApp, createElement, inject, onMounted, onUnmounted, provide };
1268
- //# sourceMappingURL=index.js.map