-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
native-apis.ts
402 lines (369 loc) · 10.1 KB
/
native-apis.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { isFunction, isString } from './is'
import { nonsupport, setUniqueKeyToRoute } from './utils'
declare const getCurrentPages: () => any
declare const getApp: () => any
declare const requirePlugin: () => void
type IObject = Record<string, any>
interface IProcessApisIOptions {
noPromiseApis?: Set<string>
needPromiseApis?: Set<string>
handleSyncApis?: (key: string, global: IObject, args: any[]) => any
transformMeta?: (key: string, options: IObject) => { key: string, options: IObject }
modifyApis?: (apis: Set<string>) => void
modifyAsyncResult?: (key: string, res) => void
isOnlyPromisify?: boolean
[propName: string]: any
}
export interface IApiDiff {
[key: string]: {
/** API重命名 */
alias?: string
options?: {
/** API参数键名修改 */
change?: {
old: string
new: string
}[]
/** API参数值修改 */
set?: {
key: string
value: ((options: Record<string, any>) => unknown) | unknown
}[]
}
}
}
const needPromiseApis = new Set<string>([
'addPhoneContact',
'authorize',
'canvasGetImageData',
'canvasPutImageData',
'canvasToTempFilePath',
'checkSession',
'chooseAddress',
'chooseImage',
'chooseInvoiceTitle',
'chooseLocation',
'chooseVideo',
'clearStorage',
'closeBLEConnection',
'closeBluetoothAdapter',
'closeSocket',
'compressImage',
'connectSocket',
'createBLEConnection',
'downloadFile',
'exitMiniProgram',
'getAvailableAudioSources',
'getBLEDeviceCharacteristics',
'getBLEDeviceServices',
'getBatteryInfo',
'getBeacons',
'getBluetoothAdapterState',
'getBluetoothDevices',
'getClipboardData',
'getConnectedBluetoothDevices',
'getConnectedWifi',
'getExtConfig',
'getFileInfo',
'getImageInfo',
'getLocation',
'getNetworkType',
'getSavedFileInfo',
'getSavedFileList',
'getScreenBrightness',
'getSetting',
'getStorage',
'getStorageInfo',
'getSystemInfo',
'getUserInfo',
'getWifiList',
'hideHomeButton',
'hideShareMenu',
'hideTabBar',
'hideTabBarRedDot',
'loadFontFace',
'login',
'makePhoneCall',
'navigateBack',
'navigateBackMiniProgram',
'navigateTo',
'navigateToBookshelf',
'navigateToMiniProgram',
'notifyBLECharacteristicValueChange',
'hideKeyboard',
'hideLoading',
'hideNavigationBarLoading',
'hideToast',
'openBluetoothAdapter',
'openDocument',
'openLocation',
'openSetting',
'pageScrollTo',
'previewImage',
'queryBookshelf',
'reLaunch',
'readBLECharacteristicValue',
'redirectTo',
'removeSavedFile',
'removeStorage',
'removeTabBarBadge',
'requestSubscribeMessage',
'saveFile',
'saveImageToPhotosAlbum',
'saveVideoToPhotosAlbum',
'scanCode',
'sendSocketMessage',
'setBackgroundColor',
'setBackgroundTextStyle',
'setClipboardData',
'setEnableDebug',
'setInnerAudioOption',
'setKeepScreenOn',
'setNavigationBarColor',
'setNavigationBarTitle',
'setScreenBrightness',
'setStorage',
'setTabBarBadge',
'setTabBarItem',
'setTabBarStyle',
'showActionSheet',
'showFavoriteGuide',
'showLoading',
'showModal',
'showShareMenu',
'showTabBar',
'showTabBarRedDot',
'showToast',
'startBeaconDiscovery',
'startBluetoothDevicesDiscovery',
'startDeviceMotionListening',
'startPullDownRefresh',
'stopBeaconDiscovery',
'stopBluetoothDevicesDiscovery',
'stopCompass',
'startCompass',
'startAccelerometer',
'stopAccelerometer',
'showNavigationBarLoading',
'stopDeviceMotionListening',
'stopPullDownRefresh',
'switchTab',
'uploadFile',
'vibrateLong',
'vibrateShort',
'writeBLECharacteristicValue'
])
function getCanIUseWebp (taro) {
return function () {
const res = taro.getSystemInfoSync?.()
if (!res) {
if (process.env.NODE_ENV !== 'production') {
console.error('不支持 API canIUseWebp')
}
return false
}
const { platform } = res
const platformLower = platform.toLowerCase()
if (platformLower === 'android' || platformLower === 'devtools') {
return true
}
return false
}
}
function getNormalRequest (global) {
return function request (options) {
options = options
? (
isString(options)
? { url: options }
: options
)
: {}
const originSuccess = options.success
const originFail = options.fail
const originComplete = options.complete
let requestTask
const p: any = new Promise((resolve, reject) => {
options.success = res => {
originSuccess && originSuccess(res)
resolve(res)
}
options.fail = res => {
originFail && originFail(res)
reject(res)
}
options.complete = res => {
originComplete && originComplete(res)
}
requestTask = global.request(options)
})
equipTaskMethodsIntoPromise(requestTask, p)
p.abort = (cb) => {
cb && cb()
if (requestTask) {
requestTask.abort()
}
return p
}
return p
}
}
function processApis (taro, global, config: IProcessApisIOptions = {}) {
const patchNeedPromiseApis = config.needPromiseApis || []
const _needPromiseApis = new Set<string>([...patchNeedPromiseApis, ...needPromiseApis])
const preserved = [
'getEnv',
'interceptors',
'Current',
'getCurrentInstance',
'options',
'nextTick',
'eventCenter',
'Events',
'preload',
'webpackJsonp'
]
const apis = new Set(
!config.isOnlyPromisify
? Object.keys(global).filter(api => preserved.indexOf(api) === -1)
: patchNeedPromiseApis
)
if (config.modifyApis) {
config.modifyApis(apis)
}
apis.forEach(key => {
if (_needPromiseApis.has(key)) {
const originKey = key
taro[originKey] = (options: Record<string, any> | string = {}, ...args) => {
let key = originKey
// 第一个参数 options 为字符串,单独处理
if (typeof options === 'string') {
if (args.length) {
return global[key](options, ...args)
}
return global[key](options)
}
// 改变 key 或 option 字段,如需要把支付宝标准的字段对齐微信标准的字段
if (config.transformMeta) {
const transformResult = config.transformMeta(key, options)
key = transformResult.key
; (options as Record<string, any>) = transformResult.options
// 新 key 可能不存在
if (!global.hasOwnProperty(key)) {
return nonsupport(key)()
}
}
let task: any = null
const obj: Record<string, any> = Object.assign({}, options)
// 为页面跳转相关的 API 设置一个随机数作为路由参数。为了给 runtime 区分页面。
setUniqueKeyToRoute(key, options)
// Promise 化
const p: any = new Promise((resolve, reject) => {
obj.success = res => {
config.modifyAsyncResult?.(key, res)
options.success?.(res)
if (key === 'connectSocket') {
resolve(
Promise.resolve().then(() => task ? Object.assign(task, res) : res)
)
} else {
resolve(res)
}
}
obj.fail = res => {
options.fail?.(res)
reject(res)
}
obj.complete = res => {
options.complete?.(res)
}
if (args.length) {
task = global[key](obj, ...args)
} else {
task = global[key](obj)
}
})
// 给 promise 对象挂载属性
if (['uploadFile', 'downloadFile'].includes(key)) {
equipTaskMethodsIntoPromise(task, p)
p.progress = cb => {
task?.onProgressUpdate(cb)
return p
}
p.abort = cb => {
cb?.()
task?.abort()
return p
}
}
return p
}
} else {
let platformKey = key
// 改变 key 或 option 字段,如需要把支付宝标准的字段对齐微信标准的字段
if (config.transformMeta) {
platformKey = config.transformMeta(key, {}).key
}
// API 不存在
if (!global.hasOwnProperty(platformKey)) {
taro[key] = nonsupport(key)
return
}
if (isFunction(global[key])) {
taro[key] = (...args) => {
if (config.handleSyncApis) {
return config.handleSyncApis(key, global, args)
} else {
return global[platformKey].apply(global, args)
}
}
} else {
taro[key] = global[platformKey]
}
}
})
!config.isOnlyPromisify && equipCommonApis(taro, global, config)
}
/**
* 挂载常用 API
* @param taro Taro 对象
* @param global 小程序全局对象,如微信的 wx,支付宝的 my
*/
function equipCommonApis (taro, global, apis: Record<string, any> = {}) {
taro.canIUseWebp = getCanIUseWebp(taro)
taro.getCurrentPages = getCurrentPages || nonsupport('getCurrentPages')
taro.getApp = getApp || nonsupport('getApp')
taro.env = global.env || {}
try {
taro.requirePlugin = requirePlugin || nonsupport('requirePlugin')
} catch (error) {
taro.requirePlugin = nonsupport('requirePlugin')
}
// request & interceptors
const request = apis.request || getNormalRequest(global)
function taroInterceptor (chain) {
return request(chain.requestParams)
}
const link = new taro.Link(taroInterceptor)
taro.request = link.request.bind(link)
taro.addInterceptor = link.addInterceptor.bind(link)
taro.cleanInterceptors = link.cleanInterceptors.bind(link)
taro.miniGlobal = taro.options.miniGlobal = global
}
/**
* 将Task对象中的方法挂载到promise对象中,适配小程序api原生返回结果
* @param task Task对象 {RequestTask | DownloadTask | UploadTask}
* @param promise Promise
*/
function equipTaskMethodsIntoPromise (task, promise) {
if (!task || !promise) return
const taskMethods = ['abort', 'onHeadersReceived', 'offHeadersReceived', 'onProgressUpdate', 'offProgressUpdate', 'onChunkReceived', 'offChunkReceived']
task && taskMethods.forEach(method => {
if (method in task) {
promise[method] = task[method].bind(task)
}
})
}
export {
processApis
}