@easy-editor/react-renderer 0.0.18 → 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 (50) 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} +406 -1894
  9. package/dist/index.d.ts +10 -3
  10. package/dist/index.js +353 -1823
  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 +15 -20
  19. package/dist/cjs/index.development.js +0 -4013
  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 -4013
  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 -3977
  27. package/dist/esm/index.development.js.map +0 -1
  28. package/dist/esm/index.js +0 -3977
  29. package/dist/esm/index.js.map +0 -1
  30. package/dist/esm/index.production.js +0 -3977
  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 -202
  40. package/dist/renderer-core/utils/classnames.d.ts +0 -1
  41. package/dist/renderer-core/utils/common.d.ts +0 -59
  42. package/dist/renderer-core/utils/data-helper.d.ts +0 -83
  43. package/dist/renderer-core/utils/index.d.ts +0 -4
  44. package/dist/renderer-core/utils/logger.d.ts +0 -5
  45. package/dist/renderer-core/utils/request.d.ts +0 -43
  46. /package/dist/{renderer-core/context.d.ts → context.d.ts} +0 -0
  47. /package/dist/{renderer-core/hoc → hoc}/comp.d.ts +0 -0
  48. /package/dist/{renderer-core/hoc → hoc}/index.d.ts +0 -0
  49. /package/dist/{configure-renderer → setting-renderer}/SettingSetter.d.ts +0 -0
  50. /package/dist/{renderer-core/utils → utils}/hoc.d.ts +0 -0
