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