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

add modules

上级 0ae35ac7
module.exports = {
base: {
title: '基础',
api: [
'base64ToArrayBuffer',
'arrayBufferToBase64'
]
},
network: {
title: '网络',
api: [
'request'
'connectSocket'
'sendSocketMessage'
'closeSocket'
'onSocketOpen'
'onSocketError'
'onSocketMessage'
'onSocketClose'
'downloadFile'
'uploadFile'
]
},
storage: {
title: '数据缓存',
api: [
'setStorage'
'setStorageSync'
'getStorage'
'getStorageSync'
'removeStorage'
'removeStorageSync'
'clearStorage'
'clearStorageSync'
'getStorageInfo'
'getStorageInfoSync'
]
},
location: {
title: '位置',
api: [
'getLocation',
'openLocation',
'chooseLocation'
]
},
media: {
title: '媒体',
api: [
'chooseImage',
'previewImage',
'getImageInfo',
'saveImageToPhotosAlbum',
'compressImage',
'getRecorderManager',
'getBackgroundAudioManager',
'createInnerAudioContext',
'chooseVideo',
'saveVideoToPhotosAlbum',
'createVideoContext',
'createCameraContext',
'createLivePlayerContext'
]
}
}
export function createServiceContext(Vue, weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge){
export function createServiceContext(Vue, weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge,instanceContext){
var localStorage = plus.storage
var setTimeout = global.setTimeout
var clearTimeout = global.clearTimeout
var setTimeout = instanceContext.setTimeout
var clearTimeout = instanceContext.clearTimeout
var setInterval = instanceContext.setInterval
var clearInterval = instanceContext.clearInterval
var serviceContext = (function () {
'use strict';
......@@ -24,27 +26,51 @@ var serviceContext = (function () {
return callHook(vm, hook, params)
}
function callApiSync (api, args, name, alias) {
const ret = api(args);
if (ret && ret.errMsg) {
ret.errMsg = ret.errMsg.replace(name, alias);
}
return ret
function pack (args) {
return args
}
function unpack (args) {
return args
}
function getLastWebview () {
try {
function invoke (...args) {
return UniServiceJSBridge.invokeCallbackHandler(...args)
}
function requireNativePlugin (name) {
return uni.requireNativePlugin(name)
}
/**
* 触发 service 层,与 onMethod 对应
*/
function publish (name, res) {
return UniServiceJSBridge.emit('api.' + name, res)
}
let lastStatusBarStyle;
function setStatusBarStyle (statusBarStyle) {
if (!statusBarStyle) {
const pages = getCurrentPages();
if (pages.length) {
return pages[pages.length - 1].$getAppWebview()
if (!pages.length) {
return
}
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
console.log('getCurrentPages is not ready');
statusBarStyle = pages[pages.length - 1].$page.meta.statusBarStyle;
if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) {
return
}
}
}
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] setStatusBarStyle`, statusBarStyle);
}
lastStatusBarStyle = statusBarStyle;
plus.navigator.setStatusBarStyle(statusBarStyle);
}
function isTabBarPage (path = '') {
if (!(__uniConfig.tabBar && Array.isArray(__uniConfig.tabBar.list))) {
return false
......@@ -68,6 +94,27 @@ var serviceContext = (function () {
}
}
return false
}
function callApiSync (api, args, name, alias) {
const ret = api(args);
if (ret && ret.errMsg) {
ret.errMsg = ret.errMsg.replace(name, alias);
}
return ret
}
function getLastWebview () {
try {
const pages = getCurrentPages();
if (pages.length) {
return pages[pages.length - 1].$getAppWebview()
}
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
console.log('getCurrentPages is not ready');
}
}
}
const getRealRoute = (e, t) => {
......@@ -674,54 +721,13 @@ var serviceContext = (function () {
return webview
}
function unpack (args) {
return args
}
function invoke (...args) {
return UniServiceJSBridge.invokeCallbackHandler(...args)
}
function requireNativePlugin (name) {
return uni.requireNativePlugin(name)
}
/**
* 触发 service 层,与 onMethod 对应
*/
function publish (name, res) {
return UniServiceJSBridge.emit('api.' + name, res)
}
let lastStatusBarStyle;
function setStatusBarStyle (statusBarStyle) {
if (!statusBarStyle) {
const pages = getCurrentPages();
if (!pages.length) {
return
}
statusBarStyle = pages[pages.length - 1].$page.meta.statusBarStyle;
if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) {
return
}
}
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] setStatusBarStyle`, statusBarStyle);
}
lastStatusBarStyle = statusBarStyle;
plus.navigator.setStatusBarStyle(statusBarStyle);
}
const callbacks = {};
/**
* 注册 view 层通知 service 层事件处理
*/
function registerPlusMessage (type, callback, keepAlive = true) {
if (callbacks[type]) {
throw new Error(`${type} 已注册:` + (callbacks[type].toString()))
return console.warn(`${type} 已注册:` + (callbacks[type].toString()))
}
callback.keepAlive = !!keepAlive;
callbacks[type] = callback;
......@@ -1421,7 +1427,6 @@ var serviceContext = (function () {
'getImageInfo',
'saveImageToPhotosAlbum',
'compressImage',
'chooseMessageFile',
'getRecorderManager',
'getBackgroundAudioManager',
'createInnerAudioContext',
......@@ -3716,28 +3721,6 @@ var serviceContext = (function () {
upx2px: upx2px$1
});
const Emitter = new Vue();
function apply (ctx, method, args) {
return ctx[method].apply(ctx, args)
}
function $on$1 () {
return apply(Emitter, '$on', [...arguments])
}
function $off$1 () {
return apply(Emitter, '$off', [...arguments])
}
function $once$1 () {
return apply(Emitter, '$once', [...arguments])
}
function $emit$1 () {
return apply(Emitter, '$emit', [...arguments])
}
let audios = {};
const evts = ['play', 'canplay', 'ended', 'stop', 'waiting', 'seeking', 'seeked', 'pause'];
......@@ -4324,7 +4307,7 @@ var serviceContext = (function () {
/**
* 执行蓝牙相关方法
*/
function bluetoothExec (method, callbackId, data = {}, beforeSuccess) {
function bluetoothExec (method, callbackId, data = {}) {
var deviceId = data.deviceId;
if (deviceId) {
data.deviceId = deviceId.toUpperCase();
......@@ -4336,10 +4319,7 @@ var serviceContext = (function () {
plus.bluetooth[method.replace('Changed', 'Change')](Object.assign(data, {
success (data) {
if (typeof beforeSuccess === 'function') {
beforeSuccess(data);
}
invoke(callbackId, Object.assign({}, data, {
invoke(callbackId, Object.assign({}, pack(data), {
errMsg: `${method}:ok`,
code: undefined,
message: undefined
......@@ -4356,12 +4336,9 @@ var serviceContext = (function () {
/**
* 监听蓝牙相关事件
*/
function bluetoothOn (method, beforeSuccess) {
function bluetoothOn (method) {
plus.bluetooth[method.replace('Changed', 'Change')](function (data) {
if (typeof beforeSuccess === 'function') {
beforeSuccess(data);
}
publish(method, Object.assign({}, data, {
publish(method, Object.assign({}, pack(data), {
code: undefined,
message: undefined
}));
......@@ -4369,16 +4346,6 @@ var serviceContext = (function () {
return true
}
function checkDevices (data) {
data.devices = data.devices.map(device => {
var advertisData = device.advertisData;
if (advertisData && typeof advertisData !== 'string') {
device.advertisData = wx.arrayBufferToBase64(advertisData);
}
return device
});
}
var onBluetoothAdapterStateChange;
var onBluetoothDeviceFound;
var onBLEConnectionStateChange;
......@@ -4399,7 +4366,7 @@ var serviceContext = (function () {
}
function startBluetoothDevicesDiscovery (data, callbackId) {
onBluetoothDeviceFound = onBluetoothDeviceFound || bluetoothOn('onBluetoothDeviceFound', checkDevices);
onBluetoothDeviceFound = onBluetoothDeviceFound || bluetoothOn('onBluetoothDeviceFound');
bluetoothExec('startBluetoothDevicesDiscovery', callbackId, data);
}
......@@ -4408,7 +4375,7 @@ var serviceContext = (function () {
}
function getBluetoothDevices (data, callbackId) {
bluetoothExec('getBluetoothDevices', callbackId, {}, checkDevices);
bluetoothExec('getBluetoothDevices', callbackId, {});
}
function getConnectedBluetoothDevices (data, callbackId) {
......@@ -4434,18 +4401,12 @@ var serviceContext = (function () {
}
function notifyBLECharacteristicValueChange (data, callbackId) {
onBLECharacteristicValueChange = onBLECharacteristicValueChange || bluetoothOn('onBLECharacteristicValueChange',
data => {
data.value = wx.arrayBufferToBase64(data.value);
});
onBLECharacteristicValueChange = onBLECharacteristicValueChange || bluetoothOn('onBLECharacteristicValueChange');
bluetoothExec('notifyBLECharacteristicValueChange', callbackId, data);
}
function notifyBLECharacteristicValueChanged (data, callbackId) {
onBLECharacteristicValueChange = onBLECharacteristicValueChange || bluetoothOn('onBLECharacteristicValueChange',
data => {
data.value = wx.arrayBufferToBase64(data.value);
});
onBLECharacteristicValueChange = onBLECharacteristicValueChange || bluetoothOn('onBLECharacteristicValueChange');
bluetoothExec('notifyBLECharacteristicValueChanged', callbackId, data);
}
......@@ -4454,8 +4415,7 @@ var serviceContext = (function () {
}
function writeBLECharacteristicValue (data, callbackId) {
data.value = wx.base64ToArrayBuffer(data.value);
bluetoothExec('writeBLECharacteristicValue', callbackId, data);
bluetoothExec('writeBLECharacteristicValue', callbackId, unpack(data));
}
function getScreenBrightness () {
......@@ -7021,15 +6981,11 @@ var serviceContext = (function () {
startPullDownRefresh: startPullDownRefresh,
stopPullDownRefresh: stopPullDownRefresh,
chooseImage: chooseImage$1,
$on: $on$1,
$off: $off$1,
$once: $once$1,
$emit: $emit$1,
getMusicPlayerState: getMusicPlayerState,
operateMusicPlayer: operateMusicPlayer,
setBackgroundAudioState: setBackgroundAudioState,
operateBackgroundAudio: operateBackgroundAudio,
getBackgroundAudioState: getBackgroundAudioState,
createAudioInstance: createAudioInstance,
destroyAudioInstance: destroyAudioInstance,
setAudioState: setAudioState,
getAudioState: getAudioState,
operateAudio: operateAudio,
enableAccelerometer: enableAccelerometer,
addPhoneContact: addPhoneContact,
openBluetoothAdapter: openBluetoothAdapter,
......@@ -7081,11 +7037,11 @@ var serviceContext = (function () {
playVoice: playVoice,
pauseVoice: pauseVoice,
stopVoice: stopVoice,
createAudioInstance: createAudioInstance,
destroyAudioInstance: destroyAudioInstance,
setAudioState: setAudioState,
getAudioState: getAudioState,
operateAudio: operateAudio,
getMusicPlayerState: getMusicPlayerState,
operateMusicPlayer: operateMusicPlayer,
setBackgroundAudioState: setBackgroundAudioState,
operateBackgroundAudio: operateBackgroundAudio,
getBackgroundAudioState: getBackgroundAudioState,
chooseVideo: chooseVideo$1,
compressImage: compressImage,
getImageInfo: getImageInfo$1,
......@@ -7131,895 +7087,1355 @@ var serviceContext = (function () {
showTabBar: showTabBar$2
});
const SUCCESS = 'success';
const FAIL = 'fail';
const COMPLETE = 'complete';
const CALLBACKS = [SUCCESS, FAIL, COMPLETE];
const Emitter = new Vue();
/**
* 调用无参数,或仅一个参数且为 callback 的 API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethodWithoutArgs (vm, method, args, extras) {
if (!vm) {
return
}
if (typeof args === 'undefined') {
return vm[method]()
}
const [, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method]()
}
return vm[method](normalizeCallback(method, callbacks))
}
/**
* 调用两个参数(第一个入参为普通参数,第二个入参为 callback) API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethod (vm, method, args, extras) {
if (!vm) {
return
}
const [pureArgs, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method](pureArgs)
}
return vm[method](pureArgs, normalizeCallback(method, callbacks))
function apply (ctx, method, args) {
return ctx[method].apply(ctx, args)
}
function findElmById (id, vm) {
return findElmByVNode(id, vm._vnode)
function $on$1 () {
return apply(Emitter, '$on', [...arguments])
}
function findElmByVNode (id, vnode) {
if (!id || !vnode) {
return
}
if (
vnode.data &&
vnode.data.attrs &&
vnode.data.attrs.id === id
) {
return vnode.elm
}
const children = vnode.children;
if (!children) {
return
}
for (let i = 0, len = children.length; i < len; i++) {
const elm = findElmByVNode(id, children[i]);
if (elm) {
return elm
}
}
function $off$1 () {
return apply(Emitter, '$off', [...arguments])
}
function normalizeArgs (args = {}, extras) {
const callbacks = Object.create(null);
const iterator = function iterator (name) {
const callback = args[name];
if (isFn(callback)) {
callbacks[name] = callback;
delete args[name];
}
};
CALLBACKS.forEach(iterator);
extras && extras.forEach(iterator);
return [args, callbacks]
function $once$1 () {
return apply(Emitter, '$once', [...arguments])
}
function normalizeCallback (method, callbacks) {
return function weexCallback (ret) {
const type = ret.type;
delete ret.type;
const callback = callbacks[type];
if (type === SUCCESS) {
ret.errMsg = `${method}:ok`;
} else if (type === FAIL) {
ret.errMsg = method + ':fail' + (ret.msg ? (' ' + ret.msg) : '');
}
delete ret.code;
delete ret.msg;
isFn(callback) && callback(ret);
if (type === SUCCESS || type === FAIL) {
const complete = callbacks['complete'];
isFn(complete) && complete(ret);
}
}
function $emit$1 () {
return apply(Emitter, '$emit', [...arguments])
}
class LivePusherContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
var eventApis = /*#__PURE__*/Object.freeze({
$on: $on$1,
$off: $off$1,
$once: $once$1,
$emit: $emit$1
});
var api = Object.assign(Object.create(null), appApi, eventApis);
/**
* 执行内部平台方法
*/
function invokeMethod (name, ...args) {
return api[name].apply(null, args)
}
/**
* 监听 service 层内部平台方法回调,与 publish 对应
* @param {Object} name
* @param {Object} callback
*/
function onMethod (name, callback) {
return UniServiceJSBridge.on('api.' + name, callback)
}
const callbacks$1 = [];
start (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'start', cbs)
}
onMethod('onAccelerometerChange', function (res) {
callbacks$1.forEach(callbackId => {
invoke(callbackId, res);
});
});
stop (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stop', cbs)
let isEnable = false;
/**
* 监听加速度
* @param {*} callbackId
*/
function onAccelerometerChange (callbackId) {
// TODO 当没有 start 时,添加 on 需要主动 start?
callbacks$1.push(callbackId);
if (!isEnable) {
startAccelerometer();
}
}
pause (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pause', cbs)
function startAccelerometer ({
interval // TODO
} = {}) {
if (isEnable) {
return
}
isEnable = true;
return invokeMethod('enableAccelerometer', {
enable: true
})
}
resume (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resume', cbs)
function stopAccelerometer () {
isEnable = false;
return invokeMethod('enableAccelerometer', {
enable: false
})
}
var require_context_module_1_4 = /*#__PURE__*/Object.freeze({
onAccelerometerChange: onAccelerometerChange,
startAccelerometer: startAccelerometer,
stopAccelerometer: stopAccelerometer
});
function on (method) {
const callbacks = [];
onMethod(method, data => {
callbacks.forEach(callbackId => {
invoke(callbackId, data);
});
});
return function (callbackId) {
callbacks.push(callbackId);
}
}
switchCamera (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', cbs)
}
const onBluetoothDeviceFound$1 = on('onBluetoothDeviceFound');
const onBluetoothAdapterStateChange$1 = on('onBluetoothAdapterStateChange');
const onBLEConnectionStateChange$1 = on('onBLEConnectionStateChange');
const onBLECharacteristicValueChange$1 = on('onBLECharacteristicValueChange');
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
onBluetoothDeviceFound: onBluetoothDeviceFound$1,
onBluetoothAdapterStateChange: onBluetoothAdapterStateChange$1,
onBLEConnectionStateChange: onBLEConnectionStateChange$1,
onBLECharacteristicValueChange: onBLECharacteristicValueChange$1
});
const callbacks$2 = [];
snapshot (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', cbs)
}
onMethod('onCompassChange', function (res) {
callbacks$2.forEach(callbackId => {
invoke(callbackId, res);
});
});
toggleTorch (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', cbs)
let isEnable$1 = false;
/**
* 监听加速度
* @param {*} callbackId
*/
function onCompassChange (callbackId) {
// TODO 当没有 start 时,添加 on 需要主动 start?
callbacks$2.push(callbackId);
if (!isEnable$1) {
startCompass();
}
}
playBGM (args) {
return invokeVmMethod(this.ctx, 'playBGM', args)
function startCompass ({
interval // TODO
} = {}) {
if (isEnable$1) {
return
}
isEnable$1 = true;
return invokeMethod('enableCompass', {
enable: true
})
}
stopBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', cbs)
function stopCompass () {
isEnable$1 = false;
return invokeMethod('enableCompass', {
enable: false
})
}
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
onCompassChange: onCompassChange,
startCompass: startCompass,
stopCompass: stopCompass
});
class DownloadTask {
constructor (downloadTaskId, callbackId) {
this.id = downloadTaskId;
this._callbackId = callbackId;
this._callbacks = [];
}
pauseBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', cbs)
abort () {
invokeMethod('operateRequestTask', {
downloadTaskId: this.id,
operationType: 'abort'
});
}
resumeBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', cbs)
onProgressUpdate (callback) {
if (typeof callback !== 'function') {
return
}
this._callbacks.push(callback);
}
onHeadersReceived () {
setBGMVolume (cbs) {
return invokeVmMethod(this.ctx, 'setBGMVolume', cbs)
}
startPreview (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', cbs)
offProgressUpdate (callback) {
const index = this._callbacks.indexOf(callback);
if (index >= 0) {
this._callbacks.splice(index, 1);
}
}
offHeadersReceived () {
stopPreview (args) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args)
}
}
const downloadTasks$1 = Object.create(null);
onMethod('onDownloadTaskStateChange', ({
downloadTaskId,
state,
tempFilePath,
statusCode,
progress,
totalBytesWritten,
totalBytesExpectedToWrite,
errMsg
}) => {
const downloadTask = downloadTasks$1[downloadTaskId];
const callbackId = downloadTask._callbackId;
function createLivePusherContext (id, vm) {
if (!vm) {
return console.warn('uni.createLivePusherContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
switch (state) {
case 'progressUpdate':
downloadTask._callbacks.forEach(callback => {
callback({
progress,
totalBytesWritten,
totalBytesExpectedToWrite
});
});
break
case 'success':
invoke(callbackId, {
tempFilePath,
statusCode,
errMsg: 'request:ok'
});
// eslint-disable-next-line no-fallthrough
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
});
// eslint-disable-next-line no-fallthrough
default:
// progressUpdate 可能晚于 success
setTimeout(() => {
delete downloadTasks$1[downloadTaskId];
}, 100);
break
}
return new LivePusherContext(id, elm)
});
function downloadFile$1 (args, callbackId) {
const {
downloadTaskId
} = invokeMethod('createDownloadTask', args);
const task = new DownloadTask(downloadTaskId, callbackId);
downloadTasks$1[downloadTaskId] = task;
return task
}
class MapContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
getCenterLocation (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getCenterLocation', cbs)
}
var require_context_module_1_7 = /*#__PURE__*/Object.freeze({
downloadFile: downloadFile$1
});
const requestTasks$1 = Object.create(null);
moveToLocation () {
return invokeVmMethodWithoutArgs(this.ctx, 'moveToLocation')
function formatResponse (res, args) {
if (
typeof res.data === 'string' &&
res.data.charCodeAt(0) === 65279
) {
res.data = res.data.substr(1);
}
translateMarker (args) {
return invokeVmMethod(this.ctx, 'translateMarker', args, ['animationEnd'])
}
res.statusCode = parseInt(res.statusCode, 10);
includePoints (args) {
return invokeVmMethod(this.ctx, 'includePoints', args)
if (isPlainObject(res.header)) {
res.header = Object.keys(res.header).reduce(function (ret, key) {
const value = res.header[key];
if (Array.isArray(value)) {
ret[key] = value.join(',');
} else if (typeof value === 'string') {
ret[key] = value;
}
return ret
}, {});
}
getRegion (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getRegion', cbs)
if (args.dataType && args.dataType.toLowerCase() === 'json') {
try {
res.data = JSON.parse(res.data);
} catch (e) {}
}
getScale (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getScale', cbs)
}
return res
}
function createMapContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createMapContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
onMethod('onRequestTaskStateChange', function ({
requestTaskId,
state,
data,
statusCode,
header,
errMsg
}) {
const {
args,
callbackId
} = requestTasks$1[requestTaskId] || {};
if (!callbackId) {
return
}
return new MapContext(id, elm)
}
class VideoContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
delete requestTasks$1[requestTaskId];
switch (state) {
case 'success':
invoke(callbackId, formatResponse({
data,
statusCode,
header,
errMsg: 'request:ok'
}, args));
break
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
});
break
}
});
play () {
return invokeVmMethodWithoutArgs(this.ctx, 'play')
class RequestTask {
constructor (id) {
this.id = id;
}
pause () {
return invokeVmMethodWithoutArgs(this.ctx, 'pause')
abort () {
invokeMethod('operateRequestTask', {
requestTaskId: this.id,
operationType: 'abort'
});
}
seek (args) {
return invokeVmMethod(this.ctx, 'seek', args)
}
offHeadersReceived () {
stop () {
return invokeVmMethodWithoutArgs(this.ctx, 'stop')
}
sendDanmu (args) {
return invokeVmMethod(this.ctx, 'sendDanmu', args)
}
onHeadersReceived () {
playbackRate (args) {
return invokeVmMethod(this.ctx, 'playbackRate', args)
}
}
requestFullScreen (args) {
return invokeVmMethod(this.ctx, 'requestFullScreen', args)
}
function request$1 (args, callbackId) {
const {
requestTaskId
} = invokeMethod('createRequestTask', args);
exitFullScreen () {
return invokeVmMethodWithoutArgs(this.ctx, 'exitFullScreen')
}
requestTasks$1[requestTaskId] = {
args,
callbackId
};
showStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'showStatusBar')
return new RequestTask(requestTaskId)
}
var require_context_module_1_8 = /*#__PURE__*/Object.freeze({
request: request$1
});
class SocketTask {
constructor (socketTaskId) {
this.id = socketTaskId;
this._callbacks = {
open: [],
close: [],
error: [],
message: []
};
this.CLOSED = 3;
this.CLOSING = 2;
this.CONNECTING = 0;
this.OPEN = 1;
this.readyState = this.CLOSED;
}
hideStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'hideStatusBar')
send (args) {
if (this.readyState !== this.OPEN) {
this._callback(args, 'sendSocketMessage:fail WebSocket is not connected');
}
const {
errMsg
} = invokeMethod('operateSocketTask', Object.assign({}, args, {
operationType: 'send',
socketTaskId: this.id
}));
this._callback(args, errMsg.replace('operateSocketTask', 'sendSocketMessage'));
}
}
function createVideoContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createVideoContext 必须传入第二个参数,即当前 vm 对象(this)')
close (args) {
this.readyState = this.CLOSING;
const {
errMsg
} = invokeMethod('operateSocketTask', Object.assign({}, args, {
operationType: 'close',
socketTaskId: this.id
}));
this._callback(args, errMsg.replace('operateSocketTask', 'closeSocket'));
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
onOpen (callback) {
this._callbacks.open.push(callback);
}
return new VideoContext(id, elm)
}
function requireNativePlugin$1 (name) {
return weex.requireModule(name)
}
const ANI_DURATION$1 = 300;
const ANI_SHOW$1 = 'pop-in';
const ANI_CLOSE = 'pop-out';
function showWebview (webview, animationType, animationDuration, callback) {
setTimeout(() => {
webview.show(
animationType || ANI_SHOW$1,
parseInt(animationDuration) || ANI_DURATION$1,
() => {
callback && callback();
}
);
}, 50);
}
let firstBackTime = 0;
function quit () {
if (!firstBackTime) {
firstBackTime = Date.now();
plus.nativeUI.toast('再按一次退出应用');
setTimeout(() => {
firstBackTime = null;
}, 2000);
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit();
onClose (callback) {
this._callbacks.close.push(callback);
}
}
function backWebview (webview, callback) {
if (!webview.__uniapp_webview) {
return callback()
onError (callback) {
this._callbacks.error.push(callback);
}
const children = webview.children();
if (!children || !children.length) { // 有子 webview
return callback()
onMessage (callback) {
this._callbacks.message.push(callback);
}
const childWebview = children[0];
childWebview.canBack(({
canBack
}) => {
if (canBack) {
childWebview.back(); // webview 返回
_callback ({
success,
fail,
complete
}, errMsg) {
var data = {
errMsg
};
if (/:ok$/.test(errMsg)) {
if (typeof success === 'function') {
success(data);
}
} else {
callback();
if (typeof fail === 'function') {
fail(data);
}
}
});
if (typeof complete === 'function') {
complete(data);
}
}
}
function back (delta, animationType, animationDuration) {
const pages = getCurrentPages();
const len = pages.length;
const currentPage = pages[len - 1];
if (delta > 1) {
// 中间页隐藏
pages.slice(len - delta, len - 1).reverse().forEach(deltaPage => {
deltaPage.$getAppWebview().close('none');
});
const socketTasks$1 = Object.create(null);
const socketTasksArray = [];
const callbacks$3 = Object.create(null);
onMethod('onSocketTaskStateChange', ({
socketTaskId,
state,
data,
errMsg
}) => {
const socketTask = socketTasks$1[socketTaskId];
if (!socketTask) {
return
}
backWebview(currentPage, () => {
if (animationType) {
currentPage.$getAppWebview().close(animationType, animationDuration || ANI_DURATION$1);
} else {
if (currentPage.$page.openType === 'redirect') { // 如果是 redirectTo 跳转的,需要制定 back 动画
currentPage.$getAppWebview().close(ANI_CLOSE, ANI_DURATION$1);
}
currentPage.$getAppWebview().close('auto');
socketTask._callbacks[state].forEach(callback => {
if (typeof callback === 'function') {
callback(state === 'message' ? {
data
} : {});
}
});
if (state === 'open') {
socketTask.readyState = socketTask.OPEN;
}
if (socketTask === socketTasksArray[0] && callbacks$3[state]) {
invoke(callbacks$3[state], state === 'message' ? {
data
} : {});
}
if (state === 'error' || state === 'close') {
socketTask.readyState = socketTask.CLOSED;
delete socketTasks$1[socketTaskId];
const index = socketTasksArray.indexOf(socketTask);
if (index >= 0) {
socketTasksArray.splice(index, 1);
}
}
});
pages.slice(len - delta, len).forEach(page => page.$remove());
setStatusBarStyle();
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateBack'
function connectSocket$1 (args, callbackId) {
const {
socketTaskId
} = invokeMethod('createSocketTask', args);
const task = new SocketTask(socketTaskId);
socketTasks$1[socketTaskId] = task;
socketTasksArray.push(task);
setTimeout(() => {
invoke(callbackId, {
errMsg: 'connectSocket:ok'
});
});
}, 0);
return task
}
function navigateBack$1 ({
delta,
animationType,
animationDuration
}) {
const pages = getCurrentPages();
const len = pages.length;
uni.hideToast(); // 后退时,关闭 toast,loading
function sendSocketMessage$1 (args, callbackId) {
const socketTask = socketTasksArray[0];
if (!socketTask || socketTask.readyState !== socketTask.OPEN) {
invoke(callbackId, {
errMsg: 'sendSocketMessage:fail WebSocket is not connected'
});
return
}
return invokeMethod('operateSocketTask', Object.assign({}, args, {
operationType: 'send',
socketTaskId: socketTask.id
}))
}
pages[len - 1].$page.meta.isQuit
? quit()
: back(delta, animationType, animationDuration);
}
function navigateTo$1 ({
url,
animationType,
animationDuration
}) {
const urls = url.split('?');
const path = urls[0];
function closeSocket$1 (args, callbackId) {
const socketTask = socketTasksArray[0];
if (!socketTask) {
invoke(callbackId, {
errMsg: 'closeSocket:fail WebSocket is not connected'
});
return
}
socketTask.readyState = socketTask.CLOSING;
return invokeMethod('operateSocketTask', Object.assign({}, args, {
operationType: 'close',
socketTaskId: socketTask.id
}))
}
const query = parseQuery(urls[1] || '');
function onSocketOpen (callbackId) {
callbacks$3.open = callbackId;
}
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
path
});
function onSocketError (callbackId) {
callbacks$3.error = callbackId;
}
showWebview(
__registerPage({
path,
query,
openType: 'navigate'
}),
animationType,
animationDuration
);
function onSocketMessage (callbackId) {
callbacks$3.message = callbackId;
}
setStatusBarStyle();
function onSocketClose (callbackId) {
callbacks$3.close = callbackId;
}
function reLaunch$1 ({
url
}) {
const urls = url.split('?');
const path = urls[0];
var require_context_module_1_9 = /*#__PURE__*/Object.freeze({
connectSocket: connectSocket$1,
sendSocketMessage: sendSocketMessage$1,
closeSocket: closeSocket$1,
onSocketOpen: onSocketOpen,
onSocketError: onSocketError,
onSocketMessage: onSocketMessage,
onSocketClose: onSocketClose
});
class UploadTask {
constructor (uploadTaskId, callbackId) {
this.id = uploadTaskId;
this._callbackId = callbackId;
this._callbacks = [];
}
abort () {
invokeMethod('operateRequestTask', {
uploadTaskId: this.id,
operationType: 'abort'
});
}
onProgressUpdate (callback) {
if (typeof callback !== 'function') {
return
}
this._callbacks.push(callback);
}
onHeadersReceived () {
const query = parseQuery(urls[1] || '');
}
offProgressUpdate (callback) {
const index = this._callbacks.indexOf(callback);
if (index >= 0) {
this._callbacks.splice(index, 1);
}
}
offHeadersReceived () {
const pages = getCurrentPages(true).slice(0);
}
}
const uploadTasks$1 = Object.create(null);
onMethod('onUploadTaskStateChange', ({
uploadTaskId,
state,
data,
statusCode,
progress,
totalBytesSent,
totalBytesExpectedToSend,
errMsg
}) => {
const uploadTask = uploadTasks$1[uploadTaskId];
const callbackId = uploadTask._callbackId;
switch (state) {
case 'progressUpdate':
uploadTask._callbacks.forEach(callback => {
callback({
progress,
totalBytesSent,
totalBytesExpectedToSend
});
});
break
case 'success':
invoke(callbackId, {
data,
statusCode,
errMsg: 'request:ok'
});
// eslint-disable-next-line no-fallthrough
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
});
// eslint-disable-next-line no-fallthrough
default:
// progressUpdate 可能晚于 success
setTimeout(() => {
delete uploadTasks$1[uploadTaskId];
}, 100);
break
}
});
function uploadFile$1 (args, callbackId) {
const {
uploadTaskId
} = invokeMethod('createUploadTask', args);
const task = new UploadTask(uploadTaskId, callbackId);
uploadTasks$1[uploadTaskId] = task;
return task
}
var require_context_module_1_10 = /*#__PURE__*/Object.freeze({
uploadFile: uploadFile$1
});
function setStorage$1 ({
key,
data
} = {}) {
const value = {
type: typeof data === 'object' ? 'object' : 'string',
data: data
};
localStorage.setItem(key, JSON.stringify(value));
const keyList = localStorage.getItem('uni-storage-keys');
if (!keyList) {
localStorage.setItem('uni-storage-keys', JSON.stringify([key]));
} else {
const keys = JSON.parse(keyList);
if (keys.indexOf(key) < 0) {
keys.push(key);
localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
}
}
return {
errMsg: 'setStorage:ok'
}
}
function setStorageSync$1 (key, data) {
setStorage$1({
key,
data
});
}
function getStorage$1 ({
key
} = {}) {
const data = localStorage.getItem(key);
return data ? {
data: JSON.parse(data).data,
errMsg: 'getStorage:ok'
} : {
data: '',
errMsg: 'getStorage:fail'
}
}
function getStorageSync$1 (key) {
const res = getStorage$1({
key
});
return res.data
}
function removeStorage$1 ({
key
} = {}) {
const keyList = localStorage.getItem('uni-storage-keys');
if (keyList) {
const keys = JSON.parse(keyList);
const index = keys.indexOf(key);
keys.splice(index, 1);
localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
}
localStorage.removeItem(key);
return {
errMsg: 'removeStorage:ok'
}
}
function removeStorageSync$1 (key) {
removeStorage$1({
key
});
}
function clearStorage () {
localStorage.clear();
return {
errMsg: 'clearStorage:ok'
}
}
function clearStorageSync () {
clearStorage();
}
function getStorageInfo () { // TODO 暂时先不做大小的转换
const keyList = localStorage.getItem('uni-storage-keys');
return keyList ? {
keys: JSON.parse(keyList),
currentSize: 0,
limitSize: 0,
errMsg: 'getStorageInfo:ok'
} : {
keys: '',
currentSize: 0,
limitSize: 0,
errMsg: 'getStorageInfo:fail'
}
}
function getStorageInfoSync () {
const res = getStorageInfo();
delete res.errMsg;
return res
}
var require_context_module_1_11 = /*#__PURE__*/Object.freeze({
setStorage: setStorage$1,
setStorageSync: setStorageSync$1,
getStorage: getStorage$1,
getStorageSync: getStorageSync$1,
removeStorage: removeStorage$1,
removeStorageSync: removeStorageSync$1,
clearStorage: clearStorage,
clearStorageSync: clearStorageSync,
getStorageInfo: getStorageInfo,
getStorageInfoSync: getStorageInfoSync
});
function pageScrollTo$1 (args) {
const pages = getCurrentPages();
if (pages.length) {
UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
}
return {}
}
var require_context_module_1_12 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1
});
const api$1 = Object.create(null);
const modules$1 =
(function() {
var map = {
'./base/base64.js': require_context_module_1_0,
'./base/can-i-use.js': require_context_module_1_1,
'./base/interceptor.js': require_context_module_1_2,
'./base/upx2px.js': require_context_module_1_3,
'./device/accelerometer.js': require_context_module_1_4,
'./device/bluetooth.js': require_context_module_1_5,
'./device/compass.js': require_context_module_1_6,
'./network/download-file.js': require_context_module_1_7,
'./network/request.js': require_context_module_1_8,
'./network/socket.js': require_context_module_1_9,
'./network/upload-file.js': require_context_module_1_10,
'./storage/storage.js': require_context_module_1_11,
'./ui/page-scroll-to.js': require_context_module_1_12,
};
var req = function req(key) {
return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
};
req.keys = function() {
return Object.keys(map);
};
return req;
})();
modules$1.keys().forEach(function (key) {
Object.assign(api$1, modules$1(key));
});
const SUCCESS = 'success';
const FAIL = 'fail';
const COMPLETE = 'complete';
const CALLBACKS = [SUCCESS, FAIL, COMPLETE];
/**
* 调用无参数,或仅一个参数且为 callback 的 API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethodWithoutArgs (vm, method, args, extras) {
if (!vm) {
return
}
if (typeof args === 'undefined') {
return vm[method]()
}
const [, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method]()
}
return vm[method](normalizeCallback(method, callbacks))
}
/**
* 调用两个参数(第一个入参为普通参数,第二个入参为 callback) API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethod (vm, method, args, extras) {
if (!vm) {
return
}
const [pureArgs, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method](pureArgs)
}
return vm[method](pureArgs, normalizeCallback(method, callbacks))
}
function findElmById (id, vm) {
return findElmByVNode(id, vm._vnode)
}
function findElmByVNode (id, vnode) {
if (!id || !vnode) {
return
}
if (
vnode.data &&
vnode.data.attrs &&
vnode.data.attrs.id === id
) {
return vnode.elm
}
const children = vnode.children;
if (!children) {
return
}
for (let i = 0, len = children.length; i < len; i++) {
const elm = findElmByVNode(id, children[i]);
if (elm) {
return elm
}
}
}
function normalizeArgs (args = {}, extras) {
const callbacks = Object.create(null);
const iterator = function iterator (name) {
const callback = args[name];
if (isFn(callback)) {
callbacks[name] = callback;
delete args[name];
}
};
CALLBACKS.forEach(iterator);
extras && extras.forEach(iterator);
return [args, callbacks]
}
function normalizeCallback (method, callbacks) {
return function weexCallback (ret) {
const type = ret.type;
delete ret.type;
const callback = callbacks[type];
const routeOptions = __uniRoutes.find(route => route.path === path);
if (type === SUCCESS) {
ret.errMsg = `${method}:ok`;
} else if (type === FAIL) {
ret.errMsg = method + ':fail' + (ret.msg ? (' ' + ret.msg) : '');
}
if (routeOptions.meta.isTabBar) {
tabBar.switchTab(url);
delete ret.code;
delete ret.msg;
isFn(callback) && callback(ret);
if (type === SUCCESS || type === FAIL) {
const complete = callbacks['complete'];
isFn(complete) && complete(ret);
}
}
}
class LivePusherContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
showWebview(
__registerPage({
path,
query,
openType: 'reLaunch'
}),
'none',
0
);
start (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'start', cbs)
}
pages.forEach(page => {
page.$remove();
page.$getAppWebview().close('none');
});
stop (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stop', cbs)
}
setStatusBarStyle();
pause (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pause', cbs)
}
resume (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resume', cbs)
}
switchCamera (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', cbs)
}
snapshot (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', cbs)
}
toggleTorch (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', cbs)
}
playBGM (args) {
return invokeVmMethod(this.ctx, 'playBGM', args)
}
stopBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', cbs)
}
pauseBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', cbs)
}
resumeBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', cbs)
}
setBGMVolume (cbs) {
return invokeVmMethod(this.ctx, 'setBGMVolume', cbs)
}
startPreview (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', cbs)
}
stopPreview (args) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args)
}
}
function createLivePusherContext (id, vm) {
if (!vm) {
return console.warn('uni.createLivePusherContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new LivePusherContext(id, elm)
}
function redirectTo$1 ({
url
}) {
const urls = url.split('?');
const path = urls[0];
class MapContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
const query = parseQuery(urls[1] || '');
getCenterLocation (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getCenterLocation', cbs)
}
const pages = getCurrentPages();
const lastPage = pages[pages.length - 1];
moveToLocation () {
return invokeVmMethodWithoutArgs(this.ctx, 'moveToLocation')
}
lastPage && lastPage.$remove();
translateMarker (args) {
return invokeVmMethod(this.ctx, 'translateMarker', args, ['animationEnd'])
}
showWebview(
__registerPage({
path,
query,
openType: 'redirect'
}),
'none',
0,
() => {
lastPage && lastPage.$getAppWebview().close('none');
}
);
includePoints (args) {
return invokeVmMethod(this.ctx, 'includePoints', args)
}
setStatusBarStyle();
getRegion (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getRegion', cbs)
}
getScale (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getScale', cbs)
}
}
function createMapContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createMapContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new MapContext(id, elm)
}
function switchTab$1 ({
url,
from
}) {
const path = url.split('?')[0];
class VideoContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
tabBar.switchTab(path.slice(1));
play () {
return invokeVmMethodWithoutArgs(this.ctx, 'play')
}
const pages = getCurrentPages();
const len = pages.length;
pause () {
return invokeVmMethodWithoutArgs(this.ctx, 'pause')
}
if (len >= 1) { // 前一个页面是非 tabBar 页面
const currentPage = pages[len - 1];
if (!currentPage.$page.meta.isTabBar) {
pages.reverse().forEach(page => {
if (!page.$page.meta.isTabBar && page !== currentPage) {
page.$remove();
page.$getAppWebview().close('none');
}
});
currentPage.$remove();
if (currentPage.$page.openType === 'redirect') {
currentPage.$getAppWebview().close(ANI_CLOSE, ANI_DURATION$1);
} else {
currentPage.$getAppWebview().close('auto');
}
} else {
// TODO 客户端 Bug
currentPage.$getAppWebview().hide('none');
// 前一个 tabBar 触发 onHide
currentPage.$vm.__call_hook('onHide');
}
seek (args) {
return invokeVmMethod(this.ctx, 'seek', args)
}
let tabBarPage;
// 查找当前 tabBarPage,且设置 visible
getCurrentPages(true).forEach(page => {
if (('/' + page.route) === path) {
page.$page.meta.visible = true;
tabBarPage = page;
} else {
if (page.$page.meta.isTabBar) {
page.$page.meta.visible = false;
}
}
});
stop () {
return invokeVmMethodWithoutArgs(this.ctx, 'stop')
}
if (tabBarPage) {
tabBarPage.$vm.__call_hook('onShow');
tabBarPage.$getAppWebview().show('none');
} else {
showWebview(
__registerPage({
path,
query: {},
openType: 'switchTab'
})
);
sendDanmu (args) {
return invokeVmMethod(this.ctx, 'sendDanmu', args)
}
playbackRate (args) {
return invokeVmMethod(this.ctx, 'playbackRate', args)
}
requestFullScreen (args) {
return invokeVmMethod(this.ctx, 'requestFullScreen', args)
}
exitFullScreen () {
return invokeVmMethodWithoutArgs(this.ctx, 'exitFullScreen')
}
showStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'showStatusBar')
}
hideStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'hideStatusBar')
}
}
function createVideoContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createVideoContext 必须传入第二个参数,即当前 vm 对象(this)')
}
setStatusBarStyle();
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new VideoContext(id, elm)
}
var nvueApi = /*#__PURE__*/Object.freeze({
createLivePusherContext: createLivePusherContext,
createMapContext: createMapContext$1,
createVideoContext: createVideoContext$1,
requireNativePlugin: requireNativePlugin$1,
navigateBack: navigateBack$1,
navigateTo: navigateTo$1,
reLaunch: reLaunch$1,
redirectTo: redirectTo$1,
switchTab: switchTab$1
});
var platformApi = Object.assign(Object.create(null), appApi, nvueApi);
/**
* 执行内部平台方法
*/
function invokeMethod (name, ...args) {
return platformApi[name].apply(null, args)
}
/**
* 监听 service 层内部平台方法回调,与 publish 对应
* @param {Object} name
* @param {Object} callback
*/
function onMethod (name, callback) {
return UniServiceJSBridge.on('api.' + name, callback)
function requireNativePlugin$1 (name) {
return weex.requireModule(name)
}
const callbacks$1 = [];
const ANI_DURATION$1 = 300;
const ANI_SHOW$1 = 'pop-in';
const ANI_CLOSE = 'pop-out';
onMethod('onAccelerometerChange', function (res) {
callbacks$1.forEach(callbackId => {
invoke(callbackId, res);
});
});
function showWebview (webview, animationType, animationDuration, callback) {
setTimeout(() => {
webview.show(
animationType || ANI_SHOW$1,
parseInt(animationDuration) || ANI_DURATION$1,
() => {
callback && callback();
}
);
}, 50);
}
let firstBackTime = 0;
let isEnable = false;
/**
* 监听加速度
* @param {*} callbackId
*/
function onAccelerometerChange (callbackId) {
// TODO 当没有 start 时,添加 on 需要主动 start?
callbacks$1.push(callbackId);
if (!isEnable) {
startAccelerometer();
function quit () {
if (!firstBackTime) {
firstBackTime = Date.now();
plus.nativeUI.toast('再按一次退出应用');
setTimeout(() => {
firstBackTime = null;
}, 2000);
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit();
}
}
function startAccelerometer ({
interval // TODO
} = {}) {
if (isEnable) {
return
function backWebview (webview, callback) {
if (!webview.__uniapp_webview) {
return callback()
}
isEnable = true;
return invokeMethod('enableAccelerometer', {
enable: true
})
const children = webview.children();
if (!children || !children.length) { // 有子 webview
return callback()
}
const childWebview = children[0];
childWebview.canBack(({
canBack
}) => {
if (canBack) {
childWebview.back(); // webview 返回
} else {
callback();
}
});
}
function stopAccelerometer () {
isEnable = false;
return invokeMethod('enableAccelerometer', {
enable: false
})
}
var require_context_module_1_4 = /*#__PURE__*/Object.freeze({
onAccelerometerChange: onAccelerometerChange,
startAccelerometer: startAccelerometer,
stopAccelerometer: stopAccelerometer
});
const requestTasks$1 = Object.create(null);
function back (delta, animationType, animationDuration) {
const pages = getCurrentPages();
const len = pages.length;
const currentPage = pages[len - 1];
function formatResponse (res, args) {
if (
typeof res.data === 'string' &&
res.data.charCodeAt(0) === 65279
) {
res.data = res.data.substr(1);
if (delta > 1) {
// 中间页隐藏
pages.slice(len - delta, len - 1).reverse().forEach(deltaPage => {
deltaPage.$getAppWebview().close('none');
});
}
res.statusCode = parseInt(res.statusCode, 10);
if (isPlainObject(res.header)) {
res.header = Object.keys(res.header).reduce(function (ret, key) {
const value = res.header[key];
if (Array.isArray(value)) {
ret[key] = value.join(',');
} else if (typeof value === 'string') {
ret[key] = value;
backWebview(currentPage, () => {
if (animationType) {
currentPage.$getAppWebview().close(animationType, animationDuration || ANI_DURATION$1);
} else {
if (currentPage.$page.openType === 'redirect') { // 如果是 redirectTo 跳转的,需要制定 back 动画
currentPage.$getAppWebview().close(ANI_CLOSE, ANI_DURATION$1);
}
return ret
}, {});
}
currentPage.$getAppWebview().close('auto');
}
if (args.dataType && args.dataType.toLowerCase() === 'json') {
try {
res.data = JSON.parse(res.data);
} catch (e) {}
}
pages.slice(len - delta, len).forEach(page => page.$remove());
return res
setStatusBarStyle();
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateBack'
});
});
}
onMethod('onRequestTaskStateChange', function ({
requestTaskId,
state,
data,
statusCode,
header,
errMsg
function navigateBack$1 ({
delta,
animationType,
animationDuration
}) {
const {
args,
callbackId
} = requestTasks$1[requestTaskId];
const pages = getCurrentPages();
const len = pages.length;
if (!callbackId) {
return
}
delete requestTasks$1[requestTaskId];
switch (state) {
case 'success':
invoke(callbackId, formatResponse({
data,
statusCode,
header,
errMsg: 'request:ok'
}, args));
break
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
});
break
}
});
uni.hideToast(); // 后退时,关闭 toast,loading
class RequestTask {
constructor (id) {
this.id = id;
}
pages[len - 1].$page.meta.isQuit
? quit()
: back(delta, animationType, animationDuration);
}
function navigateTo$1 ({
url,
animationType,
animationDuration
}) {
const urls = url.split('?');
const path = urls[0];
abort () {
invokeMethod('operateRequestTask', {
requestTaskId: this.id,
operationType: 'abort'
});
}
const query = parseQuery(urls[1] || '');
offHeadersReceived () {
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
path
});
}
showWebview(
__registerPage({
path,
query,
openType: 'navigate'
}),
animationType,
animationDuration
);
setStatusBarStyle();
}
function reLaunch$1 ({
url
}) {
const urls = url.split('?');
const path = urls[0];
const query = parseQuery(urls[1] || '');
const pages = getCurrentPages(true).slice(0);
onHeadersReceived () {
const routeOptions = __uniRoutes.find(route => route.path === path);
if (routeOptions.meta.isTabBar) {
tabBar.switchTab(url);
}
}
function request$1 (args, callbackId) {
const {
requestTaskId
} = invokeMethod('createRequestTask', args);
showWebview(
__registerPage({
path,
query,
openType: 'reLaunch'
}),
'none',
0
);
requestTasks$1[requestTaskId] = {
args,
callbackId
};
pages.forEach(page => {
page.$remove();
page.$getAppWebview().close('none');
});
return new RequestTask(requestTaskId)
setStatusBarStyle();
}
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
request: request$1
});
function setStorage$1 ({
key,
data
} = {}) {
const value = {
type: typeof data === 'object' ? 'object' : 'string',
data: data
};
localStorage.setItem(key, JSON.stringify(value));
const keyList = localStorage.getItem('uni-storage-keys');
if (!keyList) {
localStorage.setItem('uni-storage-keys', JSON.stringify([key]));
} else {
const keys = JSON.parse(keyList);
if (keys.indexOf(key) < 0) {
keys.push(key);
localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
}
}
return {
errMsg: 'setStorage:ok'
}
}
function redirectTo$1 ({
url
}) {
const urls = url.split('?');
const path = urls[0];
function setStorageSync$1 (key, data) {
setStorage$1({
key,
data
});
}
const query = parseQuery(urls[1] || '');
function getStorage$1 ({
key
} = {}) {
const data = localStorage.getItem(key);
return data ? {
data: JSON.parse(data).data,
errMsg: 'getStorage:ok'
} : {
data: '',
errMsg: 'getStorage:fail'
}
}
const pages = getCurrentPages();
const lastPage = pages[pages.length - 1];
function getStorageSync$1 (key) {
const res = getStorage$1({
key
});
return res.data
}
lastPage && lastPage.$remove();
function removeStorage$1 ({
key
} = {}) {
const keyList = localStorage.getItem('uni-storage-keys');
if (keyList) {
const keys = JSON.parse(keyList);
const index = keys.indexOf(key);
keys.splice(index, 1);
localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
}
localStorage.removeItem(key);
return {
errMsg: 'removeStorage:ok'
}
}
showWebview(
__registerPage({
path,
query,
openType: 'redirect'
}),
'none',
0,
() => {
lastPage && lastPage.$getAppWebview().close('none');
}
);
function removeStorageSync$1 (key) {
removeStorage$1({
key
});
}
setStatusBarStyle();
}
function switchTab$1 ({
url,
from
}) {
const path = url.split('?')[0];
function clearStorage () {
localStorage.clear();
return {
errMsg: 'clearStorage:ok'
tabBar.switchTab(path.slice(1));
const pages = getCurrentPages();
const len = pages.length;
if (len >= 1) { // 前一个页面是非 tabBar 页面
const currentPage = pages[len - 1];
if (!currentPage.$page.meta.isTabBar) {
pages.reverse().forEach(page => {
if (!page.$page.meta.isTabBar && page !== currentPage) {
page.$remove();
page.$getAppWebview().close('none');
}
});
currentPage.$remove();
if (currentPage.$page.openType === 'redirect') {
currentPage.$getAppWebview().close(ANI_CLOSE, ANI_DURATION$1);
} else {
currentPage.$getAppWebview().close('auto');
}
} else {
// 前一个 tabBar 触发 onHide
currentPage.$vm.__call_hook('onHide');
}
}
}
function clearStorageSync () {
clearStorage();
}
let tabBarPage;
// 查找当前 tabBarPage,且设置 visible
getCurrentPages(true).forEach(page => {
if (('/' + page.route) === path) {
page.$page.meta.visible = true;
tabBarPage = page;
} else {
if (page.$page.meta.isTabBar) {
page.$page.meta.visible = false;
}
}
});
function getStorageInfo () { // TODO 暂时先不做大小的转换
const keyList = localStorage.getItem('uni-storage-keys');
return keyList ? {
keys: JSON.parse(keyList),
currentSize: 0,
limitSize: 0,
errMsg: 'getStorageInfo:ok'
} : {
keys: '',
currentSize: 0,
limitSize: 0,
errMsg: 'getStorageInfo:fail'
if (tabBarPage) {
tabBarPage.$vm.__call_hook('onShow');
tabBarPage.$getAppWebview().show('none');
} else {
showWebview(
__registerPage({
path,
query: {},
openType: 'switchTab'
})
);
}
}
function getStorageInfoSync () {
const res = getStorageInfo();
delete res.errMsg;
return res
setStatusBarStyle();
}
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
setStorage: setStorage$1,
setStorageSync: setStorageSync$1,
getStorage: getStorage$1,
getStorageSync: getStorageSync$1,
removeStorage: removeStorage$1,
removeStorageSync: removeStorageSync$1,
clearStorage: clearStorage,
clearStorageSync: clearStorageSync,
getStorageInfo: getStorageInfo,
getStorageInfoSync: getStorageInfoSync
});
function pageScrollTo$1 (args) {
const pages = getCurrentPages();
if (pages.length) {
UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
}
return {}
}
var require_context_module_1_7 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1
var nvueApi = /*#__PURE__*/Object.freeze({
createLivePusherContext: createLivePusherContext,
createMapContext: createMapContext$1,
createVideoContext: createVideoContext$1,
requireNativePlugin: requireNativePlugin$1,
navigateBack: navigateBack$1,
navigateTo: navigateTo$1,
reLaunch: reLaunch$1,
redirectTo: redirectTo$1,
switchTab: switchTab$1
});
const api = Object.create(null);
const modules$1 =
(function() {
var map = {
'./base/base64.js': require_context_module_1_0,
'./base/can-i-use.js': require_context_module_1_1,
'./base/interceptor.js': require_context_module_1_2,
'./base/upx2px.js': require_context_module_1_3,
'./device/accelerometer.js': require_context_module_1_4,
'./network/request.js': require_context_module_1_5,
'./storage/storage.js': require_context_module_1_6,
'./ui/page-scroll-to.js': require_context_module_1_7,
};
var req = function req(key) {
return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
};
req.keys = function() {
return Object.keys(map);
};
return req;
})();
modules$1.keys().forEach(function (key) {
Object.assign(api, modules$1(key));
});
var platformApi = Object.assign(Object.create(null), appApi, nvueApi);
var api$1 = Object.assign(Object.create(null), api, platformApi);
var api$2 = Object.assign(Object.create(null), api$1, platformApi);
const uni$1 = Object.create(null);
apis_1.forEach(name => {
if (api$1[name]) {
uni$1[name] = promisify(name, wrapper(name, api$1[name]));
if (api$2[name]) {
uni$1[name] = promisify(name, wrapper(name, api$2[name]));
} else {
uni$1[name] = wrapperUnimplemented(name);
}
......
因为 它太大了无法显示 source diff 。你可以改为 查看blob
......@@ -406,6 +406,22 @@
"/platforms/h5/service/api/device/vibrate.js",
[]
],
"onBluetoothDeviceFound": [
"/core/service/api/device/bluetooth.js",
[]
],
"onBluetoothAdapterStateChange": [
"/core/service/api/device/bluetooth.js",
[]
],
"onBLEConnectionStateChange": [
"/core/service/api/device/bluetooth.js",
[]
],
"onBLECharacteristicValueChange": [
"/core/service/api/device/bluetooth.js",
[]
],
"hideKeyboard": [
"/platforms/h5/service/api/device/hide-keyboard.js",
[]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册