Skip to content

Commit 059aeaa

Browse files
authored
Merge branch 'master' into feat-rn-support-disableRequireAsync
2 parents 475f585 + 2e343f7 commit 059aeaa

27 files changed

Lines changed: 1094 additions & 463 deletions

File tree

docs-vitepress/guide/basic/component.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,6 @@ createComponent({
151151
})
152152
</script>
153153
```
154-
// TODO data 的注意项
155-
156154

157155
### computed
158156

docs-vitepress/guide/extend/api-proxy.md

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Api代理
22

3-
> convert API at each end 各个平台之间 api 进行转换,目前已支持微信转支付宝、微信转web
3+
> convert API at each end 各个平台之间 api 进行转换,目前已支持微信转支付宝、微信转web、微信转RN
44
55
## Usage
66

@@ -31,12 +31,13 @@ proxy.navigateTo({
3131

3232
|参数名称|类型|含义|是否必填| 默认值 |备注|
3333
|---|---|---|---|-------|---|
34-
|platform|Object|各平台之间的转换|| |使用 mpx 脚手架配置会自动进行转换,无需配置|
35-
|exclude|Array(String)|跨平台时不需要转换的 api|-|
34+
|~~platform~~|~~Object~~|~~各平台之间的转换~~|~~~~| |已删除|
35+
|~~exclude~~|~~Array(String)~~|~~跨平台时不需要转换的 api~~|已删除|
3636
|usePromise|Boolean|是否将 api 转化为 promise 格式使用|| false |-|
3737
|whiteList|Array(String)|强行转化为 promise 格式的 api|| [] |需要 usePromise 设为 true|
3838
|blackList|Array(String)|强制不变成 promise 格式的 api|| [] |-|
39-
|fallbackMap|Object|对于不支持的API,允许配置一个映射表,接管不存在的API|| {} |-|
39+
|~~fallbackMap~~|~~Object~~|~~对于不支持的API,允许配置一个映射表,接管不存在的API~~|~~~~| {} |已删除|
40+
| custom | Object | 提供用户在各渠道下自定义api开放能力 || [] | - |
4041

4142
## example
4243

@@ -65,6 +66,12 @@ mpx.showModal({
6566

6667
> 开启usePromise时所有的异步api将返回promise,但是小程序中存在一些异步api本身的返回值是具有意义的,如uploadFile会返回一个uploadTask对象用于后续监听上传进度或者取消上传,在对api进行promise化之后我们会将原始的返回值挂载到promise.__returned属性上,便于开发者访问使用
6768
69+
**⚠️ 注意**
70+
- mpx中开启usePromise后,所有options中有success和fail都会以promise风格处理,不与微信拉齐
71+
- 开启 usePromise 后,若同时写了 success 和 then,两者都会执行。但需注意:启用 usePromise 后,API 调用应使用 promise 方式;若仍用 success/fail 接收回调,当 API 调用失败时,promise 的 catch 会无法捕获错误,进而触发 onUnhandledRejection 来捕获该错误。
72+
- 整体支持 promise 写法,但个别 API 若想继续用 success/fail 回调,又不想出现调用失败未被 catch 的报错,可在调用API方法时传 usePromise: false(默认 true),临时关闭本次 promise 转换
73+
74+
6875
```js
6976
import mpx from '@mpxjs/core'
7077
import apiProxy from '@mpxjs/api-proxy'
@@ -82,4 +89,16 @@ mpx.showActionSheet({
8289
.catch(err => {
8390
console.log(err)
8491
})
92+
93+
// 关闭本次调用转换promise风格
94+
mpx.showActionSheet({
95+
itemList: ['A', 'B', 'C'],
96+
success (res) {
97+
console.log(res.tapIndex)
98+
},
99+
fail () {
100+
console.log(err)
101+
},
102+
usePromise: false // 关闭设置
103+
})
85104
```

docs-vitepress/guide/platform/rn.md

Lines changed: 325 additions & 244 deletions
Large diffs are not rendered by default.

packages/api-proxy/src/common/js/promisify.js

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,14 @@
1-
import { ENV_OBJ } from './utils'
1+
import { ENV_OBJ, warn } from './utils'
22

33
// 特别指定的不进行Promise封装的方法
44
const blackList = [
5-
'clearStorage',
6-
'hideToast',
7-
'hideLoading',
85
'drawCanvas',
96
'canIUse',
10-
'stopRecord',
11-
'pauseVoice',
12-
'stopVoice',
13-
'pauseBackgroundAudio',
14-
'stopBackgroundAudio',
15-
'showNavigationBarLoading',
16-
'hideNavigationBarLoading',
177
'getPerformance',
18-
'hideKeyboard',
19-
'stopPullDownRefresh',
20-
'pageScrollTo',
218
'reportAnalytics',
229
'getMenuButtonBoundingClientRect',
2310
'reportMonitor',
2411
'reportEvent',
25-
'connectSocket',
2612
'base64ToArrayBuffer',
2713
'arrayBufferToBase64',
2814
'getDeviceInfo',
@@ -33,16 +19,12 @@ const blackList = [
3319
'postMessageToReferrerPage',
3420
'postMessageToReferrerMiniProgram',
3521
'reportPerformance',
36-
'getPerformance',
37-
'preDownloadSubpackage',
3822
'router',
3923
'nextTick',
4024
'checkIsPictureInPictureActive',
4125
'worklet',
4226
'revokeBufferURL',
43-
'reportEvent',
4427
'getExptInfoSync',
45-
'reserveChannelsLive',
4628
'getNFCAdapter',
4729
'isVKSupport'
4830
]
@@ -79,18 +61,22 @@ function promisify (listObj, whiteList, customBlackList) {
7961
if (typeof listObj[key] !== 'function') {
8062
return
8163
}
82-
83-
result[key] = function (...args) {
84-
const obj = args[0] || {}
85-
// 不需要转换 or 用户已定义回调,则不处理
86-
if (!promisifyFilter(key)) {
87-
return listObj[key].apply(ENV_OBJ, args)
88-
} else { // 其他情况进行转换
64+
if (!promisifyFilter(key)) {
65+
result[key] = listObj[key].bind(ENV_OBJ)
66+
} else {
67+
result[key] = function (...args) {
68+
const obj = args[0] || {}
69+
if (obj.usePromise === false) {
70+
return listObj[key].apply(ENV_OBJ, args)
71+
}
8972
if (!args[0]) args.unshift(obj)
9073
let returned
9174
const promise = new Promise((resolve, reject) => {
9275
const originSuccess = obj.success
9376
const originFail = obj.fail
77+
if (originSuccess || originFail) {
78+
warn(`The [${key}] method has been promisified, please use .then or .catch to handle the result, if you need to handle the result with options.success/fail, please set options.usePromise to false to close the promisify in this call temporarily. `)
79+
}
9480
obj.success = function (res) {
9581
originSuccess && originSuccess.call(this, res)
9682
resolve(res)

packages/api-proxy/src/common/js/utils.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { hasOwn, noop, getEnvObj, getFocusedNavigation, error as errorHandler, warn as warnHandler } from '@mpxjs/utils'
2-
import { getCurrentInstance } from '@mpxjs/core'
32

43
/**
54
*
@@ -90,8 +89,7 @@ function failHandle (result, fail, complete) {
9089
}
9190

9291
function getCurrentPageId () {
93-
const currentInstance = getCurrentInstance()
94-
const id = currentInstance?.proxy?.getPageId() || getFocusedNavigation()?.pageId || null
92+
const id = getFocusedNavigation()?.pageId || null
9593
return id
9694
}
9795

packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const styles = StyleSheet.create({
2828
bottom: 0,
2929
right: 0,
3030
position: 'absolute',
31-
zIndex: 1000
31+
zIndex: 10000
3232
},
3333
maskWrap: {
3434
left: 0,
@@ -65,8 +65,8 @@ const styles = StyleSheet.create({
6565
},
6666
itemTextStyle: {
6767
fontSize: 18,
68-
height: 22,
69-
lineHeight: 22
68+
paddingTop: 2,
69+
paddingBottom: 2
7070
},
7171
buttonStyle: {
7272
paddingTop: 10,
@@ -195,8 +195,8 @@ function ActionSheet ({ itemColor, height, success, fail, complete, alertText, i
195195
style={{
196196
color: '#000000',
197197
fontSize: 18,
198-
lineHeight: 22,
199-
height: 22,
198+
paddingTop: 2,
199+
paddingBottom: 2,
200200
width: '100%',
201201
textAlign: 'center'
202202
}}

packages/api-proxy/src/platform/api/image/Preview.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ export default class Preview {
4141
})
4242
// click to close
4343
bindTap(this.preview, () => {
44-
this.currentIndex = 0
4544
this.preview.style.display = 'none'
4645
this.preview.querySelector('.__mpx_preview_images__').remove()
4746
this.preview.remove()
@@ -54,17 +53,19 @@ export default class Preview {
5453
* @param {string[]} options.urls - 图片地址数组
5554
*/
5655
show (options) {
57-
const supported = ['urls', 'success', 'fail', 'complete']
56+
const supported = ['urls', 'success', 'fail', 'complete', 'current']
5857
Object.keys(options).forEach(key => !supported.includes(key) && warn(`previewImage: 暂不支持选项 ${key} !`))
59-
const { urls, success, fail, complete } = options
58+
const { urls, current, success, fail, complete } = options
6059
try {
60+
this.currentIndex = urls.indexOf(current) > -1 ? urls.indexOf(current) : 0
6161
getRootElement().appendChild(this.preview)
6262
this.preview.style.display = 'block'
6363
// create images with urls
6464
// append to preview
6565
this.preview.appendChild(createDom('div', { class: '__mpx_preview_images__' }, urls.map(url => createDom('div', {
6666
style: `background-image: url(${url})`
6767
}))))
68+
this.preview.querySelector('.__mpx_preview_images__').style.transform = `translateX(-${this.currentIndex * 100}%)`
6869
this.maxIndex = urls.length
6970
this.updateTextTip()
7071
successHandle({ errMsg: 'previewImage:ok' }, success, complete)

packages/api-proxy/src/platform/api/modal/rnModal.jsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ const showModal = function (options = {}) {
4747
alignItems: 'center',
4848
display: 'flex',
4949
backgroundColor: 'rgba(0,0,0,0.6)',
50-
position: 'absolute'
50+
position: 'absolute',
51+
zIndex: 10000
5152
},
5253
modalContent: {
5354
paddingTop: 20,

packages/api-proxy/src/platform/api/route/index.ios.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function isLock (navigationHelper, type, options) {
2424
navigationHelper.lastFailCallback('timeout')
2525
navigationHelper.lastFailCallback = null
2626
}
27-
}, 350)
27+
}, 1000)
2828
return false
2929
}
3030

packages/core/src/platform/builtInMixins/proxyEventMixin.js

Lines changed: 74 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -4,70 +4,85 @@ import contextMap from '../../dynamic/vnode/context'
44

55
function logCallbackNotFound (context, callbackName) {
66
const location = context.__mpxProxy && context.__mpxProxy.options.mpxFileResource
7-
error(`Instance property [${callbackName}] is not function, please check.`, location)
7+
error(
8+
`Instance property [${callbackName}] is not function, please check.`,
9+
location
10+
)
11+
}
12+
13+
function handleEvent (context, $event, isCapture) {
14+
if (typeof Mpx.config.proxyEventHandler === 'function') {
15+
try {
16+
Mpx.config.proxyEventHandler($event, context)
17+
} catch (e) {
18+
}
19+
}
20+
const location = context.__mpxProxy.options.mpxFileResource
21+
const type = $event.type
22+
// thanos 平台特殊事件标识
23+
const emitMode = $event.detail && $event.detail.mpxEmit
24+
if (!type) {
25+
error('Event object must have [type] property!', location)
26+
return
27+
}
28+
let fallbackType = ''
29+
if (type === 'begin' || type === 'end') {
30+
// 地图的 regionchange 事件会派发 e.type 为 begin 和 end 的事件
31+
fallbackType = __mpx_mode__ === 'ali' ? 'regionChange' : 'regionchange'
32+
} else if (/-([a-z])/.test(type)) {
33+
fallbackType = dash2hump(type)
34+
} else if (__mpx_mode__ === 'ali') {
35+
fallbackType = type.replace(/^./, i => i.toLowerCase())
36+
}
37+
const target = $event.currentTarget || $event.target
38+
if (!target) {
39+
error(`[${type}] event object must have [currentTarget/target] property!`, location)
40+
return
41+
}
42+
const mode = isCapture ? 'capture' : 'bubble'
43+
const eventConfigs = target.dataset.eventconfigs?.[mode] || {}
44+
45+
const curEventConfig = eventConfigs[type] || eventConfigs[fallbackType] || []
46+
// 如果有 mpxuid 说明是运行时组件,那么需要设置对应的上下文
47+
const rootRuntimeContext = contextMap.get(target.dataset.mpxuid)
48+
const runtimeContext = rootRuntimeContext || context
49+
let returnedValue
50+
curEventConfig.forEach((item) => {
51+
const callbackName = item[0]
52+
if (emitMode) {
53+
// thanos 平台特殊事件标识处理
54+
$event = $event.detail.data
55+
}
56+
if (callbackName) {
57+
const params = item.length > 1
58+
? item.slice(1).map(item => {
59+
if (item === '__mpx_event__') {
60+
return $event
61+
} else {
62+
return item
63+
}
64+
})
65+
: [$event]
66+
if (typeof runtimeContext[callbackName] === 'function') {
67+
returnedValue = runtimeContext[callbackName].apply(
68+
runtimeContext,
69+
params
70+
)
71+
} else {
72+
logCallbackNotFound(runtimeContext, callbackName)
73+
}
74+
}
75+
})
76+
return returnedValue
877
}
978

1079
export default function proxyEventMixin () {
1180
const methods = {
1281
__invoke ($event) {
13-
if (typeof Mpx.config.proxyEventHandler === 'function') {
14-
try {
15-
Mpx.config.proxyEventHandler($event, this)
16-
} catch (e) {
17-
}
18-
}
19-
const location = this.__mpxProxy.options.mpxFileResource
20-
const type = $event.type
21-
// thanos 平台特殊事件标识
22-
const emitMode = $event.detail && $event.detail.mpxEmit
23-
if (!type) {
24-
error('Event object must have [type] property!', location)
25-
return
26-
}
27-
let fallbackType = ''
28-
if (type === 'begin' || type === 'end') {
29-
// 地图的 regionchange 事件会派发 e.type 为 begin 和 end 的事件
30-
fallbackType = __mpx_mode__ === 'ali' ? 'regionChange' : 'regionchange'
31-
} else if (/-([a-z])/.test(type)) {
32-
fallbackType = dash2hump(type)
33-
} else if (__mpx_mode__ === 'ali') {
34-
fallbackType = type.replace(/^./, i => i.toLowerCase())
35-
}
36-
const target = $event.currentTarget || $event.target
37-
if (!target) {
38-
error(`[${type}] event object must have [currentTarget/target] property!`, location)
39-
return
40-
}
41-
const eventConfigs = target.dataset.eventconfigs || {}
42-
const curEventConfig = eventConfigs[type] || eventConfigs[fallbackType] || []
43-
// 如果有 mpxuid 说明是运行时组件,那么需要设置对应的上下文
44-
const rootRuntimeContext = contextMap.get(target.dataset.mpxuid)
45-
const context = rootRuntimeContext || this
46-
let returnedValue
47-
curEventConfig.forEach((item) => {
48-
const callbackName = item[0]
49-
if (emitMode) {
50-
// thanos 平台特殊事件标识处理
51-
$event = $event.detail.data
52-
}
53-
if (callbackName) {
54-
const params = item.length > 1
55-
? item.slice(1).map(item => {
56-
if (item === '__mpx_event__') {
57-
return $event
58-
} else {
59-
return item
60-
}
61-
})
62-
: [$event]
63-
if (typeof context[callbackName] === 'function') {
64-
returnedValue = context[callbackName].apply(context, params)
65-
} else {
66-
logCallbackNotFound(context, callbackName)
67-
}
68-
}
69-
})
70-
return returnedValue
82+
return handleEvent(this, $event, false)
83+
},
84+
__captureInvoke ($event) {
85+
return handleEvent(this, $event, true)
7186
},
7287
__model (expr, $event, valuePath = ['value'], filterMethod) {
7388
const innerFilter = {

0 commit comments

Comments
 (0)