@cloudbase/lowcode-builder 1.2.4 → 1.3.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.
@@ -1,37 +1,37 @@
1
1
  'use strict';
2
- import { findForItemsOfWidget, getWidget } from './widget'
2
+ import { generateForContextOfWidget, generateWidgetAPIContext, getWidget } from './widget';
3
3
  import { observable, untracked } from 'mobx';
4
- import { getAccessToken, loginScope } from '../datasources/index'
5
- import { app } from '../app/weapps-api'
4
+ import { getAccessToken, loginScope } from '../datasources/index';
5
+ import { app } from '../app/weapps-api';
6
6
 
7
7
  /**
8
8
  * Convert abcWordSnd -> abc-word-snd
9
9
  */
10
10
  export function toDash(str) {
11
- return str.replace(/[A-Z]/g, upperLetter => `-${upperLetter.toLowerCase()}`)
11
+ return str.replace(/[A-Z]/g, (upperLetter) => `-${upperLetter.toLowerCase()}`);
12
12
  }
13
13
 
14
14
  export function createComputed(funcs, bindContext = null) {
15
- const computed = {}
15
+ const computed = {};
16
16
  for (const name in funcs) {
17
17
  Object.defineProperty(computed, name, {
18
18
  get() {
19
19
  try {
20
- return bindContext ? funcs[name].call(bindContext) : funcs[name]()
20
+ return bindContext ? funcs[name].call(bindContext) : funcs[name]();
21
21
  } catch (e) {
22
- console.error('Computed error', e)
22
+ console.error('Computed error', e);
23
23
  }
24
24
  },
25
- enumerable: true
26
- })
25
+ enumerable: true,
26
+ });
27
27
  }
28
- return computed
28
+ return computed;
29
29
  }
30
30
 
