Skip to content

Commit 688919d

Browse files
authored
Merge pull request #2117 from didi/feat-preview-image-add-current
补充web下previewImage的current
2 parents 2298532 + 4ec2f61 commit 688919d

10 files changed

Lines changed: 77 additions & 55 deletions

File tree

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
```

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/webpack-plugin/lib/runtime/components/react/mpx-portal/portal-manager.tsx

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { useState, useCallback, forwardRef, ForwardedRef, useImperativeHandle, ReactNode, ReactElement } from 'react'
2-
import { View, StyleSheet } from 'react-native'
1+
import { useState, useCallback, forwardRef, ForwardedRef, useImperativeHandle, ReactNode, ReactElement, Fragment } from 'react'
32

43
export type State = {
54
portals: Array<{
@@ -48,13 +47,10 @@ const _PortalManager = forwardRef((props: PortalManagerProps, ref:ForwardedRef<u
4847

4948
return (
5049
<>
51-
{state.portals.map(({ key, children }, i) => (
52-
<View
53-
key={key}
54-
collapsable={false} // Need collapsable=false here to clip the elevations
55-
style={[StyleSheet.absoluteFill, { zIndex: 1000 + i, pointerEvents: 'box-none' }]}>
50+
{state.portals.map(({ key, children }) => (
51+
<Fragment key={key}>
5652
{children}
57-
</View>
53+
</Fragment>
5854
))}
5955
</>
6056
)

packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const styles = StyleSheet.create({
7676
borderRadius: 10
7777
}
7878
})
79+
7980
const _WebView = forwardRef<HandlerRef<WebView, WebViewProps>, WebViewProps>((props, ref): JSX.Element | null => {
8081
const { src, bindmessage, bindload, binderror } = props
8182
const mpx = global.__mpx
@@ -126,10 +127,27 @@ const _WebView = forwardRef<HandlerRef<WebView, WebViewProps>, WebViewProps>((pr
126127
style: defaultWebViewStyle
127128
})
128129

130+
const hostValidate = (url: string) => {
131+
const host = url && new URL(url).host
132+
const hostWhitelists = mpx.config.rnConfig?.webviewConfig?.hostWhitelists || []
133+
if (hostWhitelists.length) {
134+
return hostWhitelists.some((item: string) => {
135+
return host.endsWith(item)
136+
})
137+
} else {
138+
return true
139+
}
140+
}
141+
129142
if (!src) {
130143
return null
131144
}
132145

146+
if (!hostValidate(src)) {
147+
console.error('访问页面域名不符合domainWhiteLists白名单配置,请确认是否正确配置该域名白名单')
148+
return null
149+
}
150+
133151
const _reload = function () {
134152
if (__mpx_mode__ !== 'ios') {
135153
fristLoaded.current = false // 安卓需要重新设置
@@ -182,6 +200,9 @@ const _WebView = forwardRef<HandlerRef<WebView, WebViewProps>, WebViewProps>((pr
182200
}
183201
}
184202
const _message = function (res: WebViewMessageEvent) {
203+
if (!hostValidate(res.nativeEvent?.url)) {
204+
return
205+
}
185206
let data: MessageData = {}
186207
let asyncCallback
187208
const navObj = promisify({ redirectTo, navigateTo, navigateBack, reLaunch, switchTab })
@@ -232,7 +253,7 @@ const _WebView = forwardRef<HandlerRef<WebView, WebViewProps>, WebViewProps>((pr
232253
break
233254
default:
234255
if (type) {
235-
const implement = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type]
256+
const implement = mpx.config.rnConfig.webviewConfig && mpx.config.rnConfig.webviewConfig.apiImplementations && mpx.config.rnConfig.webviewConfig.apiImplementations[type]
236257
if (isFunction(implement)) {
237258
asyncCallback = Promise.resolve(implement(...params))
238259
} else {

packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export default {
124124
case 'postMessage':
125125
let data = {
126126
type: 'message',
127-
data: params[0]?.data
127+
data: params[0]?.data || params[0] // 补充兜底逻辑
128128
}
129129
this.$emit(eventMessage, getCustomEvent(eventMessage, data, this))
130130
asyncCallback = Promise.resolve({
@@ -148,7 +148,7 @@ export default {
148148
break
149149
default:
150150
if (type) {
151-
const implement = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type]
151+
const implement = mpx.config.webConfig?.webviewConfig?.apiImplementations?.[type]
152152
if (isFunction(implement)) {
153153
asyncCallback = Promise.resolve(implement(...params))
154154
} else {
@@ -174,7 +174,7 @@ export default {
174174
})
175175
},
176176
hostValidate (host) {
177-
const hostWhitelists = mpx.config.webviewConfig && mpx.config.webviewConfig.hostWhitelists || []
177+
const hostWhitelists = mpx.config.webConfig?.webviewConfig?.hostWhitelists || []
178178
if (hostWhitelists.length) {
179179
return hostWhitelists.some((item) => {
180180
return host.endsWith(item)

0 commit comments

Comments
 (0)