提交 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){
var localStorage = plus.storage
output.banner =
`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
}
{
"name": "uniapp-js-framework",
"version": "0.0.1",
"scripts": {
"lint": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore build src",
"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: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",
"build:mp-weixin": "cross-env UNI_PLATFORM=mp-weixin rollup -c build/rollup.config.mp.js",
"build:mp-baidu": "cross-env UNI_PLATFORM=mp-baidu rollup -c build/rollup.config.mp.js",
"build:mp-alipay": "cross-env UNI_PLATFORM=mp-alipay rollup -c build/rollup.config.mp.js",
"build:mp-toutiao": "cross-env UNI_PLATFORM=mp-toutiao rollup -c build/rollup.config.mp.js",
"build:runtime": "npm run lint && npm run build:mp-weixin && npm run build:mp-qq && npm run build:mp-alipay && npm run build:mp-baidu && npm run build:mp-toutiao && npm run build:app-plus",
"test:unit": "cross-env NODE_ENV=test UNI_PLATFORM=h5 mocha-webpack --require tests/unit/setup.js --webpack-config build/webpack.config.test.js tests/unit/**/*.spec.js"
"name": "uniapp-js-framework",
"version": "0.0.1",
"scripts": {
"lint": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore build src",
"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: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",
"build:mp-weixin": "cross-env UNI_PLATFORM=mp-weixin rollup -c build/rollup.config.mp.js",
"build:mp-baidu": "cross-env UNI_PLATFORM=mp-baidu rollup -c build/rollup.config.mp.js",
"build:mp-alipay": "cross-env UNI_PLATFORM=mp-alipay rollup -c build/rollup.config.mp.js",
"build:mp-toutiao": "cross-env UNI_PLATFORM=mp-toutiao rollup -c build/rollup.config.mp.js",
"build:runtime": "npm run lint && npm run build:mp-weixin && npm run build:mp-qq && npm run build:mp-alipay && npm run build:mp-baidu && npm run build:mp-toutiao && npm run build:app-plus",
"test:unit": "cross-env NODE_ENV=test UNI_PLATFORM=h5 mocha-webpack --require tests/unit/setup.js --webpack-config build/webpack.config.test.js tests/unit/**/*.spec.js"
},
"dependencies": {
"base64-arraybuffer": "^0.2.0",
"intersection-observer": "^0.7.0"
},
"private": true,
"devDependencies": {
"@vue/cli-plugin-babel": "^3.4.1",
"@vue/cli-plugin-eslint": "^3.4.1",
"@vue/cli-plugin-unit-mocha": "^3.4.1",
"@vue/cli-service": "^3.4.1",
"@vue/test-utils": "^1.0.0-beta.25",
"babel-eslint": "^10.0.1",
"babylon": "^6.18.0",
"browserslist": "^4.4.2",
"caniuse-lite": "^1.0.30000940",
"chai": "^4.1.2",
"copy": "^0.3.2",
"cross-env": "^5.2.0",
"del": "^5.0.0",
"eslint": "^5.5.0",
"eslint-config-standard": "^12.0.0",
"eslint-loader": "^2.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^4.0.0",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^4.7.1",
"jsdom": "^13.0.0",
"jsdom-global": "^3.0.2",
"jsonfile": "^5.0.0",
"rollup": "^1.17.0",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-replace": "^2.1.0",
"strip-json-comments": "^2.0.1",
"vue": "^2.6.8",
"vue-router": "^3.0.1",
"vue-template-compiler": "^2.6.8",
"webpack": "^4.18.0",
"webpack-bundle-analyzer": "^3.0.3",
"webpack-virtual-modules": "^0.1.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"dependencies": {
"base64-arraybuffer": "^0.2.0",
"intersection-observer": "^0.7.0"
},
"private": true,
"devDependencies": {
"@vue/cli-plugin-babel": "^3.4.1",
"@vue/cli-plugin-eslint": "^3.4.1",
"@vue/cli-plugin-unit-mocha": "^3.4.1",
"@vue/cli-service": "^3.4.1",
"@vue/test-utils": "^1.0.0-beta.25",
"babel-eslint": "^10.0.1",
"babylon": "^6.18.0",
"browserslist": "^4.4.2",
"caniuse-lite": "^1.0.30000940",
"chai": "^4.1.2",
"copy": "^0.3.2",
"cross-env": "^5.2.0",
"del": "^5.0.0",
"eslint": "^5.5.0",
"eslint-config-standard": "^12.0.0",
"eslint-loader": "^2.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^4.0.0",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^4.7.1",
"jsdom": "^13.0.0",
"jsdom-global": "^3.0.2",
"jsonfile": "^5.0.0",
"rollup": "^1.17.0",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-replace": "^2.1.0",
"strip-json-comments": "^2.0.1",
"vue": "^2.6.8",
"vue-router": "^3.0.1",
"vue-template-compiler": "^2.6.8",
"webpack": "^4.18.0",
"webpack-bundle-analyzer": "^3.0.3",
"webpack-virtual-modules": "^0.1.10"
"extends": [
"plugin:vue/recommended",
"standard"
],
"globals": {
"App": true,
"Page": true,
"Component": true,
"Behavior": true,
"getApp": true,
"getCurrentPages": true,
"plus": true,
"uni": true,
"Vue": true,
"wx": true,
"my": true,
"swan": true,
"__uniConfig": true,
"__uniRoutes": true,
"__registerPage": true,
"UniViewJSBridge": true,
"UniServiceJSBridge": true,
"__PLATFORM__": true,
"__VERSION__": true,
"__GLOBAL__": true,
"__PLATFORM_TITLE__": true,
"__PLATFORM_PREFIX__": true
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/recommended",
"standard"
],
"globals": {
"App": true,
"Page": true,
"Component": true,
"Behavior": true,
"getApp": true,
"getCurrentPages": true,
"plus": true,
"uni": true,
"Vue": true,
"wx": true,
"my": true,
"swan": true,
"__uniConfig": true,
"__uniRoutes": true,
"UniViewJSBridge": true,
"UniServiceJSBridge": true,
"__PLATFORM__": true,
"__VERSION__": true,
"__GLOBAL__": true,
"__PLATFORM_TITLE__": true,
"__PLATFORM_PREFIX__": true
},
"rules": {
"no-tabs": 0,
"standard/no-callback-literal": 0
},
"parserOptions": {
"parser": "babel-eslint"
}
"rules": {
"no-tabs": 0,
"standard/no-callback-literal": 0
},
"browserslist": [
"last 3 versions",
"Android >= 4.1",
"ios >= 8"
],
"license": "Apache-2.0",
"main": "index.js",
"description": "",
"author": ""
}
"parserOptions": {
"parser": "babel-eslint"
}
},
"browserslist": [
"last 3 versions",
"Android >= 4.1",
"ios >= 8"
],
"license": "Apache-2.0",
"main": "index.js",
"description": "",
"author": ""
}
......@@ -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 = [
......@@ -160,14 +34,15 @@ function getApp () {
return appCtx
}
function initGlobalListeners ({
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
......@@ -587,7 +424,7 @@ function registerConfig (config, {
function initOn (on, {
getApp,
getCurrentPages
}) {
}) {
function onError (err) {
callAppHook(getApp(), 'onError', err);
}
......@@ -673,169 +510,9 @@ 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) {
function initServiceJSBridge (Vue, instanceContext) {
if (bridge) {
return bridge
}
......@@ -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,187 +419,644 @@ 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/;
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)
const interceptors = {
promiseInterceptor
};
var require_context_module_1_2 = /*#__PURE__*/Object.freeze({
interceptors: interceptors,
addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor
});
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
});
const base64ToArrayBuffer = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}];
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_1 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer,
arrayBufferToBase64: arrayBufferToBase64
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
});
function getInt (method) {
return function (value, params) {
if (value) {
params[method] = Math.round(value);
}
}
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
}
const canvasGetImageData = {
canvasId: {
type: String,
required: true
},
x: {
type: Number,
required: true,
validator: getInt('x')
},
y: {
type: Number,
required: true,
validator: getInt('y')
},
width: {
type: Number,
required: true,
validator: getInt('width')
},
height: {
type: Number,
required: true,
validator: getInt('height')
}
};
const canvasPutImageData = {
canvasId: {
type: String,
required: true
},
data: {
type: Uint8ClampedArray,
required: true
},
x: {
type: Number,
required: true,
validator: getInt('x')
},
y: {
type: Number,
required: true,
validator: getInt('y')
},
width: {
type: Number,
required: true,
validator: getInt('width')
},
height: {
type: Number,
validator: getInt('height')
}
};
const fileType = {
PNG: 'png',
JPG: 'jpeg'
};
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
upx2px: upx2px
});
const canvasToTempFilePath = {
x: {
type: Number,
default: 0,
validator: getInt('x')
},
y: {
type: Number,
default: 0,
validator: getInt('y')
},
width: {
type: Number,
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$1 = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64$1 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}];
var require_context_module_2_1 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer$1,
arrayBufferToBase64: arrayBufferToBase64$1
});
function getInt (method) {
return function (value, params) {
if (value) {
params[method] = Math.round(value);
}
}
}
const canvasGetImageData = {
canvasId: {
type: String,
required: true
},
x: {
type: Number,
required: true,
validator: getInt('x')
},
y: {
type: Number,
required: true,
validator: getInt('y')
},
width: {
type: Number,
required: true,
validator: getInt('width')
},
height: {
type: Number,
required: true,
validator: getInt('height')
}
};
const canvasPutImageData = {
canvasId: {
type: String,
required: true
},
data: {
type: Uint8ClampedArray,
required: true
},
x: {
type: Number,
required: true,
validator: getInt('x')
},
y: {
type: Number,
required: true,
validator: getInt('y')
},
width: {
type: Number,
required: true,
validator: getInt('width')
},
height: {
type: Number,
validator: getInt('height')
}
};
const fileType = {
PNG: 'png',
JPG: 'jpeg'
};
const canvasToTempFilePath = {
x: {
type: Number,
default: 0,
validator: getInt('x')
},
y: {
type: Number,
default: 0,
validator: getInt('y')
},
width: {
type: Number,
validator: getInt('width')
},
height: {
......@@ -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
......@@ -967,1228 +1601,914 @@ const uploadFile = {
type: String,
required: true
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
},
formData: {
type: Object,
validator (value, params) {
params.formData = value || {};
}
}
};
var require_context_module_1_15 = /*#__PURE__*/Object.freeze({
uploadFile: uploadFile
});
const pageScrollTo = {
scrollTop: {
type: Number,
required: true
},
duration: {
type: Number,
default: 300,
validator (duration, params) {
params.duration = Math.max(0, duration);
}
}
};
var require_context_module_1_16 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo
});
const service = {
OAUTH: 'OAUTH',
SHARE: 'SHARE',
PAYMENT: 'PAYMENT',
PUSH: 'PUSH'
};
const getProvider = {
service: {
type: String,
required: true,
validator (value, params) {
value = (value || '').toUpperCase();
if (value && Object.values(service).indexOf(value) < 0) {
return 'service error'
}
}
}
};
var require_context_module_1_17 = /*#__PURE__*/Object.freeze({
getProvider: getProvider
});
const showModal = {
title: {
type: String,
default: ''
},
content: {
type: String,
default: ''
},
showCancel: {
type: Boolean,
default: true
},
cancelText: {
type: String,
default: '取消'
},
cancelColor: {
type: String,
default: '#000000'
},
confirmText: {
type: String,
default: '确定'
},
confirmColor: {
type: String,
default: '#007aff'
},
visible: {
type: Boolean,
default: true
}
};
const showToast = {
title: {
type: String,
default: ''
},
icon: {
default: 'success',
validator (icon, params) {
if (['success', 'loading', 'none'].indexOf(icon) === -1) {
params.icon = 'success';
}
}
},
image: {
type: String,
default: '',
validator (image, params) {
if (image) {
params.image = getRealPath(image);
}
}
},
duration: {
type: Number,
default: 1500
},
mask: {
type: Boolean,
default: false
},
visible: {
type: Boolean,
default: true
}
};
const showLoading = {
title: {
type: String,
default: ''
},
icon: {
type: String,
default: 'loading'
},
duration: {
type: Number,
default: 100000000 // 简单处理 showLoading,直接设置个大值
},
mask: {
type: Boolean,
default: false
},
visible: {
type: Boolean,
default: true
}
};
const showActionSheet = {
itemList: {
type: Array,
required: true,
validator (itemList, params) {
if (!itemList.length) {
return 'parameter.itemList should have at least 1 item'
}
}
},
itemColor: {
type: String,
default: '#000000'
},
visible: {
type: Boolean,
default: true
}
};
var require_context_module_1_18 = /*#__PURE__*/Object.freeze({
showModal: showModal,
showToast: showToast,
showLoading: showLoading,
showActionSheet: showActionSheet
});
function encodeQueryString (url) {
if (typeof url !== 'string') {
return url
}
const index = url.indexOf('?');
if (index === -1) {
return url
}
const query = url.substr(index + 1).trim().replace(/^(\?|#|&)/, '');
if (!query) {
return url
}
url = url.substr(0, index);
const params = [];
query.split('&').forEach(param => {
const parts = param.replace(/\+/g, ' ').split('=');
const key = parts.shift();
const val = parts.length > 0
? parts.join('=')
: '';
params.push(key + '=' + encodeURIComponent(val));
});
return params.length ? url + '?' + params.join('&') : url
}
function createValidator (type) {
return function validator (url, params) {
// 格式化为绝对路径路由
url = getRealRoute(url);
const pagePath = url.split('?')[0];
// 匹配路由是否存在
const routeOptions = __uniRoutes.find(({
path,
alias
}) => path === pagePath || alias === pagePath);
if (!routeOptions) {
return 'page `' + url + '` is not found'
}
// 检测不同类型跳转
if (type === 'navigateTo' || type === 'redirectTo') {
if (routeOptions.meta.isTabBar) {
return `can not ${type} a tabbar page`
}
} else if (type === 'switchTab') {
if (!routeOptions.meta.isTabBar) {
return 'can not switch to no-tabBar page'
}
}
// tabBar不允许传递参数
if (routeOptions.meta.isTabBar) {
url = pagePath;
}
// 首页自动格式化为`/`
if (routeOptions.meta.isEntry) {
url = url.replace(routeOptions.alias, '/');
}
// 参数格式化
params.url = encodeQueryString(url);
}
}
function createProtocol (type, extras = {}) {
return Object.assign({
url: {
type: String,
required: true,
validator: createValidator(type)
}
}, extras)
}
function createAnimationProtocol (animationTypes) {
return {
animationType: {
type: String,
validator (type) {
if (type && animationTypes.indexOf(type) === -1) {
return '`' + type + '` is not supported for `animationType` (supported values are: `' + animationTypes.join(
'`|`') + '`)'
}
}
},
animationDuration: {
type: Number
}
}
}
const redirectTo = createProtocol('redirectTo');
const reLaunch = createProtocol('reLaunch');
const navigateTo = createProtocol('navigateTo', createAnimationProtocol(
[
'slide-in-right',
'slide-in-left',
'slide-in-top',
'slide-in-bottom',
'fade-in',
'zoom-out',
'zoom-fade-out',
'pop-in',
'none'
]
));
const switchTab = createProtocol('switchTab');
const navigateBack = Object.assign({
delta: {
type: Number,
validator (delta, params) {
delta = parseInt(delta) || 1;
params.delta = Math.min(getCurrentPages().length - 1, delta);
}
}
}, createAnimationProtocol(
[
'slide-out-right',
'slide-out-left',
'slide-out-top',
'slide-out-bottom',
'fade-out',
'zoom-in',
'zoom-fade-in',
'pop-out',
'none'
]
));
var require_context_module_1_19 = /*#__PURE__*/Object.freeze({
redirectTo: redirectTo,
reLaunch: reLaunch,
navigateTo: navigateTo,
switchTab: switchTab,
navigateBack: navigateBack
});
const setStorage = {
'key': {
type: String,
required: true
},
'data': {
required: true
}
};
const setStorageSync = [{
name: 'key',
type: String,
required: true
}, {
name: 'data',
required: true
}];
var require_context_module_1_20 = /*#__PURE__*/Object.freeze({
setStorage: setStorage,
setStorageSync: setStorageSync
});
const indexValidator = {
type: Number,
required: true
};
const setTabBarItem = {
index: indexValidator,
text: {
type: String
},
iconPath: {
type: String
},
selectedIconPath: {
type: String
}
};
const setTabBarStyle = {
color: {
type: String
},
selectedColor: {
type: String
},
backgroundColor: {
type: String
},
borderStyle: {
type: String,
validator (borderStyle, params) {
if (borderStyle) {
params.borderStyle = borderStyle === 'black' ? 'black' : 'white';
}
}
}
};
const hideTabBar = {
animation: {
type: Boolean,
default: false
}
};
const showTabBar = {
animation: {
type: Boolean,
default: false
}
};
const hideTabBarRedDot = {
index: indexValidator
};
const showTabBarRedDot = {
index: indexValidator
};
const removeTabBarBadge = {
index: indexValidator
};
const setTabBarBadge = {
index: indexValidator,
text: {
type: String,
required: true,
validator (text, params) {
if (getLen(text) >= 4) {
params.text = '...';
}
}
}
};
var require_context_module_1_21 = /*#__PURE__*/Object.freeze({
setTabBarItem: setTabBarItem,
setTabBarStyle: setTabBarStyle,
hideTabBar: hideTabBar,
showTabBar: showTabBar,
hideTabBarRedDot: hideTabBarRedDot,
showTabBarRedDot: showTabBarRedDot,
removeTabBarBadge: removeTabBarBadge,
setTabBarBadge: setTabBarBadge
});
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,
};
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.keys().forEach(function (key) {
Object.assign(protocol, modules(key));
});
function validateParam (key, paramTypes, paramsData) {
const paramOptions = paramTypes[key];
const absent = !hasOwn(paramsData, key);
let value = paramsData[key];
const booleanIndex = getTypeIndex(Boolean, paramOptions.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(paramOptions, 'default')) {
value = false;
}
}
if (value === undefined) {
if (hasOwn(paramOptions, 'default')) {
const paramDefault = paramOptions['default'];
value = isFn(paramDefault) ? paramDefault() : paramDefault;
paramsData[key] = value; // 默认值
}
}
return assertParam(paramOptions, key, value, absent, paramsData)
}
function assertParam (
paramOptions,
name,
value,
absent,
paramsData
) {
if (paramOptions.required && absent) {
return `Missing required parameter \`${name}\``
}
if (value == null && !paramOptions.required) {
const validator = paramOptions.validator;
if (validator) {
return validator(value, paramsData)
}
return
}
let type = paramOptions.type;
let valid = !type || type === true;
const expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (let i = 0; i < type.length && !valid; i++) {
const assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
return getInvalidTypeMessage(name, value, expectedTypes)
}
const validator = paramOptions.validator;
if (validator) {
return validator(value, paramsData)
}
}
const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
let valid;
const expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
const t = typeof value;
valid = t === expectedType.toLowerCase();
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid,
expectedType
}
}
function getType (fn) {
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function isSameType (a, b) {
return getType(a) === getType(b)
}
function getTypeIndex (type, expectedTypes) {
if (!Array.isArray(expectedTypes)) {
return isSameType(expectedTypes, type) ? 0 : -1
}
for (let i = 0, len = expectedTypes.length; i < len; i++) {
if (isSameType(expectedTypes[i], type)) {
return i
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
},
formData: {
type: Object,
validator (value, params) {
params.formData = value || {};
}
}
};
var require_context_module_2_15 = /*#__PURE__*/Object.freeze({
uploadFile: uploadFile
});
const pageScrollTo$1 = {
scrollTop: {
type: Number,
required: true
},
duration: {
type: Number,
default: 300,
validator (duration, params) {
params.duration = Math.max(0, duration);
}
}
return -1
}
function getInvalidTypeMessage (name, value, expectedTypes) {
let message = `parameter \`${name}\`.` +
` Expected ${expectedTypes.join(', ')}`;
const expectedType = expectedTypes[0];
const receivedType = toRawType(value);
const expectedValue = styleValue(value, expectedType);
const receivedValue = styleValue(value, receivedType);
if (expectedTypes.length === 1 &&
isExplicable(expectedType) &&
!isBoolean(expectedType, receivedType)) {
message += ` with value ${expectedValue}`;
}
message += `, got ${receivedType} `;
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`;
}
return message
}
function styleValue (value, type) {
if (type === 'String') {
return `"${value}"`
} else if (type === 'Number') {
return `${Number(value)}`
} else {
return `${value}`
}
}
const explicitTypes = ['string', 'number', 'boolean'];
function isExplicable (value) {
return explicitTypes.some(elem => value.toLowerCase() === elem)
}
function isBoolean (...args) {
return args.some(elem => elem.toLowerCase() === 'boolean')
}
};
function invokeCallbackHandlerFail (err, apiName, callbackId) {
const errMsg = `${apiName}:fail ${err}`;
console.error(errMsg);
if (callbackId === -1) {
throw new Error(errMsg)
}
if (typeof callbackId === 'number') {
invokeCallbackHandler(callbackId, {
errMsg
});
var require_context_module_2_16 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1
});
const service = {
OAUTH: 'OAUTH',
SHARE: 'SHARE',
PAYMENT: 'PAYMENT',
PUSH: 'PUSH'
};
const getProvider = {
service: {
type: String,
required: true,
validator (value, params) {
value = (value || '').toUpperCase();
if (value && Object.values(service).indexOf(value) < 0) {
return 'service error'
}
}
}
};
var require_context_module_2_17 = /*#__PURE__*/Object.freeze({
getProvider: getProvider
});
const showModal = {
title: {
type: String,
default: ''
},
content: {
type: String,
default: ''
},
showCancel: {
type: Boolean,
default: true
},
cancelText: {
type: String,
default: '取消'
},
cancelColor: {
type: String,
default: '#000000'
},
confirmText: {
type: String,
default: '确定'
},
confirmColor: {
type: String,
default: '#007aff'
},
visible: {
type: Boolean,
default: true
}
return false
}
const callbackApiParamTypes = [{
name: 'callback',
type: Function,
required: true
}];
};
function validateParams (apiName, paramsData, callbackId) {
let paramTypes = protocol[apiName];
if (!paramTypes && isCallbackApi(apiName)) {
paramTypes = callbackApiParamTypes;
}
if (paramTypes) {
if (Array.isArray(paramTypes) && Array.isArray(paramsData)) {
const paramTypeObj = Object.create(null);
const paramsDataObj = Object.create(null);
const paramsDataLength = paramsData.length;
paramTypes.forEach((paramType, index) => {
paramTypeObj[paramType.name] = paramType;
if (paramsDataLength > index) {
paramsDataObj[paramType.name] = paramsData[index];
}
});
paramTypes = paramTypeObj;
paramsData = paramsDataObj;
const showToast = {
title: {
type: String,
default: ''
},
icon: {
default: 'success',
validator (icon, params) {
if (['success', 'loading', 'none'].indexOf(icon) === -1) {
params.icon = 'success';
}
}
if (isFn(paramTypes.beforeValidate)) {
const err = paramTypes.beforeValidate(paramsData);
if (err) {
return invokeCallbackHandlerFail(err, apiName, callbackId)
},
image: {
type: String,
default: '',
validator (image, params) {
if (image) {
params.image = getRealPath(image);
}
}
},
duration: {
type: Number,
default: 1500
},
mask: {
type: Boolean,
default: false
},
visible: {
type: Boolean,
default: true
}
};
const showLoading = {
title: {
type: String,
default: ''
},
icon: {
type: String,
default: 'loading'
},
duration: {
type: Number,
default: 100000000 // 简单处理 showLoading,直接设置个大值
},
mask: {
type: Boolean,
default: false
},
visible: {
type: Boolean,
default: true
}
};
const keys = Object.keys(paramTypes);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === 'beforeValidate') {
continue
}
const err = validateParam(keys[i], paramTypes, paramsData);
if (err) {
return invokeCallbackHandlerFail(err, apiName, callbackId)
const showActionSheet = {
itemList: {
type: Array,
required: true,
validator (itemList, params) {
if (!itemList.length) {
return 'parameter.itemList should have at least 1 item'
}
}
},
itemColor: {
type: String,
default: '#000000'
},
visible: {
type: Boolean,
default: true
}
};
var require_context_module_2_18 = /*#__PURE__*/Object.freeze({
showModal: showModal,
showToast: showToast,
showLoading: showLoading,
showActionSheet: showActionSheet
});
function encodeQueryString (url) {
if (typeof url !== 'string') {
return url
}
return true
}
const index = url.indexOf('?');
let invokeCallbackId = 1;
if (index === -1) {
return url
}
const invokeCallbacks = {};
const query = url.substr(index + 1).trim().replace(/^(\?|#|&)/, '');
function createKeepAliveApiCallback (apiName, callback) {
const callbackId = invokeCallbackId++;
const invokeCallbackName = 'api.' + apiName + '.' + callbackId;
if (!query) {
return url
}
const invokeCallback = function (res) {
callback(res);
};
url = url.substr(0, index);
invokeCallbacks[callbackId] = {
name: invokeCallbackName,
keepAlive: true,
callback: invokeCallback
};
return callbackId
}
const params = [];
function createApiCallback (apiName, params = {}, extras = {}) {
if (!isPlainObject(params)) {
return {
params
}
}
params = Object.assign({}, params);
query.split('&').forEach(param => {
const parts = param.replace(/\+/g, ' ').split('=');
const key = parts.shift();
const val = parts.length > 0
? parts.join('=')
: '';
const apiCallbacks = {};
for (let name in params) {
const param = params[name];
if (isFn(param)) {
apiCallbacks[name] = tryCatch(param);
delete params[name];
}
}
params.push(key + '=' + encodeURIComponent(val));
});
const {
success,
fail,
cancel,
complete
} = apiCallbacks;
return params.length ? url + '?' + params.join('&') : url
}
const hasSuccess = isFn(success);
const hasFail = isFn(fail);
const hasCancel = isFn(cancel);
const hasComplete = isFn(complete);
function createValidator (type) {
return function validator (url, params) {
// 格式化为绝对路径路由
url = getRealRoute(url);
if (!hasSuccess && !hasFail && !hasCancel && !hasComplete) { // 无回调
return {
params
const pagePath = url.split('?')[0];
// 匹配路由是否存在
const routeOptions = __uniRoutes.find(({
path,
alias
}) => path === pagePath || alias === pagePath);
if (!routeOptions) {
return 'page `' + url + '` is not found'
}
}
const wrapperCallbacks = {};
for (let name in extras) {
const extra = extras[name];
if (isFn(extra)) {
wrapperCallbacks[name] = tryCatchFramework(extra);
delete extras[name];
// 检测不同类型跳转
if (type === 'navigateTo' || type === 'redirectTo') {
if (routeOptions.meta.isTabBar) {
return `can not ${type} a tabbar page`
}
} else if (type === 'switchTab') {
if (!routeOptions.meta.isTabBar) {
return 'can not switch to no-tabBar page'
}
}
}
const {
beforeSuccess,
afterSuccess,
beforeFail,
afterFail,
beforeCancel,
afterCancel,
afterAll
} = wrapperCallbacks;
// tabBar不允许传递参数
if (routeOptions.meta.isTabBar) {
url = pagePath;
}
const callbackId = invokeCallbackId++;
const invokeCallbackName = 'api.' + apiName + '.' + callbackId;
// 首页自动格式化为`/`
if (routeOptions.meta.isEntry) {
url = url.replace(routeOptions.alias, '/');
}
const invokeCallback = function (res) {
res.errMsg = res.errMsg || apiName + ':ok';
// 参数格式化
params.url = encodeQueryString(url);
}
}
const errMsg = res.errMsg;
function createProtocol (type, extras = {}) {
return Object.assign({
url: {
type: String,
required: true,
validator: createValidator(type)
}
}, extras)
}
if (errMsg.indexOf(apiName + ':ok') === 0) {
isFn(beforeSuccess) && beforeSuccess(res);
function createAnimationProtocol (animationTypes) {
return {
animationType: {
type: String,
validator (type) {
if (type && animationTypes.indexOf(type) === -1) {
return '`' + type + '` is not supported for `animationType` (supported values are: `' + animationTypes.join(
'`|`') + '`)'
}
}
},
animationDuration: {
type: Number
}
}
}
hasSuccess && success(res);
const redirectTo$1 = createProtocol('redirectTo');
isFn(afterSuccess) && afterSuccess(res);
} else if (errMsg.indexOf(apiName + ':cancel') === 0) {
res.errMsg = res.errMsg.replace(apiName + ':cancel', apiName + ':fail cancel');
const reLaunch$1 = createProtocol('reLaunch');
hasFail && fail(res);
const navigateTo$1 = createProtocol('navigateTo', createAnimationProtocol(
[
'slide-in-right',
'slide-in-left',
'slide-in-top',
'slide-in-bottom',
'fade-in',
'zoom-out',
'zoom-fade-out',
'pop-in',
'none'
]
));
isFn(beforeCancel) && beforeCancel(res);
const switchTab$1 = createProtocol('switchTab');
hasCancel && cancel(res);
const navigateBack$1 = Object.assign({
delta: {
type: Number,
validator (delta, params) {
delta = parseInt(delta) || 1;
params.delta = Math.min(getCurrentPages().length - 1, delta);
}
}
}, createAnimationProtocol(
[
'slide-out-right',
'slide-out-left',
'slide-out-top',
'slide-out-bottom',
'fade-out',
'zoom-in',
'zoom-fade-in',
'pop-out',
'none'
]
));
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$1 = {
'key': {
type: String,
required: true
},
'data': {
required: true
}
};
isFn(afterCancel) && afterCancel(res);
} else if (errMsg.indexOf(apiName + ':fail') === 0) {
isFn(beforeFail) && beforeFail(res);
const setStorageSync$1 = [{
name: 'key',
type: String,
required: true
}, {
name: 'data',
required: true
}];
var require_context_module_2_20 = /*#__PURE__*/Object.freeze({
setStorage: setStorage$1,
setStorageSync: setStorageSync$1
});
const indexValidator = {
type: Number,
required: true
};
hasFail && fail(res);
const setTabBarItem = {
index: indexValidator,
text: {
type: String
},
iconPath: {
type: String
},
selectedIconPath: {
type: String
}
};
isFn(afterFail) && afterFail(res);
const setTabBarStyle = {
color: {
type: String
},
selectedColor: {
type: String
},
backgroundColor: {
type: String
},
borderStyle: {
type: String,
validator (borderStyle, params) {
if (borderStyle) {
params.borderStyle = borderStyle === 'black' ? 'black' : 'white';
}
}
}
};
const hideTabBar = {
animation: {
type: Boolean,
default: false
}
};
const showTabBar = {
animation: {
type: Boolean,
default: false
}
};
hasComplete && complete(res);
const hideTabBarRedDot = {
index: indexValidator
};
isFn(afterAll) && afterAll(res);
};
const showTabBarRedDot = {
index: indexValidator
};
invokeCallbacks[callbackId] = {
name: invokeCallbackName,
callback: invokeCallback
};
const removeTabBarBadge = {
index: indexValidator
};
return {
params,
callbackId
const setTabBarBadge = {
index: indexValidator,
text: {
type: String,
required: true,
validator (text, params) {
if (getLen(text) >= 4) {
params.text = '...';
}
}
}
}
};
var require_context_module_2_21 = /*#__PURE__*/Object.freeze({
setTabBarItem: setTabBarItem,
setTabBarStyle: setTabBarStyle,
hideTabBar: hideTabBar,
showTabBar: showTabBar,
hideTabBarRedDot: hideTabBarRedDot,
showTabBarRedDot: showTabBarRedDot,
removeTabBarBadge: removeTabBarBadge,
setTabBarBadge: setTabBarBadge
});
const protocol = Object.create(null);
const modules =
(function() {
var map = {
'./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) {
return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
};
req.keys = function() {
return Object.keys(map);
};
return req;
})();
function createInvokeCallback (apiName, params = {}, extras = {}) {
const {
params: args,
callbackId
} = createApiCallback(apiName, params, extras);
modules.keys().forEach(function (key) {
Object.assign(protocol, modules(key));
});
function validateParam (key, paramTypes, paramsData) {
const paramOptions = paramTypes[key];
const absent = !hasOwn(paramsData, key);
let value = paramsData[key];
if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
return {
params: args,
callbackId: false
const booleanIndex = getTypeIndex(Boolean, paramOptions.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(paramOptions, 'default')) {
value = false;
}
}
return {
params: args,
callbackId
if (value === undefined) {
if (hasOwn(paramOptions, 'default')) {
const paramDefault = paramOptions['default'];
value = isFn(paramDefault) ? paramDefault() : paramDefault;
paramsData[key] = value; // 默认值
}
}
return assertParam(paramOptions, key, value, absent, paramsData)
}
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 assertParam (
paramOptions,
name,
value,
absent,
paramsData
) {
if (paramOptions.required && absent) {
return `Missing required parameter \`${name}\``
}
return res
}
function wrapper (name, invokeMethod, extras) {
if (!isFn(invokeMethod)) {
return invokeMethod
if (value == null && !paramOptions.required) {
const validator = paramOptions.validator;
if (validator) {
return validator(value, paramsData)
}
return
}
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
}
let type = paramOptions.type;
let valid = !type || type === true;
const expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (let i = 0; i < type.length && !valid; i++) {
const assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
}
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]
if (!valid) {
return getInvalidTypeMessage(name, value, expectedTypes)
}
const validator = paramOptions.validator;
if (validator) {
return validator(value, paramsData)
}
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);
}
const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
let valid;
const expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
const t = typeof value;
valid = t === expectedType.toLowerCase();
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid,
expectedType
}
return {}
}
let pageId;
function getType (fn) {
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function setPullDownRefreshPageId (pullDownRefreshPageId) {
pageId = pullDownRefreshPageId;
function isSameType (a, b) {
return getType(a) === getType(b)
}
function startPullDownRefresh () {
if (pageId) {
UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
function getTypeIndex (type, expectedTypes) {
if (!Array.isArray(expectedTypes)) {
return isSameType(expectedTypes, type) ? 0 : -1
}
const pages = getCurrentPages();
if (pages.length) {
pageId = pages[pages.length - 1].$page.id;
UniServiceJSBridge.emit(pageId + '.startPullDownRefresh', {}, pageId);
for (let i = 0, len = expectedTypes.length; i < len; i++) {
if (isSameType(expectedTypes[i], type)) {
return i
}
}
return {}
return -1
}
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);
}
function getInvalidTypeMessage (name, value, expectedTypes) {
let message = `parameter \`${name}\`.` +
` Expected ${expectedTypes.join(', ')}`;
const expectedType = expectedTypes[0];
const receivedType = toRawType(value);
const expectedValue = styleValue(value, expectedType);
const receivedValue = styleValue(value, receivedType);
if (expectedTypes.length === 1 &&
isExplicable(expectedType) &&
!isBoolean(expectedType, receivedType)) {
message += ` with value ${expectedValue}`;
}
return {}
message += `, got ${receivedType} `;
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`;
}
return message
}
function styleValue (value, type) {
if (type === 'String') {
return `"${value}"`
} else if (type === 'Number') {
return `${Number(value)}`
} else {
return `${value}`
}
}
const explicitTypes = ['string', 'number', 'boolean'];
function isExplicable (value) {
return explicitTypes.some(elem => value.toLowerCase() === elem)
}
function isBoolean (...args) {
return args.some(elem => elem.toLowerCase() === 'boolean')
}
var require_context_module_0_3 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1,
setPullDownRefreshPageId: setPullDownRefreshPageId,
startPullDownRefresh: startPullDownRefresh,
stopPullDownRefresh: stopPullDownRefresh
});
function setStorage$1 ({
key,
data
} = {}) {
const value = {
type: typeof data === 'object' ? 'object' : 'string',
data: data
function invokeCallbackHandlerFail (err, apiName, callbackId) {
const errMsg = `${apiName}:fail ${err}`;
console.error(errMsg);
if (callbackId === -1) {
throw new Error(errMsg)
}
if (typeof callbackId === 'number') {
invokeCallbackHandler(callbackId, {
errMsg
});
}
return false
}
const callbackApiParamTypes = [{
name: 'callback',
type: Function,
required: true
}];
function validateParams (apiName, paramsData, callbackId) {
let paramTypes = protocol[apiName];
if (!paramTypes && isCallbackApi(apiName)) {
paramTypes = callbackApiParamTypes;
}
if (paramTypes) {
if (Array.isArray(paramTypes) && Array.isArray(paramsData)) {
const paramTypeObj = Object.create(null);
const paramsDataObj = Object.create(null);
const paramsDataLength = paramsData.length;
paramTypes.forEach((paramType, index) => {
paramTypeObj[paramType.name] = paramType;
if (paramsDataLength > index) {
paramsDataObj[paramType.name] = paramsData[index];
}
});
paramTypes = paramTypeObj;
paramsData = paramsDataObj;
}
if (isFn(paramTypes.beforeValidate)) {
const err = paramTypes.beforeValidate(paramsData);
if (err) {
return invokeCallbackHandlerFail(err, apiName, callbackId)
}
}
const keys = Object.keys(paramTypes);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === 'beforeValidate') {
continue
}
const err = validateParam(keys[i], paramTypes, paramsData);
if (err) {
return invokeCallbackHandlerFail(err, apiName, callbackId)
}
}
}
return true
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function createKeepAliveApiCallback (apiName, callback) {
const callbackId = invokeCallbackId++;
const invokeCallbackName = 'api.' + apiName + '.' + callbackId;
const invokeCallback = function (res) {
callback(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));
invokeCallbacks[callbackId] = {
name: invokeCallbackName,
keepAlive: true,
callback: invokeCallback
};
return callbackId
}
function createApiCallback (apiName, params = {}, extras = {}) {
if (!isPlainObject(params)) {
return {
params
}
}
params = Object.assign({}, params);
const apiCallbacks = {};
for (let name in params) {
const param = params[name];
if (isFn(param)) {
apiCallbacks[name] = tryCatch(param);
delete params[name];
}
}
const {
success,
fail,
cancel,
complete
} = apiCallbacks;
const hasSuccess = isFn(success);
const hasFail = isFn(fail);
const hasCancel = isFn(cancel);
const hasComplete = isFn(complete);
if (!hasSuccess && !hasFail && !hasCancel && !hasComplete) { // 无回调
return {
params
}
}
return {
errMsg: 'setStorage:ok'
const wrapperCallbacks = {};
for (let name in extras) {
const extra = extras[name];
if (isFn(extra)) {
wrapperCallbacks[name] = tryCatchFramework(extra);
delete extras[name];
}
}
}
function setStorageSync$1 (key, data) {
setStorage$1({
key,
data
});
}
const {
beforeSuccess,
afterSuccess,
beforeFail,
afterFail,
beforeCancel,
afterCancel,
afterAll
} = wrapperCallbacks;
function getStorage ({
key
} = {}) {
const data = localStorage.getItem(key);
return data ? {
data: JSON.parse(data).data,
errMsg: 'getStorage:ok'
} : {
data: '',
errMsg: 'getStorage:fail'
}
}
const callbackId = invokeCallbackId++;
const invokeCallbackName = 'api.' + apiName + '.' + callbackId;
function getStorageSync (key) {
const res = getStorage({
key
});
return res.data
}
const invokeCallback = function (res) {
res.errMsg = res.errMsg || apiName + ':ok';
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'
}
}
const errMsg = res.errMsg;
function removeStorageSync (key) {
removeStorage({
key
});
}
if (errMsg.indexOf(apiName + ':ok') === 0) {
isFn(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
isFn(afterSuccess) && afterSuccess(res);
} else if (errMsg.indexOf(apiName + ':cancel') === 0) {
res.errMsg = res.errMsg.replace(apiName + ':cancel', apiName + ':fail cancel');
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
};
function clearStorage () {
localStorage.clear();
return {
errMsg: 'clearStorage:ok'
params,
callbackId
}
}
function clearStorageSync () {
clearStorage();
}
function createInvokeCallback (apiName, params = {}, extras = {}) {
const {
params: args,
callbackId
} = createApiCallback(apiName, params, extras);
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 (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
return {
params: args,
callbackId: false
}
}
return {
params: args,
callbackId
}
}
function getStorageInfoSync () {
const res = getStorageInfo();
delete res.errMsg;
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
}
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 upx2px (number, newDeviceWidth) {
if (deviceWidth === 0) {
checkDeviceWidth();
function wrapperUnimplemented (name) {
return function (args) {
console.error('API `' + name + '` is not yet implemented');
}
}
number = Number(number);
if (number === 0) {
return 0
}
let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
if (result < 0) {
result = -result;
function wrapper (name, invokeMethod, extras) {
if (!isFn(invokeMethod)) {
return invokeMethod
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS) {
return 1
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 {
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 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,
const uni$1 = Object.create(null);
};
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;
})();
platformApis.keys().forEach(function (key) {
Object.assign(api, platformApis(key));
});
Object.keys(api).forEach(name => {
uni$1[name] = promisify(name, wrapper(name, api[name]));
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)
......@@ -30,11 +27,4 @@ export function subscribeHandler (event, args, pageId) {
export {
publishHandler
}
from 'uni-platform/service/bridge'
initOn(on, {
getApp: global.getApp,
getCurrentPages: global.getCurrentPages
})
initSubscribe(subscribe)
from 'uni-platform/service/bridge'
......@@ -10,7 +10,7 @@ import {
export default function initOn (on, {
getApp,
getCurrentPages
}) {
}) {
function onError (err) {
callAppHook(getApp(), 'onError', err)
}
......
......@@ -4,52 +4,55 @@ import {
callPageHook
} from '../plugins/util'
function createPageEvent (eventType) {
return function (args, pageId) {
const pages = getCurrentPages()
const page = pages.find(page => page.$page.id === pageId)
if (page) {
callPageHook(page, eventType, args)
} else {
console.error(`Not Found:Page[${pageId}]`)
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)
if (page) {
callPageHook(page, eventType, args)
} else {
console.error(`Not Found:Page[${pageId}]`)
}
}
}
}
const requestComponentInfoCallbacks = createCallbacks('requestComponentInfo')
const requestComponentInfoCallbacks = createCallbacks('requestComponentInfo')
function onRequestComponentInfo ({
reqId,
res
}) {
const callback = requestComponentInfoCallbacks.pop(reqId)
if (callback) {
callback(res)
function onRequestComponentInfo ({
reqId,
res
}) {
const callback = requestComponentInfoCallbacks.pop(reqId)
if (callback) {
callback(res)
}
}
}
const requestComponentObserverCallbacks = createCallbacks('requestComponentObserver')
function onRequestComponentObserver ({
reqId,
reqEnd,
res
}) {
const callback = requestComponentObserverCallbacks.get(reqId)
if (callback) {
if (reqEnd) {
requestComponentObserverCallbacks.pop(reqId)
return
const requestComponentObserverCallbacks = createCallbacks('requestComponentObserver')
function onRequestComponentObserver ({
reqId,
reqEnd,
res
}) {
const callback = requestComponentObserverCallbacks.get(reqId)
if (callback) {
if (reqEnd) {
requestComponentObserverCallbacks.pop(reqId)
return
}
callback(res)
}
callback(res)
}
}
export default function initSubscribe (subscribe) {
subscribe('onPageReady', createPageEvent('onReady'))
subscribe('onPageScroll', createPageEvent('onPageScroll'))
subscribe('onReachBottom', createPageEvent('onReachBottom'))
subscribe('onRequestComponentInfo', onRequestComponentInfo)
subscribe('onRequestComponentObserver', onRequestComponentObserver)
}
}
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
from './plugins/app'
......@@ -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))
})
......@@ -13,12 +25,22 @@ const platformApis = require.context(
'../../platforms/' + __PLATFORM__ + '/service/api',
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 = [
......@@ -20,14 +18,15 @@ export function getApp () {
return appCtx
}
function initGlobalListeners ({
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
export function initServiceJSBridge (Vue, instanceContext) {
export function initServiceJSBridge (Vue, instanceContext) {
if (bridge) {
return 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.
先完成此消息的编辑!
想要评论请 注册