提交 a99e666b 编写于 作者: fxy060608's avatar fxy060608

feat(api): format args

上级 72bb6b1c
...@@ -32,7 +32,11 @@ declare var __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__: boolean ...@@ -32,7 +32,11 @@ declare var __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__: boolean
declare var __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__: boolean declare var __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__: boolean
declare var __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__: boolean declare var __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__: boolean
// TODO // TODO
declare var __uniRoutes: any declare var __uniRoutes: UniApp.UniRoutes
declare var __uniConfig: UniApp.UniConfig declare var __uniConfig: UniApp.UniConfig
declare var UniViewJSBridge: any declare var UniViewJSBridge: any
declare var UniServiceJSBridge: any declare var UniServiceJSBridge: any
declare const getCurrentPages: <T extends AnyObject = {}>(
isAll?: boolean
) => Array<Page.PageInstance<AnyObject, T> & T>
...@@ -22,6 +22,7 @@ declare namespace UniApp { ...@@ -22,6 +22,7 @@ declare namespace UniApp {
} }
interface UniConfig { interface UniConfig {
ready?: boolean
router: { router: {
strict: boolean strict: boolean
base: string base: string
...@@ -35,6 +36,15 @@ declare namespace UniApp { ...@@ -35,6 +36,15 @@ declare namespace UniApp {
rightWindow?: LayoutWindowOptions rightWindow?: LayoutWindowOptions
} }
interface UniRoute {
path: string
redirect?: string
meta: PageRouteMeta
component?: any
}
type UniRoutes = UniRoute[]
interface PageNavigationBarButton { interface PageNavigationBarButton {
type: type:
| 'none' | 'none'
...@@ -115,6 +125,7 @@ declare namespace UniApp { ...@@ -115,6 +125,7 @@ declare namespace UniApp {
} }
interface PageRouteMeta extends PagesJsonPageStyle { interface PageRouteMeta extends PagesJsonPageStyle {
id: number id: number
isNVue?: boolean
isQuit?: boolean isQuit?: boolean
isEntry?: boolean isEntry?: boolean
isTabBar?: boolean isTabBar?: boolean
......
import { isPlainObject } from '@vue/shared'
import { ApiOptions, ApiProtocols } from '../../protocols/type' import { ApiOptions, ApiProtocols } from '../../protocols/type'
import { API_TYPE_ON_PROTOCOLS, validateProtocols } from '../protocol' import { API_TYPE_ON_PROTOCOLS, validateProtocols } from '../protocol'
import { import {
...@@ -19,6 +20,17 @@ type API_TYPES = ...@@ -19,6 +20,17 @@ type API_TYPES =
| typeof API_TYPE_ASYNC | typeof API_TYPE_ASYNC
function formatApiArgs(args: any[], options?: ApiOptions) { function formatApiArgs(args: any[], options?: ApiOptions) {
const params = args[0]
if (
!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))
) {
return args
}
const formatArgs = options.formatArgs!
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params)
})
return args return args
} }
...@@ -39,7 +51,12 @@ function wrapperSyncApi(fn: Function) { ...@@ -39,7 +51,12 @@ function wrapperSyncApi(fn: Function) {
function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) { function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) {
return (args: Record<string, any>) => { return (args: Record<string, any>) => {
const callbackId = createAsyncApiCallback(name, args, options) const callbackId = createAsyncApiCallback(name, args, options)
const res = fn.apply(null, [args, callbackId]) const res = fn.apply(null, [
args,
(res: unknown) => {
invokeCallback(callbackId, res)
},
])
if (res) { if (res) {
invokeCallback(callbackId, res) invokeCallback(callbackId, res)
} }
......
...@@ -20,6 +20,7 @@ export * from './protocols/location/openLocation' ...@@ -20,6 +20,7 @@ export * from './protocols/location/openLocation'
export * from './protocols/media/chooseImage' export * from './protocols/media/chooseImage'
export * from './protocols/media/chooseVideo' export * from './protocols/media/chooseVideo'
export * from './protocols/media/getImageInfo' export * from './protocols/media/getImageInfo'
export * from './protocols/route/route'
// helpers // helpers
export { export {
...@@ -29,5 +30,7 @@ export { ...@@ -29,5 +30,7 @@ export {
defineAsyncApi, defineAsyncApi,
} from './helpers/api' } from './helpers/api'
export { getCurrentPageVm } from './helpers/utils'
export { handlePromise } from './helpers/api/promise' export { handlePromise } from './helpers/api/promise'
export { invokeApi, wrapperReturnValue } from './helpers/interceptor' export { invokeApi, wrapperReturnValue } from './helpers/interceptor'
import { ProtocolOptions } from '../type' import { ProtocolOptions } from '../type'
export const API_BASE64_TO_ARRAY_BUFFER = 'base64ToArrayBuffer'
export const API_ARRAY_BUFFER_TO_BASE64 = 'arrayBufferToBase64'
export const Base64ToArrayBufferProtocol: ProtocolOptions<String>[] = [ export const Base64ToArrayBufferProtocol: ProtocolOptions<String>[] = [
{ {
name: 'base64', name: 'base64',
......
import { ProtocolOptions } from '../type' import { ProtocolOptions } from '../type'
export const API_CAN_I_USE = 'canIUse'
export const CanIUseProtocol: ProtocolOptions<String>[] = [ export const CanIUseProtocol: ProtocolOptions<String>[] = [
{ {
name: 'schema', name: 'schema',
......
import { ProtocolOptions } from '../type' import { ProtocolOptions } from '../type'
export const API_ADD_INTERCEPTOR = 'addInterceptor'
export const API_REMOVE_INTERCEPTOR = 'removeInterceptor'
export const AddInterceptorProtocol: ProtocolOptions<String | Object>[] = [ export const AddInterceptorProtocol: ProtocolOptions<String | Object>[] = [
{ {
name: 'method', name: 'method',
......
import { ProtocolOptions } from '../type' import { ProtocolOptions } from '../type'
export const API_UPX2PX = 'upx2px'
export const Upx2pxProtocol: ProtocolOptions<Number | String>[] = [ export const Upx2pxProtocol: ProtocolOptions<Number | String>[] = [
{ {
name: 'upx', name: 'upx',
......
import { ApiProtocol } from '../type' import { ApiProtocol } from '../type'
export const API_MAKE_PHONE_CALL = 'makePhoneCall'
export const MakePhoneCallProtocol: ApiProtocol = { export const MakePhoneCallProtocol: ApiProtocol = {
phoneNumber: { phoneNumber: {
type: String, type: String,
required: true, required: true,
validator(phoneNumber: string) { validator(phoneNumber: string) {
if (!phoneNumber) { if (!phoneNumber) {
return 'makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;' return 'parameter error: parameter.phoneNumber should not be empty String;'
} }
}, },
}, },
......
import { ApiProtocol } from '../type' import { ApiProtocol } from '../type'
export const API_OPEN_DOCUMENT = 'openDocument'
export const OpenDocumentProtocol: ApiProtocol = { export const OpenDocumentProtocol: ApiProtocol = {
filePath: { filePath: {
......
import { getRealPath } from '@dcloudio/uni-platform' import { getRealPath } from '@dcloudio/uni-platform'
import { ApiOptions, ApiProtocol } from '../type' import { ApiOptions, ApiProtocol } from '../type'
export const API_GET_IMAGE_INFO = 'getImageInfo'
export const GetImageInfoOptions: ApiOptions = { export const GetImageInfoOptions: ApiOptions = {
formatArgs: { formatArgs: {
src(src, params) { src(src, params) {
......
export function encodeQueryString(url: string) {
if (typeof url !== 'string') {
return url
}
const index = url.indexOf('?')
if (index === -1) {
return url
}
const query = url
.substr(index + 1)
.trim()
.replace(/^(\?|#|&)/, '')
if (!query) {
return url
}
url = url.substr(0, index)
const params: string[] = []
query.split('&').forEach((param) => {
const parts = param.replace(/\+/g, ' ').split('=')
const key = parts.shift()
const val = parts.length > 0 ? parts.join('=') : ''
params.push(key + '=' + encodeURIComponent(val))
})
return params.length ? url + '?' + params.join('&') : url
}
import getRealRoute from '../../get-real-route' import { extend } from '@vue/shared'
import { getRealRoute } from '@dcloudio/uni-core'
function encodeQueryString(url) { import { ApiOptions, ApiProtocol } from '../type'
if (typeof url !== 'string') { import { encodeQueryString } from './encodeQueryString'
return url
} const ANIMATION_IN = [
const index = url.indexOf('?') 'slide-in-right',
'slide-in-left',
if (index === -1) { 'slide-in-top',
return url 'slide-in-bottom',
} 'fade-in',
'zoom-out',
const query = url 'zoom-fade-out',
.substr(index + 1) 'pop-in',
.trim() 'none',
.replace(/^(\?|#|&)/, '') ]
if (!query) { const ANIMATION_OUT = [
return url 'slide-out-right',
} 'slide-out-left',
'slide-out-top',
url = url.substr(0, index) 'slide-out-bottom',
'fade-out',
const params = [] 'zoom-in',
'zoom-fade-in',
query.split('&').forEach(param => { 'pop-out',
const parts = param.replace(/\+/g, ' ').split('=') 'none',
const key = parts.shift() ]
const val = parts.length > 0 ? parts.join('=') : ''
const BaseRouteProtocol: ApiProtocol = {
params.push(key + '=' + encodeURIComponent(val)) url: {
}) type: String,
required: true,
return params.length ? url + '?' + params.join('&') : url },
} }
function createValidator(type) { export const API_NAVIGATE_TO = 'navigateTo'
return function validator(url, params) { export const API_REDIRECT_TO = 'redirectTo'
// 格式化为绝对路径路由 export const API_RE_LAUNCH = 'reLaunch'
url = getRealRoute(url) export const API_SWITCH_TAB = 'switchTab'
export const API_NAVIGATE_BACK = 'navigateBack'
const pagePath = url.split('?')[0]
// 匹配路由是否存在 export const API_PRELOAD_PAGE = 'preloadPage'
const routeOptions = __uniRoutes.find( export const API_UN_PRELOAD_PAGE = 'unPreloadPage'
({ path, alias }) => path === pagePath || alias === pagePath
) export const NavigateToProtocol: ApiProtocol = extend(
{},
if (!routeOptions) { BaseRouteProtocol,
return 'page `' + url + '` is not found' createAnimationProtocol(ANIMATION_IN)
} )
// 检测不同类型跳转 export const NavigateBackProtocol: ApiProtocol = extend(
if (type === 'navigateTo' || type === 'redirectTo') { {
if (routeOptions.meta.isTabBar) { delta: {
return `can not ${type} a tabbar page` type: Number,
} },
} else if (type === 'switchTab') { },
if (!routeOptions.meta.isTabBar) { createAnimationProtocol(ANIMATION_OUT)
return 'can not switch to no-tabBar page' )
}
} export const RedirectToProtocol = BaseRouteProtocol
// switchTab不允许传递参数,reLaunch到一个tabBar页面是可以的 export const ReLaunchProtocol = BaseRouteProtocol
if (
(type === 'switchTab' || type === 'preloadPage') && export const SwitchTabProtocol = BaseRouteProtocol
routeOptions.meta.isTabBar &&
params.openType !== 'appLaunch' export const PreloadPageProtocol = BaseRouteProtocol
) {
url = pagePath export const UnPreloadPageProtocol = BaseRouteProtocol
}
export const NavigateToOptions: ApiOptions = /*#__PURE__*/ createRouteOptions(
// 首页自动格式化为`/` API_NAVIGATE_TO
if (routeOptions.meta.isEntry) { )
url = url.replace(routeOptions.alias, '/') export const RedirectToOptions: ApiOptions = /*#__PURE__*/ createRouteOptions(
} API_REDIRECT_TO
)
// 参数格式化 export const ReLaunchOptions: ApiOptions = /*#__PURE__*/ createRouteOptions(
params.url = encodeQueryString(url) API_RE_LAUNCH
if (type === 'unPreloadPage') { )
return export const SwitchTabOptions: ApiOptions = /*#__PURE__*/ createRouteOptions(
} else if (type === 'preloadPage') { API_SWITCH_TAB
if (__PLATFORM__ === 'app-plus') { )
if (!routeOptions.meta.isNVue) {
return 'can not preload vue page' export const NavigateBackOptions: ApiOptions = {
} formatArgs: {
} delta(delta, params) {
if (routeOptions.meta.isTabBar) { delta = parseInt(delta) || 1
const pages = getCurrentPages(true) params.delta = Math.min(getCurrentPages().length - 1, delta)
const tabBarPagePath = (routeOptions.alias || routeOptions.path).substr( },
1 },
) }
if (pages.find(page => page.route === tabBarPagePath)) {
return 'tabBar page `' + tabBarPagePath + '` already exists' function createAnimationProtocol(animationTypes: string[]) {
} return {
} animationType: {
return type: String,
} validator(type: string) {
if (type && animationTypes.indexOf(type) === -1) {
// 主要拦截目标为用户快速点击时触发的多次跳转,该情况,通常前后 url 是一样的 return (
if (navigatorLock === url) { '`' +
return `${navigatorLock} locked` type +
} '` is not supported for `animationType` (supported values are: `' +
// 至少 onLaunch 之后,再启用lock逻辑(onLaunch之前可能开发者手动调用路由API,来提前跳转) animationTypes.join('`|`') +
// enableNavigatorLock 临时开关(不对外开放),避免该功能上线后,有部分情况异常,可以让开发者临时关闭 lock 功能 '`)'
if (__uniConfig.ready && __uniConfig.enableNavigatorLock !== false) { )
navigatorLock = url }
} },
} },
} animationDuration: {
type: Number,
let navigatorLock },
}
function createProtocol(type, extras = {}) { }
return Object.assign(
{ let navigatorLock: string
url: {
type: String, function beforeRoute() {
required: true, navigatorLock = ''
validator: createValidator(type) }
},
beforeAll() { function createRouteOptions(type: string): ApiOptions {
navigatorLock = '' return {
} formatArgs: {
}, url: createNormalizeUrl(type),
extras },
) beforeAll: beforeRoute,
} }
}
function createAnimationProtocol(animationTypes) {
return { function createNormalizeUrl(type: string) {
animationType: { return function normalizeUrl(url: string, params: Record<string, any>) {
type: String, // 格式化为绝对路径路由
validator(type) { url = getRealRoute(url)
if (type && animationTypes.indexOf(type) === -1) { const pagePath = url.split('?')[0]
return ( // 匹配路由是否存在
'`' + const routeOptions = __uniRoutes.find(
type + ({ path, redirect }) => path === pagePath || redirect === pagePath
'` is not supported for `animationType` (supported values are: `' + )
animationTypes.join('`|`') +
'`)' if (!routeOptions) {
) return 'page `' + url + '` is not found'
} }
}
}, // 检测不同类型跳转
animationDuration: { if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) {
type: Number if (routeOptions.meta.isTabBar) {
} return `can not ${type} a tabbar page`
} }
} } else if (type === API_SWITCH_TAB) {
if (!routeOptions.meta.isTabBar) {
export const redirectTo = createProtocol('redirectTo') return 'can not switch to no-tabBar page'
}
export const reLaunch = createProtocol('reLaunch') }
export const navigateTo = createProtocol( // switchTab不允许传递参数,reLaunch到一个tabBar页面是可以的
'navigateTo', if (
createAnimationProtocol([ (type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) &&
'slide-in-right', routeOptions.meta.isTabBar &&
'slide-in-left', params.openType !== 'appLaunch'
'slide-in-top', ) {
'slide-in-bottom', url = pagePath
'fade-in', }
'zoom-out',
'zoom-fade-out', // 首页自动格式化为`/`
'pop-in', if (routeOptions.meta.isEntry) {
'none' url = url.replace(routeOptions.path, '/')
]) }
)
// 参数格式化
export const switchTab = createProtocol('switchTab') params.url = encodeQueryString(url)
if (type === API_UN_PRELOAD_PAGE) {
export const navigateBack = Object.assign( return
{ } else if (type === API_PRELOAD_PAGE) {
delta: { if (__PLATFORM__ === 'app-plus') {
type: Number, if (!routeOptions.meta.isNVue) {
validator(delta, params) { return 'can not preload vue page'
delta = parseInt(delta) || 1 }
params.delta = Math.min(getCurrentPages().length - 1, delta) }
} if (routeOptions.meta.isTabBar) {
} const pages = getCurrentPages(true)
}, const tabBarPagePath = routeOptions.path.substr(1)
createAnimationProtocol([ if (pages.find((page) => page.route === tabBarPagePath)) {
'slide-out-right', return 'tabBar page `' + tabBarPagePath + '` already exists'
'slide-out-left', }
'slide-out-top', }
'slide-out-bottom', return
'fade-out', }
'zoom-in',
'zoom-fade-in', // 主要拦截目标为用户快速点击时触发的多次跳转,该情况,通常前后 url 是一样的
'pop-out', if (navigatorLock === url && params.openType !== 'appLaunch') {
'none' return `${navigatorLock} locked`
]) }
) // 至少 onLaunch 之后,再启用lock逻辑(onLaunch之前可能开发者手动调用路由API,来提前跳转)
// enableNavigatorLock 临时开关(不对外开放),避免该功能上线后,有部分情况异常,可以让开发者临时关闭 lock 功能
export const preloadPage = { if (__uniConfig.ready) {
url: { navigatorLock = url
type: String, }
required: true, }
validator: createValidator('preloadPage') }
}
}
export const unPreloadPage = {
url: {
type: String,
required: true,
validator: createValidator('unPreloadPage')
}
}
...@@ -6,12 +6,14 @@ import { defineSyncApi } from '../../helpers/api' ...@@ -6,12 +6,14 @@ import { defineSyncApi } from '../../helpers/api'
import { import {
Base64ToArrayBufferProtocol, Base64ToArrayBufferProtocol,
ArrayBufferToBase64Protocol, ArrayBufferToBase64Protocol,
API_BASE64_TO_ARRAY_BUFFER,
API_ARRAY_BUFFER_TO_BASE64,
} from '../../protocols/base/base64' } from '../../protocols/base/base64'
export const base64ToArrayBuffer = defineSyncApi< export const base64ToArrayBuffer = defineSyncApi<
typeof uni.base64ToArrayBuffer typeof uni.base64ToArrayBuffer
>( >(
'base64ToArrayBuffer', API_BASE64_TO_ARRAY_BUFFER,
(base64) => { (base64) => {
return decode(base64) as ArrayBuffer return decode(base64) as ArrayBuffer
}, },
...@@ -21,7 +23,7 @@ export const base64ToArrayBuffer = defineSyncApi< ...@@ -21,7 +23,7 @@ export const base64ToArrayBuffer = defineSyncApi<
export const arrayBufferToBase64 = defineSyncApi< export const arrayBufferToBase64 = defineSyncApi<
typeof uni.arrayBufferToBase64 typeof uni.arrayBufferToBase64
>( >(
'arrayBufferToBase64', API_ARRAY_BUFFER_TO_BASE64,
(arrayBuffer) => { (arrayBuffer) => {
return encode(arrayBuffer) as string return encode(arrayBuffer) as string
}, },
......
import { isArray, isFunction, isPromise, isPlainObject } from '@vue/shared' import { isArray, isFunction, isPromise, isPlainObject } from '@vue/shared'
import { import {
HOOKS,
Interceptor, Interceptor,
scopedInterceptors, scopedInterceptors,
globalInterceptors, globalInterceptors,
Interceptors, Interceptors,
HOOKS,
} from '../../helpers/interceptor' } from '../../helpers/interceptor'
import { defineSyncApi } from '../../helpers/api' import { defineSyncApi } from '../../helpers/api'
import { import {
API_ADD_INTERCEPTOR,
API_REMOVE_INTERCEPTOR,
AddInterceptorProtocol, AddInterceptorProtocol,
RemoveInterceptorProtocol, RemoveInterceptorProtocol,
} from '../../protocols/base/interceptor' } from '../../protocols/base/interceptor'
...@@ -81,7 +83,7 @@ function removeHook(hooks: Function[] | undefined, hook: Function) { ...@@ -81,7 +83,7 @@ function removeHook(hooks: Function[] | undefined, hook: Function) {
} }
export const addInterceptor = defineSyncApi( export const addInterceptor = defineSyncApi(
'addInterceptor', API_ADD_INTERCEPTOR,
(method: string | Interceptor, interceptor: Interceptor | undefined) => { (method: string | Interceptor, interceptor: Interceptor | undefined) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook( mergeInterceptorHook(
...@@ -96,7 +98,7 @@ export const addInterceptor = defineSyncApi( ...@@ -96,7 +98,7 @@ export const addInterceptor = defineSyncApi(
) )
export const removeInterceptor = defineSyncApi( export const removeInterceptor = defineSyncApi(
'removeInterceptor', API_REMOVE_INTERCEPTOR,
(method: string | Interceptor, interceptor: Interceptor | undefined) => { (method: string | Interceptor, interceptor: Interceptor | undefined) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
......
import { getBaseSystemInfo } from '@dcloudio/uni-platform' import { getBaseSystemInfo } from '@dcloudio/uni-platform'
import { defineSyncApi } from '../../helpers/api' import { defineSyncApi } from '../../helpers/api'
import { Upx2pxProtocol } from '../../protocols/base/upx2px' import { API_UPX2PX, Upx2pxProtocol } from '../../protocols/base/upx2px'
const EPS = 1e-4 const EPS = 1e-4
const BASE_DEVICE_WIDTH = 750 const BASE_DEVICE_WIDTH = 750
...@@ -16,7 +16,7 @@ function checkDeviceWidth() { ...@@ -16,7 +16,7 @@ function checkDeviceWidth() {
} }
export const upx2px = defineSyncApi<typeof uni.upx2px>( export const upx2px = defineSyncApi<typeof uni.upx2px>(
'upx2px', API_UPX2PX,
(number, newDeviceWidth?: number) => { (number, newDeviceWidth?: number) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth() checkDeviceWidth()
......
...@@ -3,7 +3,7 @@ import { extend } from '@vue/shared' ...@@ -3,7 +3,7 @@ import { extend } from '@vue/shared'
import { ServiceJSBridge } from '@dcloudio/uni-core' import { ServiceJSBridge } from '@dcloudio/uni-core'
import { defineSyncApi } from '../../helpers/api' import { defineSyncApi } from '../../helpers/api'
import { getCurrentPageVm } from '../utils' import { getCurrentPageVm } from '../../helpers/utils'
const defaultOptions = { const defaultOptions = {
thresholds: [0], thresholds: [0],
...@@ -35,6 +35,8 @@ let reqComponentObserverId = 1 ...@@ -35,6 +35,8 @@ let reqComponentObserverId = 1
const reqComponentObserverCallbacks: Record<number, ObserveResultCallback> = {} const reqComponentObserverCallbacks: Record<number, ObserveResultCallback> = {}
export const API_CREATE_INTERSECTION_OBSERVER = 'createIntersectionObserver'
ServiceJSBridge.subscribe( ServiceJSBridge.subscribe(
'requestComponentObserver', 'requestComponentObserver',
({ reqId, reqEnd, res }: requestComponentObserver) => { ({ reqId, reqEnd, res }: requestComponentObserver) => {
...@@ -122,7 +124,7 @@ class ServiceIntersectionObserver { ...@@ -122,7 +124,7 @@ class ServiceIntersectionObserver {
export const createIntersectionObserver = defineSyncApi< export const createIntersectionObserver = defineSyncApi<
typeof uni.createIntersectionObserver typeof uni.createIntersectionObserver
>('createIntersectionObserver', (context?, options?) => { >(API_CREATE_INTERSECTION_OBSERVER, (context?, options?) => {
if (!context) { if (!context) {
context = getCurrentPageVm() context = getCurrentPageVm()
} }
......
export function getRealRoute(fromRoute: string, toRoute: string): string { export function getRealRoute(fromRoute: string, toRoute?: string): string {
if (!toRoute) { if (!toRoute) {
toRoute = fromRoute toRoute = fromRoute
if (toRoute.indexOf('/') === 0) { if (toRoute.indexOf('/') === 0) {
......
import {isFunction, extend, isPlainObject, hasOwn as hasOwn$1, hyphenate, isArray, isObject as isObject$1, capitalize, toRawType, makeMap as makeMap$1, isPromise} from "@vue/shared"; import {isFunction, extend, isPlainObject, hasOwn as hasOwn$1, hyphenate, isArray, isObject as isObject$1, capitalize, toRawType, makeMap as makeMap$1, isPromise} from "@vue/shared";
import {injectHook, createVNode, defineComponent, inject, provide, reactive, computed, nextTick, withDirectives, vShow, withCtx, openBlock, createBlock, KeepAlive, resolveDynamicComponent, resolveComponent, onMounted, ref, mergeProps, toDisplayString, toHandlers, renderSlot, createCommentVNode, withModifiers, vModelDynamic, Fragment, renderList, vModelText} from "vue"; import {injectHook, createVNode, defineComponent, inject, provide, reactive, computed, nextTick, withDirectives, vShow, withCtx, openBlock, createBlock, KeepAlive, resolveDynamicComponent, resolveComponent, onMounted, ref, mergeProps, toDisplayString, toHandlers, renderSlot, createCommentVNode, withModifiers, vModelDynamic, Fragment, renderList, vModelText} from "vue";
import {NAVBAR_HEIGHT, COMPONENT_NAME_PREFIX, isCustomElement, plusReady, debounce, PRIMARY_COLOR} from "@dcloudio/uni-shared"; import {NAVBAR_HEIGHT, COMPONENT_NAME_PREFIX, isCustomElement, plusReady, debounce, PRIMARY_COLOR} from "@dcloudio/uni-shared";
import {createRouter, createWebHistory, createWebHashHistory, useRoute, RouterView} from "vue-router"; import {createRouter, createWebHistory, createWebHashHistory, useRoute, RouterView, isNavigationFailure} from "vue-router";
function applyOptions(options, instance2, publicThis) { function applyOptions(options, instance2, publicThis) {
Object.keys(options).forEach((name) => { Object.keys(options).forEach((name) => {
if (name.indexOf("on") === 0) { if (name.indexOf("on") === 0) {
...@@ -757,7 +757,10 @@ function createRouterOptions() { ...@@ -757,7 +757,10 @@ function createRouterOptions() {
return { return {
history: initHistory(), history: initHistory(),
strict: !!__uniConfig.router.strict, strict: !!__uniConfig.router.strict,
routes: __uniRoutes, routes: [
{path: __uniRoutes[0].path, redirect: "/"},
...__uniRoutes
],
scrollBehavior scrollBehavior
}; };
} }
...@@ -994,7 +997,7 @@ function createTabBarTsx(route) { ...@@ -994,7 +997,7 @@ function createTabBarTsx(route) {
return withDirectives(createVNode(TabBar, null, null, 512), [[vShow, route.meta.isTabBar]]); return withDirectives(createVNode(TabBar, null, null, 512), [[vShow, route.meta.isTabBar]]);
} }
function createPageVNode() { function createPageVNode() {
return createVNode(__uniRoutes[1].component); return createVNode(__uniRoutes[0].component);
} }
function createRouterViewVNode(keepAliveRoute) { function createRouterViewVNode(keepAliveRoute) {
return createVNode(RouterView, null, { return createVNode(RouterView, null, {
...@@ -7738,6 +7741,14 @@ const API_TYPE_TASK = 1; ...@@ -7738,6 +7741,14 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -7752,7 +7763,12 @@ function wrapperSyncApi(fn) { ...@@ -7752,7 +7763,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res2) => {
invokeCallback(callbackId, res2);
}
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -7766,7 +7782,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -7766,7 +7782,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -7778,15 +7794,17 @@ function defineAsyncApi(name, fn, protocol, options) { ...@@ -7778,15 +7794,17 @@ function defineAsyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer";
const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64";
const Base64ToArrayBufferProtocol = [ const Base64ToArrayBufferProtocol = [
{ {
name: "base64", name: "base64",
...@@ -7801,12 +7819,13 @@ const ArrayBufferToBase64Protocol = [ ...@@ -7801,12 +7819,13 @@ const ArrayBufferToBase64Protocol = [
required: true required: true
} }
]; ];
const base64ToArrayBuffer = defineSyncApi("base64ToArrayBuffer", (base64) => { const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => {
return decode(base64); return decode(base64);
}, Base64ToArrayBufferProtocol); }, Base64ToArrayBufferProtocol);
const arrayBufferToBase64 = defineSyncApi("arrayBufferToBase64", (arrayBuffer) => { const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => {
return encode(arrayBuffer); return encode(arrayBuffer);
}, ArrayBufferToBase64Protocol); }, ArrayBufferToBase64Protocol);
const API_UPX2PX = "upx2px";
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: "upx", name: "upx",
...@@ -7825,7 +7844,7 @@ function checkDeviceWidth() { ...@@ -7825,7 +7844,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio2; deviceDPR = pixelRatio2;
isIOS = platform === "ios"; isIOS = platform === "ios";
} }
const upx2px = defineSyncApi("upx2px", (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -7857,6 +7876,8 @@ var HOOKS; ...@@ -7857,6 +7876,8 @@ var HOOKS;
})(HOOKS || (HOOKS = {})); })(HOOKS || (HOOKS = {}));
const globalInterceptors = {}; const globalInterceptors = {};
const scopedInterceptors = {}; const scopedInterceptors = {};
const API_ADD_INTERCEPTOR = "addInterceptor";
const API_REMOVE_INTERCEPTOR = "removeInterceptor";
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: "method", name: "method",
...@@ -7904,14 +7925,14 @@ function removeHook(hooks, hook) { ...@@ -7904,14 +7925,14 @@ function removeHook(hooks, hook) {
hooks.splice(index2, 1); hooks.splice(index2, 1);
} }
} }
const addInterceptor = defineSyncApi("addInterceptor", (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === "string" && isPlainObject(interceptor)) { if (typeof method === "string" && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} else if (isPlainObject(method)) { } else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi("removeInterceptor", (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === "string") { if (typeof method === "string") {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
...@@ -7947,6 +7968,7 @@ const defaultOptions = { ...@@ -7947,6 +7968,7 @@ const defaultOptions = {
}; };
let reqComponentObserverId = 1; let reqComponentObserverId = 1;
const reqComponentObserverCallbacks = {}; const reqComponentObserverCallbacks = {};
const API_CREATE_INTERSECTION_OBSERVER = "createIntersectionObserver";
ServiceJSBridge.subscribe("requestComponentObserver", ({reqId, reqEnd, res}) => { ServiceJSBridge.subscribe("requestComponentObserver", ({reqId, reqEnd, res}) => {
const callback = reqComponentObserverCallbacks[reqId]; const callback = reqComponentObserverCallbacks[reqId];
if (callback) { if (callback) {
...@@ -7999,7 +8021,7 @@ class ServiceIntersectionObserver { ...@@ -7999,7 +8021,7 @@ class ServiceIntersectionObserver {
}, this._pageId); }, this._pageId);
} }
} }
const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (context, options) => { const createIntersectionObserver = defineSyncApi(API_CREATE_INTERSECTION_OBSERVER, (context, options) => {
if (!context) { if (!context) {
context = getCurrentPageVm(); context = getCurrentPageVm();
} }
...@@ -8007,6 +8029,7 @@ const createIntersectionObserver = defineSyncApi("createIntersectionObserver", ( ...@@ -8007,6 +8029,7 @@ const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (
}); });
const createSelectorQuery = () => { const createSelectorQuery = () => {
}; };
const API_CAN_I_USE = "canIUse";
const CanIUseProtocol = [ const CanIUseProtocol = [
{ {
name: "schema", name: "schema",
...@@ -8014,17 +8037,19 @@ const CanIUseProtocol = [ ...@@ -8014,17 +8037,19 @@ const CanIUseProtocol = [
required: true required: true
} }
]; ];
const API_MAKE_PHONE_CALL = "makePhoneCall";
const MakePhoneCallProtocol = { const MakePhoneCallProtocol = {
phoneNumber: { phoneNumber: {
type: String, type: String,
required: true, required: true,
validator(phoneNumber) { validator(phoneNumber) {
if (!phoneNumber) { if (!phoneNumber) {
return "makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;"; return "parameter error: parameter.phoneNumber should not be empty String;";
} }
} }
} }
}; };
const API_OPEN_DOCUMENT = "openDocument";
const OpenDocumentProtocol = { const OpenDocumentProtocol = {
filePath: { filePath: {
type: String, type: String,
...@@ -8034,6 +8059,7 @@ const OpenDocumentProtocol = { ...@@ -8034,6 +8059,7 @@ const OpenDocumentProtocol = {
type: String type: String
} }
}; };
const API_GET_IMAGE_INFO = "getImageInfo";
const GetImageInfoOptions = { const GetImageInfoOptions = {
formatArgs: { formatArgs: {
src(src, params) { src(src, params) {
...@@ -8047,6 +8073,155 @@ const GetImageInfoProtocol = { ...@@ -8047,6 +8073,155 @@ const GetImageInfoProtocol = {
required: true required: true
} }
}; };
function encodeQueryString(url) {
if (typeof url !== "string") {
return url;
}
const index2 = url.indexOf("?");
if (index2 === -1) {
return url;
}
const query = url.substr(index2 + 1).trim().replace(/^(\?|#|&)/, "");
if (!query) {
return url;
}
url = url.substr(0, index2);
const params = [];
query.split("&").forEach((param) => {
const parts = param.replace(/\+/g, " ").split("=");
const key = parts.shift();
const val = parts.length > 0 ? parts.join("=") : "";
params.push(key + "=" + encodeURIComponent(val));
});
return params.length ? url + "?" + params.join("&") : url;
}
const ANIMATION_IN = [
"slide-in-right",
"slide-in-left",
"slide-in-top",
"slide-in-bottom",
"fade-in",
"zoom-out",
"zoom-fade-out",
"pop-in",
"none"
];
const ANIMATION_OUT = [
"slide-out-right",
"slide-out-left",
"slide-out-top",
"slide-out-bottom",
"fade-out",
"zoom-in",
"zoom-fade-in",
"pop-out",
"none"
];
const BaseRouteProtocol = {
url: {
type: String,
required: true
}
};
const API_NAVIGATE_TO = "navigateTo";
const API_REDIRECT_TO = "redirectTo";
const API_RE_LAUNCH = "reLaunch";
const API_SWITCH_TAB = "switchTab";
const API_NAVIGATE_BACK = "navigateBack";
const API_PRELOAD_PAGE = "preloadPage";
const API_UN_PRELOAD_PAGE = "unPreloadPage";
const NavigateToProtocol = extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN));
const NavigateBackProtocol = extend({
delta: {
type: Number
}
}, createAnimationProtocol(ANIMATION_OUT));
const RedirectToProtocol = BaseRouteProtocol;
const ReLaunchProtocol = BaseRouteProtocol;
const SwitchTabProtocol = BaseRouteProtocol;
const NavigateToOptions = /* @__PURE__ */ createRouteOptions(API_NAVIGATE_TO);
const RedirectToOptions = /* @__PURE__ */ createRouteOptions(API_REDIRECT_TO);
const ReLaunchOptions = /* @__PURE__ */ createRouteOptions(API_RE_LAUNCH);
const SwitchTabOptions = /* @__PURE__ */ createRouteOptions(API_SWITCH_TAB);
const NavigateBackOptions = {
formatArgs: {
delta(delta, params) {
delta = parseInt(delta) || 1;
params.delta = Math.min(getCurrentPages().length - 1, delta);
}
}
};
function createAnimationProtocol(animationTypes) {
return {
animationType: {
type: String,
validator(type) {
if (type && animationTypes.indexOf(type) === -1) {
return "`" + type + "` is not supported for `animationType` (supported values are: `" + animationTypes.join("`|`") + "`)";
}
}
},
animationDuration: {
type: Number
}
};
}
let navigatorLock;
function beforeRoute() {
navigatorLock = "";
}
function createRouteOptions(type) {
return {
formatArgs: {
url: createNormalizeUrl(type)
},
beforeAll: beforeRoute
};
}
function createNormalizeUrl(type) {
return function normalizeUrl(url, params) {
url = getRealRoute(url);
const pagePath = url.split("?")[0];
const routeOptions = __uniRoutes.find(({path, redirect}) => path === pagePath || redirect === pagePath);
if (!routeOptions) {
return "page `" + url + "` is not found";
}
if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) {
if (routeOptions.meta.isTabBar) {
return `can not ${type} a tabbar page`;
}
} else if (type === API_SWITCH_TAB) {
if (!routeOptions.meta.isTabBar) {
return "can not switch to no-tabBar page";
}
}
if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && routeOptions.meta.isTabBar && params.openType !== "appLaunch") {
url = pagePath;
}
if (routeOptions.meta.isEntry) {
url = url.replace(routeOptions.path, "/");
}
params.url = encodeQueryString(url);
if (type === API_UN_PRELOAD_PAGE) {
return;
} else if (type === API_PRELOAD_PAGE) {
if (routeOptions.meta.isTabBar) {
const pages = getCurrentPages(true);
const tabBarPagePath = routeOptions.path.substr(1);
if (pages.find((page) => page.route === tabBarPagePath)) {
return "tabBar page `" + tabBarPagePath + "` already exists";
}
}
return;
}
if (navigatorLock === url && params.openType !== "appLaunch") {
return `${navigatorLock} locked`;
}
if (__uniConfig.ready) {
navigatorLock = url;
}
};
}
function cssSupports(css) { function cssSupports(css) {
return window.CSS && window.CSS.supports && window.CSS.supports(css); return window.CSS && window.CSS.supports && window.CSS.supports(css);
} }
...@@ -8055,13 +8230,13 @@ const SCHEMA_CSS = { ...@@ -8055,13 +8230,13 @@ const SCHEMA_CSS = {
"css.env": cssSupports("top:env(a)"), "css.env": cssSupports("top:env(a)"),
"css.constant": cssSupports("top:constant(a)") "css.constant": cssSupports("top:constant(a)")
}; };
const canIUse = defineSyncApi("canIUse", (schema) => { const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => {
if (hasOwn$1(SCHEMA_CSS, schema)) { if (hasOwn$1(SCHEMA_CSS, schema)) {
return SCHEMA_CSS[schema]; return SCHEMA_CSS[schema];
} }
return true; return true;
}, CanIUseProtocol); }, CanIUseProtocol);
const makePhoneCall = defineAsyncApi("makePhoneCall", (option) => { const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, (option) => {
window.location.href = `tel:${option.phoneNumber}`; window.location.href = `tel:${option.phoneNumber}`;
}, MakePhoneCallProtocol); }, MakePhoneCallProtocol);
const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
...@@ -8167,17 +8342,17 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { ...@@ -8167,17 +8342,17 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
const getSystemInfo = defineAsyncApi("getSystemInfo", () => { const getSystemInfo = defineAsyncApi("getSystemInfo", () => {
return getSystemInfoSync(); return getSystemInfoSync();
}); });
const openDocument = defineAsyncApi("openDocument", (option) => { const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, (option) => {
window.open(option.filePath); window.open(option.filePath);
}, OpenDocumentProtocol); }, OpenDocumentProtocol);
function _getServiceAddress() { function _getServiceAddress() {
return window.location.protocol + "//" + window.location.host; return window.location.protocol + "//" + window.location.host;
} }
const getImageInfo = defineAsyncApi("getImageInfo", ({src}, callback) => { const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}, callback) => {
const img = new Image(); const img = new Image();
img.onload = function() { img.onload = function() {
callback({ callback({
errMsg: "getImageInfo:ok", errMsg: `${API_GET_IMAGE_INFO}:ok`,
width: img.naturalWidth, width: img.naturalWidth,
height: img.naturalHeight, height: img.naturalHeight,
path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src
...@@ -8185,27 +8360,45 @@ const getImageInfo = defineAsyncApi("getImageInfo", ({src}, callback) => { ...@@ -8185,27 +8360,45 @@ const getImageInfo = defineAsyncApi("getImageInfo", ({src}, callback) => {
}; };
img.onerror = function() { img.onerror = function() {
callback({ callback({
errMsg: "getImageInfo:fail" errMsg: `${API_GET_IMAGE_INFO}:fail`
}); });
}; };
img.src = src; img.src = src;
}, GetImageInfoProtocol, GetImageInfoOptions); }, GetImageInfoProtocol, GetImageInfoOptions);
const navigateBack = defineAsyncApi("navigateBack", () => { const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (options) => {
}); let canBack = true;
const navigateTo = defineAsyncApi("navigateTo", (options) => { const vm = getCurrentPageVm();
if (vm && vm.$callHook("onBackPress") === true) {
canBack = false;
}
if (!canBack) {
return {
errMsg: `${API_NAVIGATE_BACK}:fail onBackPress`
};
}
getApp().$router.go(-options.delta);
}, NavigateBackProtocol, NavigateBackOptions);
const navigateTo = defineAsyncApi(API_NAVIGATE_TO, (options, callback) => {
const router = getApp().$router; const router = getApp().$router;
router.push({ router.push({
path: options.url, path: options.url,
force: true, force: true,
state: createPageState("navigateTo") state: createPageState("navigateTo")
}).then((failure) => {
if (isNavigationFailure(failure)) {
return callback({
errMsg: `${API_NAVIGATE_TO}:fail ${failure.message}`
});
}
callback();
}); });
}); }, NavigateToProtocol, NavigateToOptions);
const redirectTo = defineAsyncApi("redirectTo", () => { const redirectTo = defineAsyncApi(API_REDIRECT_TO, () => {
}); }, RedirectToProtocol, RedirectToOptions);
const reLaunch = defineAsyncApi("reLaunch", () => { const reLaunch = defineAsyncApi(API_RE_LAUNCH, () => {
}); }, ReLaunchProtocol, ReLaunchOptions);
const switchTab = defineAsyncApi("switchTab", () => { const switchTab = defineAsyncApi(API_SWITCH_TAB, () => {
}); }, SwitchTabProtocol, SwitchTabOptions);
var api = /* @__PURE__ */ Object.freeze({ var api = /* @__PURE__ */ Object.freeze({
__proto__: null, __proto__: null,
[Symbol.toStringTag]: "Module", [Symbol.toStringTag]: "Module",
......
...@@ -87,7 +87,7 @@ function createTabBarTsx(route: RouteLocationNormalizedLoaded) { ...@@ -87,7 +87,7 @@ function createTabBarTsx(route: RouteLocationNormalizedLoaded) {
} }
function createPageVNode() { function createPageVNode() {
return createVNode(__uniRoutes[1].component) return createVNode(__uniRoutes[0].component)
} }
function createRouterViewVNode( function createRouterViewVNode(
......
...@@ -31,7 +31,10 @@ function createRouterOptions(): RouterOptions { ...@@ -31,7 +31,10 @@ function createRouterOptions(): RouterOptions {
return { return {
history: initHistory(), history: initHistory(),
strict: !!__uniConfig.router.strict, strict: !!__uniConfig.router.strict,
routes: __uniRoutes as RouteRecordRaw[], routes: [
{ path: __uniRoutes[0].path, redirect: '/' },
...__uniRoutes,
] as RouteRecordRaw[],
scrollBehavior, scrollBehavior,
} }
} }
......
import { hasOwn } from '@vue/shared' import { hasOwn } from '@vue/shared'
import { CanIUseProtocol, defineSyncApi } from '@dcloudio/uni-api' import {
API_CAN_I_USE,
CanIUseProtocol,
defineSyncApi,
} from '@dcloudio/uni-api'
function cssSupports(css: string) { function cssSupports(css: string) {
return window.CSS && window.CSS.supports && window.CSS.supports(css) return window.CSS && window.CSS.supports && window.CSS.supports(css)
...@@ -13,7 +17,7 @@ const SCHEMA_CSS = { ...@@ -13,7 +17,7 @@ const SCHEMA_CSS = {
} }
export const canIUse = defineSyncApi<typeof uni.canIUse>( export const canIUse = defineSyncApi<typeof uni.canIUse>(
'canIUse', API_CAN_I_USE,
(schema: string) => { (schema: string) => {
if (hasOwn(SCHEMA_CSS, schema)) { if (hasOwn(SCHEMA_CSS, schema)) {
return SCHEMA_CSS[schema] return SCHEMA_CSS[schema]
......
import { defineAsyncApi, MakePhoneCallProtocol } from '@dcloudio/uni-api' import {
API_MAKE_PHONE_CALL,
defineAsyncApi,
MakePhoneCallProtocol,
} from '@dcloudio/uni-api'
export const makePhoneCall = defineAsyncApi<typeof uni.makePhoneCall>( export const makePhoneCall = defineAsyncApi<typeof uni.makePhoneCall>(
'makePhoneCall', API_MAKE_PHONE_CALL,
(option) => { (option) => {
window.location.href = `tel:${option.phoneNumber}` window.location.href = `tel:${option.phoneNumber}`
}, },
......
import { defineAsyncApi, OpenDocumentProtocol } from '@dcloudio/uni-api' import {
API_OPEN_DOCUMENT,
defineAsyncApi,
OpenDocumentProtocol,
} from '@dcloudio/uni-api'
export const openDocument = defineAsyncApi<typeof uni.openDocument>( export const openDocument = defineAsyncApi<typeof uni.openDocument>(
'openDocument', API_OPEN_DOCUMENT,
(option) => { (option) => {
window.open(option.filePath) window.open(option.filePath)
}, },
......
import { import {
API_GET_IMAGE_INFO,
defineAsyncApi, defineAsyncApi,
GetImageInfoOptions, GetImageInfoOptions,
GetImageInfoProtocol, GetImageInfoProtocol,
...@@ -9,12 +10,12 @@ function _getServiceAddress() { ...@@ -9,12 +10,12 @@ function _getServiceAddress() {
} }
export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>( export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>(
'getImageInfo', API_GET_IMAGE_INFO,
({ src }, callback?: Function) => { ({ src }, callback?: Function) => {
const img = new Image() const img = new Image()
img.onload = function () { img.onload = function () {
callback!({ callback!({
errMsg: 'getImageInfo:ok', errMsg: `${API_GET_IMAGE_INFO}:ok`,
width: img.naturalWidth, width: img.naturalWidth,
height: img.naturalHeight, height: img.naturalHeight,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src, path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src,
...@@ -22,7 +23,7 @@ export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>( ...@@ -22,7 +23,7 @@ export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>(
} }
img.onerror = function () { img.onerror = function () {
callback!({ callback!({
errMsg: 'getImageInfo:fail', errMsg: `${API_GET_IMAGE_INFO}:fail`,
}) })
} }
img.src = src img.src = src
......
import { defineAsyncApi } from '@dcloudio/uni-api' import {
API_NAVIGATE_BACK,
defineAsyncApi,
getCurrentPageVm,
NavigateBackOptions,
NavigateBackProtocol,
} from '@dcloudio/uni-api'
export const navigateBack = defineAsyncApi<typeof uni.navigateBack>( export const navigateBack = defineAsyncApi<typeof uni.navigateBack>(
'navigateBack', API_NAVIGATE_BACK,
() => {} (options) => {
let canBack = true
const vm = getCurrentPageVm()
if (vm && vm.$callHook('onBackPress') === true) {
canBack = false
}
if (!canBack) {
return {
errMsg: `${API_NAVIGATE_BACK}:fail onBackPress`,
}
}
getApp().$router.go(-options.delta!)
},
NavigateBackProtocol,
NavigateBackOptions
) )
import { Router } from 'vue-router' import { isNavigationFailure, Router } from 'vue-router'
import { defineAsyncApi } from '@dcloudio/uni-api' import {
API_NAVIGATE_TO,
defineAsyncApi,
NavigateToOptions,
NavigateToProtocol,
} from '@dcloudio/uni-api'
import { createPageState } from '../../../framework/plugin/page' import { createPageState } from '../../../framework/plugin/page'
export const navigateTo = defineAsyncApi<typeof uni.navigateTo>( export const navigateTo = defineAsyncApi<typeof uni.navigateTo>(
'navigateTo', API_NAVIGATE_TO,
(options) => { (options, callback?: Function) => {
const router = getApp().$router as Router const router = getApp().$router as Router
router.push({ router
path: options.url, .push({
force: true, path: options.url,
state: createPageState('navigateTo'), force: true,
}) state: createPageState('navigateTo'),
} })
.then((failure) => {
if (isNavigationFailure(failure)) {
return callback!({
errMsg: `${API_NAVIGATE_TO}:fail ${failure.message}`,
})
}
callback!()
})
},
NavigateToProtocol,
NavigateToOptions
) )
import { defineAsyncApi } from '@dcloudio/uni-api' import {
API_RE_LAUNCH,
defineAsyncApi,
ReLaunchOptions,
ReLaunchProtocol,
} from '@dcloudio/uni-api'
export const reLaunch = defineAsyncApi('reLaunch', () => {}) export const reLaunch = defineAsyncApi(
API_RE_LAUNCH,
() => {},
ReLaunchProtocol,
ReLaunchOptions
)
import { defineAsyncApi } from '@dcloudio/uni-api' import {
API_REDIRECT_TO,
defineAsyncApi,
RedirectToOptions,
RedirectToProtocol,
} from '@dcloudio/uni-api'
export const redirectTo = defineAsyncApi('redirectTo', () => {}) export const redirectTo = defineAsyncApi(
API_REDIRECT_TO,
() => {},
RedirectToProtocol,
RedirectToOptions
)
import { defineAsyncApi } from '@dcloudio/uni-api' import {
API_SWITCH_TAB,
defineAsyncApi,
SwitchTabOptions,
SwitchTabProtocol,
} from '@dcloudio/uni-api'
export const switchTab = defineAsyncApi('switchTab', () => {}) export const switchTab = defineAsyncApi(
API_SWITCH_TAB,
() => {},
SwitchTabProtocol,
SwitchTabOptions
)
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return my.getSystemInfoSync() return my.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return swan.getSystemInfoSync() return swan.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return qq.getSystemInfoSync() return qq.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return tt.getSystemInfoSync() return tt.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return wx.getSystemInfoSync() return wx.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1; ...@@ -254,6 +254,15 @@ const API_TYPE_TASK = 1;
const API_TYPE_SYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_ASYNC = 3; const API_TYPE_ASYNC = 3;
function formatApiArgs(args, options) { function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return args;
}
const formatArgs = options.formatArgs;
Object.keys(formatArgs).forEach((name) => {
formatArgs[name](args[0][name], params);
});
return args; return args;
} }
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) { ...@@ -268,7 +277,12 @@ function wrapperSyncApi(fn) {
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
const res = fn.apply(null, [args, callbackId]); const res = fn.apply(null, [
args,
(res) => {
invokeCallback(callbackId, res);
},
]);
if (res) { if (res) {
invokeCallback(callbackId, res); invokeCallback(callbackId, res);
} }
...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -282,7 +296,7 @@ function wrapperApi(fn, name, protocol, options) {
return errMsg; return errMsg;
} }
} }
return fn.apply(null, formatApiArgs(args)); return fn.apply(null, formatApiArgs(args, options));
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) { ...@@ -291,13 +305,13 @@ function defineSyncApi(name, fn, protocol, options) {
function defineApi(type, name, fn, protocol, options) { function defineApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_TASK: case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol); return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
} }
} }
...@@ -305,6 +319,7 @@ function getBaseSystemInfo() { ...@@ -305,6 +319,7 @@ function getBaseSystemInfo() {
return qa.getSystemInfoSync() return qa.getSystemInfoSync()
} }
const API_UPX2PX = 'upx2px';
const Upx2pxProtocol = [ const Upx2pxProtocol = [
{ {
name: 'upx', name: 'upx',
...@@ -324,7 +339,7 @@ function checkDeviceWidth() { ...@@ -324,7 +339,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio; deviceDPR = pixelRatio;
isIOS = platform === 'ios'; isIOS = platform === 'ios';
} }
const upx2px = defineSyncApi('upx2px', (number, newDeviceWidth) => { const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) { ...@@ -452,6 +467,8 @@ function invokeApi(method, api, options, ...params) {
return api(options, ...params); return api(options, ...params);
} }
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [ const AddInterceptorProtocol = [
{ {
name: 'method', name: 'method',
...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) { ...@@ -506,7 +523,7 @@ function removeHook(hooks, hook) {
hooks.splice(index, 1); hooks.splice(index, 1);
} }
} }
const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => { const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string' && isPlainObject(interceptor)) { if (typeof method === 'string' && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} }
...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) => ...@@ -514,7 +531,7 @@ const addInterceptor = defineSyncApi('addInterceptor', (method, interceptor) =>
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi('removeInterceptor', (method, interceptor) => { const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (typeof method === 'string') { if (typeof method === 'string') {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册