31
31
  export function generateDataContext(widget) {
32
32
  const dataContext = {};
33
33
  while (widget?._scope) {
34
- const current = widget
34
+ const current = widget;
35
35
  // 此处采用代理的方式,是为了可以获取到最新的 _scope.dataContext 防止 dataContext 引用被重新赋值
36
36
  Object.defineProperty(dataContext, current._scope.id, {
37
37
  get() {
@@ -59,24 +59,26 @@ export function createEventHandlers(
59
59
  const listeners = evtListeners[name];
60
60
  evtHandlers[name] = function (event = {}) {
61
61
  const self = this;
62
- const owner = this.getWeAppInst();
62
+ const owner = this._getInstance();
63
63
  const target = !!event?.target?.id ? getWidget(owner.widgets, event.target.id) : undefined;
64
64
  const currentTarget = !!event?.currentTarget?.id ? getWidget(owner.widgets, event.currentTarget.id) : undefined;
65
65
  event.target = target;
66
66
  event.currentTarget = currentTarget;
67
67
  const [prefix = ''] = name.split('$');
68
68
  // The page event handler
69
- const { lists = [], itemsById = {} } = (!!currentTarget && findForItemsOfWidget(currentTarget)) || {};
69
+ const forContext = (!!currentTarget && generateForContextOfWidget(currentTarget)) || {};
70
+ const { lists = [], forItems = {} } = forContext;
70
71
  const dataContext = untracked(() => generateDataContext(currentTarget));
72
+ const $w = untracked(() => generateWidgetAPIContext(owner?.__internal__?.$w, currentTarget, forContext));
71
73
 
72
74
  listeners.forEach(async (l) => {
73
75
  let { data = {}, boundData = {} } = l;
74
76
  data = { ...data };
75
77
  try {
76
78
  for (const k in boundData) {
77
- set(data, k, boundData[k].call(owner, owner, lists, itemsById, event, dataContext));
79
+ set(data, k, boundData[k].call(owner, owner, lists, forItems, event, dataContext, $w));
78
80
  }
79
- let res = await l.handler.call(owner, { event, lists, forItems: itemsById, data });
81
+ let res = await l.handler.call(owner, { event, data });
80
82
  let eventName = prefix && l.key ? `${prefix}$${l.key}_success` : '';
81
83
  self[eventName] &&
82
84
  self[eventName]({
@@ -109,13 +111,13 @@ export function createEventHandlers(
109
111
  }
110
112
  export function getDeep(target, key, keySeparator = '.') {
111
113
  if (key == null) {
112
- return target
114
+ return target;
113
115
  }
114
- const keys = (key + '').split(keySeparator)
116
+ const keys = (key + '').split(keySeparator);
115
117
  while (keys.length > 0 && target != null) {
116
- target = target[keys.shift()]
118
+ target = target[keys.shift()];
117
119
  }
118
- return keys.length === 0 ? target : undefined
120
+ return keys.length === 0 ? target : undefined;
119
121
  }
120
122
 
121
123
  /**
@@ -123,141 +125,135 @@ export function getDeep(target, key, keySeparator = '.') {
123
125
  */
124
126
  export function touchObj(obj) {
125
127
  if (!obj) {
126
- return
128
+ return;
127
129
  }
128
130
  if (typeof obj === 'string') {
129
- return
131
+ return;
130
132
  }
131
133
  if (Array.isArray(obj)) {
132
- obj.forEach(touchObj)
134
+ obj.forEach(touchObj);
133
135
  } else if (obj) {
134
- Object.keys(obj).forEach(key => touchObj(obj[key]))
136
+ Object.keys(obj).forEach((key) => touchObj(obj[key]));
135
137
  }
136
138
  }
137
139
 
138
140
  export function throttle(fn, limit) {
139
- let lastExecTime = 0
140
- let timer = null
141
+ let lastExecTime = 0;
142
+ let timer = null;
141
143
 
142
144
  function invoke() {
143
- lastExecTime = Date.now()
144
- timer = null
145
- fn()
145
+ lastExecTime = Date.now();
146
+ timer = null;
147
+ fn();
146
148
  }
147
149
 
148
150
  const throttled = function () {
149
- const idledDuration = Date.now() - lastExecTime
151
+ const idledDuration = Date.now() - lastExecTime;
150
152
  if (idledDuration >= limit) {
151
153
  if (timer) {
152
- clearTimeout(timer)
153
- timer = null
154
+ clearTimeout(timer);
155
+ timer = null;
154
156
  }
155
- invoke()
157
+ invoke();
156
158
  } else if (!timer) {
157
- timer = setTimeout(invoke, limit - idledDuration)
159
+ timer = setTimeout(invoke, limit - idledDuration);
158
160
  }
159
- }
160
- return throttled
161
+ };
162
+ return throttled;
161
163
  }
162
164
 
163
165
  export function deepEqual(a, b) {
164
166
  if (a === b) {
165
- return true
167
+ return true;
166
168
  }
167
169
 
168
170
  if (Array.isArray(a) && Array.isArray(b)) {
169
171
  if (a.length !== b.length) {
170
- return false
172
+ return false;
171
173
  }
172
174
  for (let i = 0; i < a.length; i++) {
173
175
  if (!deepEqual(a[i], b[i])) {
174
- return false
176
+ return false;
175
177
  }
176
178
  }
177
- return true
179
+ return true;
178
180
  }
179
181
 
180
182
  if (a && b && typeof a === 'object' && typeof b === 'object') {
181
- const aProps = Object.keys(a), bProps = Object.keys(b)
183
+ const aProps = Object.keys(a),
184
+ bProps = Object.keys(b);
182
185
  if (!deepEqual(aProps, bProps)) {
183
- return false
186
+ return false;
184
187
  }
185
188
  for (let i = 0; i < aProps.length; i++) {
186
- const prop = aProps[i]
189
+ const prop = aProps[i];
187
190
  if (!deepEqual(a[prop], b[prop])) {
188
- return false
191
+ return false;
189
192
  }
190
193
  }
191
- return true
194
+ return true;
192
195
  }
193
- return false
196
+ return false;
194
197
  }
195
198
 
196
199
  function isObject(value) {
197
- var type = typeof value
198
- return !!value && (type == 'object' || type == 'function')
200
+ var type = typeof value;
201
+ return !!value && (type == 'object' || type == 'function');
199
202
  }
200
203
 
201
204
  function isIndex(value, length) {
202
- length = length == null ? 9007199254740991 : length
205
+ length = length == null ? 9007199254740991 : length;
203
206
  return (
204
207
  !!length &&
205
208
  (typeof value == 'number' || /^(?:0|[1-9]\d*)$/.test(value)) &&
206
209
  value > -1 &&
207
210
  value % 1 == 0 &&
208
211
  value < length
209
- )
212
+ );
210
213
  }
211
214
 
212
215
  function assignValue(object, key, value) {
213
- var objValue = object[key]
216
+ var objValue = object[key];
214
217
  if (
215
- !(
216
- Object.hasOwnProperty.call(object, key) &&
217
- (objValue === value || (objValue !== objValue && value !== value))
218
- ) ||
218
+ !(Object.hasOwnProperty.call(object, key) && (objValue === value || (objValue !== objValue && value !== value))) ||
219
219
  (value === undefined && !(key in object))
220
220
  ) {
221
- object[key] = value
221
+ object[key] = value;
222
222
  }
223
223
  }
224
224
 
225
225
  export function set(object, path, value) {
226
226
  if (!isObject(object)) {
227
- return object
227
+ return object;
228
228
  }
229
- path = path.split('.')
229
+ path = path.split('.');
230
230
 
231
231
  var index = -1,
232
232
  length = path.length,
233
233
  lastIndex = length - 1,
234
- nested = object
234
+ nested = object;
235
235
 
236
236
  while (nested != null && ++index < length) {
237
237
  var key = path[index],
238
- newValue = value
238
+ newValue = value;
239
239
 
240
240
  if (index != lastIndex) {
241
- var objValue = nested[key]
242
- newValue = undefined
241
+ var objValue = nested[key];
242
+ newValue = undefined;
243
243
  if (newValue === undefined) {
244
- newValue = isObject(objValue)
245
- ? objValue
246
- : isIndex(path[index + 1])
247
- ? []
248
- : {}
244
+ newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {};
249
245
  }
250
246
  }
251
- assignValue(nested, key, newValue)
252
- nested = nested[key]
247
+ assignValue(nested, key, newValue);
248
+ nested = nested[key];
253
249
  }
254
- return object
250
+ return object;
255
251
  }
256
252
 
257
253
  export function findLoginPage() {
258
254
  const { app } = getApp();
259
255
  const { pages = [] } = app.__internal__.getConfig();
260
- return pages.find(item => item.type === 'login');
256
+ return pages.find((item) => item.type === 'login');
261
257
  }
262
258
 
263
259
  let _AUTH_CONFIG_CACHE = null;
@@ -269,7 +265,7 @@ export async function getAuthConfig() {
269
265
  }
270
266
  try {
271
267
  const res = await app.cloud.callWedaApi({
272
- action: "DescribeRuntimeResourceStrategy",
268
+ action: 'DescribeRuntimeResourceStrategy',
273
269
  data: {
274
270
  ResourceType: `<%= isAdminPortal? 'modelApp' : 'app'%>`,
275
271
  ResourceId: app.id,
@@ -285,15 +281,15 @@ export async function getAuthConfig() {
285
281
  } catch (e) {
286
282
  return {
287
283
  NeedLogin: false,
288
- RejectStrategy: "show_warning",
284
+ RejectStrategy: 'show_warning',
289
285
  };
290
286
  }
291
287
  }
292
288
 
293
- let _AUTH_CACHE_MAP = {}
289
+ let _AUTH_CACHE_MAP = {};
294
290
 
295
291
  async function getAccessPermission(app, appId, pageId) {
296
- const cacheKey = `${appId}-${pageId}`
292
+ const cacheKey = `${appId}-${pageId}`;
297
293
  if (_AUTH_CACHE_MAP[cacheKey] !== undefined) {
298
294
  return _AUTH_CACHE_MAP[cacheKey];
299
295
  }
@@ -345,9 +341,10 @@ export function formatErrorMsg(e) {
345
341
  * 检查页面权限
346
342
  **/
347
343
  export async function checkAuth(app, appId, $page) {
344
+ return true;
348
345
  const loginPage = findLoginPage(app);
349
346
  if (loginPage?.id === $page.id) {
350
- return true
347
+ return true;
351
348
  }
352
349
  app.showNavigationBarLoading();
353
350
  const requestList = [getAccessPermission(app, appId, $page.id)];
@@ -400,16 +397,16 @@ export function redirectToLogin(currentPage) {
400
397
  currentPage = app.utils.getCurrentPage() || {};
401
398
  }
402
399
  if (loginPage?.id === currentPage.id) {
403
- return true
400
+ return true;
404
401
  }
405
402
  if (loginPage) {
406
403
  app.redirectTo({
407
404
  pageId: loginPage.id,
408
405
  params: {
409
406
  sourcePageId: currentPage.id,
410
- sourcePageParams: currentPage.params
411
- }
412
- })
407
+ sourcePageParams: currentPage.params,
408
+ },
409
+ });
413
410
  } else {
414
411
  app.showToast({
415
412
  title: '用户未登录',
@@ -433,8 +430,8 @@ export function formatEnum(path, optionname) {
433
430
  let value = !isSingle
434
431
  ? JSON.parse(parseOptions)?.find((item) => item?.key === path)?.value
435
432
  : JSON.parse(parseOptions)
436
- ?.filter((item) => path.some((pathValue) => item?.key === pathValue))
437
- .map((item) => multiTmp.push(item?.value));
433
+ ?.filter((item) => path.some((pathValue) => item?.key === pathValue))
434
+ .map((item) => multiTmp.push(item?.value));
438
435
  // 对多选或者单选有不同处理
439
436
  return !isSingle ? value : multiTmp?.join(',');
440
437
  }
@@ -7,7 +7,7 @@ import { getDeep } from './util'
7
7
  * @returns Dipsonsers
8
8
  */
9
9
  export function runWatchers({ watchEffects = {}, watch = {}, watchState = {}, watchWidget = {} }, mpInst) {
10
- const weappInst = mpInst.getWeAppInst()
10
+ const weappInst = mpInst._getInstance()
11
11
  const disposers = []
12
12
  Object.keys(watchEffects).map(name => {
13
13
  const fn = watchEffects[name]
@@ -3,9 +3,10 @@ import { createEventHandlers, createComputed } from './util'
3
3
  import { createWidgets, getWidget, disposeWidget } from './widget'
4
4
  import mergeRenderer from './merge-renderer'
5
5
  import { runWatchers } from './watch'
6
- import sdk from './weapp-sdk'
7
6
  import lodashGet from 'lodash.get';
8
7
  import { createInitData } from './widget';
8
+ import { commonCompBehavior } from '@cloudbase/weda-client';
9
+ import { $w as baseAPI } from '../app/weapps-api'
9
10
 
10
11
  /**
11
12
  * Lowcodes of all components
@@ -30,12 +31,12 @@ export function createComponent(key, behaviors, properties, events, handler, dat
30
31
  multipleSlots: true,
31
32
  styleIsolation: 'shared',
32
33
  },
33
- behaviors: behaviors,
34
+ /**
35
+ * commonCompBehavior 生命周期最先执行
36
+ */
37
+ behaviors: [commonCompBehavior, ...behaviors,],
34
38
  // externalClasses: ['class'],
35
39
  properties: {
36
- id: {
37
- type: String
38
- },
39
40
  style: {
40
41
  type: String
41
42
  },
@@ -53,23 +54,23 @@ export function createComponent(key, behaviors, properties, events, handler, dat
53
54
  this._disposers = []
54
55
  },
55
56
  attached() {
56
- const $comp = this.getWeAppInst()
57
+ const $comp = this._getInstance()
57
58
  if(!$comp) return
58
59
 
59
60
  $comp.props.events = createPropEvents(events, this)
60
- $comp.widgets = {}
61
- const { widgets, rootWidget: virtualRootWidget } = createWidgets(widgetProps, dataBinds, $comp.widgets, this)
61
+ const { widgets, rootWidget: virtualRootWidget } = createWidgets(widgetProps, dataBinds, {}, this)
62
+ $comp.widgets = widgets
62
63
  this._virtualRootWidget = virtualRootWidget
63
64
 
64
65
  try {
65
66
  lifeCycle.onAttached && lifeCycle.onAttached.call($comp)
66
67
  this.__mnt__ = (e) => {
67
- const widget = lodashGet(widgets, e.target.id);
68
+ const widget = getWidget($comp.widgets, e.target.id)
68
69
  widget._methods = e.detail.methods;
69
70
  }
70
71
  this.__unmnt__ = (e) => {
71
- const widget = lodashGet(widgets, e.target.id);
72
- delete widget._methods;
72
+ const widget = lodashGet($comp.widgets, e.target.id);
73
+ widget._methods = {}
73
74
  }
74
75
  if ($comp.methods) {
75
76
  this.triggerEvent('attached', {
@@ -80,16 +81,16 @@ export function createComponent(key, behaviors, properties, events, handler, dat
80
81
  console.error('Component lifecycle(attached) error', this.is, e)
81
82
  }
82
83
 
83
- this._disposers = this.initMergeRenderer(widgets)
84
+ this._disposers = this.initMergeRenderer($comp.widgets)
84
85
  },
85
86
  ready() {
86
- const $comp = this.getWeAppInst()
87
+ const $comp = this._getInstance()
87
88
  if(!$comp) return
88
89
  this._disposers.push(...runWatchers(index, this))
89
90
  lifeCycle.onReady && lifeCycle.onReady.call($comp)
90
91
  },
91
92
  detached() {
92
- const $comp = this.getWeAppInst()
93
+ const $comp = this._getInstance()
93
94
  if(!$comp) return
94
95
 
95
96
  $comp.widgets = null
@@ -105,17 +106,17 @@ export function createComponent(key, behaviors, properties, events, handler, dat
105
106
 
106
107
  pageLifetimes: {
107
108
  show() {
108
- const $comp = this.getWeAppInst()
109
+ const $comp = this._getInstance()
109
110
  if(!$comp) return
110
111
  lifeCycle.onPageShow && lifeCycle.onPageShow.call($comp)
111
112
  },
112
113
  hide() {
113
- const $comp = this.getWeAppInst()
114
+ const $comp = this._getInstance()
114
115
  if(!$comp) return
115
116
  lifeCycle.onPageHide && lifeCycle.onPageHide.call($comp)
116
117
  },
117
118
  resize(size) {
118
- const $comp = this.getWeAppInst()
119
+ const $comp = this._getInstance()
119
120
  if(!$comp) return
120
121
  lifeCycle.onPageResize && lifeCycle.onPageResize.call($comp, size)
121
122
  }
@@ -124,24 +125,17 @@ export function createComponent(key, behaviors, properties, events, handler, dat
124
125
  methods: {
125
126
  ...createEventHandlers(evtListeners, { looseError: true }),
126
127
  ...mergeRenderer,
127
- getWeAppInst() {
128
- const $comp = this.$WEAPPS_COMP
129
- if ($comp) { return $comp }
130
-
131
- if (!this.selectOwnerComponent) {
132
- console.error('Fatal error: not support selectOwnerComponent API, need 2.8.2')
133
- return null
134
- }
135
-
136
- const owner = this.selectOwnerComponent()
137
- const widget = getWidget(owner.getWeAppInst().widgets, this.id)
138
- if (!widget || !widget.$comp) {
139
- console.error('Fatal error: weapps component instance not created', this.is, this.id)
128
+ _getInstance() {
129
+ if(!this.$WEAPPS_COMP){
130
+ const widget = this.$widget
131
+ if (!widget) {
132
+ console.error('Fatal error: weapps component instance not created', this.is, this.id)
133
+ }else {
134
+ widget.getDom = (fields) => this._virtualRootWidget.children[0].getDom(fields)
135
+ this.$WEAPPS_COMP = create$comp(widget)
136
+ }
140
137
  }
141
- widget.getDom = (fields) => this._virtualRootWidget.children[0].getDom(fields)
142
-
143
- this.$WEAPPS_COMP = widget.$comp
144
- return widget.$comp
138
+ return this.$WEAPPS_COMP
145
139
  },
146
140
  },
147
141
  // observers: createObservers(Object.keys(properties))
@@ -158,6 +152,8 @@ export function create$comp(w) {
158
152
  const { stateFn, computedFuncs, handler, lib } = lowcode
159
153
 
160
154
  const $comp = {
155
+ __internal__: {
156
+ },
161
157
  state: {},
162
158
  computed: {},
163
159
  widgets: {},
@@ -170,13 +166,12 @@ export function create$comp(w) {
170
166
  },
171
167
  handler: {},
172
168
  lib,
173
- i18n: {
174
- ...sdk.i18n,
175
- t(key, data) {
176
- const ns = libCode;
177
- return sdk.i18n.t(`${ns}:${key}`, data)
178
- },
179
- }
169
+ // i18n: {
170
+ // t(key, data) {
171
+ // const ns = libCode;
172
+ // return sdk.i18n.t(`${ns}:${key}`, data)
173
+ // },
174
+ // }
180
175
  }
181
176
  $comp.$WEAPPS_COMP = $comp // TODO $comp will replaced to this.$WEAPPS_COMP
182
177
  $comp.computed = createComputed(computedFuncs, $comp)
@@ -187,13 +182,27 @@ export function create$comp(w) {
187
182
  $comp.state = observable(stateFn.call($comp)) // May depend on this.props.data.xxx
188
183
 
189
184
 
185
+ $comp.__internal__.$w = new Proxy(
186
+ baseAPI,
187
+ {
188
+ get(target, prop) {
189
+ // 尝试代理组件级别组件实例
190
+ const childWidget = $comp.widgets?.[prop];
191
+ if (childWidget) {
192
+ return childWidget._userWidget;
193
+ }
194
+ return target[prop]
195
+ },
196
+ },
197
+ );
198
+
190
199
  return $comp
191
200
  }
192
201
 
193
202
  function createObservers(props) {
194
203
  return props.reduce((observers, prop) => {
195
204
  observers[prop] = function (newVal) {
196
- const data = this.getWeAppInst().props.data
205
+ const data = this._getInstance().props.data
197
206
  if (!deepEqual(data[prop], newVal)) {
198
207
  data[prop] = newVal
199
208
  } else {
@@ -240,7 +249,7 @@ function createPropEvents(events, mpInst) {
240
249
  mpInst.setData({ value: evt.getValueFromEvent({ detail: evtDetail }) })
241
250
  }
242
251
  mpInst.triggerEvent(evt.name, evtDetail)
243
- mpInst.getWeAppInst().node._eventListeners.emit(evt.name, evtDetail)
252
+ mpInst._getInstance().node._eventListeners.emit(evt.name, evtDetail)
244
253
  }
245
254
  }
246
255
  })