@easy-editor/react-renderer 0.0.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 (39) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +9 -0
  3. package/README.md +4 -0
  4. package/dist/cjs/index.development.js +2149 -0
  5. package/dist/cjs/index.development.js.map +1 -0
  6. package/dist/cjs/index.js +2149 -0
  7. package/dist/cjs/index.js.map +1 -0
  8. package/dist/cjs/index.production.js +2149 -0
  9. package/dist/cjs/index.production.js.map +1 -0
  10. package/dist/configure-renderer/SettingSetter.d.ts +7 -0
  11. package/dist/configure-renderer/context.d.ts +12 -0
  12. package/dist/configure-renderer/index.d.ts +10 -0
  13. package/dist/esm/index.development.js +2114 -0
  14. package/dist/esm/index.development.js.map +1 -0
  15. package/dist/esm/index.js +2114 -0
  16. package/dist/esm/index.js.map +1 -0
  17. package/dist/esm/index.production.js +2114 -0
  18. package/dist/esm/index.production.js.map +1 -0
  19. package/dist/index.d.ts +3 -0
  20. package/dist/index.js +2113 -0
  21. package/dist/renderer-core/adapter/index.d.ts +17 -0
  22. package/dist/renderer-core/base.d.ts +11 -0
  23. package/dist/renderer-core/component.d.ts +2 -0
  24. package/dist/renderer-core/components/FaultComponent.d.ts +7 -0
  25. package/dist/renderer-core/components/NotFoundComponent.d.ts +7 -0
  26. package/dist/renderer-core/context.d.ts +6 -0
  27. package/dist/renderer-core/hoc/comp.d.ts +2 -0
  28. package/dist/renderer-core/hoc/index.d.ts +2 -0
  29. package/dist/renderer-core/hoc/leaf.d.ts +27 -0
  30. package/dist/renderer-core/index.d.ts +9 -0
  31. package/dist/renderer-core/page.d.ts +2 -0
  32. package/dist/renderer-core/renderer.d.ts +2 -0
  33. package/dist/renderer-core/types.d.ts +187 -0
  34. package/dist/renderer-core/utils/classnames.d.ts +1 -0
  35. package/dist/renderer-core/utils/common.d.ts +54 -0
  36. package/dist/renderer-core/utils/hoc.d.ts +2 -0
  37. package/dist/renderer-core/utils/index.d.ts +4 -0
  38. package/dist/renderer-core/utils/logger.d.ts +5 -0
  39. package/package.json +82 -0
