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

refactor navigateBack

上级 7bb0cb54
......@@ -17,16 +17,27 @@ const external = []
if (process.env.UNI_SERVICE === 'legacy') {
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.js'
output.file = 'packages/uni-app-plus-nvue/dist/uni.js'
} else {
input = 'src/platforms/app-plus/service/index.js'
output.file = 'packages/uni-app-plus-nvue/dist/index.js'
output.format = 'iife'
output.name = 'serviceContext'
output.banner =
`export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, __registerPage, UniServiceJSBridge, getApp, getCurrentPages){
`export function createServiceContext(Vue, weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge){
var localStorage = plus.storage
var setTimeout = global.setTimeout
var clearTimeout = global.clearTimeout
`
output.footer =
`
var uni = serviceContext.uni
var getApp = serviceContext.getApp
var getCurrentPages = serviceContext.getCurrentPages
var __registerPage = serviceContext.__registerPage
return serviceContext \n}
`
output.footer = '\n return uni$1 \n}'
} else {
external.push('./uni')
}
module.exports = {
......@@ -40,7 +51,7 @@ module.exports = {
'uni-core': path.resolve(__dirname, '../src/core'),
'uni-platform': path.resolve(__dirname, '../src/platforms/' + process.env.UNI_PLATFORM),
'uni-platforms': path.resolve(__dirname, '../src/platforms'),
'uni-shared': path.resolve(__dirname, '../src/shared/util.js'),
'uni-shared': path.resolve(__dirname, '../src/shared/index.js'),
'uni-helpers': path.resolve(__dirname, '../src/core/helpers')
}),
replace({
......
......@@ -6,8 +6,7 @@
"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:all": "npm run lint && npm run build:app:nvue && npm run build:app:legacy",
"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",
......
因为 它太大了无法显示 source diff 。你可以改为 查看blob
let supportsPassive = false;
try {
const opts = {};
Object.defineProperty(opts, 'passive', ({
get () {
/* istanbul ignore next */
supportsPassive = true;
}
})); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function isFn (fn) {
......
export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, __registerPage, UniServiceJSBridge, getApp, getCurrentPages){
var localStorage = plus.storage
const _toString = Object.prototype.toString;
const hasOwnProperty = Object.prototype.hasOwnProperty;
function isFn (fn) {
return typeof fn === 'function'
}
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
function toRawType (val) {
return _toString.call(val).slice(8, -1)
}
function getLen (str = '') {
/* eslint-disable no-control-regex */
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);
}
}
}
const HOOKS = [
'invoke',
'success',
'fail',
'complete',
'returnValue'
];
const globalInterceptors = {};
const scopedInterceptors = {};
function mergeHook (parentVal, childVal) {
const res = childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal : [childVal]
: parentVal;
return res
? dedupeHooks(res)
: res
}
function dedupeHooks (hooks) {
const res = [];
for (let i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res
}
function removeHook (hooks, hook) {
const index = hooks.indexOf(hook);
if (index !== -1) {
hooks.splice(index, 1);
}
}
function mergeInterceptorHook (interceptor, option) {
Object.keys(option).forEach(hook => {
if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
interceptor[hook] = mergeHook(interceptor[hook], option[hook]);
}
});
}
function removeInterceptorHook (interceptor, option) {
if (!interceptor || !option) {
return
}
Object.keys(option).forEach(hook => {
if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
removeHook(interceptor[hook], option[hook]);
}
});
}
function addInterceptor (method, option) {
if (typeof method === 'string' && isPlainObject(option)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), option);
} else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method);
}
}
function removeInterceptor (method, option) {
if (typeof method === 'string') {
if (isPlainObject(option)) {
removeInterceptorHook(scopedInterceptors[method], option);
} else {
delete scopedInterceptors[method];
}
} else if (isPlainObject(method)) {
removeInterceptorHook(globalInterceptors, method);
}
}
function wrapperHook (hook) {
return function (data) {
return hook(data) || data
}
}
function isPromise (obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
function queue (hooks, data) {
let promise = false;
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i];
if (promise) {
promise = Promise.then(wrapperHook(hook));
} else {
const res = hook(data);
if (isPromise(res)) {
promise = Promise.resolve(res);
}
if (res === false) {
return {
then () {}
}
}
}
}
return promise || {
then (callback) {
return callback(data)
}
}
}
function wrapperOptions (interceptor, options = {}) {
['success', 'fail', 'complete'].forEach(name => {
if (Array.isArray(interceptor[name])) {
const oldCallback = options[name];
options[name] = function callbackInterceptor (res) {
queue(interceptor[name], res).then((res) => {
/* eslint-disable no-mixed-operators */
return isFn(oldCallback) && oldCallback(res) || res
});
};
}
});
return options
}
function wrapperReturnValue (method, returnValue) {
const returnValueHooks = [];
if (Array.isArray(globalInterceptors.returnValue)) {
returnValueHooks.push(...globalInterceptors.returnValue);
}
const interceptor = scopedInterceptors[method];
if (interceptor && Array.isArray(interceptor.returnValue)) {
returnValueHooks.push(...interceptor.returnValue);
}
returnValueHooks.forEach(hook => {
returnValue = hook(returnValue) || returnValue;
});
return returnValue
}
function getApiInterceptorHooks (method) {
const interceptor = Object.create(null);
Object.keys(globalInterceptors).forEach(hook => {
if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice();
}
});
const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
}
});
}
return interceptor
}
function invokeApi (method, api, options, ...params) {
const interceptor = getApiInterceptorHooks(method);
if (interceptor && Object.keys(interceptor).length) {
if (Array.isArray(interceptor.invoke)) {
const res = queue(interceptor.invoke, options);
return res.then((options) => {
return api(wrapperOptions(interceptor, options), ...params)
})
} else {
return api(wrapperOptions(interceptor, options), ...params)
}
}
return api(options, ...params)
}
const promiseInterceptor = {
returnValue (res) {
if (!isPromise(res)) {
return res
}
return res.then(res => {
return res[1]
}).catch(res => {
return res[0]
})
}
};
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 = [{
name: 'schema',
type: String,
required: true
}];
var require_context_module_1_0 = /*#__PURE__*/Object.freeze({
canIUse: canIUse
});
const base64ToArrayBuffer = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}];
var require_context_module_1_1 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer,
arrayBufferToBase64: arrayBufferToBase64
});
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: {
type: Number,
validator: getInt('height')
},
destWidth: {
type: Number,
validator: getInt('destWidth')
},
destHeight: {
type: Number,
validator: getInt('destHeight')
},
canvasId: {
type: String,
require: true
},
fileType: {
type: String,
validator (value, params) {
value = (value || '').toUpperCase();
params.fileType = value in fileType ? fileType[value] : fileType.PNG;
}
},
quality: {
type: Number,
validator (value, params) {
value = Math.floor(value);
params.quality = value > 0 && value < 1 ? value : 1;
}
}
};
const drawCanvas = {
canvasId: {
type: String,
require: true
},
actions: {
type: Array,
require: true
},
reserve: {
type: Boolean,
default: false
}
};
var require_context_module_1_2 = /*#__PURE__*/Object.freeze({
canvasGetImageData: canvasGetImageData,
canvasPutImageData: canvasPutImageData,
canvasToTempFilePath: canvasToTempFilePath,
drawCanvas: drawCanvas
});
const validator = [{
name: 'id',
type: String,
required: true
}];
const createAudioContext = validator;
const createVideoContext = validator;
const createMapContext = validator;
const createCanvasContext = [{
name: 'canvasId',
type: String,
required: true
}, {
name: 'componentInstance',
type: Object
}];
var require_context_module_1_3 = /*#__PURE__*/Object.freeze({
createAudioContext: createAudioContext,
createVideoContext: createVideoContext,
createMapContext: createMapContext,
createCanvasContext: createCanvasContext
});
const makePhoneCall = {
'phoneNumber': {
type: String,
required: true,
validator (phoneNumber) {
if (!phoneNumber) {
return `makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;`
}
}
}
};
var require_context_module_1_4 = /*#__PURE__*/Object.freeze({
makePhoneCall: makePhoneCall
});
const openDocument = {
filePath: {
type: String,
required: true
},
fileType: {
type: String
}
};
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
openDocument: openDocument
});
const type = {
WGS84: 'WGS84',
GCJ02: 'GCJ02'
};
const getLocation = {
type: {
type: String,
validator (value, params) {
value = (value || '').toUpperCase();
params.type = Object.values(type).indexOf(value) < 0 ? type.WGS84 : value;
},
default: type.WGS84
},
altitude: {
altitude: Boolean,
default: false
}
};
const openLocation = {
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
},
scale: {
type: Number,
validator (value, params) {
value = Math.floor(value);
params.scale = value >= 5 && value <= 18 ? value : 18;
},
default: 18
},
name: {
type: String
},
address: {
type: String
}
};
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
getLocation: getLocation,
openLocation: openLocation
});
const SIZE_TYPES = ['original', 'compressed'];
const SOURCE_TYPES = ['album', 'camera'];
const chooseImage = {
'count': {
type: Number,
required: false,
default: 9,
validator (count, params) {
if (count <= 0) {
params.count = 9;
}
}
},
'sizeType': {
type: Array,
required: false,
default: SIZE_TYPES,
validator (sizeType, params) {
// 非必传的参数,不符合预期时处理为默认值。
const length = sizeType.length;
if (!length) {
params.sizeType = SIZE_TYPES;
} else {
for (let i = 0; i < length; i++) {
if (typeof sizeType[i] !== 'string' || !~SIZE_TYPES.indexOf(sizeType[i])) {
params.sizeType = SIZE_TYPES;
break
}
}
}
}
},
'sourceType': {
type: Array,
required: false,
default: SOURCE_TYPES,
validator (sourceType, params) {
const length = sourceType.length;
if (!length) {
params.sourceType = SOURCE_TYPES;
} else {
for (let i = 0; i < length; i++) {
if (typeof sourceType[i] !== 'string' || !~SOURCE_TYPES.indexOf(sourceType[i])) {
params.sourceType = SOURCE_TYPES;
break
}
}
}
}
}
};
var require_context_module_1_7 = /*#__PURE__*/Object.freeze({
chooseImage: chooseImage
});
const SOURCE_TYPES$1 = ['album', 'camera'];
const chooseVideo = {
'sourceType': {
type: Array,
required: false,
default: SOURCE_TYPES$1,
validator (sourceType, params) {
const length = sourceType.length;
if (!length) {
params.sourceType = SOURCE_TYPES$1;
} else {
for (let i = 0; i < length; i++) {
if (typeof sourceType[i] !== 'string' || !~SOURCE_TYPES$1.indexOf(sourceType[i])) {
params.sourceType = SOURCE_TYPES$1;
break
}
}
}
}
}
};
var require_context_module_1_8 = /*#__PURE__*/Object.freeze({
chooseVideo: chooseVideo
});
function getRealRoute (fromRoute, toRoute) {
if (!toRoute) {
toRoute = fromRoute;
if (toRoute.indexOf('/') === 0) {
return toRoute
}
const pages = getCurrentPages();
if (pages.length) {
fromRoute = pages[pages.length - 1].$page.route;
} else {
fromRoute = '';
}
} else {
if (toRoute.indexOf('/') === 0) {
return toRoute
}
}
if (toRoute.indexOf('./') === 0) {
return getRealRoute(fromRoute, toRoute.substr(2))
}
const toRouteArray = toRoute.split('/');
const toRouteLength = toRouteArray.length;
let i = 0;
for (; i < toRouteLength && toRouteArray[i] === '..'; i++) {
// noop
}
toRouteArray.splice(0, i);
toRoute = toRouteArray.join('/');
const fromRouteArray = fromRoute.length > 0 ? fromRoute.split('/') : [];
fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
return '/' + fromRouteArray.concat(toRouteArray).join('/')
}
const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const BASE64_RE = /^data:[a-z-]+\/[a-z-]+;base64,/;
function addBase (filePath) {
return filePath
}
function getRealPath (filePath) {
if (filePath.indexOf('/') === 0) {
if (filePath.indexOf('//') === 0) {
filePath = 'https:' + filePath;
} else {
return addBase(filePath.substr(1))
}
}
// 网络资源或base64
if (SCHEME_RE.test(filePath) || BASE64_RE.test(filePath) || filePath.indexOf('blob:') === 0) {
return filePath
}
const pages = getCurrentPages();
if (pages.length) {
return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1))
}
return filePath
}
const getImageInfo = {
'src': {
type: String,
required: true,
validator (src, params) {
params.src = getRealPath(src);
}
}
};
var require_context_module_1_9 = /*#__PURE__*/Object.freeze({
getImageInfo: getImageInfo
});
const previewImage = {
urls: {
type: Array,
required: true,
validator (value, params) {
var typeError;
params.urls = value.map(url => {
if (typeof url === 'string') {
return getRealPath(url)
} else {
typeError = true;
}
});
if (typeError) {
return 'url is not string'
}
}
},
current: {
type: [String, Number],
validator (value, params) {
if (typeof value === 'number') {
params.current = value > 0 && value < params.urls.length ? value : 0;
} else if (typeof value === 'string' && value) {
params.current = getRealPath(value);
}
},
default: 0
}
};
var require_context_module_1_10 = /*#__PURE__*/Object.freeze({
previewImage: previewImage
});
const FRONT_COLORS = ['#ffffff', '#000000'];
const setNavigationBarColor = {
'frontColor': {
type: String,
required: true,
validator (frontColor, params) {
if (FRONT_COLORS.indexOf(frontColor) === -1) {
return `invalid frontColor "${frontColor}"`
}
}
},
'backgroundColor': {
type: String,
required: true
},
'animation': {
type: Object,
default () {
return {
duration: 0,
timingFunc: 'linear'
}
},
validator (animation = {}, params) {
params.animation = {
duration: animation.duration || 0,
timingFunc: animation.timingFunc || 'linear'
};
}
}
};
const setNavigationBarTitle = {
'title': {
type: String,
required: true
}
};
var require_context_module_1_11 = /*#__PURE__*/Object.freeze({
setNavigationBarColor: setNavigationBarColor,
setNavigationBarTitle: setNavigationBarTitle
});
const downloadFile = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
}
};
var require_context_module_1_12 = /*#__PURE__*/Object.freeze({
downloadFile: downloadFile
});
const method = {
OPTIONS: 'OPTIONS',
GET: 'GET',
HEAD: 'HEAD',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
TRACE: 'TRACE',
CONNECT: 'CONNECT'
};
const dataType = {
JSON: 'JSON'
};
const responseType = {
TEXT: 'TEXT',
ARRAYBUFFER: 'ARRAYBUFFER'
};
const request = {
url: {
type: String,
required: true
},
data: {
type: [Object, String, ArrayBuffer],
validator (value, params) {
params.data = value || '';
}
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
},
method: {
type: String,
validator (value, params) {
value = (value || '').toUpperCase();
params.method = Object.values(method).indexOf(value) < 0 ? method.GET : value;
}
},
dataType: {
type: String,
validator (value, params) {
params.dataType = (value || dataType.JSON).toUpperCase();
}
},
responseType: {
type: String,
validator (value, params) {
value = (value || '').toUpperCase();
params.responseType = Object.values(responseType).indexOf(value) < 0 ? responseType.TEXT : value;
}
}
};
var require_context_module_1_13 = /*#__PURE__*/Object.freeze({
request: request
});
const method$1 = {
OPTIONS: 'OPTIONS',
GET: 'GET',
HEAD: 'HEAD',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
TRACE: 'TRACE',
CONNECT: 'CONNECT'
};
const connectSocket = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
},
method: {
type: String,
validator (value, params) {
value = (value || '').toUpperCase();
params.method = Object.values(method$1).indexOf(value) < 0 ? method$1.GET : value;
}
},
protocols: {
type: Array,
validator (value, params) {
params.protocols = (value || []).filter(str => typeof str === 'string');
}
}
};
const sendSocketMessage = {
data: {
type: [String, ArrayBuffer]
}
};
const closeSocket = {
code: {
type: Number
},
reason: {
type: String
}
};
var require_context_module_1_14 = /*#__PURE__*/Object.freeze({
connectSocket: connectSocket,
sendSocketMessage: sendSocketMessage,
closeSocket: closeSocket
});
const uploadFile = {
url: {
type: String,
required: true
},
filePath: {
type: String,
required: true,
validator (value, params) {
params.type = getRealPath(value);
}
},
name: {
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
}
}
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
});
}
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);
};
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
}
}
const wrapperCallbacks = {};
for (let name in extras) {
const extra = extras[name];
if (isFn(extra)) {
wrapperCallbacks[name] = tryCatchFramework(extra);
delete extras[name];
}
}
const {
beforeSuccess,
afterSuccess,
beforeFail,
afterFail,
beforeCancel,
afterCancel,
afterAll
} = wrapperCallbacks;
const callbackId = invokeCallbackId++;
const invokeCallbackName = 'api.' + apiName + '.' + callbackId;
const invokeCallback = function (res) {
res.errMsg = res.errMsg || apiName + ':ok';
const errMsg = res.errMsg;
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
};
return {
params,
callbackId
}
}
function createInvokeCallback (apiName, params = {}, extras = {}) {
const {
params: args,
callbackId
} = createApiCallback(apiName, params, extras);
if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
return {
params: args,
callbackId: false
}
}
return {
params: args,
callbackId
}
}
function invokeCallbackHandler (invokeCallbackId, res) {
if (typeof invokeCallbackId === 'number') {
const invokeCallback = invokeCallbacks[invokeCallbackId];
if (invokeCallback) {
if (!invokeCallback.keepAlive) {
delete invokeCallbacks[invokeCallbackId];
}
return invokeCallback.callback(res)
}
}
return res
}
function wrapperUnimplemented (name) {
return function todo (args) {
console.error('API `' + name + '` is not yet implemented');
}
}
function wrapper (name, invokeMethod, extras) {
if (!isFn(invokeMethod)) {
return invokeMethod
}
return function (...args) {
if (isSyncApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod.apply(null, args)
}
} else if (isCallbackApi(name)) {
if (validateParams(name, args, -1)) {
return invokeMethod(createKeepAliveApiCallback(name, args[0]))
}
} else {
let argsObj = {};
if (args.length) {
argsObj = args[0];
}
const {
params,
callbackId
} = createInvokeCallback(name, argsObj, extras);
if (callbackId !== false) {
let res;
if (isFn(params)) {
res = invokeMethod(callbackId);
} else {
res = invokeMethod(params, callbackId);
}
if (res && !isTaskApi(name)) {
res = invokeCallbackHandler(callbackId, res);
if (isPlainObject(res)) {
res.errMsg = res.errMsg || name + ':ok';
}
}
return res
}
}
}
}
UniServiceJSBridge.publishHandler = UniServiceJSBridge.emit;
UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler;
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
];
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var base64Arraybuffer = createCommonjsModule(function (module, exports) {
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(){
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Use a lookup table to find the index.
var lookup = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i+1)];
encoded3 = lookup[base64.charCodeAt(i+2)];
encoded4 = lookup[base64.charCodeAt(i+3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})();
});
var base64Arraybuffer_1 = base64Arraybuffer.encode;
var base64Arraybuffer_2 = base64Arraybuffer.decode;
const base64ToArrayBuffer$1 = base64Arraybuffer_2;
const arrayBufferToBase64$1 = base64Arraybuffer_1;
var require_context_module_0_0 = /*#__PURE__*/Object.freeze({
base64ToArrayBuffer: base64ToArrayBuffer$1,
arrayBufferToBase64: arrayBufferToBase64$1
});
var platformSchema = {};
// TODO 待处理其他 API 的检测
function canIUse$1 (schema) {
if (hasOwn(platformSchema, schema)) {
return platformSchema[schema]
}
return true
}
var require_context_module_0_1 = /*#__PURE__*/Object.freeze({
canIUse: canIUse$1
});
const interceptors = {
promiseInterceptor
};
var require_context_module_0_2 = /*#__PURE__*/Object.freeze({
interceptors: interceptors,
addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor
});
const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS = false;
let deviceWidth = 0;
let deviceDPR = 0;
function checkDeviceWidth () {
const {
platform,
pixelRatio,
windowWidth
} = uni.getSystemInfoSync();
deviceWidth = windowWidth;
deviceDPR = pixelRatio;
isIOS = platform === 'ios';
}
function upx2px (number, newDeviceWidth) {
if (deviceWidth === 0) {
checkDeviceWidth();
}
number = Number(number);
if (number === 0) {
return 0
}
let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
if (result < 0) {
result = -result;
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS) {
return 1
} else {
return 0.5
}
}
return number < 0 ? -result : result
}
var require_context_module_0_3 = /*#__PURE__*/Object.freeze({
upx2px: upx2px
});
function setStorage$1 ({
key,
data
} = {}) {
const value = {
type: typeof data === 'object' ? 'object' : 'string',
data: data
};
localStorage.setItem(key, JSON.stringify(value));
const keyList = localStorage.getItem('uni-storage-keys');
if (!keyList) {
localStorage.setItem('uni-storage-keys', JSON.stringify([key]));
} else {
const keys = JSON.parse(keyList);
if (keys.indexOf(key) < 0) {
keys.push(key);
localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
}
}
return {
errMsg: 'setStorage:ok'
}
}
function setStorageSync$1 (key, data) {
setStorage$1({
key,
data
});
}
function getStorage ({
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_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
});
function pageScrollTo$1 (args) {
const pages = getCurrentPages();
if (pages.length) {
UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
}
return {}
}
var require_context_module_0_5 = /*#__PURE__*/Object.freeze({
pageScrollTo: pageScrollTo$1
});
const api = Object.create(null);
const modules$1 =
(function() {
var map = {
'./base/base64.js': require_context_module_0_0,
'./base/can-i-use.js': require_context_module_0_1,
'./base/interceptor.js': require_context_module_0_2,
'./base/upx2px.js': require_context_module_0_3,
'./storage/storage.js': require_context_module_0_4,
'./ui/page-scroll-to.js': require_context_module_0_5,
};
var req = function req(key) {
return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
};
req.keys = function() {
return Object.keys(map);
};
return req;
})();
modules$1.keys().forEach(function (key) {
Object.assign(api, modules$1(key));
});
const SUCCESS = 'success';
const FAIL = 'fail';
const COMPLETE = 'complete';
const CALLBACKS = [SUCCESS, FAIL, COMPLETE];
/**
* 调用无参数,或仅一个参数且为 callback 的 API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethodWithoutArgs (vm, method, args, extras) {
if (!vm) {
return
}
if (typeof args === 'undefined') {
return vm[method]()
}
const [, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method]()
}
return vm[method](normalizeCallback(method, callbacks))
}
/**
* 调用两个参数(第一个入参为普通参数,第二个入参为 callback) API
* @param {Object} vm
* @param {Object} method
* @param {Object} args
* @param {Object} extras
*/
function invokeVmMethod (vm, method, args, extras) {
if (!vm) {
return
}
const [pureArgs, callbacks] = normalizeArgs(args, extras);
if (!Object.keys(callbacks).length) {
return vm[method](pureArgs)
}
return vm[method](pureArgs, normalizeCallback(method, callbacks))
}
function findElmById (id, vm) {
return findElmByVNode(id, vm._vnode)
}
function findElmByVNode (id, vnode) {
if (!id || !vnode) {
return
}
if (
vnode.data &&
vnode.data.attrs &&
vnode.data.attrs.id === id
) {
return vnode.elm
}
const children = vnode.children;
if (!children) {
return
}
for (let i = 0, len = children.length; i < len; i++) {
const elm = findElmByVNode(id, children[i]);
if (elm) {
return elm
}
}
}
function normalizeArgs (args = {}, extras) {
const callbacks = Object.create(null);
const iterator = function iterator (name) {
const callback = args[name];
if (isFn(callback)) {
callbacks[name] = callback;
delete args[name];
}
};
CALLBACKS.forEach(iterator);
extras && extras.forEach(iterator);
return [args, callbacks]
}
function normalizeCallback (method, callbacks) {
return function weexCallback (ret) {
const type = ret.type;
delete ret.type;
const callback = callbacks[type];
if (type === SUCCESS) {
ret.errMsg = `${method}:ok`;
} else if (type === FAIL) {
ret.errMsg = method + ':fail' + (ret.msg ? (' ' + ret.msg) : '');
}
delete ret.code;
delete ret.msg;
isFn(callback) && callback(ret);
if (type === SUCCESS || type === FAIL) {
const complete = callbacks['complete'];
isFn(complete) && complete(ret);
}
}
}
class LivePusherContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
start (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'start', cbs)
}
stop (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stop', cbs)
}
pause (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pause', cbs)
}
resume (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resume', cbs)
}
switchCamera (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', cbs)
}
snapshot (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', cbs)
}
toggleTorch (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', cbs)
}
playBGM (args) {
return invokeVmMethod(this.ctx, 'playBGM', args)
}
stopBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', cbs)
}
pauseBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', cbs)
}
resumeBGM (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', cbs)
}
setBGMVolume (cbs) {
return invokeVmMethod(this.ctx, 'setBGMVolume', cbs)
}
startPreview (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', cbs)
}
stopPreview (args) {
return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args)
}
}
function createLivePusherContext (id, vm) {
if (!vm) {
return console.warn('uni.createLivePusherContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new LivePusherContext(id, elm)
}
class MapContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
getCenterLocation (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getCenterLocation', cbs)
}
moveToLocation () {
return invokeVmMethodWithoutArgs(this.ctx, 'moveToLocation')
}
translateMarker (args) {
return invokeVmMethod(this.ctx, 'translateMarker', args, ['animationEnd'])
}
includePoints (args) {
return invokeVmMethod(this.ctx, 'includePoints', args)
}
getRegion (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getRegion', cbs)
}
getScale (cbs) {
return invokeVmMethodWithoutArgs(this.ctx, 'getScale', cbs)
}
}
function createMapContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createMapContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new MapContext(id, elm)
}
class VideoContext {
constructor (id, ctx) {
this.id = id;
this.ctx = ctx;
}
play () {
return invokeVmMethodWithoutArgs(this.ctx, 'play')
}
pause () {
return invokeVmMethodWithoutArgs(this.ctx, 'pause')
}
seek (args) {
return invokeVmMethod(this.ctx, 'seek', args)
}
stop () {
return invokeVmMethodWithoutArgs(this.ctx, 'stop')
}
sendDanmu (args) {
return invokeVmMethod(this.ctx, 'sendDanmu', args)
}
playbackRate (args) {
return invokeVmMethod(this.ctx, 'playbackRate', args)
}
requestFullScreen (args) {
return invokeVmMethod(this.ctx, 'requestFullScreen', args)
}
exitFullScreen () {
return invokeVmMethodWithoutArgs(this.ctx, 'exitFullScreen')
}
showStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'showStatusBar')
}
hideStatusBar () {
return invokeVmMethodWithoutArgs(this.ctx, 'hideStatusBar')
}
}
function createVideoContext$1 (id, vm) {
if (!vm) {
return console.warn('uni.createVideoContext 必须传入第二个参数,即当前 vm 对象(this)')
}
const elm = findElmById(id, vm);
if (!elm) {
return console.warn('Can not find `' + id + '`')
}
return new VideoContext(id, elm)
}
function requireNativePlugin (name) {
return weex.requireModule(name)
}
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$1 ({
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'
});
}
}
function navigateTo$1 ({
url,
animationType,
animationDuration
}) {
const path = url.split('?')[0];
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
path
});
showWebview(
__registerPage({
path
}),
animationType,
animationDuration
);
}
function reLaunch$1 ({
path
}) {}
function redirectTo$1 ({
path
}) {}
function switchTab$1 ({
path
}) {}
var api$1 = /*#__PURE__*/Object.freeze({
createLivePusherContext: createLivePusherContext,
createMapContext: createMapContext$1,
createVideoContext: createVideoContext$1,
requireNativePlugin: requireNativePlugin,
navigateBack: navigateBack$1,
navigateTo: navigateTo$1,
reLaunch: reLaunch$1,
redirectTo: redirectTo$1,
switchTab: switchTab$1
});
const api$2 = Object.assign(Object.create(null), api, api$1);
const uni$1 = Object.create(null);
apis.forEach(name => {
if (api$2[name]) {
uni$1[name] = promisify(name, wrapper(name, api$2[name]));
} else {
uni$1[name] = wrapperUnimplemented(name);
}
});
return uni$1
}
因为 它太大了无法显示 source diff 。你可以改为 查看blob
import {
isPlainObject
} from 'uni-shared'
const method = {
OPTIONS: 'OPTIONS',
GET: 'GET',
......@@ -15,10 +19,41 @@ const responseType = {
TEXT: 'TEXT',
ARRAYBUFFER: 'ARRAYBUFFER'
}
const encode = encodeURIComponent
function stringifyQuery (url, data) {
let str = url.split('#')
const hash = str[1] || ''
str = str[0].split('?')
let query = str[1] || ''
url = str[0]
const search = query.split('&').filter(item => item)
query = {}
search.forEach(item => {
item = item.split('=')
query[item[0]] = item[1]
})
for (let key in data) {
if (data.hasOwnProperty(key)) {
if (isPlainObject(data[key])) {
query[encode(key)] = encode(JSON.stringify(data[key]))
} else {
query[encode(key)] = encode(data[key])
}
}
}
query = Object.keys(query).map(item => `${item}=${query[item]}`).join('&')
return url + (query ? '?' + query : '') + (hash ? '#' + hash : '')
}
export const request = {
url: {
method: {
type: String,
required: true
validator (value, params) {
value = (value || '').toUpperCase()
params.method = Object.values(method).indexOf(value) < 0 ? method.GET : value
}
},
data: {
type: [Object, String, ArrayBuffer],
......@@ -26,17 +61,23 @@ export const request = {
params.data = value || ''
}
},
header: {
type: Object,
url: {
type: String,
required: true,
validator (value, params) {
params.header = value || {}
if (
params.method === method.GET &&
isPlainObject(params.data) &&
Object.keys(params.data).length
) { // 将 method,data 校验提前,保证 url 校验时,method,data 已被格式化
params.url = stringifyQuery(value, params.data)
}
}
},
method: {
type: String,
header: {
type: Object,
validator (value, params) {
value = (value || '').toUpperCase()
params.method = Object.values(method).indexOf(value) < 0 ? method.GET : value
params.header = value || {}
}
},
dataType: {
......
import {
isPlainObject
} from 'uni-shared'
import {
invoke
} from 'uni-core/service/bridge'
import {
onMethod,
invokeMethod
} from '../../platform'
const requestTasks = Object.create(null)
function formatResponse (res, args) {
if (
typeof res.data === 'string' &&
res.data.charCodeAt(0) === 65279
) {
res.data = res.data.substr(1)
}
res.statusCode = parseInt(res.statusCode, 10)
if (isPlainObject(res.header)) {
res.header = Object.keys(res.header).reduce(function (ret, key) {
const value = res.header[key]
if (Array.isArray(value)) {
ret[key] = value.join(',')
} else if (typeof value === 'string') {
ret[key] = value
}
return ret
}, {})
}
if (args.dataType && args.dataType.toLowerCase() === 'json') {
try {
res.data = JSON.parse(res.data)
} catch (e) {}
}
return res
}
onMethod('onRequestTaskStateChange', function ({
requestTaskId,
state,
data,
statusCode,
header,
errMsg
}) {
const {
args,
callbackId
} = requestTasks[requestTaskId]
if (!callbackId) {
return
}
delete requestTasks[requestTaskId]
switch (state) {
case 'success':
invoke(callbackId, formatResponse({
data,
statusCode,
header,
errMsg: 'request:ok'
}, args))
break
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
})
break
}
})
class RequestTask {
constructor (id) {
this.id = id
}
abort () {
invokeMethod('operateRequestTask', {
requestTaskId: this.id,
operationType: 'abort'
})
}
offHeadersReceived () {
}
onHeadersReceived () {
}
}
export function request (args, callbackId) {
const {
requestTaskId
} = invokeMethod('createRequestTask', args)
requestTasks[requestTaskId] = {
args,
callbackId
}
return new RequestTask(requestTaskId)
}
import api from 'uni-platform/service/api'
export function unpack (args) {
return args
}
......@@ -7,19 +5,3 @@ export function unpack (args) {
export function invoke (...args) {
return UniServiceJSBridge.invokeCallbackHandler(...args)
}
/**
* 执行内部平台方法
*/
export function invokeMethod (name, ...args) {
return api[name].apply(null, args)
}
/**
* 监听 service 层内部平台方法回调,与 publish 对应
* @param {Object} name
* @param {Object} callback
*/
export function onMethod (name, callback) {
return UniServiceJSBridge.on('api.' + name, callback)
}
import api from 'uni-platform/service/api'
/**
* 执行内部平台方法
*/
export function invokeMethod (name, ...args) {
return api[name].apply(null, args)
}
/**
* 监听 service 层内部平台方法回调,与 publish 对应
* @param {Object} name
* @param {Object} callback
*/
export function onMethod (name, callback) {
return UniServiceJSBridge.on('api.' + name, callback)
}
import * as api from './api/index'
import * as appApi from '../../app-plus/service/api/index'
import * as nvueApi from './api/index'
export default api
export default Object.assign(Object.create(null), appApi, nvueApi)
......@@ -2,17 +2,13 @@ import {
ANI_DURATION
} from './util'
import {
setStatusBarStyle
} from '../../bridge'
let firstBackTime = 0
export function navigateBack ({
delta,
animationType,
animationDuration
}) {
const pages = getCurrentPages()
const len = pages.length - 1
const page = pages[len]
if (page.$page.meta.isQuit) {
function quit() {
if (!firstBackTime) {
firstBackTime = Date.now()
plus.nativeUI.toast('再按一次退出应用')
......@@ -22,15 +18,68 @@ export function navigateBack ({
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit()
}
}
function backWebview(webview, callback) {
if (!webview.__uniapp_webview) {
return callback()
}
const children = webview.children()
if (!children || !children.length) { // 有子 webview
return callback()
}
const childWebview = children[0]
childWebview.canBack(({
canBack
}) => {
if (canBack) {
childWebview.back() // webview 返回
} else {
pages.splice(len, 1)
callback()
}
})
}
function back(delta, animationType, animationDuration) {
const pages = getCurrentPages()
const len = pages.length
const currentPage = pages[len - 1]
if (delta > 1) {
// 中间页隐藏
pages.slice(len - delta, len - 1).reverse().forEach(deltaPage => {
deltaPage.$getAppWebview().close('none')
})
}
backWebview(currentPage, () => {
if (animationType) {
page.$getAppWebview().close(animationType, animationDuration || ANI_DURATION)
currentPage.$getAppWebview().close(animationType, animationDuration || ANI_DURATION)
} else {
page.$getAppWebview().close('auto')
currentPage.$getAppWebview().close('auto')
}
// 移除所有 page
pages.splice(len - delta, len)
setStatusBarStyle()
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateBack'
})
}
})
}
export function navigateBack({
delta,
animationType,
animationDuration
}) {
const pages = getCurrentPages()
const len = pages.length
uni.hideToast() // 后退时,关闭 toast,loading
pages[len - 1].$page.meta.isQuit ?
quit() :
back(delta, animationType, animationDuration)
}
import {
parseQuery
} from 'uni-shared'
import {
showWebview
} from './util'
import {
setStatusBarStyle
} from '../../bridge'
export function navigateTo ({
url,
animationType,
animationDuration
}) {
const path = url.split('?')[0]
const urls = url.split('?')
const path = urls[0]
const query = parseQuery(urls[1] || '')
UniServiceJSBridge.emit('onAppRoute', {
type: 'navigateTo',
......@@ -16,9 +27,12 @@ export function navigateTo ({
showWebview(
__registerPage({
path
path,
query
}),
animationType,
animationDuration
)
setStatusBarStyle()
}
......@@ -9,7 +9,7 @@ import {
TITLEBAR_HEIGHT
} from '../../constants'
import tabbar from '../../framework/tabbar'
import tabBar from '../../framework/tab-bar'
export function getSystemInfoSync () {
return callApiSync(getSystemInfo, Object.create(null), 'getSystemInfo', 'getSystemInfoSync')
......@@ -48,7 +48,7 @@ export function getSystemInfo () {
// TODO screenWidth,screenHeight
windowWidth: screenWidth,
windowHeight: Math.min(screenHeight - (titleNView ? (statusBarHeight + TITLEBAR_HEIGHT)
: 0) - (isTabBarPage() && tabbar.visible ? TABBAR_HEIGHT : 0), screenHeight),
: 0) - (isTabBarPage() && tabBar.visible ? TABBAR_HEIGHT : 0), screenHeight),
statusBarHeight,
language: plus.os.language,
system: plus.os.version,
......
......@@ -41,6 +41,7 @@ export * from './plugin/oauth'
export * from './plugin/payment'
export * from './plugin/push'
export * from './plugin/share'
export * from './plugin/event-bus'
export * from './ui/keyboard'
export * from './ui/navigation-bar'
......
const Emitter = new Vue()
function apply (ctx, method, args) {
return ctx[method].apply(ctx, args)
}
export function $on () {
return apply(Emitter, '$on', [...arguments])
}
export function $off () {
return apply(Emitter, '$off', [...arguments])
}
export function $once () {
return apply(Emitter, '$once', [...arguments])
}
export function $emit () {
return apply(Emitter, '$emit', [...arguments])
}
......@@ -2,14 +2,14 @@ import {
isTabBarPage
} from '../util'
import tabbar from '../../framework/tabbar'
import tabBar from '../../framework/tab-bar'
export function setTabBarBadge ({
index,
text,
type
}) {
tabbar.setTabBarBadge(type, index, text)
tabBar.setTabBarBadge(type, index, text)
return {
errMsg: 'setTabBarBadge:ok'
}
......@@ -26,7 +26,7 @@ export function setTabBarItem ({
errMsg: 'setTabBarItem:fail not TabBar page'
}
}
tabbar.setTabBarItem(index, text, iconPath, selectedIconPath)
tabBar.setTabBarItem(index, text, iconPath, selectedIconPath)
return {
errMsg: 'setTabBarItem:ok'
}
......@@ -43,7 +43,7 @@ export function setTabBarStyle ({
errMsg: 'setTabBarStyle:fail not TabBar page'
}
}
tabbar.setTabBarStyle({
tabBar.setTabBarStyle({
color,
selectedColor,
backgroundColor,
......@@ -62,7 +62,7 @@ export function hideTabBar ({
errMsg: 'hideTabBar:fail not TabBar page'
}
}
tabbar.hideTabBar(animation)
tabBar.hideTabBar(animation)
return {
errMsg: 'hideTabBar:ok'
}
......@@ -76,7 +76,7 @@ export function showTabBar ({
errMsg: 'showTabBar:fail not TabBar page'
}
}
tabbar.showTabBar(animation)
tabBar.showTabBar(animation)
return {
errMsg: 'showTabBar:ok'
}
......
......@@ -14,3 +14,25 @@ export function requireNativePlugin (name) {
export function publish (name, res) {
return UniServiceJSBridge.emit('api.' + name, res)
}
let lastStatusBarStyle
export function setStatusBarStyle (statusBarStyle) {
if (!statusBarStyle) {
const pages = getCurrentPages()
if (!pages.length) {
return
}
statusBarStyle = pages[pages.length - 1].$page.meta.statusBarStyle
if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) {
return
}
}
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] setStatusBarStyle`, statusBarStyle)
}
lastStatusBarStyle = statusBarStyle
plus.navigator.setStatusBarStyle(statusBarStyle)
}
......@@ -2,6 +2,22 @@ import {
callAppHook
} from 'uni-core/service/plugins/util'
import initOn from 'uni-core/service/bridge/on'
import {
getCurrentPages
} from './page'
import {
registerPlusMessage
} from './plus-message'
import {
isTabBarPage
} from '../api/util'
import tabBar from './tab-bar'
let appCtx
const NETWORK_TYPES = [
......@@ -18,14 +34,11 @@ export function getApp () {
return appCtx
}
function initGlobalListeners ({
uni,
plus,
UniServiceJSBridge
}) {
function initGlobalListeners () {
const emit = UniServiceJSBridge.emit
plus.key.addEventListener('backbutton', () => {
// TODO uni?
uni.navigateBack({
from: 'backbutton'
})
......@@ -48,9 +61,7 @@ function initGlobalListeners ({
})
}
function initAppLaunch (appVm, {
__uniConfig
}) {
function initAppLaunch (appVm) {
const args = {
path: __uniConfig.entryPagePath,
query: {},
......@@ -61,14 +72,55 @@ function initAppLaunch (appVm, {
callAppHook(appVm, 'onShow', args)
}
export function registerApp (appVm, instanceContext) {
function initTabBar () {
if (!__uniConfig.tabBar || !__uniConfig.tabBar.list.length) {
return
}
const currentTab = isTabBarPage(__uniConfig.entryPagePath)
if (currentTab) {
// 取当前 tab 索引值
__uniConfig.tabBar.selected = __uniConfig.tabBar.list.indexOf(currentTab)
// 如果真实的首页与 condition 都是 tabbar,无需启用 realEntryPagePath 机制
if (__uniConfig.realEntryPagePath && isTabBarPage(__uniConfig.realEntryPagePath)) {
delete __uniConfig.realEntryPagePath
}
}
__uniConfig.__ready__ = true
const onLaunchWebviewReady = function onLaunchWebviewReady () {
const tabBarView = tabBar.init(__uniConfig.tabBar, (item) => {
uni.switchTab({
url: '/' + item.pagePath,
openType: 'switchTab',
from: 'tabbar'
})
})
tabBarView && plus.webview.getLaunchWebview().append(tabBarView)
}
if (plus.webview.getLaunchWebview()) {
onLaunchWebviewReady()
} else {
registerPlusMessage('UniWebviewReady-' + plus.runtime.appid, onLaunchWebviewReady, false)
}
}
export function registerApp (appVm) {
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] registerApp`)
}
appCtx = appVm
initAppLaunch(appVm, instanceContext)
initOn(UniServiceJSBridge.on, {
getApp,
getCurrentPages
})
initAppLaunch(appVm)
initGlobalListeners()
initGlobalListeners(instanceContext)
initTabBar()
}
import initOn from 'uni-core/service/bridge/on'
let bridge
export function initServiceJSBridge (Vue, instanceContext) {
if (bridge) {
return bridge
}
const Emitter = new Vue()
bridge = {
on: Emitter.$on.bind(Emitter),
off: Emitter.$off.bind(Emitter),
once: Emitter.$once.bind(Emitter),
emit: Emitter.$emit.bind(Emitter)
}
initOn(bridge.on, instanceContext)
return bridge
}
export const uniConfig = Object.create(null)
export const uniRoutes = []
function parseRoutes (config) {
uniRoutes.length = 0
__uniRoutes.length = 0
/* eslint-disable no-mixed-operators */
const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath)
......@@ -10,7 +7,7 @@ function parseRoutes (config) {
const isTabBar = tabBarList.indexOf(pagePath) !== -1
const isQuit = isTabBar || (config.pages[0] === pagePath)
const isNVue = !!config.page[pagePath].nvue
uniRoutes.push({
__uniRoutes.push({
path: '/' + pagePath,
meta: {
isQuit,
......@@ -22,22 +19,20 @@ function parseRoutes (config) {
})
}
export function registerConfig (config, {
plus
}) {
Object.assign(uniConfig, config)
export function registerConfig (config) {
Object.assign(__uniConfig, config)
uniConfig.viewport = ''
uniConfig.defaultFontSize = ''
__uniConfig.viewport = ''
__uniConfig.defaultFontSize = ''
if (uniConfig.nvueCompiler === 'uni-app') {
uniConfig.viewport = plus.screen.resolutionWidth
uniConfig.defaultFontSize = uniConfig.viewport / 20
if (__uniConfig.nvueCompiler === 'uni-app') {
__uniConfig.viewport = plus.screen.resolutionWidth
__uniConfig.defaultFontSize = __uniConfig.viewport / 20
}
parseRoutes(uniConfig)
parseRoutes(__uniConfig)
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] registerConfig`, uniConfig)
console.log(`[uni-app] registerConfig`, __uniConfig)
}
}
import {
getApp,
registerApp
} from './app'
import {
registerPage,
getCurrentPages
} from './page'
import {
uniConfig,
uniRoutes,
registerConfig
} from './config'
import {
createUniInstance
} from './uni'
import {
initServiceJSBridge
} from './bridge'
let uni
export function createInstanceContext (instanceContext) {
const {
weex,
Vue,
WeexPlus
} = instanceContext
const plus = new WeexPlus(weex)
const UniServiceJSBridge = initServiceJSBridge(Vue, {
plus,
getApp,
getCurrentPages
})
function __registerPage (page) {
return registerPage(page, instanceContext)
}
if (!uni) {
uni = createUniInstance(
weex,
plus,
uniConfig,
uniRoutes,
__registerPage,
UniServiceJSBridge,
getApp,
getCurrentPages
)
}
return {
__uniConfig: uniConfig,
__uniRoutes: uniRoutes,
__registerConfig (config) {
return registerConfig(config, instanceContext)
},
__registerApp (appVm) {
return registerApp(appVm, instanceContext)
},
__registerPage,
plus,
uni,
getApp,
getCurrentPages,
UniServiceJSBridge
}
}
export 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
}
}
......@@ -32,19 +32,20 @@ export function getCurrentPages () {
*/
export function registerPage ({
path,
query,
webview
}, instanceContext) {
const routeOptions = JSON.parse(JSON.stringify(instanceContext.__uniRoutes.find(route => route.path === path)))
}) {
const routeOptions = JSON.parse(JSON.stringify(__uniRoutes.find(route => route.path === path)))
if (!webview) {
webview = createWebview(path, instanceContext, routeOptions)
webview = createWebview(path, routeOptions)
}
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] registerPage`, path, webview.id)
}
initWebview(webview, instanceContext, webview.id === '1' && routeOptions)
initWebview(webview, webview.id === '1' && routeOptions)
const route = path.slice(1)
......@@ -52,6 +53,7 @@ export function registerPage ({
pages.push({
route,
options: Object.assign({}, query || {}),
$getAppWebview () {
return webview
},
......
......@@ -59,18 +59,12 @@ let initView = function () {
viewStyles.bottom = 0
viewStyles.height += safeArea.bottom
}
if (process.env.NODE_ENV !== 'production') {
console.log(`UNIAPP[tabbar]:${JSON.stringify(viewStyles)}`)
}
view = new plus.nativeObj.View(TABBAR_VIEW_ID, viewStyles, getDraws())
view.interceptTouchEvent(true)
view.addEventListener('click', (e) => {
if (!__uniConfig.__ready__) { // 未 ready,不允许点击
if (process.env.NODE_ENV !== 'production') {
console.log(`UNIAPP[tabbar].prevent`)
}
return
}
const x = e.clientX
......
......@@ -7,10 +7,6 @@ import {
parseWebviewStyle
} from './parser/webview-style-parser'
import {
parseNavigationBar
} from './parser/navigation-bar-parser'
let id = 2
const WEBVIEW_LISTENERS = {
......@@ -20,45 +16,39 @@ const WEBVIEW_LISTENERS = {
'titleNViewSearchInputClicked': 'onNavigationBarSearchInputClicked'
}
export function createWebview (path, instanceContext, routeOptions) {
export function createWebview (path, routeOptions) {
const webviewId = id++
const webviewStyle = parseWebviewStyle(
webviewId,
path,
routeOptions,
instanceContext
routeOptions
)
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] createWebview`, webviewId, path, webviewStyle)
}
const webview = instanceContext.plus.webview.create('', String(webviewId), webviewStyle)
webview.$navigationBar = parseNavigationBar(webviewStyle)
const webview = plus.webview.create('', String(webviewId), webviewStyle)
return webview
}
export function initWebview (webview, instanceContext, routeOptions) {
export function initWebview (webview, routeOptions) {
if (isPlainObject(routeOptions)) {
const webviewStyle = parseWebviewStyle(
parseInt(webview.id),
'',
routeOptions,
instanceContext
routeOptions
)
if (process.env.NODE_ENV !== 'production') {
console.log(`[uni-app] updateWebview`, webviewStyle)
}
webview.$navigationBar = parseNavigationBar(webviewStyle)
webview.setStyle(webviewStyle)
}
const {
on,
emit
} = instanceContext.UniServiceJSBridge
} = UniServiceJSBridge
// TODO subNVues
Object.keys(WEBVIEW_LISTENERS).forEach(name => {
......
export function parsePullToRefresh (routeOptions, {
plus
}) {
export function parsePullToRefresh (routeOptions) {
const windowOptions = routeOptions.window
if (windowOptions.enablePullDownRefresh) {
......
......@@ -24,6 +24,8 @@ export function parseTitleNView (routeOptions) {
titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff'
}
routeOptions.meta.statusBarStyle = windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light'
if (isPlainObject(titleNView)) {
return Object.assign(ret, titleNView)
}
......
......@@ -23,22 +23,18 @@ const WEBVIEW_STYLE_BLACKLIST = [
'pullToRefresh'
]
export function parseWebviewStyle (id, path, routeOptions = {}, instanceContext) {
const {
__uniConfig
} = instanceContext
export function parseWebviewStyle (id, path, routeOptions = {}) {
const webviewStyle = Object.create(null)
// 合并
const windowOptions = Object.assign(
routeOptions.window = Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {}
)
Object.keys(windowOptions).forEach(name => {
Object.keys(routeOptions.window).forEach(name => {
if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
webviewStyle[name] = windowOptions[name]
webviewStyle[name] = routeOptions.window[name]
}
})
......@@ -50,7 +46,7 @@ export function parseWebviewStyle (id, path, routeOptions = {}, instanceContext)
webviewStyle.titleNView = titleNView
}
const pullToRefresh = parsePullToRefresh(routeOptions, instanceContext)
const pullToRefresh = parsePullToRefresh(routeOptions)
if (pullToRefresh) {
if (pullToRefresh.style === 'circle') {
webviewStyle.bounce = 'none'
......
import {
getApp,
registerApp
} from './framework/app'
import {
registerPage,
getCurrentPages
} from './framework/page'
import {
registerConfig
} from './framework/config'
import {
uni
} from 'uni-core/service/uni'
import {
invokeCallbackHandler
} from 'uni-helpers/api'
UniServiceJSBridge.publishHandler = UniServiceJSBridge.emit // TODO
UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler
export default {
__registerConfig: registerConfig,
__registerApp: registerApp,
__registerPage: registerPage,
uni,
getApp,
getCurrentPages
}
import {
invokeCallbackHandler
} from 'uni-helpers/api'
UniServiceJSBridge.publishHandler = UniServiceJSBridge.emit
UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler
import './polyfill'
import apis from 'uni-helpers/apis'
import {
wrapper,
wrapperUnimplemented
} from 'uni-helpers/api'
import {
promisify
} from 'uni-helpers/promise'
import baseApi from 'uni-core/service/api'
import platformApi from 'uni-platform/service/api'
const api = Object.assign(Object.create(null), baseApi, platformApi)
const uni = Object.create(null)
apis.forEach(name => {
if (api[name]) {
uni[name] = promisify(name, wrapper(name, api[name]))
} else {
uni[name] = wrapperUnimplemented(name)
}
})
......@@ -13,32 +13,7 @@ class RequestTask {
}
}
}
/**
* 拼接网址和参数
* @param {string} url 网址
* @param {any} data 参数
* @return {string}
*/
function setUrl (url, data) {
var str = url.split('#')
var hash = str[1] || ''
str = str[0].split('?')
var query = str[1] || ''
url = str[0]
var search = query.split('&').filter(item => item)
query = {}
search.forEach(item => {
item = item.split('=')
query[item[0]] = item[1]
})
for (var key in data) {
if (data.hasOwnProperty(key)) {
query[encodeURIComponent(key)] = encodeURIComponent(data[key])
}
}
query = Object.keys(query).map(item => `${item}=${query[item]}`).join('&')
return url + (query ? '?' + query : '') + (hash ? '#' + hash : '')
}
/**
* 解析响应头
* @param {string} headers
......@@ -94,9 +69,7 @@ export function request ({
}
}
}
if (method === 'GET') {
url = setUrl(url, data)
} else {
if (method !== 'GET') {
if (!contentType) {
/**
* 跨域时部分服务器OPTION响应头Access-Control-Allow-Headers未包含Content-Type会请求失败
......
......@@ -3,7 +3,7 @@ import initSubscribe from 'uni-core/service/bridge/subscribe'
import {
uni
} from './uni'
} from 'uni-core/service/uni'
import {
getApp,
......
export * from './env'
export * from './util'
export * from './color'
export * from './query'
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册