diff --git a/src/core/helpers/api.js b/src/core/helpers/api.js
index 59b086086c96541cfcea0bdcdefb01119b8f739a..4292d41c3f4dafaef06c2331e0453138321cbfad 100644
--- a/src/core/helpers/api.js
+++ b/src/core/helpers/api.js
@@ -108,7 +108,7 @@ function createApiCallback (apiName, params = {}, extras = {}) {
params = Object.assign({}, params)
const apiCallbacks = {}
- for (let name in params) {
+ for (const name in params) {
const param = params[name]
if (isFn(param)) {
apiCallbacks[name] = tryCatch(param)
@@ -135,7 +135,7 @@ function createApiCallback (apiName, params = {}, extras = {}) {
}
const wrapperCallbacks = {}
- for (let name in extras) {
+ for (const name in extras) {
const extra = extras[name]
if (isFn(extra)) {
wrapperCallbacks[name] = tryCatchFramework(extra)
@@ -165,7 +165,7 @@ function createApiCallback (apiName, params = {}, extras = {}) {
res.errMsg = apiName + ':cancel'
} else if (res.errMsg.indexOf(':fail') !== -1) {
let errDetail = ''
- let spaceIndex = res.errMsg.indexOf(' ')
+ const spaceIndex = res.errMsg.indexOf(' ')
if (spaceIndex > -1) {
errDetail = res.errMsg.substr(spaceIndex)
}
diff --git a/src/core/helpers/hidpi.js b/src/core/helpers/hidpi.js
index 0c131d1042b3ed645a63f5b3ce8102dad03f17ed..b2d06e6a59ab8cfca6e2c4585fc53cd068936ba8 100644
--- a/src/core/helpers/hidpi.js
+++ b/src/core/helpers/hidpi.js
@@ -1,166 +1,171 @@
-export const pixelRatio = (function () {
- const canvas = document.createElement('canvas')
- canvas.height = canvas.width = 0
- const context = canvas.getContext('2d')
- const backingStore = context.backingStorePixelRatio ||
- context.webkitBackingStorePixelRatio ||
- context.mozBackingStorePixelRatio ||
- context.msBackingStorePixelRatio ||
- context.oBackingStorePixelRatio ||
- context.backingStorePixelRatio || 1
- return (window.devicePixelRatio || 1) / backingStore
-})()
-
-const forEach = function (obj, func) {
- for (let key in obj) {
- if (obj.hasOwnProperty(key)) {
- func(obj[key], key)
- }
- }
-}
-const ratioArgs = {
- 'fillRect': 'all',
- 'clearRect': 'all',
- 'strokeRect': 'all',
- 'moveTo': 'all',
- 'lineTo': 'all',
- 'arc': [0, 1, 2],
- 'arcTo': 'all',
- 'bezierCurveTo': 'all',
- 'isPointinPath': 'all',
- 'isPointinStroke': 'all',
- 'quadraticCurveTo': 'all',
- 'rect': 'all',
- 'translate': 'all',
- 'createRadialGradient': 'all',
- 'createLinearGradient': 'all',
- 'setTransform': [4, 5]
-}
-
-const proto = CanvasRenderingContext2D.prototype
-
-proto.drawImageByCanvas = (function (_super) {
- return function (canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
- srcx *= pixelRatio
- srcy *= pixelRatio
- srcw *= pixelRatio
- srch *= pixelRatio
- desx *= pixelRatio
- desy *= pixelRatio
- desw = isScale ? desw * pixelRatio : desw
- desh = isScale ? desh * pixelRatio : desh
- _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh)
- }
-})(proto.drawImage)
-
-if (pixelRatio !== 1) {
- forEach(ratioArgs, function (value, key) {
- proto[key] = (function (_super) {
- return function () {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
-
- let args = Array.prototype.slice.call(arguments)
-
- if (value === 'all') {
- args = args.map(function (a) {
- return a * pixelRatio
- })
- } else if (Array.isArray(value)) {
- for (let i = 0; i < value.length; i++) {
- args[value[i]] *= pixelRatio
- }
- }
- return _super.apply(this, args)
- }
- })(proto[key])
- })
-
- proto.stroke = (function (_super) {
- return function () {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
- this.lineWidth *= pixelRatio
- _super.apply(this, arguments)
- this.lineWidth /= pixelRatio
- }
- })(proto.stroke)
-
- proto.fillText = (function (_super) {
- return function () {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
- const args = Array.prototype.slice.call(arguments)
-
- args[1] *= pixelRatio
- args[2] *= pixelRatio
-
- this.font = this.font.replace(
- /(\d+)(px|em|rem|pt)/g,
- function (w, m, u) {
- return (m * pixelRatio) + u
- }
- )
-
- _super.apply(this, args)
-
- this.font = this.font.replace(
- /(\d+)(px|em|rem|pt)/g,
- function (w, m, u) {
- return (m / pixelRatio) + u
- }
- )
- }
- })(proto.fillText)
-
- proto.strokeText = (function (_super) {
- return function () {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
- var args = Array.prototype.slice.call(arguments)
-
- args[1] *= pixelRatio // x
- args[2] *= pixelRatio // y
-
- this.font = this.font.replace(
- /(\d+)(px|em|rem|pt)/g,
- function (w, m, u) {
- return (m * pixelRatio) + u
- }
- )
-
- _super.apply(this, args)
-
- this.font = this.font.replace(
- /(\d+)(px|em|rem|pt)/g,
- function (w, m, u) {
- return (m / pixelRatio) + u
- }
- )
- }
- })(proto.strokeText)
-
- proto.drawImage = (function (_super) {
- return function () {
- if (!this.__hidpi__) {
- return _super.apply(this, arguments)
- }
- this.scale(pixelRatio, pixelRatio)
- _super.apply(this, arguments)
- this.scale(1 / pixelRatio, 1 / pixelRatio)
- }
- })(proto.drawImage)
-}
-
-export function wrapper (canvas) {
- canvas.width = canvas.offsetWidth * pixelRatio
- canvas.height = canvas.offsetHeight * pixelRatio
- canvas.getContext('2d').__hidpi__ = true
+import {
+ hasOwn
+}
+ from 'uni-shared'
+
+export const pixelRatio = (function () {
+ const canvas = document.createElement('canvas')
+ canvas.height = canvas.width = 0
+ const context = canvas.getContext('2d')
+ const backingStore = context.backingStorePixelRatio ||
+ context.webkitBackingStorePixelRatio ||
+ context.mozBackingStorePixelRatio ||
+ context.msBackingStorePixelRatio ||
+ context.oBackingStorePixelRatio ||
+ context.backingStorePixelRatio || 1
+ return (window.devicePixelRatio || 1) / backingStore
+})()
+
+const forEach = function (obj, func) {
+ for (const key in obj) {
+ if (hasOwn(obj, key)) {
+ func(obj[key], key)
+ }
+ }
+}
+const ratioArgs = {
+ fillRect: 'all',
+ clearRect: 'all',
+ strokeRect: 'all',
+ moveTo: 'all',
+ lineTo: 'all',
+ arc: [0, 1, 2],
+ arcTo: 'all',
+ bezierCurveTo: 'all',
+ isPointinPath: 'all',
+ isPointinStroke: 'all',
+ quadraticCurveTo: 'all',
+ rect: 'all',
+ translate: 'all',
+ createRadialGradient: 'all',
+ createLinearGradient: 'all',
+ setTransform: [4, 5]
+}
+
+const proto = CanvasRenderingContext2D.prototype
+
+proto.drawImageByCanvas = (function (_super) {
+ return function (canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+ srcx *= pixelRatio
+ srcy *= pixelRatio
+ srcw *= pixelRatio
+ srch *= pixelRatio
+ desx *= pixelRatio
+ desy *= pixelRatio
+ desw = isScale ? desw * pixelRatio : desw
+ desh = isScale ? desh * pixelRatio : desh
+ _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh)
+ }
+})(proto.drawImage)
+
+if (pixelRatio !== 1) {
+ forEach(ratioArgs, function (value, key) {
+ proto[key] = (function (_super) {
+ return function () {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+
+ let args = Array.prototype.slice.call(arguments)
+
+ if (value === 'all') {
+ args = args.map(function (a) {
+ return a * pixelRatio
+ })
+ } else if (Array.isArray(value)) {
+ for (let i = 0; i < value.length; i++) {
+ args[value[i]] *= pixelRatio
+ }
+ }
+ return _super.apply(this, args)
+ }
+ })(proto[key])
+ })
+
+ proto.stroke = (function (_super) {
+ return function () {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+ this.lineWidth *= pixelRatio
+ _super.apply(this, arguments)
+ this.lineWidth /= pixelRatio
+ }
+ })(proto.stroke)
+
+ proto.fillText = (function (_super) {
+ return function () {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+ const args = Array.prototype.slice.call(arguments)
+
+ args[1] *= pixelRatio
+ args[2] *= pixelRatio
+
+ this.font = this.font.replace(
+ /(\d+)(px|em|rem|pt)/g,
+ function (w, m, u) {
+ return (m * pixelRatio) + u
+ }
+ )
+
+ _super.apply(this, args)
+
+ this.font = this.font.replace(
+ /(\d+)(px|em|rem|pt)/g,
+ function (w, m, u) {
+ return (m / pixelRatio) + u
+ }
+ )
+ }
+ })(proto.fillText)
+
+ proto.strokeText = (function (_super) {
+ return function () {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+ var args = Array.prototype.slice.call(arguments)
+
+ args[1] *= pixelRatio // x
+ args[2] *= pixelRatio // y
+
+ this.font = this.font.replace(
+ /(\d+)(px|em|rem|pt)/g,
+ function (w, m, u) {
+ return (m * pixelRatio) + u
+ }
+ )
+
+ _super.apply(this, args)
+
+ this.font = this.font.replace(
+ /(\d+)(px|em|rem|pt)/g,
+ function (w, m, u) {
+ return (m / pixelRatio) + u
+ }
+ )
+ }
+ })(proto.strokeText)
+
+ proto.drawImage = (function (_super) {
+ return function () {
+ if (!this.__hidpi__) {
+ return _super.apply(this, arguments)
+ }
+ this.scale(pixelRatio, pixelRatio)
+ _super.apply(this, arguments)
+ this.scale(1 / pixelRatio, 1 / pixelRatio)
+ }
+ })(proto.drawImage)
+}
+
+export function wrapper (canvas) {
+ canvas.width = canvas.offsetWidth * pixelRatio
+ canvas.height = canvas.offsetHeight * pixelRatio
+ canvas.getContext('2d').__hidpi__ = true
}
diff --git a/src/core/helpers/params.js b/src/core/helpers/params.js
index 03175bdf242c1b6b5bc7fd16af2af186d535a322..f0610358e9216ddef7692ef12e641971ac72b262 100644
--- a/src/core/helpers/params.js
+++ b/src/core/helpers/params.js
@@ -18,7 +18,7 @@ export default function validateParam (key, paramTypes, paramsData) {
}
if (value === undefined) {
if (hasOwn(paramOptions, 'default')) {
- const paramDefault = paramOptions['default']
+ const paramDefault = paramOptions.default
value = isFn(paramDefault) ? paramDefault() : paramDefault
paramsData[key] = value // 默认值
}
diff --git a/src/core/helpers/protocol/device/make-phone-call.js b/src/core/helpers/protocol/device/make-phone-call.js
index 48719cd9821e4fbc1fafad3917aa32a50918fed7..5848e277a61cbc0e9c3d239050a41774454ee5a2 100644
--- a/src/core/helpers/protocol/device/make-phone-call.js
+++ b/src/core/helpers/protocol/device/make-phone-call.js
@@ -1,10 +1,10 @@
export const makePhoneCall = {
- 'phoneNumber': {
+ phoneNumber: {
type: String,
required: true,
validator (phoneNumber) {
if (!phoneNumber) {
- return `makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;`
+ return 'makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;'
}
}
}
diff --git a/src/core/helpers/protocol/media/choose-image.js b/src/core/helpers/protocol/media/choose-image.js
index 09a55e14f250a31cb879b6e980e4be2673322c02..ba626eddc08409ae3956ad2b98712e0e11897895 100644
--- a/src/core/helpers/protocol/media/choose-image.js
+++ b/src/core/helpers/protocol/media/choose-image.js
@@ -2,7 +2,7 @@ const SIZE_TYPES = ['original', 'compressed']
const SOURCE_TYPES = ['album', 'camera']
export const chooseImage = {
- 'count': {
+ count: {
type: Number,
required: false,
default: 9,
@@ -12,7 +12,7 @@ export const chooseImage = {
}
}
},
- 'sizeType': {
+ sizeType: {
type: [Array, String],
required: false,
default: SIZE_TYPES,
@@ -35,7 +35,7 @@ export const chooseImage = {
}
}
},
- 'sourceType': {
+ sourceType: {
type: Array,
required: false,
default: SOURCE_TYPES,
diff --git a/src/core/helpers/protocol/media/choose-video.js b/src/core/helpers/protocol/media/choose-video.js
index 426411814f0628316135b0a65999356c446912c6..566f8c1923bff558e3bafd722184e74b2951ec8f 100644
--- a/src/core/helpers/protocol/media/choose-video.js
+++ b/src/core/helpers/protocol/media/choose-video.js
@@ -1,7 +1,7 @@
const SOURCE_TYPES = ['album', 'camera']
export const chooseVideo = {
- 'sourceType': {
+ sourceType: {
type: Array,
required: false,
default: SOURCE_TYPES,
diff --git a/src/core/helpers/protocol/media/get-image-info.js b/src/core/helpers/protocol/media/get-image-info.js
index 7245223fa84adf3db94adbfbbc8082ccc08045ad..2da4c0d63920c8a344d1cf152d9039bfbe996ea3 100644
--- a/src/core/helpers/protocol/media/get-image-info.js
+++ b/src/core/helpers/protocol/media/get-image-info.js
@@ -1,7 +1,7 @@
import getRealPath from 'uni-platform/helpers/get-real-path'
export const getImageInfo = {
- 'src': {
+ src: {
type: String,
required: true,
validator (src, params) {
diff --git a/src/core/helpers/protocol/network/request.js b/src/core/helpers/protocol/network/request.js
index dee53a1c9d71652eaffe1de56453d9648708db83..5029e7ecb8e9316a9b6cc9b3119f0d5b195a60cc 100644
--- a/src/core/helpers/protocol/network/request.js
+++ b/src/core/helpers/protocol/network/request.js
@@ -35,7 +35,7 @@ function stringifyQuery (url, data) {
item = item.split('=')
query[item[0]] = item[1]
})
- for (let key in data) {
+ for (const key in data) {
if (hasOwn(data, key)) {
let v = data[key]
if (typeof v === 'undefined' || v === null) {
diff --git a/src/core/helpers/protocol/storage/storage.js b/src/core/helpers/protocol/storage/storage.js
index f1762cb5a5f400ca343756d7420b24e567d65a90..e55c2f5e4d239118df5e45fad3c84b085190cd31 100644
--- a/src/core/helpers/protocol/storage/storage.js
+++ b/src/core/helpers/protocol/storage/storage.js
@@ -1,5 +1,5 @@
export const getStorage = {
- 'key': {
+ key: {
type: String,
required: true
}
@@ -12,11 +12,11 @@ export const getStorageSync = [{
}]
export const setStorage = {
- 'key': {
+ key: {
type: String,
required: true
},
- 'data': {
+ data: {
required: true
}
}
diff --git a/src/core/helpers/protocol/ui/navigation-bar.js b/src/core/helpers/protocol/ui/navigation-bar.js
index 59e83430e9a98fab7b8ae77c1ff700333ad01a10..3e57f2925a1857dfc49fee24c5422c35e76d585f 100644
--- a/src/core/helpers/protocol/ui/navigation-bar.js
+++ b/src/core/helpers/protocol/ui/navigation-bar.js
@@ -1,6 +1,6 @@
const FRONT_COLORS = ['#ffffff', '#000000']
export const setNavigationBarColor = {
- 'frontColor': {
+ frontColor: {
type: String,
required: true,
validator (frontColor, params) {
@@ -9,11 +9,11 @@ export const setNavigationBarColor = {
}
}
},
- 'backgroundColor': {
+ backgroundColor: {
type: String,
required: true
},
- 'animation': {
+ animation: {
type: Object,
default () {
return {
@@ -30,7 +30,7 @@ export const setNavigationBarColor = {
}
}
export const setNavigationBarTitle = {
- 'title': {
+ title: {
type: String,
required: true
}
diff --git a/src/core/runtime/mp/constants.js b/src/core/runtime/mp/constants.js
index 80d660e2c6ad9bd4c1f16fa79af530840d88a438..cb42d25064e6aee45348a4bef15c4824888ee707 100644
--- a/src/core/runtime/mp/constants.js
+++ b/src/core/runtime/mp/constants.js
@@ -1,11 +1,11 @@
export const SOURCE_KEY = '__data__'
export const COMPONENT_LIFECYCLE = {
- 'created': 'onServiceCreated',
- 'attached': 'onServiceAttached',
- 'ready': 'mounted',
- 'moved': 'moved',
- 'detached': 'destroyed'
+ created: 'onServiceCreated',
+ attached: 'onServiceAttached',
+ ready: 'mounted',
+ moved: 'moved',
+ detached: 'destroyed'
}
export const COMPONENT_LIFECYCLE_KEYS = Object.keys(COMPONENT_LIFECYCLE)
diff --git a/src/core/runtime/mp/index.js b/src/core/runtime/mp/index.js
index b431ad9fd88b26b1acdf9dc1aa6a7cc5797832ac..8ff446c4fbfd1cf4a0d51a69dd7252c44635e4a2 100644
--- a/src/core/runtime/mp/index.js
+++ b/src/core/runtime/mp/index.js
@@ -14,23 +14,23 @@ import {
import polyfill from './polyfill/index'
-global['__wxRoute'] = ''
-global['__wxComponents'] = Object.create(null)
-global['__wxVueOptions'] = Object.create(null)
+global.__wxRoute = ''
+global.__wxComponents = Object.create(null)
+global.__wxVueOptions = Object.create(null)
export function Page (options) {
const pageOptions = parsePage(options)
pageOptions.mixins.unshift(polyfill)
- pageOptions.mpOptions.path = global['__wxRoute']
- global['__wxComponents'][global['__wxRoute']] = pageOptions
+ pageOptions.mpOptions.path = global.__wxRoute
+ global.__wxComponents[global.__wxRoute] = pageOptions
}
function initRelationsHandler (vueComponentOptions) {
// linked 需要在当前组件 attached 之后再执行
- if (!vueComponentOptions['onServiceAttached']) {
- vueComponentOptions['onServiceAttached'] = []
+ if (!vueComponentOptions.onServiceAttached) {
+ vueComponentOptions.onServiceAttached = []
}
- vueComponentOptions['onServiceAttached'].push(function onServiceAttached () {
+ vueComponentOptions.onServiceAttached.push(function onServiceAttached () {
handleRelations(this, 'linked')
})
}
@@ -38,9 +38,9 @@ function initRelationsHandler (vueComponentOptions) {
export function Component (options) {
const componentOptions = parseComponent(options)
componentOptions.mixins.unshift(polyfill)
- componentOptions.mpOptions.path = global['__wxRoute']
+ componentOptions.mpOptions.path = global.__wxRoute
initRelationsHandler(componentOptions)
- global['__wxComponents'][global['__wxRoute']] = componentOptions
+ global.__wxComponents[global.__wxRoute] = componentOptions
}
export function Behavior (options) {
diff --git a/src/core/runtime/mp/parser/components-parser.js b/src/core/runtime/mp/parser/components-parser.js
index ab59fb3c68102658e292aa1f00cdc7dc5667acce..96af5941b8a3871da3d0f9bbcca657dbffddc715 100644
--- a/src/core/runtime/mp/parser/components-parser.js
+++ b/src/core/runtime/mp/parser/components-parser.js
@@ -1,3 +1,3 @@
export function parseComponents (vueComponentOptions) {
- vueComponentOptions.components = global['__wxVueOptions'].components
+ vueComponentOptions.components = global.__wxVueOptions.components
}
diff --git a/src/core/runtime/mp/parser/methods-parser.js b/src/core/runtime/mp/parser/methods-parser.js
index 0db83c5ea64adfc6bbb2370515d5a643b51e080d..a6fff55c8fd133efd06faf9427afcadd0b0187f9 100644
--- a/src/core/runtime/mp/parser/methods-parser.js
+++ b/src/core/runtime/mp/parser/methods-parser.js
@@ -3,7 +3,7 @@ export function parseMethods (methods, vueComponentOptions) {
return
}
if (methods.$emit) {
- console.warn(`Method "$emit" conflicts with an existing Vue instance method`)
+ console.warn('Method "$emit" conflicts with an existing Vue instance method')
delete methods.$emit
}
vueComponentOptions.methods = methods
diff --git a/src/core/runtime/mp/parser/relations-parser.js b/src/core/runtime/mp/parser/relations-parser.js
index fedaf9c6807c86f5bec3e27115e7c2ddeca72a58..1404721d4648675291b5c2a972cf7a170d392583 100644
--- a/src/core/runtime/mp/parser/relations-parser.js
+++ b/src/core/runtime/mp/parser/relations-parser.js
@@ -25,7 +25,7 @@ export function parseRelations (relations, vueComponentOptions) {
Object.keys(relations).forEach(name => {
const relation = relations[name]
relation.name = name
- relation.target = relation.target ? String(relation.target) : relative(global['__wxRoute'], name)
+ relation.target = relation.target ? String(relation.target) : relative(global.__wxRoute, name)
})
vueComponentOptions.mpOptions.relations = relations
}
diff --git a/src/core/runtime/web-view/index.js b/src/core/runtime/web-view/index.js
index 8b500744e8869f200965a1ab9fd197c9c567e5f2..527bf1e680e5c0f9fb4378f96a16ee4b8071041e 100644
--- a/src/core/runtime/web-view/index.js
+++ b/src/core/runtime/web-view/index.js
@@ -1,3 +1,7 @@
+import {
+ hasOwn
+} from 'uni-shared'
+
import {
initWebviewApi as initAppplusWebviewApi
} from 'uni-platforms/app-plus/runtime/web-view'
@@ -58,11 +62,11 @@ const api = typeof uni !== 'undefined' ? uni : {}
if (!api.navigateTo) {
for (const key in webViewApi) {
- if (webViewApi.hasOwnProperty(key)) {
+ if (hasOwn(webViewApi, key)) {
api[key] = webViewApi[key]
}
}
}
api.webView = webViewApi
-export default api
+export default api
diff --git a/src/core/runtime/wrapper.js b/src/core/runtime/wrapper.js
index bd856a8a3324b87a7d58f6b291a6415ea8c06a97..5224851befe9c170aa132fe035d1e3dae7186d6f 100644
--- a/src/core/runtime/wrapper.js
+++ b/src/core/runtime/wrapper.js
@@ -26,7 +26,7 @@ function processArgs (methodName, fromArgs, argsOption = {}, returnValue = {}, k
if (isFn(argsOption)) {
argsOption = argsOption(fromArgs, toArgs) || {}
}
- for (let key in fromArgs) {
+ for (const key in fromArgs) {
if (hasOwn(argsOption, key)) {
let keyOption = argsOption[key]
if (isFn(keyOption)) {
diff --git a/src/core/runtime/wrapper/util.js b/src/core/runtime/wrapper/util.js
index ad0d83dec21244eac2dbd6ac4998d5b6478640b7..e8ab325949c6048b605d290e88f57fd4e276e616 100644
--- a/src/core/runtime/wrapper/util.js
+++ b/src/core/runtime/wrapper/util.js
@@ -144,14 +144,14 @@ function createObserver (name) {
}
export function initBehaviors (vueOptions, initBehavior) {
- const vueBehaviors = vueOptions['behaviors']
- const vueExtends = vueOptions['extends']
- const vueMixins = vueOptions['mixins']
+ const vueBehaviors = vueOptions.behaviors
+ const vueExtends = vueOptions.extends
+ const vueMixins = vueOptions.mixins
- let vueProps = vueOptions['props']
+ let vueProps = vueOptions.props
if (!vueProps) {
- vueOptions['props'] = vueProps = []
+ vueOptions.props = vueProps = []
}
const behaviors = []
@@ -163,11 +163,11 @@ export function initBehaviors (vueOptions, initBehavior) {
vueProps.push('name')
vueProps.push('value')
} else {
- vueProps['name'] = {
+ vueProps.name = {
type: String,
default: ''
}
- vueProps['value'] = {
+ vueProps.value = {
type: [String, Number, Boolean, Array, Object, Date],
default: ''
}
@@ -252,7 +252,7 @@ export function initProperties (props, isBehavior = false, file = '') {
Object.keys(props).forEach(key => {
const opts = props[key]
if (isPlainObject(opts)) { // title:{type:String,default:''}
- let value = opts['default']
+ let value = opts.default
if (isFn(value)) {
value = value()
}
@@ -453,11 +453,11 @@ export function handleEvent (event) {
// [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
const dataset = (event.currentTarget || event.target).dataset
if (!dataset) {
- return console.warn(`事件信息不存在`)
+ return console.warn('事件信息不存在')
}
const eventOpts = dataset.eventOpts || dataset['event-opts'] // 支付宝 web-view 组件 dataset 非驼峰
if (!eventOpts) {
- return console.warn(`事件信息不存在`)
+ return console.warn('事件信息不存在')
}
// [['handle',[1,2,a]],['handle1',[1,2,a]]]
diff --git a/src/core/service/api/context/audio.js b/src/core/service/api/context/audio.js
index 004d8dd8ba5fe810d82b43c3e7b91f24c9a90559..56c6569524212986d331019ceb9848311b1896d8 100644
--- a/src/core/service/api/context/audio.js
+++ b/src/core/service/api/context/audio.js
@@ -92,28 +92,34 @@ class InnerAudioContext {
}
Object.defineProperty(this, name, data)
})
- }
+ }
+
play () {
this._operate('play')
- }
+ }
+
pause () {
this._operate('pause')
- }
+ }
+
stop () {
this._operate('stop')
- }
+ }
+
seek (position) {
this._operate('seek', {
currentTime: position * 1e3
})
- }
+ }
+
destroy () {
clearInterval(this.__timing)
invokeMethod('destroyAudioInstance', {
audioId: this.id
})
delete innerAudioContexts[this.id]
- }
+ }
+
_operate (type, options) {
invokeMethod('operateAudio', Object.assign({}, options, {
audioId: this.id,
diff --git a/src/core/service/api/context/background-audio.js b/src/core/service/api/context/background-audio.js
index f9c07702366069cc9e3187657db2816039d08db8..f82868d95f22f95f7226f3afcf3ee39ec89c8b5f 100644
--- a/src/core/service/api/context/background-audio.js
+++ b/src/core/service/api/context/background-audio.js
@@ -108,21 +108,26 @@ class BackgroundAudioManager {
}
Object.defineProperty(this, name, data)
})
- }
+ }
+
play () {
this._operate('play')
- }
+ }
+
pause () {
this._operate('pause')
- }
+ }
+
stop () {
this._operate('stop')
- }
+ }
+
seek (position) {
this._operate('seek', {
currentTime: position
})
- }
+ }
+
_operate (type, options) {
invokeMethod('operateBackgroundAudio', Object.assign({}, options, {
operationType: type
diff --git a/src/core/service/api/context/canvas.js b/src/core/service/api/context/canvas.js
index 427ba591c2407e1f0c72b22a371ff96548313883..655ee60e95e19dc429e8c9f11550ef9956ac595f 100644
--- a/src/core/service/api/context/canvas.js
+++ b/src/core/service/api/context/canvas.js
@@ -1,869 +1,915 @@
-import createCallbacks from 'uni-helpers/callbacks'
-
-import {
- invokeMethod,
- getCurrentPageId
-} from '../../platform'
-
-import {
- invoke
-} from '../../bridge'
-
-const canvasEventCallbacks = createCallbacks('canvasEvent')
-
-UniServiceJSBridge.subscribe('onDrawCanvas', ({
- callbackId,
- data
-}) => {
- const callback = canvasEventCallbacks.pop(callbackId)
- if (callback) {
- callback(data)
- }
-})
-
-UniServiceJSBridge.subscribe('onCanvasMethodCallback', ({
- callbackId,
- data
-}) => {
- const callback = canvasEventCallbacks.pop(callbackId)
- if (callback) {
- callback(data)
- }
-})
-
-function operateCanvas (canvasId, pageId, type, data) {
- UniServiceJSBridge.publishHandler(pageId + '-canvas-' + canvasId, {
- canvasId,
- type,
- data
- }, pageId)
-}
-
-const predefinedColor = {
- aliceblue: '#f0f8ff',
- antiquewhite: '#faebd7',
- aqua: '#00ffff',
- aquamarine: '#7fffd4',
- azure: '#f0ffff',
- beige: '#f5f5dc',
- bisque: '#ffe4c4',
- black: '#000000',
- blanchedalmond: '#ffebcd',
- blue: '#0000ff',
- blueviolet: '#8a2be2',
- brown: '#a52a2a',
- burlywood: '#deb887',
- cadetblue: '#5f9ea0',
- chartreuse: '#7fff00',
- chocolate: '#d2691e',
- coral: '#ff7f50',
- cornflowerblue: '#6495ed',
- cornsilk: '#fff8dc',
- crimson: '#dc143c',
- cyan: '#00ffff',
- darkblue: '#00008b',
- darkcyan: '#008b8b',
- darkgoldenrod: '#b8860b',
- darkgray: '#a9a9a9',
- darkgrey: '#a9a9a9',
- darkgreen: '#006400',
- darkkhaki: '#bdb76b',
- darkmagenta: '#8b008b',
- darkolivegreen: '#556b2f',
- darkorange: '#ff8c00',
- darkorchid: '#9932cc',
- darkred: '#8b0000',
- darksalmon: '#e9967a',
- darkseagreen: '#8fbc8f',
- darkslateblue: '#483d8b',
- darkslategray: '#2f4f4f',
- darkslategrey: '#2f4f4f',
- darkturquoise: '#00ced1',
- darkviolet: '#9400d3',
- deeppink: '#ff1493',
- deepskyblue: '#00bfff',
- dimgray: '#696969',
- dimgrey: '#696969',
- dodgerblue: '#1e90ff',
- firebrick: '#b22222',
- floralwhite: '#fffaf0',
- forestgreen: '#228b22',
- fuchsia: '#ff00ff',
- gainsboro: '#dcdcdc',
- ghostwhite: '#f8f8ff',
- gold: '#ffd700',
- goldenrod: '#daa520',
- gray: '#808080',
- grey: '#808080',
- green: '#008000',
- greenyellow: '#adff2f',
- honeydew: '#f0fff0',
- hotpink: '#ff69b4',
- indianred: '#cd5c5c',
- indigo: '#4b0082',
- ivory: '#fffff0',
- khaki: '#f0e68c',
- lavender: '#e6e6fa',
- lavenderblush: '#fff0f5',
- lawngreen: '#7cfc00',
- lemonchiffon: '#fffacd',
- lightblue: '#add8e6',
- lightcoral: '#f08080',
- lightcyan: '#e0ffff',
- lightgoldenrodyellow: '#fafad2',
- lightgray: '#d3d3d3',
- lightgrey: '#d3d3d3',
- lightgreen: '#90ee90',
- lightpink: '#ffb6c1',
- lightsalmon: '#ffa07a',
- lightseagreen: '#20b2aa',
- lightskyblue: '#87cefa',
- lightslategray: '#778899',
- lightslategrey: '#778899',
- lightsteelblue: '#b0c4de',
- lightyellow: '#ffffe0',
- lime: '#00ff00',
- limegreen: '#32cd32',
- linen: '#faf0e6',
- magenta: '#ff00ff',
- maroon: '#800000',
- mediumaquamarine: '#66cdaa',
- mediumblue: '#0000cd',
- mediumorchid: '#ba55d3',
- mediumpurple: '#9370db',
- mediumseagreen: '#3cb371',
- mediumslateblue: '#7b68ee',
- mediumspringgreen: '#00fa9a',
- mediumturquoise: '#48d1cc',
- mediumvioletred: '#c71585',
- midnightblue: '#191970',
- mintcream: '#f5fffa',
- mistyrose: '#ffe4e1',
- moccasin: '#ffe4b5',
- navajowhite: '#ffdead',
- navy: '#000080',
- oldlace: '#fdf5e6',
- olive: '#808000',
- olivedrab: '#6b8e23',
- orange: '#ffa500',
- orangered: '#ff4500',
- orchid: '#da70d6',
- palegoldenrod: '#eee8aa',
- palegreen: '#98fb98',
- paleturquoise: '#afeeee',
- palevioletred: '#db7093',
- papayawhip: '#ffefd5',
- peachpuff: '#ffdab9',
- peru: '#cd853f',
- pink: '#ffc0cb',
- plum: '#dda0dd',
- powderblue: '#b0e0e6',
- purple: '#800080',
- rebeccapurple: '#663399',
- red: '#ff0000',
- rosybrown: '#bc8f8f',
- royalblue: '#4169e1',
- saddlebrown: '#8b4513',
- salmon: '#fa8072',
- sandybrown: '#f4a460',
- seagreen: '#2e8b57',
- seashell: '#fff5ee',
- sienna: '#a0522d',
- silver: '#c0c0c0',
- skyblue: '#87ceeb',
- slateblue: '#6a5acd',
- slategray: '#708090',
- slategrey: '#708090',
- snow: '#fffafa',
- springgreen: '#00ff7f',
- steelblue: '#4682b4',
- tan: '#d2b48c',
- teal: '#008080',
- thistle: '#d8bfd8',
- tomato: '#ff6347',
- turquoise: '#40e0d0',
- violet: '#ee82ee',
- wheat: '#f5deb3',
- white: '#ffffff',
- whitesmoke: '#f5f5f5',
- yellow: '#ffff00',
- yellowgreen: '#9acd32',
- transparent: '#00000000'
-}
-
-function checkColor (e) {
- // 其他开发者适配的echarts会传入一个undefined到这里
- e = e || '#000000'
- var t = null
- if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) {
- let n = parseInt(t[1].slice(0, 2), 16)
- let o = parseInt(t[1].slice(2, 4), 16)
- let r = parseInt(t[1].slice(4), 16)
- return [n, o, r, 255]
- }
- if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) {
- let n = t[1].slice(0, 1)
- let o = t[1].slice(1, 2)
- let r = t[1].slice(2, 3)
- n = parseInt(n + n, 16)
- o = parseInt(o + o, 16)
- r = parseInt(r + r, 16)
- return [n, o, r, 255]
- }
- if ((t = /^rgb\((.+)\)$/.exec(e)) != null) {
- return t[1].split(',').map(function (e) {
- return Math.min(255, parseInt(e.trim()))
- }).concat(255)
- }
- if ((t = /^rgba\((.+)\)$/.exec(e)) != null) {
- return t[1].split(',').map(function (e, t) {
- return t === 3 ? Math.floor(255 * parseFloat(e.trim())) : Math.min(255, parseInt(e.trim()))
- })
- }
- var i = e.toLowerCase()
- if (predefinedColor.hasOwnProperty(i)) {
- t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i])
- let n = parseInt(t[1].slice(0, 2), 16)
- let o = parseInt(t[1].slice(2, 4), 16)
- let r = parseInt(t[1].slice(4, 6), 16)
- let a = parseInt(t[1].slice(6, 8), 16)
- a = a >= 0 ? a : 255
- return [n, o, r, a]
- }
- console.group('非法颜色: ' + e)
- console.error('不支持颜色:' + e)
- console.groupEnd()
- return [0, 0, 0, 255]
-}
-
-function Pattern (image, repetition) {
- this.image = image
- this.repetition = repetition
-}
-
-class CanvasGradient {
- constructor (type, data) {
- this.type = type
- this.data = data
- this.colorStop = []
- }
- addColorStop (position, color) {
- this.colorStop.push([position, checkColor(color)])
- }
-}
-var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform']
-var methods2 = ['drawImage', 'fillText', 'fill', 'stroke', 'fillRect', 'strokeRect', 'clearRect',
- 'strokeText'
-]
-var methods3 = ['setFillStyle', 'setTextAlign', 'setStrokeStyle', 'setGlobalAlpha', 'setShadow',
- 'setFontSize', 'setLineCap', 'setLineJoin', 'setLineWidth', 'setMiterLimit',
- 'setTextBaseline', 'setLineDash'
-]
-
-var tempCanvas
-function getTempCanvas (width = 0, height = 0) {
- if (!tempCanvas) {
- tempCanvas = document.createElement('canvas')
- }
- tempCanvas.width = width
- tempCanvas.height = height
- return tempCanvas
-}
-
-function TextMetrics (width) {
- this.width = width
-}
-
-export class CanvasContext {
- constructor (id, pageId) {
- this.id = id
- this.pageId = pageId
- this.actions = []
- this.path = []
- this.subpath = []
- this.currentTransform = []
- this.currentStepAnimates = []
- this.drawingState = []
- this.state = {
- lineDash: [0, 0],
- shadowOffsetX: 0,
- shadowOffsetY: 0,
- shadowBlur: 0,
- shadowColor: [0, 0, 0, 0],
- font: '10px sans-serif',
- fontSize: 10,
- fontWeight: 'normal',
- fontStyle: 'normal',
- fontFamily: 'sans-serif'
- }
- }
- draw (reserve = false, callback) {
- var actions = [...this.actions]
- this.actions = []
- this.path = []
- var callbackId
-
- if (typeof callback === 'function') {
- callbackId = canvasEventCallbacks.push(callback)
- }
-
- operateCanvas(this.id, this.pageId, 'actionsChanged', {
- actions,
- reserve,
- callbackId
- })
- }
- createLinearGradient (x0, y0, x1, y1) {
- return new CanvasGradient('linear', [x0, y0, x1, y1])
- }
- createCircularGradient (x, y, r) {
- return new CanvasGradient('radial', [x, y, r])
- }
- createPattern (image, repetition) {
- if (undefined === repetition) {
- console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present.")
- } else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) {
- console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.")
- } else {
- return new Pattern(image, repetition)
- }
- }
- // TODO
- measureText (text) {
- if (typeof document === 'object') {
- var c2d = getTempCanvas().getContext('2d')
- c2d.font = this.state.font
- return new TextMetrics(c2d.measureText(text).width || 0)
- } else {
- return new TextMetrics(0)
- }
- }
- save () {
- this.actions.push({
- method: 'save',
- data: []
- })
- this.drawingState.push(this.state)
- }
- restore () {
- this.actions.push({
- method: 'restore',
- data: []
- })
- this.state = this.drawingState.pop() || {
- lineDash: [0, 0],
- shadowOffsetX: 0,
- shadowOffsetY: 0,
- shadowBlur: 0,
- shadowColor: [0, 0, 0, 0],
- font: '10px sans-serif',
- fontSize: 10,
- fontWeight: 'normal',
- fontStyle: 'normal',
- fontFamily: 'sans-serif'
- }
- }
- beginPath () {
- this.path = []
- this.subpath = []
- }
- moveTo (x, y) {
- this.path.push({
- method: 'moveTo',
- data: [x, y]
- })
- this.subpath = [
- [x, y]
- ]
- }
- lineTo (x, y) {
- if (this.path.length === 0 && this.subpath.length === 0) {
- this.path.push({
- method: 'moveTo',
- data: [x, y]
- })
- } else {
- this.path.push({
- method: 'lineTo',
- data: [x, y]
- })
- }
- this.subpath.push([x, y])
- }
- quadraticCurveTo (cpx, cpy, x, y) {
- this.path.push({
- method: 'quadraticCurveTo',
- data: [cpx, cpy, x, y]
- })
- this.subpath.push([x, y])
- }
- bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) {
- this.path.push({
- method: 'bezierCurveTo',
- data: [cp1x, cp1y, cp2x, cp2y, x, y]
- })
- this.subpath.push([x, y])
- }
- arc (x, y, r, sAngle, eAngle, counterclockwise = false) {
- this.path.push({
- method: 'arc',
- data: [x, y, r, sAngle, eAngle, counterclockwise]
- })
- this.subpath.push([x, y])
- }
- rect (x, y, width, height) {
- this.path.push({
- method: 'rect',
- data: [x, y, width, height]
- })
- this.subpath = [
- [x, y]
- ]
- }
- arcTo (x1, y1, x2, y2, radius) {
- this.path.push({
- method: 'arcTo',
- data: [x1, y1, x2, y2, radius]
- })
- this.subpath.push([x2, y2])
- }
- clip () {
- this.actions.push({
- method: 'clip',
- data: [...this.path]
- })
- }
- closePath () {
- this.path.push({
- method: 'closePath',
- data: []
- })
- if (this.subpath.length) {
- this.subpath = [this.subpath.shift()]
- }
- }
- clearActions () {
- this.actions = []
- this.path = []
- this.subpath = []
- }
- getActions () {
- var actions = [...this.actions]
- this.clearActions()
- return actions
- }
- set lineDashOffset (value) {
- this.actions.push({
- method: 'setLineDashOffset',
- data: [value]
- })
- }
- set globalCompositeOperation (type) {
- this.actions.push({
- method: 'setGlobalCompositeOperation',
- data: [type]
- })
- }
- set shadowBlur (level) {
- this.actions.push({
- method: 'setShadowBlur',
- data: [level]
- })
- }
- set shadowColor (color) {
- this.actions.push({
- method: 'setShadowColor',
- data: [color]
- })
- }
- set shadowOffsetX (x) {
- this.actions.push({
- method: 'setShadowOffsetX',
- data: [x]
- })
- }
- set shadowOffsetY (y) {
- this.actions.push({
- method: 'setShadowOffsetY',
- data: [y]
- })
- }
- set font (value) {
- var self = this
- this.state.font = value
- // eslint-disable-next-line
- var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/)
- if (fontFormat) {
- var style = fontFormat[1].trim().split(/\s/)
- var fontSize = parseFloat(fontFormat[3])
- var fontFamily = fontFormat[7]
- var actions = []
- style.forEach(function (value, index) {
- if (['italic', 'oblique', 'normal'].indexOf(value) > -1) {
- actions.push({
- method: 'setFontStyle',
- data: [value]
- })
- self.state.fontStyle = value
- } else if (['bold', 'normal'].indexOf(value) > -1) {
- actions.push({
- method: 'setFontWeight',
- data: [value]
- })
- self.state.fontWeight = value
- } else if (index === 0) {
- actions.push({
- method: 'setFontStyle',
- data: ['normal']
- })
- self.state.fontStyle = 'normal'
- } else if (index === 1) {
- pushAction()
- }
- })
- if (style.length === 1) {
- pushAction()
- }
- style = actions.map(function (action) {
- return action.data[0]
- }).join(' ')
- this.state.fontSize = fontSize
- this.state.fontFamily = fontFamily
- this.actions.push({
- method: 'setFont',
- data: [`${style} ${fontSize}px ${fontFamily}`]
- })
- } else {
- console.warn("Failed to set 'font' on 'CanvasContext': invalid format.")
- }
- function pushAction () {
- actions.push({
- method: 'setFontWeight',
- data: ['normal']
- })
- self.state.fontWeight = 'normal'
- }
- }
- get font () {
- return this.state.font
- }
- set fillStyle (color) {
- this.setFillStyle(color)
- }
- set strokeStyle (color) {
- this.setStrokeStyle(color)
- }
- set globalAlpha (value) {
- value = Math.floor(255 * parseFloat(value))
- this.actions.push({
- method: 'setGlobalAlpha',
- data: [value]
- })
- }
- set textAlign (align) {
- this.actions.push({
- method: 'setTextAlign',
- data: [align]
- })
- }
- set lineCap (type) {
- this.actions.push({
- method: 'setLineCap',
- data: [type]
- })
- }
- set lineJoin (type) {
- this.actions.push({
- method: 'setLineJoin',
- data: [type]
- })
- }
- set lineWidth (value) {
- this.actions.push({
- method: 'setLineWidth',
- data: [value]
- })
- }
- set miterLimit (value) {
- this.actions.push({
- method: 'setMiterLimit',
- data: [value]
- })
- }
- set textBaseline (type) {
- this.actions.push({
- method: 'setTextBaseline',
- data: [type]
- })
- }
-}
-
-[...methods1, ...methods2].forEach(function (method) {
- function get (method) {
- switch (method) {
- case 'fill':
- case 'stroke':
- return function () {
- this.actions.push({
- method: method + 'Path',
- data: [...this.path]
- })
- }
- case 'fillRect':
- return function (x, y, width, height) {
- this.actions.push({
- method: 'fillPath',
- data: [{
- method: 'rect',
- data: [x, y, width, height]
- }]
- })
- }
- case 'strokeRect':
- return function (x, y, width, height) {
- this.actions.push({
- method: 'strokePath',
- data: [{
- method: 'rect',
- data: [x, y, width, height]
- }]
- })
- }
- case 'fillText':
- case 'strokeText':
- return function (text, x, y, maxWidth) {
- var data = [text.toString(), x, y]
- if (typeof maxWidth === 'number') {
- data.push(maxWidth)
- }
- this.actions.push({
- method,
- data
- })
- }
- case 'drawImage':
- return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) {
- if (sHeight === undefined) {
- sx = dx
- sy = dy
- sWidth = dWidth
- sHeight = dHeight
- dx = undefined
- dy = undefined
- dWidth = undefined
- dHeight = undefined
- }
- var data
- function isNumber (e) {
- return typeof e === 'number'
- }
- data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight] : isNumber(sWidth) && isNumber(
- sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy]
- this.actions.push({
- method,
- data
- })
- }
- default:
- return function (...data) {
- this.actions.push({
- method,
- data
- })
- }
- }
- }
- CanvasContext.prototype[method] = get(method)
-})
-methods3.forEach(function (method) {
- function get (method) {
- switch (method) {
- case 'setFillStyle':
- case 'setStrokeStyle':
- return function (color) {
- if (typeof color !== 'object') {
- this.actions.push({
- method,
- data: ['normal', checkColor(color)]
- })
- } else {
- this.actions.push({
- method,
- data: [color.type, color.data, color.colorStop]
- })
- }
- }
- case 'setGlobalAlpha':
- return function (alpha) {
- alpha = Math.floor(255 * parseFloat(alpha))
- this.actions.push({
- method,
- data: [alpha]
- })
- }
- case 'setShadow':
- return function (offsetX, offsetY, blur, color) {
- color = checkColor(color)
- this.actions.push({
- method,
- data: [offsetX, offsetY, blur, color]
- })
- this.state.shadowBlur = blur
- this.state.shadowColor = color
- this.state.shadowOffsetX = offsetX
- this.state.shadowOffsetY = offsetY
- }
- case 'setLineDash':
- return function (pattern, offset) {
- pattern = pattern || [0, 0]
- offset = offset || 0
- this.actions.push({
- method,
- data: [pattern, offset]
- })
- this.state.lineDash = pattern
- }
- case 'setFontSize':
- return function (fontSize) {
- this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px')
- this.state.fontSize = fontSize
- this.actions.push({
- method,
- data: [fontSize]
- })
- }
- default:
- return function (...data) {
- this.actions.push({
- method,
- data
- })
- }
- }
- }
- CanvasContext.prototype[method] = get(method)
-})
-
-export function createCanvasContext (id, context) {
- if (context) {
- return new CanvasContext(id, context.$page.id)
- }
- const pageId = getCurrentPageId()
- if (pageId) {
- return new CanvasContext(id, pageId)
- } else {
- UniServiceJSBridge.emit('onError', 'createCanvasContext:fail')
- }
-}
-
-export function canvasGetImageData ({
- canvasId,
- x,
- y,
- width,
- height
-}, callbackId) {
- var pageId = getCurrentPageId()
- if (!pageId) {
- invoke(callbackId, {
- errMsg: 'canvasGetImageData:fail'
- })
- return
- }
- var cId = canvasEventCallbacks.push(function (data) {
- var imgData = data.data
- if (imgData && imgData.length) {
- data.data = new Uint8ClampedArray(imgData)
- }
- invoke(callbackId, data)
- })
- operateCanvas(canvasId, pageId, 'getImageData', {
- x,
- y,
- width,
- height,
- callbackId: cId
- })
-}
-
-export function canvasPutImageData ({
- canvasId,
- data,
- x,
- y,
- width,
- height
-}, callbackId) {
- var pageId = getCurrentPageId()
- if (!pageId) {
- invoke(callbackId, {
- errMsg: 'canvasPutImageData:fail'
- })
- return
- }
- var cId = canvasEventCallbacks.push(function (data) {
- invoke(callbackId, data)
- })
- // fix ...
- operateCanvas(canvasId, pageId, 'putImageData', {
- data: Array.prototype.slice.call(data),
- x,
- y,
- width,
- height,
- callbackId: cId
- })
-}
-
-export function canvasToTempFilePath ({
- x = 0,
- y = 0,
- width,
- height,
- destWidth,
- destHeight,
- canvasId,
- fileType,
- qualit
-}, callbackId) {
- var pageId = getCurrentPageId()
- if (!pageId) {
- invoke(callbackId, {
- errMsg: 'canvasToTempFilePath:fail'
- })
- return
- }
- const cId = canvasEventCallbacks.push(function ({
- base64
- }) {
- if (!base64 || !base64.length) {
- invoke(callbackId, {
- errMsg: 'canvasToTempFilePath:fail'
- })
- }
- invokeMethod('base64ToTempFilePath', {
- base64Data: base64,
- x,
- y,
- width,
- height,
- destWidth,
- destHeight,
- canvasId,
- fileType,
- qualit
- }, callbackId)
- })
- operateCanvas(canvasId, pageId, 'getDataUrl', {
- x,
- y,
- width,
- height,
- destWidth,
- destHeight,
- hidpi: false,
- fileType,
- qualit,
- callbackId: cId
- })
+import {
+ hasOwn
+} from 'uni-shared'
+import createCallbacks from 'uni-helpers/callbacks'
+
+import {
+ invokeMethod,
+ getCurrentPageId
+} from '../../platform'
+
+import {
+ invoke
+} from '../../bridge'
+
+const canvasEventCallbacks = createCallbacks('canvasEvent')
+
+UniServiceJSBridge.subscribe('onDrawCanvas', ({
+ callbackId,
+ data
+}) => {
+ const callback = canvasEventCallbacks.pop(callbackId)
+ if (callback) {
+ callback(data)
+ }
+})
+
+UniServiceJSBridge.subscribe('onCanvasMethodCallback', ({
+ callbackId,
+ data
+}) => {
+ const callback = canvasEventCallbacks.pop(callbackId)
+ if (callback) {
+ callback(data)
+ }
+})
+
+function operateCanvas (canvasId, pageId, type, data) {
+ UniServiceJSBridge.publishHandler(pageId + '-canvas-' + canvasId, {
+ canvasId,
+ type,
+ data
+ }, pageId)
+}
+
+const predefinedColor = {
+ aliceblue: '#f0f8ff',
+ antiquewhite: '#faebd7',
+ aqua: '#00ffff',
+ aquamarine: '#7fffd4',
+ azure: '#f0ffff',
+ beige: '#f5f5dc',
+ bisque: '#ffe4c4',
+ black: '#000000',
+ blanchedalmond: '#ffebcd',
+ blue: '#0000ff',
+ blueviolet: '#8a2be2',
+ brown: '#a52a2a',
+ burlywood: '#deb887',
+ cadetblue: '#5f9ea0',
+ chartreuse: '#7fff00',
+ chocolate: '#d2691e',
+ coral: '#ff7f50',
+ cornflowerblue: '#6495ed',
+ cornsilk: '#fff8dc',
+ crimson: '#dc143c',
+ cyan: '#00ffff',
+ darkblue: '#00008b',
+ darkcyan: '#008b8b',
+ darkgoldenrod: '#b8860b',
+ darkgray: '#a9a9a9',
+ darkgrey: '#a9a9a9',
+ darkgreen: '#006400',
+ darkkhaki: '#bdb76b',
+ darkmagenta: '#8b008b',
+ darkolivegreen: '#556b2f',
+ darkorange: '#ff8c00',
+ darkorchid: '#9932cc',
+ darkred: '#8b0000',
+ darksalmon: '#e9967a',
+ darkseagreen: '#8fbc8f',
+ darkslateblue: '#483d8b',
+ darkslategray: '#2f4f4f',
+ darkslategrey: '#2f4f4f',
+ darkturquoise: '#00ced1',
+ darkviolet: '#9400d3',
+ deeppink: '#ff1493',
+ deepskyblue: '#00bfff',
+ dimgray: '#696969',
+ dimgrey: '#696969',
+ dodgerblue: '#1e90ff',
+ firebrick: '#b22222',
+ floralwhite: '#fffaf0',
+ forestgreen: '#228b22',
+ fuchsia: '#ff00ff',
+ gainsboro: '#dcdcdc',
+ ghostwhite: '#f8f8ff',
+ gold: '#ffd700',
+ goldenrod: '#daa520',
+ gray: '#808080',
+ grey: '#808080',
+ green: '#008000',
+ greenyellow: '#adff2f',
+ honeydew: '#f0fff0',
+ hotpink: '#ff69b4',
+ indianred: '#cd5c5c',
+ indigo: '#4b0082',
+ ivory: '#fffff0',
+ khaki: '#f0e68c',
+ lavender: '#e6e6fa',
+ lavenderblush: '#fff0f5',
+ lawngreen: '#7cfc00',
+ lemonchiffon: '#fffacd',
+ lightblue: '#add8e6',
+ lightcoral: '#f08080',
+ lightcyan: '#e0ffff',
+ lightgoldenrodyellow: '#fafad2',
+ lightgray: '#d3d3d3',
+ lightgrey: '#d3d3d3',
+ lightgreen: '#90ee90',
+ lightpink: '#ffb6c1',
+ lightsalmon: '#ffa07a',
+ lightseagreen: '#20b2aa',
+ lightskyblue: '#87cefa',
+ lightslategray: '#778899',
+ lightslategrey: '#778899',
+ lightsteelblue: '#b0c4de',
+ lightyellow: '#ffffe0',
+ lime: '#00ff00',
+ limegreen: '#32cd32',
+ linen: '#faf0e6',
+ magenta: '#ff00ff',
+ maroon: '#800000',
+ mediumaquamarine: '#66cdaa',
+ mediumblue: '#0000cd',
+ mediumorchid: '#ba55d3',
+ mediumpurple: '#9370db',
+ mediumseagreen: '#3cb371',
+ mediumslateblue: '#7b68ee',
+ mediumspringgreen: '#00fa9a',
+ mediumturquoise: '#48d1cc',
+ mediumvioletred: '#c71585',
+ midnightblue: '#191970',
+ mintcream: '#f5fffa',
+ mistyrose: '#ffe4e1',
+ moccasin: '#ffe4b5',
+ navajowhite: '#ffdead',
+ navy: '#000080',
+ oldlace: '#fdf5e6',
+ olive: '#808000',
+ olivedrab: '#6b8e23',
+ orange: '#ffa500',
+ orangered: '#ff4500',
+ orchid: '#da70d6',
+ palegoldenrod: '#eee8aa',
+ palegreen: '#98fb98',
+ paleturquoise: '#afeeee',
+ palevioletred: '#db7093',
+ papayawhip: '#ffefd5',
+ peachpuff: '#ffdab9',
+ peru: '#cd853f',
+ pink: '#ffc0cb',
+ plum: '#dda0dd',
+ powderblue: '#b0e0e6',
+ purple: '#800080',
+ rebeccapurple: '#663399',
+ red: '#ff0000',
+ rosybrown: '#bc8f8f',
+ royalblue: '#4169e1',
+ saddlebrown: '#8b4513',
+ salmon: '#fa8072',
+ sandybrown: '#f4a460',
+ seagreen: '#2e8b57',
+ seashell: '#fff5ee',
+ sienna: '#a0522d',
+ silver: '#c0c0c0',
+ skyblue: '#87ceeb',
+ slateblue: '#6a5acd',
+ slategray: '#708090',
+ slategrey: '#708090',
+ snow: '#fffafa',
+ springgreen: '#00ff7f',
+ steelblue: '#4682b4',
+ tan: '#d2b48c',
+ teal: '#008080',
+ thistle: '#d8bfd8',
+ tomato: '#ff6347',
+ turquoise: '#40e0d0',
+ violet: '#ee82ee',
+ wheat: '#f5deb3',
+ white: '#ffffff',
+ whitesmoke: '#f5f5f5',
+ yellow: '#ffff00',
+ yellowgreen: '#9acd32',
+ transparent: '#00000000'
+}
+
+function checkColor (e) {
+ // 其他开发者适配的echarts会传入一个undefined到这里
+ e = e || '#000000'
+ var t = null
+ if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) {
+ const n = parseInt(t[1].slice(0, 2), 16)
+ const o = parseInt(t[1].slice(2, 4), 16)
+ const r = parseInt(t[1].slice(4), 16)
+ return [n, o, r, 255]
+ }
+ if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) {
+ let n = t[1].slice(0, 1)
+ let o = t[1].slice(1, 2)
+ let r = t[1].slice(2, 3)
+ n = parseInt(n + n, 16)
+ o = parseInt(o + o, 16)
+ r = parseInt(r + r, 16)
+ return [n, o, r, 255]
+ }
+ if ((t = /^rgb\((.+)\)$/.exec(e)) != null) {
+ return t[1].split(',').map(function (e) {
+ return Math.min(255, parseInt(e.trim()))
+ }).concat(255)
+ }
+ if ((t = /^rgba\((.+)\)$/.exec(e)) != null) {
+ return t[1].split(',').map(function (e, t) {
+ return t === 3 ? Math.floor(255 * parseFloat(e.trim())) : Math.min(255, parseInt(e.trim()))
+ })
+ }
+ var i = e.toLowerCase()
+ if (hasOwn(predefinedColor, i)) {
+ t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i])
+ const n = parseInt(t[1].slice(0, 2), 16)
+ const o = parseInt(t[1].slice(2, 4), 16)
+ const r = parseInt(t[1].slice(4, 6), 16)
+ let a = parseInt(t[1].slice(6, 8), 16)
+ a = a >= 0 ? a : 255
+ return [n, o, r, a]
+ }
+ console.group('非法颜色: ' + e)
+ console.error('不支持颜色:' + e)
+ console.groupEnd()
+ return [0, 0, 0, 255]
+}
+
+function Pattern (image, repetition) {
+ this.image = image
+ this.repetition = repetition
+}
+
+class CanvasGradient {
+ constructor (type, data) {
+ this.type = type
+ this.data = data
+ this.colorStop = []
+ }
+
+ addColorStop (position, color) {
+ this.colorStop.push([position, checkColor(color)])
+ }
+}
+var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform']
+var methods2 = ['drawImage', 'fillText', 'fill', 'stroke', 'fillRect', 'strokeRect', 'clearRect',
+ 'strokeText'
+]
+var methods3 = ['setFillStyle', 'setTextAlign', 'setStrokeStyle', 'setGlobalAlpha', 'setShadow',
+ 'setFontSize', 'setLineCap', 'setLineJoin', 'setLineWidth', 'setMiterLimit',
+ 'setTextBaseline', 'setLineDash'
+]
+
+var tempCanvas
+
+function getTempCanvas (width = 0, height = 0) {
+ if (!tempCanvas) {
+ tempCanvas = document.createElement('canvas')
+ }
+ tempCanvas.width = width
+ tempCanvas.height = height
+ return tempCanvas
+}
+
+function TextMetrics (width) {
+ this.width = width
+}
+
+export class CanvasContext {
+ constructor (id, pageId) {
+ this.id = id
+ this.pageId = pageId
+ this.actions = []
+ this.path = []
+ this.subpath = []
+ this.currentTransform = []
+ this.currentStepAnimates = []
+ this.drawingState = []
+ this.state = {
+ lineDash: [0, 0],
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ shadowBlur: 0,
+ shadowColor: [0, 0, 0, 0],
+ font: '10px sans-serif',
+ fontSize: 10,
+ fontWeight: 'normal',
+ fontStyle: 'normal',
+ fontFamily: 'sans-serif'
+ }
+ }
+
+ draw (reserve = false, callback) {
+ var actions = [...this.actions]
+ this.actions = []
+ this.path = []
+ var callbackId
+
+ if (typeof callback === 'function') {
+ callbackId = canvasEventCallbacks.push(callback)
+ }
+
+ operateCanvas(this.id, this.pageId, 'actionsChanged', {
+ actions,
+ reserve,
+ callbackId
+ })
+ }
+
+ createLinearGradient (x0, y0, x1, y1) {
+ return new CanvasGradient('linear', [x0, y0, x1, y1])
+ }
+
+ createCircularGradient (x, y, r) {
+ return new CanvasGradient('radial', [x, y, r])
+ }
+
+ createPattern (image, repetition) {
+ if (undefined === repetition) {
+ console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present.")
+ } else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) {
+ console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition +
+ "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.")
+ } else {
+ return new Pattern(image, repetition)
+ }
+ }
+
+ // TODO
+ measureText (text) {
+ if (typeof document === 'object') {
+ var c2d = getTempCanvas().getContext('2d')
+ c2d.font = this.state.font
+ return new TextMetrics(c2d.measureText(text).width || 0)
+ } else {
+ return new TextMetrics(0)
+ }
+ }
+
+ save () {
+ this.actions.push({
+ method: 'save',
+ data: []
+ })
+ this.drawingState.push(this.state)
+ }
+
+ restore () {
+ this.actions.push({
+ method: 'restore',
+ data: []
+ })
+ this.state = this.drawingState.pop() || {
+ lineDash: [0, 0],
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ shadowBlur: 0,
+ shadowColor: [0, 0, 0, 0],
+ font: '10px sans-serif',
+ fontSize: 10,
+ fontWeight: 'normal',
+ fontStyle: 'normal',
+ fontFamily: 'sans-serif'
+ }
+ }
+
+ beginPath () {
+ this.path = []
+ this.subpath = []
+ }
+
+ moveTo (x, y) {
+ this.path.push({
+ method: 'moveTo',
+ data: [x, y]
+ })
+ this.subpath = [
+ [x, y]
+ ]
+ }
+
+ lineTo (x, y) {
+ if (this.path.length === 0 && this.subpath.length === 0) {
+ this.path.push({
+ method: 'moveTo',
+ data: [x, y]
+ })
+ } else {
+ this.path.push({
+ method: 'lineTo',
+ data: [x, y]
+ })
+ }
+ this.subpath.push([x, y])
+ }
+
+ quadraticCurveTo (cpx, cpy, x, y) {
+ this.path.push({
+ method: 'quadraticCurveTo',
+ data: [cpx, cpy, x, y]
+ })
+ this.subpath.push([x, y])
+ }
+
+ bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) {
+ this.path.push({
+ method: 'bezierCurveTo',
+ data: [cp1x, cp1y, cp2x, cp2y, x, y]
+ })
+ this.subpath.push([x, y])
+ }
+
+ arc (x, y, r, sAngle, eAngle, counterclockwise = false) {
+ this.path.push({
+ method: 'arc',
+ data: [x, y, r, sAngle, eAngle, counterclockwise]
+ })
+ this.subpath.push([x, y])
+ }
+
+ rect (x, y, width, height) {
+ this.path.push({
+ method: 'rect',
+ data: [x, y, width, height]
+ })
+ this.subpath = [
+ [x, y]
+ ]
+ }
+
+ arcTo (x1, y1, x2, y2, radius) {
+ this.path.push({
+ method: 'arcTo',
+ data: [x1, y1, x2, y2, radius]
+ })
+ this.subpath.push([x2, y2])
+ }
+
+ clip () {
+ this.actions.push({
+ method: 'clip',
+ data: [...this.path]
+ })
+ }
+
+ closePath () {
+ this.path.push({
+ method: 'closePath',
+ data: []
+ })
+ if (this.subpath.length) {
+ this.subpath = [this.subpath.shift()]
+ }
+ }
+
+ clearActions () {
+ this.actions = []
+ this.path = []
+ this.subpath = []
+ }
+
+ getActions () {
+ var actions = [...this.actions]
+ this.clearActions()
+ return actions
+ }
+
+ set lineDashOffset (value) {
+ this.actions.push({
+ method: 'setLineDashOffset',
+ data: [value]
+ })
+ }
+
+ set globalCompositeOperation (type) {
+ this.actions.push({
+ method: 'setGlobalCompositeOperation',
+ data: [type]
+ })
+ }
+
+ set shadowBlur (level) {
+ this.actions.push({
+ method: 'setShadowBlur',
+ data: [level]
+ })
+ }
+
+ set shadowColor (color) {
+ this.actions.push({
+ method: 'setShadowColor',
+ data: [color]
+ })
+ }
+
+ set shadowOffsetX (x) {
+ this.actions.push({
+ method: 'setShadowOffsetX',
+ data: [x]
+ })
+ }
+
+ set shadowOffsetY (y) {
+ this.actions.push({
+ method: 'setShadowOffsetY',
+ data: [y]
+ })
+ }
+
+ set font (value) {
+ var self = this
+ this.state.font = value
+ // eslint-disable-next-line
+ var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/)
+ if (fontFormat) {
+ var style = fontFormat[1].trim().split(/\s/)
+ var fontSize = parseFloat(fontFormat[3])
+ var fontFamily = fontFormat[7]
+ var actions = []
+ style.forEach(function (value, index) {
+ if (['italic', 'oblique', 'normal'].indexOf(value) > -1) {
+ actions.push({
+ method: 'setFontStyle',
+ data: [value]
+ })
+ self.state.fontStyle = value
+ } else if (['bold', 'normal'].indexOf(value) > -1) {
+ actions.push({
+ method: 'setFontWeight',
+ data: [value]
+ })
+ self.state.fontWeight = value
+ } else if (index === 0) {
+ actions.push({
+ method: 'setFontStyle',
+ data: ['normal']
+ })
+ self.state.fontStyle = 'normal'
+ } else if (index === 1) {
+ pushAction()
+ }
+ })
+ if (style.length === 1) {
+ pushAction()
+ }
+ style = actions.map(function (action) {
+ return action.data[0]
+ }).join(' ')
+ this.state.fontSize = fontSize
+ this.state.fontFamily = fontFamily
+ this.actions.push({
+ method: 'setFont',
+ data: [`${style} ${fontSize}px ${fontFamily}`]
+ })
+ } else {
+ console.warn("Failed to set 'font' on 'CanvasContext': invalid format.")
+ }
+
+ function pushAction () {
+ actions.push({
+ method: 'setFontWeight',
+ data: ['normal']
+ })
+ self.state.fontWeight = 'normal'
+ }
+ }
+
+ get font () {
+ return this.state.font
+ }
+
+ set fillStyle (color) {
+ this.setFillStyle(color)
+ }
+
+ set strokeStyle (color) {
+ this.setStrokeStyle(color)
+ }
+
+ set globalAlpha (value) {
+ value = Math.floor(255 * parseFloat(value))
+ this.actions.push({
+ method: 'setGlobalAlpha',
+ data: [value]
+ })
+ }
+
+ set textAlign (align) {
+ this.actions.push({
+ method: 'setTextAlign',
+ data: [align]
+ })
+ }
+
+ set lineCap (type) {
+ this.actions.push({
+ method: 'setLineCap',
+ data: [type]
+ })
+ }
+
+ set lineJoin (type) {
+ this.actions.push({
+ method: 'setLineJoin',
+ data: [type]
+ })
+ }
+
+ set lineWidth (value) {
+ this.actions.push({
+ method: 'setLineWidth',
+ data: [value]
+ })
+ }
+
+ set miterLimit (value) {
+ this.actions.push({
+ method: 'setMiterLimit',
+ data: [value]
+ })
+ }
+
+ set textBaseline (type) {
+ this.actions.push({
+ method: 'setTextBaseline',
+ data: [type]
+ })
+ }
+}
+
+[...methods1, ...methods2].forEach(function (method) {
+ function get (method) {
+ switch (method) {
+ case 'fill':
+ case 'stroke':
+ return function () {
+ this.actions.push({
+ method: method + 'Path',
+ data: [...this.path]
+ })
+ }
+ case 'fillRect':
+ return function (x, y, width, height) {
+ this.actions.push({
+ method: 'fillPath',
+ data: [{
+ method: 'rect',
+ data: [x, y, width, height]
+ }]
+ })
+ }
+ case 'strokeRect':
+ return function (x, y, width, height) {
+ this.actions.push({
+ method: 'strokePath',
+ data: [{
+ method: 'rect',
+ data: [x, y, width, height]
+ }]
+ })
+ }
+ case 'fillText':
+ case 'strokeText':
+ return function (text, x, y, maxWidth) {
+ var data = [text.toString(), x, y]
+ if (typeof maxWidth === 'number') {
+ data.push(maxWidth)
+ }
+ this.actions.push({
+ method,
+ data
+ })
+ }
+ case 'drawImage':
+ return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) {
+ if (sHeight === undefined) {
+ sx = dx
+ sy = dy
+ sWidth = dWidth
+ sHeight = dHeight
+ dx = undefined
+ dy = undefined
+ dWidth = undefined
+ dHeight = undefined
+ }
+ var data
+
+ function isNumber (e) {
+ return typeof e === 'number'
+ }
+ data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [imageResource, sx, sy,
+ sWidth, sHeight, dx, dy, dWidth, dHeight
+ ] : isNumber(sWidth) && isNumber(
+ sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy]
+ this.actions.push({
+ method,
+ data
+ })
+ }
+ default:
+ return function (...data) {
+ this.actions.push({
+ method,
+ data
+ })
+ }
+ }
+ }
+ CanvasContext.prototype[method] = get(method)
+})
+methods3.forEach(function (method) {
+ function get (method) {
+ switch (method) {
+ case 'setFillStyle':
+ case 'setStrokeStyle':
+ return function (color) {
+ if (typeof color !== 'object') {
+ this.actions.push({
+ method,
+ data: ['normal', checkColor(color)]
+ })
+ } else {
+ this.actions.push({
+ method,
+ data: [color.type, color.data, color.colorStop]
+ })
+ }
+ }
+ case 'setGlobalAlpha':
+ return function (alpha) {
+ alpha = Math.floor(255 * parseFloat(alpha))
+ this.actions.push({
+ method,
+ data: [alpha]
+ })
+ }
+ case 'setShadow':
+ return function (offsetX, offsetY, blur, color) {
+ color = checkColor(color)
+ this.actions.push({
+ method,
+ data: [offsetX, offsetY, blur, color]
+ })
+ this.state.shadowBlur = blur
+ this.state.shadowColor = color
+ this.state.shadowOffsetX = offsetX
+ this.state.shadowOffsetY = offsetY
+ }
+ case 'setLineDash':
+ return function (pattern, offset) {
+ pattern = pattern || [0, 0]
+ offset = offset || 0
+ this.actions.push({
+ method,
+ data: [pattern, offset]
+ })
+ this.state.lineDash = pattern
+ }
+ case 'setFontSize':
+ return function (fontSize) {
+ this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px')
+ this.state.fontSize = fontSize
+ this.actions.push({
+ method,
+ data: [fontSize]
+ })
+ }
+ default:
+ return function (...data) {
+ this.actions.push({
+ method,
+ data
+ })
+ }
+ }
+ }
+ CanvasContext.prototype[method] = get(method)
+})
+
+export function createCanvasContext (id, context) {
+ if (context) {
+ return new CanvasContext(id, context.$page.id)
+ }
+ const pageId = getCurrentPageId()
+ if (pageId) {
+ return new CanvasContext(id, pageId)
+ } else {
+ UniServiceJSBridge.emit('onError', 'createCanvasContext:fail')
+ }
+}
+
+export function canvasGetImageData ({
+ canvasId,
+ x,
+ y,
+ width,
+ height
+}, callbackId) {
+ var pageId = getCurrentPageId()
+ if (!pageId) {
+ invoke(callbackId, {
+ errMsg: 'canvasGetImageData:fail'
+ })
+ return
+ }
+ var cId = canvasEventCallbacks.push(function (data) {
+ var imgData = data.data
+ if (imgData && imgData.length) {
+ data.data = new Uint8ClampedArray(imgData)
+ }
+ invoke(callbackId, data)
+ })
+ operateCanvas(canvasId, pageId, 'getImageData', {
+ x,
+ y,
+ width,
+ height,
+ callbackId: cId
+ })
+}
+
+export function canvasPutImageData ({
+ canvasId,
+ data,
+ x,
+ y,
+ width,
+ height
+}, callbackId) {
+ var pageId = getCurrentPageId()
+ if (!pageId) {
+ invoke(callbackId, {
+ errMsg: 'canvasPutImageData:fail'
+ })
+ return
+ }
+ var cId = canvasEventCallbacks.push(function (data) {
+ invoke(callbackId, data)
+ })
+ // fix ...
+ operateCanvas(canvasId, pageId, 'putImageData', {
+ data: Array.prototype.slice.call(data),
+ x,
+ y,
+ width,
+ height,
+ callbackId: cId
+ })
+}
+
+export function canvasToTempFilePath ({
+ x = 0,
+ y = 0,
+ width,
+ height,
+ destWidth,
+ destHeight,
+ canvasId,
+ fileType,
+ qualit
+}, callbackId) {
+ var pageId = getCurrentPageId()
+ if (!pageId) {
+ invoke(callbackId, {
+ errMsg: 'canvasToTempFilePath:fail'
+ })
+ return
+ }
+ const cId = canvasEventCallbacks.push(function ({
+ base64
+ }) {
+ if (!base64 || !base64.length) {
+ invoke(callbackId, {
+ errMsg: 'canvasToTempFilePath:fail'
+ })
+ }
+ invokeMethod('base64ToTempFilePath', {
+ base64Data: base64,
+ x,
+ y,
+ width,
+ height,
+ destWidth,
+ destHeight,
+ canvasId,
+ fileType,
+ qualit
+ }, callbackId)
+ })
+ operateCanvas(canvasId, pageId, 'getDataUrl', {
+ x,
+ y,
+ width,
+ height,
+ destWidth,
+ destHeight,
+ hidpi: false,
+ fileType,
+ qualit,
+ callbackId: cId
+ })
}
diff --git a/src/core/service/api/context/create-video-context.js b/src/core/service/api/context/create-video-context.js
index 9d2d0a28248a3de1b34c82a6fe209437a9a166f3..8ba0feb59bbf5258c8229f9345b56545f02b4827 100644
--- a/src/core/service/api/context/create-video-context.js
+++ b/src/core/service/api/context/create-video-context.js
@@ -17,21 +17,26 @@ export class VideoContext {
play () {
operateVideoPlayer(this.id, this.pageVm, 'play')
- }
+ }
+
pause () {
operateVideoPlayer(this.id, this.pageVm, 'pause')
- }
+ }
+
stop () {
operateVideoPlayer(this.id, this.pageVm, 'stop')
- }
+ }
+
seek (position) {
operateVideoPlayer(this.id, this.pageVm, 'seek', {
position
})
- }
+ }
+
sendDanmu (args) {
operateVideoPlayer(this.id, this.pageVm, 'sendDanmu', args)
- }
+ }
+
playbackRate (rate) {
if (!~RATES.indexOf(rate)) {
rate = 1.0
@@ -39,16 +44,20 @@ export class VideoContext {
operateVideoPlayer(this.id, this.pageVm, 'playbackRate', {
rate
})
- }
+ }
+
requestFullScreen (args = {}) {
operateVideoPlayer(this.id, this.pageVm, 'requestFullScreen', args)
- }
+ }
+
exitFullScreen () {
operateVideoPlayer(this.id, this.pageVm, 'exitFullScreen')
- }
+ }
+
showStatusBar () {
operateVideoPlayer(this.id, this.pageVm, 'showStatusBar')
- }
+ }
+
hideStatusBar () {
operateVideoPlayer(this.id, this.pageVm, 'hideStatusBar')
}
diff --git a/src/core/service/api/context/editor.js b/src/core/service/api/context/editor.js
index 008b8f4cd8829fc5d7f636f6e46527df7db753ac..34e901abfea1db8b613a77a26ea93d313ead8f54 100644
--- a/src/core/service/api/context/editor.js
+++ b/src/core/service/api/context/editor.js
@@ -24,6 +24,7 @@ export class EditorContext {
this.id = id
this.pageId = pageId
}
+
format (name, value) {
operateEditor(this.id, this.pageId, 'format', {
options: {
diff --git a/src/core/service/api/media/recorder.js b/src/core/service/api/media/recorder.js
index f760465960cabd455d1cf324b7e55555a2e3f15e..e2d687918566e8896b5d2ee0f07384681225d2b8 100644
--- a/src/core/service/api/media/recorder.js
+++ b/src/core/service/api/media/recorder.js
@@ -22,45 +22,57 @@ class RecorderManager {
}
})
}
+
onError (callback) {
callbacks.error = callback
}
+
onFrameRecorded (callback) {
}
+
onInterruptionBegin (callback) {
}
+
onInterruptionEnd (callback) {
}
+
onPause (callback) {
callbacks.pause = callback
}
+
onResume (callback) {
callbacks.resume = callback
}
+
onStart (callback) {
callbacks.start = callback
}
+
onStop (callback) {
callbacks.stop = callback
}
+
pause () {
invokeMethod('operateRecorder', {
operationType: 'pause'
})
}
+
resume () {
invokeMethod('operateRecorder', {
operationType: 'resume'
})
}
+
start (options) {
invokeMethod('operateRecorder', Object.assign({}, options, {
operationType: 'start'
}))
}
+
stop () {
invokeMethod('operateRecorder', {
operationType: 'stop'
diff --git a/src/core/service/api/network/download-file.js b/src/core/service/api/network/download-file.js
index 05388832cf6ebce580a636b8689376ed28770f0e..6eee099cabf9e2b4f063dfd6f9a7764f9b2cfd20 100644
--- a/src/core/service/api/network/download-file.js
+++ b/src/core/service/api/network/download-file.js
@@ -12,28 +12,33 @@ class DownloadTask {
this.id = downloadTaskId
this._callbackId = callbackId
this._callbacks = []
- }
+ }
+
abort () {
invokeMethod('operateRequestTask', {
downloadTaskId: this.id,
operationType: 'abort'
})
- }
+ }
+
onProgressUpdate (callback) {
if (typeof callback !== 'function') {
return
}
this._callbacks.push(callback)
- }
+ }
+
onHeadersReceived () {
- }
+ }
+
offProgressUpdate (callback) {
const index = this._callbacks.indexOf(callback)
if (index >= 0) {
this._callbacks.splice(index, 1)
}
- }
+ }
+
offHeadersReceived () {
}
diff --git a/src/core/service/api/network/socket.js b/src/core/service/api/network/socket.js
index 0cc9bc2c8a4fbe56218f7ede914b94fc3de03d92..a060590be07d82051e2c2f1a4cba0a8028a7c41a 100644
--- a/src/core/service/api/network/socket.js
+++ b/src/core/service/api/network/socket.js
@@ -21,7 +21,8 @@ class SocketTask {
this.CONNECTING = 0
this.OPEN = 1
this.readyState = this.CLOSED
- }
+ }
+
send (args) {
if (this.readyState !== this.OPEN) {
this._callback(args, 'sendSocketMessage:fail WebSocket is not connected')
@@ -33,7 +34,8 @@ class SocketTask {
socketTaskId: this.id
}))
this._callback(args, errMsg.replace('operateSocketTask', 'sendSocketMessage'))
- }
+ }
+
close (args) {
this.readyState = this.CLOSING
const {
@@ -43,19 +45,24 @@ class SocketTask {
socketTaskId: this.id
}))
this._callback(args, errMsg.replace('operateSocketTask', 'closeSocket'))
- }
+ }
+
onOpen (callback) {
this._callbacks.open.push(callback)
- }
+ }
+
onClose (callback) {
this._callbacks.close.push(callback)
- }
+ }
+
onError (callback) {
this._callbacks.error.push(callback)
- }
+ }
+
onMessage (callback) {
this._callbacks.message.push(callback)
- }
+ }
+
_callback ({
success,
fail,
diff --git a/src/core/service/api/network/upload-file.js b/src/core/service/api/network/upload-file.js
index e3b38e79a9a41aefbe22a8ae68ac9dc0426737fa..1317cce6bcd42223355d47ade074a3f50ee21620 100644
--- a/src/core/service/api/network/upload-file.js
+++ b/src/core/service/api/network/upload-file.js
@@ -12,28 +12,33 @@ class UploadTask {
this.id = uploadTaskId
this._callbackId = callbackId
this._callbacks = []
- }
+ }
+
abort () {
invokeMethod('operateRequestTask', {
uploadTaskId: this.id,
operationType: 'abort'
})
- }
+ }
+
onProgressUpdate (callback) {
if (typeof callback !== 'function') {
return
}
this._callbacks.push(callback)
- }
+ }
+
onHeadersReceived () {
- }
+ }
+
offProgressUpdate (callback) {
const index = this._callbacks.indexOf(callback)
if (index >= 0) {
this._callbacks.splice(index, 1)
}
- }
+ }
+
offHeadersReceived () {
}
diff --git a/src/core/service/api/ui/create-animation.js b/src/core/service/api/ui/create-animation.js
index 49a599c0640bde01b4f7b635037a8b16b80d0f43..c0739b7b60ddb733df6fd02d9a449907c4c389b7 100644
--- a/src/core/service/api/ui/create-animation.js
+++ b/src/core/service/api/ui/create-animation.js
@@ -12,28 +12,33 @@ class MPAnimation {
this.currentStepAnimates = []
this.option = Object.assign({}, defaultOption, option)
}
+
_getOption (option) {
- let _option = {
+ const _option = {
transition: Object.assign({}, this.option, option)
}
_option.transformOrigin = _option.transition.transformOrigin
delete _option.transition.transformOrigin
return _option
}
+
_pushAnimates (type, args) {
this.currentStepAnimates.push({
type: type,
args: args
})
}
+
_converType (type) {
return type.replace(/[A-Z]/g, text => {
return `-${text.toLowerCase()}`
})
}
+
_getValue (value) {
return typeof value === 'number' ? `${value}px` : value
}
+
export () {
const actions = this.actions
this.actions = []
@@ -41,6 +46,7 @@ class MPAnimation {
actions
}
}
+
step (option) {
this.currentStepAnimates.forEach(animate => {
if (animate.type !== 'style') {
diff --git a/src/core/service/api/ui/create-intersection-observer.js b/src/core/service/api/ui/create-intersection-observer.js
index c0336e5557b445a2657c10d3f492bc940fd7ecac..275f130d58acf3bb14f6a03101db252ea196ea35 100644
--- a/src/core/service/api/ui/create-intersection-observer.js
+++ b/src/core/service/api/ui/create-intersection-observer.js
@@ -17,21 +17,25 @@ class ServiceIntersectionObserver {
this.pageId = component.$page.id
this.component = component._$id || component // app-plus 平台传输_$id
this.options = Object.assign({}, defaultOptions, options)
- }
+ }
+
_makeRootMargin (margins = {}) {
this.options.rootMargin = ['top', 'right', 'bottom', 'left'].map(name => `${Number(margins[name]) || 0}px`).join(
' ')
- }
+ }
+
relativeTo (selector, margins) {
this.options.relativeToSelector = selector
this._makeRootMargin(margins)
return this
- }
+ }
+
relativeToViewport (margins) {
this.options.relativeToSelector = null
this._makeRootMargin(margins)
return this
- }
+ }
+
observe (selector, callback) {
if (typeof callback !== 'function') {
return
@@ -45,7 +49,8 @@ class ServiceIntersectionObserver {
component: this.component,
options: this.options
}, this.pageId)
- }
+ }
+
disconnect () {
UniServiceJSBridge.publishHandler('destroyComponentObserver', {
reqId: this.reqId
diff --git a/src/core/view/bridge/subscribe/api/request-component-observer.js b/src/core/view/bridge/subscribe/api/request-component-observer.js
index dac80dc11b9f84505dd35bf19aec0f832ca42d28..4641612fb18d350da246ce4465c8bdba38ae30e9 100644
--- a/src/core/view/bridge/subscribe/api/request-component-observer.js
+++ b/src/core/view/bridge/subscribe/api/request-component-observer.js
@@ -40,7 +40,7 @@ export function requestComponentObserver ({
const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null
- let intersectionObserver = intersectionObservers[reqId] = new IntersectionObserver((entries, observer) => {
+ const intersectionObserver = intersectionObservers[reqId] = new IntersectionObserver((entries, observer) => {
entries.forEach(entrie => {
UniViewJSBridge.publishHandler('onRequestComponentObserver', {
reqId,
diff --git a/src/core/view/bridge/subscribe/api/util.js b/src/core/view/bridge/subscribe/api/util.js
index 356018dab72e3ba6cd6303c45b81c1469bb8fe3b..c64a09493d987a6c219d9ff89778aada303d3912 100644
--- a/src/core/view/bridge/subscribe/api/util.js
+++ b/src/core/view/bridge/subscribe/api/util.js
@@ -14,7 +14,7 @@ function findVmById (id, vm) {
export function findElm (component, pageVm) {
if (!pageVm) {
- return console.error(`page is not ready`)
+ return console.error('page is not ready')
}
if (!component) {
return pageVm.$el
diff --git a/src/core/view/bridge/subscribe/font.js b/src/core/view/bridge/subscribe/font.js
index 26753477591dfdbd18ba8a9a417479cc7e4f0732..273cdf493622b0538224f28ef87134c5657da4f8 100644
--- a/src/core/view/bridge/subscribe/font.js
+++ b/src/core/view/bridge/subscribe/font.js
@@ -13,7 +13,7 @@ export function loadFontFace ({
UniViewJSBridge.publishHandler('onLoadFontFaceCallback', {
callbackId,
data: {
- errMsg: `loadFontFace:ok`
+ errMsg: 'loadFontFace:ok'
}
})
})
@@ -32,7 +32,7 @@ export function loadFontFace ({
UniViewJSBridge.publishHandler('onLoadFontFaceCallback', {
callbackId,
data: {
- errMsg: `loadFontFace:ok`
+ errMsg: 'loadFontFace:ok'
}
})
}
diff --git a/src/core/view/bridge/subscribe/scroll.js b/src/core/view/bridge/subscribe/scroll.js
index 2250965d5f2c8d58b55b6729e3e4c5819f32f3e7..2f3116f74c0b2318d3481ef3c92faa2ad8644f79 100644
--- a/src/core/view/bridge/subscribe/scroll.js
+++ b/src/core/view/bridge/subscribe/scroll.js
@@ -80,7 +80,7 @@ export function createScrollListener (pageId, {
// 部分浏览器窗口高度变化后document.documentelement.clientheight不会变化,采用window.innerHeight
const windowHeight = window.innerHeight
const scrollY = window.scrollY
- let isBottom = scrollY > 0 && scrollHeight > windowHeight && (scrollY + windowHeight + onReachBottomDistance) >= scrollHeight
+ const isBottom = scrollY > 0 && scrollHeight > windowHeight && (scrollY + windowHeight + onReachBottomDistance) >= scrollHeight
// 兼容部分浏览器滚动时scroll事件不触发
const heightChanged = Math.abs(scrollHeight - lastScrollHeight) > onReachBottomDistance
if (isBottom && (!hasReachBottom || heightChanged)) {
diff --git a/src/core/view/components/button/index.vue b/src/core/view/components/button/index.vue
index 58354e14b74bc875136e6e17248b714167a7d88c..56d8bfaf33434024f82b7111921cbdcade52e198 100644
--- a/src/core/view/components/button/index.vue
+++ b/src/core/view/components/button/index.vue
@@ -63,9 +63,9 @@ export default {
},
_bindObjectListeners (data, value) {
if (value) {
- for (let key in value) {
- let existing = data.on[key]
- let ours = value[key]
+ for (const key in value) {
+ const existing = data.on[key]
+ const ours = value[key]
data.on[key] = existing ? [].concat(existing, ours) : ours
}
}
@@ -73,7 +73,7 @@ export default {
}
},
render (createElement) {
- let $listeners = Object.create(null)
+ const $listeners = Object.create(null)
if (this.$listeners) {
Object.keys(this.$listeners).forEach(e => {
if (this.disabled && (e === 'click' || e === 'tap')) {
@@ -86,7 +86,7 @@ export default {
return createElement('uni-button', this._bindObjectListeners({
class: [this.hovering ? this.hoverClass : ''],
attrs: {
- 'disabled': this.disabled
+ disabled: this.disabled
},
on: {
touchstart: this._hoverTouchStart,
@@ -99,7 +99,7 @@ export default {
return createElement('uni-button', this._bindObjectListeners({
class: [this.hovering ? this.hoverClass : ''],
attrs: {
- 'disabled': this.disabled
+ disabled: this.disabled
},
on: {
click: this._onClick
diff --git a/src/core/view/components/canvas/index.vue b/src/core/view/components/canvas/index.vue
index 910d20c47fefa404ab7abdda2b3e3b2b2ac107a4..000ba276c4f79edc130f38f367a55f1ff9b99808 100644
--- a/src/core/view/components/canvas/index.vue
+++ b/src/core/view/components/canvas/index.vue
@@ -2,17 +2,20 @@
+ v-on="_listeners"
+ >
+ height="150"
+ />
+ @resize="_resize"
+ />