package/dist/index.js ADDED
@@ -0,0 +1,2113 @@
1
+ import { observer } from 'mobx-react';
2
+ import { createContext, useContext, useMemo, Component, forwardRef, createElement, PureComponent } from 'react';
3
+ import { isSetterConfig, createLogger, isJSExpression, TRANSFORM_STAGE, DESIGNER_EVENT, isJSFunction, logger as logger$1 } from '@easy-editor/core';
4
+ import { debounce, isEmpty, forEach } from 'lodash-es';
5
+
6
+ function _extends() {
7
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
8
+ for (var e = 1; e < arguments.length; e++) {
9
+ var t = arguments[e];
10
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
11
+ }
12
+ return n;
13
+ }, _extends.apply(null, arguments);
14
+ }
15
+
16
+ const SettingRendererContext = /*#__PURE__*/createContext({});
17
+ const useSettingRendererContext = () => {
18
+ try {
19
+ return useContext(SettingRendererContext);
20
+ } catch (error) {
21
+ console.warn('useSettingRendererContext must be used within a SettingRendererContextProvider');
22
+ }
23
+ return {};
24
+ };
25
+
26
+ const getSetterInfo = field => {
27
+ const {
28
+ extraProps,
29
+ setter
30
+ } = field;
31
+ const {
32
+ defaultValue
33
+ } = extraProps;
34
+ let setterProps = {};
35
+ let setterType;
36
+ let initialValue = null;
37
+ if (isSetterConfig(setter)) {
38
+ setterType = setter.componentName;
39
+ if (setter.props) {
40
+ setterProps = setter.props;
41
+ if (typeof setterProps === 'function') {
42
+ setterProps = setterProps(field);
43
+ }
44
+ }
45
+ if (setter.defaultValue != null) {
46
+ initialValue = setter.defaultValue;
47
+ }
48
+ } else if (setter) {
49
+ setterType = setter;
50
+ }
51
+ if (defaultValue != null && !('defaultValue' in setterProps)) {
52
+ setterProps.defaultValue = defaultValue;
53
+ if (initialValue == null) {
54
+ initialValue = defaultValue;
55
+ }
56
+ }
57
+ if (field.valueState === -1) {
58
+ setterProps.multiValue = true;
59
+ }
60
+
61
+ // 根据是否支持变量配置做相应的更改
62
+ const supportVariable = field.extraProps?.supportVariable;
63
+ const isUseVariableSetter = supportVariable;
64
+ if (isUseVariableSetter === false) {
65
+ return {
66
+ setterProps,
67
+ initialValue,
68
+ setterType
69
+ };
70
+ }
71
+ return {
72
+ setterProps,
73
+ setterType,
74
+ initialValue
75
+ };
76
+ };
77
+ const SettingSetter = observer(({
78
+ field,
79
+ children
80
+ }) => {
81
+ const {
82
+ setterManager
83
+ } = useSettingRendererContext();
84
+ const {
85
+ extraProps
86
+ } = field;
87
+ const visible = extraProps?.condition && typeof extraProps.condition === 'function' ? extraProps.condition(field) !== false : true;
88
+ if (!visible) {
89
+ return null;
90
+ }
91
+ const {
92
+ setterProps = {},
93
+ setterType,
94
+ initialValue = null
95
+ } = getSetterInfo(field);
96
+ const onChange = extraProps?.onChange;
97
+ const value = field.valueState === -1 ? null : field.getValue();
98
+ const {
99
+ component: SetterComponent,
100
+ props: mixedSetterProps
101
+ } = setterManager.createSetterContent(setterType, setterProps);
102
+ return /*#__PURE__*/React.createElement(SetterComponent, _extends({
103
+ key: field.id,
104
+ field: field,
105
+ selected: field.top?.getNode(),
106
+ initialValue: initialValue,
107
+ value: value,
108
+ onChange: newVal => {
109
+ field.setValue(newVal);
110
+ onChange?.(field, newVal);
111
+ },
112
+ onInitial: () => {
113
+ if (initialValue == null) {
114
+ return;
115
+ }
116
+ const value = typeof initialValue === 'function' ? initialValue(field) : initialValue;
117
+ field.setValue(value, true);
118
+ },
119
+ removeProp: () => {
120
+ if (field.name) {
121
+ field.parent.clearPropValue(field.name);
122
+ }
123
+ }
124
+ }, mixedSetterProps), children);
125
+ });
126
+
127
+ const SettingFieldItem = observer(({
128
+ field
129
+ }) => {
130
+ const {
131
+ customFieldItem
132
+ } = useSettingRendererContext();
133
+ if (customFieldItem) {
134
+ return customFieldItem(field, /*#__PURE__*/React.createElement(SettingSetter, {
135
+ field: field
136
+ }));
137
+ }
138
+ return /*#__PURE__*/React.createElement("div", {
139
+ className: "space-y-2"
140
+ }, /*#__PURE__*/React.createElement("label", {
141
+ htmlFor: field.id,
142
+ className: "block text-sm font-medium text-gray-700"
143
+ }, field.title), /*#__PURE__*/React.createElement(SettingSetter, {
144
+ field: field
145
+ }));
146
+ });
147
+ const SettingFieldGroup = observer(({
148
+ field
149
+ }) => {
150
+ const {
151
+ customFieldGroup
152
+ } = useSettingRendererContext();
153
+ if (customFieldGroup) {
154
+ return customFieldGroup(field, /*#__PURE__*/React.createElement(SettingSetter, {
155
+ field: field
156
+ }, field.items?.map(item => /*#__PURE__*/React.createElement(SettingFieldView, {
157
+ key: item.id,
158
+ field: item
159
+ }))));
160
+ }
161
+ return /*#__PURE__*/React.createElement(SettingSetter, {
162
+ field: field
163
+ }, field.items?.map(item => /*#__PURE__*/React.createElement(SettingFieldView, {
164
+ key: item.id,
165
+ field: item
166
+ })));
167
+ });
168
+ const SettingFieldView = ({
169
+ field
170
+ }) => {
171
+ if (field.isGroup) {
172
+ return /*#__PURE__*/React.createElement(SettingFieldGroup, {
173
+ field: field,
174
+ key: field.id
175
+ });
176
+ } else {
177
+ return /*#__PURE__*/React.createElement(SettingFieldItem, {
178
+ field: field,
179
+ key: field.id
180
+ });
181
+ }
182
+ };
183
+ const SettingRender = observer(props => {
184
+ const {
185
+ editor,
186
+ customFieldItem,
187
+ customFieldGroup
188
+ } = props;
189
+ const designer = editor.get('designer');
190
+ const setterManager = editor.get('setterManager');
191
+ const {
192
+ settingsManager
193
+ } = designer;
194
+ const {
195
+ settings
196
+ } = settingsManager;
197
+ const items = settings?.items;
198
+ const ctx = useMemo(() => {
199
+ const ctx = {};
200
+ ctx.setterManager = setterManager;
201
+ ctx.settingsManager = settingsManager;
202
+ ctx.customFieldItem = customFieldItem;
203
+ ctx.customFieldGroup = customFieldGroup;
204
+ return ctx;
205
+ }, [setterManager, settingsManager, customFieldItem, customFieldGroup]);
206
+ if (!settings) {
207
+ // 未选中节点,提示选中 或者 显示根节点设置
208
+ return /*#__PURE__*/React.createElement("div", {
209
+ className: "lc-settings-main"
210
+ }, /*#__PURE__*/React.createElement("div", {
211
+ className: "lc-settings-notice"
212
+ }, /*#__PURE__*/React.createElement("p", null, "Please select a node in canvas")));
213
+ }
214
+
215
+ // 当节点被锁定,且未开启锁定后容器可设置属性
216
+ if (settings.isLocked) {
217
+ return /*#__PURE__*/React.createElement("div", {
218
+ className: "lc-settings-main"
219
+ }, /*#__PURE__*/React.createElement("div", {
220
+ className: "lc-settings-notice"
221
+ }, /*#__PURE__*/React.createElement("p", null, "Current node is locked")));
222
+ }
223
+ if (Array.isArray(settings.items) && settings.items.length === 0) {
224
+ return /*#__PURE__*/React.createElement("div", {
225
+ className: "lc-settings-main"
226
+ }, /*#__PURE__*/React.createElement("div", {
227
+ className: "lc-settings-notice"
228
+ }, /*#__PURE__*/React.createElement("p", null, "No config found for this type of component")));
229
+ }
230
+ if (!settings.isSameComponent) {
231
+ // TODO: future support 获取设置项交集编辑
232
+ return /*#__PURE__*/React.createElement("div", {
233
+ className: "lc-settings-main"
234
+ }, /*#__PURE__*/React.createElement("div", {
235
+ className: "lc-settings-notice"
236
+ }, /*#__PURE__*/React.createElement("p", null, "Please select same kind of components")));
237
+ }
238
+ return /*#__PURE__*/React.createElement(SettingRendererContext.Provider, {
239
+ value: ctx
240
+ }, items?.map(item => /*#__PURE__*/React.createElement(SettingFieldView, {
241
+ key: item.id,
242
+ field: item
243
+ })));
244
+ });
245
+
246
+ class Adapter {
247
+ renderers = {};
248
+ setRenderers(renderers) {
249
+ this.renderers = renderers;
250
+ }
251
+ setBaseRenderer(BaseRenderer) {
252
+ this.renderers.BaseRenderer = BaseRenderer;
253
+ }
254
+ setPageRenderer(PageRenderer) {
255
+ this.renderers.PageRenderer = PageRenderer;
256
+ }
257
+ setComponentRenderer(ComponentRenderer) {
258
+ this.renderers.ComponentRenderer = ComponentRenderer;
259
+ }
260
+ getRenderers() {
261
+ return this.renderers || {};
262
+ }
263
+ }
264
+ const adapter = new Adapter();
265
+
266
+ const RendererContext = /*#__PURE__*/createContext({});
267
+ const useRendererContext = () => {
268
+ try {
269
+ return useContext(RendererContext);
270
+ } catch (error) {
271
+ console.warn('useRendererContext must be used within a RendererContextProvider');
272
+ }
273
+ return {};
274
+ };
275
+ function contextFactory() {
276
+ let context = window.__appContext;
277
+ if (!context) {
278
+ context = /*#__PURE__*/createContext({});
279
+ window.__appContext = context;
280
+ }
281
+ return context;
282
+ }
283
+
284
+ const classnames = (...args) => {
285
+ return args.filter(Boolean).join(' ');
286
+ };
287
+
288
+ const logger = createLogger('Renderer');
289
+
290
+ const PropTypes2 = true;
291
+ function inSameDomain() {
292
+ try {
293
+ return window.parent !== window && window.parent.location.host === window.location.host;
294
+ } catch (e) {
295
+ return false;
296
+ }
297
+ }
298
+ function getFileCssName(fileName) {
299
+ if (!fileName) {
300
+ return;
301
+ }
302
+ const name = fileName.replace(/([A-Z])/g, '-$1').toLowerCase();
303
+ return `lce-${name}`.split('-').filter(p => !!p).join('-');
304
+ }
305
+ const isSchema = schema => {
306
+ if (!schema) {
307
+ return false;
308
+ }
309
+ if (schema.componentName === 'Leaf' || schema.componentName === 'Slot') {
310
+ return true;
311
+ }
312
+ if (Array.isArray(schema)) {
313
+ return schema.every(item => isSchema(item));
314
+ }
315
+ const isValidProps = props => {
316
+ if (!props) {
317
+ return false;
318
+ }
319
+ return typeof schema.props === 'object' && !Array.isArray(props);
320
+ };
321
+ return !!(schema.componentName && isValidProps(schema.props));
322
+ };
323
+ const getValue = (obj, path, defaultValue = {}) => {
324
+ if (Array.isArray(obj)) {
325
+ return defaultValue;
326
+ }
327
+ if (!obj || typeof obj !== 'object') {
328
+ return defaultValue;
329
+ }
330
+ const res = path.split('.').reduce((pre, cur) => {
331
+ return pre && pre[cur];
332
+ }, obj);
333
+ if (res === undefined) {
334
+ return defaultValue;
335
+ }
336
+ return res;
337
+ };
338
+ function transformArrayToMap(arr, key, overwrite = true) {
339
+ if (!arr || !Array.isArray(arr)) {
340
+ return {};
341
+ }
342
+ const res = {};
343
+ arr.forEach(item => {
344
+ const curKey = item[key];
345
+ if (item[key] === undefined) {
346
+ return;
347
+ }
348
+ if (res[curKey] && !overwrite) {
349
+ return;
350
+ }
351
+ res[curKey] = item;
352
+ });
353
+ return res;
354
+ }
355
+ const parseData = (schema, self, options = {}) => {
356
+ if (isJSExpression(schema)) {
357
+ return parseExpression({
358
+ str: schema,
359
+ self,
360
+ thisRequired: options.thisRequiredInJSE,
361
+ logScope: options.logScope
362
+ });
363
+ }
364
+ if (typeof schema === 'string') {
365
+ return schema.trim();
366
+ } else if (Array.isArray(schema)) {
367
+ return schema.map(item => parseData(item, self, options));
368
+ } else if (typeof schema === 'function') {
369
+ return schema.bind(self);
370
+ } else if (typeof schema === 'object') {
371
+ if (!schema) {
372
+ return schema;
373
+ }
374
+ const res = {};
375
+ Object.entries(schema).forEach(([key, val]) => {
376
+ if (key.startsWith('__')) {
377
+ return;
378
+ }
379
+ res[key] = parseData(val, self, options);
380
+ });
381
+ return res;
382
+ }
383
+ return schema;
384
+ };
385
+ const isUseLoop = (loop, isDesignMode) => {
386
+ if (!isDesignMode) {
387
+ return true;
388
+ }
389
+ if (!Array.isArray(loop)) {
390
+ return false;
391
+ }
392
+ return loop.length > 0;
393
+ };
394
+ function checkPropTypes(value, name, rule, componentName) {
395
+ let ruleFunction = rule;
396
+ if (typeof rule === 'string') {
397
+ ruleFunction = new Function(`"use strict"; const PropTypes = arguments[0]; return ${rule}`)(PropTypes2);
398
+ }
399
+ if (!ruleFunction || typeof ruleFunction !== 'function') {
400
+ logger.warn('checkPropTypes should have a function type rule argument');
401
+ return true;
402
+ }
403
+ const err = ruleFunction({
404
+ [name]: value
405
+ }, name, componentName, 'prop', null
406
+ );
407
+ if (err) {
408
+ logger.warn(err);
409
+ }
410
+ return !err;
411
+ }
412
+ function transformStringToFunction(str) {
413
+ if (typeof str !== 'string') {
414
+ return str;
415
+ }
416
+ if (inSameDomain() && window.parent.__newFunc) {
417
+ return window.parent.__newFunc(`"use strict"; return ${str}`)();
418
+ } else {
419
+ return new Function(`"use strict"; return ${str}`)();
420
+ }
421
+ }
422
+ function parseExpression(a, b, c = false) {
423
+ let str;
424
+ let self;
425
+ let thisRequired;
426
+ let logScope;
427
+ if (typeof a === 'object' && b === undefined) {
428
+ str = a.str;
429
+ self = a.self;
430
+ thisRequired = a.thisRequired;
431
+ logScope = a.logScope;
432
+ } else {
433
+ str = a;
434
+ self = b;
435
+ thisRequired = c;
436
+ }
437
+ try {
438
+ const contextArr = ['"use strict";', 'var __self = arguments[0];'];
439
+ contextArr.push('return ');
440
+ let tarStr;
441
+ tarStr = (str.value || '').trim();
442
+ tarStr = tarStr.replace(/this(\W|$)/g, (_a, b) => `__self${b}`);
443
+ tarStr = contextArr.join('\n') + tarStr;
444
+ if (inSameDomain() && window.parent.__newFunc) {
445
+ return window.parent.__newFunc(tarStr)(self);
446
+ }
447
+ const code = `with(${thisRequired ? '{}' : '$scope || {}'}) { ${tarStr} }`;
448
+ return new Function('$scope', code)(self);
449
+ } catch (err) {
450
+ logger.error(`${logScope || ''} parseExpression.error`, err, str, self?.__self ?? self);
451
+ return undefined;
452
+ }
453
+ }
454
+ function parseThisRequiredExpression(str, self) {
455
+ return parseExpression(str, self, true);
456
+ }
457
+ function isString(str) {
458
+ return {}.toString.call(str) === '[object String]';
459
+ }
460
+ function capitalizeFirstLetter(word) {
461
+ if (!word || !isString(word) || word.length === 0) {
462
+ return word;
463
+ }
464
+ return word[0].toUpperCase() + word.slice(1);
465
+ }
466
+ const isReactClass = obj => {
467
+ return obj && obj.prototype && (obj.prototype.isReactComponent || obj.prototype instanceof Component);
468
+ };
469
+ function isReactComponent(obj) {
470
+ return obj && (isReactClass(obj) || typeof obj === 'function');
471
+ }
472
+
473
+ const excludePropertyNames = ['$$typeof', 'render', 'defaultProps', 'props', 'length', 'prototype', 'name', 'caller', 'callee', 'arguments'];
474
+ const cloneEnumerableProperty = (target, origin, excludes = excludePropertyNames) => {
475
+ const compExtraPropertyNames = Object.keys(origin).filter(d => !excludes.includes(d));
476
+ compExtraPropertyNames.forEach(d => {
477
+ target[d] = origin[d];
478
+ });
479
+ return target;
480
+ };
481
+ const createForwardRefHocElement = (Wrapper, Comp) => {
482
+ const WrapperComponent = cloneEnumerableProperty(/*#__PURE__*/forwardRef((props, ref) => {
483
+ return /*#__PURE__*/createElement(Wrapper, {
484
+ ...props,
485
+ forwardRef: ref
486
+ });
487
+ }), Comp);
488
+ WrapperComponent.displayName = Comp.displayName;
489
+ return WrapperComponent;
490
+ };
491
+
492
+ const patchDidCatch = (Comp, {
493
+ baseRenderer
494
+ }) => {
495
+ if (Comp.patchedCatch) {
496
+ return;
497
+ }
498
+ Comp.patchedCatch = true;
499
+ const originalDidCatch = Comp.prototype.componentDidCatch;
500
+ Comp.prototype.componentDidCatch = function didCatch(error, errorInfo) {
501
+ this.setState({
502
+ engineRenderError: true,
503
+ error
504
+ });
505
+ if (originalDidCatch && typeof originalDidCatch === 'function') {
506
+ originalDidCatch.call(this, error, errorInfo);
507
+ }
508
+ };
509
+ const {
510
+ engine
511
+ } = baseRenderer.context;
512
+ const originRender = Comp.prototype.render;
513
+ Comp.prototype.render = function () {
514
+ if (this.state && this.state.engineRenderError) {
515
+ this.state.engineRenderError = false;
516
+ return engine.createElement(engine.getFaultComponent(), {
517
+ ...this.props,
518
+ error: this.state.error,
519
+ componentName: this.props._componentName
520
+ });
521
+ }
522
+ return originRender.call(this);
523
+ };
524
+ if (!(Comp.prototype instanceof PureComponent)) {
525
+ const originShouldComponentUpdate = Comp.prototype.shouldComponentUpdate;
526
+ Comp.prototype.shouldComponentUpdate = function (nextProps, nextState) {
527
+ if (nextState && nextState.engineRenderError) {
528
+ return true;
529
+ }
530
+ return originShouldComponentUpdate ? originShouldComponentUpdate.call(this, nextProps, nextState) : true;
531
+ };
532
+ }
533
+ };
534
+ const cache$1 = new Map();
535
+ const compWrapper = (Comp, info) => {
536
+ if (Comp?.prototype?.isReactComponent || Comp?.prototype instanceof Component) {
537
+ patchDidCatch(Comp, info);
538
+ return Comp;
539
+ }
540
+ if (info.schema.id && cache$1.has(info.schema.id) && cache$1.get(info.schema.id)?.Comp === Comp) {
541
+ return cache$1.get(info.schema.id)?.WrapperComponent;
542
+ }
543
+ class Wrapper extends Component {
544
+ static displayName = Comp.displayName;
545
+ render() {
546
+ const {
547
+ forwardRef,
548
+ ...rest
549
+ } = this.props;
550
+ // @ts-ignore
551
+ return /*#__PURE__*/createElement(Comp, {
552
+ ...rest,
553
+ ref: forwardRef
554
+ });
555
+ }
556
+ }
557
+ patchDidCatch(Wrapper, info);
558
+ const WrapperComponent = createForwardRefHocElement(Wrapper, Comp);
559
+ info.schema.id && cache$1.set(info.schema.id, {
560
+ WrapperComponent,
561
+ Comp
562
+ });
563
+ return WrapperComponent;
564
+ };
565
+
566
+ var RerenderType = /*#__PURE__*/function (RerenderType) {
567
+ RerenderType["All"] = "All";
568
+ RerenderType["ChildChanged"] = "ChildChanged";
569
+ RerenderType["PropsChanged"] = "PropsChanged";
570
+ RerenderType["VisibleChanged"] = "VisibleChanged";
571
+ RerenderType["MinimalRenderUnit"] = "MinimalRenderUnit";
572
+ return RerenderType;
573
+ }(RerenderType || {}); // 缓存 Leaf 层组件,防止重新渲染问题
574
+ class LeafCache {
575
+ /** 组件缓存 */
576
+ component = new Map();
577
+
578
+ /**
579
+ * 状态缓存,场景:属性变化后,改组件被销毁,state 为空,没有展示修改后的属性
580
+ */
581
+ state = new Map();
582
+
583
+ /**
584
+ * 订阅事件缓存,导致 rerender 的订阅事件
585
+ */
586
+ event = new Map();
587
+ ref = new Map();
588
+ constructor(documentId, device) {
589
+ this.documentId = documentId;
590
+ this.device = device;
591
+ }
592
+ }
593
+ let cache;
594
+
595
+ /** 部分没有渲染的 node 节点进行兜底处理 or 渲染方式没有渲染 LeafWrapper */
596
+ const initRerenderEvent = ({
597
+ schema,
598
+ container,
599
+ getNode
600
+ }) => {
601
+ const leaf = getNode?.(schema.id);
602
+ if (!leaf || cache.event.get(schema.id)?.clear || leaf === cache.event.get(schema.id)) {
603
+ return;
604
+ }
605
+ cache.event.get(schema.id)?.dispose.forEach(disposeFn => disposeFn && disposeFn());
606
+ const debounceRerender = debounce(() => {
607
+ container.rerender();
608
+ }, 20);
609
+ cache.event.set(schema.id, {
610
+ clear: false,
611
+ leaf,
612
+ dispose: [leaf?.onPropChange?.(() => {
613
+ if (!container.autoRepaintNode) {
614
+ return;
615
+ }
616
+ logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onPropsChange make rerender`);
617
+ debounceRerender();
618
+ }), leaf?.onChildrenChange?.(() => {
619
+ if (!container.autoRepaintNode) {
620
+ return;
621
+ }
622
+ logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onChildrenChange make rerender`);
623
+ debounceRerender();
624
+ }), leaf?.onVisibleChange?.(() => {
625
+ if (!container.autoRepaintNode) {
626
+ return;
627
+ }
628
+ logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onVisibleChange make rerender`);
629
+ debounceRerender();
630
+ })]
631
+ });
632
+ };
633
+
634
+ /** 渲染的 node 节点全局注册事件清除 */
635
+ const clearRerenderEvent = id => {
636
+ if (cache.event.get(id)?.clear) {
637
+ return;
638
+ }
639
+ cache.event.get(id)?.dispose?.forEach(disposeFn => disposeFn && disposeFn());
640
+ cache.event.set(id, {
641
+ clear: true,
642
+ dispose: []
643
+ });
644
+ };
645
+
646
+ // 给每个组件包裹一个 HOC Leaf,支持组件内部属性变化,自响应渲染
647
+ const leafWrapper = (Comp, {
648
+ schema,
649
+ baseRenderer,
650
+ componentInfo,
651
+ scope
652
+ }) => {
653
+ const {
654
+ __getComponentProps: getProps,
655
+ __getSchemaChildrenVirtualDom: getChildren,
656
+ __parseData
657
+ } = baseRenderer;
658
+ const {
659
+ engine
660
+ } = baseRenderer.context;
661
+ const host = baseRenderer.props?.__host;
662
+ const curDocumentId = baseRenderer.props?.documentId ?? '';
663
+ const curDevice = baseRenderer.props?.device ?? '';
664
+ const getNode = baseRenderer.props?.getNode;
665
+ const container = baseRenderer.props?.__container;
666
+ const setSchemaChangedSymbol = baseRenderer.props?.setSchemaChangedSymbol;
667
+ const designer = host?.designer;
668
+ const componentCacheId = schema.id;
669
+ if (!cache || curDocumentId && curDocumentId !== cache.documentId || curDevice && curDevice !== cache.device) {
670
+ cache?.event.forEach(event => {
671
+ event.dispose?.forEach(disposeFn => disposeFn && disposeFn());
672
+ });
673
+ cache = new LeafCache(curDocumentId, curDevice);
674
+ }
675
+
676
+ // if (!isReactComponent(Comp)) {
677
+ // logger.error(`${schema.componentName} component may be has errors: `, Comp)
678
+ // }
679
+
680
+ initRerenderEvent({
681
+ schema,
682
+ container,
683
+ getNode
684
+ });
685
+ if (curDocumentId && cache.component.has(componentCacheId) && cache.component.get(componentCacheId).Comp === Comp) {
686
+ return cache.component.get(componentCacheId).LeafWrapper;
687
+ }
688
+ class LeafHoc extends Component {
689
+ recordInfo = {};
690
+ curEventLeaf;
691
+ static displayName = schema.componentName;
692
+ disposeFunctions = [];
693
+ __component_tag = 'leafWrapper';
694
+ renderUnitInfo;
695
+
696
+ // 最小渲染单元做防抖处理
697
+ makeUnitRenderDebounced = debounce(() => {
698
+ this.beforeRender(RerenderType.MinimalRenderUnit);
699
+ const schema = this.leaf?.export?.(TRANSFORM_STAGE.RENDER);
700
+ if (!schema) {
701
+ return;
702
+ }
703
+ const nextProps = getProps(schema, scope, Comp, componentInfo);
704
+ const children = getChildren(schema, scope, Comp);
705
+ const nextState = {
706
+ nodeProps: nextProps,
707
+ nodeChildren: children,
708
+ childrenInState: true
709
+ };
710
+ if ('children' in nextProps) {
711
+ nextState.nodeChildren = nextProps.children;
712
+ }
713
+ logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) MinimalRenderUnit Render!`);
714
+ this.setState(nextState);
715
+ }, 20);
716
+ constructor(props) {
717
+ super(props);
718
+ // 监听以下事件,当变化时更新自己
719
+ logger.log(`${schema.componentName}[${this.leaf?.id}] leaf render in SimulatorRendererView`);
720
+ componentCacheId && clearRerenderEvent(componentCacheId);
721
+ this.curEventLeaf = this.leaf;
722
+ cache.ref.set(componentCacheId, {
723
+ makeUnitRender: this.makeUnitRender
724
+ });
725
+ let cacheState = cache.state.get(componentCacheId);
726
+ if (!cacheState || cacheState.__tag !== props.__tag) {
727
+ cacheState = this.getDefaultState(props);
728
+ }
729
+ this.state = cacheState;
730
+ }
731
+ recordTime = () => {
732
+ if (!this.recordInfo.startTime) {
733
+ return;
734
+ }
735
+ const endTime = Date.now();
736
+ const nodeCount = host?.designer?.currentDocument?.getNodeCount?.();
737
+ const componentName = this.recordInfo.node?.componentName || this.leaf?.componentName || 'UnknownComponent';
738
+ designer?.postEvent(DESIGNER_EVENT.NODE_RENDER, {
739
+ componentName,
740
+ time: endTime - this.recordInfo.startTime,
741
+ type: this.recordInfo.type,
742
+ nodeCount
743
+ });
744
+ this.recordInfo.startTime = null;
745
+ };
746
+ makeUnitRender = () => {
747
+ this.makeUnitRenderDebounced();
748
+ };
749
+ get autoRepaintNode() {
750
+ return container?.autoRepaintNode;
751
+ }
752
+ componentDidUpdate() {
753
+ this.recordTime();
754
+ }
755
+ componentDidMount() {
756
+ const _leaf = this.leaf;
757
+ this.initOnPropsChangeEvent(_leaf);
758
+ this.initOnChildrenChangeEvent(_leaf);
759
+ this.initOnVisibleChangeEvent(_leaf);
760
+ this.recordTime();
761
+ }
762
+ getDefaultState(nextProps) {
763
+ const {
764
+ hidden = false,
765
+ condition = true
766
+ } = nextProps.__inner__ || this.leaf?.export?.(TRANSFORM_STAGE.RENDER) || {};
767
+ return {
768
+ nodeChildren: null,
769
+ childrenInState: false,
770
+ visible: !hidden,
771
+ condition: __parseData?.(condition, scope),
772
+ nodeCacheProps: {},
773
+ nodeProps: {}
774
+ };
775
+ }
776
+ setState(state) {
777
+ cache.state.set(componentCacheId, {
778
+ ...this.state,
779
+ ...state,
780
+ __tag: this.props.__tag
781
+ });
782
+ super.setState(state);
783
+ }
784
+
785
+ /** 由于内部属性变化,在触发渲染前,会执行该函数 */
786
+ beforeRender(type, node) {
787
+ this.recordInfo.startTime = Date.now();
788
+ this.recordInfo.type = type;
789
+ this.recordInfo.node = node;
790
+ setSchemaChangedSymbol?.(true);
791
+ }
792
+ judgeMiniUnitRender() {
793
+ if (!this.renderUnitInfo) {
794
+ this.getRenderUnitInfo();
795
+ }
796
+ const renderUnitInfo = this.renderUnitInfo || {
797
+ singleRender: true
798
+ };
799
+ if (renderUnitInfo.singleRender) {
800
+ return;
801
+ }
802
+ const ref = cache.ref.get(renderUnitInfo.minimalUnitId);
803
+ if (!ref) {
804
+ logger.log('Cant find minimalRenderUnit ref! This make rerender!');
805
+ container?.rerender();
806
+ return;
807
+ }
808
+ logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) need render, make its minimalRenderUnit ${renderUnitInfo.minimalUnitName}(${renderUnitInfo.minimalUnitId})`);
809
+ ref.makeUnitRender();
810
+ }
811
+ getRenderUnitInfo(leaf = this.leaf) {
812
+ // leaf 在低代码组件中存在 mock 的情况,退出最小渲染单元判断
813
+ if (!leaf || typeof leaf.isRoot !== 'function') {
814
+ return;
815
+ }
816
+ if (leaf.isRoot) {
817
+ this.renderUnitInfo = {
818
+ singleRender: true,
819
+ ...(this.renderUnitInfo || {})
820
+ };
821
+ }
822
+ if (leaf.componentMeta.isMinimalRenderUnit) {
823
+ this.renderUnitInfo = {
824
+ minimalUnitId: leaf.id,
825
+ minimalUnitName: leaf.componentName,
826
+ singleRender: false
827
+ };
828
+ }
829
+ if (leaf.hasLoop()) {
830
+ // 含有循环配置的元素,父元素是最小渲染单元
831
+ this.renderUnitInfo = {
832
+ minimalUnitId: leaf?.parent?.id,
833
+ minimalUnitName: leaf?.parent?.componentName,
834
+ singleRender: false
835
+ };
836
+ }
837
+ if (leaf.parent) {
838
+ this.getRenderUnitInfo(leaf.parent);
839
+ }
840
+ }
841
+ UNSAFE_componentWillReceiveProps(nextProps) {
842
+ const {
843
+ componentId
844
+ } = nextProps;
845
+ if (nextProps.__tag === this.props.__tag) {
846
+ return null;
847
+ }
848
+ const _leaf = getNode?.(componentId);
849
+ if (_leaf && this.curEventLeaf && _leaf !== this.curEventLeaf) {
850
+ this.disposeFunctions.forEach(fn => fn());
851
+ this.disposeFunctions = [];
852
+ this.initOnChildrenChangeEvent(_leaf);
853
+ this.initOnPropsChangeEvent(_leaf);
854
+ this.initOnVisibleChangeEvent(_leaf);
855
+ this.curEventLeaf = _leaf;
856
+ }
857
+ const {
858
+ visible,
859
+ ...resetState
860
+ } = this.getDefaultState(nextProps);
861
+ this.setState(resetState);
862
+ }
863
+
864
+ /** 监听参数变化 */
865
+ initOnPropsChangeEvent(leaf = this.leaf) {
866
+ // const handlePropsChange = debounce((propChangeInfo: PropChangeInfo) => {
867
+ const handlePropsChange = debounce(propChangeInfo => {
868
+ const {
869
+ key,
870
+ newValue = null
871
+ } = propChangeInfo;
872
+ const node = leaf;
873
+ if (key === '___condition___') {
874
+ const {
875
+ condition = true
876
+ } = this.leaf?.export(TRANSFORM_STAGE.RENDER) || {};
877
+ const conditionValue = __parseData?.(condition, scope);
878
+ logger.log(`key is ___condition___, change condition value to [${condition}]`);
879
+ // 条件表达式改变
880
+ this.setState({
881
+ condition: conditionValue
882
+ });
883
+ return;
884
+ }
885
+
886
+ // 如果循坏条件变化,从根节点重新渲染
887
+ // 目前多层循坏无法判断需要从哪一层开始渲染,故先粗暴解决
888
+ if (key === '___loop___') {
889
+ logger.log('key is ___loop___, render a page!');
890
+ container?.rerender();
891
+ // 由于 scope 变化,需要清空缓存,使用新的 scope
892
+ cache.component.delete(componentCacheId);
893
+ return;
894
+ }
895
+ this.beforeRender(RerenderType.PropsChanged);
896
+ const {
897
+ state
898
+ } = this;
899
+ const {
900
+ nodeCacheProps
901
+ } = state;
902
+ const nodeProps = getProps(node?.export?.(TRANSFORM_STAGE.RENDER), scope, Comp, componentInfo);
903
+ if (key && !(key in nodeProps) && key in this.props) {
904
+ // 当 key 在 this.props 中时,且不存在在计算值中,需要用 newValue 覆盖掉 this.props 的取值
905
+ nodeCacheProps[key] = newValue;
906
+ }
907
+ logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onPropsChange!`, nodeProps, nodeCacheProps, key, newValue);
908
+ this.setState('children' in nodeProps ? {
909
+ nodeChildren: nodeProps.children,
910
+ nodeProps,
911
+ childrenInState: true,
912
+ nodeCacheProps
913
+ } : {
914
+ nodeProps,
915
+ nodeCacheProps
916
+ });
917
+ this.judgeMiniUnitRender();
918
+ });
919
+ // const dispose = leaf?.onPropChange?.((propChangeInfo: IPublicTypePropChangeOptions) => {
920
+ const dispose = leaf?.onPropChange?.(propChangeInfo => {
921
+ if (!this.autoRepaintNode) {
922
+ return;
923
+ }
924
+ handlePropsChange(propChangeInfo);
925
+ });
926
+ dispose && this.disposeFunctions.push(dispose);
927
+ }
928
+
929
+ /**
930
+ * 监听显隐变化
931
+ */
932
+ initOnVisibleChangeEvent(leaf = this.leaf) {
933
+ const dispose = leaf?.onVisibleChange?.(flag => {
934
+ if (!this.autoRepaintNode) {
935
+ return;
936
+ }
937
+ if (this.state.visible === flag) {
938
+ return;
939
+ }
940
+ logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onVisibleChange(${flag}) event`);
941
+ this.beforeRender(RerenderType.VisibleChanged);
942
+ this.setState({
943
+ visible: flag
944
+ });
945
+ this.judgeMiniUnitRender();
946
+ });
947
+ dispose && this.disposeFunctions.push(dispose);
948
+ }
949
+
950
+ /**
951
+ * 监听子元素变化(拖拽,删除...)
952
+ */
953
+ initOnChildrenChangeEvent(leaf = this.leaf) {
954
+ const dispose = leaf?.onChildrenChange?.(param => {
955
+ if (!this.autoRepaintNode) {
956
+ return;
957
+ }
958
+ const {
959
+ type,
960
+ node
961
+ } = param || {};
962
+ this.beforeRender(`${RerenderType.ChildChanged}-${type}`, node);
963
+ // TODO: 缓存同级其他元素的 children。
964
+ // 缓存二级 children Next 查询筛选组件有问题
965
+ // 缓存一级 children Next Tab 组件有问题
966
+ const nextChild = getChildren(leaf?.export?.(TRANSFORM_STAGE.RENDER), scope, Comp);
967
+ logger.log(`${schema.componentName}[${this.leaf?.id}] component trigger onChildrenChange event`, nextChild);
968
+ this.setState({
969
+ nodeChildren: nextChild,
970
+ childrenInState: true
971
+ });
972
+ this.judgeMiniUnitRender();
973
+ });
974
+ dispose && this.disposeFunctions.push(dispose);
975
+ }
976
+ componentWillUnmount() {
977
+ this.disposeFunctions.forEach(fn => fn());
978
+ }
979
+ get hasChildren() {
980
+ if (!this.state.childrenInState) {
981
+ return 'children' in this.props;
982
+ }
983
+ return true;
984
+ }
985
+ get children() {
986
+ if (this.state.childrenInState) {
987
+ return this.state.nodeChildren;
988
+ }
989
+ if (this.props.children && !Array.isArray(this.props.children)) {
990
+ return [this.props.children];
991
+ }
992
+ if (this.props.children && this.props.children.length) {
993
+ return this.props.children;
994
+ }
995
+ return this.props.children;
996
+ }
997
+ get leaf() {
998
+ // if (this.props._leaf?.isMock) {
999
+ // // 低代码组件作为一个整体更新,其内部的组件不需要监听相关事件
1000
+ // return undefined
1001
+ // }
1002
+
1003
+ return getNode?.(componentCacheId);
1004
+ }
1005
+ render() {
1006
+ if (!this.state.visible || !this.state.condition) {
1007
+ return null;
1008
+ }
1009
+ const {
1010
+ forwardRef,
1011
+ ...rest
1012
+ } = this.props;
1013
+ const compProps = {
1014
+ ...rest,
1015
+ ...(this.state.nodeCacheProps || {}),
1016
+ ...(this.state.nodeProps || {}),
1017
+ children: [],
1018
+ __id: this.leaf?.id,
1019
+ ref: forwardRef
1020
+ };
1021
+ delete compProps.__inner__;
1022
+ if (this.hasChildren) {
1023
+ return engine.createElement(Comp, compProps, this.children);
1024
+ }
1025
+ return engine.createElement(Comp, compProps);
1026
+ }
1027
+ }
1028
+ const LeafWrapper = createForwardRefHocElement(LeafHoc, Comp);
1029
+ cache.component.set(componentCacheId, {
1030
+ LeafWrapper,
1031
+ Comp
1032
+ });
1033
+ return LeafWrapper;
1034
+ };
1035
+
1036
+ /**
1037
+ * execute method in schema.lifeCycles with context
1038
+ */
1039
+ function executeLifeCycleMethod(context, schema, method, args, thisRequiredInJSE) {
1040
+ if (!context || !isSchema(schema) || !method) {
1041
+ return;
1042
+ }
1043
+ const lifeCycleMethods = getValue(schema, 'lifeCycles', {});
1044
+ let fn = lifeCycleMethods[method];
1045
+ if (!fn) {
1046
+ return;
1047
+ }
1048
+
1049
+ // TODO: cache
1050
+ if (isJSExpression(fn) || isJSFunction(fn)) {
1051
+ fn = thisRequiredInJSE ? parseThisRequiredExpression(fn, context) : parseExpression(fn, context);
1052
+ }
1053
+ if (typeof fn !== 'function') {
1054
+ logger.error(`生命周期${method}类型不符`, fn);
1055
+ return;
1056
+ }
1057
+ try {
1058
+ return fn.apply(context, args);
1059
+ } catch (e) {
1060
+ logger.error(`[${schema.componentName}]生命周期${method}出错`, e);
1061
+ }
1062
+ }
1063
+
1064
+ /**
1065
+ * get children from a node schema
1066
+ */
1067
+ function getSchemaChildren(schema) {
1068
+ if (!schema) {
1069
+ return;
1070
+ }
1071
+ return schema.children;
1072
+ }
1073
+ function baseRendererFactory() {
1074
+ const {
1075
+ BaseRenderer: customBaseRenderer
1076
+ } = adapter.getRenderers();
1077
+ if (customBaseRenderer) {
1078
+ return customBaseRenderer;
1079
+ }
1080
+ const DEFAULT_LOOP_ARG_ITEM = 'item';
1081
+ const DEFAULT_LOOP_ARG_INDEX = 'index';
1082
+ // const scopeIdx = 0
1083
+
1084
+ return class BaseRenderer extends Component {
1085
+ static displayName = 'BaseRenderer';
1086
+ static defaultProps = {
1087
+ __schema: {}
1088
+ };
1089
+ static contextType = RendererContext;
1090
+ dataSourceMap = {};
1091
+ __namespace = 'base';
1092
+ __compScopes = {};
1093
+ __instanceMap = {};
1094
+ __dataHelper;
1095
+
1096
+ /**
1097
+ * keep track of customMethods added to this context
1098
+ *
1099
+ * @type {any}
1100
+ */
1101
+ __customMethodsList = [];
1102
+ __parseExpression;
1103
+ __ref;
1104
+
1105
+ /**
1106
+ * reference of style element contains schema.css
1107
+ *
1108
+ * @type {any}
1109
+ */
1110
+ __styleElement;
1111
+ constructor(props) {
1112
+ super(props);
1113
+ this.__parseExpression = (str, self) => {
1114
+ return parseExpression({
1115
+ str,
1116
+ self,
1117
+ thisRequired: props?.thisRequiredInJSE,
1118
+ logScope: props.componentName
1119
+ });
1120
+ };
1121
+ this.__beforeInit(props);
1122
+ this.__init(props);
1123
+ this.__afterInit(props);
1124
+ logger.log(`constructor - ${props?.__schema?.fileName}`);
1125
+ }
1126
+ __beforeInit(props) {}
1127
+ __init(props) {
1128
+ this.__compScopes = {};
1129
+ this.__instanceMap = {};
1130
+ this.__bindCustomMethods(props);
1131
+ }
1132
+ __afterInit(props) {}
1133
+ static getDerivedStateFromProps(props, state) {
1134
+ const result = executeLifeCycleMethod(this, props?.__schema, 'getDerivedStateFromProps', [props, state], props.thisRequiredInJSE);
1135
+ return result === undefined ? null : result;
1136
+ }
1137
+ async getSnapshotBeforeUpdate(...args) {
1138
+ this.__executeLifeCycleMethod('getSnapshotBeforeUpdate', args);
1139
+ logger.log(`getSnapshotBeforeUpdate - ${this.props?.__schema?.componentName}`);
1140
+ }
1141
+ async componentDidMount(...args) {
1142
+ this.reloadDataSource();
1143
+ this.__executeLifeCycleMethod('componentDidMount', args);
1144
+ logger.log(`componentDidMount - ${this.props?.__schema?.componentName}`);
1145
+ }
1146
+ async componentDidUpdate(...args) {
1147
+ this.__executeLifeCycleMethod('componentDidUpdate', args);
1148
+ logger.log(`componentDidUpdate - ${this.props.__schema.componentName}`);
1149
+ }
1150
+ async componentWillUnmount(...args) {
1151
+ this.__executeLifeCycleMethod('componentWillUnmount', args);
1152
+ logger.log(`componentWillUnmount - ${this.props?.__schema?.componentName}`);
1153
+ }
1154
+ async componentDidCatch(...args) {
1155
+ this.__executeLifeCycleMethod('componentDidCatch', args);
1156
+ logger.warn(args);
1157
+ }
1158
+ reloadDataSource = () => new Promise((resolve, reject) => {
1159
+ logger.log('reload data source');
1160
+ if (!this.__dataHelper) {
1161
+ return resolve({});
1162
+ }
1163
+ this.__dataHelper.getInitData().then(res => {
1164
+ if (isEmpty(res)) {
1165
+ this.forceUpdate();
1166
+ return resolve({});
1167
+ }
1168
+ this.setState(res, resolve);
1169
+ }).catch(err => {
1170
+ reject(err);
1171
+ });
1172
+ });
1173
+ shouldComponentUpdate() {
1174
+ if (this.props.getSchemaChangedSymbol?.() && this.props.__container?.rerender) {
1175
+ this.props.__container?.rerender();
1176
+ return false;
1177
+ }
1178
+ return true;
1179
+ }
1180
+ forceUpdate() {
1181
+ if (this.shouldComponentUpdate()) {
1182
+ super.forceUpdate();
1183
+ }
1184
+ }
1185
+
1186
+ /**
1187
+ * execute method in schema.lifeCycles
1188
+ */
1189
+ __executeLifeCycleMethod = (method, args) => {
1190
+ executeLifeCycleMethod(this, this.props.__schema, method, args, this.props.thisRequiredInJSE);
1191
+ };
1192
+
1193
+ /**
1194
+ * this method is for legacy purpose only, which used _ prefix instead of __ as private for some historical reasons
1195
+ */
1196
+ __getComponentView = () => {
1197
+ const {
1198
+ __components,
1199
+ __schema
1200
+ } = this.props;
1201
+ if (!__components) {
1202
+ return;
1203
+ }
1204
+ return __components[__schema.componentName];
1205
+ };
1206
+ __bindCustomMethods = props => {
1207
+ const {
1208
+ __schema
1209
+ } = props;
1210
+ const customMethodsList = Object.keys(__schema.methods || {}) || [];
1211
+ (this.__customMethodsList || []).forEach(item => {
1212
+ if (!customMethodsList.includes(item)) {
1213
+ delete this[item];
1214
+ }
1215
+ });
1216
+ this.__customMethodsList = customMethodsList;
1217
+ forEach(__schema.methods, (val, key) => {
1218
+ let value = val;
1219
+ if (isJSExpression(value) || isJSFunction(value)) {
1220
+ value = this.__parseExpression(value, this);
1221
+ }
1222
+ if (typeof value !== 'function') {
1223
+ logger.error(`custom method ${key} can not be parsed to a valid function`, value);
1224
+ return;
1225
+ }
1226
+ this[key] = value.bind(this);
1227
+ });
1228
+ };
1229
+ __generateCtx = ctx => {
1230
+ const {
1231
+ pageContext,
1232
+ compContext
1233
+ } = this.context;
1234
+ const obj = {
1235
+ page: pageContext,
1236
+ component: compContext,
1237
+ ...ctx
1238
+ };
1239
+ forEach(obj, (val, key) => {
1240
+ this[key] = val;
1241
+ });
1242
+ };
1243
+ __parseData = (data, ctx) => {
1244
+ const {
1245
+ __ctx,
1246
+ thisRequiredInJSE,
1247
+ componentName
1248
+ } = this.props;
1249
+ return parseData(data, ctx || __ctx || this, {
1250
+ thisRequiredInJSE,
1251
+ logScope: componentName
1252
+ });
1253
+ };
1254
+ __initDataSource = props => {
1255
+ if (!props) {
1256
+ return;
1257
+ }
1258
+ // TODO: 数据源引擎方案
1259
+ // const schema = props.__schema || {}
1260
+ // const defaultDataSource: DataSource = {
1261
+ // list: [],
1262
+ // }
1263
+ // const dataSource = schema.dataSource || defaultDataSource
1264
+ // // requestHandlersMap 存在才走数据源引擎方案
1265
+ // // TODO: 下面if else 抽成独立函数
1266
+ // const useDataSourceEngine = !!props.__appHelper?.requestHandlersMap
1267
+ // if (useDataSourceEngine) {
1268
+ // this.__dataHelper = {
1269
+ // updateConfig: (updateDataSource: any) => {
1270
+ // const { dataSourceMap, reloadDataSource } = createDataSourceEngine(
1271
+ // updateDataSource ?? {},
1272
+ // this,
1273
+ // props.__appHelper.requestHandlersMap
1274
+ // ? { requestHandlersMap: props.__appHelper.requestHandlersMap }
1275
+ // : undefined,
1276
+ // )
1277
+
1278
+ // this.reloadDataSource = () =>
1279
+ // new Promise(resolve => {
1280
+ // logger.log('reload data source')
1281
+ // reloadDataSource().then(() => {
1282
+ // resolve({})
1283
+ // })
1284
+ // })
1285
+ // return dataSourceMap
1286
+ // },
1287
+ // }
1288
+ // this.dataSourceMap = this.__dataHelper.updateConfig(dataSource)
1289
+ // } else {
1290
+ // const appHelper = props.__appHelper
1291
+ // this.__dataHelper = new DataHelper(this, dataSource, appHelper, (config: any) => this.__parseData(config))
1292
+ // this.dataSourceMap = this.__dataHelper.dataSourceMap
1293
+ // this.reloadDataSource = () =>
1294
+ // new Promise((resolve, reject) => {
1295
+ // logger.log('reload data source')
1296
+ // if (!this.__dataHelper) {
1297
+ // return resolve({})
1298
+ // }
1299
+ // this.__dataHelper
1300
+ // .getInitData()
1301
+ // .then((res: any) => {
1302
+ // if (isEmpty(res)) {
1303
+ // return resolve({})
1304
+ // }
1305
+ // this.setState(res, resolve as () => void)
1306
+ // })
1307
+ // .catch((err: Error) => {
1308
+ // reject(err)
1309
+ // })
1310
+ // })
1311
+ // }
1312
+ };
1313
+
1314
+ /**
1315
+ * write props.__schema.css to document as a style element,
1316
+ * which will be added once and only once.
1317
+ * @PRIVATE
1318
+ */
1319
+ __writeCss = props => {
1320
+ const css = getValue(props.__schema, 'css', '');
1321
+ logger.log('create this.styleElement with css', css);
1322
+ let style = this.__styleElement;
1323
+ if (!this.__styleElement) {
1324
+ style = document.createElement('style');
1325
+ style.type = 'text/css';
1326
+ style.setAttribute('from', 'style-sheet');
1327
+ const head = document.head || document.getElementsByTagName('head')[0];
1328
+ head.appendChild(style);
1329
+ this.__styleElement = style;
1330
+ logger.log('this.styleElement is created', this.__styleElement);
1331
+ }
1332
+ if (style.innerHTML === css) {
1333
+ return;
1334
+ }
1335
+ style.innerHTML = css;
1336
+ };
1337
+ __render = () => {
1338
+ const schema = this.props.__schema;
1339
+ this.__executeLifeCycleMethod('render');
1340
+ this.__writeCss(this.props);
1341
+ const {
1342
+ engine
1343
+ } = this.context;
1344
+ if (engine) {
1345
+ engine.props.onCompGetCtx(schema, this);
1346
+ // 画布场景才需要每次渲染bind自定义方法
1347
+ if (this.__designModeIsDesign) {
1348
+ this.__bindCustomMethods(this.props);
1349
+ this.dataSourceMap = this.__dataHelper?.updateConfig(schema.dataSource);
1350
+ }
1351
+ }
1352
+ };
1353
+ __getRef = ref => {
1354
+ const {
1355
+ engine
1356
+ } = this.context;
1357
+ const {
1358
+ __schema
1359
+ } = this.props;
1360
+ // ref && engine?.props?.onCompGetRef(__schema, ref)
1361
+ // TODO: 只在 ref 存在执行,会影响 documentInstance 的卸载
1362
+ engine?.props?.onCompGetRef(__schema, ref);
1363
+ this.__ref = ref;
1364
+ };
1365
+ __createDom = () => {
1366
+ const {
1367
+ __schema,
1368
+ __ctx
1369
+ } = this.props;
1370
+ // merge defaultProps
1371
+ const scopeProps = {
1372
+ ...__schema.defaultProps,
1373
+ ...this.props
1374
+ };
1375
+ const scope = {
1376
+ props: scopeProps
1377
+ };
1378
+ scope.__proto__ = __ctx || this;
1379
+ const _children = getSchemaChildren(__schema);
1380
+ const Comp = this.__getComponentView();
1381
+ if (!Comp) {
1382
+ logger.log(`${__schema.componentName} is invalid!`);
1383
+ }
1384
+ const parentNodeInfo = {
1385
+ schema: __schema,
1386
+ Comp: this.__getHOCWrappedComponent(Comp, {
1387
+ schema: __schema,
1388
+ scope
1389
+ })
1390
+ };
1391
+ return this.__createVirtualDom(_children, scope, parentNodeInfo);
1392
+ };
1393
+
1394
+ /**
1395
+ * 将模型结构转换成react Element
1396
+ * @param originalSchema schema
1397
+ * @param originalScope scope
1398
+ * @param parentInfo 父组件的信息,包含schema和Comp
1399
+ * @param idx 为循环渲染的循环Index
1400
+ */
1401
+ __createVirtualDom = (originalSchema, originalScope, parentInfo, idx = '') => {
1402
+ if (originalSchema === null || originalSchema === undefined) {
1403
+ return null;
1404
+ }
1405
+ const scope = originalScope;
1406
+ const schema = originalSchema;
1407
+ const {
1408
+ engine
1409
+ } = this.context || {};
1410
+ if (!engine) {
1411
+ logger.log('this.context.engine is invalid!');
1412
+ return null;
1413
+ }
1414
+ try {
1415
+ const {
1416
+ __appHelper: appHelper,
1417
+ __components: components = {}
1418
+ } = this.props || {};
1419
+ if (isJSExpression(schema)) {
1420
+ return this.__parseExpression(schema, scope);
1421
+ }
1422
+ if (typeof schema === 'string') {
1423
+ return schema;
1424
+ }
1425
+ if (typeof schema === 'number' || typeof schema === 'boolean') {
1426
+ return String(schema);
1427
+ }
1428
+ if (Array.isArray(schema)) {
1429
+ if (schema.length === 1) {
1430
+ return this.__createVirtualDom(schema[0], scope, parentInfo);
1431
+ }
1432
+ return schema.map((item, idy) => this.__createVirtualDom(item, scope, parentInfo, item?.__ctx?.lceKey ? '' : String(idy)));
1433
+ }
1434
+ if (schema.$$typeof) {
1435
+ return schema;
1436
+ }
1437
+ if (!schema.componentName) {
1438
+ logger.error('The componentName in the schema is invalid, please check the schema: ', schema);
1439
+ return;
1440
+ }
1441
+ if (!isSchema(schema)) {
1442
+ return null;
1443
+ }
1444
+ let Comp = components[schema.componentName] || this.props.__container?.components?.[schema.componentName];
1445
+
1446
+ // 容器类组件的上下文通过props传递,避免context传递带来的嵌套问题
1447
+ const otherProps = isSchema(schema) ? {
1448
+ __schema: schema,
1449
+ __appHelper: appHelper,
1450
+ __components: components
1451
+ } : {};
1452
+ if (!Comp) {
1453
+ logger.error(`${schema.componentName} component is not found in components list! component list is:`, components || this.props.__container?.components);
1454
+ return engine.createElement(engine.getNotFoundComponent(), {
1455
+ componentName: schema.componentName,
1456
+ componentId: schema.id,
1457
+ enableStrictNotFoundMode: engine.props.enableStrictNotFoundMode,
1458
+ ref: ref => {
1459
+ ref && engine.props?.onCompGetRef(schema, ref);
1460
+ }
1461
+ }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp));
1462
+ }
1463
+ if (schema.loop != null) {
1464
+ const loop = this.__parseData(schema.loop, scope);
1465
+ if (Array.isArray(loop) && loop.length === 0) return null;
1466
+ const useLoop = isUseLoop(loop, this.__designModeIsDesign);
1467
+ if (useLoop) {
1468
+ return this.__createLoopVirtualDom({
1469
+ ...schema,
1470
+ loop
1471
+ }, scope, parentInfo, idx);
1472
+ }
1473
+ }
1474
+ const condition = schema.condition == null ? true : this.__parseData(schema.condition, scope);
1475
+
1476
+ // DesignMode 为 design 情况下,需要进入 leaf Hoc,进行相关事件注册
1477
+ const displayInHook = this.__designModeIsDesign;
1478
+ if (!condition && !displayInHook) {
1479
+ return null;
1480
+ }
1481
+
1482
+ // TODO: scope
1483
+ // let scopeKey = ''
1484
+ // // 判断组件是否需要生成scope,且只生成一次,挂在this.__compScopes上
1485
+ // if (Comp.generateScope) {
1486
+ // const key = this.__parseExpression(schema.props?.key, scope)
1487
+ // if (key) {
1488
+ // // 如果组件自己设置key则使用组件自己的key
1489
+ // scopeKey = key
1490
+ // } else if (schema.__ctx) {
1491
+ // // 需要判断循环的情况
1492
+ // scopeKey = schema.__ctx.lceKey + (idx !== undefined ? `_${idx}` : '')
1493
+ // } else {
1494
+ // // 在生产环境schema没有__ctx上下文,需要手动生成一个lceKey
1495
+ // schema.__ctx = {
1496
+ // lceKey: `lce${++scopeIdx}`,
1497
+ // }
1498
+ // scopeKey = schema.__ctx.lceKey
1499
+ // }
1500
+ // if (!this.__compScopes[scopeKey]) {
1501
+ // this.__compScopes[scopeKey] = Comp.generateScope(this, schema)
1502
+ // }
1503
+ // }
1504
+ // // 如果组件有设置scope,需要为组件生成一个新的scope上下文
1505
+ // if (scopeKey && this.__compScopes[scopeKey]) {
1506
+ // const compSelf = { ...this.__compScopes[scopeKey] }
1507
+ // compSelf.__proto__ = scope
1508
+ // scope = compSelf
1509
+ // }
1510
+
1511
+ if (engine.props?.designMode) {
1512
+ otherProps.__designMode = engine.props.designMode;
1513
+ }
1514
+ if (this.__designModeIsDesign) {
1515
+ otherProps.__tag = Math.random();
1516
+ }
1517
+ const componentInfo = {};
1518
+ const props = this.__getComponentProps(schema, scope, Comp, {
1519
+ ...componentInfo,
1520
+ props: transformArrayToMap(componentInfo.props, 'name')
1521
+ }) || {};
1522
+ Comp = this.__getHOCWrappedComponent(Comp, {
1523
+ schema,
1524
+ componentInfo,
1525
+ baseRenderer: this,
1526
+ scope
1527
+ });
1528
+ otherProps.ref = ref => {
1529
+ this.$(schema.id || props.ref, ref); // 收集ref
1530
+ const refProps = props.ref;
1531
+ if (refProps && typeof refProps === 'string') {
1532
+ this[refProps] = ref;
1533
+ }
1534
+ ref && engine.props?.onCompGetRef(schema, ref);
1535
+ };
1536
+
1537
+ // scope需要传入到组件上
1538
+ // if (scopeKey && this.__compScopes[scopeKey]) {
1539
+ // props.__scope = this.__compScopes[scopeKey]
1540
+ // }
1541
+ if (schema?.__ctx?.lceKey) {
1542
+ if (!isSchema(schema)) {
1543
+ engine.props?.onCompGetCtx(schema, scope);
1544
+ }
1545
+ props.key = props.key || `${schema.__ctx.lceKey}_${schema.__ctx.idx || 0}_${idx !== undefined ? idx : ''}`;
1546
+ } else if ((typeof idx === 'number' || typeof idx === 'string') && !props.key) {
1547
+ // 仅当循环场景走这里
1548
+ props.key = idx;
1549
+ }
1550
+ props.__id = schema.id;
1551
+ if (!props.key) {
1552
+ props.key = props.__id;
1553
+ }
1554
+ return engine.createElement(Comp, {
1555
+ ...props,
1556
+ ...otherProps,
1557
+ // TODO: 看看这里需要怎么处理简洁
1558
+ __inner__: {
1559
+ hidden: schema.hidden,
1560
+ condition
1561
+ }
1562
+ }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp, condition));
1563
+ } catch (e) {
1564
+ return engine.createElement(engine.getFaultComponent(), {
1565
+ error: e,
1566
+ schema,
1567
+ self: scope,
1568
+ parentInfo,
1569
+ idx
1570
+ });
1571
+ }
1572
+ };
1573
+
1574
+ /**
1575
+ * get Component HOCs
1576
+ *
1577
+ * @readonly
1578
+ * @type {ComponentConstruct[]}
1579
+ */
1580
+ get __componentHOCs() {
1581
+ if (this.__designModeIsDesign) {
1582
+ return [leafWrapper, compWrapper];
1583
+ }
1584
+ return [compWrapper];
1585
+ }
1586
+ __getSchemaChildrenVirtualDom = (schema, scope, Comp, condition = true) => {
1587
+ let children = condition ? getSchemaChildren(schema) : null;
1588
+ const result = [];
1589
+ if (children) {
1590
+ if (!Array.isArray(children)) {
1591
+ children = [children];
1592
+ }
1593
+ children.forEach(child => {
1594
+ const childVirtualDom = this.__createVirtualDom(isJSExpression(child) ? this.__parseExpression(child, scope) : child, scope, {
1595
+ schema,
1596
+ Comp
1597
+ });
1598
+ result.push(childVirtualDom);
1599
+ });
1600
+ }
1601
+ if (result && result.length > 0) {
1602
+ return result;
1603
+ }
1604
+ return null;
1605
+ };
1606
+ __getComponentProps = (schema, scope, Comp, componentInfo) => {
1607
+ if (!schema) {
1608
+ return {};
1609
+ }
1610
+ return this.__parseProps(schema?.props, scope, '', {
1611
+ schema,
1612
+ Comp,
1613
+ componentInfo: {
1614
+ ...(componentInfo || {}),
1615
+ props: transformArrayToMap((componentInfo || {}).props, 'name')
1616
+ }
1617
+ }) || {};
1618
+ };
1619
+ __createLoopVirtualDom = (schema, scope, parentInfo, idx) => {
1620
+ // TODO
1621
+ // if (isSchema(schema)) {
1622
+ // logger.warn('file type not support Loop')
1623
+ // return null
1624
+ // }
1625
+ if (!Array.isArray(schema.loop)) {
1626
+ return null;
1627
+ }
1628
+ const itemArg = schema.loopArgs && schema.loopArgs[0] || DEFAULT_LOOP_ARG_ITEM;
1629
+ const indexArg = schema.loopArgs && schema.loopArgs[1] || DEFAULT_LOOP_ARG_INDEX;
1630
+ const {
1631
+ loop
1632
+ } = schema;
1633
+ return loop.map((item, i) => {
1634
+ const loopSelf = {
1635
+ [itemArg]: item,
1636
+ [indexArg]: i
1637
+ };
1638
+ loopSelf.__proto__ = scope;
1639
+ return this.__createVirtualDom({
1640
+ ...schema,
1641
+ loop: undefined,
1642
+ props: {
1643
+ ...schema.props,
1644
+ // 循环下 key 不能为常量,这样会造成 key 值重复,渲染异常
1645
+ key: isJSExpression(schema.props?.key) ? schema.props?.key : null
1646
+ }
1647
+ }, loopSelf, parentInfo, idx ? `${idx}_${i}` : i);
1648
+ });
1649
+ };
1650
+ get __designModeIsDesign() {
1651
+ const {
1652
+ engine
1653
+ } = this.context || {};
1654
+ return engine?.props?.designMode === 'design';
1655
+ }
1656
+ __parseProps = (originalProps, scope, path, info) => {
1657
+ let props = originalProps;
1658
+ const {
1659
+ schema,
1660
+ Comp,
1661
+ componentInfo = {}
1662
+ } = info;
1663
+ const propInfo = getValue(componentInfo.props, path);
1664
+ // FIXME: 将这行逻辑外置,解耦,线上环境不要验证参数,调试环境可以有,通过传参自定义
1665
+ const propType = propInfo?.extra?.propType;
1666
+ const checkProps = value => {
1667
+ if (!propType) {
1668
+ return value;
1669
+ }
1670
+ return checkPropTypes(value, path, propType, componentInfo.name) ? value : undefined;
1671
+ };
1672
+ const parseReactNode = (data, params) => {
1673
+ if (isEmpty(params)) {
1674
+ const virtualDom = this.__createVirtualDom(data, scope, {
1675
+ schema,
1676
+ Comp
1677
+ });
1678
+ return checkProps(virtualDom);
1679
+ }
1680
+ return checkProps((...argValues) => {
1681
+ const args = {};
1682
+ if (Array.isArray(params) && params.length) {
1683
+ params.forEach((item, idx) => {
1684
+ if (typeof item === 'string') {
1685
+ args[item] = argValues[idx];
1686
+ } else if (item && typeof item === 'object') {
1687
+ args[item.name] = argValues[idx];
1688
+ }
1689
+ });
1690
+ }
1691
+ args.__proto__ = scope;
1692
+ return scope.__createVirtualDom(data, args, {
1693
+ schema,
1694
+ Comp
1695
+ });
1696
+ });
1697
+ };
1698
+ if (isJSExpression(props)) {
1699
+ props = this.__parseExpression(props, scope);
1700
+ // 只有当变量解析出来为模型结构的时候才会继续解析
1701
+ if (!isSchema(props)) {
1702
+ return checkProps(props);
1703
+ }
1704
+ }
1705
+ if (isJSFunction(props)) {
1706
+ props = transformStringToFunction(props.value);
1707
+ }
1708
+
1709
+ // 兼容通过componentInfo判断的情况
1710
+ if (isSchema(props)) {
1711
+ const isReactNodeFunction = !!(propInfo?.type === 'ReactNode' && propInfo?.props?.type === 'function');
1712
+ const isMixinReactNodeFunction = !!(propInfo?.type === 'Mixin' && propInfo?.props?.types?.indexOf('ReactNode') > -1 && propInfo?.props?.reactNodeProps?.type === 'function');
1713
+ let params = null;
1714
+ if (isReactNodeFunction) {
1715
+ params = propInfo?.props?.params;
1716
+ } else if (isMixinReactNodeFunction) {
1717
+ params = propInfo?.props?.reactNodeProps?.params;
1718
+ }
1719
+ return parseReactNode(props, params);
1720
+ }
1721
+ if (Array.isArray(props)) {
1722
+ return checkProps(props.map((item, idx) => this.__parseProps(item, scope, path ? `${path}.${idx}` : `${idx}`, info)));
1723
+ }
1724
+ if (typeof props === 'function') {
1725
+ return checkProps(props.bind(scope));
1726
+ }
1727
+ if (props && typeof props === 'object') {
1728
+ if (props.$$typeof) {
1729
+ return checkProps(props);
1730
+ }
1731
+ const res = {};
1732
+ forEach(props, (val, key) => {
1733
+ if (key.startsWith('__')) {
1734
+ res[key] = val;
1735
+ return;
1736
+ }
1737
+ res[key] = this.__parseProps(val, scope, path ? `${path}.${key}` : key, info);
1738
+ });
1739
+ return checkProps(res);
1740
+ }
1741
+ return checkProps(props);
1742
+ };
1743
+ $(id, instance) {
1744
+ this.__instanceMap = this.__instanceMap || {};
1745
+ if (!id || typeof id !== 'string') {
1746
+ return this.__instanceMap;
1747
+ }
1748
+ if (instance) {
1749
+ this.__instanceMap[id] = instance;
1750
+ }
1751
+ return this.__instanceMap[id];
1752
+ }
1753
+ __renderContextProvider = (customProps, children) => {
1754
+ return /*#__PURE__*/React.createElement(RendererContext.Provider, {
1755
+ value: {
1756
+ ...this.context,
1757
+ blockContext: this,
1758
+ ...(customProps || {})
1759
+ }
1760
+ }, children || this.__createDom());
1761
+ };
1762
+ __renderContextConsumer = children => {
1763
+ return /*#__PURE__*/React.createElement(RendererContext.Consumer, null, children);
1764
+ };
1765
+ __getHOCWrappedComponent(OriginalComp, info) {
1766
+ let Comp = OriginalComp;
1767
+ this.__componentHOCs.forEach(ComponentConstruct => {
1768
+ Comp = ComponentConstruct(Comp, {
1769
+ componentInfo: {},
1770
+ baseRenderer: this,
1771
+ ...info
1772
+ });
1773
+ });
1774
+ return Comp;
1775
+ }
1776
+ __renderComp(OriginalComp, ctxProps) {
1777
+ let Comp = OriginalComp;
1778
+ const {
1779
+ __schema,
1780
+ __ctx
1781
+ } = this.props;
1782
+ const scope = {};
1783
+ scope.__proto__ = __ctx || this;
1784
+ Comp = this.__getHOCWrappedComponent(Comp, {
1785
+ schema: __schema,
1786
+ scope
1787
+ });
1788
+ const data = this.__parseProps(__schema?.props, scope, '', {
1789
+ schema: __schema,
1790
+ Comp,
1791
+ componentInfo: {}
1792
+ });
1793
+ const {
1794
+ className
1795
+ } = data;
1796
+ const otherProps = {};
1797
+ const {
1798
+ engine
1799
+ } = this.context || {};
1800
+ if (!engine) {
1801
+ return null;
1802
+ }
1803
+ if (this.__designModeIsDesign) {
1804
+ otherProps.__tag = Math.random();
1805
+ }
1806
+ const child = engine.createElement(Comp, {
1807
+ ...data,
1808
+ ...this.props,
1809
+ ref: this.__getRef,
1810
+ className: classnames(__schema?.fileName && getFileCssName(__schema.fileName), className, this.props.className),
1811
+ __id: __schema?.id,
1812
+ ...otherProps
1813
+ }, this.__createDom());
1814
+ return this.__renderContextProvider(ctxProps, child);
1815
+ }
1816
+ __renderContent(children) {
1817
+ const {
1818
+ __schema
1819
+ } = this.props;
1820
+ const parsedProps = this.__parseData(__schema.props);
1821
+ const className = classnames(`lce-${this.__namespace}`, __schema?.fileName && getFileCssName(__schema.fileName), parsedProps.className, this.props.className);
1822
+ const style = {
1823
+ ...(parsedProps.style || {}),
1824
+ ...(typeof this.props.style === 'object' ? this.props.style : {})
1825
+ };
1826
+ const id = this.props.id || parsedProps.id;
1827
+ return /*#__PURE__*/React.createElement("div", {
1828
+ ref: this.__getRef,
1829
+ className: className,
1830
+ id: id,
1831
+ style: style
1832
+ }, children);
1833
+ }
1834
+ __checkSchema = (schema, originalExtraComponents = []) => {
1835
+ let extraComponents = originalExtraComponents;
1836
+ if (typeof extraComponents === 'string') {
1837
+ extraComponents = [extraComponents];
1838
+ }
1839
+
1840
+ // const builtin = capitalizeFirstLetter(this.__namespace)
1841
+ // const componentNames = [builtin, ...extraComponents]
1842
+ const componentNames = [...Object.keys(this.props.__components), ...extraComponents];
1843
+ return !isSchema(schema) || !componentNames.includes(schema?.componentName ?? '');
1844
+ };
1845
+ get appHelper() {
1846
+ return this.props.__appHelper;
1847
+ }
1848
+ get requestHandlersMap() {
1849
+ return this.appHelper?.requestHandlersMap;
1850
+ }
1851
+ get utils() {
1852
+ return this.appHelper?.utils;
1853
+ }
1854
+ get constants() {
1855
+ return this.appHelper?.constants;
1856
+ }
1857
+
1858
+ // render() {
1859
+ // return null
1860
+ // }
1861
+ };
1862
+ }
1863
+
1864
+ function componentRendererFactory() {
1865
+ const BaseRenderer = baseRendererFactory();
1866
+ return class CompRenderer extends BaseRenderer {
1867
+ static displayName = 'CompRenderer';
1868
+ __namespace = 'component';
1869
+ __afterInit(props, ...rest) {
1870
+ this.__generateCtx({
1871
+ component: this
1872
+ });
1873
+ const schema = props.__schema || {};
1874
+ this.state = this.__parseData(schema.state || {});
1875
+ this.__initDataSource(props);
1876
+ this.__executeLifeCycleMethod('constructor', [props, ...rest]);
1877
+ }
1878
+ render() {
1879
+ const {
1880
+ __schema
1881
+ } = this.props;
1882
+ if (this.__checkSchema(__schema)) {
1883
+ return '自定义组件 schema 结构异常!';
1884
+ }
1885
+ logger.log(`${CompRenderer.displayName} render - ${__schema.componentName}`);
1886
+ this.__generateCtx({
1887
+ component: this
1888
+ });
1889
+ this.__render();
1890
+ const noContainer = this.__parseData(__schema.props?.noContainer);
1891
+ this.__bindCustomMethods(this.props);
1892
+ if (noContainer) {
1893
+ return this.__renderContextProvider({
1894
+ compContext: this
1895
+ });
1896
+ }
1897
+ const Comp = this.__getComponentView();
1898
+ if (!Comp) {
1899
+ return this.__renderContent(this.__renderContextProvider({
1900
+ compContext: this
1901
+ }));
1902
+ }
1903
+ return this.__renderComp(Comp, {
1904
+ compContext: this
1905
+ });
1906
+ }
1907
+ };
1908
+ }
1909
+
1910
+ function pageRendererFactory() {
1911
+ const BaseRenderer = baseRendererFactory();
1912
+ return class PageRenderer extends BaseRenderer {
1913
+ static displayName = 'PageRenderer';
1914
+ __namespace = 'page';
1915
+ __afterInit(props, ...rest) {
1916
+ const schema = props.__schema || {};
1917
+ this.state = this.__parseData(schema.state || {});
1918
+ this.__initDataSource(props);
1919
+ this.__executeLifeCycleMethod('constructor', [props, ...rest]);
1920
+ }
1921
+ async componentDidUpdate(prevProps, _prevState, snapshot) {
1922
+ const {
1923
+ __ctx
1924
+ } = this.props;
1925
+ // 当编排的时候修改 schema.state 值,需要将最新 schema.state 值 setState
1926
+ if (JSON.stringify(prevProps.__schema.state) !== JSON.stringify(this.props.__schema.state)) {
1927
+ const newState = this.__parseData(this.props.__schema.state, __ctx);
1928
+ this.setState(newState);
1929
+ }
1930
+ super.componentDidUpdate?.(prevProps, _prevState, snapshot);
1931
+ }
1932
+ setState(state, callback) {
1933
+ logger.log('page set state', state);
1934
+ super.setState(state, callback);
1935
+ }
1936
+ render() {
1937
+ const {
1938
+ __schema
1939
+ } = this.props;
1940
+ if (this.__checkSchema(__schema)) {
1941
+ return '页面schema结构异常!';
1942
+ }
1943
+ logger.log(`${PageRenderer.displayName} render - ${__schema.componentName}`);
1944
+ this.__bindCustomMethods(this.props);
1945
+ this.__initDataSource(this.props);
1946
+ this.__generateCtx({
1947
+ page: this
1948
+ });
1949
+ this.__render();
1950
+ const Comp = this.__getComponentView();
1951
+ if (!Comp) {
1952
+ return this.__renderContent(this.__renderContextProvider({
1953
+ pageContext: this
1954
+ }));
1955
+ }
1956
+ return this.__renderComp(Comp, {
1957
+ pageContext: this
1958
+ });
1959
+ }
1960
+ };
1961
+ }
1962
+
1963
+ const FaultComponent = ({
1964
+ componentName = '',
1965
+ error
1966
+ }) => {
1967
+ logger.error(`${componentName} 组件渲染异常, 异常原因: ${error?.message || error || '未知'}`);
1968
+ return /*#__PURE__*/React.createElement("div", {
1969
+ role: "alert",
1970
+ "aria-label": `${componentName} 组件渲染异常`,
1971
+ style: {
1972
+ width: '100%',
1973
+ height: '50px',
1974
+ lineHeight: '50px',
1975
+ textAlign: 'center',
1976
+ fontSize: '15px',
1977
+ color: '#ef4444',
1978
+ border: '2px solid #ef4444'
1979
+ }
1980
+ }, componentName, " \u7EC4\u4EF6\u6E32\u67D3\u5F02\u5E38\uFF0C\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7");
1981
+ };
1982
+
1983
+ const NotFoundComponent = ({
1984
+ componentName = '',
1985
+ enableStrictNotFoundMode,
1986
+ children
1987
+ }) => {
1988
+ logger.warn(`Component ${componentName} not found`);
1989
+ if (enableStrictNotFoundMode) {
1990
+ return /*#__PURE__*/React.createElement(React.Fragment, null, `${componentName} Component Not Found`);
1991
+ }
1992
+ return /*#__PURE__*/React.createElement("div", {
1993
+ role: "alert",
1994
+ "aria-label": `${componentName} component not found`,
1995
+ style: {
1996
+ width: '100%',
1997
+ height: '50px',
1998
+ lineHeight: '50px',
1999
+ textAlign: 'center',
2000
+ fontSize: '15px',
2001
+ color: '#eab308',
2002
+ border: '2px solid #eab308'
2003
+ }
2004
+ }, `${componentName} Component Not Found`);
2005
+ };
2006
+
2007
+ function rendererFactory() {
2008
+ const RENDERER_COMPS = adapter.getRenderers();
2009
+ return class Renderer extends Component {
2010
+ static displayName = 'Renderer';
2011
+ state = {};
2012
+ __ref;
2013
+ static defaultProps = {
2014
+ appHelper: undefined,
2015
+ components: {},
2016
+ designMode: 'live',
2017
+ suspended: false,
2018
+ schema: {},
2019
+ onCompGetRef: () => {},
2020
+ onCompGetCtx: () => {},
2021
+ thisRequiredInJSE: true
2022
+ };
2023
+ constructor(props) {
2024
+ super(props);
2025
+ this.state = {};
2026
+ logger$1.log(`entry.constructor - ${props?.schema?.componentName}`);
2027
+ }
2028
+ async componentDidMount() {
2029
+ logger$1.log(`entry.componentDidMount - ${this.props.schema && this.props.schema.componentName}`);
2030
+ }
2031
+ async componentDidUpdate() {
2032
+ logger$1.log(`entry.componentDidUpdate - ${this.props?.schema?.componentName}`);
2033
+ }
2034
+ async componentWillUnmount() {
2035
+ logger$1.log(`entry.componentWillUnmount - ${this.props?.schema?.componentName}`);
2036
+ }
2037
+ componentDidCatch(error) {
2038
+ this.state.engineRenderError = true;
2039
+ this.state.error = error;
2040
+ }
2041
+ shouldComponentUpdate(nextProps) {
2042
+ return !nextProps.suspended;
2043
+ }
2044
+ __getRef = ref => {
2045
+ this.__ref = ref;
2046
+ if (ref) {
2047
+ this.props.onCompGetRef?.(this.props.schema, ref);
2048
+ }
2049
+ };
2050
+ isValidComponent(SetComponent) {
2051
+ return SetComponent;
2052
+ }
2053
+ createElement(SetComponent, props, children) {
2054
+ return (this.props.customCreateElement || createElement)(SetComponent, props, children);
2055
+ }
2056
+ getNotFoundComponent() {
2057
+ return this.props.notFoundComponent || NotFoundComponent;
2058
+ }
2059
+ getFaultComponent() {
2060
+ return this.props.faultComponent || FaultComponent;
2061
+ }
2062
+ render() {
2063
+ const {
2064
+ schema,
2065
+ designMode,
2066
+ appHelper,
2067
+ components
2068
+ } = this.props;
2069
+ if (isEmpty(schema)) {
2070
+ return null;
2071
+ }
2072
+ if (!isSchema(schema)) {
2073
+ logger$1.error('The root component name needs to be one of Page、Block、Component, please check the schema: ', schema);
2074
+ return '模型结构异常';
2075
+ }
2076
+ logger$1.log('entry.render');
2077
+ const allComponents = {
2078
+ ...components,
2079
+ ...RENDERER_COMPS
2080
+ };
2081
+ // TODO: 默认最顶层使用 PageRenderer
2082
+ const Comp = allComponents.PageRenderer;
2083
+ if (this.state && this.state.engineRenderError) {
2084
+ return /*#__PURE__*/createElement(this.getFaultComponent(), {
2085
+ componentName: schema.componentName,
2086
+ error: this.state.error
2087
+ });
2088
+ }
2089
+ if (!Comp) {
2090
+ return null;
2091
+ }
2092
+ return /*#__PURE__*/React.createElement(RendererContext.Provider, {
2093
+ value: {
2094
+ appHelper,
2095
+ components: allComponents,
2096
+ engine: this
2097
+ }
2098
+ }, /*#__PURE__*/React.createElement(Comp, _extends({
2099
+ key: schema.__ctx && `${schema.__ctx.lceKey}_${schema.__ctx.idx || '0'}`
2100
+ // ref={this.__getRef}
2101
+ ,
2102
+ __appHelper: appHelper,
2103
+ __components: allComponents,
2104
+ __schema: schema,
2105
+ __designMode: designMode
2106
+ }, this.props)));
2107
+ }
2108
+ };
2109
+ }
2110
+
2111
+ const DEV = '_EASY_EDITOR_DEV_';
2112
+
2113
+ 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 };