@easy-editor/react-renderer 0.0.17 → 1.0.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 (48) hide show
  1. package/README.md +12 -1
  2. package/dist/adapter/index.d.ts +17 -0
  3. package/dist/{renderer-core/base.d.ts → base.d.ts} +2 -2
  4. package/dist/component.d.ts +2 -0
  5. package/dist/components/FaultComponent.d.ts +4 -0
  6. package/dist/components/NotFoundComponent.d.ts +4 -0
  7. package/dist/{renderer-core/hoc → hoc}/leaf.d.ts +2 -1
  8. package/dist/{cjs/index.js → index.cjs} +374 -583
  9. package/dist/index.d.ts +10 -3
  10. package/dist/index.js +324 -516
  11. package/dist/page.d.ts +2 -0
  12. package/dist/renderer.d.ts +2 -0
  13. package/dist/setting-renderer/context.d.ts +8 -0
  14. package/dist/setting-renderer/index.d.ts +8 -0
  15. package/dist/types.d.ts +7 -0
  16. package/dist/utils/index.d.ts +2 -0
  17. package/dist/utils/is.d.ts +3 -0
  18. package/package.json +16 -21
  19. package/dist/cjs/index.development.js +0 -2734
  20. package/dist/cjs/index.development.js.map +0 -1
  21. package/dist/cjs/index.js.map +0 -1
  22. package/dist/cjs/index.production.js +0 -2734
  23. package/dist/cjs/index.production.js.map +0 -1
  24. package/dist/configure-renderer/context.d.ts +0 -13
  25. package/dist/configure-renderer/index.d.ts +0 -10
  26. package/dist/esm/index.development.js +0 -2699
  27. package/dist/esm/index.development.js.map +0 -1
  28. package/dist/esm/index.js +0 -2699
  29. package/dist/esm/index.js.map +0 -1
  30. package/dist/esm/index.production.js +0 -2699
  31. package/dist/esm/index.production.js.map +0 -1
  32. package/dist/renderer-core/adapter/index.d.ts +0 -17
  33. package/dist/renderer-core/component.d.ts +0 -2
  34. package/dist/renderer-core/components/FaultComponent.d.ts +0 -7
  35. package/dist/renderer-core/components/NotFoundComponent.d.ts +0 -7
  36. package/dist/renderer-core/index.d.ts +0 -9
  37. package/dist/renderer-core/page.d.ts +0 -2
  38. package/dist/renderer-core/renderer.d.ts +0 -2
  39. package/dist/renderer-core/types.d.ts +0 -187
  40. package/dist/renderer-core/utils/classnames.d.ts +0 -1
  41. package/dist/renderer-core/utils/common.d.ts +0 -53
  42. package/dist/renderer-core/utils/index.d.ts +0 -4
  43. package/dist/renderer-core/utils/logger.d.ts +0 -5
  44. /package/dist/{renderer-core/context.d.ts → context.d.ts} +0 -0
  45. /package/dist/{renderer-core/hoc → hoc}/comp.d.ts +0 -0
  46. /package/dist/{renderer-core/hoc → hoc}/index.d.ts +0 -0
  47. /package/dist/{configure-renderer → setting-renderer}/SettingSetter.d.ts +0 -0
  48. /package/dist/{renderer-core/utils → utils}/hoc.d.ts +0 -0
