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

refactor app api

上级 60e8e2e2
......@@ -5,24 +5,28 @@ const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const requireContext = require('./rollup-plugin-require-context')
let input = 'src/platforms/app-plus/service/uni/create-instance-context.js'
let input = 'src/platforms/app-plus/service/framework/create-instance-context.js'
const output = {
file: 'packages/uni-app-plus-nvue/dist/index.js',
format: 'es'
}
const external = []
if (process.env.UNI_SERVICE === 'legacy') {
input = 'src/platforms/app-plus-nvue/service/index.legacy.js'
input = 'src/platforms/app-plus-nvue/services/index.legacy.js'
output.file = 'packages/uni-app-plus-nvue/dist/index.legacy.js'
} else if (process.env.UNI_SERVICE === 'uni') {
input = 'src/platforms/app-plus/service/uni/index.js'
input = 'src/platforms/app-plus/service/uni.js'
output.file = 'packages/uni-app-plus-nvue/dist/uni.js'
output.banner =
`export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge, getApp, getCurrentPages){
`export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, __registerPage, UniServiceJSBridge, getApp, getCurrentPages){
var localStorage = plus.storage
`
output.footer = '\n return uni$1 \n}'
} else {
external.push('./uni')
}
module.exports = {
......@@ -34,16 +38,16 @@ module.exports = {
requireContext(),
alias({
'uni-core': path.resolve(__dirname, '../src/core'),
'uni-platform': path.resolve(__dirname, '../src/platforms/' + process.env.UNI_PLATFORM),
'uni-platform': path.resolve(__dirname, '../src/platforms/app-plus'),
'uni-platforms': path.resolve(__dirname, '../src/platforms'),
'uni-shared': path.resolve(__dirname, '../src/shared/util.js'),
'uni-helpers': path.resolve(__dirname, '../src/core/helpers')
}),
replace({
__GLOBAL__: 'getGlobalUni()',
__PLATFORM__: JSON.stringify(process.env.UNI_PLATFORM),
__PLATFORM__: JSON.stringify('app-plus'),
__PLATFORM_TITLE__: 'app-plus-nvue'
})
],
external: ['./uni']
external
}
......@@ -6,8 +6,8 @@
"dev:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=true UNI_PLATFORM=h5 node build/build.js",
"build:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=false UNI_PLATFORM=h5 node build/build.js",
"build:app-plus": "cross-env UNI_PLATFORM=app-plus rollup -c build/rollup.config.mp.js",
"build:app:all": "npm run lint && npm run build:app && npm run build:app:nvue && npm run build:app:legacy",
"build:app": "UNI_PLATFORM=app-plus-nvue UNI_SERVICE=uni rollup -c build/rollup.config.app.js",
"build:app:all": "npm run lint && npm run build:app:uni && npm run build:app:nvue && npm run build:app:legacy",
"build:app:uni": "UNI_PLATFORM=app-plus-nvue UNI_SERVICE=uni rollup -c build/rollup.config.app.js",
"build:app:nvue": "cross-env UNI_PLATFORM=app-plus-nvue rollup -c build/rollup.config.app.js",
"build:app:legacy": "cross-env UNI_PLATFORM=app-plus-nvue UNI_SERVICE=legacy rollup -c build/rollup.config.app.js",
"build:mp-qq": "cross-env UNI_PLATFORM=mp-qq rollup -c build/rollup.config.mp.js",
......@@ -85,6 +85,7 @@
"swan": true,
"__uniConfig": true,
"__uniRoutes": true,
"__registerPage": true,
"UniViewJSBridge": true,
"UniServiceJSBridge": true,
"__PLATFORM__": true,
......
......@@ -18,132 +18,6 @@ function callPageHook (vm, hook, params) {
return callHook(vm, hook, params)
}
const ANI_DURATION = 300;
const ANI_SHOW = 'pop-in';
function showWebview (webview, animationType, animationDuration) {
setTimeout(() => {
webview.show(
animationType || ANI_SHOW,
animationDuration || ANI_DURATION,
() => {
console.log('show.callback');
}
);
}, 50);
}
let firstBackTime = 0;
function navigateBack ({
delta,
animationType,
animationDuration
}, {
plus,
getCurrentPages
}, callback) {
const pages = getCurrentPages();
const len = pages.length - 1;
const page = pages[len];
if (page.$page.meta.isQuit) {
if (!firstBackTime) {
firstBackTime = Date.now();
plus.nativeUI.toast('再按一次退出应用');
setTimeout(() => {
firstBackTime = null;
}, 2000);
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit();
}
} else {
pages.splice(len, 1);
if (animationType) {
page.$getAppWebview().close(animationType, animationDuration || ANI_DURATION);
} else {
page.$getAppWebview().close('auto');
}
callback && callback();
}
}
function navigateTo ({
path,
animationType,
animationDuration
}, {
__registerPage
}) {
showWebview(
__registerPage({
path
}),
animationType,
animationDuration
);
}
function reLaunch ({
path
}, instanceContext) {}
function redirectTo ({
path
}, instanceContext) {}
function switchTab ({
path
}, instanceContext) {}
const route = {
navigateBack,
navigateTo,
reLaunch,
redirectTo,
switchTab
};
class Router {
constructor (instanceContext) {
this.instanceContext = instanceContext;
this.$emit = instanceContext.UniServiceJSBridge.emit;
}
push ({
type,
path,
animationType,
animationDuration
} = {}) {
this.$emit('onAppRoute', {
type,
path
});
route[type]({
path,
animationType,
animationDuration
}, this.instanceContext);
}
go (delta, {
animationType,
animationDuration
} = {}) {
delta = Math.abs(parseInt(delta) || 1);
route.navigateBack({
delta,
animationType,
animationDuration
}, this.instanceContext, () => {
this.$emit('onAppRoute', {
type: 'navigateBack'
});
});
}
}
let appCtx;
const NETWORK_TYPES = [
......@@ -161,13 +35,14 @@ function getApp () {
}
function initGlobalListeners ({
uni,
plus,
UniServiceJSBridge
}) {
const emit = UniServiceJSBridge.emit;
plus.key.addEventListener('backbutton', () => {
appCtx.$router.go(-1);
uni.navigateBack();
});
plus.globalEvent.addEventListener('pause', () => {
......@@ -207,8 +82,6 @@ function registerApp (appVm, instanceContext) {
appCtx = appVm;
appCtx.$router = new Router(instanceContext);
initAppLaunch(appVm, instanceContext);
initGlobalListeners(instanceContext);
......@@ -445,39 +318,6 @@ function initWebview (webview, instanceContext, routeOptions) {
return webview
}
function createHolder (webview, {
navigationBar
}, {
Vue
}) {
const navigationBarState = Vue.observable(navigationBar);
/* eslint-disable no-new */
new Vue({
created () {
this.$watch(() => navigationBarState.titleText, (val, oldVal) => {
webview.setStyle({
titleNView: {
titleText: val || ''
}
});
});
this.$watch(() => [navigationBarState.textColor, navigationBarState.backgroundColor], (val) => {
webview.setStyle({
titleNView: {
titleColor: val[0],
backgroundColor: val[1]
}
});
});
}
});
return {
navigationBar: navigationBarState
}
}
const pages = [];
function getCurrentPages () {
......@@ -531,10 +371,7 @@ function registerPage ({
meta: routeOptions.meta,
path,
route
},
$holder: createHolder(webview, {
navigationBar: webview.$navigationBar
}, instanceContext)
}
});
return webview
......@@ -673,166 +510,6 @@ function initOn (on, {
on('onWebInvokeAppService', onWebInvokeAppService);
}
let waiting;
let waitingTimeout;
let toast = false;
let toastTimeout;
// 此处设计不对
function initPopup (on, {
plus
}) {
on('onShowToast', showToast);
on('onHideToast', hideToast);
on('onShowLoading', showToast);
on('onHideLoading', hideToast);
on('onShowModal', showModal);
on('onShowActionSheet', showActionSheet);
function showToast ({
title = '',
icon = 'success',
image = '',
duration = 1500,
mask = false,
position = ''
}) {
if (position) {
if (toast) {
toastTimeout && clearTimeout(toastTimeout);
plus.nativeUI.closeToast();
}
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout);
waiting.close();
}
if (~['top', 'center', 'bottom'].indexOf(position)) {
let richText = `<span>${title}</span>`;
plus.nativeUI.toast(richText, {
verticalAlign: position,
type: 'richtext'
});
toast = true;
toastTimeout = setTimeout(() => {
hideToast();
}, 2000);
return
}
console.warn('uni.showToast 传入的 "position" 值 "' + position + '" 无效');
}
if (duration) {
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout);
waiting.close();
}
if (toast) {
toastTimeout && clearTimeout(toastTimeout);
plus.nativeUI.closeToast();
}
if (icon && !~['success', 'loading', 'none'].indexOf(icon)) {
icon = 'success';
}
const waitingOptions = {
modal: mask,
back: 'transmit',
padding: '10px',
size: '16px' // 固定字体大小
};
if (!image && (!icon || icon === 'none')) { // 无图
// waitingOptions.width = '120px'
// waitingOptions.height = '40px'
waitingOptions.loading = {
display: 'none'
};
} else { // 有图
waitingOptions.width = '140px';
waitingOptions.height = '112px';
}
if (image) {
waitingOptions.loading = {
display: 'block',
height: '55px',
icon: image,
interval: duration
};
} else {
if (icon === 'success') {
waitingOptions.loading = {
display: 'block',
height: '55px',
icon: '__uniappsuccess.png',
interval: duration
};
}
}
waiting = plus.nativeUI.showWaiting(title, waitingOptions);
waitingTimeout = setTimeout(() => {
hideToast();
}, duration);
}
}
function hideToast () {
if (toast) {
toastTimeout && clearTimeout(toastTimeout);
plus.nativeUI.closeToast();
toast = false;
}
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout);
waiting.close();
waiting = null;
waitingTimeout = null;
}
}
function showModal ({
title = '',
content = '',
showCancel = true,
cancelText = '取消',
cancelColor = '#000000',
confirmText = '确定',
confirmColor = '#3CC51F'
}, callback) {
plus.nativeUI.confirm(content, (e) => {
if (showCancel) {
callback(e.index === 1 ? 'confirm' : 'cancel');
} else {
callback(e.index === 0 ? 'confirm' : 'cancel');
}
}, title, showCancel ? [cancelText, confirmText] : [confirmText]);
}
function showActionSheet ({
itemList = [],
itemColor = '#000000',
title = ''
}, callback) {
const options = {
buttons: itemList.map(item => ({
title: item
}))
};
if (title) {
options.title = title;
}
if (plus.os.name === 'iOS') {
options.cancel = '取消';
}
plus.nativeUI.actionSheet(options, (e) => {
if (e.index > 0) {
callback(e.index - 1);
} else {
callback(-1);
}
});
}
}
let bridge;
function initServiceJSBridge (Vue, instanceContext) {
......@@ -850,7 +527,6 @@ function initServiceJSBridge (Vue, instanceContext) {
};
initOn(bridge.on, instanceContext);
initPopup(bridge.on, instanceContext);
return bridge
}
......@@ -871,12 +547,17 @@ function createInstanceContext (instanceContext) {
getCurrentPages
});
function __registerPage (page) {
return registerPage(page, instanceContext)
}
if (!uni$1) {
uni$1 = createUniInstance(
weex,
plus,
uniConfig,
uniRoutes,
__registerPage,
UniServiceJSBridge,
getApp,
getCurrentPages
......@@ -892,9 +573,7 @@ function createInstanceContext (instanceContext) {
__registerApp (appVm) {
return registerApp(appVm, instanceContext)
},
__registerPage (page) {
return registerPage(page, instanceContext)
},
__registerPage,
plus,
uni: uni$1,
getApp,
......
export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge, getApp, getCurrentPages){
export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, __registerPage, UniServiceJSBridge, getApp, getCurrentPages){
var localStorage = plus.storage
const ANI_DURATION = 300;
const ANI_SHOW = 'pop-in';
function showWebview (webview, animationType, animationDuration) {
setTimeout(() => {
webview.show(
animationType || ANI_SHOW,
animationDuration || ANI_DURATION,
() => {
console.log('show.callback');
}
);
}, 50);
}
var require_context_module_0_5 = /*#__PURE__*/Object.freeze({
ANI_DURATION: ANI_DURATION,
showWebview: showWebview
});
let firstBackTime = 0;
function navigateBack ({
delta,
animationType,
animationDuration
}) {
const pages = getCurrentPages();
const len = pages.length - 1;
const page = pages[len];
if (page.$page.meta.isQuit) {
if (!firstBackTime) {
firstBackTime = Date.now();
plus.nativeUI.toast('再按一次退出应用');
setTimeout(() => {
firstBackTime = null;
}, 2000);
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit();
}
} else {
pages.splice(len, 1);
if (animationType) {
page.$getAppWebview().close(animationType, animationDuration || ANI_DURATION);
} else {
page.$getAppWebview().close('auto');
}
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateBack'
});
}
}
var require_context_module_0_0 = /*#__PURE__*/Object.freeze({
navigateBack: navigateBack
});
function navigateTo ({
url,
animationType,
animationDuration
}) {
const path = url.split('?')[0];
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
path
});
showWebview(
__registerPage({
path
}),
animationType,
animationDuration
);
}
var require_context_module_0_1 = /*#__PURE__*/Object.freeze({
navigateTo: navigateTo
});
function reLaunch ({
path
}) {}
var require_context_module_0_2 = /*#__PURE__*/Object.freeze({
reLaunch: reLaunch
});
function redirectTo ({
path
}) {}
var require_context_module_0_3 = /*#__PURE__*/Object.freeze({
redirectTo: redirectTo
});
function switchTab ({
path
}) {}
var require_context_module_0_4 = /*#__PURE__*/Object.freeze({
switchTab: switchTab
});
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var base64Arraybuffer = createCommonjsModule(function (module, exports) {
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(){
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Use a lookup table to find the index.
var lookup = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i+1)];
encoded3 = lookup[base64.charCodeAt(i+2)];
encoded4 = lookup[base64.charCodeAt(i+3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})();
});
var base64Arraybuffer_1 = base64Arraybuffer.encode;
var base64Arraybuffer_2 = base64Arraybuffer.decode;
const base64ToArrayBuffer = base64Arraybuffer_2;
const arrayBufferToBase64 = base64Arraybuffer_1;
var require_context_module_1_0 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer,
arrayBufferToBase64: arrayBufferToBase64
});
const _toString = Object.prototype.toString;
const hasOwnProperty = Object.prototype.hasOwnProperty;
......@@ -25,33 +214,21 @@ function getLen (str = '') {
return ('' + str).replace(/[^\x00-\xff]/g, '**').length
}
/**
* 框架内 try-catch
*/
function tryCatchFramework (fn) {
return function () {
try {
return fn.apply(fn, arguments)
} catch (e) {
// TODO
console.error(e);
}
}
}
/**
* 开发者 try-catch
*/
function tryCatch (fn) {
return function () {
try {
return fn.apply(fn, arguments)
} catch (e) {
// TODO
console.error(e);
}
var platformSchema = {};
// TODO 待处理其他 API 的检测
function canIUse (schema) {
if (hasOwn(platformSchema, schema)) {
return platformSchema[schema]
}
return true
}
var require_context_module_1_1 = /*#__PURE__*/Object.freeze({
canIUse: canIUse
});
const HOOKS = [
'invoke',
'success',
......@@ -242,102 +419,559 @@ const promiseInterceptor = {
}
};
const SYNC_API_RE =
/^\$|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
const CONTEXT_API_RE = /^create|Manager$/;
const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket'];
const CALLBACK_API_RE = /^on/;
const interceptors = {
promiseInterceptor
};
function isContextApi (name) {
return CONTEXT_API_RE.test(name)
}
function isSyncApi (name) {
return SYNC_API_RE.test(name)
}
var require_context_module_1_2 = /*#__PURE__*/Object.freeze({
interceptors: interceptors,
addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor
});
function isCallbackApi (name) {
return CALLBACK_API_RE.test(name)
function pageScrollTo (args) {
const pages = getCurrentPages();
if (pages.length) {
UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
}
return {}
}
function isTaskApi (name) {
return TASK_APIS.indexOf(name) !== -1
}
let pageId;
function handlePromise (promise) {
return promise.then(data => {
return [null, data]
})
.catch(err => [err])
function setPullDownRefreshPageId (pullDownRefreshPageId) {
pageId = pullDownRefreshPageId;
}
function shouldPromise (name) {
if (
isContextApi(name) ||
isSyncApi(name) ||
isCallbackApi(name)
) {
return false
function startPullDownRefresh () {
if (pageId) {
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
}
return true
const pages = getCurrentPages();
if (pages.length) {
pageId = pages[pages.length - 1].$page.id;
UniServiceJSBridge.emit(pageId + '.startPullDownRefresh', {}, pageId);
}
return {}
}
function promisify (name, api) {
if (!shouldPromise(name)) {
return api
}
return function promiseApi (options = {}, ...params) {
if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
}
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, {
success: resolve,
fail: reject
}), ...params);
/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
Promise.prototype.finally = function (callback) {
const promise = this.constructor;
return this.then(
value => promise.resolve(callback()).then(() => value),
reason => promise.resolve(callback()).then(() => {
throw reason
})
)
};
function stopPullDownRefresh () {
if (pageId) {
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
pageId = null;
} else {
const pages = getCurrentPages();
if (pages.length) {
pageId = pages[pages.length - 1].$page.id;
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
}
})))
}
return {}
}
const canIUse = [{
name: 'schema',
type: String,
required: true
}];
var require_context_module_1_0 = /*#__PURE__*/Object.freeze({
canIUse: canIUse
var require_context_module_1_3 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo,
setPullDownRefreshPageId: setPullDownRefreshPageId,
startPullDownRefresh: startPullDownRefresh,
stopPullDownRefresh: stopPullDownRefresh
});
function setStorage ({
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 (key, data) {
setStorage({
key,
data
});
}
function getStorage ({
key
} = {}) {
const data = localStorage.getItem(key);
return data ? {
data: JSON.parse(data).data,
errMsg: 'getStorage:ok'
} : {
data: '',
errMsg: 'getStorage:fail'
}
}
function getStorageSync (key) {
const res = getStorage({
key
});
return res.data
}
function removeStorage ({
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 (key) {
removeStorage({
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_4 = /*#__PURE__*/Object.freeze({
setStorage: setStorage,
setStorageSync: setStorageSync,
getStorage: getStorage,
getStorageSync: getStorageSync,
removeStorage: removeStorage,
removeStorageSync: removeStorageSync,
clearStorage: clearStorage,
clearStorageSync: clearStorageSync,
getStorageInfo: getStorageInfo,
getStorageInfoSync: getStorageInfoSync
});
const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS = false;
let deviceWidth = 0;
let deviceDPR = 0;
function checkDeviceWidth () {
const {
platform,
pixelRatio,
windowWidth
} = uni.getSystemInfoSync();
deviceWidth = windowWidth;
deviceDPR = pixelRatio;
isIOS = platform === 'ios';
}
function upx2px (number, newDeviceWidth) {
if (deviceWidth === 0) {
checkDeviceWidth();
}
number = Number(number);
if (number === 0) {
return 0
}
let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
if (result < 0) {
result = -result;
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS) {
return 1
} else {
return 0.5
}
}
return number < 0 ? -result : result
}
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
upx2px: upx2px
});
const base = [
'base64ToArrayBuffer',
'arrayBufferToBase64'
];
const network = [
'request',
'uploadFile',
'downloadFile',
'connectSocket',
'onSocketOpen',
'onSocketError',
'sendSocketMessage',
'onSocketMessage',
'closeSocket',
'onSocketClose'
];
const route = [
'navigateTo',
'redirectTo',
'reLaunch',
'switchTab',
'navigateBack'
];
const storage = [
'setStorage',
'setStorageSync',
'getStorage',
'getStorageSync',
'getStorageInfo',
'getStorageInfoSync',
'removeStorage',
'removeStorageSync',
'clearStorage',
'clearStorageSync'
];
const location = [
'getLocation',
'chooseLocation',
'openLocation',
'createMapContext'
];
const media = [
'chooseImage',
'previewImage',
'getImageInfo',
'saveImageToPhotosAlbum',
'compressImage',
'chooseMessageFile',
'getRecorderManager',
'getBackgroundAudioManager',
'createInnerAudioContext',
'chooseVideo',
'saveVideoToPhotosAlbum',
'createVideoContext',
'createCameraContext',
'createLivePlayerContext'
];
const device = [
'getSystemInfo',
'getSystemInfoSync',
'canIUse',
'onMemoryWarning',
'getNetworkType',
'onNetworkStatusChange',
'onAccelerometerChange',
'startAccelerometer',
'stopAccelerometer',
'onCompassChange',
'startCompass',
'stopCompass',
'onGyroscopeChange',
'startGyroscope',
'stopGyroscope',
'makePhoneCall',
'scanCode',
'setClipboardData',
'getClipboardData',
'setScreenBrightness',
'getScreenBrightness',
'setKeepScreenOn',
'onUserCaptureScreen',
'vibrateLong',
'vibrateShort',
'addPhoneContact',
'openBluetoothAdapter',
'startBluetoothDevicesDiscovery',
'onBluetoothDeviceFound',
'stopBluetoothDevicesDiscovery',
'onBluetoothAdapterStateChange',
'getConnectedBluetoothDevices',
'getBluetoothDevices',
'getBluetoothAdapterState',
'closeBluetoothAdapter',
'writeBLECharacteristicValue',
'readBLECharacteristicValue',
'onBLEConnectionStateChange',
'onBLECharacteristicValueChange',
'notifyBLECharacteristicValueChange',
'getBLEDeviceServices',
'getBLEDeviceCharacteristics',
'createBLEConnection',
'closeBLEConnection',
'onBeaconServiceChange',
'onBeaconUpdate',
'getBeacons',
'startBeaconDiscovery',
'stopBeaconDiscovery'
];
const keyboard = [
'hideKeyboard'
];
const ui = [
'showToast',
'hideToast',
'showLoading',
'hideLoading',
'showModal',
'showActionSheet',
'setNavigationBarTitle',
'setNavigationBarColor',
'showNavigationBarLoading',
'hideNavigationBarLoading',
'setTabBarItem',
'setTabBarStyle',
'hideTabBar',
'showTabBar',
'setTabBarBadge',
'removeTabBarBadge',
'showTabBarRedDot',
'hideTabBarRedDot',
'setBackgroundColor',
'setBackgroundTextStyle',
'createAnimation',
'pageScrollTo',
'onWindowResize',
'offWindowResize',
'loadFontFace',
'startPullDownRefresh',
'stopPullDownRefresh',
'createSelectorQuery',
'createIntersectionObserver'
];
const event = [
'$emit',
'$on',
'$once',
'$off'
];
const file = [
'saveFile',
'getSavedFileList',
'getSavedFileInfo',
'removeSavedFile',
'getFileInfo',
'openDocument',
'getFileSystemManager'
];
const canvas = [
'createOffscreenCanvas',
'createCanvasContext',
'canvasToTempFilePath',
'canvasPutImageData',
'canvasGetImageData'
];
const third = [
'getProvider',
'login',
'checkSession',
'getUserInfo',
'share',
'showShareMenu',
'hideShareMenu',
'requestPayment',
'subscribePush',
'unsubscribePush',
'onPush',
'offPush',
'requireNativePlugin',
'upx2px'
];
const apis = [
...base,
...network,
...route,
...storage,
...location,
...media,
...device,
...keyboard,
...ui,
...event,
...file,
...canvas,
...third
];
/**
* 框架内 try-catch
*/
function tryCatchFramework (fn) {
return function () {
try {
return fn.apply(fn, arguments)
} catch (e) {
// TODO
console.error(e);
}
}
}
/**
* 开发者 try-catch
*/
function tryCatch (fn) {
return function () {
try {
return fn.apply(fn, arguments)
} catch (e) {
// TODO
console.error(e);
}
}
}
const SYNC_API_RE =
/^\$|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
const CONTEXT_API_RE = /^create|Manager$/;
const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket'];
const CALLBACK_API_RE = /^on/;
function isContextApi (name) {
return CONTEXT_API_RE.test(name)
}
function isSyncApi (name) {
return SYNC_API_RE.test(name)
}
function isCallbackApi (name) {
return CALLBACK_API_RE.test(name)
}
function isTaskApi (name) {
return TASK_APIS.indexOf(name) !== -1
}
function handlePromise (promise) {
return promise.then(data => {
return [null, data]
})
.catch(err => [err])
}
function shouldPromise (name) {
if (
isContextApi(name) ||
isSyncApi(name) ||
isCallbackApi(name)
) {
return false
}
return true
}
function promisify (name, api) {
if (!shouldPromise(name)) {
return api
}
return function promiseApi (options = {}, ...params) {
if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
}
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, {
success: resolve,
fail: reject
}), ...params);
/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
Promise.prototype.finally = function (callback) {
const promise = this.constructor;
return this.then(
value => promise.resolve(callback()).then(() => value),
reason => promise.resolve(callback()).then(() => {
throw reason
})
)
};
}
})))
}
}
const canIUse$1 = [{
name: 'schema',
type: String,
required: true
}];
var require_context_module_2_0 = /*#__PURE__*/Object.freeze({
canIUse: canIUse$1
});
const base64ToArrayBuffer = [{
const base64ToArrayBuffer$1 = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64 = [{
const arrayBufferToBase64$1 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}];
var require_context_module_1_1 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer,
arrayBufferToBase64: arrayBufferToBase64
var require_context_module_2_1 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer$1,
arrayBufferToBase64: arrayBufferToBase64$1
});
function getInt (method) {
......@@ -472,7 +1106,7 @@ const drawCanvas = {
}
};
var require_context_module_1_2 = /*#__PURE__*/Object.freeze({
var require_context_module_2_2 = /*#__PURE__*/Object.freeze({
canvasGetImageData: canvasGetImageData,
canvasPutImageData: canvasPutImageData,
canvasToTempFilePath: canvasToTempFilePath,
......@@ -497,7 +1131,7 @@ const createCanvasContext = [{
type: Object
}];
var require_context_module_1_3 = /*#__PURE__*/Object.freeze({
var require_context_module_2_3 = /*#__PURE__*/Object.freeze({
createAudioContext: createAudioContext,
createVideoContext: createVideoContext,
createMapContext: createMapContext,
......@@ -516,7 +1150,7 @@ const makePhoneCall = {
}
};
var require_context_module_1_4 = /*#__PURE__*/Object.freeze({
var require_context_module_2_4 = /*#__PURE__*/Object.freeze({
makePhoneCall: makePhoneCall
});
......@@ -530,7 +1164,7 @@ const openDocument = {
}
};
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
var require_context_module_2_5 = /*#__PURE__*/Object.freeze({
openDocument: openDocument
});
......@@ -577,7 +1211,7 @@ const openLocation = {
}
};
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
var require_context_module_2_6 = /*#__PURE__*/Object.freeze({
getLocation: getLocation,
openLocation: openLocation
});
......@@ -635,7 +1269,7 @@ const chooseImage = {
}
};
var require_context_module_1_7 = /*#__PURE__*/Object.freeze({
var require_context_module_2_7 = /*#__PURE__*/Object.freeze({
chooseImage: chooseImage
});
......@@ -662,7 +1296,7 @@ const chooseVideo = {
}
};
var require_context_module_1_8 = /*#__PURE__*/Object.freeze({
var require_context_module_2_8 = /*#__PURE__*/Object.freeze({
chooseVideo: chooseVideo
});
......@@ -737,7 +1371,7 @@ const getImageInfo = {
}
};
var require_context_module_1_9 = /*#__PURE__*/Object.freeze({
var require_context_module_2_9 = /*#__PURE__*/Object.freeze({
getImageInfo: getImageInfo
});
......@@ -772,7 +1406,7 @@ const previewImage = {
}
};
var require_context_module_1_10 = /*#__PURE__*/Object.freeze({
var require_context_module_2_10 = /*#__PURE__*/Object.freeze({
previewImage: previewImage
});
......@@ -814,7 +1448,7 @@ const setNavigationBarTitle = {
}
};
var require_context_module_1_11 = /*#__PURE__*/Object.freeze({
var require_context_module_2_11 = /*#__PURE__*/Object.freeze({
setNavigationBarColor: setNavigationBarColor,
setNavigationBarTitle: setNavigationBarTitle
});
......@@ -832,7 +1466,7 @@ const downloadFile = {
}
};
var require_context_module_1_12 = /*#__PURE__*/Object.freeze({
var require_context_module_2_12 = /*#__PURE__*/Object.freeze({
downloadFile: downloadFile
});
......@@ -892,7 +1526,7 @@ const request = {
}
};
var require_context_module_1_13 = /*#__PURE__*/Object.freeze({
var require_context_module_2_13 = /*#__PURE__*/Object.freeze({
request: request
});
......@@ -945,7 +1579,7 @@ const closeSocket = {
}
};
var require_context_module_1_14 = /*#__PURE__*/Object.freeze({
var require_context_module_2_14 = /*#__PURE__*/Object.freeze({
connectSocket: connectSocket,
sendSocketMessage: sendSocketMessage,
closeSocket: closeSocket
......@@ -981,11 +1615,11 @@ const uploadFile = {
}
};
var require_context_module_1_15 = /*#__PURE__*/Object.freeze({
var require_context_module_2_15 = /*#__PURE__*/Object.freeze({
uploadFile: uploadFile
});
const pageScrollTo = {
const pageScrollTo$1 = {
scrollTop: {
type: Number,
required: true
......@@ -999,8 +1633,8 @@ const pageScrollTo = {
}
};
var require_context_module_1_16 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo
var require_context_module_2_16 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1
});
const service = {
......@@ -1023,7 +1657,7 @@ const getProvider = {
}
};
var require_context_module_1_17 = /*#__PURE__*/Object.freeze({
var require_context_module_2_17 = /*#__PURE__*/Object.freeze({
getProvider: getProvider
});
......@@ -1140,7 +1774,7 @@ const showActionSheet = {
}
};
var require_context_module_1_18 = /*#__PURE__*/Object.freeze({
var require_context_module_2_18 = /*#__PURE__*/Object.freeze({
showModal: showModal,
showToast: showToast,
showLoading: showLoading,
......@@ -1249,11 +1883,11 @@ function createAnimationProtocol (animationTypes) {
}
}
const redirectTo = createProtocol('redirectTo');
const redirectTo$1 = createProtocol('redirectTo');
const reLaunch = createProtocol('reLaunch');
const reLaunch$1 = createProtocol('reLaunch');
const navigateTo = createProtocol('navigateTo', createAnimationProtocol(
const navigateTo$1 = createProtocol('navigateTo', createAnimationProtocol(
[
'slide-in-right',
'slide-in-left',
......@@ -1267,9 +1901,9 @@ const navigateTo = createProtocol('navigateTo', createAnimationProtocol(
]
));
const switchTab = createProtocol('switchTab');
const switchTab$1 = createProtocol('switchTab');
const navigateBack = Object.assign({
const navigateBack$1 = Object.assign({
delta: {
type: Number,
validator (delta, params) {
......@@ -1291,15 +1925,15 @@ const navigateBack = Object.assign({
]
));
var require_context_module_1_19 = /*#__PURE__*/Object.freeze({
redirectTo: redirectTo,
reLaunch: reLaunch,
navigateTo: navigateTo,
switchTab: switchTab,
navigateBack: navigateBack
var require_context_module_2_19 = /*#__PURE__*/Object.freeze({
redirectTo: redirectTo$1,
reLaunch: reLaunch$1,
navigateTo: navigateTo$1,
switchTab: switchTab$1,
navigateBack: navigateBack$1
});
const setStorage = {
const setStorage$1 = {
'key': {
type: String,
required: true
......@@ -1309,7 +1943,7 @@ const setStorage = {
}
};
const setStorageSync = [{
const setStorageSync$1 = [{
name: 'key',
type: String,
required: true
......@@ -1318,9 +1952,9 @@ const setStorageSync = [{
required: true
}];
var require_context_module_1_20 = /*#__PURE__*/Object.freeze({
setStorage: setStorage,
setStorageSync: setStorageSync
var require_context_module_2_20 = /*#__PURE__*/Object.freeze({
setStorage: setStorage$1,
setStorageSync: setStorageSync$1
});
const indexValidator = {
......@@ -1400,7 +2034,7 @@ const setTabBarBadge = {
}
};
var require_context_module_1_21 = /*#__PURE__*/Object.freeze({
var require_context_module_2_21 = /*#__PURE__*/Object.freeze({
setTabBarItem: setTabBarItem,
setTabBarStyle: setTabBarStyle,
hideTabBar: hideTabBar,
......@@ -1415,28 +2049,28 @@ const protocol = Object.create(null);
const modules =
(function() {
var map = {
'./base.js': require_context_module_1_0,
'./base64.js': require_context_module_1_1,
'./canvas.js': require_context_module_1_2,
'./context.js': require_context_module_1_3,
'./device/make-phone-call.js': require_context_module_1_4,
'./file/open-document.js': require_context_module_1_5,
'./location.js': require_context_module_1_6,
'./media/choose-image.js': require_context_module_1_7,
'./media/choose-video.js': require_context_module_1_8,
'./media/get-image-info.js': require_context_module_1_9,
'./media/preview-image.js': require_context_module_1_10,
'./navigation-bar.js': require_context_module_1_11,
'./network/download-file.js': require_context_module_1_12,
'./network/request.js': require_context_module_1_13,
'./network/socket.js': require_context_module_1_14,
'./network/upload-file.js': require_context_module_1_15,
'./page-scroll-to.js': require_context_module_1_16,
'./plugins.js': require_context_module_1_17,
'./popup.js': require_context_module_1_18,
'./route.js': require_context_module_1_19,
'./storage.js': require_context_module_1_20,
'./tab-bar.js': require_context_module_1_21,
'./base.js': require_context_module_2_0,
'./base64.js': require_context_module_2_1,
'./canvas.js': require_context_module_2_2,
'./context.js': require_context_module_2_3,
'./device/make-phone-call.js': require_context_module_2_4,
'./file/open-document.js': require_context_module_2_5,
'./location.js': require_context_module_2_6,
'./media/choose-image.js': require_context_module_2_7,
'./media/choose-video.js': require_context_module_2_8,
'./media/get-image-info.js': require_context_module_2_9,
'./media/preview-image.js': require_context_module_2_10,
'./navigation-bar.js': require_context_module_2_11,
'./network/download-file.js': require_context_module_2_12,
'./network/request.js': require_context_module_2_13,
'./network/socket.js': require_context_module_2_14,
'./network/upload-file.js': require_context_module_2_15,
'./page-scroll-to.js': require_context_module_2_16,
'./plugins.js': require_context_module_2_17,
'./popup.js': require_context_module_2_18,
'./route.js': require_context_module_2_19,
'./storage.js': require_context_module_2_20,
'./tab-bar.js': require_context_module_2_21,
};
var req = function req(key) {
......@@ -1754,441 +2388,127 @@ function createApiCallback (apiName, params = {}, extras = {}) {
hasFail && fail(res);
isFn(beforeCancel) && beforeCancel(res);
hasCancel && cancel(res);
isFn(afterCancel) && afterCancel(res);
} else if (errMsg.indexOf(apiName + ':fail') === 0) {
isFn(beforeFail) && beforeFail(res);
hasFail && fail(res);
isFn(afterFail) && afterFail(res);
}
hasComplete && complete(res);
isFn(afterAll) && afterAll(res);
};
invokeCallbacks[callbackId] = {
name: invokeCallbackName,
callback: invokeCallback
};
return {
params,
callbackId
}
}
function createInvokeCallback (apiName, params = {}, extras = {}) {
const {
params: args,
callbackId
} = createApiCallback(apiName, params, extras);
if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
return {
params: args,
callbackId: false
}
}
return {
params: args,
callbackId
}
}
function invokeCallbackHandler (invokeCallbackId, res) {
if (typeof invokeCallbackId === 'number') {
const invokeCallback = invokeCallbacks[invokeCallbackId];
if (invokeCallback) {
if (!invokeCallback.keepAlive) {
delete invokeCallbacks[invokeCallbackId];
}
return invokeCallback.callback(res)
}
}
return res
}
function wrapper (name, invokeMethod, extras) {
if (!isFn(invokeMethod)) {
return invokeMethod
}
return function (...args) {
if (isSyncApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod.apply(null, args)
}
} else if (isCallbackApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod(createKeepAliveApiCallback(name, args[0]))
}
} else {
let argsObj = {};
if (args.length) {
argsObj = args[0];
}
const {
params,
callbackId
} = createInvokeCallback(name, argsObj, extras);
if (callbackId !== false) {
let res;
if (isFn(params)) {
res = invokeMethod(callbackId);
} else {
res = invokeMethod(params, callbackId);
}
if (res && !isTaskApi(name)) {
res = invokeCallbackHandler(callbackId, res);
if (isPlainObject(res)) {
res.errMsg = res.errMsg || name + ':ok';
}
}
return res
}
}
}
}
UniServiceJSBridge.publishHandler = UniServiceJSBridge.emit;
UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var base64Arraybuffer = createCommonjsModule(function (module, exports) {
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(){
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Use a lookup table to find the index.
var lookup = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i+1)];
encoded3 = lookup[base64.charCodeAt(i+2)];
encoded4 = lookup[base64.charCodeAt(i+3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})();
});
var base64Arraybuffer_1 = base64Arraybuffer.encode;
var base64Arraybuffer_2 = base64Arraybuffer.decode;
const base64ToArrayBuffer$1 = base64Arraybuffer_2;
const arrayBufferToBase64$1 = base64Arraybuffer_1;
var require_context_module_0_0 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer$1,
arrayBufferToBase64: arrayBufferToBase64$1
});
var platformSchema = {};
// TODO 待处理其他 API 的检测
function canIUse$1 (schema) {
if (hasOwn(platformSchema, schema)) {
return platformSchema[schema]
}
return true
}
var require_context_module_0_1 = /*#__PURE__*/Object.freeze({
canIUse: canIUse$1
});
const interceptors = {
promiseInterceptor
};
var require_context_module_0_2 = /*#__PURE__*/Object.freeze({
interceptors: interceptors,
addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor
});
function pageScrollTo$1 (args) {
const pages = getCurrentPages();
if (pages.length) {
UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
}
return {}
}
let pageId;
isFn(beforeCancel) && beforeCancel(res);
function setPullDownRefreshPageId (pullDownRefreshPageId) {
pageId = pullDownRefreshPageId;
}
hasCancel && cancel(res);
function startPullDownRefresh () {
if (pageId) {
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
}
const pages = getCurrentPages();
if (pages.length) {
pageId = pages[pages.length - 1].$page.id;
UniServiceJSBridge.emit(pageId + '.startPullDownRefresh', {}, pageId);
}
return {}
}
isFn(afterCancel) && afterCancel(res);
} else if (errMsg.indexOf(apiName + ':fail') === 0) {
isFn(beforeFail) && beforeFail(res);
function stopPullDownRefresh () {
if (pageId) {
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
pageId = null;
} else {
const pages = getCurrentPages();
if (pages.length) {
pageId = pages[pages.length - 1].$page.id;
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
}
hasFail && fail(res);
isFn(afterFail) && afterFail(res);
}
return {}
}
var require_context_module_0_3 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1,
setPullDownRefreshPageId: setPullDownRefreshPageId,
startPullDownRefresh: startPullDownRefresh,
stopPullDownRefresh: stopPullDownRefresh
});
hasComplete && complete(res);
function setStorage$1 ({
key,
data
} = {}) {
const value = {
type: typeof data === 'object' ? 'object' : 'string',
data: data
isFn(afterAll) && afterAll(res);
};
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
});
}
invokeCallbacks[callbackId] = {
name: invokeCallbackName,
callback: invokeCallback
};
function getStorage ({
key
} = {}) {
const data = localStorage.getItem(key);
return data ? {
data: JSON.parse(data).data,
errMsg: 'getStorage:ok'
} : {
data: '',
errMsg: 'getStorage:fail'
return {
params,
callbackId
}
}
function getStorageSync (key) {
const res = getStorage({
key
});
return res.data
}
function createInvokeCallback (apiName, params = {}, extras = {}) {
const {
params: args,
callbackId
} = createApiCallback(apiName, params, extras);
function removeStorage ({
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);
if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
return {
errMsg: 'removeStorage:ok'
params: args,
callbackId: false
}
}
}
function removeStorageSync (key) {
removeStorage({
key
});
}
function clearStorage () {
localStorage.clear();
return {
errMsg: 'clearStorage:ok'
params: args,
callbackId
}
}
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 invokeCallbackHandler (invokeCallbackId, res) {
if (typeof invokeCallbackId === 'number') {
const invokeCallback = invokeCallbacks[invokeCallbackId];
if (invokeCallback) {
if (!invokeCallback.keepAlive) {
delete invokeCallbacks[invokeCallbackId];
}
return invokeCallback.callback(res)
}
}
}
function getStorageInfoSync () {
const res = getStorageInfo();
delete res.errMsg;
return res
}
var require_context_module_0_4 = /*#__PURE__*/Object.freeze({
setStorage: setStorage$1,
setStorageSync: setStorageSync$1,
getStorage: getStorage,
getStorageSync: getStorageSync,
removeStorage: removeStorage,
removeStorageSync: removeStorageSync,
clearStorage: clearStorage,
clearStorageSync: clearStorageSync,
getStorageInfo: getStorageInfo,
getStorageInfoSync: getStorageInfoSync
});
const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS = false;
let deviceWidth = 0;
let deviceDPR = 0;
function checkDeviceWidth () {
const {
platform,
pixelRatio,
windowWidth
} = uni.getSystemInfoSync();
deviceWidth = windowWidth;
deviceDPR = pixelRatio;
isIOS = platform === 'ios';
function wrapperUnimplemented (name) {
return function (args) {
console.error('API `' + name + '` is not yet implemented');
}
}
function upx2px (number, newDeviceWidth) {
if (deviceWidth === 0) {
checkDeviceWidth();
function wrapper (name, invokeMethod, extras) {
if (!isFn(invokeMethod)) {
return invokeMethod
}
number = Number(number);
if (number === 0) {
return 0
return function (...args) {
if (isSyncApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod.apply(null, args)
}
let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
if (result < 0) {
result = -result;
} else if (isCallbackApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod(createKeepAliveApiCallback(name, args[0]))
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS) {
return 1
} else {
return 0.5
let argsObj = {};
if (args.length) {
argsObj = args[0];
}
const {
params,
callbackId
} = createInvokeCallback(name, argsObj, extras);
if (callbackId !== false) {
let res;
if (isFn(params)) {
res = invokeMethod(callbackId);
} else {
res = invokeMethod(params, callbackId);
}
if (res && !isTaskApi(name)) {
res = invokeCallbackHandler(callbackId, res);
if (isPlainObject(res)) {
res.errMsg = res.errMsg || name + ':ok';
}
}
return res
}
}
}
return number < 0 ? -result : result
}
var require_context_module_0_5 = /*#__PURE__*/Object.freeze({
checkDeviceWidth: checkDeviceWidth,
upx2px: upx2px
});
const api = Object.create(null);
const modules$1 =
const uni$1 = Object.create(null);
const baseApis =
(function() {
var map = {
'./base64.js': require_context_module_0_0,
'./can-i-use.js': require_context_module_0_1,
'./interceptor.js': require_context_module_0_2,
'./page-event.js': require_context_module_0_3,
'./storage.js': require_context_module_0_4,
'./upx2px.js': require_context_module_0_5,
'./base64.js': require_context_module_1_0,
'./can-i-use.js': require_context_module_1_1,
'./interceptor.js': require_context_module_1_2,
'./page-event.js': require_context_module_1_3,
'./storage.js': require_context_module_1_4,
'./upx2px.js': require_context_module_1_5,
};
var req = function req(key) {
......@@ -2200,14 +2520,41 @@ const modules$1 =
return req;
})();
modules$1.keys().forEach(function (key) {
Object.assign(api, modules$1(key));
baseApis.keys().forEach(function (key) {
Object.assign(api, baseApis(key));
});
const uni$1 = Object.create(null);
const platformApis =
(function() {
var map = {
'./router/navigate-back.js': require_context_module_0_0,
'./router/navigate-to.js': require_context_module_0_1,
'./router/re-launch.js': require_context_module_0_2,
'./router/redirect-to.js': require_context_module_0_3,
'./router/switch-tab.js': require_context_module_0_4,
'./router/util.js': require_context_module_0_5,
};
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;
})();
Object.keys(api).forEach(name => {
platformApis.keys().forEach(function (key) {
Object.assign(api, platformApis(key));
});
apis.forEach(name => {
if (api[name]) {
uni$1[name] = promisify(name, wrapper(name, api[name]));
} else {
uni$1[name] = wrapperUnimplemented(name);
}
});
return uni$1
......
<meta charset="utf-8">
<title>index demo</title>
<script src="./index.umd.js"></script>
<link rel="stylesheet" href="./index.css">
<script>
console.log(index)
</script>
因为 它太大了无法显示 source diff 。你可以改为 查看blob
因为 它太大了无法显示 source diff 。你可以改为 查看blob
import Vue from 'vue'
import initOn from './on'
import initSubscribe from './subscribe'
const Emitter = new Vue()
export const on = Emitter.$on.bind(Emitter)
......@@ -31,10 +28,3 @@ export {
publishHandler
}
from 'uni-platform/service/bridge'
initOn(on, {
getApp: global.getApp,
getCurrentPages: global.getCurrentPages
})
initSubscribe(subscribe)
......@@ -4,7 +4,11 @@ import {
callPageHook
} from '../plugins/util'
function createPageEvent (eventType) {
export default function initSubscribe (subscribe, {
getApp,
getCurrentPages
}) {
function createPageEvent (eventType) {
return function (args, pageId) {
const pages = getCurrentPages()
const page = pages.find(page => page.$page.id === pageId)
......@@ -14,27 +18,27 @@ function createPageEvent (eventType) {
console.error(`Not Found:Page[${pageId}]`)
}
}
}
}
const requestComponentInfoCallbacks = createCallbacks('requestComponentInfo')
const requestComponentInfoCallbacks = createCallbacks('requestComponentInfo')
function onRequestComponentInfo ({
function onRequestComponentInfo ({
reqId,
res
}) {
}) {
const callback = requestComponentInfoCallbacks.pop(reqId)
if (callback) {
callback(res)
}
}
}
const requestComponentObserverCallbacks = createCallbacks('requestComponentObserver')
const requestComponentObserverCallbacks = createCallbacks('requestComponentObserver')
function onRequestComponentObserver ({
function onRequestComponentObserver ({
reqId,
reqEnd,
res
}) {
}) {
const callback = requestComponentObserverCallbacks.get(reqId)
if (callback) {
if (reqEnd) {
......@@ -43,9 +47,8 @@ function onRequestComponentObserver ({
}
callback(res)
}
}
}
export default function initSubscribe (subscribe) {
subscribe('onPageReady', createPageEvent('onReady'))
subscribe('onPageScroll', createPageEvent('onPageScroll'))
subscribe('onReachBottom', createPageEvent('onReachBottom'))
......
import apis from 'uni-helpers/apis'
import initOn from './bridge/on'
import initSubscribe from './bridge/subscribe'
import {
wrapper,
wrapperUnimplemented
} from 'uni-helpers/api'
uni
} from './uni'
import {
promisify
} from 'uni-helpers/promise'
import {
api
} from './api'
const uni = Object.create(null)
getApp,
getCurrentPages
}
from './plugins/app'
/* eslint-disable no-undef */
uni.version = __VERSION__
initOn(UniServiceJSBridge.on, {
getApp,
getCurrentPages
})
apis.forEach(name => {
if (api[name]) {
uni[name] = promisify(name, wrapper(name, api[name]))
} else {
uni[name] = wrapperUnimplemented(name)
}
initSubscribe(UniServiceJSBridge.subscribe, {
getApp,
getCurrentPages
})
export default uni
export {
getApp,
getCurrentPages
}
from './plugins/app'
export default uni
......@@ -2,7 +2,7 @@ import VueRouter from 'vue-router'
import {
isPage
} from 'uni-helpers'
} from 'uni-helpers/index'
import {
createAppMixin
......
export const api = Object.create(null)
import apis from 'uni-helpers/apis'
import {
wrapper,
wrapperUnimplemented
} from 'uni-helpers/api'
import {
promisify
} from 'uni-helpers/promise'
const api = Object.create(null)
export const uni = Object.create(null)
const baseApis = require.context(
'./api',
true,
/\.js$/
)
baseApis.keys().forEach(function (key) {
Object.assign(api, baseApis(key))
})
......@@ -14,11 +26,21 @@ const platformApis = require.context(
true,
/\.js$/
)
platformApis.keys().forEach(function (key) {
Object.assign(api, platformApis(key))
})
/* eslint-disable no-undef */
uni.version = __VERSION__
apis.forEach(name => {
if (api[name]) {
uni[name] = promisify(name, wrapper(name, api[name]))
} else {
uni[name] = wrapperUnimplemented(name)
}
})
export function invokeMethod (name, ...args) {
return api[name](...args)
}
import {
normalizeDataset
} from 'uni-helpers'
} from 'uni-helpers/index'
import getWindowOffset from 'uni-platform/helpers/get-window-offset'
......
......@@ -2,7 +2,7 @@ import 'intersection-observer'
import {
normalizeDataset
} from 'uni-helpers'
} from 'uni-helpers/index'
function getRect (rect) {
return {
......
......@@ -4,7 +4,7 @@ import {
import {
normalizeDataset
} from 'uni-helpers'
} from 'uni-helpers/index'
import {
wrapperMPEvent
......
import {
isPage
} from 'uni-helpers'
} from 'uni-helpers/index'
import {
initEvents,
......
export function publishHandler (event, args, pageId) {
// TODO
}
......@@ -4,14 +4,11 @@ import {
let firstBackTime = 0
export default function navigateBack ({
export function navigateBack ({
delta,
animationType,
animationDuration
}, {
plus,
getCurrentPages
}, callback) {
}) {
const pages = getCurrentPages()
const len = pages.length - 1
const page = pages[len]
......@@ -32,6 +29,8 @@ export default function navigateBack ({
} else {
page.$getAppWebview().close('auto')
}
callback && callback()
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateBack'
})
}
}
......@@ -2,13 +2,18 @@ import {
showWebview
} from './util'
export default function navigateTo ({
path,
export function navigateTo ({
url,
animationType,
animationDuration
}, {
__registerPage
}) {
const path = url.split('?')[0]
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
path
})
showWebview(
__registerPage({
path
......
export function publishHandler (event, args, pageId) {
// TODO
}
......@@ -2,8 +2,6 @@ import {
callAppHook
} from 'uni-core/service/plugins/util'
import Router from './router/index'
let appCtx
const NETWORK_TYPES = [
......@@ -21,13 +19,14 @@ export function getApp () {
}
function initGlobalListeners ({
uni,
plus,
UniServiceJSBridge
}) {
const emit = UniServiceJSBridge.emit
plus.key.addEventListener('backbutton', () => {
appCtx.$router.go(-1)
uni.navigateBack()
})
plus.globalEvent.addEventListener('pause', () => {
......@@ -67,8 +66,6 @@ export function registerApp (appVm, instanceContext) {
appCtx = appVm
appCtx.$router = new Router(instanceContext)
initAppLaunch(appVm, instanceContext)
initGlobalListeners(instanceContext)
......
import initOn from 'uni-core/service/bridge/on'
import initPopup from './popup'
let bridge
......@@ -18,7 +17,6 @@ export function initServiceJSBridge (Vue, instanceContext) {
}
initOn(bridge.on, instanceContext)
initPopup(bridge.on, instanceContext)
return bridge
}
......@@ -38,12 +38,17 @@ export function createInstanceContext (instanceContext) {
getCurrentPages
})
function __registerPage (page) {
return registerPage(page, instanceContext)
}
if (!uni) {
uni = createUniInstance(
weex,
plus,
uniConfig,
uniRoutes,
__registerPage,
UniServiceJSBridge,
getApp,
getCurrentPages
......@@ -59,9 +64,7 @@ export function createInstanceContext (instanceContext) {
__registerApp (appVm) {
return registerApp(appVm, instanceContext)
},
__registerPage (page) {
return registerPage(page, instanceContext)
},
__registerPage,
plus,
uni,
getApp,
......
......@@ -3,10 +3,6 @@ import {
createWebview
} from './webview/index'
import {
createHolder
} from './holder'
const pages = []
export function getCurrentPages () {
......@@ -60,10 +56,7 @@ export function registerPage ({
meta: routeOptions.meta,
path,
route
},
$holder: createHolder(webview, {
navigationBar: webview.$navigationBar
}, instanceContext)
}
})
return webview
......
import apis from 'uni-helpers/apis'
import {
wrapper,
wrapperUnimplemented
} from 'uni-helpers/api'
import {
promisify
} from 'uni-helpers/promise'
const api = Object.create(null)
const uni = Object.create(null)
const baseApis = require.context(
'../../../core/service/api',
true,
/\.js$/
)
baseApis.keys().forEach(function (key) {
Object.assign(api, baseApis(key))
})
const platformApis = require.context(
'./api',
true,
/\.js$/
)
platformApis.keys().forEach(function (key) {
Object.assign(api, platformApis(key))
})
apis.forEach(name => {
if (api[name]) {
uni[name] = promisify(name, wrapper(name, api[name]))
} else {
uni[name] = wrapperUnimplemented(name)
}
})
import './polyfill'
import {
wrapper
} from 'uni-helpers/api'
import {
promisify
} from 'uni-helpers/promise'
import api from 'uni-core/service/api'
const uni = Object.create(null)
Object.keys(api).forEach(name => {
uni[name] = promisify(name, wrapper(name, api[name]))
})
let waiting
let waitingTimeout
let toast = false
let toastTimeout
// 此处设计不对
export default function initPopup (on, {
plus
}) {
on('onShowToast', showToast)
on('onHideToast', hideToast)
on('onShowLoading', showToast)
on('onHideLoading', hideToast)
on('onShowModal', showModal)
on('onShowActionSheet', showActionSheet)
function showToast ({
title = '',
icon = 'success',
image = '',
duration = 1500,
mask = false,
position = ''
}) {
if (position) {
if (toast) {
toastTimeout && clearTimeout(toastTimeout)
plus.nativeUI.closeToast()
}
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout)
waiting.close()
}
if (~['top', 'center', 'bottom'].indexOf(position)) {
let richText = `<span>${title}</span>`
plus.nativeUI.toast(richText, {
verticalAlign: position,
type: 'richtext'
})
toast = true
toastTimeout = setTimeout(() => {
hideToast()
}, 2000)
return
}
console.warn('uni.showToast 传入的 "position" 值 "' + position + '" 无效')
}
if (duration) {
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout)
waiting.close()
}
if (toast) {
toastTimeout && clearTimeout(toastTimeout)
plus.nativeUI.closeToast()
}
if (icon && !~['success', 'loading', 'none'].indexOf(icon)) {
icon = 'success'
}
const waitingOptions = {
modal: mask,
back: 'transmit',
padding: '10px',
size: '16px' // 固定字体大小
}
if (!image && (!icon || icon === 'none')) { // 无图
// waitingOptions.width = '120px'
// waitingOptions.height = '40px'
waitingOptions.loading = {
display: 'none'
}
} else { // 有图
waitingOptions.width = '140px'
waitingOptions.height = '112px'
}
if (image) {
waitingOptions.loading = {
display: 'block',
height: '55px',
icon: image,
interval: duration
}
} else {
if (icon === 'success') {
waitingOptions.loading = {
display: 'block',
height: '55px',
icon: '__uniappsuccess.png',
interval: duration
}
}
}
waiting = plus.nativeUI.showWaiting(title, waitingOptions)
waitingTimeout = setTimeout(() => {
hideToast()
}, duration)
}
}
function hideToast () {
if (toast) {
toastTimeout && clearTimeout(toastTimeout)
plus.nativeUI.closeToast()
toast = false
}
if (waiting) {
waitingTimeout && clearTimeout(waitingTimeout)
waiting.close()
waiting = null
waitingTimeout = null
}
}
function showModal ({
title = '',
content = '',
showCancel = true,
cancelText = '取消',
cancelColor = '#000000',
confirmText = '确定',
confirmColor = '#3CC51F'
}, callback) {
plus.nativeUI.confirm(content, (e) => {
if (showCancel) {
callback(e.index === 1 ? 'confirm' : 'cancel')
} else {
callback(e.index === 0 ? 'confirm' : 'cancel')
}
}, title, showCancel ? [cancelText, confirmText] : [confirmText])
}
function showActionSheet ({
itemList = [],
itemColor = '#000000',
title = ''
}, callback) {
const options = {
buttons: itemList.map(item => ({
title: item
}))
}
if (title) {
options.title = title
}
if (plus.os.name === 'iOS') {
options.cancel = '取消'
}
plus.nativeUI.actionSheet(options, (e) => {
if (e.index > 0) {
callback(e.index - 1)
} else {
callback(-1)
}
})
}
}
import navigateBack from './navigate-back'
import navigateTo from './navigate-to'
import reLaunch from './re-launch'
import redirectTo from './redirect-to'
import switchTab from './switch-tab'
const route = {
navigateBack,
navigateTo,
reLaunch,
redirectTo,
switchTab
}
export default class Router {
constructor (instanceContext) {
this.instanceContext = instanceContext
this.$emit = instanceContext.UniServiceJSBridge.emit
}
push ({
type,
path,
animationType,
animationDuration
} = {}) {
this.$emit('onAppRoute', {
type,
path
})
route[type]({
path,
animationType,
animationDuration
}, this.instanceContext)
}
go (delta, {
animationType,
animationDuration
} = {}) {
delta = Math.abs(parseInt(delta) || 1)
route.navigateBack({
delta,
animationType,
animationDuration
}, this.instanceContext, () => {
this.$emit('onAppRoute', {
type: 'navigateBack'
})
})
}
}
export default function reLaunch ({
path
}, instanceContext) {}
export default function redirectTo ({
path
}, instanceContext) {}
export default function switchTab ({
path
}, instanceContext) {}
......@@ -31,7 +31,7 @@
<script>
import {
upx2px
} from 'uni-helpers'
} from 'uni-helpers/index'
import {
NAVBAR_HEIGHT
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册