@@ -1,4013 +0,0 @@
1
- 'use strict';
2
-
3
- var mobxReact = require('mobx-react');
4
- var react = require('react');
5
- var core = require('@easy-editor/core');
6
- var jsxRuntime = require('react/jsx-runtime');
7
-
8
- const SettingRendererContext = /*#__PURE__*/react.createContext({});
9
- const useSettingRendererContext = () => {
10
- try {
11
- return react.useContext(SettingRendererContext);
12
- } catch (error) {
13
- console.warn('useSettingRendererContext must be used within a SettingRendererContextProvider');
14
- }
15
- return {};
16
- };
17
-
18
- const getSetterInfo = field => {
19
- const {
20
- extraProps,
21
- setter
22
- } = field;
23
- const {
24
- defaultValue
25
- } = extraProps;
26
- let setterProps = {};
27
- let setterType;
28
- let initialValue = null;
29
- if (core.isSetterConfig(setter)) {
30
- setterType = setter.componentName;
31
- if (setter.props) {
32
- setterProps = setter.props;
33
- if (typeof setterProps === 'function') {
34
- setterProps = setterProps(field);
35
- }
36
- }
37
- if (setter.defaultValue != null) {
38
- initialValue = setter.defaultValue;
39
- }
40
- } else if (setter) {
41
- setterType = setter;
42
- }
43
- if (defaultValue != null && !('defaultValue' in setterProps)) {
44
- setterProps.defaultValue = defaultValue;
45
- if (initialValue == null) {
46
- initialValue = defaultValue;
47
- }
48
- }
49
- if (field.valueState === -1) {
50
- setterProps.multiValue = true;
51
- }
52
-
53
- // 根据是否支持变量配置做相应的更改
54
- const supportVariable = field.extraProps?.supportVariable;
55
- const isUseVariableSetter = supportVariable;
56
- if (isUseVariableSetter === false) {
57
- return {
58
- setterProps,
59
- initialValue,
60
- setterType
61
- };
62
- }
63
- return {
64
- setterProps,
65
- setterType,
66
- initialValue
67
- };
68
- };
69
- const SettingSetter = mobxReact.observer(({
70
- field,
71
- children
72
- }) => {
73
- const {
74
- setterManager
75
- } = useSettingRendererContext();
76
- const {
77
- extraProps
78
- } = field;
79
- const visible = extraProps?.condition && typeof extraProps.condition === 'function' ? extraProps.condition(field) !== false : true;
80
- if (!visible) {
81
- return null;
82
- }
83
- const {
84
- setterProps = {},
85
- setterType,
86
- initialValue = null
87
- } = getSetterInfo(field);
88
- const onChange = extraProps?.onChange;
89
- const value = field.valueState === -1 ? null : field.getValue();
90
- const {
91
- component: SetterComponent,
92
- props: mixedSetterProps
93
- } = setterManager.createSetterContent(setterType, setterProps);
94
- return /*#__PURE__*/jsxRuntime.jsx(SetterComponent, {
95
- field: field,
96
- selected: field.top?.getNode(),
97
- initialValue: initialValue,
98
- value: value,
99
- onChange: newVal => {
100
- field.setValue(newVal);
101
- onChange?.(field, newVal);
102
- },
103
- onInitial: () => {
104
- if (initialValue == null) {
105
- return;
106
- }
107
- const value = typeof initialValue === 'function' ? initialValue(field) : initialValue;
108
- field.setValue(value, true);
109
- },
110
- removeProp: () => {
111
- if (field.name) {
112
- field.parent.clearPropValue(field.name);
113
- }
114
- },
115
- ...mixedSetterProps,
116
- children: children
117
- }, field.id);
118
- });
119
-
120
- const SettingFieldItem = mobxReact.observer(({
121
- field
122
- }) => {
123
- const {
124
- customFieldItem
125
- } = useSettingRendererContext();
126
- if (customFieldItem) {
127
- return customFieldItem(field, /*#__PURE__*/jsxRuntime.jsx(SettingSetter, {
128
- field: field
129
- }));
130
- }
131
- return /*#__PURE__*/jsxRuntime.jsxs("div", {
132
- className: "space-y-2",
133
- children: [/*#__PURE__*/jsxRuntime.jsx("label", {
134
- htmlFor: field.id,
135
- className: "block text-sm font-medium text-gray-700",
136
- children: field.title
137
- }), /*#__PURE__*/jsxRuntime.jsx(SettingSetter, {
138
- field: field
139
- })]
140
- });
141
- });
142
- const SettingFieldGroup = mobxReact.observer(({
143
- field
144
- }) => {
145
- const {
146
- customFieldGroup
147
- } = useSettingRendererContext();
148
- if (customFieldGroup) {
149
- return customFieldGroup(field, /*#__PURE__*/jsxRuntime.jsx(SettingSetter, {
150
- field: field,
151
- children: field.items?.map(item => /*#__PURE__*/jsxRuntime.jsx(SettingFieldView, {
152
- field: item
153
- }, item.id))
154
- }));
155
- }
156
-
157
- // 如果 field 没有 setter,则理解为其 父级 field 的 items 数据
158
- if (!field.setter) {
159
- return field.items?.map(item => /*#__PURE__*/jsxRuntime.jsx(SettingFieldView, {
160
- field: item
161
- }, item.id));
162
- }
163
- return /*#__PURE__*/jsxRuntime.jsx(SettingSetter, {
164
- field: field,
165
- children: field.items?.map(item => /*#__PURE__*/jsxRuntime.jsx(SettingFieldView, {
166
- field: item
167
- }, item.id))
168
- });
169
- });
170
- const SettingFieldView = ({
171
- field
172
- }) => {
173
- if (field.isGroup) {
174
- return /*#__PURE__*/jsxRuntime.jsx(SettingFieldGroup, {
175
- field: field
176
- }, field.id);
177
- } else {
178
- return /*#__PURE__*/jsxRuntime.jsx(SettingFieldItem, {
179
- field: field
180
- }, field.id);
181
- }
182
- };
183
- const SettingRender = mobxReact.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 = react.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__*/jsxRuntime.jsx("div", {
209
- className: "lc-settings-main",
210
- children: /*#__PURE__*/jsxRuntime.jsx("div", {
211
- className: "lc-settings-notice",
212
- children: /*#__PURE__*/jsxRuntime.jsx("p", {
213
- children: "Please select a node in canvas"
214
- })
215
- })
216
- });
217
- }
218
-
219
- // 当节点被锁定,且未开启锁定后容器可设置属性
220
- if (settings.isLocked) {
221
- return /*#__PURE__*/jsxRuntime.jsx("div", {
222
- className: "lc-settings-main",
223
- children: /*#__PURE__*/jsxRuntime.jsx("div", {
224
- className: "lc-settings-notice",
225
- children: /*#__PURE__*/jsxRuntime.jsx("p", {
226
- children: "Current node is locked"
227
- })
228
- })
229
- });
230
- }
231
- if (Array.isArray(settings.items) && settings.items.length === 0) {
232
- return /*#__PURE__*/jsxRuntime.jsx("div", {
233
- className: "lc-settings-main",
234
- children: /*#__PURE__*/jsxRuntime.jsx("div", {
235
- className: "lc-settings-notice",
236
- children: /*#__PURE__*/jsxRuntime.jsx("p", {
237
- children: "No config found for this type of component"
238
- })
239
- })
240
- });
241
- }
242
- if (!settings.isSameComponent) {
243
- // TODO: future support 获取设置项交集编辑
244
- return /*#__PURE__*/jsxRuntime.jsx("div", {
245
- className: "lc-settings-main",
246
- children: /*#__PURE__*/jsxRuntime.jsx("div", {
247
- className: "lc-settings-notice",
248
- children: /*#__PURE__*/jsxRuntime.jsx("p", {
249
- children: "Please select same kind of components"
250
- })
251
- })
252
- });
253
- }
254
- return /*#__PURE__*/jsxRuntime.jsx(SettingRendererContext.Provider, {
255
- value: ctx,
256
- children: items?.map(item => /*#__PURE__*/jsxRuntime.jsx(SettingFieldView, {
257
- field: item
258
- }, item.id))
259
- });
260
- });
261
-
262
- class Adapter {
263
- renderers = {};
264
- setRenderers(renderers) {
265
- this.renderers = renderers;
266
- }
267
- setBaseRenderer(BaseRenderer) {
268
- this.renderers.BaseRenderer = BaseRenderer;
269
- }
270
- setPageRenderer(PageRenderer) {
271
- this.renderers.PageRenderer = PageRenderer;
272
- }
273
- setComponentRenderer(ComponentRenderer) {
274
- this.renderers.ComponentRenderer = ComponentRenderer;
275
- }
276
- getRenderers() {
277
- return this.renderers || {};
278
- }
279
- }
280
- const adapter = new Adapter();
281
-
282
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
283
-
284
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
285
- var root = freeGlobal || freeSelf || Function('return this')();
286
-
287
- var Symbol = root.Symbol;
288
-
289
- var objectProto$c = Object.prototype;
290
- var hasOwnProperty$a = objectProto$c.hasOwnProperty;
291
- var nativeObjectToString$1 = objectProto$c.toString;
292
- var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined;
293
- function getRawTag(value) {
294
- var isOwn = hasOwnProperty$a.call(value, symToStringTag$1),
295
- tag = value[symToStringTag$1];
296
- try {
297
- value[symToStringTag$1] = undefined;
298
- var unmasked = true;
299
- } catch (e) {}
300
- var result = nativeObjectToString$1.call(value);
301
- if (unmasked) {
302
- if (isOwn) {
303
- value[symToStringTag$1] = tag;
304
- } else {
305
- delete value[symToStringTag$1];
306
- }
307
- }
308
- return result;
309
- }
310
-
311
- var objectProto$b = Object.prototype;
312
- var nativeObjectToString = objectProto$b.toString;
313
- function objectToString(value) {
314
- return nativeObjectToString.call(value);
315
- }
316
-
317
- var nullTag = '[object Null]',
318
- undefinedTag = '[object Undefined]';
319
- var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
320
- function baseGetTag(value) {
321
- if (value == null) {
322
- return value === undefined ? undefinedTag : nullTag;
323
- }
324
- return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
325
- }
326
-
327
- function isObjectLike(value) {
328
- return value != null && typeof value == 'object';
329
- }
330
-
331
- var symbolTag = '[object Symbol]';
332
- function isSymbol(value) {
333
- return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
334
- }
335
-
336
- var isArray = Array.isArray;
337
-
338
- var reWhitespace = /\s/;
339
- function trimmedEndIndex(string) {
340
- var index = string.length;
341
- while (index-- && reWhitespace.test(string.charAt(index))) {}
342
- return index;
343
- }
344
-
345
- var reTrimStart = /^\s+/;
346
- function baseTrim(string) {
347
- return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
348
- }
349
-
350
- function isObject$1(value) {
351
- var type = typeof value;
352
- return value != null && (type == 'object' || type == 'function');
353
- }
354
-
355
- var NAN = 0 / 0;
356
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
357
- var reIsBinary = /^0b[01]+$/i;
358
- var reIsOctal = /^0o[0-7]+$/i;
359
- var freeParseInt = parseInt;
360
- function toNumber(value) {
361
- if (typeof value == 'number') {
362
- return value;
363
- }
364
- if (isSymbol(value)) {
365
- return NAN;
366
- }
367
- if (isObject$1(value)) {
368
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
369
- value = isObject$1(other) ? other + '' : other;
370
- }
371
- if (typeof value != 'string') {
372
- return value === 0 ? value : +value;
373
- }
374
- value = baseTrim(value);
375
- var isBinary = reIsBinary.test(value);
376
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
377
- }
378
-
379
- function identity(value) {
380
- return value;
381
- }
382
-
383
- var asyncTag = '[object AsyncFunction]',
384
- funcTag$1 = '[object Function]',
385
- genTag = '[object GeneratorFunction]',
386
- proxyTag = '[object Proxy]';
387
- function isFunction(value) {
388
- if (!isObject$1(value)) {
389
- return false;
390
- }
391
- var tag = baseGetTag(value);
392
- return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
393
- }
394
-
395
- var coreJsData = root['__core-js_shared__'];
396
-
397
- var maskSrcKey = function () {
398
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
399
- return uid ? 'Symbol(src)_1.' + uid : '';
400
- }();
401
- function isMasked(func) {
402
- return !!maskSrcKey && maskSrcKey in func;
403
- }
404
-
405
- var funcProto$2 = Function.prototype;
406
- var funcToString$2 = funcProto$2.toString;
407
- function toSource(func) {
408
- if (func != null) {
409
- try {
410
- return funcToString$2.call(func);
411
- } catch (e) {}
412
- try {
413
- return func + '';
414
- } catch (e) {}
415
- }
416
- return '';
417
- }
418
-
419
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
420
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
421
- var funcProto$1 = Function.prototype,
422
- objectProto$a = Object.prototype;
423
- var funcToString$1 = funcProto$1.toString;
424
- var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
425
- var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$9).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
426
- function baseIsNative(value) {
427
- if (!isObject$1(value) || isMasked(value)) {
428
- return false;
429
- }
430
- var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
431
- return pattern.test(toSource(value));
432
- }
433
-
434
- function getValue$1(object, key) {
435
- return object == null ? undefined : object[key];
436
- }
437
-
438
- function getNative(object, key) {
439
- var value = getValue$1(object, key);
440
- return baseIsNative(value) ? value : undefined;
441
- }
442
-
443
- var WeakMap = getNative(root, 'WeakMap');
444
-
445
- var objectCreate = Object.create;
446
- var baseCreate = function () {
447
- function object() {}
448
- return function (proto) {
449
- if (!isObject$1(proto)) {
450
- return {};
451
- }
452
- if (objectCreate) {
453
- return objectCreate(proto);
454
- }
455
- object.prototype = proto;
456
- var result = new object();
457
- object.prototype = undefined;
458
- return result;
459
- };
460
- }();
461
-
462
- function apply(func, thisArg, args) {
463
- switch (args.length) {
464
- case 0:
465
- return func.call(thisArg);
466
- case 1:
467
- return func.call(thisArg, args[0]);
468
- case 2:
469
- return func.call(thisArg, args[0], args[1]);
470
- case 3:
471
- return func.call(thisArg, args[0], args[1], args[2]);
472
- }
473
- return func.apply(thisArg, args);
474
- }
475
-
476
- function copyArray(source, array) {
477
- var index = -1,
478
- length = source.length;
479
- array || (array = Array(length));
480
- while (++index < length) {
481
- array[index] = source[index];
482
- }
483
- return array;
484
- }
485
-
486
- var HOT_COUNT = 800,
487
- HOT_SPAN = 16;
488
- var nativeNow = Date.now;
489
- function shortOut(func) {
490
- var count = 0,
491
- lastCalled = 0;
492
- return function () {
493
- var stamp = nativeNow(),
494
- remaining = HOT_SPAN - (stamp - lastCalled);
495
- lastCalled = stamp;
496
- if (remaining > 0) {
497
- if (++count >= HOT_COUNT) {
498
- return arguments[0];
499
- }
500
- } else {
501
- count = 0;
502
- }
503
- return func.apply(undefined, arguments);
504
- };
505
- }
506
-
507
- function constant(value) {
508
- return function () {
509
- return value;
510
- };
511
- }
512
-
513
- var defineProperty = function () {
514
- try {
515
- var func = getNative(Object, 'defineProperty');
516
- func({}, '', {});
517
- return func;
518
- } catch (e) {}
519
- }();
520
-
521
- var baseSetToString = !defineProperty ? identity : function (func, string) {
522
- return defineProperty(func, 'toString', {
523
- 'configurable': true,
524
- 'enumerable': false,
525
- 'value': constant(string),
526
- 'writable': true
527
- });
528
- };
529
-
530
- var setToString = shortOut(baseSetToString);
531
-
532
- function arrayEach(array, iteratee) {
533
- var index = -1,
534
- length = array == null ? 0 : array.length;
535
- while (++index < length) {
536
- if (iteratee(array[index], index, array) === false) {
537
- break;
538
- }
539
- }
540
- return array;
541
- }
542
-
543
- var MAX_SAFE_INTEGER$1 = 9007199254740991;
544
- var reIsUint = /^(?:0|[1-9]\d*)$/;
545
- function isIndex(value, length) {
546
- var type = typeof value;
547
- length = length == null ? MAX_SAFE_INTEGER$1 : length;
548
- return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
549
- }
550
-
551
- function baseAssignValue(object, key, value) {
552
- if (key == '__proto__' && defineProperty) {
553
- defineProperty(object, key, {
554
- 'configurable': true,
555
- 'enumerable': true,
556
- 'value': value,
557
- 'writable': true
558
- });
559
- } else {
560
- object[key] = value;
561
- }
562
- }
563
-
564
- function eq(value, other) {
565
- return value === other || value !== value && other !== other;
566
- }
567
-
568
- var objectProto$9 = Object.prototype;
569
- var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
570
- function assignValue(object, key, value) {
571
- var objValue = object[key];
572
- if (!(hasOwnProperty$8.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) {
573
- baseAssignValue(object, key, value);
574
- }
575
- }
576
-
577
- function copyObject(source, props, object, customizer) {
578
- var isNew = !object;
579
- object || (object = {});
580
- var index = -1,
581
- length = props.length;
582
- while (++index < length) {
583
- var key = props[index];
584
- var newValue = undefined;
585
- if (newValue === undefined) {
586
- newValue = source[key];
587
- }
588
- if (isNew) {
589
- baseAssignValue(object, key, newValue);
590
- } else {
591
- assignValue(object, key, newValue);
592
- }
593
- }
594
- return object;
595
- }
596
-
597
- var nativeMax$1 = Math.max;
598
- function overRest(func, start, transform) {
599
- start = nativeMax$1(start === undefined ? func.length - 1 : start, 0);
600
- return function () {
601
- var args = arguments,
602
- index = -1,
603
- length = nativeMax$1(args.length - start, 0),
604
- array = Array(length);
605
- while (++index < length) {
606
- array[index] = args[start + index];
607
- }
608
- index = -1;
609
- var otherArgs = Array(start + 1);
610
- while (++index < start) {
611
- otherArgs[index] = args[index];
612
- }
613
- otherArgs[start] = transform(array);
614
- return apply(func, this, otherArgs);
615
- };
616
- }
617
-
618
- function baseRest(func, start) {
619
- return setToString(overRest(func, start, identity), func + '');
620
- }
621
-
622
- var MAX_SAFE_INTEGER = 9007199254740991;
623
- function isLength(value) {
624
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
625
- }
626
-
627
- function isArrayLike(value) {
628
- return value != null && isLength(value.length) && !isFunction(value);
629
- }
630
-
631
- function isIterateeCall(value, index, object) {
632
- if (!isObject$1(object)) {
633
- return false;
634
- }
635
- var type = typeof index;
636
- if (type == 'number' ? isArrayLike(object) && isIndex(index, object.length) : type == 'string' && index in object) {
637
- return eq(object[index], value);
638
- }
639
- return false;
640
- }
641
-
642
- function createAssigner(assigner) {
643
- return baseRest(function (object, sources) {
644
- var index = -1,
645
- length = sources.length,
646
- customizer = length > 1 ? sources[length - 1] : undefined,
647
- guard = length > 2 ? sources[2] : undefined;
648
- customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined;
649
- if (guard && isIterateeCall(sources[0], sources[1], guard)) {
650
- customizer = length < 3 ? undefined : customizer;
651
- length = 1;
652
- }
653
- object = Object(object);
654
- while (++index < length) {
655
- var source = sources[index];
656
- if (source) {
657
- assigner(object, source, index, customizer);
658
- }
659
- }
660
- return object;
661
- });
662
- }
663
-
664
- var objectProto$8 = Object.prototype;
665
- function isPrototype(value) {
666
- var Ctor = value && value.constructor,
667
- proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
668
- return value === proto;
669
- }
670
-
671
- function baseTimes(n, iteratee) {
672
- var index = -1,
673
- result = Array(n);
674
- while (++index < n) {
675
- result[index] = iteratee(index);
676
- }
677
- return result;
678
- }
679
-
680
- var argsTag$1 = '[object Arguments]';
681
- function baseIsArguments(value) {
682
- return isObjectLike(value) && baseGetTag(value) == argsTag$1;
683
- }
684
-
685
- var objectProto$7 = Object.prototype;
686
- var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
687
- var propertyIsEnumerable = objectProto$7.propertyIsEnumerable;
688
- var isArguments = baseIsArguments(function () {
689
- return arguments;
690
- }()) ? baseIsArguments : function (value) {
691
- return isObjectLike(value) && hasOwnProperty$7.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
692
- };
693
-
694
- function stubFalse() {
695
- return false;
696
- }
697
-
698
- var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;
699
- var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;
700
- var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;
701
- var Buffer$1 = moduleExports$2 ? root.Buffer : undefined;
702
- var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined;
703
- var isBuffer = nativeIsBuffer || stubFalse;
704
-
705
- var argsTag = '[object Arguments]',
706
- arrayTag = '[object Array]',
707
- boolTag = '[object Boolean]',
708
- dateTag = '[object Date]',
709
- errorTag = '[object Error]',
710
- funcTag = '[object Function]',
711
- mapTag$2 = '[object Map]',
712
- numberTag = '[object Number]',
713
- objectTag$2 = '[object Object]',
714
- regexpTag = '[object RegExp]',
715
- setTag$2 = '[object Set]',
716
- stringTag = '[object String]',
717
- weakMapTag$1 = '[object WeakMap]';
718
- var arrayBufferTag = '[object ArrayBuffer]',
719
- dataViewTag$1 = '[object DataView]',
720
- float32Tag = '[object Float32Array]',
721
- float64Tag = '[object Float64Array]',
722
- int8Tag = '[object Int8Array]',
723
- int16Tag = '[object Int16Array]',
724
- int32Tag = '[object Int32Array]',
725
- uint8Tag = '[object Uint8Array]',
726
- uint8ClampedTag = '[object Uint8ClampedArray]',
727
- uint16Tag = '[object Uint16Array]',
728
- uint32Tag = '[object Uint32Array]';
729
- var typedArrayTags = {};
730
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
731
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag$2] = typedArrayTags[numberTag] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag] = typedArrayTags[setTag$2] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false;
732
- function baseIsTypedArray(value) {
733
- return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
734
- }
735
-
736
- function baseUnary(func) {
737
- return function (value) {
738
- return func(value);
739
- };
740
- }
741
-
742
- var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
743
- var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
744
- var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
745
- var freeProcess = moduleExports$1 && freeGlobal.process;
746
- var nodeUtil = function () {
747
- try {
748
- var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
749
- if (types) {
750
- return types;
751
- }
752
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
753
- } catch (e) {}
754
- }();
755
-
756
- var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
757
- var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
758
-
759
- var objectProto$6 = Object.prototype;
760
- var hasOwnProperty$6 = objectProto$6.hasOwnProperty;
761
- function arrayLikeKeys(value, inherited) {
762
- var isArr = isArray(value),
763
- isArg = !isArr && isArguments(value),
764
- isBuff = !isArr && !isArg && isBuffer(value),
765
- isType = !isArr && !isArg && !isBuff && isTypedArray(value),
766
- skipIndexes = isArr || isArg || isBuff || isType,
767
- result = skipIndexes ? baseTimes(value.length, String) : [],
768
- length = result.length;
769
- for (var key in value) {
770
- if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && (
771
- key == 'length' ||
772
- isBuff && (key == 'offset' || key == 'parent') ||
773
- isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
774
- isIndex(key, length)))) {
775
- result.push(key);
776
- }
777
- }
778
- return result;
779
- }
780
-
781
- function overArg(func, transform) {
782
- return function (arg) {
783
- return func(transform(arg));
784
- };
785
- }
786
-
787
- var nativeKeys = overArg(Object.keys, Object);
788
-
789
- var objectProto$5 = Object.prototype;
790
- var hasOwnProperty$5 = objectProto$5.hasOwnProperty;
791
- function baseKeys(object) {
792
- if (!isPrototype(object)) {
793
- return nativeKeys(object);
794
- }
795
- var result = [];
796
- for (var key in Object(object)) {
797
- if (hasOwnProperty$5.call(object, key) && key != 'constructor') {
798
- result.push(key);
799
- }
800
- }
801
- return result;
802
- }
803
-
804
- function keys(object) {
805
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
806
- }
807
-
808
- function nativeKeysIn(object) {
809
- var result = [];
810
- if (object != null) {
811
- for (var key in Object(object)) {
812
- result.push(key);
813
- }
814
- }
815
- return result;
816
- }
817
-
818
- var objectProto$4 = Object.prototype;
819
- var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
820
- function baseKeysIn(object) {
821
- if (!isObject$1(object)) {
822
- return nativeKeysIn(object);
823
- }
824
- var isProto = isPrototype(object),
825
- result = [];
826
- for (var key in object) {
827
- if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
828
- result.push(key);
829
- }
830
- }
831
- return result;
832
- }
833
-
834
- function keysIn(object) {
835
- return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
836
- }
837
-
838
- var nativeCreate = getNative(Object, 'create');
839
-
840
- function hashClear() {
841
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
842
- this.size = 0;
843
- }
844
-
845
- function hashDelete(key) {
846
- var result = this.has(key) && delete this.__data__[key];
847
- this.size -= result ? 1 : 0;
848
- return result;
849
- }
850
-
851
- var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
852
- var objectProto$3 = Object.prototype;
853
- var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
854
- function hashGet(key) {
855
- var data = this.__data__;
856
- if (nativeCreate) {
857
- var result = data[key];
858
- return result === HASH_UNDEFINED$1 ? undefined : result;
859
- }
860
- return hasOwnProperty$3.call(data, key) ? data[key] : undefined;
861
- }
862
-
863
- var objectProto$2 = Object.prototype;
864
- var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
865
- function hashHas(key) {
866
- var data = this.__data__;
867
- return nativeCreate ? data[key] !== undefined : hasOwnProperty$2.call(data, key);
868
- }
869
-
870
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
871
- function hashSet(key, value) {
872
- var data = this.__data__;
873
- this.size += this.has(key) ? 0 : 1;
874
- data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
875
- return this;
876
- }
877
-
878
- function Hash(entries) {
879
- var index = -1,
880
- length = entries == null ? 0 : entries.length;
881
- this.clear();
882
- while (++index < length) {
883
- var entry = entries[index];
884
- this.set(entry[0], entry[1]);
885
- }
886
- }
887
- Hash.prototype.clear = hashClear;
888
- Hash.prototype['delete'] = hashDelete;
889
- Hash.prototype.get = hashGet;
890
- Hash.prototype.has = hashHas;
891
- Hash.prototype.set = hashSet;
892
-
893
- function listCacheClear() {
894
- this.__data__ = [];
895
- this.size = 0;
896
- }
897
-
898
- function assocIndexOf(array, key) {
899
- var length = array.length;
900
- while (length--) {
901
- if (eq(array[length][0], key)) {
902
- return length;
903
- }
904
- }
905
- return -1;
906
- }
907
-
908
- var arrayProto = Array.prototype;
909
- var splice = arrayProto.splice;
910
- function listCacheDelete(key) {
911
- var data = this.__data__,
912
- index = assocIndexOf(data, key);
913
- if (index < 0) {
914
- return false;
915
- }
916
- var lastIndex = data.length - 1;
917
- if (index == lastIndex) {
918
- data.pop();
919
- } else {
920
- splice.call(data, index, 1);
921
- }
922
- --this.size;
923
- return true;
924
- }
925
-
926
- function listCacheGet(key) {
927
- var data = this.__data__,
928
- index = assocIndexOf(data, key);
929
- return index < 0 ? undefined : data[index][1];
930
- }
931
-
932
- function listCacheHas(key) {
933
- return assocIndexOf(this.__data__, key) > -1;
934
- }
935
-
936
- function listCacheSet(key, value) {
937
- var data = this.__data__,
938
- index = assocIndexOf(data, key);
939
- if (index < 0) {
940
- ++this.size;
941
- data.push([key, value]);
942
- } else {
943
- data[index][1] = value;
944
- }
945
- return this;
946
- }
947
-
948
- function ListCache(entries) {
949
- var index = -1,
950
- length = entries == null ? 0 : entries.length;
951
- this.clear();
952
- while (++index < length) {
953
- var entry = entries[index];
954
- this.set(entry[0], entry[1]);
955
- }
956
- }
957
- ListCache.prototype.clear = listCacheClear;
958
- ListCache.prototype['delete'] = listCacheDelete;
959
- ListCache.prototype.get = listCacheGet;
960
- ListCache.prototype.has = listCacheHas;
961
- ListCache.prototype.set = listCacheSet;
962
-
963
- var Map$1 = getNative(root, 'Map');
964
-
965
- function mapCacheClear() {
966
- this.size = 0;
967
- this.__data__ = {
968
- 'hash': new Hash(),
969
- 'map': new (Map$1 || ListCache)(),
970
- 'string': new Hash()
971
- };
972
- }
973
-
974
- function isKeyable(value) {
975
- var type = typeof value;
976
- return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
977
- }
978
-
979
- function getMapData(map, key) {
980
- var data = map.__data__;
981
- return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
982
- }
983
-
984
- function mapCacheDelete(key) {
985
- var result = getMapData(this, key)['delete'](key);
986
- this.size -= result ? 1 : 0;
987
- return result;
988
- }
989
-
990
- function mapCacheGet(key) {
991
- return getMapData(this, key).get(key);
992
- }
993
-
994
- function mapCacheHas(key) {
995
- return getMapData(this, key).has(key);
996
- }
997
-
998
- function mapCacheSet(key, value) {
999
- var data = getMapData(this, key),
1000
- size = data.size;
1001
- data.set(key, value);
1002
- this.size += data.size == size ? 0 : 1;
1003
- return this;
1004
- }
1005
-
1006
- function MapCache(entries) {
1007
- var index = -1,
1008
- length = entries == null ? 0 : entries.length;
1009
- this.clear();
1010
- while (++index < length) {
1011
- var entry = entries[index];
1012
- this.set(entry[0], entry[1]);
1013
- }
1014
- }
1015
- MapCache.prototype.clear = mapCacheClear;
1016
- MapCache.prototype['delete'] = mapCacheDelete;
1017
- MapCache.prototype.get = mapCacheGet;
1018
- MapCache.prototype.has = mapCacheHas;
1019
- MapCache.prototype.set = mapCacheSet;
1020
-
1021
- var getPrototype = overArg(Object.getPrototypeOf, Object);
1022
-
1023
- var objectTag$1 = '[object Object]';
1024
- var funcProto = Function.prototype,
1025
- objectProto$1 = Object.prototype;
1026
- var funcToString = funcProto.toString;
1027
- var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
1028
- var objectCtorString = funcToString.call(Object);
1029
- function isPlainObject(value) {
1030
- if (!isObjectLike(value) || baseGetTag(value) != objectTag$1) {
1031
- return false;
1032
- }
1033
- var proto = getPrototype(value);
1034
- if (proto === null) {
1035
- return true;
1036
- }
1037
- var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor;
1038
- return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
1039
- }
1040
-
1041
- function stackClear() {
1042
- this.__data__ = new ListCache();
1043
- this.size = 0;
1044
- }
1045
-
1046
- function stackDelete(key) {
1047
- var data = this.__data__,
1048
- result = data['delete'](key);
1049
- this.size = data.size;
1050
- return result;
1051
- }
1052
-
1053
- function stackGet(key) {
1054
- return this.__data__.get(key);
1055
- }
1056
-
1057
- function stackHas(key) {
1058
- return this.__data__.has(key);
1059
- }
1060
-
1061
- var LARGE_ARRAY_SIZE = 200;
1062
- function stackSet(key, value) {
1063
- var data = this.__data__;
1064
- if (data instanceof ListCache) {
1065
- var pairs = data.__data__;
1066
- if (!Map$1 || pairs.length < LARGE_ARRAY_SIZE - 1) {
1067
- pairs.push([key, value]);
1068
- this.size = ++data.size;
1069
- return this;
1070
- }
1071
- data = this.__data__ = new MapCache(pairs);
1072
- }
1073
- data.set(key, value);
1074
- this.size = data.size;
1075
- return this;
1076
- }
1077
-
1078
- function Stack(entries) {
1079
- var data = this.__data__ = new ListCache(entries);
1080
- this.size = data.size;
1081
- }
1082
- Stack.prototype.clear = stackClear;
1083
- Stack.prototype['delete'] = stackDelete;
1084
- Stack.prototype.get = stackGet;
1085
- Stack.prototype.has = stackHas;
1086
- Stack.prototype.set = stackSet;
1087
-
1088
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
1089
- var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
1090
- var moduleExports = freeModule && freeModule.exports === freeExports;
1091
- var Buffer = moduleExports ? root.Buffer : undefined;
1092
- Buffer ? Buffer.allocUnsafe : undefined;
1093
- function cloneBuffer(buffer, isDeep) {
1094
- {
1095
- return buffer.slice();
1096
- }
1097
- }
1098
-
1099
- var DataView = getNative(root, 'DataView');
1100
-
1101
- var Promise$1 = getNative(root, 'Promise');
1102
-
1103
- var Set = getNative(root, 'Set');
1104
-
1105
- var mapTag$1 = '[object Map]',
1106
- objectTag = '[object Object]',
1107
- promiseTag = '[object Promise]',
1108
- setTag$1 = '[object Set]',
1109
- weakMapTag = '[object WeakMap]';
1110
- var dataViewTag = '[object DataView]';
1111
- var dataViewCtorString = toSource(DataView),
1112
- mapCtorString = toSource(Map$1),
1113
- promiseCtorString = toSource(Promise$1),
1114
- setCtorString = toSource(Set),
1115
- weakMapCtorString = toSource(WeakMap);
1116
- var getTag = baseGetTag;
1117
- 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) {
1118
- getTag = function (value) {
1119
- var result = baseGetTag(value),
1120
- Ctor = result == objectTag ? value.constructor : undefined,
1121
- ctorString = Ctor ? toSource(Ctor) : '';
1122
- if (ctorString) {
1123
- switch (ctorString) {
1124
- case dataViewCtorString:
1125
- return dataViewTag;
1126
- case mapCtorString:
1127
- return mapTag$1;
1128
- case promiseCtorString:
1129
- return promiseTag;
1130
- case setCtorString:
1131
- return setTag$1;
1132
- case weakMapCtorString:
1133
- return weakMapTag;
1134
- }
1135
- }
1136
- return result;
1137
- };
1138
- }
1139
-
1140
- var Uint8Array = root.Uint8Array;
1141
-
1142
- function cloneArrayBuffer(arrayBuffer) {
1143
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
1144
- new Uint8Array(result).set(new Uint8Array(arrayBuffer));
1145
- return result;
1146
- }
1147
-
1148
- function cloneTypedArray(typedArray, isDeep) {
1149
- var buffer = cloneArrayBuffer(typedArray.buffer) ;
1150
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
1151
- }
1152
-
1153
- function initCloneObject(object) {
1154
- return typeof object.constructor == 'function' && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
1155
- }
1156
-
1157
- function createBaseFor(fromRight) {
1158
- return function (object, iteratee, keysFunc) {
1159
- var index = -1,
1160
- iterable = Object(object),
1161
- props = keysFunc(object),
1162
- length = props.length;
1163
- while (length--) {
1164
- var key = props[++index];
1165
- if (iteratee(iterable[key], key, iterable) === false) {
1166
- break;
1167
- }
1168
- }
1169
- return object;
1170
- };
1171
- }
1172
-
1173
- var baseFor = createBaseFor();
1174
-
1175
- function baseForOwn(object, iteratee) {
1176
- return object && baseFor(object, iteratee, keys);
1177
- }
1178
-
1179
- function createBaseEach(eachFunc, fromRight) {
1180
- return function (collection, iteratee) {
1181
- if (collection == null) {
1182
- return collection;
1183
- }
1184
- if (!isArrayLike(collection)) {
1185
- return eachFunc(collection, iteratee);
1186
- }
1187
- var length = collection.length,
1188
- index = -1,
1189
- iterable = Object(collection);
1190
- while (++index < length) {
1191
- if (iteratee(iterable[index], index, iterable) === false) {
1192
- break;
1193
- }
1194
- }
1195
- return collection;
1196
- };
1197
- }
1198
-
1199
- var baseEach = createBaseEach(baseForOwn);
1200
-
1201
- var now = function () {
1202
- return root.Date.now();
1203
- };
1204
-
1205
- var FUNC_ERROR_TEXT = 'Expected a function';
1206
- var nativeMax = Math.max,
1207
- nativeMin = Math.min;
1208
- function debounce(func, wait, options) {
1209
- var lastArgs,
1210
- lastThis,
1211
- maxWait,
1212
- result,
1213
- timerId,
1214
- lastCallTime,
1215
- lastInvokeTime = 0,
1216
- leading = false,
1217
- maxing = false,
1218
- trailing = true;
1219
- if (typeof func != 'function') {
1220
- throw new TypeError(FUNC_ERROR_TEXT);
1221
- }
1222
- wait = toNumber(wait) || 0;
1223
- if (isObject$1(options)) {
1224
- leading = !!options.leading;
1225
- maxing = 'maxWait' in options;
1226
- maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
1227
- trailing = 'trailing' in options ? !!options.trailing : trailing;
1228
- }
1229
- function invokeFunc(time) {
1230
- var args = lastArgs,
1231
- thisArg = lastThis;
1232
- lastArgs = lastThis = undefined;
1233
- lastInvokeTime = time;
1234
- result = func.apply(thisArg, args);
1235
- return result;
1236
- }
1237
- function leadingEdge(time) {
1238
- lastInvokeTime = time;
1239
- timerId = setTimeout(timerExpired, wait);
1240
- return leading ? invokeFunc(time) : result;
1241
- }
1242
- function remainingWait(time) {
1243
- var timeSinceLastCall = time - lastCallTime,
1244
- timeSinceLastInvoke = time - lastInvokeTime,
1245
- timeWaiting = wait - timeSinceLastCall;
1246
- return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
1247
- }
1248
- function shouldInvoke(time) {
1249
- var timeSinceLastCall = time - lastCallTime,
1250
- timeSinceLastInvoke = time - lastInvokeTime;
1251
- return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
1252
- }
1253
- function timerExpired() {
1254
- var time = now();
1255
- if (shouldInvoke(time)) {
1256
- return trailingEdge(time);
1257
- }
1258
- timerId = setTimeout(timerExpired, remainingWait(time));
1259
- }
1260
- function trailingEdge(time) {
1261
- timerId = undefined;
1262
- if (trailing && lastArgs) {
1263
- return invokeFunc(time);
1264
- }
1265
- lastArgs = lastThis = undefined;
1266
- return result;
1267
- }
1268
- function cancel() {
1269
- if (timerId !== undefined) {
1270
- clearTimeout(timerId);
1271
- }
1272
- lastInvokeTime = 0;
1273
- lastArgs = lastCallTime = lastThis = timerId = undefined;
1274
- }
1275
- function flush() {
1276
- return timerId === undefined ? result : trailingEdge(now());
1277
- }
1278
- function debounced() {
1279
- var time = now(),
1280
- isInvoking = shouldInvoke(time);
1281
- lastArgs = arguments;
1282
- lastThis = this;
1283
- lastCallTime = time;
1284
- if (isInvoking) {
1285
- if (timerId === undefined) {
1286
- return leadingEdge(lastCallTime);
1287
- }
1288
- if (maxing) {
1289
- clearTimeout(timerId);
1290
- timerId = setTimeout(timerExpired, wait);
1291
- return invokeFunc(lastCallTime);
1292
- }
1293
- }
1294
- if (timerId === undefined) {
1295
- timerId = setTimeout(timerExpired, wait);
1296
- }
1297
- return result;
1298
- }
1299
- debounced.cancel = cancel;
1300
- debounced.flush = flush;
1301
- return debounced;
1302
- }
1303
-
1304
- function assignMergeValue(object, key, value) {
1305
- if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) {
1306
- baseAssignValue(object, key, value);
1307
- }
1308
- }
1309
-
1310
- function isArrayLikeObject(value) {
1311
- return isObjectLike(value) && isArrayLike(value);
1312
- }
1313
-
1314
- function safeGet(object, key) {
1315
- if (key === 'constructor' && typeof object[key] === 'function') {
1316
- return;
1317
- }
1318
- if (key == '__proto__') {
1319
- return;
1320
- }
1321
- return object[key];
1322
- }
1323
-
1324
- function toPlainObject(value) {
1325
- return copyObject(value, keysIn(value));
1326
- }
1327
-
1328
- function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
1329
- var objValue = safeGet(object, key),
1330
- srcValue = safeGet(source, key),
1331
- stacked = stack.get(srcValue);
1332
- if (stacked) {
1333
- assignMergeValue(object, key, stacked);
1334
- return;
1335
- }
1336
- var newValue = customizer ? customizer(objValue, srcValue, key + '', object, source, stack) : undefined;
1337
- var isCommon = newValue === undefined;
1338
- if (isCommon) {
1339
- var isArr = isArray(srcValue),
1340
- isBuff = !isArr && isBuffer(srcValue),
1341
- isTyped = !isArr && !isBuff && isTypedArray(srcValue);
1342
- newValue = srcValue;
1343
- if (isArr || isBuff || isTyped) {
1344
- if (isArray(objValue)) {
1345
- newValue = objValue;
1346
- } else if (isArrayLikeObject(objValue)) {
1347
- newValue = copyArray(objValue);
1348
- } else if (isBuff) {
1349
- isCommon = false;
1350
- newValue = cloneBuffer(srcValue);
1351
- } else if (isTyped) {
1352
- isCommon = false;
1353
- newValue = cloneTypedArray(srcValue);
1354
- } else {
1355
- newValue = [];
1356
- }
1357
- } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
1358
- newValue = objValue;
1359
- if (isArguments(objValue)) {
1360
- newValue = toPlainObject(objValue);
1361
- } else if (!isObject$1(objValue) || isFunction(objValue)) {
1362
- newValue = initCloneObject(srcValue);
1363
- }
1364
- } else {
1365
- isCommon = false;
1366
- }
1367
- }
1368
- if (isCommon) {
1369
- stack.set(srcValue, newValue);
1370
- mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
1371
- stack['delete'](srcValue);
1372
- }
1373
- assignMergeValue(object, key, newValue);
1374
- }
1375
-
1376
- function baseMerge(object, source, srcIndex, customizer, stack) {
1377
- if (object === source) {
1378
- return;
1379
- }
1380
- baseFor(source, function (srcValue, key) {
1381
- stack || (stack = new Stack());
1382
- if (isObject$1(srcValue)) {
1383
- baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
1384
- } else {
1385
- var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + '', object, source, stack) : undefined;
1386
- if (newValue === undefined) {
1387
- newValue = srcValue;
1388
- }
1389
- assignMergeValue(object, key, newValue);
1390
- }
1391
- }, keysIn);
1392
- }
1393
-
1394
- function castFunction(value) {
1395
- return typeof value == 'function' ? value : identity;
1396
- }
1397
-
1398
- function forEach(collection, iteratee) {
1399
- var func = isArray(collection) ? arrayEach : baseEach;
1400
- return func(collection, castFunction(iteratee));
1401
- }
1402
-
1403
- var mapTag = '[object Map]',
1404
- setTag = '[object Set]';
1405
- var objectProto = Object.prototype;
1406
- var hasOwnProperty = objectProto.hasOwnProperty;
1407
- function isEmpty(value) {
1408
- if (value == null) {
1409
- return true;
1410
- }
1411
- if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
1412
- return !value.length;
1413
- }
1414
- var tag = getTag(value);
1415
- if (tag == mapTag || tag == setTag) {
1416
- return !value.size;
1417
- }
1418
- if (isPrototype(value)) {
1419
- return !baseKeys(value).length;
1420
- }
1421
- for (var key in value) {
1422
- if (hasOwnProperty.call(value, key)) {
1423
- return false;
1424
- }
1425
- }
1426
- return true;
1427
- }
1428
-
1429
- var merge = createAssigner(function (object, source, srcIndex) {
1430
- baseMerge(object, source, srcIndex);
1431
- });
1432
-
1433
- let RuntimeDataSourceStatus = /*#__PURE__*/function (RuntimeDataSourceStatus) {
1434
- RuntimeDataSourceStatus["Initial"] = "init";
1435
- RuntimeDataSourceStatus["Loading"] = "loading";
1436
- RuntimeDataSourceStatus["Loaded"] = "loaded";
1437
- RuntimeDataSourceStatus["Error"] = "error";
1438
- return RuntimeDataSourceStatus;
1439
- }({});
1440
-
1441
- class RuntimeDataSourceItem {
1442
- _data;
1443
- _error;
1444
- _status = RuntimeDataSourceStatus.Initial;
1445
- _dataSourceConfig;
1446
- _request;
1447
- _context;
1448
- _options;
1449
- constructor(dataSourceConfig, request, context) {
1450
- this._dataSourceConfig = dataSourceConfig;
1451
- this._request = request;
1452
- this._context = context;
1453
- }
1454
- get data() {
1455
- return this._data;
1456
- }
1457
- get error() {
1458
- return this._error;
1459
- }
1460
- get status() {
1461
- return this._status;
1462
- }
1463
- get isLoading() {
1464
- return this._status === RuntimeDataSourceStatus.Loading;
1465
- }
1466
- async load(params) {
1467
- if (!this._dataSourceConfig) return;
1468
- if (!this._request) {
1469
- this._error = new Error(`no ${this._dataSourceConfig.type} handler provide`);
1470
- this._status = RuntimeDataSourceStatus.Error;
1471
- throw this._error;
1472
- }
1473
- if (this._dataSourceConfig.type === 'urlParams') {
1474
- const response = await this._request(this._context);
1475
- this._context.setState({
1476
- [this._dataSourceConfig.id]: response
1477
- });
1478
- this._data = response;
1479
- this._status = RuntimeDataSourceStatus.Loaded;
1480
- return response;
1481
- }
1482
- if (!this._dataSourceConfig.options) {
1483
- throw new Error(`${this._dataSourceConfig.id} has no options`);
1484
- }
1485
- if (typeof this._dataSourceConfig.options === 'function') {
1486
- this._options = this._dataSourceConfig.options();
1487
- }
1488
- if (!this._options) {
1489
- throw new Error(`${this._dataSourceConfig.id} options transform error`);
1490
- }
1491
- let shouldFetch = true;
1492
- let fetchOptions = this._options;
1493
- if (params) {
1494
- fetchOptions.params = merge(fetchOptions.params, params);
1495
- }
1496
- if (this._dataSourceConfig.shouldFetch) {
1497
- if (typeof this._dataSourceConfig.shouldFetch === 'function') {
1498
- shouldFetch = this._dataSourceConfig.shouldFetch(fetchOptions);
1499
- } else if (typeof this._dataSourceConfig.shouldFetch === 'boolean') {
1500
- shouldFetch = this._dataSourceConfig.shouldFetch;
1501
- }
1502
- }
1503
- if (!shouldFetch) {
1504
- this._status = RuntimeDataSourceStatus.Error;
1505
- this._error = new Error(`the ${this._dataSourceConfig.id} request should not fetch, please check the condition`);
1506
- console.warn(this.error);
1507
- return;
1508
- }
1509
- if (this._dataSourceConfig.willFetch) {
1510
- try {
1511
- fetchOptions = await this._dataSourceConfig.willFetch(this._options);
1512
- } catch (error) {
1513
- console.error(error);
1514
- }
1515
- }
1516
- const dataHandler = this._dataSourceConfig.dataHandler;
1517
- const {
1518
- errorHandler
1519
- } = this._dataSourceConfig;
1520
- try {
1521
- this._status = RuntimeDataSourceStatus.Loading;
1522
- const result = await this._request(fetchOptions, this._context).then(dataHandler, errorHandler);
1523
- this._data = result;
1524
- this._status = RuntimeDataSourceStatus.Loaded;
1525
- this._context.setState({
1526
- UNSTABLE_dataSourceUpdatedAt: Date.now(),
1527
- [this._dataSourceConfig.id]: result
1528
- });
1529
- return this._data;
1530
- } catch (error) {
1531
- this._error = error;
1532
- this._status = RuntimeDataSourceStatus.Error;
1533
- this._context.setState({
1534
- UNSTABLE_dataSourceUpdatedAt: Date.now(),
1535
- [`UNSTABLE_${this._dataSourceConfig.id}_error`]: error
1536
- });
1537
- throw error;
1538
- }
1539
- }
1540
- }
1541
-
1542
- const defaultDataHandler = async response => response.data;
1543
- const defaultWillFetch = options => options;
1544
- const getRequestHandler = (ds, requestHandlersMap) => {
1545
- if (ds.type === 'custom') {
1546
- return ds.requestHandler;
1547
- }
1548
- return requestHandlersMap[ds.type || 'fetch'];
1549
- };
1550
- const promiseSettled = (Promise.allSettled ? Promise.allSettled.bind(Promise) : null) || (promises => {
1551
- return Promise.all(promises.map(p => {
1552
- return p.then(v => ({
1553
- status: 'fulfilled',
1554
- value: v
1555
- })).catch(e => ({
1556
- status: 'rejected',
1557
- reason: e
1558
- }));
1559
- }));
1560
- });
1561
-
1562
- function isObject(obj) {
1563
- return Object.prototype.toString.call(obj).indexOf('Object') !== -1;
1564
- }
1565
- const transformExpression = (code, context) => {
1566
- if (code === undefined) {
1567
- return () => {};
1568
- }
1569
- if (code === '') {
1570
- return () => '';
1571
- }
1572
- try {
1573
- return new Function(`return (${code})`).call(context);
1574
- } catch (error) {
1575
- console.error(`transformExpression error, code is ${code}, context is ${context}, error is ${error}`);
1576
- }
1577
- };
1578
- const transformFunction = (code, context) => {
1579
- if (code === undefined) {
1580
- return () => {};
1581
- }
1582
- if (code === '') {
1583
- return () => '';
1584
- }
1585
- try {
1586
- return new Function(`return (${code})`).call(context).bind(context);
1587
- } catch (error) {
1588
- console.error(`transformFunction error, code is ${code}, context is ${context}, error is ${error}`);
1589
- }
1590
- };
1591
- const transformBoolStr = str => {
1592
- return str !== 'false';
1593
- };
1594
- const getRuntimeJsValue = (value, context) => {
1595
- if (!['JSExpression', 'JSFunction'].includes(value.type)) {
1596
- console.error(`translate error, value is ${JSON.stringify(value)}`);
1597
- return '';
1598
- }
1599
- const code = value.compiled || value.value;
1600
- return value.type === 'JSFunction' ? transformFunction(code, context) : transformExpression(code, context);
1601
- };
1602
- const getRuntimeBaseValue = (type, value) => {
1603
- switch (type) {
1604
- case 'string':
1605
- return `${value}`;
1606
- case 'boolean':
1607
- return typeof value === 'string' ? transformBoolStr(value) : !!value;
1608
- case 'number':
1609
- return Number(value);
1610
- default:
1611
- return value;
1612
- }
1613
- };
1614
- const getRuntimeValueFromConfig = (type, value, context) => {
1615
- if (value === undefined) {
1616
- return undefined;
1617
- }
1618
- if (core.isJSExpression(value) || core.isJSFunction(value)) {
1619
- return getRuntimeBaseValue(type, getRuntimeJsValue(value, context));
1620
- }
1621
- return value;
1622
- };
1623
- const buildJsonObj = (params, context) => {
1624
- if (core.isJSExpression(params)) {
1625
- return transformExpression(params.value, context);
1626
- } else if (isObject(params)) {
1627
- const newParams = {};
1628
- for (const [name, param] of Object.entries(params)) {
1629
- if (core.isJSExpression(param)) {
1630
- newParams[name] = transformExpression(param?.value, context);
1631
- } else if (isObject(param)) {
1632
- newParams[name] = buildJsonObj(param, context);
1633
- } else {
1634
- newParams[name] = param;
1635
- }
1636
- }
1637
- return newParams;
1638
- }
1639
- return params;
1640
- };
1641
- const buildShouldFetch = (ds, context) => {
1642
- if (!ds.options || !ds.shouldFetch) {
1643
- return true;
1644
- }
1645
- if (core.isJSExpression(ds.shouldFetch) || core.isJSFunction(ds.shouldFetch)) {
1646
- return getRuntimeJsValue(ds.shouldFetch, context);
1647
- }
1648
- return getRuntimeBaseValue('boolean', ds.shouldFetch);
1649
- };
1650
- const buildOptions = (ds, context) => {
1651
- const {
1652
- options
1653
- } = ds;
1654
- if (!options) return undefined;
1655
- return () => {
1656
- const fetchOptions = {
1657
- uri: '',
1658
- params: {},
1659
- method: 'GET',
1660
- isCors: true,
1661
- timeout: 5000,
1662
- headers: undefined,
1663
- v: '1.0'
1664
- };
1665
- Object.keys(options).forEach(key => {
1666
- switch (key) {
1667
- case 'uri':
1668
- fetchOptions.uri = getRuntimeValueFromConfig('string', options.uri, context);
1669
- break;
1670
- case 'params':
1671
- fetchOptions.params = buildJsonObj(options.params, context);
1672
- break;
1673
- case 'method':
1674
- fetchOptions.method = getRuntimeValueFromConfig('string', options.method, context);
1675
- break;
1676
- case 'isCors':
1677
- fetchOptions.isCors = getRuntimeValueFromConfig('boolean', options.isCors, context);
1678
- break;
1679
- case 'timeout':
1680
- fetchOptions.timeout = getRuntimeValueFromConfig('number', options.timeout, context);
1681
- break;
1682
- case 'headers':
1683
- fetchOptions.headers = buildJsonObj(options.headers, context);
1684
- break;
1685
- case 'v':
1686
- fetchOptions.v = getRuntimeValueFromConfig('string', options.v, context);
1687
- break;
1688
- default:
1689
- fetchOptions[key] = getRuntimeValueFromConfig('unknown', options[key], context);
1690
- }
1691
- });
1692
- return fetchOptions;
1693
- };
1694
- };
1695
-
1696
- const adapt2Runtime = (dataSource, context, extraConfig) => {
1697
- const {
1698
- list: interpretConfigList,
1699
- dataHandler: interpretDataHandler
1700
- } = dataSource;
1701
- const dataHandler = interpretDataHandler ? getRuntimeJsValue(interpretDataHandler, context) : undefined;
1702
- if (!interpretConfigList || !interpretConfigList.length) {
1703
- return {
1704
- list: [],
1705
- dataHandler
1706
- };
1707
- }
1708
- const list = interpretConfigList.map(el => {
1709
- const {
1710
- defaultDataHandler: customDataHandler
1711
- } = extraConfig;
1712
- const finalDataHandler = customDataHandler || defaultDataHandler;
1713
- return {
1714
- id: el.id,
1715
- isInit: getRuntimeValueFromConfig('boolean', el.isInit, context),
1716
- isSync: getRuntimeValueFromConfig('boolean', el.isSync, context),
1717
- type: el.type || 'fetch',
1718
- willFetch: el.willFetch ? getRuntimeJsValue(el.willFetch, context) : defaultWillFetch,
1719
- shouldFetch: buildShouldFetch(el, context),
1720
- dataHandler: el.dataHandler ? getRuntimeJsValue(el.dataHandler, context) : finalDataHandler,
1721
- errorHandler: el.errorHandler ? getRuntimeJsValue(el.errorHandler, context) : undefined,
1722
- requestHandler: el.requestHandler ? getRuntimeJsValue(el.requestHandler, context) : undefined,
1723
- options: buildOptions(el, context)
1724
- };
1725
- });
1726
- return {
1727
- list,
1728
- dataHandler
1729
- };
1730
- };
1731
-
1732
- const reloadDataSourceFactory = (dataSource, dataSourceMap, dataHandler) => {
1733
- return async () => {
1734
- const allAsyncLoadings = [];
1735
- dataSource.list.filter(el => el.type === 'urlParams' && isInit(el)).forEach(el => {
1736
- dataSourceMap[el.id].load();
1737
- });
1738
- const remainRuntimeDataSourceList = dataSource.list.filter(el => el.type !== 'urlParams');
1739
- for (const ds of remainRuntimeDataSourceList) {
1740
- if (!ds.options) {
1741
- continue;
1742
- }
1743
- if (
1744
- isInit(ds) && !ds.isSync) {
1745
- allAsyncLoadings.push(dataSourceMap[ds.id].load());
1746
- }
1747
- }
1748
- for (const ds of remainRuntimeDataSourceList) {
1749
- if (!ds.options) {
1750
- continue;
1751
- }
1752
- if (
1753
- isInit(ds) && ds.isSync) {
1754
- try {
1755
- await dataSourceMap[ds.id].load();
1756
- } catch (e) {
1757
- console.error(e);
1758
- }
1759
- }
1760
- }
1761
- await promiseSettled(allAsyncLoadings);
1762
- if (dataHandler) {
1763
- dataHandler(dataSourceMap);
1764
- }
1765
- };
1766
- };
1767
- function isInit(ds) {
1768
- return typeof ds.isInit === 'function' ? ds.isInit() : ds.isInit ?? true;
1769
- }
1770
-
1771
- var createDataSourceEngine = (dataSource, context, extraConfig = {
1772
- requestHandlersMap: {}
1773
- }) => {
1774
- const {
1775
- requestHandlersMap
1776
- } = extraConfig;
1777
- const runtimeDataSource = adapt2Runtime(dataSource, context, {
1778
- defaultDataHandler: extraConfig.defaultDataHandler
1779
- });
1780
- const dataSourceMap = runtimeDataSource.list.reduce((prev, current) => {
1781
- prev[current.id] = new RuntimeDataSourceItem(current, getRequestHandler(current, requestHandlersMap), context);
1782
- return prev;
1783
- }, {});
1784
- return {
1785
- dataSourceMap,
1786
- reloadDataSource: reloadDataSourceFactory(runtimeDataSource, dataSourceMap, runtimeDataSource.dataHandler)
1787
- };
1788
- };
1789
-
1790
- const RendererContext = /*#__PURE__*/react.createContext({});
1791
- const useRendererContext = () => {
1792
- try {
1793
- return react.useContext(RendererContext);
1794
- } catch (error) {
1795
- console.warn('useRendererContext must be used within a RendererContextProvider');
1796
- }
1797
- return {};
1798
- };
1799
- function contextFactory() {
1800
- let context = window.__appContext;
1801
- if (!context) {
1802
- context = /*#__PURE__*/react.createContext({});
1803
- window.__appContext = context;
1804
- }
1805
- return context;
1806
- }
1807
-
1808
- const classnames = (...args) => {
1809
- return args.filter(Boolean).join(' ');
1810
- };
1811
-
1812
- const logger = core.createLogger('Renderer');
1813
-
1814
- const PropTypes2 = true;
1815
- function inSameDomain() {
1816
- try {
1817
- return window.parent !== window && window.parent.location.host === window.location.host;
1818
- } catch (e) {
1819
- return false;
1820
- }
1821
- }
1822
- function getFileCssName(fileName) {
1823
- if (!fileName) {
1824
- return;
1825
- }
1826
- const name = fileName.replace(/([A-Z])/g, '-$1').toLowerCase();
1827
- return `lce-${name}`.split('-').filter(p => !!p).join('-');
1828
- }
1829
- const isSchema = schema => {
1830
- if (!schema) {
1831
- return false;
1832
- }
1833
- if (schema.componentName === 'Leaf' || schema.componentName === 'Slot') {
1834
- return true;
1835
- }
1836
- if (Array.isArray(schema)) {
1837
- return schema.every(item => isSchema(item));
1838
- }
1839
- const isValidProps = props => {
1840
- if (!props) {
1841
- return false;
1842
- }
1843
- return typeof schema.props === 'object' && !Array.isArray(props);
1844
- };
1845
- return !!(schema.componentName && isValidProps(schema.props));
1846
- };
1847
- const getValue = (obj, path, defaultValue = {}) => {
1848
- if (Array.isArray(obj)) {
1849
- return defaultValue;
1850
- }
1851
- if (!obj || typeof obj !== 'object') {
1852
- return defaultValue;
1853
- }
1854
- const res = path.split('.').reduce((pre, cur) => {
1855
- return pre && pre[cur];
1856
- }, obj);
1857
- if (res === undefined) {
1858
- return defaultValue;
1859
- }
1860
- return res;
1861
- };
1862
- function transformArrayToMap(arr, key, overwrite = true) {
1863
- if (!arr || !Array.isArray(arr)) {
1864
- return {};
1865
- }
1866
- const res = {};
1867
- arr.forEach(item => {
1868
- const curKey = item[key];
1869
- if (item[key] === undefined) {
1870
- return;
1871
- }
1872
- if (res[curKey] && !overwrite) {
1873
- return;
1874
- }
1875
- res[curKey] = item;
1876
- });
1877
- return res;
1878
- }
1879
- const parseData = (schema, self, options = {}) => {
1880
- if (core.isJSExpression(schema)) {
1881
- return parseExpression({
1882
- str: schema,
1883
- self,
1884
- thisRequired: true,
1885
- logScope: options.logScope
1886
- });
1887
- }
1888
- if (typeof schema === 'string') {
1889
- return schema.trim();
1890
- } else if (Array.isArray(schema)) {
1891
- return schema.map(item => parseData(item, self, options));
1892
- } else if (typeof schema === 'function') {
1893
- return schema.bind(self);
1894
- } else if (typeof schema === 'object') {
1895
- if (!schema) {
1896
- return schema;
1897
- }
1898
- const res = {};
1899
- Object.entries(schema).forEach(([key, val]) => {
1900
- if (key.startsWith('__')) {
1901
- return;
1902
- }
1903
- res[key] = parseData(val, self, options);
1904
- });
1905
- return res;
1906
- }
1907
- return schema;
1908
- };
1909
- const isUseLoop = (loop, isDesignMode) => {
1910
- if (!isDesignMode) {
1911
- return true;
1912
- }
1913
- if (!Array.isArray(loop)) {
1914
- return false;
1915
- }
1916
- return loop.length > 0;
1917
- };
1918
- function checkPropTypes(value, name, rule, componentName) {
1919
- let ruleFunction = rule;
1920
- if (typeof rule === 'string') {
1921
- ruleFunction = new Function(`"use strict"; const PropTypes = arguments[0]; return ${rule}`)(PropTypes2);
1922
- }
1923
- if (!ruleFunction || typeof ruleFunction !== 'function') {
1924
- logger.warn('checkPropTypes should have a function type rule argument');
1925
- return true;
1926
- }
1927
- const err = ruleFunction({
1928
- [name]: value
1929
- }, name, componentName, 'prop', null
1930
- );
1931
- if (err) {
1932
- logger.warn(err);
1933
- }
1934
- return !err;
1935
- }
1936
- function transformStringToFunction(str) {
1937
- if (typeof str !== 'string') {
1938
- return str;
1939
- }
1940
- if (inSameDomain() && window.parent.__newFunc) {
1941
- return window.parent.__newFunc(`"use strict"; return ${str}`)();
1942
- } else {
1943
- return new Function(`"use strict"; return ${str}`)();
1944
- }
1945
- }
1946
- function parseExpression(a, b, c = false) {
1947
- let str;
1948
- let self;
1949
- let thisRequired;
1950
- let logScope;
1951
- if (typeof a === 'object' && b === undefined) {
1952
- str = a.str;
1953
- self = a.self;
1954
- thisRequired = a.thisRequired;
1955
- logScope = a.logScope;
1956
- } else {
1957
- str = a;
1958
- self = b;
1959
- thisRequired = c;
1960
- }
1961
- try {
1962
- const contextArr = ['"use strict";', 'var __self = arguments[0];'];
1963
- contextArr.push('return ');
1964
- let tarStr;
1965
- tarStr = (str.value || '').trim();
1966
- tarStr = tarStr.replace(/this(\W|$)/g, (_a, b) => `__self${b}`);
1967
- tarStr = contextArr.join('\n') + tarStr;
1968
- if (inSameDomain() && window.parent.__newFunc) {
1969
- return window.parent.__newFunc(tarStr)(self);
1970
- }
1971
- const code = `with(${thisRequired ? '{}' : '$scope || {}'}) { ${tarStr} }`;
1972
- return new Function('$scope', code)(self);
1973
- } catch (err) {
1974
- logger.error(`${logScope || ''} parseExpression.error`, err, str, self?.__self ?? self);
1975
- return undefined;
1976
- }
1977
- }
1978
- function parseThisRequiredExpression(str, self) {
1979
- return parseExpression(str, self, true);
1980
- }
1981
- function isString(str) {
1982
- return {}.toString.call(str) === '[object String]';
1983
- }
1984
- function capitalizeFirstLetter(word) {
1985
- if (!word || !isString(word) || word.length === 0) {
1986
- return word;
1987
- }
1988
- return word[0].toUpperCase() + word.slice(1);
1989
- }
1990
- const isReactClass = obj => {
1991
- return obj && obj.prototype && (obj.prototype.isReactComponent || obj.prototype instanceof react.Component);
1992
- };
1993
- function isReactComponent(obj) {
1994
- return obj && (isReactClass(obj) || typeof obj === 'function');
1995
- }
1996
- function serializeParams(obj) {
1997
- const result = [];
1998
- forEach(obj, (val, key) => {
1999
- if (val === null || val === undefined || val === '') {
2000
- return;
2001
- }
2002
- if (typeof val === 'object') {
2003
- result.push(`${key}=${encodeURIComponent(JSON.stringify(val))}`);
2004
- } else {
2005
- result.push(`${key}=${encodeURIComponent(val)}`);
2006
- }
2007
- });
2008
- return result.join('&');
2009
- }
2010
-
2011
- const excludePropertyNames = ['$$typeof', 'render', 'defaultProps', 'props', 'length', 'prototype', 'name', 'caller', 'callee', 'arguments'];
2012
- const cloneEnumerableProperty = (target, origin, excludes = excludePropertyNames) => {
2013
- const compExtraPropertyNames = Object.keys(origin).filter(d => !excludes.includes(d));
2014
- compExtraPropertyNames.forEach(d => {
2015
- target[d] = origin[d];
2016
- });
2017
- return target;
2018
- };
2019
- const createForwardRefHocElement = (Wrapper, Comp) => {
2020
- const WrapperComponent = cloneEnumerableProperty(/*#__PURE__*/react.forwardRef((props, ref) => {
2021
- return /*#__PURE__*/react.createElement(Wrapper, {
2022
- ...props,
2023
- forwardRef: ref
2024
- });
2025
- }), Comp);
2026
- WrapperComponent.displayName = Comp.displayName;
2027
- return WrapperComponent;
2028
- };
2029
-
2030
- const patchDidCatch = (Comp, {
2031
- baseRenderer
2032
- }) => {
2033
- if (Comp.patchedCatch) {
2034
- return;
2035
- }
2036
- Comp.patchedCatch = true;
2037
- const originalDidCatch = Comp.prototype.componentDidCatch;
2038
- Comp.prototype.componentDidCatch = function didCatch(error, errorInfo) {
2039
- this.setState({
2040
- engineRenderError: true,
2041
- error
2042
- });
2043
- if (originalDidCatch && typeof originalDidCatch === 'function') {
2044
- originalDidCatch.call(this, error, errorInfo);
2045
- }
2046
- };
2047
- const {
2048
- engine
2049
- } = baseRenderer.context;
2050
- const originRender = Comp.prototype.render;
2051
- Comp.prototype.render = function () {
2052
- if (this.state && this.state.engineRenderError) {
2053
- this.state.engineRenderError = false;
2054
- return engine.createElement(engine.getFaultComponent(), {
2055
- ...this.props,
2056
- error: this.state.error,
2057
- componentName: this.props._componentName
2058
- });
2059
- }
2060
- return originRender.call(this);
2061
- };
2062
- if (!(Comp.prototype instanceof react.PureComponent)) {
2063
- const originShouldComponentUpdate = Comp.prototype.shouldComponentUpdate;
2064
- Comp.prototype.shouldComponentUpdate = function (nextProps, nextState) {
2065
- if (nextState && nextState.engineRenderError) {
2066
- return true;
2067
- }
2068
- return originShouldComponentUpdate ? originShouldComponentUpdate.call(this, nextProps, nextState) : true;
2069
- };
2070
- }
2071
- };
2072
- const cache$1 = new Map();
2073
- const compWrapper = (Comp, info) => {
2074
- if (Comp?.prototype?.isReactComponent || Comp?.prototype instanceof react.Component) {
2075
- patchDidCatch(Comp, info);
2076
- return Comp;
2077
- }
2078
- if (info.schema.id && cache$1.has(info.schema.id) && cache$1.get(info.schema.id)?.Comp === Comp) {
2079
- return cache$1.get(info.schema.id)?.WrapperComponent;
2080
- }
2081
- class Wrapper extends react.Component {
2082
- static displayName = Comp.displayName;
2083
- render() {
2084
- const {
2085
- forwardRef,
2086
- ...rest
2087
- } = this.props;
2088
- // @ts-ignore
2089
- return /*#__PURE__*/react.createElement(Comp, {
2090
- ...rest,
2091
- ref: forwardRef
2092
- });
2093
- }
2094
- }
2095
- patchDidCatch(Wrapper, info);
2096
- const WrapperComponent = createForwardRefHocElement(Wrapper, Comp);
2097
- info.schema.id && cache$1.set(info.schema.id, {
2098
- WrapperComponent,
2099
- Comp
2100
- });
2101
- return WrapperComponent;
2102
- };
2103
-
2104
- var RerenderType = /*#__PURE__*/function (RerenderType) {
2105
- RerenderType["All"] = "All";
2106
- RerenderType["ChildChanged"] = "ChildChanged";
2107
- RerenderType["PropsChanged"] = "PropsChanged";
2108
- RerenderType["VisibleChanged"] = "VisibleChanged";
2109
- RerenderType["MinimalRenderUnit"] = "MinimalRenderUnit";
2110
- return RerenderType;
2111
- }(RerenderType || {}); // 缓存 Leaf 层组件,防止重新渲染问题
2112
- class LeafCache {
2113
- /** 组件缓存 */
2114
- component = new Map();
2115
-
2116
- /**
2117
- * 状态缓存,场景:属性变化后,改组件被销毁,state 为空,没有展示修改后的属性
2118
- */
2119
- state = new Map();
2120
-
2121
- /**
2122
- * 订阅事件缓存,导致 rerender 的订阅事件
2123
- */
2124
- event = new Map();
2125
- ref = new Map();
2126
- constructor(documentId, device) {
2127
- this.documentId = documentId;
2128
- this.device = device;
2129
- }
2130
- }
2131
- let cache;
2132
-
2133
- /** 部分没有渲染的 node 节点进行兜底处理 or 渲染方式没有渲染 LeafWrapper */
2134
- const initRerenderEvent = ({
2135
- schema,
2136
- container,
2137
- getNode
2138
- }) => {
2139
- const leaf = getNode?.(schema.id);
2140
- if (!leaf || cache.event.get(schema.id)?.clear || leaf === cache.event.get(schema.id)) {
2141
- return;
2142
- }
2143
- cache.event.get(schema.id)?.dispose.forEach(disposeFn => disposeFn && disposeFn());
2144
- const debounceRerender = debounce(() => {
2145
- container.rerender();
2146
- }, 20);
2147
- cache.event.set(schema.id, {
2148
- clear: false,
2149
- leaf,
2150
- dispose: [leaf?.onPropChange?.(() => {
2151
- if (!container.autoRepaintNode) {
2152
- return;
2153
- }
2154
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onPropsChange make rerender`);
2155
- debounceRerender();
2156
- }), leaf?.onChildrenChange?.(() => {
2157
- if (!container.autoRepaintNode) {
2158
- return;
2159
- }
2160
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onChildrenChange make rerender`);
2161
- debounceRerender();
2162
- }), leaf?.onVisibleChange?.(() => {
2163
- if (!container.autoRepaintNode) {
2164
- return;
2165
- }
2166
- logger.log(`${schema.componentName}[${schema.id}] leaf not render in SimulatorRendererView, leaf onVisibleChange make rerender`);
2167
- debounceRerender();
2168
- })]
2169
- });
2170
- };
2171
-
2172
- /** 渲染的 node 节点全局注册事件清除 */
2173
- const clearRerenderEvent = id => {
2174
- if (cache.event.get(id)?.clear) {
2175
- return;
2176
- }
2177
- cache.event.get(id)?.dispose?.forEach(disposeFn => disposeFn && disposeFn());
2178
- cache.event.set(id, {
2179
- clear: true,
2180
- dispose: []
2181
- });
2182
- };
2183
-
2184
- // 给每个组件包裹一个 HOC Leaf,支持组件内部属性变化,自响应渲染
2185
- const leafWrapper = (Comp, {
2186
- schema,
2187
- baseRenderer,
2188
- componentInfo,
2189
- scope
2190
- }) => {
2191
- const {
2192
- __getComponentProps: getProps,
2193
- __getSchemaChildrenVirtualDom: getChildren,
2194
- __parseData
2195
- } = baseRenderer;
2196
- const {
2197
- engine
2198
- } = baseRenderer.context;
2199
- const host = baseRenderer.props?.__host;
2200
- const curDocumentId = baseRenderer.props?.documentId ?? '';
2201
- const curDevice = baseRenderer.props?.device ?? '';
2202
- const getNode = baseRenderer.props?.getNode;
2203
- const container = baseRenderer.props?.__container;
2204
- const setSchemaChangedSymbol = baseRenderer.props?.setSchemaChangedSymbol;
2205
- const designer = host?.designer;
2206
- const componentCacheId = schema.id;
2207
- if (!cache || curDocumentId && curDocumentId !== cache.documentId || curDevice && curDevice !== cache.device) {
2208
- cache?.event.forEach(event => {
2209
- event.dispose?.forEach(disposeFn => disposeFn && disposeFn());
2210
- });
2211
- cache = new LeafCache(curDocumentId, curDevice);
2212
- }
2213
-
2214
- // if (!isReactComponent(Comp)) {
2215
- // logger.error(`${schema.componentName} component may be has errors: `, Comp)
2216
- // }
2217
-
2218
- initRerenderEvent({
2219
- schema,
2220
- container,
2221
- getNode
2222
- });
2223
- if (curDocumentId && cache.component.has(componentCacheId) && cache.component.get(componentCacheId).Comp === Comp) {
2224
- return cache.component.get(componentCacheId).LeafWrapper;
2225
- }
2226
- class LeafHoc extends react.Component {
2227
- recordInfo = {};
2228
- curEventLeaf;
2229
- static displayName = schema.componentName;
2230
- disposeFunctions = [];
2231
- __component_tag = 'leafWrapper';
2232
- renderUnitInfo;
2233
-
2234
- // 最小渲染单元做防抖处理
2235
- makeUnitRenderDebounced = debounce(() => {
2236
- this.beforeRender(RerenderType.MinimalRenderUnit);
2237
- const schema = this.leaf?.export?.(core.TRANSFORM_STAGE.RENDER);
2238
- if (!schema) {
2239
- return;
2240
- }
2241
- const nextProps = getProps(schema, scope, Comp, componentInfo);
2242
- const children = getChildren(schema, scope, Comp);
2243
- const nextState = {
2244
- nodeProps: nextProps,
2245
- nodeChildren: children,
2246
- childrenInState: true
2247
- };
2248
- if ('children' in nextProps) {
2249
- nextState.nodeChildren = nextProps.children;
2250
- }
2251
- logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) MinimalRenderUnit Render!`);
2252
- this.setState(nextState);
2253
- }, 20);
2254
- constructor(props) {
2255
- super(props);
2256
- // 监听以下事件,当变化时更新自己
2257
- logger.log(`${schema.componentName}[${this.leaf?.id}] leaf render in SimulatorRendererView`);
2258
- componentCacheId && clearRerenderEvent(componentCacheId);
2259
- this.curEventLeaf = this.leaf;
2260
- cache.ref.set(componentCacheId, {
2261
- makeUnitRender: this.makeUnitRender
2262
- });
2263
- let cacheState = cache.state.get(componentCacheId);
2264
- if (!cacheState || cacheState.__tag !== props.__tag) {
2265
- cacheState = this.getDefaultState(props);
2266
- }
2267
- this.state = cacheState;
2268
- }
2269
- recordTime = () => {
2270
- if (!this.recordInfo.startTime) {
2271
- return;
2272
- }
2273
- const endTime = Date.now();
2274
- const nodeCount = host?.designer?.currentDocument?.getNodeCount?.();
2275
- const componentName = this.recordInfo.node?.componentName || this.leaf?.componentName || 'UnknownComponent';
2276
- designer?.postEvent(core.DESIGNER_EVENT.NODE_RENDER, {
2277
- componentName,
2278
- time: endTime - this.recordInfo.startTime,
2279
- type: this.recordInfo.type,
2280
- nodeCount
2281
- });
2282
- this.recordInfo.startTime = null;
2283
- };
2284
- makeUnitRender = () => {
2285
- this.makeUnitRenderDebounced();
2286
- };
2287
- get autoRepaintNode() {
2288
- return container?.autoRepaintNode;
2289
- }
2290
- componentDidUpdate() {
2291
- this.recordTime();
2292
- }
2293
- componentDidMount() {
2294
- const _leaf = this.leaf;
2295
- this.initOnPropsChangeEvent(_leaf);
2296
- this.initOnChildrenChangeEvent(_leaf);
2297
- this.initOnVisibleChangeEvent(_leaf);
2298
- this.recordTime();
2299
- }
2300
- getDefaultState(nextProps) {
2301
- const {
2302
- hidden = false,
2303
- condition = true
2304
- } = nextProps.__inner__ || this.leaf?.export?.(core.TRANSFORM_STAGE.RENDER) || {};
2305
- return {
2306
- nodeChildren: null,
2307
- childrenInState: false,
2308
- visible: !hidden,
2309
- condition: __parseData?.(condition, scope),
2310
- nodeCacheProps: {},
2311
- nodeProps: {}
2312
- };
2313
- }
2314
- setState(state) {
2315
- cache.state.set(componentCacheId, {
2316
- ...this.state,
2317
- ...state,
2318
- __tag: this.props.__tag
2319
- });
2320
- super.setState(state);
2321
- }
2322
-
2323
- /** 由于内部属性变化,在触发渲染前,会执行该函数 */
2324
- beforeRender(type, node) {
2325
- this.recordInfo.startTime = Date.now();
2326
- this.recordInfo.type = type;
2327
- this.recordInfo.node = node;
2328
- setSchemaChangedSymbol?.(true);
2329
- }
2330
- judgeMiniUnitRender() {
2331
- if (!this.renderUnitInfo) {
2332
- this.getRenderUnitInfo();
2333
- }
2334
- const renderUnitInfo = this.renderUnitInfo || {
2335
- singleRender: true
2336
- };
2337
- if (renderUnitInfo.singleRender) {
2338
- return;
2339
- }
2340
- const ref = cache.ref.get(renderUnitInfo.minimalUnitId);
2341
- if (!ref) {
2342
- logger.log('Cant find minimalRenderUnit ref! This make rerender!');
2343
- container?.rerender();
2344
- return;
2345
- }
2346
- logger.log(`${this.leaf?.componentName}(${this.leaf?.id}) need render, make its minimalRenderUnit ${renderUnitInfo.minimalUnitName}(${renderUnitInfo.minimalUnitId})`);
2347
- ref.makeUnitRender();
2348
- }
2349
- getRenderUnitInfo(leaf = this.leaf) {
2350
- // leaf 在低代码组件中存在 mock 的情况,退出最小渲染单元判断
2351
- if (!leaf || typeof leaf.isRoot !== 'function') {
2352
- return;
2353
- }
2354
- if (leaf.isRoot) {
2355
- this.renderUnitInfo = {
2356
- singleRender: true,
2357
- ...(this.renderUnitInfo || {})
2358
- };
2359
- }
2360
- if (leaf.componentMeta.isMinimalRenderUnit) {
2361
- this.renderUnitInfo = {
2362
- minimalUnitId: leaf.id,
2363
- minimalUnitName: leaf.componentName,
2364
- singleRender: false
2365
- };
2366
- }
2367
- if (leaf.hasLoop()) {
2368
- // 含有循环配置的元素,父元素是最小渲染单元
2369
- this.renderUnitInfo = {
2370
- minimalUnitId: leaf?.parent?.id,
2371
- minimalUnitName: leaf?.parent?.componentName,
2372
- singleRender: false
2373
- };
2374
- }
2375
- if (leaf.parent) {
2376
- this.getRenderUnitInfo(leaf.parent);
2377
- }
2378
- }
2379
- UNSAFE_componentWillReceiveProps(nextProps) {
2380
- const {
2381
- componentId
2382
- } = nextProps;
2383
- if (nextProps.__tag === this.props.__tag) {
2384
- return null;
2385
- }
2386
- const _leaf = getNode?.(componentId);
2387
- if (_leaf && this.curEventLeaf && _leaf !== this.curEventLeaf) {
2388
- this.disposeFunctions.forEach(fn => fn());
2389
- this.disposeFunctions = [];
2390
- this.initOnChildrenChangeEvent(_leaf);
2391
- this.initOnPropsChangeEvent(_leaf);
2392
- this.initOnVisibleChangeEvent(_leaf);
2393
- this.curEventLeaf = _leaf;
2394
- }
2395
- const {
2396
- visible,
2397
- ...resetState
2398
- } = this.getDefaultState(nextProps);
2399
- this.setState(resetState);
2400
- }
2401
-
2402
- /** 监听参数变化 */
2403
- initOnPropsChangeEvent(leaf = this.leaf) {
2404
- // const handlePropsChange = debounce((propChangeInfo: PropChangeInfo) => {
2405
- const handlePropsChange = debounce(propChangeInfo => {
2406
- const {
2407
- key,
2408
- newValue = null
2409
- } = propChangeInfo;
2410
- const node = leaf;
2411
- if (key === '___condition___') {
2412
- const {
2413
- condition = true
2414
- } = this.leaf?.export(core.TRANSFORM_STAGE.RENDER) || {};
2415
- const conditionValue = __parseData?.(condition, scope);
2416
- logger.log(`key is ___condition___, change condition value to [${condition}]`);
2417
- // 条件表达式改变
2418
- this.setState({
2419
- condition: conditionValue
2420
- });
2421
- return;
2422
- }
2423
-
2424
- // 如果循坏条件变化,从根节点重新渲染
2425
- // 目前多层循坏无法判断需要从哪一层开始渲染,故先粗暴解决
2426
- if (key === '___loop___') {
2427
- logger.log('key is ___loop___, render a page!');
2428
- container?.rerender();
2429
- // 由于 scope 变化,需要清空缓存,使用新的 scope
2430
- cache.component.delete(componentCacheId);
2431
- return;
2432
- }
2433
- this.beforeRender(RerenderType.PropsChanged);
2434
- const {
2435
- state
2436
- } = this;
2437
- const {
2438
- nodeCacheProps
2439
- } = state;
2440
- const nodeProps = getProps(node?.export?.(core.TRANSFORM_STAGE.RENDER), scope, Comp, componentInfo);
2441
- if (key && !(key in nodeProps) && key in this.props) {
2442
- // 当 key 在 this.props 中时,且不存在在计算值中,需要用 newValue 覆盖掉 this.props 的取值
2443
- nodeCacheProps[key] = newValue;
2444
- }
2445
- logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onPropsChange!`, nodeProps, nodeCacheProps, key, newValue);
2446
- this.setState('children' in nodeProps ? {
2447
- nodeChildren: nodeProps.children,
2448
- nodeProps,
2449
- childrenInState: true,
2450
- nodeCacheProps
2451
- } : {
2452
- nodeProps,
2453
- nodeCacheProps
2454
- });
2455
- this.judgeMiniUnitRender();
2456
- });
2457
- // const dispose = leaf?.onPropChange?.((propChangeInfo: IPublicTypePropChangeOptions) => {
2458
- const dispose = leaf?.onPropChange?.(propChangeInfo => {
2459
- if (!this.autoRepaintNode) {
2460
- return;
2461
- }
2462
- handlePropsChange(propChangeInfo);
2463
- });
2464
- dispose && this.disposeFunctions.push(dispose);
2465
- }
2466
-
2467
- /**
2468
- * 监听显隐变化
2469
- */
2470
- initOnVisibleChangeEvent(leaf = this.leaf) {
2471
- const dispose = leaf?.onVisibleChange?.(flag => {
2472
- if (!this.autoRepaintNode) {
2473
- return;
2474
- }
2475
- if (this.state.visible === flag) {
2476
- return;
2477
- }
2478
- logger.log(`${leaf?.componentName}[${this.leaf?.id}] component trigger onVisibleChange(${flag}) event`);
2479
- this.beforeRender(RerenderType.VisibleChanged);
2480
- this.setState({
2481
- visible: flag
2482
- });
2483
- this.judgeMiniUnitRender();
2484
- });
2485
- dispose && this.disposeFunctions.push(dispose);
2486
- }
2487
-
2488
- /**
2489
- * 监听子元素变化(拖拽,删除...)
2490
- */
2491
- initOnChildrenChangeEvent(leaf = this.leaf) {
2492
- const dispose = leaf?.onChildrenChange?.(param => {
2493
- if (!this.autoRepaintNode) {
2494
- return;
2495
- }
2496
- const {
2497
- type,
2498
- node
2499
- } = param || {};
2500
- this.beforeRender(`${RerenderType.ChildChanged}-${type}`, node);
2501
- // TODO: 缓存同级其他元素的 children。
2502
- // 缓存二级 children Next 查询筛选组件有问题
2503
- // 缓存一级 children Next Tab 组件有问题
2504
- const nextChild = getChildren(leaf?.export?.(core.TRANSFORM_STAGE.RENDER), scope, Comp);
2505
- logger.log(`${schema.componentName}[${this.leaf?.id}] component trigger onChildrenChange event`, nextChild);
2506
- this.setState({
2507
- nodeChildren: nextChild,
2508
- childrenInState: true
2509
- });
2510
- this.judgeMiniUnitRender();
2511
- });
2512
- dispose && this.disposeFunctions.push(dispose);
2513
- }
2514
- componentWillUnmount() {
2515
- this.disposeFunctions.forEach(fn => fn());
2516
- }
2517
- get hasChildren() {
2518
- if (!this.state.childrenInState) {
2519
- return 'children' in this.props;
2520
- }
2521
- return true;
2522
- }
2523
- get children() {
2524
- if (this.state.childrenInState) {
2525
- return this.state.nodeChildren;
2526
- }
2527
- if (this.props.children && !Array.isArray(this.props.children)) {
2528
- return [this.props.children];
2529
- }
2530
- if (this.props.children && this.props.children.length) {
2531
- return this.props.children;
2532
- }
2533
- return this.props.children;
2534
- }
2535
- get leaf() {
2536
- // if (this.props._leaf?.isMock) {
2537
- // // 低代码组件作为一个整体更新,其内部的组件不需要监听相关事件
2538
- // return undefined
2539
- // }
2540
-
2541
- return getNode?.(componentCacheId);
2542
- }
2543
- render() {
2544
- if (!this.state.visible || !this.state.condition) {
2545
- return null;
2546
- }
2547
- const {
2548
- forwardRef,
2549
- ...rest
2550
- } = this.props;
2551
- const compProps = {
2552
- ...rest,
2553
- ...(this.state.nodeCacheProps || {}),
2554
- ...(this.state.nodeProps || {}),
2555
- children: [],
2556
- __id: this.leaf?.id,
2557
- ref: forwardRef
2558
- };
2559
- delete compProps.__inner__;
2560
- if (this.hasChildren) {
2561
- return engine.createElement(Comp, compProps, this.children);
2562
- }
2563
- return engine.createElement(Comp, compProps);
2564
- }
2565
- }
2566
- const LeafWrapper = createForwardRefHocElement(LeafHoc, Comp);
2567
- cache.component.set(componentCacheId, {
2568
- LeafWrapper,
2569
- Comp
2570
- });
2571
- return LeafWrapper;
2572
- };
2573
-
2574
- function buildUrl(dataAPI, params) {
2575
- const paramStr = serializeParams(params);
2576
- if (paramStr) {
2577
- return dataAPI.indexOf('?') > 0 ? `${dataAPI}&${paramStr}` : `${dataAPI}?${paramStr}`;
2578
- }
2579
- return dataAPI;
2580
- }
2581
- function get(dataAPI, params = {}, headers = {}, otherProps = {}) {
2582
- const processedHeaders = {
2583
- Accept: 'application/json',
2584
- ...headers
2585
- };
2586
- const url = buildUrl(dataAPI, params);
2587
- return request(url, 'GET', null, processedHeaders, otherProps);
2588
- }
2589
- function post(dataAPI, params = {}, headers = {}, otherProps = {}) {
2590
- const processedHeaders = {
2591
- Accept: 'application/json',
2592
- 'Content-Type': 'application/x-www-form-urlencoded',
2593
- ...headers
2594
- };
2595
- const body = processedHeaders['Content-Type'].indexOf('application/json') > -1 || Array.isArray(params) ? JSON.stringify(params) : serializeParams(params);
2596
- return request(dataAPI, 'POST', body, processedHeaders, otherProps);
2597
- }
2598
- function request(dataAPI, method = 'GET', data, headers = {}, otherProps = {}) {
2599
- let processedHeaders = headers || {};
2600
- let payload = data;
2601
- if (method === 'PUT' || method === 'DELETE') {
2602
- processedHeaders = {
2603
- Accept: 'application/json',
2604
- 'Content-Type': 'application/json',
2605
- ...processedHeaders
2606
- };
2607
- payload = JSON.stringify(payload || {});
2608
- }
2609
- return new Promise((resolve, reject) => {
2610
- if (otherProps.timeout) {
2611
- setTimeout(() => {
2612
- reject(new Error('timeout'));
2613
- }, otherProps.timeout);
2614
- }
2615
- fetch(dataAPI, {
2616
- method,
2617
- credentials: 'include',
2618
- headers: processedHeaders,
2619
- body: payload,
2620
- ...otherProps
2621
- }).then(response => {
2622
- switch (response.status) {
2623
- case 200:
2624
- case 201:
2625
- case 202:
2626
- return response.json();
2627
- case 204:
2628
- if (method === 'DELETE') {
2629
- return {
2630
- success: true
2631
- };
2632
- } else {
2633
- return {
2634
- __success: false,
2635
- code: response.status
2636
- };
2637
- }
2638
- case 400:
2639
- case 401:
2640
- case 403:
2641
- case 404:
2642
- case 406:
2643
- case 410:
2644
- case 422:
2645
- case 500:
2646
- return response.json().then(res => {
2647
- return {
2648
- __success: false,
2649
- code: response.status,
2650
- data: res
2651
- };
2652
- }).catch(() => {
2653
- return {
2654
- __success: false,
2655
- code: response.status
2656
- };
2657
- });
2658
- }
2659
- return null;
2660
- }).then(json => {
2661
- if (!json) {
2662
- reject(json);
2663
- return;
2664
- }
2665
- if (json.__success !== false) {
2666
- resolve(json);
2667
- } else {
2668
- delete json.__success;
2669
- reject(json);
2670
- }
2671
- }).catch(err => {
2672
- reject(err);
2673
- });
2674
- });
2675
- }
2676
-
2677
- const DS_STATUS = {
2678
- INIT: 'init',
2679
- LOADING: 'loading',
2680
- LOADED: 'loaded',
2681
- ERROR: 'error'
2682
- };
2683
- function doRequest(type, options) {
2684
- let {
2685
- uri,
2686
- url,
2687
- method = 'GET',
2688
- headers,
2689
- params,
2690
- ...otherProps
2691
- } = options;
2692
- otherProps = otherProps || {};
2693
- if (type === 'fetch') {
2694
- switch (method.toUpperCase()) {
2695
- case 'GET':
2696
- return get(uri, params, headers, otherProps);
2697
- case 'POST':
2698
- return post(uri, params, headers, otherProps);
2699
- default:
2700
- return request(uri, method, params, headers, otherProps);
2701
- }
2702
- }
2703
- logger.log(`Engine default dataSource does not support type:[${type}] dataSource request!`, options);
2704
- }
2705
- class DataHelper {
2706
- host;
2707
- config;
2708
- parser;
2709
- ajaxList;
2710
- dataHandler;
2711
- ajaxMap;
2712
- dataSourceMap;
2713
- appHelper;
2714
- constructor(comp, config, appHelper, parser) {
2715
- this.host = comp;
2716
- this.config = config || {};
2717
- this.parser = parser;
2718
- this.ajaxList = config?.list || [];
2719
- this.ajaxMap = transformArrayToMap(this.ajaxList, 'id');
2720
- this.dataSourceMap = this.generateDataSourceMap();
2721
- this.appHelper = appHelper;
2722
- this.dataHandler = config?.dataHandler ? parseExpression(config?.dataHandler, comp, true) : undefined;
2723
- }
2724
- updateConfig(config = {}) {
2725
- this.config = config;
2726
- this.ajaxList = config?.list || [];
2727
- const ajaxMap = transformArrayToMap(this.ajaxList, 'id');
2728
- Object.keys(this.ajaxMap).forEach(key => {
2729
- if (!ajaxMap[key]) {
2730
- delete this.dataSourceMap[key];
2731
- }
2732
- });
2733
- this.ajaxMap = ajaxMap;
2734
- this.ajaxList.forEach(item => {
2735
- if (!this.dataSourceMap[item.id]) {
2736
- this.dataSourceMap[item.id] = {
2737
- status: DS_STATUS.INIT,
2738
- load: (...args) => {
2739
- return this.getDataSource(item.id, ...args);
2740
- }
2741
- };
2742
- }
2743
- });
2744
- return this.dataSourceMap;
2745
- }
2746
- generateDataSourceMap() {
2747
- const res = {};
2748
- this.ajaxList.forEach(item => {
2749
- res[item.id] = {
2750
- status: DS_STATUS.INIT,
2751
- load: (...args) => {
2752
- return this.getDataSource(item.id, ...args);
2753
- }
2754
- };
2755
- });
2756
- return res;
2757
- }
2758
- updateDataSourceMap(id, data, error) {
2759
- this.dataSourceMap[id].error = error || undefined;
2760
- this.dataSourceMap[id].data = data;
2761
- this.dataSourceMap[id].status = error ? DS_STATUS.ERROR : DS_STATUS.LOADED;
2762
- }
2763
- getInitDataSourseConfigs() {
2764
- const initConfigs = this.parser(this.ajaxList).filter(item => {
2765
- if (item.isInit === true) {
2766
- this.dataSourceMap[item.id].status = DS_STATUS.LOADING;
2767
- return true;
2768
- }
2769
- return false;
2770
- });
2771
- return initConfigs;
2772
- }
2773
- getInitData() {
2774
- const initSyncData = this.getInitDataSourseConfigs();
2775
- return this.asyncDataHandler(initSyncData).then(res => {
2776
- const {
2777
- dataHandler
2778
- } = this.config;
2779
- return this.handleData(null, dataHandler, res, null);
2780
- });
2781
- }
2782
- async reloadDataSource() {
2783
- const dataSourceMap = await this.getInitData();
2784
- if (isEmpty(dataSourceMap)) {
2785
- return;
2786
- }
2787
- this.host.setState(dataSourceMap);
2788
- if (this.dataHandler) {
2789
- this.dataHandler(dataSourceMap);
2790
- }
2791
- }
2792
- getDataSource(id, params, otherOptions, callback) {
2793
- const req = this.parser(this.ajaxMap[id]);
2794
- const options = req.options || {};
2795
- let callbackFn = callback;
2796
- let otherOptionsObj = otherOptions;
2797
- if (typeof otherOptions === 'function') {
2798
- callbackFn = otherOptions;
2799
- otherOptionsObj = {};
2800
- }
2801
- const {
2802
- headers,
2803
- ...otherProps
2804
- } = otherOptionsObj || {};
2805
- if (!req) {
2806
- logger.warn(`getDataSource API named ${id} not exist`);
2807
- return;
2808
- }
2809
- return this.asyncDataHandler([{
2810
- ...req,
2811
- options: {
2812
- ...options,
2813
- params: Array.isArray(options.params) || Array.isArray(params) ? params || options.params : {
2814
- ...options.params,
2815
- ...params
2816
- },
2817
- headers: {
2818
- ...options.headers,
2819
- ...headers
2820
- },
2821
- ...otherProps
2822
- }
2823
- }]).then(res => {
2824
- try {
2825
- callbackFn && callbackFn(res && res[id]);
2826
- } catch (e) {
2827
- logger.error('load请求回调函数报错', e);
2828
- }
2829
- return res && res[id];
2830
- }).catch(err => {
2831
- try {
2832
- callbackFn && callbackFn(null, err);
2833
- } catch (e) {
2834
- logger.error('load请求回调函数报错', e);
2835
- }
2836
- return err;
2837
- });
2838
- }
2839
- asyncDataHandler(asyncDataList) {
2840
- return new Promise((resolve, reject) => {
2841
- const allReq = [];
2842
- asyncDataList.forEach(req => {
2843
- const {
2844
- id,
2845
- type
2846
- } = req;
2847
- if (!id || !type || type === 'legao') {
2848
- return;
2849
- }
2850
- allReq.push(req);
2851
- });
2852
- if (allReq.length === 0) {
2853
- resolve({});
2854
- }
2855
- const res = {};
2856
- Promise.all(allReq.map(item => {
2857
- return new Promise(innerResolve => {
2858
- const {
2859
- type,
2860
- id,
2861
- dataHandler,
2862
- options
2863
- } = item;
2864
- const fetchHandler = (data, error) => {
2865
- res[id] = this.handleData(id, dataHandler, data, error);
2866
- this.updateDataSourceMap(id, res[id], error);
2867
- innerResolve({});
2868
- };
2869
- const doFetch = (innerType, innerOptions) => {
2870
- doRequest(innerType, innerOptions)?.then(data => {
2871
- fetchHandler(data, undefined);
2872
- }).catch(err => {
2873
- fetchHandler(undefined, err);
2874
- });
2875
- };
2876
- this.dataSourceMap[id].status = DS_STATUS.LOADING;
2877
- doFetch(type, options);
2878
- });
2879
- })).then(() => {
2880
- resolve(res);
2881
- }).catch(e => {
2882
- reject(e);
2883
- });
2884
- });
2885
- }
2886
- handleData(id, dataHandler, data, error) {
2887
- let dataHandlerFun = dataHandler;
2888
- if (core.isJSFunction(dataHandler)) {
2889
- dataHandlerFun = transformStringToFunction(dataHandler.value);
2890
- }
2891
- if (!dataHandlerFun || typeof dataHandlerFun !== 'function') {
2892
- return data;
2893
- }
2894
- try {
2895
- return dataHandlerFun.call(this.host, data, error);
2896
- } catch (e) {
2897
- if (id) {
2898
- logger.error(`[${id}]单个请求数据处理函数运行出错`, e);
2899
- } else {
2900
- logger.error('请求数据处理函数运行出错', e);
2901
- }
2902
- }
2903
- }
2904
- }
2905
-
2906
- function executeLifeCycleMethod(context, schema, method, args) {
2907
- if (!context || !isSchema(schema) || !method) {
2908
- return;
2909
- }
2910
- const lifeCycleMethods = getValue(schema, 'lifeCycles', {});
2911
- let fn = lifeCycleMethods[method];
2912
- if (!fn) {
2913
- return;
2914
- }
2915
-
2916
- // TODO: cache
2917
- if (core.isJSExpression(fn) || core.isJSFunction(fn)) {
2918
- fn = parseExpression(fn, context, true);
2919
- }
2920
- if (typeof fn !== 'function') {
2921
- logger.error(`生命周期${method}类型不符`, fn);
2922
- return;
2923
- }
2924
- try {
2925
- return fn.apply(context, args);
2926
- } catch (e) {
2927
- logger.error(`[${schema.componentName}]生命周期${method}出错`, e);
2928
- }
2929
- }
2930
-
2931
- /**
2932
- * get children from a node schema
2933
- */
2934
- function getSchemaChildren(schema) {
2935
- if (!schema) {
2936
- return;
2937
- }
2938
- return schema.children;
2939
- }
2940
- function baseRendererFactory() {
2941
- const {
2942
- BaseRenderer: customBaseRenderer
2943
- } = adapter.getRenderers();
2944
- if (customBaseRenderer) {
2945
- return customBaseRenderer;
2946
- }
2947
- const DEFAULT_LOOP_ARG_ITEM = 'item';
2948
- const DEFAULT_LOOP_ARG_INDEX = 'index';
2949
- // const scopeIdx = 0
2950
-
2951
- return class BaseRenderer extends react.Component {
2952
- static displayName = 'BaseRenderer';
2953
- static defaultProps = {
2954
- __schema: {}
2955
- };
2956
- static contextType = RendererContext;
2957
- dataSourceMap = {};
2958
- __namespace = 'base';
2959
- __compScopes = {};
2960
- __instanceMap = {};
2961
- __dataHelper;
2962
-
2963
- /**
2964
- * keep track of customMethods added to this context
2965
- *
2966
- * @type {any}
2967
- */
2968
- __customMethodsList = [];
2969
- __parseExpression;
2970
- __ref;
2971
-
2972
- /**
2973
- * reference of style element contains schema.css
2974
- *
2975
- * @type {any}
2976
- */
2977
- __styleElement;
2978
- constructor(props) {
2979
- super(props);
2980
- this.__parseExpression = (str, self) => {
2981
- return parseExpression({
2982
- str,
2983
- self,
2984
- logScope: props.componentName
2985
- });
2986
- };
2987
- this.__beforeInit(props);
2988
- this.__init(props);
2989
- this.__afterInit(props);
2990
- logger.log(`constructor - ${props?.__schema?.fileName}`);
2991
- }
2992
- __beforeInit(props) {}
2993
- __init(props) {
2994
- this.__compScopes = {};
2995
- this.__instanceMap = {};
2996
- this.__bindCustomMethods(props);
2997
- }
2998
- __afterInit(props) {}
2999
- static getDerivedStateFromProps(props, state) {
3000
- const result = executeLifeCycleMethod(this, props?.__schema, 'getDerivedStateFromProps', [props, state]);
3001
- return result === undefined ? null : result;
3002
- }
3003
- async getSnapshotBeforeUpdate(...args) {
3004
- this.__executeLifeCycleMethod('getSnapshotBeforeUpdate', args);
3005
- logger.log(`getSnapshotBeforeUpdate - ${this.props?.__schema?.componentName}`);
3006
- }
3007
- async componentDidMount(...args) {
3008
- this.reloadDataSource();
3009
- this.__executeLifeCycleMethod('componentDidMount', args);
3010
- logger.log(`componentDidMount - ${this.props?.__schema?.componentName}`);
3011
- }
3012
- async componentDidUpdate(...args) {
3013
- this.__executeLifeCycleMethod('componentDidUpdate', args);
3014
- logger.log(`componentDidUpdate - ${this.props.__schema.componentName}`);
3015
- }
3016
- async componentWillUnmount(...args) {
3017
- this.__executeLifeCycleMethod('componentWillUnmount', args);
3018
- logger.log(`componentWillUnmount - ${this.props?.__schema?.componentName}`);
3019
- }
3020
- async componentDidCatch(...args) {
3021
- this.__executeLifeCycleMethod('componentDidCatch', args);
3022
- logger.warn(args);
3023
- }
3024
- reloadDataSource = () => new Promise((resolve, reject) => {
3025
- logger.log('reload data source');
3026
- if (!this.__dataHelper) {
3027
- return resolve({});
3028
- }
3029
- this.__dataHelper.getInitData().then(res => {
3030
- if (isEmpty(res)) {
3031
- this.forceUpdate();
3032
- return resolve({});
3033
- }
3034
- this.setState(res, resolve);
3035
- }).catch(err => {
3036
- reject(err);
3037
- });
3038
- });
3039
- shouldComponentUpdate() {
3040
- if (this.props.getSchemaChangedSymbol?.() && this.props.__container?.rerender) {
3041
- this.props.__container?.rerender();
3042
- return false;
3043
- }
3044
- return true;
3045
- }
3046
- forceUpdate() {
3047
- if (this.shouldComponentUpdate()) {
3048
- super.forceUpdate();
3049
- }
3050
- }
3051
-
3052
- /**
3053
- * execute method in schema.lifeCycles
3054
- */
3055
- __executeLifeCycleMethod = (method, args) => {
3056
- // 跳过 construct 的执行
3057
- if (this.context) {
3058
- const {
3059
- engine
3060
- } = this.context;
3061
- if (!engine.props.excuteLifeCycleInDesignMode) {
3062
- return;
3063
- }
3064
- }
3065
- executeLifeCycleMethod(this, this.props.__schema, method, args);
3066
- };
3067
-
3068
- /**
3069
- * this method is for legacy purpose only, which used _ prefix instead of __ as private for some historical reasons
3070
- */
3071
- __getComponentView = () => {
3072
- const {
3073
- __components,
3074
- __schema
3075
- } = this.props;
3076
- if (!__components) {
3077
- return;
3078
- }
3079
- return __components[__schema.componentName];
3080
- };
3081
- __bindCustomMethods = props => {
3082
- const {
3083
- __schema
3084
- } = props;
3085
- const customMethodsList = Object.keys(__schema.methods || {}) || [];
3086
- (this.__customMethodsList || []).forEach(item => {
3087
- if (!customMethodsList.includes(item)) {
3088
- delete this[item];
3089
- }
3090
- });
3091
- this.__customMethodsList = customMethodsList;
3092
- forEach(__schema.methods, (val, key) => {
3093
- let value = val;
3094
- if (core.isJSExpression(value) || core.isJSFunction(value)) {
3095
- value = this.__parseExpression(value, this);
3096
- }
3097
- if (typeof value !== 'function') {
3098
- logger.error(`custom method ${key} can not be parsed to a valid function`, value);
3099
- return;
3100
- }
3101
- this[key] = value.bind(this);
3102
- });
3103
- };
3104
- __generateCtx = ctx => {
3105
- const {
3106
- pageContext,
3107
- compContext
3108
- } = this.context;
3109
- const obj = {
3110
- page: pageContext,
3111
- component: compContext,
3112
- ...ctx
3113
- };
3114
- forEach(obj, (val, key) => {
3115
- this[key] = val;
3116
- });
3117
- };
3118
- __parseData = (data, ctx) => {
3119
- const {
3120
- __ctx,
3121
- componentName
3122
- } = this.props;
3123
- return parseData(data, ctx || __ctx || this, {
3124
- logScope: componentName
3125
- });
3126
- };
3127
- __initDataSource = props => {
3128
- if (!props) {
3129
- return;
3130
- }
3131
- const schema = props.__schema || {};
3132
- const defaultDataSource = {
3133
- list: []
3134
- };
3135
- const dataSource = schema.dataSource || defaultDataSource;
3136
- // requestHandlersMap 存在才走数据源引擎方案
3137
- // TODO: 下面if else 抽成独立函数
3138
- const useDataSourceEngine = !!props.__appHelper?.requestHandlersMap;
3139
- if (useDataSourceEngine) {
3140
- this.__dataHelper = {
3141
- updateConfig: updateDataSource => {
3142
- const {
3143
- dataSourceMap,
3144
- reloadDataSource
3145
- } = createDataSourceEngine(updateDataSource ?? {}, this, props.__appHelper?.requestHandlersMap ? {
3146
- requestHandlersMap: props.__appHelper.requestHandlersMap
3147
- } : undefined);
3148
- this.reloadDataSource = () => new Promise(resolve => {
3149
- logger.log('reload data source');
3150
- reloadDataSource().then(() => {
3151
- resolve({});
3152
- });
3153
- });
3154
- return dataSourceMap;
3155
- }
3156
- };
3157
- this.dataSourceMap = this.__dataHelper.updateConfig(dataSource);
3158
- } else {
3159
- const appHelper = props.__appHelper || {};
3160
- this.__dataHelper = new DataHelper(this, dataSource, appHelper, config => this.__parseData(config));
3161
- this.dataSourceMap = this.__dataHelper.dataSourceMap;
3162
- this.reloadDataSource = () => new Promise(resolve => {
3163
- logger.log('reload data source');
3164
- this.__dataHelper.reloadDataSource().then(() => {
3165
- resolve({});
3166
- });
3167
- });
3168
- }
3169
- };
3170
-
3171
- /**
3172
- * write props.__schema.css to document as a style element,
3173
- * which will be added once and only once.
3174
- * @PRIVATE
3175
- */
3176
- __writeCss = props => {
3177
- const css = getValue(props.__schema, 'css', '');
3178
- logger.log('create this.styleElement with css', css);
3179
- let style = this.__styleElement;
3180
- if (!this.__styleElement) {
3181
- style = document.createElement('style');
3182
- style.type = 'text/css';
3183
- style.setAttribute('from', 'style-sheet');
3184
- const head = document.head || document.getElementsByTagName('head')[0];
3185
- head.appendChild(style);
3186
- this.__styleElement = style;
3187
- logger.log('this.styleElement is created', this.__styleElement);
3188
- }
3189
- if (style.innerHTML === css) {
3190
- return;
3191
- }
3192
- style.innerHTML = css;
3193
- };
3194
- __render = () => {
3195
- const schema = this.props.__schema;
3196
- this.__executeLifeCycleMethod('render');
3197
- this.__writeCss(this.props);
3198
- const {
3199
- engine
3200
- } = this.context;
3201
- if (engine) {
3202
- engine.props?.onCompGetCtx?.(schema, this);
3203
- // 画布场景才需要每次渲染bind自定义方法
3204
- if (this.__designModeIsDesign) {
3205
- this.__bindCustomMethods(this.props);
3206
- this.dataSourceMap = this.__dataHelper?.updateConfig(schema.dataSource);
3207
- }
3208
- }
3209
- };
3210
- __getRef = ref => {
3211
- const {
3212
- engine
3213
- } = this.context;
3214
- const {
3215
- __schema
3216
- } = this.props;
3217
- // ref && engine?.props?.onCompGetRef(__schema, ref)
3218
- // TODO: 只在 ref 存在执行,会影响 documentInstance 的卸载
3219
- engine.props?.onCompGetRef?.(__schema, ref);
3220
- this.__ref = ref;
3221
- };
3222
- __createDom = () => {
3223
- const {
3224
- __schema,
3225
- __ctx
3226
- } = this.props;
3227
- // merge defaultProps
3228
- const scopeProps = {
3229
- ...__schema.defaultProps,
3230
- ...this.props
3231
- };
3232
- const scope = {
3233
- props: scopeProps
3234
- };
3235
- scope.__proto__ = __ctx || this;
3236
- const _children = getSchemaChildren(__schema);
3237
- const Comp = this.__getComponentView();
3238
- if (!Comp) {
3239
- logger.log(`${__schema.componentName} is invalid!`);
3240
- }
3241
- const parentNodeInfo = {
3242
- schema: __schema,
3243
- Comp: this.__getHOCWrappedComponent(Comp, {
3244
- schema: __schema,
3245
- scope
3246
- })
3247
- };
3248
- return this.__createVirtualDom(_children, scope, parentNodeInfo);
3249
- };
3250
-
3251
- /**
3252
- * 将模型结构转换成react Element
3253
- * @param originalSchema schema
3254
- * @param originalScope scope
3255
- * @param parentInfo 父组件的信息,包含schema和Comp
3256
- * @param idx 为循环渲染的循环Index
3257
- */
3258
- __createVirtualDom = (originalSchema, originalScope, parentInfo, idx = '') => {
3259
- if (originalSchema === null || originalSchema === undefined) {
3260
- return null;
3261
- }
3262
- const scope = originalScope;
3263
- const schema = originalSchema;
3264
- const {
3265
- engine
3266
- } = this.context || {};
3267
- if (!engine) {
3268
- logger.log('this.context.engine is invalid!');
3269
- return null;
3270
- }
3271
- try {
3272
- const {
3273
- __appHelper: appHelper,
3274
- __components: components = {}
3275
- } = this.props || {};
3276
- if (core.isJSExpression(schema)) {
3277
- return this.__parseExpression(schema, scope);
3278
- }
3279
- if (typeof schema === 'string') {
3280
- return schema;
3281
- }
3282
- if (typeof schema === 'number' || typeof schema === 'boolean') {
3283
- return String(schema);
3284
- }
3285
- if (Array.isArray(schema)) {
3286
- if (schema.length === 1) {
3287
- return this.__createVirtualDom(schema[0], scope, parentInfo);
3288
- }
3289
- return schema.map((item, idy) => this.__createVirtualDom(item, scope, parentInfo, item?.__ctx?.lceKey ? '' : String(idy)));
3290
- }
3291
- if (schema.$$typeof) {
3292
- return schema;
3293
- }
3294
- if (!schema.componentName) {
3295
- logger.error('The componentName in the schema is invalid, please check the schema: ', schema);
3296
- return;
3297
- }
3298
- if (!isSchema(schema)) {
3299
- return null;
3300
- }
3301
- let Comp = components[schema.componentName] || this.props.__container?.components?.[schema.componentName];
3302
-
3303
- // 容器类组件的上下文通过props传递,避免context传递带来的嵌套问题
3304
- const otherProps = isSchema(schema) ? {
3305
- __schema: schema,
3306
- __appHelper: appHelper,
3307
- __components: components
3308
- } : {};
3309
- if (!Comp) {
3310
- logger.error(`${schema.componentName} component is not found in components list! component list is:`, components || this.props.__container?.components);
3311
- return engine.createElement(engine.getNotFoundComponent(), {
3312
- componentName: schema.componentName,
3313
- componentId: schema.id,
3314
- enableStrictNotFoundMode: engine.props.enableStrictNotFoundMode,
3315
- ref: ref => {
3316
- ref && engine.props?.onCompGetRef?.(schema, ref);
3317
- }
3318
- }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp));
3319
- }
3320
- if (schema.loop != null) {
3321
- const loop = this.__parseData(schema.loop, scope);
3322
- if (Array.isArray(loop) && loop.length === 0) return null;
3323
- const useLoop = isUseLoop(loop, this.__designModeIsDesign);
3324
- if (useLoop) {
3325
- return this.__createLoopVirtualDom({
3326
- ...schema,
3327
- loop
3328
- }, scope, parentInfo, idx);
3329
- }
3330
- }
3331
- const condition = schema.condition == null ? true : this.__parseData(schema.condition, scope);
3332
-
3333
- // DesignMode 为 design 情况下,需要进入 leaf Hoc,进行相关事件注册
3334
- const displayInHook = this.__designModeIsDesign;
3335
- if (!condition && !displayInHook) {
3336
- return null;
3337
- }
3338
-
3339
- // TODO: scope
3340
- // let scopeKey = ''
3341
- // // 判断组件是否需要生成scope,且只生成一次,挂在this.__compScopes上
3342
- // if (Comp.generateScope) {
3343
- // const key = this.__parseExpression(schema.props?.key, scope)
3344
- // if (key) {
3345
- // // 如果组件自己设置key则使用组件自己的key
3346
- // scopeKey = key
3347
- // } else if (schema.__ctx) {
3348
- // // 需要判断循环的情况
3349
- // scopeKey = schema.__ctx.lceKey + (idx !== undefined ? `_${idx}` : '')
3350
- // } else {
3351
- // // 在生产环境schema没有__ctx上下文,需要手动生成一个lceKey
3352
- // schema.__ctx = {
3353
- // lceKey: `lce${++scopeIdx}`,
3354
- // }
3355
- // scopeKey = schema.__ctx.lceKey
3356
- // }
3357
- // if (!this.__compScopes[scopeKey]) {
3358
- // this.__compScopes[scopeKey] = Comp.generateScope(this, schema)
3359
- // }
3360
- // }
3361
- // // 如果组件有设置scope,需要为组件生成一个新的scope上下文
3362
- // if (scopeKey && this.__compScopes[scopeKey]) {
3363
- // const compSelf = { ...this.__compScopes[scopeKey] }
3364
- // compSelf.__proto__ = scope
3365
- // scope = compSelf
3366
- // }
3367
-
3368
- if (engine.props?.designMode) {
3369
- otherProps.__designMode = engine.props.designMode;
3370
- }
3371
- if (this.__designModeIsDesign) {
3372
- otherProps.__tag = Math.random();
3373
- }
3374
- const componentInfo = {};
3375
- const props = this.__getComponentProps(schema, scope, Comp, {
3376
- ...componentInfo,
3377
- props: transformArrayToMap(componentInfo.props, 'name')
3378
- }) || {};
3379
- Comp = this.__getHOCWrappedComponent(Comp, {
3380
- schema,
3381
- componentInfo,
3382
- baseRenderer: this,
3383
- scope
3384
- });
3385
- otherProps.ref = ref => {
3386
- this.$(schema.id || props.ref, ref); // 收集ref
3387
- const refProps = props.ref;
3388
- if (refProps && typeof refProps === 'string') {
3389
- this[refProps] = ref;
3390
- }
3391
- ref && engine.props?.onCompGetRef?.(schema, ref);
3392
- };
3393
-
3394
- // scope需要传入到组件上
3395
- // if (scopeKey && this.__compScopes[scopeKey]) {
3396
- // props.__scope = this.__compScopes[scopeKey]
3397
- // }
3398
- if (schema?.__ctx?.lceKey) {
3399
- if (!isSchema(schema)) {
3400
- engine.props?.onCompGetCtx?.(schema, scope);
3401
- }
3402
- props.key = props.key || `${schema.__ctx.lceKey}_${schema.__ctx.idx || 0}_${idx !== undefined ? idx : ''}`;
3403
- } else if ((typeof idx === 'number' || typeof idx === 'string') && !props.key) {
3404
- // 仅当循环场景走这里
3405
- props.key = idx;
3406
- }
3407
- props.__id = schema.id;
3408
- if (!props.key) {
3409
- props.key = props.__id;
3410
- }
3411
- return engine.createElement(Comp, {
3412
- ...props,
3413
- ...otherProps,
3414
- // TODO: 看看这里需要怎么处理简洁
3415
- __inner__: {
3416
- hidden: schema.hidden,
3417
- condition
3418
- }
3419
- }, this.__getSchemaChildrenVirtualDom(schema, scope, Comp, condition));
3420
- } catch (e) {
3421
- return engine.createElement(engine.getFaultComponent(), {
3422
- error: e,
3423
- schema,
3424
- self: scope,
3425
- parentInfo,
3426
- idx
3427
- });
3428
- }
3429
- };
3430
-
3431
- /**
3432
- * get Component HOCs
3433
- *
3434
- * @readonly
3435
- * @type {ComponentConstruct[]}
3436
- */
3437
- get __componentHOCs() {
3438
- if (this.__designModeIsDesign) {
3439
- return [leafWrapper, compWrapper];
3440
- }
3441
- return [compWrapper];
3442
- }
3443
- __getSchemaChildrenVirtualDom = (schema, scope, Comp, condition = true) => {
3444
- let children = condition ? getSchemaChildren(schema) : null;
3445
- const result = [];
3446
- if (children) {
3447
- if (!Array.isArray(children)) {
3448
- children = [children];
3449
- }
3450
- children.forEach(child => {
3451
- const childVirtualDom = this.__createVirtualDom(core.isJSExpression(child) ? this.__parseExpression(child, scope) : child, scope, {
3452
- schema,
3453
- Comp
3454
- });
3455
- result.push(childVirtualDom);
3456
- });
3457
- }
3458
- if (result && result.length > 0) {
3459
- return result;
3460
- }
3461
- return null;
3462
- };
3463
- __getComponentProps = (schema, scope, Comp, componentInfo) => {
3464
- if (!schema) {
3465
- return {};
3466
- }
3467
- return this.__parseProps(schema?.props, scope, '', {
3468
- schema,
3469
- Comp,
3470
- componentInfo: {
3471
- ...(componentInfo || {}),
3472
- props: transformArrayToMap((componentInfo || {}).props, 'name')
3473
- }
3474
- }) || {};
3475
- };
3476
- __createLoopVirtualDom = (schema, scope, parentInfo, idx) => {
3477
- // TODO
3478
- // if (isSchema(schema)) {
3479
- // logger.warn('file type not support Loop')
3480
- // return null
3481
- // }
3482
- if (!Array.isArray(schema.loop)) {
3483
- return null;
3484
- }
3485
- const itemArg = schema.loopArgs && schema.loopArgs[0] || DEFAULT_LOOP_ARG_ITEM;
3486
- const indexArg = schema.loopArgs && schema.loopArgs[1] || DEFAULT_LOOP_ARG_INDEX;
3487
- const {
3488
- loop
3489
- } = schema;
3490
- return loop.map((item, i) => {
3491
- const loopSelf = {
3492
- [itemArg]: item,
3493
- [indexArg]: i
3494
- };
3495
- loopSelf.__proto__ = scope;
3496
- return this.__createVirtualDom({
3497
- ...schema,
3498
- loop: undefined,
3499
- props: {
3500
- ...schema.props,
3501
- // 循环下 key 不能为常量,这样会造成 key 值重复,渲染异常
3502
- key: core.isJSExpression(schema.props?.key) ? schema.props?.key : null
3503
- }
3504
- }, loopSelf, parentInfo, idx ? `${idx}_${i}` : i);
3505
- });
3506
- };
3507
- get __designModeIsDesign() {
3508
- const {
3509
- engine
3510
- } = this.context || {};
3511
- return engine?.props?.designMode === 'design';
3512
- }
3513
- __parseProps = (originalProps, scope, path, info) => {
3514
- let props = originalProps;
3515
- const {
3516
- schema,
3517
- Comp,
3518
- componentInfo = {}
3519
- } = info;
3520
- const propInfo = getValue(componentInfo.props, path);
3521
- // FIXME: 将这行逻辑外置,解耦,线上环境不要验证参数,调试环境可以有,通过传参自定义
3522
- const propType = propInfo?.extra?.propType;
3523
- const checkProps = value => {
3524
- if (!propType) {
3525
- return value;
3526
- }
3527
- return checkPropTypes(value, path, propType, componentInfo.name) ? value : undefined;
3528
- };
3529
- const parseReactNode = (data, params) => {
3530
- if (isEmpty(params)) {
3531
- const virtualDom = this.__createVirtualDom(data, scope, {
3532
- schema,
3533
- Comp
3534
- });
3535
- return checkProps(virtualDom);
3536
- }
3537
- return checkProps((...argValues) => {
3538
- const args = {};
3539
- if (Array.isArray(params) && params.length) {
3540
- params.forEach((item, idx) => {
3541
- if (typeof item === 'string') {
3542
- args[item] = argValues[idx];
3543
- } else if (item && typeof item === 'object') {
3544
- args[item.name] = argValues[idx];
3545
- }
3546
- });
3547
- }
3548
- args.__proto__ = scope;
3549
- return scope.__createVirtualDom(data, args, {
3550
- schema,
3551
- Comp
3552
- });
3553
- });
3554
- };
3555
- if (core.isJSExpression(props)) {
3556
- props = this.__parseExpression(props, scope);
3557
- // 只有当变量解析出来为模型结构的时候才会继续解析
3558
- if (!isSchema(props)) {
3559
- return checkProps(props);
3560
- }
3561
- }
3562
- if (core.isJSFunction(props)) {
3563
- props = transformStringToFunction(props.value);
3564
- }
3565
-
3566
- // 兼容通过componentInfo判断的情况
3567
- if (isSchema(props)) {
3568
- const isReactNodeFunction = !!(propInfo?.type === 'ReactNode' && propInfo?.props?.type === 'function');
3569
- const isMixinReactNodeFunction = !!(propInfo?.type === 'Mixin' && propInfo?.props?.types?.indexOf('ReactNode') > -1 && propInfo?.props?.reactNodeProps?.type === 'function');
3570
- let params = null;
3571
- if (isReactNodeFunction) {
3572
- params = propInfo?.props?.params;
3573
- } else if (isMixinReactNodeFunction) {
3574
- params = propInfo?.props?.reactNodeProps?.params;
3575
- }
3576
- return parseReactNode(props, params);
3577
- }
3578
- if (Array.isArray(props)) {
3579
- return checkProps(props.map((item, idx) => this.__parseProps(item, scope, path ? `${path}.${idx}` : `${idx}`, info)));
3580
- }
3581
- if (typeof props === 'function') {
3582
- return checkProps(props.bind(scope));
3583
- }
3584
- if (props && typeof props === 'object') {
3585
- if (props.$$typeof) {
3586
- return checkProps(props);
3587
- }
3588
- const res = {};
3589
- forEach(props, (val, key) => {
3590
- if (key.startsWith('__')) {
3591
- res[key] = val;
3592
- return;
3593
- }
3594
- res[key] = this.__parseProps(val, scope, path ? `${path}.${key}` : key, info);
3595
- });
3596
- return checkProps(res);
3597
- }
3598
- return checkProps(props);
3599
- };
3600
- $(id, instance) {
3601
- this.__instanceMap = this.__instanceMap || {};
3602
- if (!id || typeof id !== 'string') {
3603
- return this.__instanceMap;
3604
- }
3605
- if (instance) {
3606
- this.__instanceMap[id] = instance;
3607
- }
3608
- return this.__instanceMap[id];
3609
- }
3610
- __renderContextProvider = (customProps, children) => {
3611
- return /*#__PURE__*/jsxRuntime.jsx(RendererContext.Provider, {
3612
- value: {
3613
- ...this.context,
3614
- blockContext: this,
3615
- ...(customProps || {})
3616
- },
3617
- children: children || this.__createDom()
3618
- });
3619
- };
3620
- __renderContextConsumer = children => {
3621
- return /*#__PURE__*/jsxRuntime.jsx(RendererContext.Consumer, {
3622
- children: children
3623
- });
3624
- };
3625
- __getHOCWrappedComponent(OriginalComp, info) {
3626
- let Comp = OriginalComp;
3627
- this.__componentHOCs.forEach(ComponentConstruct => {
3628
- Comp = ComponentConstruct(Comp, {
3629
- componentInfo: {},
3630
- baseRenderer: this,
3631
- ...info
3632
- });
3633
- });
3634
- return Comp;
3635
- }
3636
- __renderComp(OriginalComp, ctxProps) {
3637
- let Comp = OriginalComp;
3638
- const {
3639
- __schema,
3640
- __ctx
3641
- } = this.props;
3642
- const scope = {};
3643
- scope.__proto__ = __ctx || this;
3644
- Comp = this.__getHOCWrappedComponent(Comp, {
3645
- schema: __schema,
3646
- scope
3647
- });
3648
- const data = this.__parseProps(__schema?.props, scope, '', {
3649
- schema: __schema,
3650
- Comp,
3651
- componentInfo: {}
3652
- });
3653
- const {
3654
- className
3655
- } = data;
3656
- const otherProps = {};
3657
- const {
3658
- engine
3659
- } = this.context || {};
3660
- if (!engine) {
3661
- return null;
3662
- }
3663
- if (this.__designModeIsDesign) {
3664
- otherProps.__tag = Math.random();
3665
- }
3666
- const child = engine.createElement(Comp, {
3667
- ...data,
3668
- ...this.props,
3669
- ref: this.__getRef,
3670
- className: classnames(__schema?.fileName && getFileCssName(__schema.fileName), className, this.props.className),
3671
- __id: __schema?.id,
3672
- ...otherProps
3673
- }, this.__createDom());
3674
- return this.__renderContextProvider(ctxProps, child);
3675
- }
3676
- __renderContent(children) {
3677
- const {
3678
- __schema
3679
- } = this.props;
3680
- const parsedProps = this.__parseData(__schema.props);
3681
- const className = classnames(`lce-${this.__namespace}`, __schema?.fileName && getFileCssName(__schema.fileName), parsedProps.className, this.props.className);
3682
- const style = {
3683
- ...(parsedProps.style || {}),
3684
- ...(typeof this.props.style === 'object' ? this.props.style : {})
3685
- };
3686
- const id = this.props.id || parsedProps.id;
3687
- return /*#__PURE__*/jsxRuntime.jsx("div", {
3688
- ref: this.__getRef,
3689
- className: className,
3690
- id: id,
3691
- style: style,
3692
- children: children
3693
- });
3694
- }
3695
- __checkSchema = (schema, originalExtraComponents = []) => {
3696
- let extraComponents = originalExtraComponents;
3697
- if (typeof extraComponents === 'string') {
3698
- extraComponents = [extraComponents];
3699
- }
3700
-
3701
- // const builtin = capitalizeFirstLetter(this.__namespace)
3702
- // const componentNames = [builtin, ...extraComponents]
3703
- const componentNames = [...Object.keys(this.props.__components), ...extraComponents];
3704
- return !isSchema(schema) || !componentNames.includes(schema?.componentName ?? '');
3705
- };
3706
- get appHelper() {
3707
- return this.props.__appHelper;
3708
- }
3709
- get requestHandlersMap() {
3710
- return this.appHelper?.requestHandlersMap;
3711
- }
3712
- get utils() {
3713
- return this.appHelper?.utils;
3714
- }
3715
- get constants() {
3716
- return this.appHelper?.constants;
3717
- }
3718
-
3719
- // render() {
3720
- // return null
3721
- // }
3722
- };
3723
- }
3724
-
3725
- function componentRendererFactory() {
3726
- const BaseRenderer = baseRendererFactory();
3727
- return class CompRenderer extends BaseRenderer {
3728
- static displayName = 'CompRenderer';
3729
- __namespace = 'component';
3730
- __afterInit(props, ...rest) {
3731
- this.__generateCtx({
3732
- component: this
3733
- });
3734
- const schema = props.__schema || {};
3735
- this.state = this.__parseData(schema.state || {});
3736
- this.__initDataSource(props);
3737
- this.__executeLifeCycleMethod('constructor', [props, ...rest]);
3738
- }
3739
- render() {
3740
- const {
3741
- __schema
3742
- } = this.props;
3743
- if (this.__checkSchema(__schema)) {
3744
- return '自定义组件 schema 结构异常!';
3745
- }
3746
- logger.log(`${CompRenderer.displayName} render - ${__schema.componentName}`);
3747
- this.__generateCtx({
3748
- component: this
3749
- });
3750
- this.__render();
3751
- const noContainer = this.__parseData(__schema.props?.noContainer);
3752
- this.__bindCustomMethods(this.props);
3753
- if (noContainer) {
3754
- return this.__renderContextProvider({
3755
- compContext: this
3756
- });
3757
- }
3758
- const Comp = this.__getComponentView();
3759
- if (!Comp) {
3760
- return this.__renderContent(this.__renderContextProvider({
3761
- compContext: this
3762
- }));
3763
- }
3764
- return this.__renderComp(Comp, {
3765
- compContext: this
3766
- });
3767
- }
3768
- };
3769
- }
3770
-
3771
- function pageRendererFactory() {
3772
- const BaseRenderer = baseRendererFactory();
3773
- return class PageRenderer extends BaseRenderer {
3774
- static displayName = 'PageRenderer';
3775
- __namespace = 'page';
3776
- __afterInit(props, ...rest) {
3777
- const schema = props.__schema || {};
3778
- this.state = this.__parseData(schema.state || {});
3779
- this.__initDataSource(props);
3780
- this.__executeLifeCycleMethod('constructor', [props, ...rest]);
3781
- }
3782
- async componentDidUpdate(prevProps, _prevState, snapshot) {
3783
- const {
3784
- __ctx
3785
- } = this.props;
3786
- // 当编排的时候修改 schema.state 值,需要将最新 schema.state 值 setState
3787
- if (JSON.stringify(prevProps.__schema.state) !== JSON.stringify(this.props.__schema.state)) {
3788
- const newState = this.__parseData(this.props.__schema.state, __ctx);
3789
- this.setState(newState);
3790
- }
3791
- super.componentDidUpdate?.(prevProps, _prevState, snapshot);
3792
- }
3793
- setState(state, callback) {
3794
- logger.log('page set state', state);
3795
- super.setState(state, callback);
3796
- }
3797
- render() {
3798
- const {
3799
- __schema
3800
- } = this.props;
3801
- if (this.__checkSchema(__schema)) {
3802
- return '页面schema结构异常!';
3803
- }
3804
- logger.log(`${PageRenderer.displayName} render - ${__schema.componentName}`);
3805
- this.__bindCustomMethods(this.props);
3806
- this.__initDataSource(this.props);
3807
- this.__generateCtx({
3808
- page: this
3809
- });
3810
- this.__render();
3811
- const Comp = this.__getComponentView();
3812
- if (!Comp) {
3813
- return this.__renderContent(this.__renderContextProvider({
3814
- pageContext: this
3815
- }));
3816
- }
3817
- return this.__renderComp(Comp, {
3818
- pageContext: this
3819
- });
3820
- }
3821
- };
3822
- }
3823
-
3824
- const FaultComponent = ({
3825
- componentName = '',
3826
- error
3827
- }) => {
3828
- logger.error(`${componentName} 组件渲染异常, 异常原因: ${error?.message || error || '未知'}`);
3829
- return /*#__PURE__*/jsxRuntime.jsxs("div", {
3830
- role: "alert",
3831
- "aria-label": `${componentName} 组件渲染异常`,
3832
- style: {
3833
- width: '100%',
3834
- height: '50px',
3835
- lineHeight: '50px',
3836
- textAlign: 'center',
3837
- fontSize: '15px',
3838
- color: '#ef4444',
3839
- border: '2px solid #ef4444'
3840
- },
3841
- children: [componentName, " \u7EC4\u4EF6\u6E32\u67D3\u5F02\u5E38\uFF0C\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7"]
3842
- });
3843
- };
3844
-
3845
- const NotFoundComponent = ({
3846
- componentName = '',
3847
- enableStrictNotFoundMode,
3848
- children
3849
- }) => {
3850
- logger.warn(`Component ${componentName} not found`);
3851
- if (enableStrictNotFoundMode) {
3852
- return /*#__PURE__*/jsxRuntime.jsx(jsxRuntime.Fragment, {
3853
- children: `${componentName} Component Not Found`
3854
- });
3855
- }
3856
- return /*#__PURE__*/jsxRuntime.jsx("div", {
3857
- role: "alert",
3858
- "aria-label": `${componentName} component not found`,
3859
- style: {
3860
- width: '100%',
3861
- height: '50px',
3862
- lineHeight: '50px',
3863
- textAlign: 'center',
3864
- fontSize: '15px',
3865
- color: '#eab308',
3866
- border: '2px solid #eab308'
3867
- },
3868
- children: `${componentName} Component Not Found`
3869
- });
3870
- };
3871
-
3872
- function rendererFactory() {
3873
- const RENDERER_COMPS = adapter.getRenderers();
3874
- return class Renderer extends react.Component {
3875
- static displayName = 'Renderer';
3876
- state = {};
3877
- __ref;
3878
- static defaultProps = {
3879
- appHelper: undefined,
3880
- components: {},
3881
- designMode: 'live',
3882
- suspended: false,
3883
- schema: {},
3884
- onCompGetRef: () => {},
3885
- onCompGetCtx: () => {},
3886
- excuteLifeCycleInDesignMode: false
3887
- };
3888
- constructor(props) {
3889
- super(props);
3890
- this.state = {};
3891
- core.logger.log(`entry.constructor - ${props?.schema?.componentName}`);
3892
- }
3893
- async componentDidMount() {
3894
- core.logger.log(`entry.componentDidMount - ${this.props.schema && this.props.schema.componentName}`);
3895
- }
3896
- async componentDidUpdate() {
3897
- core.logger.log(`entry.componentDidUpdate - ${this.props?.schema?.componentName}`);
3898
- }
3899
- async componentWillUnmount() {
3900
- core.logger.log(`entry.componentWillUnmount - ${this.props?.schema?.componentName}`);
3901
- }
3902
- componentDidCatch(error) {
3903
- this.state.engineRenderError = true;
3904
- this.state.error = error;
3905
- }
3906
- shouldComponentUpdate(nextProps) {
3907
- return !nextProps.suspended;
3908
- }
3909
- __getRef = ref => {
3910
- this.__ref = ref;
3911
- if (ref) {
3912
- this.props.onCompGetRef?.(this.props.schema, ref);
3913
- }
3914
- };
3915
- isValidComponent(SetComponent) {
3916
- return SetComponent;
3917
- }
3918
- createElement(SetComponent, props, children) {
3919
- return (this.props.customCreateElement || react.createElement)(SetComponent, props, children);
3920
- }
3921
- getNotFoundComponent() {
3922
- return this.props.notFoundComponent || NotFoundComponent;
3923
- }
3924
- getFaultComponent() {
3925
- return this.props.faultComponent || FaultComponent;
3926
- }
3927
- render() {
3928
- const {
3929
- schema,
3930
- designMode,
3931
- appHelper,
3932
- components
3933
- } = this.props;
3934
- if (isEmpty(schema)) {
3935
- return null;
3936
- }
3937
- if (!isSchema(schema)) {
3938
- core.logger.error('The root component name needs to be one of Page、Block、Component, please check the schema: ', schema);
3939
- return '模型结构异常';
3940
- }
3941
- core.logger.log('entry.render');
3942
- const allComponents = {
3943
- ...components,
3944
- ...RENDERER_COMPS
3945
- };
3946
- // TODO: 默认最顶层使用 PageRenderer
3947
- const Comp = allComponents.PageRenderer;
3948
- if (this.state && this.state.engineRenderError) {
3949
- return /*#__PURE__*/react.createElement(this.getFaultComponent(), {
3950
- componentName: schema.componentName,
3951
- error: this.state.error
3952
- });
3953
- }
3954
- if (!Comp) {
3955
- return null;
3956
- }
3957
- return /*#__PURE__*/jsxRuntime.jsx(RendererContext.Provider, {
3958
- value: {
3959
- appHelper,
3960
- components: allComponents,
3961
- engine: this
3962
- },
3963
- children: /*#__PURE__*/jsxRuntime.jsx(Comp, {
3964
- // ref={this.__getRef}
3965
- __appHelper: appHelper,
3966
- __components: allComponents,
3967
- __schema: schema,
3968
- __designMode: designMode,
3969
- ...this.props
3970
- }, schema.__ctx && `${schema.__ctx.lceKey}_${schema.__ctx.idx || '0'}`)
3971
- });
3972
- }
3973
- };
3974
- }
3975
-
3976
- const DEV = '_EASY_EDITOR_DEV_';
3977
-
3978
- exports.DEV = DEV;
3979
- exports.RendererContext = RendererContext;
3980
- exports.SettingFieldView = SettingFieldView;
3981
- exports.SettingRender = SettingRender;
3982
- exports.adapter = adapter;
3983
- exports.baseRendererFactory = baseRendererFactory;
3984
- exports.capitalizeFirstLetter = capitalizeFirstLetter;
3985
- exports.checkPropTypes = checkPropTypes;
3986
- exports.classnames = classnames;
3987
- exports.cloneEnumerableProperty = cloneEnumerableProperty;
3988
- exports.compWrapper = compWrapper;
3989
- exports.componentRendererFactory = componentRendererFactory;
3990
- exports.contextFactory = contextFactory;
3991
- exports.createForwardRefHocElement = createForwardRefHocElement;
3992
- exports.executeLifeCycleMethod = executeLifeCycleMethod;
3993
- exports.getFileCssName = getFileCssName;
3994
- exports.getSchemaChildren = getSchemaChildren;
3995
- exports.getValue = getValue;
3996
- exports.inSameDomain = inSameDomain;
3997
- exports.isReactClass = isReactClass;
3998
- exports.isReactComponent = isReactComponent;
3999
- exports.isSchema = isSchema;
4000
- exports.isString = isString;
4001
- exports.isUseLoop = isUseLoop;
4002
- exports.leafWrapper = leafWrapper;
4003
- exports.logger = logger;
4004
- exports.pageRendererFactory = pageRendererFactory;
4005
- exports.parseData = parseData;
4006
- exports.parseExpression = parseExpression;
4007
- exports.parseThisRequiredExpression = parseThisRequiredExpression;
4008
- exports.rendererFactory = rendererFactory;
4009
- exports.serializeParams = serializeParams;
4010
- exports.transformArrayToMap = transformArrayToMap;
4011
- exports.transformStringToFunction = transformStringToFunction;
4012
- exports.useRendererContext = useRendererContext;
4013
- //# sourceMappingURL=index.production.js.map