@@ -1,2699 +0,0 @@
1
- import { observer } from 'mobx-react';
2
- import { createContext, useContext, useMemo, Component, forwardRef, createElement, PureComponent } from 'react';
3
- import { isSetterConfig, createLogger, isJSExpression, DESIGNER_EVENT, TRANSFORM_STAGE, isJSFunction, logger as logger$1 } from '@easy-editor/core';
4
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
-
6
- const SettingRendererContext = /*#__PURE__*/createContext({});
7
- const useSettingRendererContext = () => {
8
- try {
9
- return useContext(SettingRendererContext);
10
- } catch (error) {
11
- console.warn('useSettingRendererContext must be used within a SettingRendererContextProvider');
12
- }
13
- return {};
14
- };
15
-
16
- const getSetterInfo = field => {
17
- const {
18
- extraProps,
19
- setter
20
- } = field;
21
- const {
22
- defaultValue
23
- } = extraProps;
24
- let setterProps = {};
25
- let setterType;
26
- let initialValue = null;
27
- if (isSetterConfig(setter)) {
28
- setterType = setter.componentName;
29
- if (setter.props) {
30
- setterProps = setter.props;
31
- if (typeof setterProps === 'function') {
32
- setterProps = setterProps(field);
33
- }
34
- }
35
- if (setter.defaultValue != null) {
36
- initialValue = setter.defaultValue;
37
- }
38
- } else if (setter) {
39
- setterType = setter;
40
- }
41
- if (defaultValue != null && !('defaultValue' in setterProps)) {
42
- setterProps.defaultValue = defaultValue;
43
- if (initialValue == null) {
44
- initialValue = defaultValue;
45
- }
46
- }
47
- if (field.valueState === -1) {
48
- setterProps.multiValue = true;
49
- }
50
-
51
- // 根据是否支持变量配置做相应的更改
52
- const supportVariable = field.extraProps?.supportVariable;
53
- const isUseVariableSetter = supportVariable;
54
- if (isUseVariableSetter === false) {
55
- return {
56
- setterProps,
57
- initialValue,
58
- setterType
59
- };
60
- }
61
- return {
62
- setterProps,
63
- setterType,
64
- initialValue
65
- };
66
- };
67
- const SettingSetter = observer(({
68
- field,
69
- children
70
- }) => {
71
- const {
72
- setterManager
73
- } = useSettingRendererContext();
74
- const {
75
- extraProps
76
- } = field;
77
- const visible = extraProps?.condition && typeof extraProps.condition === 'function' ? extraProps.condition(field) !== false : true;
78
- if (!visible) {
79
- return null;
80
- }
81
- const {
82
- setterProps = {},
83
- setterType,
84
- initialValue = null
85
- } = getSetterInfo(field);
86
- const onChange = extraProps?.onChange;
87
- const value = field.valueState === -1 ? null : field.getValue();
88
- const {
89
- component: SetterComponent,
90
- props: mixedSetterProps
91
- } = setterManager.createSetterContent(setterType, setterProps);
92
- return /*#__PURE__*/jsx(SetterComponent, {
93
- field: field,
94
- selected: field.top?.getNode(),
95
- initialValue: initialValue,
96
- value: value,
97
- onChange: newVal => {
98
- field.setValue(newVal);
99
- onChange?.(field, newVal);
100
- },
101
- onInitial: () => {
102
- if (initialValue == null) {
103
- return;
104
- }
105
- const value = typeof initialValue === 'function' ? initialValue(field) : initialValue;
106
- field.setValue(value, true);
107
- },
108
- removeProp: () => {
109
- if (field.name) {
110
- field.parent.clearPropValue(field.name);
111
- }
112
- },
113
- ...mixedSetterProps,
114
- children: children
115
- }, field.id);
116
- });
117
-
118
- const SettingFieldItem = observer(({
119
- field
120
- }) => {
121
- const {
122
- customFieldItem
123
- } = useSettingRendererContext();
124
- if (customFieldItem) {
125
- return customFieldItem(field, /*#__PURE__*/jsx(SettingSetter, {
126
- field: field
127
- }));
128
- }
129
- return /*#__PURE__*/jsxs("div", {
130
- className: "space-y-2",
131
- children: [/*#__PURE__*/jsx("label", {
132
- htmlFor: field.id,
133
- className: "block text-sm font-medium text-gray-700",
134
- children: field.title
135
- }), /*#__PURE__*/jsx(SettingSetter, {
136
- field: field
137
- })]
138
- });
139
- });
140
- const SettingFieldGroup = observer(({
141
- field
142
- }) => {
143
- const {
144
- customFieldGroup
145
- } = useSettingRendererContext();
146
- if (customFieldGroup) {
147
- return customFieldGroup(field, /*#__PURE__*/jsx(SettingSetter, {
148
- field: field,
149
- children: field.items?.map(item => /*#__PURE__*/jsx(SettingFieldView, {
150
- field: item
151
- }, item.id))
152
- }));
153
- }
154
-
155
- // 如果 field 没有 setter,则理解为其 父级 field 的 items 数据
156
- if (!field.setter) {
157
- return field.items?.map(item => /*#__PURE__*/jsx(SettingFieldView, {
158
- field: item
159
- }, item.id));
160
- }
161
- return /*#__PURE__*/jsx(SettingSetter, {
162
- field: field,
163
- children: field.items?.map(item => /*#__PURE__*/jsx(SettingFieldView, {
164
- field: item
165
- }, item.id))
166
- });
167
- });
168
- const SettingFieldView = ({
169
- field
170
- }) => {
171
- if (field.isGroup) {
172
- return /*#__PURE__*/jsx(SettingFieldGroup, {
173
- field: field
174
- }, field.id);
175
- } else {
176
- return /*#__PURE__*/jsx(SettingFieldItem, {
177
- field: field
178
- }, field.id);
179
- }
180
- };
181
- const SettingRender = observer(props => {
182
- const {
183
- editor,
184
- customFieldItem,
185
- customFieldGroup
186
- } = props;
187
- const designer = editor.get('designer');
188
- const setterManager = editor.get('setterManager');
189
- const {
190
- settingsManager
191
- } = designer;
192
- const {
193
- settings
194
- } = settingsManager;
195
- const items = settings?.items;
196
- const ctx = useMemo(() => {
197
- const ctx = {};
198
- ctx.setterManager = setterManager;
199
- ctx.settingsManager = settingsManager;
200
- ctx.customFieldItem = customFieldItem;
201
- ctx.customFieldGroup = customFieldGroup;
202
- return ctx;
203
- }, [setterManager, settingsManager, customFieldItem, customFieldGroup]);
204
- if (!settings) {
205
- // 未选中节点,提示选中 或者 显示根节点设置
206
- return /*#__PURE__*/jsx("div", {
207
- className: "lc-settings-main",
208
- children: /*#__PURE__*/jsx("div", {
209
- className: "lc-settings-notice",
210
- children: /*#__PURE__*/jsx("p", {
211
- children: "Please select a node in canvas"
212
- })
213
- })
214
- });
215
- }
216
-
217
- // 当节点被锁定,且未开启锁定后容器可设置属性
218
- if (settings.isLocked) {
219
- return /*#__PURE__*/jsx("div", {
220
- className: "lc-settings-main",
221
- children: /*#__PURE__*/jsx("div", {
222
- className: "lc-settings-notice",
223
- children: /*#__PURE__*/jsx("p", {
224
- children: "Current node is locked"
225
- })
226
- })
227
- });
228
- }
229
- if (Array.isArray(settings.items) && settings.items.length === 0) {
230
- return /*#__PURE__*/jsx("div", {
231
- className: "lc-settings-main",
232
- children: /*#__PURE__*/jsx("div", {
233
- className: "lc-settings-notice",
234
- children: /*#__PURE__*/jsx("p", {
235
- children: "No config found for this type of component"
236
- })
237
- })
238
- });
239
- }
240
- if (!settings.isSameComponent) {
241
- // TODO: future support 获取设置项交集编辑
242
- return /*#__PURE__*/jsx("div", {
243
- className: "lc-settings-main",
244
- children: /*#__PURE__*/jsx("div", {
245
- className: "lc-settings-notice",
246
- children: /*#__PURE__*/jsx("p", {
247
- children: "Please select same kind of components"
248
- })
249
- })
250
- });
251
- }
252
- return /*#__PURE__*/jsx(SettingRendererContext.Provider, {
253
- value: ctx,
254
- children: items?.map(item => /*#__PURE__*/jsx(SettingFieldView, {
255
- field: item
256
- }, item.id))
257
- });
258
- });
259
-
260
- class Adapter {
261
- renderers = {};
262
- setRenderers(renderers) {
263
- this.renderers = renderers;
264
- }
265
- setBaseRenderer(BaseRenderer) {
266
- this.renderers.BaseRenderer = BaseRenderer;
267
- }
268
- setPageRenderer(PageRenderer) {
269
- this.renderers.PageRenderer = PageRenderer;
270
- }
271
- setComponentRenderer(ComponentRenderer) {
272
- this.renderers.ComponentRenderer = ComponentRenderer;
273
- }
274
- getRenderers() {
275
- return this.renderers || {};
276
- }
277
- }
278
- const adapter = new Adapter();
279
-
280
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
281
-
282
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
283
- var root = freeGlobal || freeSelf || Function('return this')();
284
-
285
- var Symbol = root.Symbol;
286
-
287
- var objectProto$7 = Object.prototype;
288
- var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
289
- var nativeObjectToString$1 = objectProto$7.toString;
290
- var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined;
291
- function getRawTag(value) {
292
- var isOwn = hasOwnProperty$5.call(value, symToStringTag$1),
293
- tag = value[symToStringTag$1];
294
- try {
295
- value[symToStringTag$1] = undefined;
296
- var unmasked = true;
297
- } catch (e) {}
298
- var result = nativeObjectToString$1.call(value);
299
- if (unmasked) {
300
- if (isOwn) {
301
- value[symToStringTag$1] = tag;
302
- } else {
303
- delete value[symToStringTag$1];
304
- }
305
- }
306
- return result;
307
- }
308
-
309
- var objectProto$6 = Object.prototype;
310
- var nativeObjectToString = objectProto$6.toString;
311
- function objectToString(value) {
312
- return nativeObjectToString.call(value);
313
- }
314
-
315
- var nullTag = '[object Null]',
316
- undefinedTag = '[object Undefined]';
317
- var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
318
- function baseGetTag(value) {
319
- if (value == null) {
320
- return value === undefined ? undefinedTag : nullTag;
321
- }
322
- return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
323
- }
324
-
325
- function isObjectLike(value) {
326
- return value != null && typeof value == 'object';
327
- }
328
-
329
- var symbolTag = '[object Symbol]';
330
- function isSymbol(value) {
331
- return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
332
- }
333
-
334
- var isArray = Array.isArray;
335
-
336
- var reWhitespace = /\s/;
337
- function trimmedEndIndex(string) {
338
- var index = string.length;
339
- while (index-- && reWhitespace.test(string.charAt(index))) {}
340
- return index;
341
- }
342
-
343
- var reTrimStart = /^\s+/;
344
- function baseTrim(string) {
345
- return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
346
- }
347
-
348
- function isObject(value) {
349
- var type = typeof value;
350
- return value != null && (type == 'object' || type == 'function');
351
- }
352
-
353
- var NAN = 0 / 0;
354
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
355
- var reIsBinary = /^0b[01]+$/i;
356
- var reIsOctal = /^0o[0-7]+$/i;
357
- var freeParseInt = parseInt;
358
- function toNumber(value) {
359
- if (typeof value == 'number') {
360
- return value;
361
- }
362
- if (isSymbol(value)) {
363
- return NAN;
364
- }
365
- if (isObject(value)) {
366
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
367
- value = isObject(other) ? other + '' : other;
368
- }
369
- if (typeof value != 'string') {
370
- return value === 0 ? value : +value;
371
- }
372
- value = baseTrim(value);
373
- var isBinary = reIsBinary.test(value);
374
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
375
- }
376
-
377
- function identity(value) {
378
- return value;
379
- }
380
-
381
- var asyncTag = '[object AsyncFunction]',
382
- funcTag$1 = '[object Function]',
383
- genTag = '[object GeneratorFunction]',
384
- proxyTag = '[object Proxy]';
385
- function isFunction(value) {
386
- if (!isObject(value)) {
387
- return false;
388
- }
389
- var tag = baseGetTag(value);
390
- return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
391
- }
392
-
393
- var coreJsData = root['__core-js_shared__'];
394
-
395
- var maskSrcKey = function () {
396
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
397
- return uid ? 'Symbol(src)_1.' + uid : '';
398
- }();
399
- function isMasked(func) {
400
- return !!maskSrcKey && maskSrcKey in func;
401
- }
402
-
403
- var funcProto$1 = Function.prototype;
404
- var funcToString$1 = funcProto$1.toString;
405
- function toSource(func) {
406
- if (func != null) {
407
- try {
408
- return funcToString$1.call(func);
409
- } catch (e) {}
410
- try {
411
- return func + '';
412
- } catch (e) {}
413
- }
414
- return '';
415
- }
416
-
417
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
418
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
419
- var funcProto = Function.prototype,
420
- objectProto$5 = Object.prototype;
421
- var funcToString = funcProto.toString;
422
- var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
423
- var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
424
- function baseIsNative(value) {
425
- if (!isObject(value) || isMasked(value)) {
426
- return false;
427
- }
428
- var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
429
- return pattern.test(toSource(value));
430
- }
431
-
432
- function getValue$1(object, key) {
433
- return object == null ? undefined : object[key];
434
- }
435
-
436
- function getNative(object, key) {
437
- var value = getValue$1(object, key);
438
- return baseIsNative(value) ? value : undefined;
439
- }
440
-
441
- var WeakMap = getNative(root, 'WeakMap');
442
-
443
- function arrayEach(array, iteratee) {
444
- var index = -1,
445
- length = array == null ? 0 : array.length;
446
- while (++index < length) {
447
- if (iteratee(array[index], index, array) === false) {
448
- break;
449
- }
450
- }
451
- return array;
452
- }
453
-
454
- var MAX_SAFE_INTEGER$1 = 9007199254740991;
455
- var reIsUint = /^(?:0|[1-9]\d*)$/;
456
- function isIndex(value, length) {
457
- var type = typeof value;
458
- length = length == null ? MAX_SAFE_INTEGER$1 : length;
459
- return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
460
- }
461
-
462
- var MAX_SAFE_INTEGER = 9007199254740991;
463
- function isLength(value) {
464
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
465
- }
466
-
467
- function isArrayLike(value) {
468
- return value != null && isLength(value.length) && !isFunction(value);
469
- }
470
-
471
- var objectProto$4 = Object.prototype;
472
- function isPrototype(value) {
473
- var Ctor = value && value.constructor,
474
- proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$4;
475
- return value === proto;
476
- }
477
-
478
- function baseTimes(n, iteratee) {
479
- var index = -1,
480
- result = Array(n);
481
- while (++index < n) {
482
- result[index] = iteratee(index);
483
- }
484
- return result;
485
- }
486
-
487
- var argsTag$1 = '[object Arguments]';
488
- function baseIsArguments(value) {
489
- return isObjectLike(value) && baseGetTag(value) == argsTag$1;
490
- }
491
-
492
- var objectProto$3 = Object.prototype;
493
- var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
494
- var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
495
- var isArguments = baseIsArguments(function () {
496
- return arguments;
497
- }()) ? baseIsArguments : function (value) {
498
- return isObjectLike(value) && hasOwnProperty$3.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
499
- };
500
-
501
- function stubFalse() {
502
- return false;
503
- }
504
-
505
- var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
506
- var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
507
- var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
508
- var Buffer = moduleExports$1 ? root.Buffer : undefined;
509
- var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
510
- var isBuffer = nativeIsBuffer || stubFalse;
511
-
512
- var argsTag = '[object Arguments]',
513
- arrayTag = '[object Array]',
514
- boolTag = '[object Boolean]',
515
- dateTag = '[object Date]',
516
- errorTag = '[object Error]',
517
- funcTag = '[object Function]',
518
- mapTag$2 = '[object Map]',
519
- numberTag = '[object Number]',
520
- objectTag$1 = '[object Object]',
521
- regexpTag = '[object RegExp]',
522
- setTag$2 = '[object Set]',
523
- stringTag = '[object String]',
524
- weakMapTag$1 = '[object WeakMap]';
525
- var arrayBufferTag = '[object ArrayBuffer]',
526
- dataViewTag$1 = '[object DataView]',
527
- float32Tag = '[object Float32Array]',
528
- float64Tag = '[object Float64Array]',
529
- int8Tag = '[object Int8Array]',
530
- int16Tag = '[object Int16Array]',
531
- int32Tag = '[object Int32Array]',
532
- uint8Tag = '[object Uint8Array]',
533
- uint8ClampedTag = '[object Uint8ClampedArray]',
534
- uint16Tag = '[object Uint16Array]',
535
- uint32Tag = '[object Uint32Array]';
536
- var typedArrayTags = {};
537
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
538
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag$2] = typedArrayTags[numberTag] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = typedArrayTags[setTag$2] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false;
539
- function baseIsTypedArray(value) {
540
- return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
541
- }
542
-
543
- function baseUnary(func) {
544
- return function (value) {
545
- return func(value);
546
- };
547
- }
548
-
549
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
550
- var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
551
- var moduleExports = freeModule && freeModule.exports === freeExports;
552
- var freeProcess = moduleExports && freeGlobal.process;
553
- var nodeUtil = function () {
554
- try {
555
- var types = freeModule && freeModule.require && freeModule.require('util').types;
556
- if (types) {
557
- return types;
558
- }
559
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
560
- } catch (e) {}
561
- }();
562
-
563
- var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
564
- var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
565
-
566
- var objectProto$2 = Object.prototype;
567
- var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
568
- function arrayLikeKeys(value, inherited) {
569
- var isArr = isArray(value),
570
- isArg = !isArr && isArguments(value),
571
- isBuff = !isArr && !isArg && isBuffer(value),
572
- isType = !isArr && !isArg && !isBuff && isTypedArray(value),
573
- skipIndexes = isArr || isArg || isBuff || isType,
574
- result = skipIndexes ? baseTimes(value.length, String) : [],
575
- length = result.length;
576
- for (var key in value) {
577
- if ((hasOwnProperty$2.call(value, key)) && !(skipIndexes && (
578
- key == 'length' ||
579
- isBuff && (key == 'offset' || key == 'parent') ||
580
- isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
581
- isIndex(key, length)))) {
582
- result.push(key);
583
- }
584
- }
585
- return result;
586
- }
587
-
588
- function overArg(func, transform) {
589
- return function (arg) {
590
- return func(transform(arg));
591
- };
592
- }
593
-
594
- var nativeKeys = overArg(Object.keys, Object);
595
-
596
- var objectProto$1 = Object.prototype;
597
- var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
598
- function baseKeys(object) {
599
- if (!isPrototype(object)) {
600
- return nativeKeys(object);
601
- }
602
- var result = [];
603
- for (var key in Object(object)) {
604
- if (hasOwnProperty$1.call(object, key) && key != 'constructor') {
605
- result.push(key);
606
- }
607
- }
608
- return result;
609
- }
610
-
611
- function keys(object) {
612
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
613
- }
614
-
615
- var Map$1 = getNative(root, 'Map');
616
-
617
- var DataView = getNative(root, 'DataView');
618
-
619
- var Promise$1 = getNative(root, 'Promise');
620
-
621
- var Set = getNative(root, 'Set');
622
-
623
- var mapTag$1 = '[object Map]',
624
- objectTag = '[object Object]',
625
- promiseTag = '[object Promise]',
626
- setTag$1 = '[object Set]',
627
- weakMapTag = '[object WeakMap]';
628
- var dataViewTag = '[object DataView]';
629
- var dataViewCtorString = toSource(DataView),
630
- mapCtorString = toSource(Map$1),
631
- promiseCtorString = toSource(Promise$1),
632
- setCtorString = toSource(Set),
633
- weakMapCtorString = toSource(WeakMap);
634
- var getTag = baseGetTag;
635
- if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map$1 && getTag(new Map$1()) != mapTag$1 || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set && getTag(new Set()) != setTag$1 || WeakMap && getTag(new WeakMap()) != weakMapTag) {
636
- getTag = function (value) {
637
- var result = baseGetTag(value),
638
- Ctor = result == objectTag ? value.constructor : undefined,
639
- ctorString = Ctor ? toSource(Ctor) : '';
640
- if (ctorString) {
641
- switch (ctorString) {
642
- case dataViewCtorString:
643
- return dataViewTag;
644
- case mapCtorString:
645
- return mapTag$1;
646
- case promiseCtorString:
647
- return promiseTag;
648
- case setCtorString:
649
- return setTag$1;
650
- case weakMapCtorString:
651
- return weakMapTag;
652
- }
653
- }
654
- return result;
655
- };
656
- }
657
-
658
- function createBaseFor(fromRight) {
659
- return function (object, iteratee, keysFunc) {
660
- var index = -1,
661
- iterable = Object(object),
662
- props = keysFunc(object),
663
- length = props.length;
664
- while (length--) {
665
- var key = props[++index];
666
- if (iteratee(iterable[key], key, iterable) === false) {
667
- break;
668
- }
669
- }
670
- return object;
671
- };
672
- }
673
-
674
- var baseFor = createBaseFor();
675
-
676
- function baseForOwn(object, iteratee) {
677
- return object && baseFor(object, iteratee, keys);
678
- }
679
-
680
- function createBaseEach(eachFunc, fromRight) {
681
- return function (collection, iteratee) {
682
- if (collection == null) {
683
- return collection;
684
- }
685
- if (!isArrayLike(collection)) {
686
- return eachFunc(collection, iteratee);
687
- }
688
- var length = collection.length,
689
- index = -1,
690
- iterable = Object(collection);
691
- while (++index < length) {
692
- if (iteratee(iterable[index], index, iterable) === false) {
693
- break;
694
- }
695
- }
696
- return collection;
697
- };
698
- }
699
-
700
- var baseEach = createBaseEach(baseForOwn);
701
-
702
- var now = function () {
703
- return root.Date.now();
704
- };
705
-
706
- var FUNC_ERROR_TEXT = 'Expected a function';
707
- var nativeMax = Math.max,
708
- nativeMin = Math.min;
709
- function debounce(func, wait, options) {
710
- var lastArgs,
711
- lastThis,
712
- maxWait,
713
- result,
714
- timerId,
715
- lastCallTime,
716
- lastInvokeTime = 0,
717
- leading = false,
718
- maxing = false,
719
- trailing = true;
720
- if (typeof func != 'function') {
721
- throw new TypeError(FUNC_ERROR_TEXT);
722
- }
723
- wait = toNumber(wait) || 0;
724
- if (isObject(options)) {
725
- leading = !!options.leading;
726
- maxing = 'maxWait' in options;
727
- maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
728
- trailing = 'trailing' in options ? !!options.trailing : trailing;
729
- }
730
- function invokeFunc(time) {
731
- var args = lastArgs,
732
- thisArg = lastThis;
733
- lastArgs = lastThis = undefined;
734
- lastInvokeTime = time;
735
- result = func.apply(thisArg, args);
736
- return result;
737
- }
738
- function leadingEdge(time) {
739
- lastInvokeTime = time;
740
- timerId = setTimeout(timerExpired, wait);
741
- return leading ? invokeFunc(time) : result;
742
- }
743
- function remainingWait(time) {
744
- var timeSinceLastCall = time - lastCallTime,
745
- timeSinceLastInvoke = time - lastInvokeTime,
746
- timeWaiting = wait - timeSinceLastCall;
747
- return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
748
- }
749
- function shouldInvoke(time) {
750
- var timeSinceLastCall = time - lastCallTime,
751
- timeSinceLastInvoke = time - lastInvokeTime;
752
- return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
753
- }
754
- function timerExpired() {
755
- var time = now();
756
- if (shouldInvoke(time)) {
757
- return trailingEdge(time);
758
- }
759
- timerId = setTimeout(timerExpired, remainingWait(time));
760
- }
761
- function trailingEdge(time) {
762
- timerId = undefined;
763
- if (trailing && lastArgs) {
764
- return invokeFunc(time);
765
- }
766
- lastArgs = lastThis = undefined;
767
- return result;
768
- }
769
- function cancel() {
770
- if (timerId !== undefined) {
771
- clearTimeout(timerId);
772
- }
773
- lastInvokeTime = 0;
774
- lastArgs = lastCallTime = lastThis = timerId = undefined;
775
- }
776
- function flush() {
777
- return timerId === undefined ? result : trailingEdge(now());
778
- }
779
- function debounced() {
780
- var time = now(),
781
- isInvoking = shouldInvoke(time);
782
- lastArgs = arguments;
783
- lastThis = this;
784
- lastCallTime = time;
785
- if (isInvoking) {
786
- if (timerId === undefined) {
787
- return leadingEdge(lastCallTime);
788
- }
789
- if (maxing) {
790
- clearTimeout(timerId);
791
- timerId = setTimeout(timerExpired, wait);
792
- return invokeFunc(lastCallTime);
793
- }
794
- }
795
- if (timerId === undefined) {
796
- timerId = setTimeout(timerExpired, wait);
797
- }
798
- return result;
799
- }
800
- debounced.cancel = cancel;
801
- debounced.flush = flush;
802
- return debounced;
803
- }
804
-
805
- function castFunction(value) {
806
- return typeof value == 'function' ? value : identity;
807
- }
808
-
809
- function forEach(collection, iteratee) {
810
- var func = isArray(collection) ? arrayEach : baseEach;
811
- return func(collection, castFunction(iteratee));
812
- }
813
-
814
- var mapTag = '[object Map]',
815
- setTag = '[object Set]';
816
- var objectProto = Object.prototype;
817
- var hasOwnProperty = objectProto.hasOwnProperty;
818
- function isEmpty(value) {
819
- if (value == null) {
820
- return true;
821
- }
822
- if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
823
- return !value.length;
824
- }
825
- var tag = getTag(value);
826
- if (tag == mapTag || tag == setTag) {
827
- return !value.size;
828
- }
829
- if (isPrototype(value)) {
830
- return !baseKeys(value).length;
831
- }
832
- for (var key in value) {
833
- if (hasOwnProperty.call(value, key)) {
834
- return false;
835
- }
836
- }
837
- return true;
838
- }
839
-
840
- const RendererContext = /*#__PURE__*/createContext({});
841
- const useRendererContext = () => {
842
- try {
843
- return useContext(RendererContext);
844
- } catch (error) {
845
- console.warn('useRendererContext must be used within a RendererContextProvider');
846
- }
847
- return {};
848
- };
849
- function contextFactory() {
850
- let context = window.__appContext;
851
- if (!context) {
852
- context = /*#__PURE__*/createContext({});
853
- window.__appContext = context;
854
- }
855
- return context;
856
- }
857
-
858
- const classnames = (...args) => {
859
- return args.filter(Boolean).join(' ');
860
- };
861
-
862
- const logger = createLogger('Renderer');
863
-
864
- const PropTypes2 = true;
865
- function inSameDomain() {
866
- try {
867
- return window.parent !== window && window.parent.location.host === window.location.host;
868
- } catch (e) {
869
- return false;
870
- }
871
- }
872
- function getFileCssName(fileName) {
873
- if (!fileName) {
874
- return;
875
- }
876
- const name = fileName.replace(/([A-Z])/g, '-$1').toLowerCase();
877
- return `lce-${name}`.split('-').filter(p => !!p).join('-');
878
- }
879
- const isSchema = schema => {
880
- if (!schema) {
881
- return false;
882
- }
883
- if (schema.componentName === 'Leaf' || schema.componentName === 'Slot') {
884
- return true;
885
- }
886
- if (Array.isArray(schema)) {
887
- return schema.every(item => isSchema(item));
888
- }
889
- const isValidProps = props => {
890
- if (!props) {
891
- return false;
892
- }
893
- return typeof schema.props === 'object' && !Array.isArray(props);
894
- };
895
- return !!(schema.componentName && isValidProps(schema.props));
896
- };
897
- const getValue = (obj, path, defaultValue = {}) => {
898
- if (Array.isArray(obj)) {
899
- return defaultValue;
900
- }
901
- if (!obj || typeof obj !== 'object') {
902
- return defaultValue;
903
- }
904
- const res = path.split('.').reduce((pre, cur) => {
905
- return pre && pre[cur];
906
- }, obj);
907
- if (res === undefined) {
908
- return defaultValue;
909
- }
910
- return res;
911
- };
912
- function transformArrayToMap(arr, key, overwrite = true) {
913
- if (!arr || !Array.isArray(arr)) {
914
- return {};
915
- }
916
- const res = {};
917
- arr.forEach(item => {
918
- const curKey = item[key];
919
- if (item[key] === undefined) {
920
- return;
921
- }
922
- if (res[curKey] && !overwrite) {
923
- return;
924
- }
925
- res[curKey] = item;
926
- });
927
- return res;
928
- }
929
- const parseData = (schema, self, options = {}) => {
930
- if (isJSExpression(schema)) {
931
- return parseExpression({
932
- str: schema,
933
- self,
934
- thisRequired: true,
935
- logScope: options.logScope
936
- });
937
- }
938
- if (typeof schema === 'string') {
939
- return schema.trim();
940
- } else if (Array.isArray(schema)) {
941
- return schema.map(item => parseData(item, self, options));
942
- } else if (typeof schema === 'function') {
943
- return schema.bind(self);
944
- } else if (typeof schema === 'object') {
945
- if (!schema) {
946
- return schema;
947
- }
948
- const res = {};
949
- Object.entries(schema).forEach(([key, val]) => {
950
- if (key.startsWith('__')) {
951
- return;
952
- }
953
- res[key] = parseData(val, self, options);
954
- });
955
- return res;
956
- }
957
- return schema;
958
- };
959
- const isUseLoop = (loop, isDesignMode) => {
960
- if (!isDesignMode) {
961
- return true;
962
- }
963
- if (!Array.isArray(loop)) {
964
- return false;
965
- }
966
- return loop.length > 0;
967
- };
968
- function checkPropTypes(value, name, rule, componentName) {
969
- let ruleFunction = rule;
970
- if (typeof rule === 'string') {
971
- ruleFunction = new Function(`"use strict"; const PropTypes = arguments[0]; return ${rule}`)(PropTypes2);
972
- }
973
- if (!ruleFunction || typeof ruleFunction !== 'function') {
974
- logger.warn('checkPropTypes should have a function type rule argument');
975
- return true;
976
- }
977
- const err = ruleFunction({
978
- [name]: value
979
- }, name, componentName, 'prop', null
980
- );
981
- if (err) {
982
- logger.warn(err);
983
- }
984
- return !err;
985
- }
986
- function transformStringToFunction(str) {
987
- if (typeof str !== 'string') {
988
- return str;
989
- }
990
- if (inSameDomain() && window.parent.__newFunc) {
991
- return window.parent.__newFunc(`"use strict"; return ${str}`)();
992
- } else {
993
- return new Function(`"use strict"; return ${str}`)();
994
- }
995
- }
996
- function parseExpression(a, b, c = false) {
997
- let str;
998
- let self;
999
- let thisRequired;
1000
- let logScope;
1001
- if (typeof a === 'object' && b === undefined) {
1002
- str = a.str;
1003
- self = a.self;
1004
- thisRequired = a.thisRequired;
1005
- logScope = a.logScope;
1006
- } else {
1007
- str = a;
1008
- self = b;
1009
- thisRequired = c;
1010
- }
1011
- try {
1012
- const contextArr = ['"use strict";', 'var __self = arguments[0];'];
1013
- contextArr.push('return ');
1014
- let tarStr;
1015
- tarStr = (str.value || '').trim();
1016
- tarStr = tarStr.replace(/this(\W|$)/g, (_a, b) => `__self${b}`);
1017
- tarStr = contextArr.join('\n') + tarStr;
1018
- if (inSameDomain() && window.parent.__newFunc) {
1019
- return window.parent.__newFunc(tarStr)(self);
1020
- }
1021
- const code = `with(${thisRequired ? '{}' : '$scope || {}'}) { ${tarStr} }`;
1022
- return new Function('$scope', code)(self);
1023
- } catch (err) {
1024
- logger.error(`${logScope || ''} parseExpression.error`, err, str, self?.__self ?? self);
1025
- return undefined;
1026
- }
1027
- }
1028
- function parseThisRequiredExpression(str, self) {
1029
- return parseExpression(str, self, true);
1030
- }
1031
- function isString(str) {
1032
- return {}.toString.call(str) === '[object String]';
1033
- }
1034
- function capitalizeFirstLetter(word) {
1035
- if (!word || !isString(word) || word.length === 0) {
1036
- return word;
1037
- }
1038
- return word[0].toUpperCase() + word.slice(1);
1039
- }
1040
- const isReactClass = obj => {
1041
- return obj && obj.prototype && (obj.prototype.isReactComponent || obj.prototype instanceof Component);
1042
- };
1043
- function isReactComponent(obj) {
1044
- return obj && (isReactClass(obj) || typeof obj === 'function');
1045
- }
1046
-
1047
- const excludePropertyNames = ['$$typeof', 'render', 'defaultProps', 'props', 'length', 'prototype', 'name', 'caller', 'callee', 'arguments'];
1048
- const cloneEnumerableProperty = (target, origin, excludes = excludePropertyNames) => {
1049
- const compExtraPropertyNames = Object.keys(origin).filter(d => !excludes.includes(d));
1050
- compExtraPropertyNames.forEach(d => {
1051
- target[d] = origin[d];
1052
- });
1053
- return target;
1054
- };
1055
- const createForwardRefHocElement = (Wrapper, Comp) => {
1056
- const WrapperComponent = cloneEnumerableProperty(/*#__PURE__*/forwardRef((props, ref) => {
1057
- return /*#__PURE__*/createElement(Wrapper, {
1058
- ...props,
1059
- forwardRef: ref
1060
- });
1061
- }), Comp);
1062
- WrapperComponent.displayName = Comp.displayName;
1063
- return WrapperComponent;
1064
- };
1065
-
1066
- const patchDidCatch = (Comp, {
1067
- baseRenderer
1068
- }) => {
1069
- if (Comp.patchedCatch) {
1070
- return;
1071
- }
1072
- Comp.patchedCatch = true;
1073
- const originalDidCatch = Comp.prototype.componentDidCatch;
1074
- Comp.prototype.componentDidCatch = function didCatch(error, errorInfo) {
1075
- this.setState({
1076
- engineRenderError: true,
1077
- error
1078
- });
1079
- if (originalDidCatch && typeof originalDidCatch === 'function') {
1080
- originalDidCatch.call(this, error, errorInfo);
1081
- }
1082
- };
1083
- const {
1084
- engine
1085
- } = baseRenderer.context;
1086
- const originRender = Comp.prototype.render;
1087
- Comp.prototype.render = function () {
1088
- if (this.state && this.state.engineRenderError) {
1089
- this.state.engineRenderError = false;
1090
- return engine.createElement(engine.getFaultComponent(), {
1091
- ...this.props,
1092
- error: this.state.error,
1093
- componentName: this.props._componentName
1094
- });
1095
- }
1096
- return originRender.call(this);
1097
- };
1098
- if (!(Comp.prototype instanceof PureComponent)) {
1099
- const originShouldComponentUpdate = Comp.prototype.shouldComponentUpdate;
1100
- Comp.prototype.shouldComponentUpdate = function (nextProps, nextState) {
1101
- if (nextState && nextState.engineRenderError) {
1102
- return true;
1103
- }
1104
- return originShouldComponentUpdate ? originShouldComponentUpdate.call(this, nextProps, nextState) : true;
1105
- };
1106
- }
1107
- };
1108
- const cache$1 = new Map();
1109
- const compWrapper = (Comp, info) => {
1110
- if (Comp?.prototype?.isReactComponent || Comp?.prototype instanceof Component) {
1111
- patchDidCatch(Comp, info);
1112
- return Comp;
1113
- }
1114
- if (info.schema.id && cache$1.has(info.schema.id) && cache$1.get(info.schema.id)?.Comp === Comp) {
1115
- return cache$1.get(info.schema.id)?.WrapperComponent;
1116
- }
1117
- class Wrapper extends Component {
1118
- static displayName = Comp.displayName;
1119
- render() {
1120
- const {
1121
- forwardRef,
1122
- ...rest
1123
- } = this.props;
1124
- // @ts-ignore
1125
- return /*#__PURE__*/createElement(Comp, {
1126
- ...rest,
1127
- ref: forwardRef
1128
- });
1129
- }
1130
- }
1131
- patchDidCatch(Wrapper, info);
1132
- const WrapperComponent = createForwardRefHocElement(Wrapper, Comp);
1133
- info.schema.id && cache$1.set(info.schema.id, {
1134
- WrapperComponent,
1135
- Comp
1136
- });
1137
- return WrapperComponent;
1138
- };
1139
-
1140
- var RerenderType = /*#__PURE__*/function (RerenderType) {
1141
- RerenderType["All"] = "All";
1142
- RerenderType["ChildChanged"] = "ChildChanged";
1143
- RerenderType["PropsChanged"] = "PropsChanged";
1144
- RerenderType["VisibleChanged"] = "VisibleChanged";
1145
- RerenderType["MinimalRenderUnit"] = "MinimalRenderUnit";
1146
- return RerenderType;
1147
- }(RerenderType || {}); // 缓存 Leaf 层组件,防止重新渲染问题
1148
- class LeafCache {
1149
- /** 组件缓存 */
1150
- component = new Map();
1151
-
1152
- /**
1153
- * 状态缓存,场景:属性变化后,改组件被销毁,state 为空,没有展示修改后的属性
1154
- */
1155
- state = new Map();
1156
-
1157
- /**
1158
- * 订阅事件缓存,导致 rerender 的订阅事件
1159
- */
1160
- event = new Map();
1161
- ref = new Map();
1162
- constructor(documentId, device) {
1163
- this.documentId = documentId;
1164
- this.device = device;
1165
- }
1166
- }
1167
- let cache;
1168
-
1169
- /** 部分没有渲染的 node 节点进行兜底处理 or 渲染方式没有渲染 LeafWrapper */
1170
- const initRerenderEvent = ({
1171
- schema,
1172
- container,
1173
- getNode
1174
- }) => {
1175
- const leaf = getNode?.(schema.id);
1176
- if (!leaf || cache.event.get(schema.id)?.clear || leaf === cache.event.get(schema.id)) {
1177
- return;
1178
- }
1179
- cache.event.get(schema.id)?.dispose.forEach(disposeFn => disposeFn && disposeFn());
1180
- const debounceRerender = debounce(() => {
1181
- container.rerender();
1182
- }, 20);
1183
- cache.event.set(schema.id, {
1184
- clear: false,
1185
- leaf,
1186
- dispose: [leaf?.onPropChange?.(() => {
1187
- if (!container.autoRepaintNode) {
1188
- return;
1189
- }
1190
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onPropsChange make rerender`);
1191
- debounceRerender();
1192
- }), leaf?.onChildrenChange?.(() => {
1193
- if (!container.autoRepaintNode) {
1194
- return;
1195
- }
1196
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onChildrenChange make rerender`);
1197
- debounceRerender();
1198
- }), leaf?.onVisibleChange?.(() => {
1199
- if (!container.autoRepaintNode) {
1200
- return;
1201
- }
1202
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onVisibleChange make rerender`);
1203
- debounceRerender();
1204
- })]
1205
- });
1206
- };
1207
-
1208
- /** 渲染的 node 节点全局注册事件清除 */
1209
- const clearRerenderEvent = id => {
1210
- if (cache.event.get(id)?.clear) {
1211
- return;
1212
- }
1213
- cache.event.get(id)?.dispose?.forEach(disposeFn => disposeFn && disposeFn());
1214
- cache.event.set(id, {
1215
- clear: true,
1216
- dispose: []
1217
- });
1218
- };
1219
-
1220
- // 给每个组件包裹一个 HOC Leaf,支持组件内部属性变化,自响应渲染
1221
- const leafWrapper = (Comp, {
1222
- schema,
1223
- baseRenderer,
1224
- componentInfo,
1225
- scope
1226
- }) => {
1227
- const {
1228
- __getComponentProps: getProps,
1229
- __getSchemaChildrenVirtualDom: getChildren,
1230
- __parseData
1231
- } = baseRenderer;
1232
- const {
1233
- engine
1234
- } = baseRenderer.context;
1235
- const host = baseRenderer.props?.__host;
1236
- const curDocumentId = baseRenderer.props?.documentId ?? '';
1237
- const curDevice = baseRenderer.props?.device ?? '';
1238
- const getNode = baseRenderer.props?.getNode;
1239
- const container = baseRenderer.props?.__container;
1240
- const setSchemaChangedSymbol = baseRenderer.props?.setSchemaChangedSymbol;
1241
- const designer = host?.designer;
1242
- const componentCacheId = schema.id;
1243
- if (!cache || curDocumentId && curDocumentId !== cache.documentId || curDevice && curDevice !== cache.device) {
1244
- cache?.event.forEach(event => {
1245
- event.dispose?.forEach(disposeFn => disposeFn && disposeFn());
1246
- });
1247
- cache = new LeafCache(curDocumentId, curDevice);
1248
- }
1249
-
1250
- // if (!isReactComponent(Comp)) {
1251
- // logger.error(`${schema.componentName} component may be has errors: `, Comp)
1252
- // }
1253
-
1254
- initRerenderEvent({
1255
- schema,
1256
- container,
1257
- getNode
1258
- });
1259
- if (curDocumentId && cache.component.has(componentCacheId) && cache.component.get(componentCacheId).Comp === Comp) {
1260
- return cache.component.get(componentCacheId).LeafWrapper;
1261
- }
1262
- class LeafHoc extends Component {
1263
- recordInfo = {};
1264
- curEventLeaf;
1265
- static displayName = schema.componentName;
1266
- disposeFunctions = [];
1267
- __component_tag = 'leafWrapper';
1268
- renderUnitInfo;
1269
-
1270
- // 最小渲染单元做防抖处理
1271
- makeUnitRenderDebounced = debounce(() => {
1272
- this.beforeRender(RerenderType.MinimalRenderUnit);
1273
- const schema = this.leaf?.export?.(TRANSFORM_STAGE.RENDER);
1274
- if (!schema) {
1275
- return;
1276
- }
1277
- const nextProps = getProps(schema, scope, Comp, componentInfo);
1278
- const children = getChildren(schema, scope, Comp);
1279
- const nextState = {
1280
- nodeProps: nextProps,
1281
- nodeChildren: children,
1282
- childrenInState: true
1283
- };
1284
- if ('children' in nextProps) {
1285
- nextState.nodeChildren = nextProps.children;
1286
- }
1287
- logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) MinimalRenderUnit Render!`);
1288
- this.setState(nextState);
1289
- }, 20);
1290
- constructor(props) {
1291
- super(props);
1292
- // 监听以下事件,当变化时更新自己
1293
- logger.log(`${schema.componentName}[${this.leaf?.id}] leaf render in SimulatorRendererView`);
1294
- componentCacheId && clearRerenderEvent(componentCacheId);
1295
- this.curEventLeaf = this.leaf;
1296
- cache.ref.set(componentCacheId, {
1297
- makeUnitRender: this.makeUnitRender
1298
- });
1299
- let cacheState = cache.state.get(componentCacheId);
1300
- if (!cacheState || cacheState.__tag !== props.__tag) {
1301
- cacheState = this.getDefaultState(props);
1302
- }
1303
- this.state = cacheState;
1304
- }
1305
- recordTime = () => {
1306
- if (!this.recordInfo.startTime) {
1307
- return;
1308
- }
1309
- const endTime = Date.now();
1310
- const nodeCount = host?.designer?.currentDocument?.getNodeCount?.();
1311
- const componentName = this.recordInfo.node?.componentName || this.leaf?.componentName || 'UnknownComponent';
1312
- designer?.postEvent(DESIGNER_EVENT.NODE_RENDER, {
1313
- componentName,
1314
- time: endTime - this.recordInfo.startTime,
1315
- type: this.recordInfo.type,
1316
- nodeCount
1317
- });
1318
- this.recordInfo.startTime = null;
1319
- };
1320
- makeUnitRender = () => {
1321
- this.makeUnitRenderDebounced();
1322
- };
1323
- get autoRepaintNode() {
1324
- return container?.autoRepaintNode;
1325
- }
1326
- componentDidUpdate() {
1327
- this.recordTime();
1328
- }
1329
- componentDidMount() {
1330
- const _leaf = this.leaf;
1331
- this.initOnPropsChangeEvent(_leaf);
1332
- this.initOnChildrenChangeEvent(_leaf);
1333
- this.initOnVisibleChangeEvent(_leaf);
1334
- this.recordTime();
1335
- }
1336
- getDefaultState(nextProps) {
1337
- const {
1338
- hidden = false,
1339
- condition = true
1340
- } = nextProps.__inner__ || this.leaf?.export?.(TRANSFORM_STAGE.RENDER) || {};
1341
- return {
1342
- nodeChildren: null,
1343
- childrenInState: false,
1344
- visible: !hidden,
1345
- condition: __parseData?.(condition, scope),
1346
- nodeCacheProps: {},
1347
- nodeProps: {}
1348
- };
1349
- }
1350
- setState(state) {
1351
- cache.state.set(componentCacheId, {
1352
- ...this.state,
1353
- ...state,
1354
- __tag: this.props.__tag
1355
- });
1356
- super.setState(state);
1357
- }
1358
-
1359
- /** 由于内部属性变化,在触发渲染前,会执行该函数 */
1360
- beforeRender(type, node) {
1361
- this.recordInfo.startTime = Date.now();
1362
- this.recordInfo.type = type;
1363
- this.recordInfo.node = node;
1364
- setSchemaChangedSymbol?.(true);
1365
- }
1366
- judgeMiniUnitRender() {
1367
- if (!this.renderUnitInfo) {
1368
- this.getRenderUnitInfo();
1369
- }
1370
- const renderUnitInfo = this.renderUnitInfo || {
1371
- singleRender: true
1372
- };
1373
- if (renderUnitInfo.singleRender) {
1374
- return;
1375
- }
1376
- const ref = cache.ref.get(renderUnitInfo.minimalUnitId);
1377
- if (!ref) {
1378
- logger.log('Cant find minimalRenderUnit ref! This make rerender!');
1379
- container?.rerender();
1380
- return;
1381
- }
1382
- logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) need render, make its minimalRenderUnit ${renderUnitInfo.minimalUnitName}(${renderUnitInfo.minimalUnitId})`);
1383
- ref.makeUnitRender();
1384
- }
1385
- getRenderUnitInfo(leaf = this.leaf) {
1386
- // leaf 在低代码组件中存在 mock 的情况,退出最小渲染单元判断
1387
- if (!leaf || typeof leaf.isRoot !== 'function') {
1388
- return;
1389
- }
1390
- if (leaf.isRoot) {
1391
- this.renderUnitInfo = {
1392
- singleRender: true,
1393
- ...(this.renderUnitInfo || {})
1394
- };
1395
- }
1396
- if (leaf.componentMeta.isMinimalRenderUnit) {
1397
- this.renderUnitInfo = {
1398
- minimalUnitId: leaf.id,
1399
- minimalUnitName: leaf.componentName,
1400
- singleRender: false
1401
- };
1402
- }
1403
- if (leaf.hasLoop()) {
1404
- // 含有循环配置的元素,父元素是最小渲染单元
1405
- this.renderUnitInfo = {
1406
- minimalUnitId: leaf?.parent?.id,
1407
- minimalUnitName: leaf?.parent?.componentName,
1408
- singleRender: false
1409
- };
1410
- }
1411
- if (leaf.parent) {
1412
- this.getRenderUnitInfo(leaf.parent);
1413
- }
1414
- }
1415
- UNSAFE_componentWillReceiveProps(nextProps) {
1416
- const {
1417
- componentId
1418
- } = nextProps;
1419
- if (nextProps.__tag === this.props.__tag) {
1420
- return null;
1421
- }
1422
- const _leaf = getNode?.(componentId);
1423
- if (_leaf && this.curEventLeaf && _leaf !== this.curEventLeaf) {
1424
- this.disposeFunctions.forEach(fn => fn());
1425
- this.disposeFunctions = [];
1426
- this.initOnChildrenChangeEvent(_leaf);
1427
- this.initOnPropsChangeEvent(_leaf);
1428
- this.initOnVisibleChangeEvent(_leaf);
1429
- this.curEventLeaf = _leaf;
1430
- }
1431
- const {
1432
- visible,
1433
- ...resetState
1434
- } = this.getDefaultState(nextProps);
1435
- this.setState(resetState);
1436
- }
1437
-
1438
- /** 监听参数变化 */
1439
- initOnPropsChangeEvent(leaf = this.leaf) {
1440
- // const handlePropsChange = debounce((propChangeInfo: PropChangeInfo) => {
1441
- const handlePropsChange = debounce(propChangeInfo => {
1442
- const {
1443
- key,
1444
- newValue = null
1445
- } = propChangeInfo;
1446
- const node = leaf;
1447
- if (key === '___condition___') {
1448
- const {
1449
- condition = true
1450
- } = this.leaf?.export(TRANSFORM_STAGE.RENDER) || {};
1451
- const conditionValue = __parseData?.(condition, scope);
1452
- logger.log(`key is ___condition___, change condition value to [${condition}]`);
1453
- // 条件表达式改变
1454
- this.setState({
1455
- condition: conditionValue
1456
- });
1457
- return;
1458
- }
1459
-
1460
- // 如果循坏条件变化,从根节点重新渲染
1461
- // 目前多层循坏无法判断需要从哪一层开始渲染,故先粗暴解决
1462
- if (key === '___loop___') {
1463
- logger.log('key is ___loop___, render a page!');
1464
- container?.rerender();
1465
- // 由于 scope 变化,需要清空缓存,使用新的 scope
1466
- cache.component.delete(componentCacheId);
1467
- return;
1468
- }
1469
- this.beforeRender(RerenderType.PropsChanged);
1470
- const {
1471
- state
1472
- } = this;
1473
- const {
1474
- nodeCacheProps
1475
- } = state;
1476
- const nodeProps = getProps(node?.export?.(TRANSFORM_STAGE.RENDER), scope, Comp, componentInfo);
1477
- if (key && !(key in nodeProps) && key in this.props) {
1478
- // 当 key 在 this.props 中时,且不存在在计算值中,需要用 newValue 覆盖掉 this.props 的取值
1479
- nodeCacheProps[key] = newValue;
1480
- }
1481
- logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onPropsChange!`, nodeProps, nodeCacheProps, key, newValue);
1482
- this.setState('children' in nodeProps ? {
1483
- nodeChildren: nodeProps.children,
1484
- nodeProps,
1485
- childrenInState: true,
1486
- nodeCacheProps
1487
- } : {
1488
- nodeProps,
1489
- nodeCacheProps
1490
- });
1491
- this.judgeMiniUnitRender();
1492
- });
1493
- // const dispose = leaf?.onPropChange?.((propChangeInfo: IPublicTypePropChangeOptions) => {
1494
- const dispose = leaf?.onPropChange?.(propChangeInfo => {
1495
- if (!this.autoRepaintNode) {
1496
- return;
1497
- }
1498
- handlePropsChange(propChangeInfo);
1499
- });
1500
- dispose && this.disposeFunctions.push(dispose);
1501
- }
1502
-
1503
- /**
1504
- * 监听显隐变化
1505
- */
1506
- initOnVisibleChangeEvent(leaf = this.leaf) {
1507
- const dispose = leaf?.onVisibleChange?.(flag => {
1508
- if (!this.autoRepaintNode) {
1509
- return;
1510
- }
1511
- if (this.state.visible === flag) {
1512
- return;
1513
- }
1514
- logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onVisibleChange(${flag}) event`);
1515
- this.beforeRender(RerenderType.VisibleChanged);
1516
- this.setState({
1517
- visible: flag
1518
- });
1519
- this.judgeMiniUnitRender();
1520
- });
1521
- dispose && this.disposeFunctions.push(dispose);
1522
- }
1523
-
1524
- /**
1525
- * 监听子元素变化(拖拽,删除...)
1526
- */
1527
- initOnChildrenChangeEvent(leaf = this.leaf) {
1528
- const dispose = leaf?.onChildrenChange?.(param => {
1529
- if (!this.autoRepaintNode) {
1530
- return;
1531
- }
1532
- const {
1533
- type,
1534
- node
1535
- } = param || {};
1536
- this.beforeRender(`${RerenderType.ChildChanged}-${type}`, node);
1537
- // TODO: 缓存同级其他元素的 children。
1538
- // 缓存二级 children Next 查询筛选组件有问题
1539
- // 缓存一级 children Next Tab 组件有问题
1540
- const nextChild = getChildren(leaf?.export?.(TRANSFORM_STAGE.RENDER), scope, Comp);
1541
- logger.log(`${schema.componentName}[${this.leaf?.id}] component trigger onChildrenChange event`, nextChild);
1542
- this.setState({
1543
- nodeChildren: nextChild,
1544
- childrenInState: true
1545
- });
1546
- this.judgeMiniUnitRender();
1547
- });
1548
- dispose && this.disposeFunctions.push(dispose);
1549
- }
1550
- componentWillUnmount() {
1551
- this.disposeFunctions.forEach(fn => fn());
1552
- }
1553
- get hasChildren() {
1554
- if (!this.state.childrenInState) {
1555
- return 'children' in this.props;
1556
- }
1557
- return true;
1558
- }
1559
- get children() {
1560
- if (this.state.childrenInState) {
1561
- return this.state.nodeChildren;
1562
- }
1563
- if (this.props.children && !Array.isArray(this.props.children)) {
1564
- return [this.props.children];
1565
- }
1566
- if (this.props.children && this.props.children.length) {
1567
- return this.props.children;
1568
- }
1569
- return this.props.children;
1570
- }
1571
- get leaf() {
1572
- // if (this.props._leaf?.isMock) {
1573
- // // 低代码组件作为一个整体更新,其内部的组件不需要监听相关事件
1574
- // return undefined
1575
- // }
1576
-
1577
- return getNode?.(componentCacheId);
1578
- }
1579
- render() {
1580
- if (!this.state.visible || !this.state.condition) {
1581
- return null;
1582
- }
1583
- const {
1584
- forwardRef,
1585
- ...rest
1586
- } = this.props;
1587
- const compProps = {
1588
- ...rest,
1589
- ...(this.state.nodeCacheProps || {}),
1590
- ...(this.state.nodeProps || {}),
1591
- children: [],
1592
- __id: this.leaf?.id,
1593
- ref: forwardRef
1594
- };
1595
- delete compProps.__inner__;
1596
- if (this.hasChildren) {
1597
- return engine.createElement(Comp, compProps, this.children);
1598
- }
1599
- return engine.createElement(Comp, compProps);
1600
- }
1601
- }
1602
- const LeafWrapper = createForwardRefHocElement(LeafHoc, Comp);
1603
- cache.component.set(componentCacheId, {
1604
- LeafWrapper,
1605
- Comp
1606
- });
1607
- return LeafWrapper;
1608
- };
1609
-
1610
- function executeLifeCycleMethod(context, schema, method, args) {
1611
- if (!context || !isSchema(schema) || !method) {
1612
- return;
1613
- }
1614
- const lifeCycleMethods = getValue(schema, 'lifeCycles', {});
1615
- let fn = lifeCycleMethods[method];
1616
- if (!fn) {
1617
- return;
1618
- }
1619
-
1620
- // TODO: cache
1621
- if (isJSExpression(fn) || isJSFunction(fn)) {
1622
- fn = parseExpression(fn, context, true);
1623
- }
1624
- if (typeof fn !== 'function') {
1625
- logger.error(`生命周期${method}类型不符`, fn);
1626
- return;
1627
- }
1628
- try {
1629
- return fn.apply(context, args);
1630
- } catch (e) {
1631
- logger.error(`[${schema.componentName}]生命周期${method}出错`, e);
1632
- }
1633
- }
1634
-
1635
- /**
1636
- * get children from a node schema
1637
- */
1638
- function getSchemaChildren(schema) {
1639
- if (!schema) {
1640
- return;
1641
- }
1642
- return schema.children;
1643
- }
1644
- function baseRendererFactory() {
1645
- const {
1646
- BaseRenderer: customBaseRenderer
1647
- } = adapter.getRenderers();
1648
- if (customBaseRenderer) {
1649
- return customBaseRenderer;
1650
- }
1651
- const DEFAULT_LOOP_ARG_ITEM = 'item';
1652
- const DEFAULT_LOOP_ARG_INDEX = 'index';
1653
- // const scopeIdx = 0
1654
-
1655
- return class BaseRenderer extends Component {
1656
- static displayName = 'BaseRenderer';
1657
- static defaultProps = {
1658
- __schema: {}
1659
- };
1660
- static contextType = RendererContext;
1661
- dataSourceMap = {};
1662
- __namespace = 'base';
1663
- __compScopes = {};
1664
- __instanceMap = {};
1665
- __dataHelper;
1666
-
1667
- /**
1668
- * keep track of customMethods added to this context
1669
- *
1670
- * @type {any}
1671
- */
1672
- __customMethodsList = [];
1673
- __parseExpression;
1674
- __ref;
1675
-
1676
- /**
1677
- * reference of style element contains schema.css
1678
- *
1679
- * @type {any}
1680
- */
1681
- __styleElement;
1682
- constructor(props) {
1683
- super(props);
1684
- this.__parseExpression = (str, self) => {
1685
- return parseExpression({
1686
- str,
1687
- self,
1688
- logScope: props.componentName
1689
- });
1690
- };
1691
- this.__beforeInit(props);
1692
- this.__init(props);
1693
- this.__afterInit(props);
1694
- logger.log(`constructor - ${props?.__schema?.fileName}`);
1695
- }
1696
- __beforeInit(props) {}
1697
- __init(props) {
1698
- this.__compScopes = {};
1699
- this.__instanceMap = {};
1700
- this.__bindCustomMethods(props);
1701
- }
1702
- __afterInit(props) {}
1703
- static getDerivedStateFromProps(props, state) {
1704
- const result = executeLifeCycleMethod(this, props?.__schema, 'getDerivedStateFromProps', [props, state]);
1705
- return result === undefined ? null : result;
1706
- }
1707
- async getSnapshotBeforeUpdate(...args) {
1708
- this.__executeLifeCycleMethod('getSnapshotBeforeUpdate', args);
1709
- logger.log(`getSnapshotBeforeUpdate - ${this.props?.__schema?.componentName}`);
1710
- }
1711
- async componentDidMount(...args) {
1712
- this.reloadDataSource();
1713
- this.__executeLifeCycleMethod('componentDidMount', args);
1714
- logger.log(`componentDidMount - ${this.props?.__schema?.componentName}`);
1715
- }
1716
- async componentDidUpdate(...args) {
1717
- this.__executeLifeCycleMethod('componentDidUpdate', args);
1718
- logger.log(`componentDidUpdate - ${this.props.__schema.componentName}`);
1719
- }
1720
- async componentWillUnmount(...args) {
1721
- this.__executeLifeCycleMethod('componentWillUnmount', args);
1722
- logger.log(`componentWillUnmount - ${this.props?.__schema?.componentName}`);
1723
- }
1724
- async componentDidCatch(...args) {
1725
- this.__executeLifeCycleMethod('componentDidCatch', args);
1726
- logger.warn(args);
1727
- }
1728
- reloadDataSource = () => new Promise((resolve, reject) => {
1729
- logger.log('reload data source');
1730
- if (!this.__dataHelper) {
1731
- return resolve({});
1732
- }
1733
- this.__dataHelper.getInitData().then(res => {
1734
- if (isEmpty(res)) {
1735
- this.forceUpdate();
1736
- return resolve({});
1737
- }
1738
- this.setState(res, resolve);
1739
- }).catch(err => {
1740
- reject(err);
1741
- });
1742
- });
1743
- shouldComponentUpdate() {
1744
- if (this.props.getSchemaChangedSymbol?.() && this.props.__container?.rerender) {
1745
- this.props.__container?.rerender();
1746
- return false;
1747
- }
1748
- return true;
1749
- }
1750
- forceUpdate() {
1751
- if (this.shouldComponentUpdate()) {
1752
- super.forceUpdate();
1753
- }
1754
- }
1755
-
1756
- /**
1757
- * execute method in schema.lifeCycles
1758
- */
1759
- __executeLifeCycleMethod = (method, args) => {
1760
- // 跳过 construct 的执行
1761
- if (this.context) {
1762
- const {
1763
- engine
1764
- } = this.context;
1765
- if (!engine.props.excuteLifeCycleInDesignMode) {
1766
- return;
1767
- }
1768
- }
1769
- executeLifeCycleMethod(this, this.props.__schema, method, args);
1770
- };
1771
-
1772
- /**
1773
- * this method is for legacy purpose only, which used _ prefix instead of __ as private for some historical reasons
1774
- */
1775
- __getComponentView = () => {
1776
- const {
1777
- __components,
1778
- __schema
1779
- } = this.props;
1780
- if (!__components) {
1781
- return;
1782
- }
1783
- return __components[__schema.componentName];
1784
- };
1785
- __bindCustomMethods = props => {
1786
- const {
1787
- __schema
1788
- } = props;
1789
- const customMethodsList = Object.keys(__schema.methods || {}) || [];
1790
- (this.__customMethodsList || []).forEach(item => {
1791
- if (!customMethodsList.includes(item)) {
1792
- delete this[item];
1793
- }
1794
- });
1795
- this.__customMethodsList = customMethodsList;
1796
- forEach(__schema.methods, (val, key) => {
1797
- let value = val;
1798
- if (isJSExpression(value) || isJSFunction(value)) {
1799
- value = this.__parseExpression(value, this);
1800
- }
1801
- if (typeof value !== 'function') {
1802
- logger.error(`custom method ${key} can not be parsed to a valid function`, value);
1803
- return;
1804
- }
1805
- this[key] = value.bind(this);
1806
- });
1807
- };
1808
- __generateCtx = ctx => {
1809
- const {
1810
- pageContext,
1811
- compContext
1812
- } = this.context;
1813
- const obj = {
1814
- page: pageContext,
1815
- component: compContext,
1816
- ...ctx
1817
- };
1818
- forEach(obj, (val, key) => {
1819
- this[key] = val;
1820
- });
1821
- };
1822
- __parseData = (data, ctx) => {
1823
- const {
1824
- __ctx,
1825
- componentName
1826
- } = this.props;
1827
- return parseData(data, ctx || __ctx || this, {
1828
- logScope: componentName
1829
- });
1830
- };
1831
- __initDataSource = props => {
1832
- if (!props) {
1833
- return;
1834
- }
1835
- // TODO: 数据源引擎方案
1836
- // const schema = props.__schema || {}
1837
- // const defaultDataSource: DataSource = {
1838
- // list: [],
1839
- // }
1840
- // const dataSource = schema.dataSource || defaultDataSource
1841
- // // requestHandlersMap 存在才走数据源引擎方案
1842
- // // TODO: 下面if else 抽成独立函数
1843
- // const useDataSourceEngine = !!props.__appHelper?.requestHandlersMap
1844
- // if (useDataSourceEngine) {
1845
- // this.__dataHelper = {
1846
- // updateConfig: (updateDataSource: any) => {
1847
- // const { dataSourceMap, reloadDataSource } = createDataSourceEngine(
1848
- // updateDataSource ?? {},
1849
- // this,
1850
- // props.__appHelper.requestHandlersMap
1851
- // ? { requestHandlersMap: props.__appHelper.requestHandlersMap }
1852
- // : undefined,
1853
- // )
1854
-
1855
- // this.reloadDataSource = () =>
1856
- // new Promise(resolve => {
1857
- // logger.log('reload data source')
1858
- // reloadDataSource().then(() => {
1859
- // resolve({})
1860
- // })
1861
- // })
1862
- // return dataSourceMap
1863
- // },
1864
- // }
1865
- // this.dataSourceMap = this.__dataHelper.updateConfig(dataSource)
1866
- // } else {
1867
- // const appHelper = props.__appHelper
1868
- // this.__dataHelper = new DataHelper(this, dataSource, appHelper, (config: any) => this.__parseData(config))
1869
- // this.dataSourceMap = this.__dataHelper.dataSourceMap
1870
- // this.reloadDataSource = () =>
1871
- // new Promise((resolve, reject) => {
1872
- // logger.log('reload data source')
1873
- // if (!this.__dataHelper) {
1874
- // return resolve({})
1875
- // }
1876
- // this.__dataHelper
1877
- // .getInitData()
1878
- // .then((res: any) => {
1879
- // if (isEmpty(res)) {
1880
- // return resolve({})
1881
- // }
1882
- // this.setState(res, resolve as () => void)
1883
- // })
1884
- // .catch((err: Error) => {
1885
- // reject(err)
1886
- // })
1887
- // })
1888
- // }
1889
- };
1890
-
1891
- /**
1892
- * write props.__schema.css to document as a style element,
1893
- * which will be added once and only once.
1894
- * @PRIVATE
1895
- */
1896
- __writeCss = props => {
1897
- const css = getValue(props.__schema, 'css', '');
1898
- logger.log('create this.styleElement with css', css);
1899
- let style = this.__styleElement;
1900
- if (!this.__styleElement) {
1901
- style = document.createElement('style');
1902
- style.type = 'text/css';
1903
- style.setAttribute('from', 'style-sheet');
1904
- const head = document.head || document.getElementsByTagName('head')[0];
1905
- head.appendChild(style);
1906
- this.__styleElement = style;
1907
- logger.log('this.styleElement is created', this.__styleElement);
1908
- }
1909
- if (style.innerHTML === css) {
1910
- return;
1911
- }
1912
- style.innerHTML = css;
1913
- };
1914
- __render = () => {
1915
- const schema = this.props.__schema;
1916
- this.__executeLifeCycleMethod('render');
1917
- this.__writeCss(this.props);
1918
- const {
1919
- engine
1920
- } = this.context;
1921
- if (engine) {
1922
- engine.props?.onCompGetCtx?.(schema, this);
1923
- // 画布场景才需要每次渲染bind自定义方法
1924
- if (this.__designModeIsDesign) {
1925
- this.__bindCustomMethods(this.props);
1926
- this.dataSourceMap = this.__dataHelper?.updateConfig(schema.dataSource);
1927
- }
1928
- }
1929
- };
1930
- __getRef = ref => {
1931
- const {
1932
- engine
1933
- } = this.context;
1934
- const {
1935
- __schema
1936
- } = this.props;
1937
- // ref && engine?.props?.onCompGetRef(__schema, ref)
1938
- // TODO: 只在 ref 存在执行,会影响 documentInstance 的卸载
1939
- engine.props?.onCompGetRef?.(__schema, ref);
1940
- this.__ref = ref;
1941
- };
1942
- __createDom = () => {
1943
- const {
1944
- __schema,
1945
- __ctx
1946
- } = this.props;
1947
- // merge defaultProps
1948
- const scopeProps = {
1949
- ...__schema.defaultProps,
1950
- ...this.props
1951
- };
1952
- const scope = {
1953
- props: scopeProps
1954
- };
1955
- scope.__proto__ = __ctx || this;
1956
- const _children = getSchemaChildren(__schema);
1957
- const Comp = this.__getComponentView();
1958
- if (!Comp) {
1959
- logger.log(`${__schema.componentName} is invalid!`);
1960
- }
1961
- const parentNodeInfo = {
1962
- schema: __schema,
1963
- Comp: this.__getHOCWrappedComponent(Comp, {
1964
- schema: __schema,
1965
- scope
1966
- })
1967
- };
1968
- return this.__createVirtualDom(_children, scope, parentNodeInfo);
1969
- };
1970
-
1971
- /**
1972
- * 将模型结构转换成react Element
1973
- * @param originalSchema schema
1974
- * @param originalScope scope
1975
- * @param parentInfo 父组件的信息,包含schema和Comp
1976
- * @param idx 为循环渲染的循环Index
1977
- */
1978
- __createVirtualDom = (originalSchema, originalScope, parentInfo, idx = '') => {
1979
- if (originalSchema === null || originalSchema === undefined) {
1980
- return null;
1981
- }
1982
- const scope = originalScope;
1983
- const schema = originalSchema;
1984
- const {
1985
- engine
1986
- } = this.context || {};
1987
- if (!engine) {
1988
- logger.log('this.context.engine is invalid!');
1989
- return null;
1990
- }
1991
- try {
1992
- const {
1993
- __appHelper: appHelper,
1994
- __components: components = {}
1995
- } = this.props || {};
1996
- if (isJSExpression(schema)) {
1997
- return this.__parseExpression(schema, scope);
1998
- }
1999
- if (typeof schema === 'string') {
2000
- return schema;
2001
- }
2002
- if (typeof schema === 'number' || typeof schema === 'boolean') {
2003
- return String(schema);
2004
- }
2005
- if (Array.isArray(schema)) {
2006
- if (schema.length === 1) {
2007
- return this.__createVirtualDom(schema[0], scope, parentInfo);
2008
- }
2009
- return schema.map((item, idy) => this.__createVirtualDom(item, scope, parentInfo, item?.__ctx?.lceKey ? '' : String(idy)));
2010
- }
2011
- if (schema.$$typeof) {
2012
- return schema;
2013
- }
2014
- if (!schema.componentName) {
2015
- logger.error('The componentName in the schema is invalid, please check the schema: ', schema);
2016
- return;
2017
- }
2018
- if (!isSchema(schema)) {
2019
- return null;
2020
- }
2021
- let Comp = components[schema.componentName] || this.props.__container?.components?.[schema.componentName];
2022
-
2023
- // 容器类组件的上下文通过props传递,避免context传递带来的嵌套问题
2024
- const otherProps = isSchema(schema) ? {
2025
- __schema: schema,
2026
- __appHelper: appHelper,
2027
- __components: components
2028
- } : {};
2029
- if (!Comp) {
2030
- logger.error(`${schema.componentName} component is not found in components list! component list is:`, components || this.props.__container?.components);
2031
- return engine.createElement(engine.getNotFoundComponent(), {
2032
- componentName: schema.componentName,
2033
- componentId: schema.id,
2034
- enableStrictNotFoundMode: engine.props.enableStrictNotFoundMode,
2035
- ref: ref => {
2036
- ref && engine.props?.onCompGetRef?.(schema, ref);
2037
- }
2038
- }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp));
2039
- }
2040
- if (schema.loop != null) {
2041
- const loop = this.__parseData(schema.loop, scope);
2042
- if (Array.isArray(loop) && loop.length === 0) return null;
2043
- const useLoop = isUseLoop(loop, this.__designModeIsDesign);
2044
- if (useLoop) {
2045
- return this.__createLoopVirtualDom({
2046
- ...schema,
2047
- loop
2048
- }, scope, parentInfo, idx);
2049
- }
2050
- }
2051
- const condition = schema.condition == null ? true : this.__parseData(schema.condition, scope);
2052
-
2053
- // DesignMode 为 design 情况下,需要进入 leaf Hoc,进行相关事件注册
2054
- const displayInHook = this.__designModeIsDesign;
2055
- if (!condition && !displayInHook) {
2056
- return null;
2057
- }
2058
-
2059
- // TODO: scope
2060
- // let scopeKey = ''
2061
- // // 判断组件是否需要生成scope,且只生成一次,挂在this.__compScopes上
2062
- // if (Comp.generateScope) {
2063
- // const key = this.__parseExpression(schema.props?.key, scope)
2064
- // if (key) {
2065
- // // 如果组件自己设置key则使用组件自己的key
2066
- // scopeKey = key
2067
- // } else if (schema.__ctx) {
2068
- // // 需要判断循环的情况
2069
- // scopeKey = schema.__ctx.lceKey + (idx !== undefined ? `_${idx}` : '')
2070
- // } else {
2071
- // // 在生产环境schema没有__ctx上下文,需要手动生成一个lceKey
2072
- // schema.__ctx = {
2073
- // lceKey: `lce${++scopeIdx}`,
2074
- // }
2075
- // scopeKey = schema.__ctx.lceKey
2076
- // }
2077
- // if (!this.__compScopes[scopeKey]) {
2078
- // this.__compScopes[scopeKey] = Comp.generateScope(this, schema)
2079
- // }
2080
- // }
2081
- // // 如果组件有设置scope,需要为组件生成一个新的scope上下文
2082
- // if (scopeKey && this.__compScopes[scopeKey]) {
2083
- // const compSelf = { ...this.__compScopes[scopeKey] }
2084
- // compSelf.__proto__ = scope
2085
- // scope = compSelf
2086
- // }
2087
-
2088
- if (engine.props?.designMode) {
2089
- otherProps.__designMode = engine.props.designMode;
2090
- }
2091
- if (this.__designModeIsDesign) {
2092
- otherProps.__tag = Math.random();
2093
- }
2094
- const componentInfo = {};
2095
- const props = this.__getComponentProps(schema, scope, Comp, {
2096
- ...componentInfo,
2097
- props: transformArrayToMap(componentInfo.props, 'name')
2098
- }) || {};
2099
- Comp = this.__getHOCWrappedComponent(Comp, {
2100
- schema,
2101
- componentInfo,
2102
- baseRenderer: this,
2103
- scope
2104
- });
2105
- otherProps.ref = ref => {
2106
- this.$(schema.id || props.ref, ref); // 收集ref
2107
- const refProps = props.ref;
2108
- if (refProps && typeof refProps === 'string') {
2109
- this[refProps] = ref;
2110
- }
2111
- ref && engine.props?.onCompGetRef?.(schema, ref);
2112
- };
2113
-
2114
- // scope需要传入到组件上
2115
- // if (scopeKey && this.__compScopes[scopeKey]) {
2116
- // props.__scope = this.__compScopes[scopeKey]
2117
- // }
2118
- if (schema?.__ctx?.lceKey) {
2119
- if (!isSchema(schema)) {
2120
- engine.props?.onCompGetCtx?.(schema, scope);
2121
- }
2122
- props.key = props.key || `${schema.__ctx.lceKey}_${schema.__ctx.idx || 0}_${idx !== undefined ? idx : ''}`;
2123
- } else if ((typeof idx === 'number' || typeof idx === 'string') && !props.key) {
2124
- // 仅当循环场景走这里
2125
- props.key = idx;
2126
- }
2127
- props.__id = schema.id;
2128
- if (!props.key) {
2129
- props.key = props.__id;
2130
- }
2131
- return engine.createElement(Comp, {
2132
- ...props,
2133
- ...otherProps,
2134
- // TODO: 看看这里需要怎么处理简洁
2135
- __inner__: {
2136
- hidden: schema.hidden,
2137
- condition
2138
- }
2139
- }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp, condition));
2140
- } catch (e) {
2141
- return engine.createElement(engine.getFaultComponent(), {
2142
- error: e,
2143
- schema,
2144
- self: scope,
2145
- parentInfo,
2146
- idx
2147
- });
2148
- }
2149
- };
2150
-
2151
- /**
2152
- * get Component HOCs
2153
- *
2154
- * @readonly
2155
- * @type {ComponentConstruct[]}
2156
- */
2157
- get __componentHOCs() {
2158
- if (this.__designModeIsDesign) {
2159
- return [leafWrapper, compWrapper];
2160
- }
2161
- return [compWrapper];
2162
- }
2163
- __getSchemaChildrenVirtualDom = (schema, scope, Comp, condition = true) => {
2164
- let children = condition ? getSchemaChildren(schema) : null;
2165
- const result = [];
2166
- if (children) {
2167
- if (!Array.isArray(children)) {
2168
- children = [children];
2169
- }
2170
- children.forEach(child => {
2171
- const childVirtualDom = this.__createVirtualDom(isJSExpression(child) ? this.__parseExpression(child, scope) : child, scope, {
2172
- schema,
2173
- Comp
2174
- });
2175
- result.push(childVirtualDom);
2176
- });
2177
- }
2178
- if (result && result.length > 0) {
2179
- return result;
2180
- }
2181
- return null;
2182
- };
2183
- __getComponentProps = (schema, scope, Comp, componentInfo) => {
2184
- if (!schema) {
2185
- return {};
2186
- }
2187
- return this.__parseProps(schema?.props, scope, '', {
2188
- schema,
2189
- Comp,
2190
- componentInfo: {
2191
- ...(componentInfo || {}),
2192
- props: transformArrayToMap((componentInfo || {}).props, 'name')
2193
- }
2194
- }) || {};
2195
- };
2196
- __createLoopVirtualDom = (schema, scope, parentInfo, idx) => {
2197
- // TODO
2198
- // if (isSchema(schema)) {
2199
- // logger.warn('file type not support Loop')
2200
- // return null
2201
- // }
2202
- if (!Array.isArray(schema.loop)) {
2203
- return null;
2204
- }
2205
- const itemArg = schema.loopArgs && schema.loopArgs[0] || DEFAULT_LOOP_ARG_ITEM;
2206
- const indexArg = schema.loopArgs && schema.loopArgs[1] || DEFAULT_LOOP_ARG_INDEX;
2207
- const {
2208
- loop
2209
- } = schema;
2210
- return loop.map((item, i) => {
2211
- const loopSelf = {
2212
- [itemArg]: item,
2213
- [indexArg]: i
2214
- };
2215
- loopSelf.__proto__ = scope;
2216
- return this.__createVirtualDom({
2217
- ...schema,
2218
- loop: undefined,
2219
- props: {
2220
- ...schema.props,
2221
- // 循环下 key 不能为常量,这样会造成 key 值重复,渲染异常
2222
- key: isJSExpression(schema.props?.key) ? schema.props?.key : null
2223
- }
2224
- }, loopSelf, parentInfo, idx ? `${idx}_${i}` : i);
2225
- });
2226
- };
2227
- get __designModeIsDesign() {
2228
- const {
2229
- engine
2230
- } = this.context || {};
2231
- return engine?.props?.designMode === 'design';
2232
- }
2233
- __parseProps = (originalProps, scope, path, info) => {
2234
- let props = originalProps;
2235
- const {
2236
- schema,
2237
- Comp,
2238
- componentInfo = {}
2239
- } = info;
2240
- const propInfo = getValue(componentInfo.props, path);
2241
- // FIXME: 将这行逻辑外置,解耦,线上环境不要验证参数,调试环境可以有,通过传参自定义
2242
- const propType = propInfo?.extra?.propType;
2243
- const checkProps = value => {
2244
- if (!propType) {
2245
- return value;
2246
- }
2247
- return checkPropTypes(value, path, propType, componentInfo.name) ? value : undefined;
2248
- };
2249
- const parseReactNode = (data, params) => {
2250
- if (isEmpty(params)) {
2251
- const virtualDom = this.__createVirtualDom(data, scope, {
2252
- schema,
2253
- Comp
2254
- });
2255
- return checkProps(virtualDom);
2256
- }
2257
- return checkProps((...argValues) => {
2258
- const args = {};
2259
- if (Array.isArray(params) && params.length) {
2260
- params.forEach((item, idx) => {
2261
- if (typeof item === 'string') {
2262
- args[item] = argValues[idx];
2263
- } else if (item && typeof item === 'object') {
2264
- args[item.name] = argValues[idx];
2265
- }
2266
- });
2267
- }
2268
- args.__proto__ = scope;
2269
- return scope.__createVirtualDom(data, args, {
2270
- schema,
2271
- Comp
2272
- });
2273
- });
2274
- };
2275
- if (isJSExpression(props)) {
2276
- props = this.__parseExpression(props, scope);
2277
- // 只有当变量解析出来为模型结构的时候才会继续解析
2278
- if (!isSchema(props)) {
2279
- return checkProps(props);
2280
- }
2281
- }
2282
- if (isJSFunction(props)) {
2283
- props = transformStringToFunction(props.value);
2284
- }
2285
-
2286
- // 兼容通过componentInfo判断的情况
2287
- if (isSchema(props)) {
2288
- const isReactNodeFunction = !!(propInfo?.type === 'ReactNode' && propInfo?.props?.type === 'function');
2289
- const isMixinReactNodeFunction = !!(propInfo?.type === 'Mixin' && propInfo?.props?.types?.indexOf('ReactNode') > -1 && propInfo?.props?.reactNodeProps?.type === 'function');
2290
- let params = null;
2291
- if (isReactNodeFunction) {
2292
- params = propInfo?.props?.params;
2293
- } else if (isMixinReactNodeFunction) {
2294
- params = propInfo?.props?.reactNodeProps?.params;
2295
- }
2296
- return parseReactNode(props, params);
2297
- }
2298
- if (Array.isArray(props)) {
2299
- return checkProps(props.map((item, idx) => this.__parseProps(item, scope, path ? `${path}.${idx}` : `${idx}`, info)));
2300
- }
2301
- if (typeof props === 'function') {
2302
- return checkProps(props.bind(scope));
2303
- }
2304
- if (props && typeof props === 'object') {
2305
- if (props.$$typeof) {
2306
- return checkProps(props);
2307
- }
2308
- const res = {};
2309
- forEach(props, (val, key) => {
2310
- if (key.startsWith('__')) {
2311
- res[key] = val;
2312
- return;
2313
- }
2314
- res[key] = this.__parseProps(val, scope, path ? `${path}.${key}` : key, info);
2315
- });
2316
- return checkProps(res);
2317
- }
2318
- return checkProps(props);
2319
- };
2320
- $(id, instance) {
2321
- this.__instanceMap = this.__instanceMap || {};
2322
- if (!id || typeof id !== 'string') {
2323
- return this.__instanceMap;
2324
- }
2325
- if (instance) {
2326
- this.__instanceMap[id] = instance;
2327
- }
2328
- return this.__instanceMap[id];
2329
- }
2330
- __renderContextProvider = (customProps, children) => {
2331
- return /*#__PURE__*/jsx(RendererContext.Provider, {
2332
- value: {
2333
- ...this.context,
2334
- blockContext: this,
2335
- ...(customProps || {})
2336
- },
2337
- children: children || this.__createDom()
2338
- });
2339
- };
2340
- __renderContextConsumer = children => {
2341
- return /*#__PURE__*/jsx(RendererContext.Consumer, {
2342
- children: children
2343
- });
2344
- };
2345
- __getHOCWrappedComponent(OriginalComp, info) {
2346
- let Comp = OriginalComp;
2347
- this.__componentHOCs.forEach(ComponentConstruct => {
2348
- Comp = ComponentConstruct(Comp, {
2349
- componentInfo: {},
2350
- baseRenderer: this,
2351
- ...info
2352
- });
2353
- });
2354
- return Comp;
2355
- }
2356
- __renderComp(OriginalComp, ctxProps) {
2357
- let Comp = OriginalComp;
2358
- const {
2359
- __schema,
2360
- __ctx
2361
- } = this.props;
2362
- const scope = {};
2363
- scope.__proto__ = __ctx || this;
2364
- Comp = this.__getHOCWrappedComponent(Comp, {
2365
- schema: __schema,
2366
- scope
2367
- });
2368
- const data = this.__parseProps(__schema?.props, scope, '', {
2369
- schema: __schema,
2370
- Comp,
2371
- componentInfo: {}
2372
- });
2373
- const {
2374
- className
2375
- } = data;
2376
- const otherProps = {};
2377
- const {
2378
- engine
2379
- } = this.context || {};
2380
- if (!engine) {
2381
- return null;
2382
- }
2383
- if (this.__designModeIsDesign) {
2384
- otherProps.__tag = Math.random();
2385
- }
2386
- const child = engine.createElement(Comp, {
2387
- ...data,
2388
- ...this.props,
2389
- ref: this.__getRef,
2390
- className: classnames(__schema?.fileName && getFileCssName(__schema.fileName), className, this.props.className),
2391
- __id: __schema?.id,
2392
- ...otherProps
2393
- }, this.__createDom());
2394
- return this.__renderContextProvider(ctxProps, child);
2395
- }
2396
- __renderContent(children) {
2397
- const {
2398
- __schema
2399
- } = this.props;
2400
- const parsedProps = this.__parseData(__schema.props);
2401
- const className = classnames(`lce-${this.__namespace}`, __schema?.fileName && getFileCssName(__schema.fileName), parsedProps.className, this.props.className);
2402
- const style = {
2403
- ...(parsedProps.style || {}),
2404
- ...(typeof this.props.style === 'object' ? this.props.style : {})
2405
- };
2406
- const id = this.props.id || parsedProps.id;
2407
- return /*#__PURE__*/jsx("div", {
2408
- ref: this.__getRef,
2409
- className: className,
2410
- id: id,
2411
- style: style,
2412
- children: children
2413
- });
2414
- }
2415
- __checkSchema = (schema, originalExtraComponents = []) => {
2416
- let extraComponents = originalExtraComponents;
2417
- if (typeof extraComponents === 'string') {
2418
- extraComponents = [extraComponents];
2419
- }
2420
-
2421
- // const builtin = capitalizeFirstLetter(this.__namespace)
2422
- // const componentNames = [builtin, ...extraComponents]
2423
- const componentNames = [...Object.keys(this.props.__components), ...extraComponents];
2424
- return !isSchema(schema) || !componentNames.includes(schema?.componentName ?? '');
2425
- };
2426
- get appHelper() {
2427
- return this.props.__appHelper;
2428
- }
2429
- get requestHandlersMap() {
2430
- return this.appHelper?.requestHandlersMap;
2431
- }
2432
- get utils() {
2433
- return this.appHelper?.utils;
2434
- }
2435
- get constants() {
2436
- return this.appHelper?.constants;
2437
- }
2438
-
2439
- // render() {
2440
- // return null
2441
- // }
2442
- };
2443
- }
2444
-
2445
- function componentRendererFactory() {
2446
- const BaseRenderer = baseRendererFactory();
2447
- return class CompRenderer extends BaseRenderer {
2448
- static displayName = 'CompRenderer';
2449
- __namespace = 'component';
2450
- __afterInit(props, ...rest) {
2451
- this.__generateCtx({
2452
- component: this
2453
- });
2454
- const schema = props.__schema || {};
2455
- this.state = this.__parseData(schema.state || {});
2456
- this.__initDataSource(props);
2457
- this.__executeLifeCycleMethod('constructor', [props, ...rest]);
2458
- }
2459
- render() {
2460
- const {
2461
- __schema
2462
- } = this.props;
2463
- if (this.__checkSchema(__schema)) {
2464
- return '自定义组件 schema 结构异常!';
2465
- }
2466
- logger.log(`${CompRenderer.displayName} render - ${__schema.componentName}`);
2467
- this.__generateCtx({
2468
- component: this
2469
- });
2470
- this.__render();
2471
- const noContainer = this.__parseData(__schema.props?.noContainer);
2472
- this.__bindCustomMethods(this.props);
2473
- if (noContainer) {
2474
- return this.__renderContextProvider({
2475
- compContext: this
2476
- });
2477
- }
2478
- const Comp = this.__getComponentView();
2479
- if (!Comp) {
2480
- return this.__renderContent(this.__renderContextProvider({
2481
- compContext: this
2482
- }));
2483
- }
2484
- return this.__renderComp(Comp, {
2485
- compContext: this
2486
- });
2487
- }
2488
- };
2489
- }
2490
-
2491
- function pageRendererFactory() {
2492
- const BaseRenderer = baseRendererFactory();
2493
- return class PageRenderer extends BaseRenderer {
2494
- static displayName = 'PageRenderer';
2495
- __namespace = 'page';
2496
- __afterInit(props, ...rest) {
2497
- const schema = props.__schema || {};
2498
- this.state = this.__parseData(schema.state || {});
2499
- this.__initDataSource(props);
2500
- this.__executeLifeCycleMethod('constructor', [props, ...rest]);
2501
- }
2502
- async componentDidUpdate(prevProps, _prevState, snapshot) {
2503
- const {
2504
- __ctx
2505
- } = this.props;
2506
- // 当编排的时候修改 schema.state 值,需要将最新 schema.state 值 setState
2507
- if (JSON.stringify(prevProps.__schema.state) !== JSON.stringify(this.props.__schema.state)) {
2508
- const newState = this.__parseData(this.props.__schema.state, __ctx);
2509
- this.setState(newState);
2510
- }
2511
- super.componentDidUpdate?.(prevProps, _prevState, snapshot);
2512
- }
2513
- setState(state, callback) {
2514
- logger.log('page set state', state);
2515
- super.setState(state, callback);
2516
- }
2517
- render() {
2518
- const {
2519
- __schema
2520
- } = this.props;
2521
- if (this.__checkSchema(__schema)) {
2522
- return '页面schema结构异常!';
2523
- }
2524
- logger.log(`${PageRenderer.displayName} render - ${__schema.componentName}`);
2525
- this.__bindCustomMethods(this.props);
2526
- this.__initDataSource(this.props);
2527
- this.__generateCtx({
2528
- page: this
2529
- });
2530
- this.__render();
2531
- const Comp = this.__getComponentView();
2532
- if (!Comp) {
2533
- return this.__renderContent(this.__renderContextProvider({
2534
- pageContext: this
2535
- }));
2536
- }
2537
- return this.__renderComp(Comp, {
2538
- pageContext: this
2539
- });
2540
- }
2541
- };
2542
- }
2543
-
2544
- const FaultComponent = ({
2545
- componentName = '',
2546
- error
2547
- }) => {
2548
- logger.error(`${componentName} 组件渲染异常, 异常原因: ${error?.message || error || '未知'}`);
2549
- return /*#__PURE__*/jsxs("div", {
2550
- role: "alert",
2551
- "aria-label": `${componentName} 组件渲染异常`,
2552
- style: {
2553
- width: '100%',
2554
- height: '50px',
2555
- lineHeight: '50px',
2556
- textAlign: 'center',
2557
- fontSize: '15px',
2558
- color: '#ef4444',
2559
- border: '2px solid #ef4444'
2560
- },
2561
- children: [componentName, " \u7EC4\u4EF6\u6E32\u67D3\u5F02\u5E38\uFF0C\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7"]
2562
- });
2563
- };
2564
-
2565
- const NotFoundComponent = ({
2566
- componentName = '',
2567
- enableStrictNotFoundMode,
2568
- children
2569
- }) => {
2570
- logger.warn(`Component ${componentName} not found`);
2571
- if (enableStrictNotFoundMode) {
2572
- return /*#__PURE__*/jsx(Fragment, {
2573
- children: `${componentName} Component Not Found`
2574
- });
2575
- }
2576
- return /*#__PURE__*/jsx("div", {
2577
- role: "alert",
2578
- "aria-label": `${componentName} component not found`,
2579
- style: {
2580
- width: '100%',
2581
- height: '50px',
2582
- lineHeight: '50px',
2583
- textAlign: 'center',
2584
- fontSize: '15px',
2585
- color: '#eab308',
2586
- border: '2px solid #eab308'
2587
- },
2588
- children: `${componentName} Component Not Found`
2589
- });
2590
- };
2591
-
2592
- function rendererFactory() {
2593
- const RENDERER_COMPS = adapter.getRenderers();
2594
- return class Renderer extends Component {
2595
- static displayName = 'Renderer';
2596
- state = {};
2597
- __ref;
2598
- static defaultProps = {
2599
- appHelper: undefined,
2600
- components: {},
2601
- designMode: 'live',
2602
- suspended: false,
2603
- schema: {},
2604
- onCompGetRef: () => {},
2605
- onCompGetCtx: () => {},
2606
- excuteLifeCycleInDesignMode: false
2607
- };
2608
- constructor(props) {
2609
- super(props);
2610
- this.state = {};
2611
- logger$1.log(`entry.constructor - ${props?.schema?.componentName}`);
2612
- }
2613
- async componentDidMount() {
2614
- logger$1.log(`entry.componentDidMount - ${this.props.schema && this.props.schema.componentName}`);
2615
- }
2616
- async componentDidUpdate() {
2617
- logger$1.log(`entry.componentDidUpdate - ${this.props?.schema?.componentName}`);
2618
- }
2619
- async componentWillUnmount() {
2620
- logger$1.log(`entry.componentWillUnmount - ${this.props?.schema?.componentName}`);
2621
- }
2622
- componentDidCatch(error) {
2623
- this.state.engineRenderError = true;
2624
- this.state.error = error;
2625
- }
2626
- shouldComponentUpdate(nextProps) {
2627
- return !nextProps.suspended;
2628
- }
2629
- __getRef = ref => {
2630
- this.__ref = ref;
2631
- if (ref) {
2632
- this.props.onCompGetRef?.(this.props.schema, ref);
2633
- }
2634
- };
2635
- isValidComponent(SetComponent) {
2636
- return SetComponent;
2637
- }
2638
- createElement(SetComponent, props, children) {
2639
- return (this.props.customCreateElement || createElement)(SetComponent, props, children);
2640
- }
2641
- getNotFoundComponent() {
2642
- return this.props.notFoundComponent || NotFoundComponent;
2643
- }
2644
- getFaultComponent() {
2645
- return this.props.faultComponent || FaultComponent;
2646
- }
2647
- render() {
2648
- const {
2649
- schema,
2650
- designMode,
2651
- appHelper,
2652
- components
2653
- } = this.props;
2654
- if (isEmpty(schema)) {
2655
- return null;
2656
- }
2657
- if (!isSchema(schema)) {
2658
- logger$1.error('The root component name needs to be one of Page、Block、Component, please check the schema: ', schema);
2659
- return '模型结构异常';
2660
- }
2661
- logger$1.log('entry.render');
2662
- const allComponents = {
2663
- ...components,
2664
- ...RENDERER_COMPS
2665
- };
2666
- // TODO: 默认最顶层使用 PageRenderer
2667
- const Comp = allComponents.PageRenderer;
2668
- if (this.state && this.state.engineRenderError) {
2669
- return /*#__PURE__*/createElement(this.getFaultComponent(), {
2670
- componentName: schema.componentName,
2671
- error: this.state.error
2672
- });
2673
- }
2674
- if (!Comp) {
2675
- return null;
2676
- }
2677
- return /*#__PURE__*/jsx(RendererContext.Provider, {
2678
- value: {
2679
- appHelper,
2680
- components: allComponents,
2681
- engine: this
2682
- },
2683
- children: /*#__PURE__*/jsx(Comp, {
2684
- // ref={this.__getRef}
2685
- __appHelper: appHelper,
2686
- __components: allComponents,
2687
- __schema: schema,
2688
- __designMode: designMode,
2689
- ...this.props
2690
- }, schema.__ctx && `${schema.__ctx.lceKey}_${schema.__ctx.idx || '0'}`)
2691
- });
2692
- }
2693
- };
2694
- }
2695
-
2696
- const DEV = '_EASY_EDITOR_DEV_';
2697
-
2698
- export { DEV, RendererContext, SettingFieldView, SettingRender, adapter, baseRendererFactory, capitalizeFirstLetter, checkPropTypes, classnames, cloneEnumerableProperty, compWrapper, componentRendererFactory, contextFactory, createForwardRefHocElement, executeLifeCycleMethod, getFileCssName, getSchemaChildren, getValue, inSameDomain, isReactClass, isReactComponent, isSchema, isString, isUseLoop, leafWrapper, logger, pageRendererFactory, parseData, parseExpression, parseThisRequiredExpression, rendererFactory, transformArrayToMap, transformStringToFunction, useRendererContext };
2699
- //# sourceMappingURL=index.development.js.map