提交 8a1a36a5 编写于 作者: d-u-a's avatar d-u-a

add api uni.createRewardedVideoAd

上级 47436782
......@@ -201,6 +201,10 @@ const third = [
'setPageMeta'
]
const ad = [
'createRewardedVideoAd'
]
const apis = [
...base,
...network,
......@@ -214,7 +218,8 @@ const apis = [
...event,
...file,
...canvas,
...third
...third,
...ad
]
module.exports = apis
......@@ -206,4 +206,10 @@
"uni.base64ToArrayBuffer": true,
"uni.arrayBufferToBase64": true
}
}, {
"name": "ad",
"title": "广告",
"apiList": {
"uni.createRewardedVideoAd": true
}
}]
......@@ -213,6 +213,10 @@ var serviceContext = (function () {
'setPageMeta'
];
const ad = [
'createRewardedVideoAd'
];
const apis = [
...base,
...network,
......@@ -226,7 +230,8 @@ var serviceContext = (function () {
...event,
...file,
...canvas,
...third
...third,
...ad
];
var apis_1 = apis;
......@@ -335,43 +340,43 @@ var serviceContext = (function () {
return res
}
let id = 0;
const callbacks = {};
function warp (fn) {
return function (options = {}) {
const callbackId = String(id++);
callbacks[callbackId] = {
success: options.success,
fail: options.fail,
complete: options.complete
};
const data = Object.assign({}, options);
delete data.success;
delete data.fail;
delete data.complete;
const res = fn.bind(this)(data, callbackId);
if (res) {
invoke(callbackId, res);
}
}
}
function invoke (callbackId, res) {
const callback = callbacks[callbackId] || {};
delete callbacks[callbackId];
const errMsg = res.errMsg || '';
if (new RegExp('\\:\\s*fail').test(errMsg)) {
callback.fail && callback.fail(res);
} else {
callback.success && callback.success(res);
}
callback.complete && callback.complete(res);
}
const callback = {
warp,
invoke
let id = 0;
const callbacks = {};
function warp (fn) {
return function (options = {}) {
const callbackId = String(id++);
callbacks[callbackId] = {
success: options.success,
fail: options.fail,
complete: options.complete
};
const data = Object.assign({}, options);
delete data.success;
delete data.fail;
delete data.complete;
const res = fn.bind(this)(data, callbackId);
if (res) {
invoke(callbackId, res);
}
}
}
function invoke (callbackId, res) {
const callback = callbacks[callbackId] || {};
delete callbacks[callbackId];
const errMsg = res.errMsg || '';
if (new RegExp('\\:\\s*fail').test(errMsg)) {
callback.fail && callback.fail(res);
} else {
callback.success && callback.success(res);
}
callback.complete && callback.complete(res);
}
const callback = {
warp,
invoke
};
/**
......@@ -662,16 +667,16 @@ var serviceContext = (function () {
}
}
const base64ToArrayBuffer = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
const base64ToArrayBuffer = [{
name: 'base64',
type: String,
required: true
}];
const arrayBufferToBase64 = [{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}];
var require_context_module_0_0 = /*#__PURE__*/Object.freeze({
......@@ -749,136 +754,136 @@ var serviceContext = (function () {
upx2px: upx2px
});
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
}
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_0_5 = /*#__PURE__*/Object.freeze({
......@@ -947,14 +952,14 @@ var serviceContext = (function () {
setClipboardData: setClipboardData
});
const openDocument = {
filePath: {
type: String,
required: true
},
fileType: {
type: String
}
const openDocument = {
filePath: {
type: String,
required: true
},
fileType: {
type: String
}
};
var require_context_module_0_9 = /*#__PURE__*/Object.freeze({
......@@ -997,29 +1002,29 @@ var serviceContext = (function () {
getLocation: getLocation
});
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
}
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_0_12 = /*#__PURE__*/Object.freeze({
......@@ -1210,35 +1215,35 @@ var serviceContext = (function () {
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
}
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_0_16 = /*#__PURE__*/Object.freeze({
......@@ -1246,17 +1251,17 @@ var serviceContext = (function () {
previewImage: previewImage
});
const downloadFile = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
}
const downloadFile = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator (value, params) {
params.header = value || {};
}
}
};
var require_context_module_0_17 = /*#__PURE__*/Object.freeze({
......@@ -1367,53 +1372,53 @@ var serviceContext = (function () {
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
}
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_0_19 = /*#__PURE__*/Object.freeze({
......@@ -1423,34 +1428,34 @@ var serviceContext = (function () {
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 || {};
}
}
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_0_20 = /*#__PURE__*/Object.freeze({
......@@ -1458,24 +1463,24 @@ var serviceContext = (function () {
uploadFile: uploadFile
});
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'
}
}
}
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_0_21 = /*#__PURE__*/Object.freeze({
......@@ -1681,31 +1686,31 @@ var serviceContext = (function () {
removeStorageSync: removeStorageSync
});
const loadFontFace = {
family: {
type: String,
required: true
},
source: {
type: String,
required: true
},
desc: {
type: Object,
required: false
},
success: {
type: Function,
required: false
},
fail: {
type: Function,
required: false
},
complete: {
type: Function,
required: false
}
const loadFontFace = {
family: {
type: String,
required: true
},
source: {
type: String,
required: true
},
desc: {
type: Object,
required: false
},
success: {
type: Function,
required: false
},
fail: {
type: Function,
required: false
},
complete: {
type: Function,
required: false
}
};
var require_context_module_0_24 = /*#__PURE__*/Object.freeze({
......@@ -3256,75 +3261,75 @@ var serviceContext = (function () {
const TEMP_PATH_BASE = '_doc/uniapp_temp';
const TEMP_PATH = `${TEMP_PATH_BASE}_${Date.now()}`;
/**
* 5+错误对象转换为错误消息
* @param {*} error 5+错误对象
*/
function toErrMsg (error) {
var msg = 'base64ToTempFilePath:fail';
if (error && error.message) {
msg += ` ${error.message}`;
} else if (error) {
msg += ` ${error}`;
}
return msg
}
function base64ToTempFilePath ({
base64Data,
x,
y,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
quality
} = {}, callbackId) {
var id = Date.now();
var bitmap = new plus.nativeObj.Bitmap(`bitmap${id}`);
bitmap.loadBase64Data(base64Data, function () {
var formats = ['jpg', 'png'];
var format = String(fileType).toLowerCase();
if (formats.indexOf(format) < 0) {
format = 'png';
}
/**
* 保存配置
*/
var saveOption = {
overwrite: true,
quality: typeof quality === 'number' ? quality * 100 : 100,
format
};
/**
* 保存文件路径
*/
var tempFilePath = `${TEMP_PATH}/canvas/${id}.${format}`;
bitmap.save(tempFilePath, saveOption, function () {
clear();
invoke$1(callbackId, {
tempFilePath,
errMsg: 'base64ToTempFilePath:ok'
});
}, function (error) {
clear();
invoke$1(callbackId, {
errMsg: toErrMsg(error)
});
});
}, function (error) {
clear();
invoke$1(callbackId, {
errMsg: toErrMsg(error)
});
});
function clear () {
bitmap.clear();
}
/**
* 5+错误对象转换为错误消息
* @param {*} error 5+错误对象
*/
function toErrMsg (error) {
var msg = 'base64ToTempFilePath:fail';
if (error && error.message) {
msg += ` ${error.message}`;
} else if (error) {
msg += ` ${error}`;
}
return msg
}
function base64ToTempFilePath ({
base64Data,
x,
y,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
quality
} = {}, callbackId) {
var id = Date.now();
var bitmap = new plus.nativeObj.Bitmap(`bitmap${id}`);
bitmap.loadBase64Data(base64Data, function () {
var formats = ['jpg', 'png'];
var format = String(fileType).toLowerCase();
if (formats.indexOf(format) < 0) {
format = 'png';
}
/**
* 保存配置
*/
var saveOption = {
overwrite: true,
quality: typeof quality === 'number' ? quality * 100 : 100,
format
};
/**
* 保存文件路径
*/
var tempFilePath = `${TEMP_PATH}/canvas/${id}.${format}`;
bitmap.save(tempFilePath, saveOption, function () {
clear();
invoke$1(callbackId, {
tempFilePath,
errMsg: 'base64ToTempFilePath:ok'
});
}, function (error) {
clear();
invoke$1(callbackId, {
errMsg: toErrMsg(error)
});
});
}, function (error) {
clear();
invoke$1(callbackId, {
errMsg: toErrMsg(error)
});
});
function clear () {
bitmap.clear();
}
}
function operateMapPlayer (mapId, pageVm, type, data) {
......@@ -4469,82 +4474,82 @@ var serviceContext = (function () {
return new Page(page)
}
function getStatusBarStyle$1 () {
let style = plus.navigator.getStatusBarStyle();
if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') {
style = 'light';
} else if (style === 'UIStatusBarStyleDefault') {
style = 'dark';
}
return style
}
function scanCode$1 (options, callbackId) {
const statusBarStyle = getStatusBarStyle$1();
const isDark = statusBarStyle !== 'light';
let result;
const page = showPage({
url: '__uniappscan',
data: {
scanType: options.scanType
},
style: {
animationType: options.animationType || 'pop-in',
titleNView: {
autoBackButton: true,
type: 'float',
titleText: options.titleText || '扫码',
titleColor: '#ffffff',
backgroundColor: 'rgba(0,0,0,0)',
buttons: !options.onlyFromCamera ? [{
text: options.albumText || '相册',
fontSize: '17px',
width: '60px',
onclick: () => {
page.sendMessage({
type: 'gallery'
});
}
}] : []
},
popGesture: 'close',
backButtonAutoControl: 'close'
},
onMessage ({
event,
detail
}) {
result = detail;
if (event === 'marked') {
result.errMsg = 'scanCode:ok';
} else {
result.errMsg = 'scanCode:fail ' + detail.message;
}
},
onClose () {
if (isDark) {
plus.navigator.setStatusBarStyle('dark');
}
invoke$1(callbackId, result || {
errMsg: 'scanCode:fail cancel'
});
}
});
if (isDark) {
plus.navigator.setStatusBarStyle('light');
page.webview.addEventListener('popGesture', ({
type,
result
}) => {
if (type === 'start') {
plus.navigator.setStatusBarStyle('dark');
} else if (type === 'end' && !result) {
plus.navigator.setStatusBarStyle('light');
}
});
}
function getStatusBarStyle$1 () {
let style = plus.navigator.getStatusBarStyle();
if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') {
style = 'light';
} else if (style === 'UIStatusBarStyleDefault') {
style = 'dark';
}
return style
}
function scanCode$1 (options, callbackId) {
const statusBarStyle = getStatusBarStyle$1();
const isDark = statusBarStyle !== 'light';
let result;
const page = showPage({
url: '__uniappscan',
data: {
scanType: options.scanType
},
style: {
animationType: options.animationType || 'pop-in',
titleNView: {
autoBackButton: true,
type: 'float',
titleText: options.titleText || '扫码',
titleColor: '#ffffff',
backgroundColor: 'rgba(0,0,0,0)',
buttons: !options.onlyFromCamera ? [{
text: options.albumText || '相册',
fontSize: '17px',
width: '60px',
onclick: () => {
page.sendMessage({
type: 'gallery'
});
}
}] : []
},
popGesture: 'close',
backButtonAutoControl: 'close'
},
onMessage ({
event,
detail
}) {
result = detail;
if (event === 'marked') {
result.errMsg = 'scanCode:ok';
} else {
result.errMsg = 'scanCode:fail ' + detail.message;
}
},
onClose () {
if (isDark) {
plus.navigator.setStatusBarStyle('dark');
}
invoke$1(callbackId, result || {
errMsg: 'scanCode:fail cancel'
});
}
});
if (isDark) {
plus.navigator.setStatusBarStyle('light');
page.webview.addEventListener('popGesture', ({
type,
result
}) => {
if (type === 'start') {
plus.navigator.setStatusBarStyle('dark');
} else if (type === 'end' && !result) {
plus.navigator.setStatusBarStyle('light');
}
});
}
}
var weex$1 = /*#__PURE__*/Object.freeze({
......@@ -4552,231 +4557,231 @@ var serviceContext = (function () {
scanCode: scanCode$1
});
function scanCode$2 (...array) {
const api = __uniConfig.nvueCompiler !== 'weex' ? weex$1 : webview;
return api.scanCode(...array)
}
function checkIsSupportFaceID () {
const platform = plus.os.name.toLowerCase();
if (platform !== 'ios') {
return false
}
const faceID = requireNativePlugin('faceID');
return !!(faceID && faceID.isSupport())
}
function checkIsSupportFingerPrint () {
return !!(plus.fingerprint && plus.fingerprint.isSupport())
}
function checkIsSupportSoterAuthentication () {
let supportMode = [];
if (checkIsSupportFingerPrint()) {
supportMode.push('fingerPrint');
}
if (checkIsSupportFaceID()) {
supportMode.push('facial');
}
return {
supportMode,
errMsg: 'checkIsSupportSoterAuthentication:ok'
}
}
function checkIsSoterEnrolledInDevice ({
checkAuthMode
} = {}) {
if (checkAuthMode === 'fingerPrint') {
if (checkIsSupportFingerPrint()) {
const isEnrolled = plus.fingerprint.isKeyguardSecure() && plus.fingerprint.isEnrolledFingerprints();
return {
isEnrolled,
errMsg: 'checkIsSoterEnrolledInDevice:ok'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
} else if (checkAuthMode === 'facial') {
if (checkIsSupportFaceID()) {
const faceID = requireNativePlugin('faceID');
const isEnrolled = faceID && faceID.isKeyguardSecure() && faceID.isEnrolledFaceID();
return {
isEnrolled,
errMsg: 'checkIsSoterEnrolledInDevice:ok'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
function scanCode$2 (...array) {
const api = __uniConfig.nvueCompiler !== 'weex' ? weex$1 : webview;
return api.scanCode(...array)
}
function startSoterAuthentication ({
requestAuthModes,
challenge = false,
authContent
} = {}, callbackId) {
/*
以手机不支持facial未录入fingerPrint为例
requestAuthModes:['facial','fingerPrint']时,微信小程序返回值里的authMode为"fingerPrint"
requestAuthModes:['fingerPrint','facial']时,微信小程序返回值里的authMode为"fingerPrint"
即先过滤不支持的方式之后再判断是否录入
微信小程序errCode(从企业号开发者中心查到如下文档):
0:识别成功 'startSoterAuthentication:ok'
90001:本设备不支持SOTER 'startSoterAuthentication:fail not support soter'
90002:用户未授权微信使用该生物认证接口 注:APP端暂不支持
90003:请求使用的生物认证方式不支持 'startSoterAuthentication:fail no corresponding mode'
90004:未传入challenge或challenge长度过长(最长512字符)注:APP端暂不支持
90005:auth_content长度超过限制(最长42个字符)注:微信小程序auth_content指纹识别时无效果,faceID暂未测试
90007:内部错误 'startSoterAuthentication:fail auth key update error'
90008:用户取消授权 'startSoterAuthentication:fail cancel'
90009:识别失败 'startSoterAuthentication:fail'
90010:重试次数过多被冻结 'startSoterAuthentication:fail authenticate freeze. please try again later'
90011:用户未录入所选识别方式 'startSoterAuthentication:fail no fingerprint enrolled'
*/
const supportMode = checkIsSupportSoterAuthentication().supportMode;
if (supportMode.length === 0) {
return {
authMode: supportMode[0] || 'fingerPrint',
errCode: 90001,
errMsg: 'startSoterAuthentication:fail'
}
}
let supportRequestAuthMode = [];
requestAuthModes.map((item, index) => {
if (supportMode.indexOf(item) > -1) {
supportRequestAuthMode.push(item);
}
});
if (supportRequestAuthMode.length === 0) {
return {
authMode: supportRequestAuthMode[0] || 'fingerPrint',
errCode: 90003,
errMsg: 'startSoterAuthentication:fail no corresponding mode'
}
}
let enrolledRequestAuthMode = [];
supportRequestAuthMode.map((item, index) => {
const checked = checkIsSoterEnrolledInDevice({
checkAuthMode: item
}).isEnrolled;
if (checked) {
enrolledRequestAuthMode.push(item);
}
});
if (enrolledRequestAuthMode.length === 0) {
return {
authMode: supportRequestAuthMode[0],
errCode: 90011,
errMsg: `startSoterAuthentication:fail no ${supportRequestAuthMode[0]} enrolled`
}
}
const realAuthMode = enrolledRequestAuthMode[0];
if (realAuthMode === 'fingerPrint') {
if (plus.os.name.toLowerCase() === 'android') {
plus.nativeUI.showWaiting(authContent || '指纹识别中...').onclose = function () {
plus.fingerprint.cancel();
};
}
plus.fingerprint.authenticate(() => {
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 0,
errMsg: 'startSoterAuthentication:ok'
});
}, (e) => {
switch (e.code) {
case e.AUTHENTICATE_MISMATCH:
// 微信小程序没有这个回调,如果要实现此处回调需要多次触发需要用事件publish实现
// invoke(callbackId, {
// authMode: realAuthMode,
// errCode: 90009,
// errMsg: 'startSoterAuthentication:fail'
// })
break
case e.AUTHENTICATE_OVERLIMIT:
// 微信小程序在第一次重试次数超限时安卓IOS返回不一致,安卓端会返回次数超过限制(errCode: 90010),IOS端会返回认证失败(errCode: 90009)。APP-IOS实际运行时不会次数超限,超过指定次数之后会弹出输入密码的界面
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90010,
errMsg: 'startSoterAuthentication:fail authenticate freeze. please try again later'
});
break
case e.CANCEL:
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90008,
errMsg: 'startSoterAuthentication:fail cancel'
});
break
default:
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90007,
errMsg: 'startSoterAuthentication:fail'
});
break
}
}, {
message: authContent
});
} else if (realAuthMode === 'facial') {
const faceID = requireNativePlugin('faceID');
faceID.authenticate({
message: authContent
}, (e) => {
if (e.type === 'success' && e.code === 0) {
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 0,
errMsg: 'startSoterAuthentication:ok'
});
} else {
switch (e.code) {
case 4:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90009,
errMsg: 'startSoterAuthentication:fail'
});
break
case 5:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90010,
errMsg: 'startSoterAuthentication:fail authenticate freeze. please try again later'
});
break
case 6:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90008,
errMsg: 'startSoterAuthentication:fail cancel'
});
break
default:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90007,
errMsg: 'startSoterAuthentication:fail'
});
break
}
}
});
}
function checkIsSupportFaceID () {
const platform = plus.os.name.toLowerCase();
if (platform !== 'ios') {
return false
}
const faceID = requireNativePlugin('faceID');
return !!(faceID && faceID.isSupport())
}
function checkIsSupportFingerPrint () {
return !!(plus.fingerprint && plus.fingerprint.isSupport())
}
function checkIsSupportSoterAuthentication () {
let supportMode = [];
if (checkIsSupportFingerPrint()) {
supportMode.push('fingerPrint');
}
if (checkIsSupportFaceID()) {
supportMode.push('facial');
}
return {
supportMode,
errMsg: 'checkIsSupportSoterAuthentication:ok'
}
}
function checkIsSoterEnrolledInDevice ({
checkAuthMode
} = {}) {
if (checkAuthMode === 'fingerPrint') {
if (checkIsSupportFingerPrint()) {
const isEnrolled = plus.fingerprint.isKeyguardSecure() && plus.fingerprint.isEnrolledFingerprints();
return {
isEnrolled,
errMsg: 'checkIsSoterEnrolledInDevice:ok'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
} else if (checkAuthMode === 'facial') {
if (checkIsSupportFaceID()) {
const faceID = requireNativePlugin('faceID');
const isEnrolled = faceID && faceID.isKeyguardSecure() && faceID.isEnrolledFaceID();
return {
isEnrolled,
errMsg: 'checkIsSoterEnrolledInDevice:ok'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
}
return {
isEnrolled: false,
errMsg: 'checkIsSoterEnrolledInDevice:fail not support'
}
}
function startSoterAuthentication ({
requestAuthModes,
challenge = false,
authContent
} = {}, callbackId) {
/*
以手机不支持facial未录入fingerPrint为例
requestAuthModes:['facial','fingerPrint']时,微信小程序返回值里的authMode为"fingerPrint"
requestAuthModes:['fingerPrint','facial']时,微信小程序返回值里的authMode为"fingerPrint"
即先过滤不支持的方式之后再判断是否录入
微信小程序errCode(从企业号开发者中心查到如下文档):
0:识别成功 'startSoterAuthentication:ok'
90001:本设备不支持SOTER 'startSoterAuthentication:fail not support soter'
90002:用户未授权微信使用该生物认证接口 注:APP端暂不支持
90003:请求使用的生物认证方式不支持 'startSoterAuthentication:fail no corresponding mode'
90004:未传入challenge或challenge长度过长(最长512字符)注:APP端暂不支持
90005:auth_content长度超过限制(最长42个字符)注:微信小程序auth_content指纹识别时无效果,faceID暂未测试
90007:内部错误 'startSoterAuthentication:fail auth key update error'
90008:用户取消授权 'startSoterAuthentication:fail cancel'
90009:识别失败 'startSoterAuthentication:fail'
90010:重试次数过多被冻结 'startSoterAuthentication:fail authenticate freeze. please try again later'
90011:用户未录入所选识别方式 'startSoterAuthentication:fail no fingerprint enrolled'
*/
const supportMode = checkIsSupportSoterAuthentication().supportMode;
if (supportMode.length === 0) {
return {
authMode: supportMode[0] || 'fingerPrint',
errCode: 90001,
errMsg: 'startSoterAuthentication:fail'
}
}
let supportRequestAuthMode = [];
requestAuthModes.map((item, index) => {
if (supportMode.indexOf(item) > -1) {
supportRequestAuthMode.push(item);
}
});
if (supportRequestAuthMode.length === 0) {
return {
authMode: supportRequestAuthMode[0] || 'fingerPrint',
errCode: 90003,
errMsg: 'startSoterAuthentication:fail no corresponding mode'
}
}
let enrolledRequestAuthMode = [];
supportRequestAuthMode.map((item, index) => {
const checked = checkIsSoterEnrolledInDevice({
checkAuthMode: item
}).isEnrolled;
if (checked) {
enrolledRequestAuthMode.push(item);
}
});
if (enrolledRequestAuthMode.length === 0) {
return {
authMode: supportRequestAuthMode[0],
errCode: 90011,
errMsg: `startSoterAuthentication:fail no ${supportRequestAuthMode[0]} enrolled`
}
}
const realAuthMode = enrolledRequestAuthMode[0];
if (realAuthMode === 'fingerPrint') {
if (plus.os.name.toLowerCase() === 'android') {
plus.nativeUI.showWaiting(authContent || '指纹识别中...').onclose = function () {
plus.fingerprint.cancel();
};
}
plus.fingerprint.authenticate(() => {
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 0,
errMsg: 'startSoterAuthentication:ok'
});
}, (e) => {
switch (e.code) {
case e.AUTHENTICATE_MISMATCH:
// 微信小程序没有这个回调,如果要实现此处回调需要多次触发需要用事件publish实现
// invoke(callbackId, {
// authMode: realAuthMode,
// errCode: 90009,
// errMsg: 'startSoterAuthentication:fail'
// })
break
case e.AUTHENTICATE_OVERLIMIT:
// 微信小程序在第一次重试次数超限时安卓IOS返回不一致,安卓端会返回次数超过限制(errCode: 90010),IOS端会返回认证失败(errCode: 90009)。APP-IOS实际运行时不会次数超限,超过指定次数之后会弹出输入密码的界面
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90010,
errMsg: 'startSoterAuthentication:fail authenticate freeze. please try again later'
});
break
case e.CANCEL:
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90008,
errMsg: 'startSoterAuthentication:fail cancel'
});
break
default:
plus.nativeUI.closeWaiting();
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90007,
errMsg: 'startSoterAuthentication:fail'
});
break
}
}, {
message: authContent
});
} else if (realAuthMode === 'facial') {
const faceID = requireNativePlugin('faceID');
faceID.authenticate({
message: authContent
}, (e) => {
if (e.type === 'success' && e.code === 0) {
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 0,
errMsg: 'startSoterAuthentication:ok'
});
} else {
switch (e.code) {
case 4:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90009,
errMsg: 'startSoterAuthentication:fail'
});
break
case 5:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90010,
errMsg: 'startSoterAuthentication:fail authenticate freeze. please try again later'
});
break
case 6:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90008,
errMsg: 'startSoterAuthentication:fail cancel'
});
break
default:
invoke$1(callbackId, {
authMode: realAuthMode,
errCode: 90007,
errMsg: 'startSoterAuthentication:fail'
});
break
}
}
});
}
}
var safeAreaInsets = {
......@@ -5331,73 +5336,73 @@ var serviceContext = (function () {
chooseLocation: chooseLocation$1
});
function getStatusBarStyle$2 () {
let style = plus.navigator.getStatusBarStyle();
if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') {
style = 'light';
} else if (style === 'UIStatusBarStyleDefault') {
style = 'dark';
}
return style
}
function chooseLocation$2 (options, callbackId) {
const statusBarStyle = getStatusBarStyle$2();
const isDark = statusBarStyle !== 'light';
let result;
const page = showPage({
url: '__uniappchooselocation',
data: options,
style: {
animationType: options.animationType || 'slide-in-bottom',
titleNView: false,
popGesture: 'close',
scrollIndicator: 'none'
},
onMessage ({
event,
detail
}) {
if (event === 'selected') {
result = detail;
result.errMsg = 'chooseLocation:ok';
}
},
onClose () {
if (isDark) {
plus.navigator.setStatusBarStyle('dark');
}
invoke$1(callbackId, result || {
errMsg: 'chooseLocation:fail cancel'
});
}
});
if (isDark) {
plus.navigator.setStatusBarStyle('light');
page.webview.addEventListener('popGesture', ({
type,
result
}) => {
if (type === 'start') {
plus.navigator.setStatusBarStyle('dark');
} else if (type === 'end' && !result) {
plus.navigator.setStatusBarStyle('light');
}
});
}
}
function getStatusBarStyle$2 () {
let style = plus.navigator.getStatusBarStyle();
if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') {
style = 'light';
} else if (style === 'UIStatusBarStyleDefault') {
style = 'dark';
}
return style
}
function chooseLocation$2 (options, callbackId) {
const statusBarStyle = getStatusBarStyle$2();
const isDark = statusBarStyle !== 'light';
let result;
const page = showPage({
url: '__uniappchooselocation',
data: options,
style: {
animationType: options.animationType || 'slide-in-bottom',
titleNView: false,
popGesture: 'close',
scrollIndicator: 'none'
},
onMessage ({
event,
detail
}) {
if (event === 'selected') {
result = detail;
result.errMsg = 'chooseLocation:ok';
}
},
onClose () {
if (isDark) {
plus.navigator.setStatusBarStyle('dark');
}
invoke$1(callbackId, result || {
errMsg: 'chooseLocation:fail cancel'
});
}
});
if (isDark) {
plus.navigator.setStatusBarStyle('light');
page.webview.addEventListener('popGesture', ({
type,
result
}) => {
if (type === 'start') {
plus.navigator.setStatusBarStyle('dark');
} else if (type === 'end' && !result) {
plus.navigator.setStatusBarStyle('light');
}
});
}
}
var weex$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
chooseLocation: chooseLocation$2
});
function chooseLocation$3 (...array) {
const api = __uniConfig.nvueCompiler !== 'weex' ? weex$2 : webview$1;
return api.chooseLocation(...array)
function chooseLocation$3 (...array) {
const api = __uniConfig.nvueCompiler !== 'weex' ? weex$2 : webview$1;
return api.chooseLocation(...array)
}
function getLocationSuccess (type, position, callbackId) {
......@@ -6177,152 +6182,152 @@ var serviceContext = (function () {
return createDownloadTaskById(++downloadTaskId, args)
}
let requestTaskId = 0;
const requestTasks = {};
const publishStateChange$1 = res => {
publish('onRequestTaskStateChange', res);
delete requestTasks[requestTaskId];
};
function createRequestTaskById (requestTaskId, {
url,
data,
header,
method = 'GET',
responseType,
sslVerify = true
} = {}) {
const stream = requireNativePlugin('stream');
const headers = {};
let abortTimeout;
let aborted;
let hasContentType = false;
for (const name in header) {
if (!hasContentType && name.toLowerCase() === 'content-type') {
hasContentType = true;
headers['Content-Type'] = header[name];
// TODO 需要重构
if (method !== 'GET' && header[name].indexOf('application/x-www-form-urlencoded') === 0 && typeof data !== 'string' && !(data instanceof ArrayBuffer)) {
let bodyArray = [];
for (let key in data) {
if (data.hasOwnProperty(key)) {
bodyArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
}
data = bodyArray.join('&');
}
} else {
headers[name] = header[name];
}
}
if (!hasContentType && method === 'POST') {
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
const timeout = __uniConfig.networkTimeout.request;
if (timeout) {
abortTimeout = setTimeout(() => {
aborted = true;
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode: 0,
errMsg: 'timeout'
});
}, timeout);
}
const options = {
method,
url: url.trim(),
// weex 官方文档有误,headers 类型实际 object,用 string 类型会无响应
headers,
type: responseType === 'arraybuffer' ? 'base64' : 'text',
// weex 官方文档未说明实际支持 timeout,单位:ms
timeout: timeout || 6e5,
// 配置和weex模块内相反
sslVerify: !sslVerify
};
if (method !== 'GET') {
options.body = data;
}
try {
stream.fetch(options, ({
ok,
status,
data,
headers
}) => {
if (aborted) {
return
}
if (abortTimeout) {
clearTimeout(abortTimeout);
}
const statusCode = status;
if (statusCode > 0) {
publishStateChange$1({
requestTaskId,
state: 'success',
data: ok && responseType === 'arraybuffer' ? base64ToArrayBuffer$2(data) : data,
statusCode,
header: headers
});
} else {
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode,
errMsg: 'abort statusCode:' + statusCode
});
}
});
requestTasks[requestTaskId] = {
abort () {
aborted = true;
if (abortTimeout) {
clearTimeout(abortTimeout);
}
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode: 0,
errMsg: 'abort'
});
}
};
} catch (e) {
return {
requestTaskId,
errMsg: 'createRequestTask:fail'
}
}
return {
requestTaskId,
errMsg: 'createRequestTask:ok'
}
}
function createRequestTask (args) {
return createRequestTaskById(++requestTaskId, args)
}
function operateRequestTask ({
requestTaskId,
operationType
} = {}) {
const requestTask = requestTasks[requestTaskId];
if (requestTask && operationType === 'abort') {
requestTask.abort();
return {
errMsg: 'operateRequestTask:ok'
}
}
return {
errMsg: 'operateRequestTask:fail'
}
let requestTaskId = 0;
const requestTasks = {};
const publishStateChange$1 = res => {
publish('onRequestTaskStateChange', res);
delete requestTasks[requestTaskId];
};
function createRequestTaskById (requestTaskId, {
url,
data,
header,
method = 'GET',
responseType,
sslVerify = true
} = {}) {
const stream = requireNativePlugin('stream');
const headers = {};
let abortTimeout;
let aborted;
let hasContentType = false;
for (const name in header) {
if (!hasContentType && name.toLowerCase() === 'content-type') {
hasContentType = true;
headers['Content-Type'] = header[name];
// TODO 需要重构
if (method !== 'GET' && header[name].indexOf('application/x-www-form-urlencoded') === 0 && typeof data !== 'string' && !(data instanceof ArrayBuffer)) {
let bodyArray = [];
for (let key in data) {
if (data.hasOwnProperty(key)) {
bodyArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
}
data = bodyArray.join('&');
}
} else {
headers[name] = header[name];
}
}
if (!hasContentType && method === 'POST') {
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
const timeout = __uniConfig.networkTimeout.request;
if (timeout) {
abortTimeout = setTimeout(() => {
aborted = true;
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode: 0,
errMsg: 'timeout'
});
}, timeout);
}
const options = {
method,
url: url.trim(),
// weex 官方文档有误,headers 类型实际 object,用 string 类型会无响应
headers,
type: responseType === 'arraybuffer' ? 'base64' : 'text',
// weex 官方文档未说明实际支持 timeout,单位:ms
timeout: timeout || 6e5,
// 配置和weex模块内相反
sslVerify: !sslVerify
};
if (method !== 'GET') {
options.body = data;
}
try {
stream.fetch(options, ({
ok,
status,
data,
headers
}) => {
if (aborted) {
return
}
if (abortTimeout) {
clearTimeout(abortTimeout);
}
const statusCode = status;
if (statusCode > 0) {
publishStateChange$1({
requestTaskId,
state: 'success',
data: ok && responseType === 'arraybuffer' ? base64ToArrayBuffer$2(data) : data,
statusCode,
header: headers
});
} else {
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode,
errMsg: 'abort statusCode:' + statusCode
});
}
});
requestTasks[requestTaskId] = {
abort () {
aborted = true;
if (abortTimeout) {
clearTimeout(abortTimeout);
}
publishStateChange$1({
requestTaskId,
state: 'fail',
statusCode: 0,
errMsg: 'abort'
});
}
};
} catch (e) {
return {
requestTaskId,
errMsg: 'createRequestTask:fail'
}
}
return {
requestTaskId,
errMsg: 'createRequestTask:ok'
}
}
function createRequestTask (args) {
return createRequestTaskById(++requestTaskId, args)
}
function operateRequestTask ({
requestTaskId,
operationType
} = {}) {
const requestTask = requestTasks[requestTaskId];
if (requestTask && operationType === 'abort') {
requestTask.abort();
return {
errMsg: 'operateRequestTask:ok'
}
}
return {
errMsg: 'operateRequestTask:fail'
}
}
const socketTasks = {};
......@@ -6483,7 +6488,7 @@ var serviceContext = (function () {
}
for (const name in formData) {
if (formData.hasOwnProperty(name)) {
uploader.addData(name, formData[name]);
uploader.addData(name, String(formData[name]));
}
}
if (files && files.length) {
......@@ -7347,29 +7352,29 @@ var serviceContext = (function () {
}
}
const REGEX_UPX = /(\d+(\.\d+)?)[r|u]px/g;
function transformCSS (css) {
return css.replace(REGEX_UPX, (a, b) => {
return uni.upx2px(parseInt(b) || 0) + 'px'
})
const REGEX_UPX = /(\d+(\.\d+)?)[r|u]px/g;
function transformCSS (css) {
return css.replace(REGEX_UPX, (a, b) => {
return uni.upx2px(parseInt(b) || 0) + 'px'
})
}
function parseStyleUnit (styles) {
let newStyles = {};
const stylesStr = JSON.stringify(styles);
if (~stylesStr.indexOf('upx') || ~stylesStr.indexOf('rpx')) {
try {
newStyles = JSON.parse(transformCSS(stylesStr));
} catch (e) {
newStyles = styles;
console.error(e);
}
} else {
newStyles = JSON.parse(stylesStr);
}
return newStyles
function parseStyleUnit (styles) {
let newStyles = {};
const stylesStr = JSON.stringify(styles);
if (~stylesStr.indexOf('upx') || ~stylesStr.indexOf('rpx')) {
try {
newStyles = JSON.parse(transformCSS(stylesStr));
} catch (e) {
newStyles = styles;
console.error(e);
}
} else {
newStyles = JSON.parse(stylesStr);
}
return newStyles
}
const WEBVIEW_STYLE_BLACKLIST = [
......@@ -7442,134 +7447,134 @@ var serviceContext = (function () {
return webviewStyle
}
function backbuttonListener () {
uni.navigateBack({
from: 'backbutton'
});
}
function initPopupSubNVue (subNVueWebview, style, maskWebview) {
if (!maskWebview.popupSubNVueWebviews) {
maskWebview.popupSubNVueWebviews = {};
}
maskWebview.popupSubNVueWebviews[subNVueWebview.id] = subNVueWebview;
if (process.env.NODE_ENV !== 'production') {
console.log(
`UNIAPP[webview][${maskWebview.id}]:add.popupSubNVueWebview[${subNVueWebview.id}]`
);
}
const hideSubNVue = function () {
maskWebview.setStyle({
mask: 'none'
});
subNVueWebview.hide('auto');
};
maskWebview.addEventListener('maskClick', hideSubNVue);
let isRemoved = false; // 增加个 remove 标记,防止出错
subNVueWebview.addEventListener('show', () => {
if (!isRemoved) {
plus.key.removeEventListener('backbutton', backbuttonListener);
plus.key.addEventListener('backbutton', hideSubNVue);
isRemoved = true;
}
});
subNVueWebview.addEventListener('hide', () => {
if (isRemoved) {
plus.key.removeEventListener('backbutton', hideSubNVue);
plus.key.addEventListener('backbutton', backbuttonListener);
isRemoved = false;
}
});
subNVueWebview.addEventListener('close', () => {
delete maskWebview.popupSubNVueWebviews[subNVueWebview.id];
if (isRemoved) {
plus.key.removeEventListener('backbutton', hideSubNVue);
plus.key.addEventListener('backbutton', backbuttonListener);
isRemoved = false;
}
});
}
function initNormalSubNVue (subNVueWebview, style, webview) {
webview.append(subNVueWebview);
}
function initSubNVue (subNVue, routeOptions, webview) {
if (!subNVue.path) {
return
}
const style = subNVue.style || {};
const isNavigationBar = subNVue.type === 'navigationBar';
const isPopup = subNVue.type === 'popup';
delete style.type;
if (isPopup && !subNVue.id) {
console.warn('subNVue[' + subNVue.path + '] 尚未配置 id');
}
// TODO lazyload
style.uniNView = {
path: subNVue.path.replace('.nvue', '.js'),
defaultFontSize: __uniConfig.defaultFontSize,
viewport: __uniConfig.viewport
};
const extras = {
__uniapp_host: routeOptions.path,
__uniapp_origin: style.uniNView.path.split('?')[0].replace('.js', ''),
__uniapp_origin_id: webview.id,
__uniapp_origin_type: webview.__uniapp_type
};
let maskWebview;
if (isNavigationBar) {
style.position = 'dock';
style.dock = 'top';
style.top = 0;
style.width = '100%';
style.height = TITLEBAR_HEIGHT + getStatusbarHeight();
delete style.left;
delete style.right;
delete style.bottom;
delete style.margin;
} else if (isPopup) {
style.position = 'absolute';
if (isTabBarPage(routeOptions.path)) {
maskWebview = tabBar$1;
} else {
maskWebview = webview;
}
extras.__uniapp_mask = style.mask || 'rgba(0,0,0,0.5)';
extras.__uniapp_mask_id = maskWebview.id;
}
if (process.env.NODE_ENV !== 'production') {
console.log(
`UNIAPP[webview][${webview.id}]:create[${subNVue.id}]:${JSON.stringify(style)}`
);
}
const subNVueWebview = plus.webview.create('', subNVue.id, style, extras);
if (isPopup) {
initPopupSubNVue(subNVueWebview, style, maskWebview);
} else {
initNormalSubNVue(subNVueWebview, style, webview);
}
function backbuttonListener () {
uni.navigateBack({
from: 'backbutton'
});
}
function initSubNVues (routeOptions, webview) {
const subNVues = routeOptions.window.subNVues;
if (!subNVues || !subNVues.length) {
return
}
subNVues.forEach(subNVue => {
initSubNVue(subNVue, routeOptions, webview);
});
function initPopupSubNVue (subNVueWebview, style, maskWebview) {
if (!maskWebview.popupSubNVueWebviews) {
maskWebview.popupSubNVueWebviews = {};
}
maskWebview.popupSubNVueWebviews[subNVueWebview.id] = subNVueWebview;
if (process.env.NODE_ENV !== 'production') {
console.log(
`UNIAPP[webview][${maskWebview.id}]:add.popupSubNVueWebview[${subNVueWebview.id}]`
);
}
const hideSubNVue = function () {
maskWebview.setStyle({
mask: 'none'
});
subNVueWebview.hide('auto');
};
maskWebview.addEventListener('maskClick', hideSubNVue);
let isRemoved = false; // 增加个 remove 标记,防止出错
subNVueWebview.addEventListener('show', () => {
if (!isRemoved) {
plus.key.removeEventListener('backbutton', backbuttonListener);
plus.key.addEventListener('backbutton', hideSubNVue);
isRemoved = true;
}
});
subNVueWebview.addEventListener('hide', () => {
if (isRemoved) {
plus.key.removeEventListener('backbutton', hideSubNVue);
plus.key.addEventListener('backbutton', backbuttonListener);
isRemoved = false;
}
});
subNVueWebview.addEventListener('close', () => {
delete maskWebview.popupSubNVueWebviews[subNVueWebview.id];
if (isRemoved) {
plus.key.removeEventListener('backbutton', hideSubNVue);
plus.key.addEventListener('backbutton', backbuttonListener);
isRemoved = false;
}
});
}
function initNormalSubNVue (subNVueWebview, style, webview) {
webview.append(subNVueWebview);
}
function initSubNVue (subNVue, routeOptions, webview) {
if (!subNVue.path) {
return
}
const style = subNVue.style || {};
const isNavigationBar = subNVue.type === 'navigationBar';
const isPopup = subNVue.type === 'popup';
delete style.type;
if (isPopup && !subNVue.id) {
console.warn('subNVue[' + subNVue.path + '] 尚未配置 id');
}
// TODO lazyload
style.uniNView = {
path: subNVue.path.replace('.nvue', '.js'),
defaultFontSize: __uniConfig.defaultFontSize,
viewport: __uniConfig.viewport
};
const extras = {
__uniapp_host: routeOptions.path,
__uniapp_origin: style.uniNView.path.split('?')[0].replace('.js', ''),
__uniapp_origin_id: webview.id,
__uniapp_origin_type: webview.__uniapp_type
};
let maskWebview;
if (isNavigationBar) {
style.position = 'dock';
style.dock = 'top';
style.top = 0;
style.width = '100%';
style.height = TITLEBAR_HEIGHT + getStatusbarHeight();
delete style.left;
delete style.right;
delete style.bottom;
delete style.margin;
} else if (isPopup) {
style.position = 'absolute';
if (isTabBarPage(routeOptions.path)) {
maskWebview = tabBar$1;
} else {
maskWebview = webview;
}
extras.__uniapp_mask = style.mask || 'rgba(0,0,0,0.5)';
extras.__uniapp_mask_id = maskWebview.id;
}
if (process.env.NODE_ENV !== 'production') {
console.log(
`UNIAPP[webview][${webview.id}]:create[${subNVue.id}]:${JSON.stringify(style)}`
);
}
const subNVueWebview = plus.webview.create('', subNVue.id, style, extras);
if (isPopup) {
initPopupSubNVue(subNVueWebview, style, maskWebview);
} else {
initNormalSubNVue(subNVueWebview, style, webview);
}
}
function initSubNVues (routeOptions, webview) {
const subNVues = routeOptions.window.subNVues;
if (!subNVues || !subNVues.length) {
return
}
subNVues.forEach(subNVue => {
initSubNVue(subNVue, routeOptions, webview);
});
}
function onWebviewClose (webview) {
......@@ -8791,6 +8796,92 @@ var serviceContext = (function () {
: requestComponentInfo(pageVm, queue, callback);
}
const eventNames = [
'load',
'close',
'error'
];
class RewardedVideoAd {
constructor (adpid) {
this._options = {
adpid: adpid
};
const _callbacks = this._callbacks = {};
eventNames.forEach(item => {
_callbacks[item] = [];
const name = item[0].toUpperCase() + item.substr(1);
this[`on${name}`] = function (callback) {
_callbacks[item].push(callback);
};
});
this._isLoad = false;
this._loadPromiseResolve = null;
this._loadPromisereject = null;
const rewardAd = this._rewardAd = plus.ad.createRewardedVideoAd(this._options);
rewardAd.onLoad((e) => {
this._isLoad = true;
this._dispatchEvent('load', {});
if(this._loadPromiseResolve != null) {
this._loadPromiseResolve();
this._loadPromiseResolve = null;
}
});
rewardAd.onClose((e) => {
this._dispatchEvent('close', {isEnded: e.isEnded});
});
rewardAd.onError((e) => {
const detail = {code: e.code, message: e.message};
this._dispatchEvent('error', detail);
if(this._loadPromisereject != null) {
this._loadPromisereject(detail);
this._loadPromisereject = null;
}
});
this._loadAd();
}
load () {
return new Promise((resolve, reject) => {
if(this._isLoad) {
resolve();
return
}
this._loadPromiseResolve = resolve;
this._loadPromisereject = reject;
this._loadAd();
})
}
show () {
return new Promise((resolve, reject) => {
if(this._isLoad) {
this._rewardAd.show();
resolve();
} else {
reject();
}
})
}
_loadAd () {
this._isLoad = false;
this._rewardAd.load();
}
_dispatchEvent(name, data) {
this._callbacks[name].forEach(callback => {
if (typeof callback === 'function') {
callback(data || {});
}
});
}
}
function createRewardedVideoAd ({
adpid = ''
} = {}) {
return new RewardedVideoAd(adpid)
}
var api = /*#__PURE__*/Object.freeze({
......@@ -8920,7 +9011,8 @@ var serviceContext = (function () {
setTabBarStyle: setTabBarStyle$2,
hideTabBar: hideTabBar$2,
showTabBar: showTabBar$2,
requestComponentInfo: requestComponentInfo$2
requestComponentInfo: requestComponentInfo$2,
createRewardedVideoAd: createRewardedVideoAd
});
var platformApi = Object.assign(Object.create(null), api, eventApis);
......@@ -8956,7 +9048,7 @@ var serviceContext = (function () {
return page && page.$page.id
}
const eventNames = [
const eventNames$1 = [
'canplay',
'play',
'pause',
......@@ -9021,7 +9113,7 @@ var serviceContext = (function () {
this.id = id;
this._callbacks = {};
this._options = {};
eventNames.forEach(name => {
eventNames$1.forEach(name => {
this._callbacks[name.toLowerCase()] = [];
});
props.forEach(item => {
......@@ -9075,7 +9167,7 @@ var serviceContext = (function () {
}
}
eventNames.forEach(item => {
eventNames$1.forEach(item => {
const name = item[0].toUpperCase() + item.substr(1);
item = item.toLowerCase();
InnerAudioContext.prototype[`on${name}`] = function (callback) {
......@@ -9140,7 +9232,7 @@ var serviceContext = (function () {
createInnerAudioContext: createInnerAudioContext
});
const eventNames$1 = [
const eventNames$2 = [
'canplay',
'play',
'pause',
......@@ -9153,7 +9245,7 @@ var serviceContext = (function () {
'waiting'
];
const callbacks$4 = {};
eventNames$1.forEach(name => {
eventNames$2.forEach(name => {
callbacks$4[name] = [];
});
......@@ -9267,7 +9359,7 @@ var serviceContext = (function () {
}
}
eventNames$1.forEach(item => {
eventNames$2.forEach(item => {
const name = item[0].toUpperCase() + item.substr(1);
BackgroundAudioManager.prototype[`on${name}`] = function (callback) {
callbacks$4[item].push(callback);
......@@ -9285,860 +9377,860 @@ var serviceContext = (function () {
getBackgroundAudioManager: getBackgroundAudioManager
});
const canvasEventCallbacks = createCallbacks('canvasEvent');
UniServiceJSBridge.subscribe('onDrawCanvas', ({
callbackId,
data
}) => {
const callback = canvasEventCallbacks.pop(callbackId);
if (callback) {
callback(data);
}
});
UniServiceJSBridge.subscribe('onCanvasMethodCallback', ({
callbackId,
data
}) => {
const callback = canvasEventCallbacks.pop(callbackId);
if (callback) {
callback(data);
}
});
function operateCanvas (canvasId, pageId, type, data) {
UniServiceJSBridge.publishHandler(pageId + '-canvas-' + canvasId, {
canvasId,
type,
data
}, pageId);
}
const predefinedColor = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgrey: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
grey: '#808080',
green: '#008000',
greenyellow: '#adff2f',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgrey: '#d3d3d3',
lightgreen: '#90ee90',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32',
transparent: '#00000000'
};
function checkColor (e) {
var t = null;
if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) {
let n = parseInt(t[1].slice(0, 2), 16);
let o = parseInt(t[1].slice(2, 4), 16);
let r = parseInt(t[1].slice(4), 16);
return [n, o, r, 255]
}
if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) {
let n = t[1].slice(0, 1);
let o = t[1].slice(1, 2);
let r = t[1].slice(2, 3);
n = parseInt(n + n, 16);
o = parseInt(o + o, 16);
r = parseInt(r + r, 16);
return [n, o, r, 255]
}
if ((t = /^rgb\((.+)\)$/.exec(e)) != null) {
return t[1].split(',').map(function (e) {
return Math.min(255, parseInt(e.trim()))
}).concat(255)
}
if ((t = /^rgba\((.+)\)$/.exec(e)) != null) {
return t[1].split(',').map(function (e, t) {
return t === 3 ? Math.floor(255 * parseFloat(e.trim())) : Math.min(255, parseInt(e.trim()))
})
}
var i = e.toLowerCase();
if (predefinedColor.hasOwnProperty(i)) {
t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]);
let n = parseInt(t[1].slice(0, 2), 16);
let o = parseInt(t[1].slice(2, 4), 16);
let r = parseInt(t[1].slice(4, 6), 16);
let a = parseInt(t[1].slice(6, 8), 16);
a = a >= 0 ? a : 255;
return [n, o, r, a]
}
console.group('非法颜色: ' + e);
console.error('不支持颜色:' + e);
console.groupEnd();
return [0, 0, 0, 255]
}
function Pattern (image, repetition) {
this.image = image;
this.repetition = repetition;
}
class CanvasGradient {
constructor (type, data) {
this.type = type;
this.data = data;
this.colorStop = [];
}
addColorStop (position, color) {
this.colorStop.push([position, checkColor(color)]);
}
}
var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform'];
var methods2 = ['drawImage', 'fillText', 'fill', 'stroke', 'fillRect', 'strokeRect', 'clearRect',
'strokeText'
];
var methods3 = ['setFillStyle', 'setTextAlign', 'setStrokeStyle', 'setGlobalAlpha', 'setShadow',
'setFontSize', 'setLineCap', 'setLineJoin', 'setLineWidth', 'setMiterLimit',
'setTextBaseline', 'setLineDash'
];
var tempCanvas;
function getTempCanvas (width = 0, height = 0) {
if (!tempCanvas) {
tempCanvas = document.createElement('canvas');
}
tempCanvas.width = width;
tempCanvas.height = height;
return tempCanvas
}
function TextMetrics (width) {
this.width = width;
}
class CanvasContext {
constructor (id, pageId) {
this.id = id;
this.pageId = pageId;
this.actions = [];
this.path = [];
this.subpath = [];
this.currentTransform = [];
this.currentStepAnimates = [];
this.drawingState = [];
this.state = {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: '10px sans-serif',
fontSize: 10,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: 'sans-serif'
};
}
draw (reserve = false, callback) {
var actions = [...this.actions];
this.actions = [];
this.path = [];
var callbackId;
if (typeof callback === 'function') {
callbackId = canvasEventCallbacks.push(callback);
}
operateCanvas(this.id, this.pageId, 'actionsChanged', {
actions,
reserve,
callbackId
});
}
createLinearGradient (x0, y0, x1, y1) {
return new CanvasGradient('linear', [x0, y0, x1, y1])
}
createCircularGradient (x, y, r) {
return new CanvasGradient('radial', [x, y, r])
}
createPattern (image, repetition) {
if (undefined === repetition) {
console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present.");
} else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) {
console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.");
} else {
return new Pattern(image, repetition)
}
}
// TODO
measureText (text) {
if (typeof document === 'object') {
var c2d = getTempCanvas().getContext('2d');
c2d.font = this.state.font;
return new TextMetrics(c2d.measureText(text).width || 0)
} else {
return new TextMetrics(0)
}
}
save () {
this.actions.push({
method: 'save',
data: []
});
this.drawingState.push(this.state);
}
restore () {
this.actions.push({
method: 'restore',
data: []
});
this.state = this.drawingState.pop() || {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: '10px sans-serif',
fontSize: 10,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: 'sans-serif'
};
}
beginPath () {
this.path = [];
this.subpath = [];
}
moveTo (x, y) {
this.path.push({
method: 'moveTo',
data: [x, y]
});
this.subpath = [
[x, y]
];
}
lineTo (x, y) {
if (this.path.length === 0 && this.subpath.length === 0) {
this.path.push({
method: 'moveTo',
data: [x, y]
});
} else {
this.path.push({
method: 'lineTo',
data: [x, y]
});
}
this.subpath.push([x, y]);
}
quadraticCurveTo (cpx, cpy, x, y) {
this.path.push({
method: 'quadraticCurveTo',
data: [cpx, cpy, x, y]
});
this.subpath.push([x, y]);
}
bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) {
this.path.push({
method: 'bezierCurveTo',
data: [cp1x, cp1y, cp2x, cp2y, x, y]
});
this.subpath.push([x, y]);
}
arc (x, y, r, sAngle, eAngle, counterclockwise = false) {
this.path.push({
method: 'arc',
data: [x, y, r, sAngle, eAngle, counterclockwise]
});
this.subpath.push([x, y]);
}
rect (x, y, width, height) {
this.path.push({
method: 'rect',
data: [x, y, width, height]
});
this.subpath = [
[x, y]
];
}
arcTo (x1, y1, x2, y2, radius) {
this.path.push({
method: 'arcTo',
data: [x1, y1, x2, y2, radius]
});
this.subpath.push([x2, y2]);
}
clip () {
this.actions.push({
method: 'clip',
data: [...this.path]
});
}
closePath () {
this.path.push({
method: 'closePath',
data: []
});
if (this.subpath.length) {
this.subpath = [this.subpath.shift()];
}
}
clearActions () {
this.actions = [];
this.path = [];
this.subpath = [];
}
getActions () {
var actions = [...this.actions];
this.clearActions();
return actions
}
set lineDashOffset (value) {
this.actions.push({
method: 'setLineDashOffset',
data: [value]
});
}
set globalCompositeOperation (type) {
this.actions.push({
method: 'setGlobalCompositeOperation',
data: [type]
});
}
set shadowBlur (level) {
this.actions.push({
method: 'setShadowBlur',
data: [level]
});
}
set shadowColor (color) {
this.actions.push({
method: 'setShadowColor',
data: [color]
});
}
set shadowOffsetX (x) {
this.actions.push({
method: 'setShadowOffsetX',
data: [x]
});
}
set shadowOffsetY (y) {
this.actions.push({
method: 'setShadowOffsetY',
data: [y]
});
}
set font (value) {
var self = this;
this.state.font = value;
// eslint-disable-next-line
var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/);
if (fontFormat) {
var style = fontFormat[1].trim().split(/\s/);
var fontSize = parseFloat(fontFormat[3]);
var fontFamily = fontFormat[7];
var actions = [];
style.forEach(function (value, index) {
if (['italic', 'oblique', 'normal'].indexOf(value) > -1) {
actions.push({
method: 'setFontStyle',
data: [value]
});
self.state.fontStyle = value;
} else if (['bold', 'normal'].indexOf(value) > -1) {
actions.push({
method: 'setFontWeight',
data: [value]
});
self.state.fontWeight = value;
} else if (index === 0) {
actions.push({
method: 'setFontStyle',
data: ['normal']
});
self.state.fontStyle = 'normal';
} else if (index === 1) {
pushAction();
}
});
if (style.length === 1) {
pushAction();
}
style = actions.map(function (action) {
return action.data[0]
}).join(' ');
this.state.fontSize = fontSize;
this.state.fontFamily = fontFamily;
this.actions.push({
method: 'setFont',
data: [`${style} ${fontSize}px ${fontFamily}`]
});
} else {
console.warn("Failed to set 'font' on 'CanvasContext': invalid format.");
}
function pushAction () {
actions.push({
method: 'setFontWeight',
data: ['normal']
});
self.state.fontWeight = 'normal';
}
}
get font () {
return this.state.font
}
set fillStyle (color) {
this.setFillStyle(color);
}
set strokeStyle (color) {
this.setStrokeStyle(color);
}
set globalAlpha (value) {
value = Math.floor(255 * parseFloat(value));
this.actions.push({
method: 'setGlobalAlpha',
data: [value]
});
}
set textAlign (align) {
this.actions.push({
method: 'setTextAlign',
data: [align]
});
}
set lineCap (type) {
this.actions.push({
method: 'setLineCap',
data: [type]
});
}
set lineJoin (type) {
this.actions.push({
method: 'setLineJoin',
data: [type]
});
}
set lineWidth (value) {
this.actions.push({
method: 'setLineWidth',
data: [value]
});
}
set miterLimit (value) {
this.actions.push({
method: 'setMiterLimit',
data: [value]
});
}
set textBaseline (type) {
this.actions.push({
method: 'setTextBaseline',
data: [type]
});
}
}
[...methods1, ...methods2].forEach(function (method) {
function get (method) {
switch (method) {
case 'fill':
case 'stroke':
return function () {
this.actions.push({
method: method + 'Path',
data: [...this.path]
});
}
case 'fillRect':
return function (x, y, width, height) {
this.actions.push({
method: 'fillPath',
data: [{
method: 'rect',
data: [x, y, width, height]
}]
});
}
case 'strokeRect':
return function (x, y, width, height) {
this.actions.push({
method: 'strokePath',
data: [{
method: 'rect',
data: [x, y, width, height]
}]
});
}
case 'fillText':
case 'strokeText':
return function (text, x, y, maxWidth) {
var data = [text.toString(), x, y];
if (typeof maxWidth === 'number') {
data.push(maxWidth);
}
this.actions.push({
method,
data
});
}
case 'drawImage':
return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) {
if (sHeight === undefined) {
sx = dx;
sy = dy;
sWidth = dWidth;
sHeight = dHeight;
dx = undefined;
dy = undefined;
dWidth = undefined;
dHeight = undefined;
}
var data;
function isNumber (e) {
return typeof e === 'number'
}
data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight] : isNumber(sWidth) && isNumber(
sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy];
this.actions.push({
method,
data
});
}
default:
return function (...data) {
this.actions.push({
method,
data
});
}
}
}
CanvasContext.prototype[method] = get(method);
});
methods3.forEach(function (method) {
function get (method) {
switch (method) {
case 'setFillStyle':
case 'setStrokeStyle':
return function (color) {
if (typeof color !== 'object') {
this.actions.push({
method,
data: ['normal', checkColor(color)]
});
} else {
this.actions.push({
method,
data: [color.type, color.data, color.colorStop]
});
}
}
case 'setGlobalAlpha':
return function (alpha) {
alpha = Math.floor(255 * parseFloat(alpha));
this.actions.push({
method,
data: [alpha]
});
}
case 'setShadow':
return function (offsetX, offsetY, blur, color) {
color = checkColor(color);
this.actions.push({
method,
data: [offsetX, offsetY, blur, color]
});
this.state.shadowBlur = blur;
this.state.shadowColor = color;
this.state.shadowOffsetX = offsetX;
this.state.shadowOffsetY = offsetY;
}
case 'setLineDash':
return function (pattern, offset) {
pattern = pattern || [0, 0];
offset = offset || 0;
this.actions.push({
method,
data: [pattern, offset]
});
this.state.lineDash = pattern;
}
case 'setFontSize':
return function (fontSize) {
this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px');
this.state.fontSize = fontSize;
this.actions.push({
method,
data: [fontSize]
});
}
default:
return function (...data) {
this.actions.push({
method,
data
});
}
}
}
CanvasContext.prototype[method] = get(method);
});
function createCanvasContext$1 (id, context) {
if (context) {
return new CanvasContext(id, context.$page.id)
}
const pageId = getCurrentPageId();
if (pageId) {
return new CanvasContext(id, pageId)
} else {
UniServiceJSBridge.emit('onError', 'createCanvasContext:fail');
}
}
function canvasGetImageData$1 ({
canvasId,
x,
y,
width,
height
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasGetImageData:fail'
});
return
}
var cId = canvasEventCallbacks.push(function (data) {
var imgData = data.data;
if (imgData && imgData.length) {
data.data = new Uint8ClampedArray(imgData);
}
invoke$1(callbackId, data);
});
operateCanvas(canvasId, pageId, 'getImageData', {
x,
y,
width,
height,
callbackId: cId
});
}
function canvasPutImageData$1 ({
canvasId,
data,
x,
y,
width,
height
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasPutImageData:fail'
});
return
}
var cId = canvasEventCallbacks.push(function (data) {
invoke$1(callbackId, data);
});
operateCanvas(canvasId, pageId, 'putImageData', {
data: [...data],
x,
y,
width,
height,
callbackId: cId
});
}
function canvasToTempFilePath$1 ({
x = 0,
y = 0,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
qualit
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasToTempFilePath:fail'
});
return
}
const cId = canvasEventCallbacks.push(function ({
base64
}) {
if (!base64 || !base64.length) {
invoke$1(callbackId, {
errMsg: 'canvasToTempFilePath:fail'
});
}
invokeMethod('base64ToTempFilePath', {
base64Data: base64,
x,
y,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
qualit
}, callbackId);
});
operateCanvas(canvasId, pageId, 'getDataUrl', {
x,
y,
width,
height,
destWidth,
destHeight,
hidpi: false,
fileType,
qualit,
callbackId: cId
});
const canvasEventCallbacks = createCallbacks('canvasEvent');
UniServiceJSBridge.subscribe('onDrawCanvas', ({
callbackId,
data
}) => {
const callback = canvasEventCallbacks.pop(callbackId);
if (callback) {
callback(data);
}
});
UniServiceJSBridge.subscribe('onCanvasMethodCallback', ({
callbackId,
data
}) => {
const callback = canvasEventCallbacks.pop(callbackId);
if (callback) {
callback(data);
}
});
function operateCanvas (canvasId, pageId, type, data) {
UniServiceJSBridge.publishHandler(pageId + '-canvas-' + canvasId, {
canvasId,
type,
data
}, pageId);
}
const predefinedColor = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgrey: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
grey: '#808080',
green: '#008000',
greenyellow: '#adff2f',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgrey: '#d3d3d3',
lightgreen: '#90ee90',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32',
transparent: '#00000000'
};
function checkColor (e) {
var t = null;
if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) {
let n = parseInt(t[1].slice(0, 2), 16);
let o = parseInt(t[1].slice(2, 4), 16);
let r = parseInt(t[1].slice(4), 16);
return [n, o, r, 255]
}
if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) {
let n = t[1].slice(0, 1);
let o = t[1].slice(1, 2);
let r = t[1].slice(2, 3);
n = parseInt(n + n, 16);
o = parseInt(o + o, 16);
r = parseInt(r + r, 16);
return [n, o, r, 255]
}
if ((t = /^rgb\((.+)\)$/.exec(e)) != null) {
return t[1].split(',').map(function (e) {
return Math.min(255, parseInt(e.trim()))
}).concat(255)
}
if ((t = /^rgba\((.+)\)$/.exec(e)) != null) {
return t[1].split(',').map(function (e, t) {
return t === 3 ? Math.floor(255 * parseFloat(e.trim())) : Math.min(255, parseInt(e.trim()))
})
}
var i = e.toLowerCase();
if (predefinedColor.hasOwnProperty(i)) {
t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]);
let n = parseInt(t[1].slice(0, 2), 16);
let o = parseInt(t[1].slice(2, 4), 16);
let r = parseInt(t[1].slice(4, 6), 16);
let a = parseInt(t[1].slice(6, 8), 16);
a = a >= 0 ? a : 255;
return [n, o, r, a]
}
console.group('非法颜色: ' + e);
console.error('不支持颜色:' + e);
console.groupEnd();
return [0, 0, 0, 255]
}
function Pattern (image, repetition) {
this.image = image;
this.repetition = repetition;
}
class CanvasGradient {
constructor (type, data) {
this.type = type;
this.data = data;
this.colorStop = [];
}
addColorStop (position, color) {
this.colorStop.push([position, checkColor(color)]);
}
}
var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform'];
var methods2 = ['drawImage', 'fillText', 'fill', 'stroke', 'fillRect', 'strokeRect', 'clearRect',
'strokeText'
];
var methods3 = ['setFillStyle', 'setTextAlign', 'setStrokeStyle', 'setGlobalAlpha', 'setShadow',
'setFontSize', 'setLineCap', 'setLineJoin', 'setLineWidth', 'setMiterLimit',
'setTextBaseline', 'setLineDash'
];
var tempCanvas;
function getTempCanvas (width = 0, height = 0) {
if (!tempCanvas) {
tempCanvas = document.createElement('canvas');
}
tempCanvas.width = width;
tempCanvas.height = height;
return tempCanvas
}
function TextMetrics (width) {
this.width = width;
}
class CanvasContext {
constructor (id, pageId) {
this.id = id;
this.pageId = pageId;
this.actions = [];
this.path = [];
this.subpath = [];
this.currentTransform = [];
this.currentStepAnimates = [];
this.drawingState = [];
this.state = {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: '10px sans-serif',
fontSize: 10,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: 'sans-serif'
};
}
draw (reserve = false, callback) {
var actions = [...this.actions];
this.actions = [];
this.path = [];
var callbackId;
if (typeof callback === 'function') {
callbackId = canvasEventCallbacks.push(callback);
}
operateCanvas(this.id, this.pageId, 'actionsChanged', {
actions,
reserve,
callbackId
});
}
createLinearGradient (x0, y0, x1, y1) {
return new CanvasGradient('linear', [x0, y0, x1, y1])
}
createCircularGradient (x, y, r) {
return new CanvasGradient('radial', [x, y, r])
}
createPattern (image, repetition) {
if (undefined === repetition) {
console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present.");
} else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) {
console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.");
} else {
return new Pattern(image, repetition)
}
}
// TODO
measureText (text) {
if (typeof document === 'object') {
var c2d = getTempCanvas().getContext('2d');
c2d.font = this.state.font;
return new TextMetrics(c2d.measureText(text).width || 0)
} else {
return new TextMetrics(0)
}
}
save () {
this.actions.push({
method: 'save',
data: []
});
this.drawingState.push(this.state);
}
restore () {
this.actions.push({
method: 'restore',
data: []
});
this.state = this.drawingState.pop() || {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: '10px sans-serif',
fontSize: 10,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: 'sans-serif'
};
}
beginPath () {
this.path = [];
this.subpath = [];
}
moveTo (x, y) {
this.path.push({
method: 'moveTo',
data: [x, y]
});
this.subpath = [
[x, y]
];
}
lineTo (x, y) {
if (this.path.length === 0 && this.subpath.length === 0) {
this.path.push({
method: 'moveTo',
data: [x, y]
});
} else {
this.path.push({
method: 'lineTo',
data: [x, y]
});
}
this.subpath.push([x, y]);
}
quadraticCurveTo (cpx, cpy, x, y) {
this.path.push({
method: 'quadraticCurveTo',
data: [cpx, cpy, x, y]
});
this.subpath.push([x, y]);
}
bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) {
this.path.push({
method: 'bezierCurveTo',
data: [cp1x, cp1y, cp2x, cp2y, x, y]
});
this.subpath.push([x, y]);
}
arc (x, y, r, sAngle, eAngle, counterclockwise = false) {
this.path.push({
method: 'arc',
data: [x, y, r, sAngle, eAngle, counterclockwise]
});
this.subpath.push([x, y]);
}
rect (x, y, width, height) {
this.path.push({
method: 'rect',
data: [x, y, width, height]
});
this.subpath = [
[x, y]
];
}
arcTo (x1, y1, x2, y2, radius) {
this.path.push({
method: 'arcTo',
data: [x1, y1, x2, y2, radius]
});
this.subpath.push([x2, y2]);
}
clip () {
this.actions.push({
method: 'clip',
data: [...this.path]
});
}
closePath () {
this.path.push({
method: 'closePath',
data: []
});
if (this.subpath.length) {
this.subpath = [this.subpath.shift()];
}
}
clearActions () {
this.actions = [];
this.path = [];
this.subpath = [];
}
getActions () {
var actions = [...this.actions];
this.clearActions();
return actions
}
set lineDashOffset (value) {
this.actions.push({
method: 'setLineDashOffset',
data: [value]
});
}
set globalCompositeOperation (type) {
this.actions.push({
method: 'setGlobalCompositeOperation',
data: [type]
});
}
set shadowBlur (level) {
this.actions.push({
method: 'setShadowBlur',
data: [level]
});
}
set shadowColor (color) {
this.actions.push({
method: 'setShadowColor',
data: [color]
});
}
set shadowOffsetX (x) {
this.actions.push({
method: 'setShadowOffsetX',
data: [x]
});
}
set shadowOffsetY (y) {
this.actions.push({
method: 'setShadowOffsetY',
data: [y]
});
}
set font (value) {
var self = this;
this.state.font = value;
// eslint-disable-next-line
var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/);
if (fontFormat) {
var style = fontFormat[1].trim().split(/\s/);
var fontSize = parseFloat(fontFormat[3]);
var fontFamily = fontFormat[7];
var actions = [];
style.forEach(function (value, index) {
if (['italic', 'oblique', 'normal'].indexOf(value) > -1) {
actions.push({
method: 'setFontStyle',
data: [value]
});
self.state.fontStyle = value;
} else if (['bold', 'normal'].indexOf(value) > -1) {
actions.push({
method: 'setFontWeight',
data: [value]
});
self.state.fontWeight = value;
} else if (index === 0) {
actions.push({
method: 'setFontStyle',
data: ['normal']
});
self.state.fontStyle = 'normal';
} else if (index === 1) {
pushAction();
}
});
if (style.length === 1) {
pushAction();
}
style = actions.map(function (action) {
return action.data[0]
}).join(' ');
this.state.fontSize = fontSize;
this.state.fontFamily = fontFamily;
this.actions.push({
method: 'setFont',
data: [`${style} ${fontSize}px ${fontFamily}`]
});
} else {
console.warn("Failed to set 'font' on 'CanvasContext': invalid format.");
}
function pushAction () {
actions.push({
method: 'setFontWeight',
data: ['normal']
});
self.state.fontWeight = 'normal';
}
}
get font () {
return this.state.font
}
set fillStyle (color) {
this.setFillStyle(color);
}
set strokeStyle (color) {
this.setStrokeStyle(color);
}
set globalAlpha (value) {
value = Math.floor(255 * parseFloat(value));
this.actions.push({
method: 'setGlobalAlpha',
data: [value]
});
}
set textAlign (align) {
this.actions.push({
method: 'setTextAlign',
data: [align]
});
}
set lineCap (type) {
this.actions.push({
method: 'setLineCap',
data: [type]
});
}
set lineJoin (type) {
this.actions.push({
method: 'setLineJoin',
data: [type]
});
}
set lineWidth (value) {
this.actions.push({
method: 'setLineWidth',
data: [value]
});
}
set miterLimit (value) {
this.actions.push({
method: 'setMiterLimit',
data: [value]
});
}
set textBaseline (type) {
this.actions.push({
method: 'setTextBaseline',
data: [type]
});
}
}
[...methods1, ...methods2].forEach(function (method) {
function get (method) {
switch (method) {
case 'fill':
case 'stroke':
return function () {
this.actions.push({
method: method + 'Path',
data: [...this.path]
});
}
case 'fillRect':
return function (x, y, width, height) {
this.actions.push({
method: 'fillPath',
data: [{
method: 'rect',
data: [x, y, width, height]
}]
});
}
case 'strokeRect':
return function (x, y, width, height) {
this.actions.push({
method: 'strokePath',
data: [{
method: 'rect',
data: [x, y, width, height]
}]
});
}
case 'fillText':
case 'strokeText':
return function (text, x, y, maxWidth) {
var data = [text.toString(), x, y];
if (typeof maxWidth === 'number') {
data.push(maxWidth);
}
this.actions.push({
method,
data
});
}
case 'drawImage':
return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) {
if (sHeight === undefined) {
sx = dx;
sy = dy;
sWidth = dWidth;
sHeight = dHeight;
dx = undefined;
dy = undefined;
dWidth = undefined;
dHeight = undefined;
}
var data;
function isNumber (e) {
return typeof e === 'number'
}
data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight] : isNumber(sWidth) && isNumber(
sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy];
this.actions.push({
method,
data
});
}
default:
return function (...data) {
this.actions.push({
method,
data
});
}
}
}
CanvasContext.prototype[method] = get(method);
});
methods3.forEach(function (method) {
function get (method) {
switch (method) {
case 'setFillStyle':
case 'setStrokeStyle':
return function (color) {
if (typeof color !== 'object') {
this.actions.push({
method,
data: ['normal', checkColor(color)]
});
} else {
this.actions.push({
method,
data: [color.type, color.data, color.colorStop]
});
}
}
case 'setGlobalAlpha':
return function (alpha) {
alpha = Math.floor(255 * parseFloat(alpha));
this.actions.push({
method,
data: [alpha]
});
}
case 'setShadow':
return function (offsetX, offsetY, blur, color) {
color = checkColor(color);
this.actions.push({
method,
data: [offsetX, offsetY, blur, color]
});
this.state.shadowBlur = blur;
this.state.shadowColor = color;
this.state.shadowOffsetX = offsetX;
this.state.shadowOffsetY = offsetY;
}
case 'setLineDash':
return function (pattern, offset) {
pattern = pattern || [0, 0];
offset = offset || 0;
this.actions.push({
method,
data: [pattern, offset]
});
this.state.lineDash = pattern;
}
case 'setFontSize':
return function (fontSize) {
this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px');
this.state.fontSize = fontSize;
this.actions.push({
method,
data: [fontSize]
});
}
default:
return function (...data) {
this.actions.push({
method,
data
});
}
}
}
CanvasContext.prototype[method] = get(method);
});
function createCanvasContext$1 (id, context) {
if (context) {
return new CanvasContext(id, context.$page.id)
}
const pageId = getCurrentPageId();
if (pageId) {
return new CanvasContext(id, pageId)
} else {
UniServiceJSBridge.emit('onError', 'createCanvasContext:fail');
}
}
function canvasGetImageData$1 ({
canvasId,
x,
y,
width,
height
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasGetImageData:fail'
});
return
}
var cId = canvasEventCallbacks.push(function (data) {
var imgData = data.data;
if (imgData && imgData.length) {
data.data = new Uint8ClampedArray(imgData);
}
invoke$1(callbackId, data);
});
operateCanvas(canvasId, pageId, 'getImageData', {
x,
y,
width,
height,
callbackId: cId
});
}
function canvasPutImageData$1 ({
canvasId,
data,
x,
y,
width,
height
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasPutImageData:fail'
});
return
}
var cId = canvasEventCallbacks.push(function (data) {
invoke$1(callbackId, data);
});
operateCanvas(canvasId, pageId, 'putImageData', {
data: [...data],
x,
y,
width,
height,
callbackId: cId
});
}
function canvasToTempFilePath$1 ({
x = 0,
y = 0,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
qualit
}, callbackId) {
var pageId = getCurrentPageId();
if (!pageId) {
invoke$1(callbackId, {
errMsg: 'canvasToTempFilePath:fail'
});
return
}
const cId = canvasEventCallbacks.push(function ({
base64
}) {
if (!base64 || !base64.length) {
invoke$1(callbackId, {
errMsg: 'canvasToTempFilePath:fail'
});
}
invokeMethod('base64ToTempFilePath', {
base64Data: base64,
x,
y,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
qualit
}, callbackId);
});
operateCanvas(canvasId, pageId, 'getDataUrl', {
x,
y,
width,
height,
destWidth,
destHeight,
hidpi: false,
fileType,
qualit,
callbackId: cId
});
}
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
......@@ -10268,45 +10360,45 @@ var serviceContext = (function () {
createVideoContext: createVideoContext$1
});
function operateEditor (componentId, pageId, type, data) {
UniServiceJSBridge.publishHandler(pageId + '-editor-' + componentId, {
componentId,
type,
data
}, pageId);
}
UniServiceJSBridge.subscribe('onEditorMethodCallback', ({
callbackId,
data
}) => {
callback.invoke(callbackId, data);
});
const methods$1 = ['insertDivider', 'insertImage', 'insertText', 'setContents', 'getContents', 'clear', 'removeFormat', 'undo', 'redo'];
class EditorContext {
constructor (id, pageId) {
this.id = id;
this.pageId = pageId;
}
format (name, value) {
operateEditor(this.id, this.pageId, 'format', {
options: {
name,
value
}
});
}
}
methods$1.forEach(function (method) {
EditorContext.prototype[method] = callback.warp(function (options, callbackId) {
operateEditor(this.id, this.pageId, method, {
options,
callbackId
});
});
function operateEditor (componentId, pageId, type, data) {
UniServiceJSBridge.publishHandler(pageId + '-editor-' + componentId, {
componentId,
type,
data
}, pageId);
}
UniServiceJSBridge.subscribe('onEditorMethodCallback', ({
callbackId,
data
}) => {
callback.invoke(callbackId, data);
});
const methods$1 = ['insertDivider', 'insertImage', 'insertText', 'setContents', 'getContents', 'clear', 'removeFormat', 'undo', 'redo'];
class EditorContext {
constructor (id, pageId) {
this.id = id;
this.pageId = pageId;
}
format (name, value) {
operateEditor(this.id, this.pageId, 'format', {
options: {
name,
value
}
});
}
}
methods$1.forEach(function (method) {
EditorContext.prototype[method] = callback.warp(function (options, callbackId) {
operateEditor(this.id, this.pageId, method, {
options,
callbackId
});
});
});
var require_context_module_1_9 = /*#__PURE__*/Object.freeze({
......@@ -10450,77 +10542,77 @@ var serviceContext = (function () {
onNetworkStatusChange: onNetworkStatusChange
});
const callbacks$8 = {
pause: [],
resume: [],
start: [],
stop: [],
error: []
};
class RecorderManager {
constructor () {
onMethod('onRecorderStateChange', res => {
const state = res.state;
delete res.state;
delete res.errMsg;
callbacks$8[state].forEach(callback => {
if (typeof callback === 'function') {
callback(res);
}
});
});
}
onError (callback) {
callbacks$8.error.push(callback);
}
onFrameRecorded (callback) {
}
onInterruptionBegin (callback) {
}
onInterruptionEnd (callback) {
}
onPause (callback) {
callbacks$8.pause.push(callback);
}
onResume (callback) {
callbacks$8.resume.push(callback);
}
onStart (callback) {
callbacks$8.start.push(callback);
}
onStop (callback) {
callbacks$8.stop.push(callback);
}
pause () {
invokeMethod('operateRecorder', {
operationType: 'pause'
});
}
resume () {
invokeMethod('operateRecorder', {
operationType: 'resume'
});
}
start (options) {
invokeMethod('operateRecorder', Object.assign({}, options, {
operationType: 'start'
}));
}
stop () {
invokeMethod('operateRecorder', {
operationType: 'stop'
});
}
}
let recorderManager;
function getRecorderManager () {
return recorderManager || (recorderManager = new RecorderManager())
const callbacks$8 = {
pause: [],
resume: [],
start: [],
stop: [],
error: []
};
class RecorderManager {
constructor () {
onMethod('onRecorderStateChange', res => {
const state = res.state;
delete res.state;
delete res.errMsg;
callbacks$8[state].forEach(callback => {
if (typeof callback === 'function') {
callback(res);
}
});
});
}
onError (callback) {
callbacks$8.error.push(callback);
}
onFrameRecorded (callback) {
}
onInterruptionBegin (callback) {
}
onInterruptionEnd (callback) {
}
onPause (callback) {
callbacks$8.pause.push(callback);
}
onResume (callback) {
callbacks$8.resume.push(callback);
}
onStart (callback) {
callbacks$8.start.push(callback);
}
onStop (callback) {
callbacks$8.stop.push(callback);
}
pause () {
invokeMethod('operateRecorder', {
operationType: 'pause'
});
}
resume () {
invokeMethod('operateRecorder', {
operationType: 'resume'
});
}
start (options) {
invokeMethod('operateRecorder', Object.assign({}, options, {
operationType: 'start'
}));
}
stop () {
invokeMethod('operateRecorder', {
operationType: 'stop'
});
}
}
let recorderManager;
function getRecorderManager () {
return recorderManager || (recorderManager = new RecorderManager())
}
var require_context_module_1_14 = /*#__PURE__*/Object.freeze({
......@@ -10996,6 +11088,23 @@ var serviceContext = (function () {
const STORAGE_DATA_TYPE = '__TYPE';
const STORAGE_KEYS = 'uni-storage-keys';
function parseValue (value) {
const types = ['object', 'string', 'number', 'boolean', 'undefined'];
try {
const object = typeof value === 'string' ? JSON.parse(value) : value;
const type = object.type;
if (types.indexOf(type) >= 0) {
const keys = Object.keys(object);
// eslint-disable-next-line valid-typeof
if (keys.length === 2 && 'data' in object && typeof object.data === type) {
return object.data
} else if (keys.length === 1) {
return ''
}
}
} catch (error) { }
}
function setStorage$1 ({
key,
data
......@@ -11006,6 +11115,11 @@ var serviceContext = (function () {
data: data
});
try {
if (type === 'string' && parseValue(value) !== undefined) {
localStorage.setItem(key + STORAGE_DATA_TYPE, type);
} else {
localStorage.removeItem(key + STORAGE_DATA_TYPE);
}
localStorage.setItem(key, value);
} catch (error) {
return {
......@@ -11035,22 +11149,26 @@ var serviceContext = (function () {
}
}
let data = value;
try {
const object = JSON.parse(value);
// 兼容App端历史格式
const type = localStorage.getItem(key + STORAGE_DATA_TYPE);
if (!type) {
const keys = Object.keys(object);
if (keys.length === 2 && 'type' in object && 'data' in object) {
data = object.data;
} else if (keys.length === 1 && 'type' in object) {
data = '';
const typeOrigin = localStorage.getItem(key + STORAGE_DATA_TYPE) || '';
const type = typeOrigin.toLowerCase();
if (type !== 'string' || (typeOrigin === 'String' && value === '{"type":"undefined"}')) {
try {
// 兼容H5和V3初期历史格式
let object = JSON.parse(value);
const result = parseValue(object);
if (result !== undefined) {
data = result;
} else if (type) {
// 兼容App端历史格式
data = object;
if (typeof object === 'string') {
object = JSON.parse(object);
// eslint-disable-next-line valid-typeof
data = typeof object === (type === 'null' ? 'object' : type) ? object : data;
}
}
} else if (type !== 'String') {
data = object;
data = typeof data === 'string' ? JSON.parse(data) : data;
}
} catch (error) { }
} catch (error) { }
}
return {
data,
errMsg: 'getStorage:ok'
......@@ -11134,82 +11252,82 @@ var serviceContext = (function () {
getStorageInfoSync: getStorageInfoSync
});
const defaultOption = {
duration: 400,
timingFunction: 'linear',
delay: 0,
transformOrigin: '50% 50% 0'
};
class MPAnimation {
constructor (option) {
this.actions = [];
this.currentTransform = {};
this.currentStepAnimates = [];
this.option = Object.assign({}, defaultOption, option);
}
_getOption (option) {
let _option = {
transition: Object.assign({}, this.option, option)
};
_option.transformOrigin = _option.transition.transformOrigin;
delete _option.transition.transformOrigin;
return _option
}
_pushAnimates (type, args) {
this.currentStepAnimates.push({
type: type,
args: args
});
}
_converType (type) {
return type.replace(/[A-Z]/g, text => {
return `-${text.toLowerCase()}`
})
}
_getValue (value) {
return typeof value === 'number' ? `${value}px` : value
}
export () {
const actions = this.actions;
this.actions = [];
return {
actions
}
}
step (option) {
this.currentStepAnimates.forEach(animate => {
if (animate.type !== 'style') {
this.currentTransform[animate.type] = animate;
} else {
this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate;
}
});
this.actions.push({
animates: Object.values(this.currentTransform),
option: this._getOption(option)
});
this.currentStepAnimates = [];
return this
}
}
const animateTypes1 = ['matrix', 'matrix3d', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ'];
const animateTypes2 = ['opacity', 'backgroundColor'];
const animateTypes3 = ['width', 'height', 'left', 'right', 'top', 'bottom'];
animateTypes1.concat(animateTypes2, animateTypes3).forEach(type => {
MPAnimation.prototype[type] = function (...args) {
if (animateTypes2.concat(animateTypes3).includes(type)) {
this._pushAnimates('style', [this._converType(type), animateTypes3.includes(type) ? this._getValue(args[0]) : args[0]]);
} else {
this._pushAnimates(type, args);
}
return this
};
});
function createAnimation (option) {
return new MPAnimation(option)
const defaultOption = {
duration: 400,
timingFunction: 'linear',
delay: 0,
transformOrigin: '50% 50% 0'
};
class MPAnimation {
constructor (option) {
this.actions = [];
this.currentTransform = {};
this.currentStepAnimates = [];
this.option = Object.assign({}, defaultOption, option);
}
_getOption (option) {
let _option = {
transition: Object.assign({}, this.option, option)
};
_option.transformOrigin = _option.transition.transformOrigin;
delete _option.transition.transformOrigin;
return _option
}
_pushAnimates (type, args) {
this.currentStepAnimates.push({
type: type,
args: args
});
}
_converType (type) {
return type.replace(/[A-Z]/g, text => {
return `-${text.toLowerCase()}`
})
}
_getValue (value) {
return typeof value === 'number' ? `${value}px` : value
}
export () {
const actions = this.actions;
this.actions = [];
return {
actions
}
}
step (option) {
this.currentStepAnimates.forEach(animate => {
if (animate.type !== 'style') {
this.currentTransform[animate.type] = animate;
} else {
this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate;
}
});
this.actions.push({
animates: Object.values(this.currentTransform),
option: this._getOption(option)
});
this.currentStepAnimates = [];
return this
}
}
const animateTypes1 = ['matrix', 'matrix3d', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ'];
const animateTypes2 = ['opacity', 'backgroundColor'];
const animateTypes3 = ['width', 'height', 'left', 'right', 'top', 'bottom'];
animateTypes1.concat(animateTypes2, animateTypes3).forEach(type => {
MPAnimation.prototype[type] = function (...args) {
if (animateTypes2.concat(animateTypes3).includes(type)) {
this._pushAnimates('style', [this._converType(type), animateTypes3.includes(type) ? this._getValue(args[0]) : args[0]]);
} else {
this._pushAnimates(type, args);
}
return this
};
});
function createAnimation (option) {
return new MPAnimation(option)
}
var require_context_module_1_20 = /*#__PURE__*/Object.freeze({
......@@ -11440,24 +11558,24 @@ var serviceContext = (function () {
onKeyboardHeightChange: onKeyboardHeightChange
});
UniServiceJSBridge.subscribe('onLoadFontFaceCallback', ({
callbackId,
data
}) => {
invoke$1(callbackId, data);
});
function loadFontFace$1 (options, callbackId) {
const pageId = getCurrentPageId();
if (!pageId) {
return {
errMsg: 'loadFontFace:fail not font page'
}
}
UniServiceJSBridge.publishHandler('loadFontFace', {
options,
callbackId
}, pageId);
UniServiceJSBridge.subscribe('onLoadFontFaceCallback', ({
callbackId,
data
}) => {
invoke$1(callbackId, data);
});
function loadFontFace$1 (options, callbackId) {
const pageId = getCurrentPageId();
if (!pageId) {
return {
errMsg: 'loadFontFace:fail not font page'
}
}
UniServiceJSBridge.publishHandler('loadFontFace', {
options,
callbackId
}, pageId);
}
var require_context_module_1_24 = /*#__PURE__*/Object.freeze({
......@@ -11930,21 +12048,21 @@ var serviceContext = (function () {
vm[method] && vm[method](args);
}
function findPage (pageId) {
pageId = parseInt(pageId);
const page = getCurrentPages(true).find(page => page.$page.id === pageId);
if (!page) {
return console.error(`Page[${pageId}] not found`)
}
return page
}
function onWebviewInserted (data, pageId) {
const page = findPage(pageId);
page && (page.__uniapp_webview = true);
}
function onWebviewRemoved (data, pageId) {
const page = findPage(pageId);
page && (delete page.__uniapp_webview);
function findPage (pageId) {
pageId = parseInt(pageId);
const page = getCurrentPages(true).find(page => page.$page.id === pageId);
if (!page) {
return console.error(`Page[${pageId}] not found`)
}
return page
}
function onWebviewInserted (data, pageId) {
const page = findPage(pageId);
page && (page.__uniapp_webview = true);
}
function onWebviewRemoved (data, pageId) {
const page = findPage(pageId);
page && (delete page.__uniapp_webview);
}
function initSubscribeHandlers () {
......@@ -12339,54 +12457,54 @@ var serviceContext = (function () {
};
}
const isAndroid = plus.os.name.toLowerCase() === 'android';
const FOCUS_TIMEOUT = isAndroid ? 300 : 700;
const HIDE_TIMEOUT = 800;
let keyboardHeight = 0;
let onKeyboardShow;
let focusTimer;
let hideKeyboardTimeout;
function hookKeyboardEvent (event, callback) {
onKeyboardShow = null;
focusTimer && clearTimeout(focusTimer);
if (event.type === 'focus') {
if (keyboardHeight > 0) {
event.detail.height = keyboardHeight;
} else {
focusTimer = setTimeout(function () {
event.detail.height = keyboardHeight;
callback(event);
}, FOCUS_TIMEOUT);
onKeyboardShow = function () {
clearTimeout(focusTimer);
event.detail.height = keyboardHeight;
callback(event);
};
return
}
}
callback(event);
}
onMethod('onKeyboardHeightChange', res => {
keyboardHeight = res.height;
if (keyboardHeight > 0) {
onKeyboardShow && onKeyboardShow();
if (hideKeyboardTimeout) {
clearTimeout(hideKeyboardTimeout);
hideKeyboardTimeout = null;
}
} else {
// 安卓/iOS13收起键盘时通知view层失去焦点
if (isAndroid || parseInt(plus.os.version) >= 13) {
hideKeyboardTimeout = setTimeout(function () {
hideKeyboardTimeout = null;
var pageId = getCurrentPageId();
UniServiceJSBridge.publishHandler('hideKeyboard', {}, pageId);
}, HIDE_TIMEOUT);
}
}
const isAndroid = plus.os.name.toLowerCase() === 'android';
const FOCUS_TIMEOUT = isAndroid ? 300 : 700;
const HIDE_TIMEOUT = 800;
let keyboardHeight = 0;
let onKeyboardShow;
let focusTimer;
let hideKeyboardTimeout;
function hookKeyboardEvent (event, callback) {
onKeyboardShow = null;
focusTimer && clearTimeout(focusTimer);
if (event.type === 'focus') {
if (keyboardHeight > 0) {
event.detail.height = keyboardHeight;
} else {
focusTimer = setTimeout(function () {
event.detail.height = keyboardHeight;
callback(event);
}, FOCUS_TIMEOUT);
onKeyboardShow = function () {
clearTimeout(focusTimer);
event.detail.height = keyboardHeight;
callback(event);
};
return
}
}
callback(event);
}
onMethod('onKeyboardHeightChange', res => {
keyboardHeight = res.height;
if (keyboardHeight > 0) {
onKeyboardShow && onKeyboardShow();
if (hideKeyboardTimeout) {
clearTimeout(hideKeyboardTimeout);
hideKeyboardTimeout = null;
}
} else {
// 安卓/iOS13收起键盘时通知view层失去焦点
if (isAndroid || parseInt(plus.os.version) >= 13) {
hideKeyboardTimeout = setTimeout(function () {
hideKeyboardTimeout = null;
var pageId = getCurrentPageId();
UniServiceJSBridge.publishHandler('hideKeyboard', {}, pageId);
}, HIDE_TIMEOUT);
}
}
});
function parseComponentCreateOptions (vm) {
......
const eventNames = [
'load',
'close',
'error'
]
class RewardedVideoAd {
constructor (adpid) {
this._options = {
adpid: adpid
}
const _callbacks = this._callbacks = {}
eventNames.forEach(item => {
_callbacks[item] = []
const name = item[0].toUpperCase() + item.substr(1)
this[`on${name}`] = function (callback) {
_callbacks[item].push(callback)
}
})
this._isLoad = false
this._adError = false
this._loadPromiseResolve = null
this._loadPromiseReject = null
const rewardAd = this._rewardAd = plus.ad.createRewardedVideoAd(this._options)
rewardAd.onLoad((e) => {
this._isLoad = true
this._dispatchEvent('load', {})
if (this._loadPromiseResolve != null) {
this._loadPromiseResolve()
this._loadPromiseResolve = null
}
})
rewardAd.onClose((e) => {
this._loadAd()
this._dispatchEvent('close', { isEnded: e.isEnded })
})
rewardAd.onError((e) => {
const { code } = e
this._adError = (code && code < 5005)
this._dispatchEvent('error', e)
if (code === 5005 && this._loadPromiseReject != null) {
this._loadPromiseReject(e)
this._loadPromiseReject = null
}
})
this._loadAd()
}
load () {
return new Promise((resolve, reject) => {
if (this._isLoad) {
resolve()
return
}
this._loadPromiseResolve = resolve
this._loadPromiseReject = reject
this._loadAd()
})
}
show () {
return new Promise((resolve, reject) => {
if (this._isLoad) {
this._rewardAd.show()
resolve()
} else {
reject(new Error(''))
}
})
}
_loadAd () {
if (this._adError) {
return
}
this._isLoad = false
this._rewardAd.load()
}
_dispatchEvent (name, data) {
this._callbacks[name].forEach(callback => {
if (typeof callback === 'function') {
callback(data || {})
}
})
}
}
export function createRewardedVideoAd ({
adpid = ''
} = {}) {
return new RewardedVideoAd(adpid)
}
......@@ -69,3 +69,5 @@ export {
export * from './ui/tab-bar'
export * from './ui/request-component-info'
export * from './ad/rewarded-video-ad'
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册