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

add api uni.createRewardedVideoAd

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