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

chore: size-check

上级 366b220b
......@@ -18,4 +18,4 @@ jobs:
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
build_script: build
files: packages/size-check/dist/assets/index.js packages/size-check/dist/assets/index.css packages/uni-h5-vue/dist/vue.runtime.esm.js packages/uni-mp-vue/dist/vue.runtime.esm.js packages/uni-mp-alipay/dist/uni.api.esm.js packages/uni-mp-alipay/dist/uni.mp.esm.js packages/uni-mp-baidu/dist/uni.api.esm.js packages/uni-mp-baidu/dist/uni.mp.esm.js packages/uni-mp-qq/dist/uni.api.esm.js packages/uni-mp-qq/dist/uni.mp.esm.js packages/uni-mp-toutiao/dist/uni.api.esm.js packages/uni-mp-toutiao/dist/uni.mp.esm.js packages/uni-mp-weixin/dist/uni.api.esm.js packages/uni-mp-weixin/dist/uni.mp.esm.js packages/uni-quickapp-webview/dist/uni.api.esm.js packages/uni-quickapp-webview/dist/uni.mp.esm.js
files: packages/size-check/dist/size-check.es.js packages/size-check/dist/style.css packages/uni-app/dist/uni-app.esm.js packages/uni-h5-vue/dist/vue.runtime.esm.js packages/uni-mp-vue/dist/vue.runtime.esm.js packages/uni-mp-alipay/dist/uni.api.esm.js packages/uni-mp-alipay/dist/uni.mp.esm.js packages/uni-mp-baidu/dist/uni.api.esm.js packages/uni-mp-baidu/dist/uni.mp.esm.js packages/uni-mp-qq/dist/uni.api.esm.js packages/uni-mp-qq/dist/uni.mp.esm.js packages/uni-mp-toutiao/dist/uni.api.esm.js packages/uni-mp-toutiao/dist/uni.mp.esm.js packages/uni-mp-weixin/dist/uni.api.esm.js packages/uni-mp-weixin/dist/uni.mp.esm.js packages/uni-quickapp-webview/dist/uni.api.esm.js packages/uni-quickapp-webview/dist/uni.mp.esm.js
......@@ -117,7 +117,7 @@ declare namespace UniApp {
interface PagesJsonPagePlatformStyle {
h5?: PagesJsonPageStyle
'app-plus'?: PagesJsonPageStyle
app?: PagesJsonPageStyle
'mp-alipay'?: PagesJsonPageStyle
'mp-baidu'?: PagesJsonPageStyle
'mp-qq'?: PagesJsonPageStyle
......
......@@ -6,7 +6,7 @@
"versionCode": "100",
"transformPx": false,
/* 5+App特有相关 */
"app-plus": {
"app": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
......
......@@ -8,13 +8,18 @@ import uni, { uniVueTemplateOptions } from '@dcloudio/vite-plugin-uni'
export default {
root: __dirname,
build: {
lib: {
entry: path.resolve(__dirname, 'src/main.ts'),
formats: ['es'],
},
// minify: false,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
},
// external: ['vue', '@vue/shared'],
// output: {
// entryFileNames: `assets/[name].js`,
// chunkFileNames: `assets/[name].js`,
// assetFileNames: `assets/[name].[ext]`,
// },
},
},
......
......@@ -163,7 +163,7 @@ function assertType(
} else if (expectedType === 'Array') {
valid = isArray(value)
} else {
if (__PLATFORM__ === 'app-plus') {
if (__PLATFORM__ === 'app') {
// App平台ArrayBuffer等参数跨实例传输,无法通过 instanceof 识别
valid = value instanceof type || toRawType(value) === getType(type)
} else {
......
......@@ -50,7 +50,7 @@ export type API_TYPE_CANVAS_PUT_IMAGE_DATA = typeof uni.canvasPutImageData
export const CanvasPutImageDataOptions = CanvasGetImageDataOptions
export const CanvasPutImageDataProtocol: ApiProtocol<API_TYPE_CANVAS_PUT_IMAGE_DATA> = extend(
export const CanvasPutImageDataProtocol: ApiProtocol<API_TYPE_CANVAS_PUT_IMAGE_DATA> = /*#__PURE__*/ extend(
{
data: {
type: Uint8ClampedArray as any,
......
......@@ -47,13 +47,13 @@ export const API_PRELOAD_PAGE = 'preloadPage'
export type API_TYPE_PRELOAD_PAGE = typeof uni.preloadPage
export const API_UN_PRELOAD_PAGE = 'unPreloadPage'
export type API_TYPE_UN_PRELOAD_PAGE = typeof uni.unPreloadPage
export const NavigateToProtocol: ApiProtocol<API_TYPE_NAVIGATE_TO> = extend(
export const NavigateToProtocol: ApiProtocol<API_TYPE_NAVIGATE_TO> = /*#__PURE__*/ extend(
{},
BaseRouteProtocol,
createAnimationProtocol(ANIMATION_IN)
)
export const NavigateBackProtocol: ApiProtocol<API_TYPE_NAVIGATE_BACK> = extend(
export const NavigateBackProtocol: ApiProtocol<API_TYPE_NAVIGATE_BACK> = /*#__PURE__*/ extend(
{
delta: {
type: Number,
......@@ -177,7 +177,7 @@ function createNormalizeUrl(type: string) {
if (type === API_UN_PRELOAD_PAGE) {
return
} else if (type === API_PRELOAD_PAGE) {
if (__PLATFORM__ === 'app-plus') {
if (__PLATFORM__ === 'app') {
if (!routeOptions.meta.isNVue) {
return 'can not preload vue page'
}
......
......@@ -28,7 +28,7 @@ const IndexOptions: ApiOptions<API_TYPE_REMOVE_TAB_BAR_BADGE> = {
}
export const API_SET_TAB_BAR_ITEM = 'setTabBarItem'
export type API_TYPE_SET_TAB_BAR_ITEM = typeof uni.setTabBarItem
export const SetTabBarItemProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_ITEM> = extend(
export const SetTabBarItemProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_ITEM> = /*#__PURE__*/ extend(
{
text: String,
iconPath: String,
......@@ -40,7 +40,7 @@ export const SetTabBarItemProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_ITEM> = ext
export const SetTabBarItemOptions: ApiOptions<API_TYPE_SET_TAB_BAR_ITEM> = {
beforeInvoke: IndexOptions.beforeInvoke,
formatArgs: extend(
formatArgs: /*#__PURE__*/ extend(
{
pagePath(value, params) {
if (value) {
......@@ -104,7 +104,7 @@ export const RemoveTabBarBadgeOptions: ApiOptions<API_TYPE_REMOVE_TAB_BAR_BADGE>
export const API_SET_TAB_BAR_BADGE = 'setTabBarBadge'
export type API_TYPE_SET_TAB_BAR_BADGE = typeof uni.setTabBarBadge
export const SetTabBarBadgeProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_BADGE> = extend(
export const SetTabBarBadgeProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_BADGE> = /*#__PURE__*/ extend(
{
text: {
type: String,
......@@ -115,7 +115,7 @@ export const SetTabBarBadgeProtocol: ApiProtocol<API_TYPE_SET_TAB_BAR_BADGE> = e
)
export const SetTabBarBadgeOptions: ApiOptions<API_TYPE_SET_TAB_BAR_BADGE> = {
beforeInvoke: IndexOptions.beforeInvoke,
formatArgs: extend(
formatArgs: /*#__PURE__*/ extend(
{
text(value, params) {
if (getLen(value) >= 4) {
......
......@@ -4,11 +4,11 @@ import { useHover } from '../../helpers/useHover'
import { useBooleanAttr } from '../../helpers/useBooleanAttr'
import { UniFormCtx, uniFormKey } from '../form'
if (__PLATFORM__ === 'app-plus') {
initI18nButtonMsgs()
if (__PLATFORM__ === 'app') {
/*#__PURE__*/ initI18nButtonMsgs()
}
export default defineComponent({
export default /*#__PURE__*/ defineComponent({
name: 'Button',
props: {
id: {
......@@ -67,7 +67,7 @@ export default defineComponent({
}
return
}
if (__PLATFORM__ === 'app-plus' && props.openType === 'feedback') {
if (__PLATFORM__ === 'app' && props.openType === 'feedback') {
openFeedback(
t('uni.button.feedback.title'),
t('uni.button.feedback.send')
......
<template>
<uni-canvas
:canvas-id="canvasId"
:disable-scroll="disableScroll"
v-on="_listeners"
>
<canvas
ref="canvas"
width="300"
height="150"
/>
<uni-canvas :canvas-id="canvasId" :disable-scroll="disableScroll" v-on="_listeners">
<canvas ref="canvas" width="300" height="150" />
<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden;">
<slot />
</div>
<v-uni-resize-sensor
ref="sensor"
@resize="_resize"
/>
<v-uni-resize-sensor ref="sensor" @resize="_resize" />
</uni-canvas>
</template>
<script>
......@@ -25,16 +14,19 @@ import {
import {
pixelRatio,
wrapper
wrapper,
initHidpi
} from '../../helpers/hidpi'
function resolveColor (color) {
/*#__PURE__*/ initHidpi()
function resolveColor(color) {
color = color.slice(0)
color[3] = color[3] / 255
return 'rgba(' + color.join(',') + ')'
}
function processTouches (target, touches) {
function processTouches(target, touches) {
return ([]).map.call(touches, (touch) => {
var boundingClientRect = target.getBoundingClientRect()
return {
......@@ -46,7 +38,7 @@ function processTouches (target, touches) {
}
var tempCanvas
function getTempCanvas (width = 0, height = 0) {
function getTempCanvas(width = 0, height = 0) {
if (!tempCanvas) {
tempCanvas = document.createElement('canvas')
}
......@@ -68,16 +60,16 @@ export default {
default: false
}
},
data () {
data() {
return {
actionsWaiting: false
}
},
computed: {
id () {
id() {
return this.canvasId
},
_listeners () {
_listeners() {
var $listeners = Object.assign({}, this.$listeners)
var events = ['touchstart', 'touchmove', 'touchend']
events.forEach(event => {
......@@ -100,22 +92,22 @@ export default {
return $listeners
}
},
created () {
created() {
this._actionsDefer = []
this._images = {}
},
mounted () {
mounted() {
this._resize({
width: this.$refs.sensor.$el.offsetWidth,
height: this.$refs.sensor.$el.offsetHeight
})
},
beforeDestroy () {
beforeDestroy() {
const canvas = this.$refs.canvas
canvas.height = canvas.width = 0
},
methods: {
_handleSubscribe ({
_handleSubscribe({
type,
data = {}
}) {
......@@ -124,7 +116,7 @@ export default {
method(data)
}
},
_resize () {
_resize() {
var canvas = this.$refs.canvas
if (canvas.width > 0 && canvas.height > 0) {
var context = canvas.getContext('2d')
......@@ -135,10 +127,10 @@ export default {
wrapper(this.$refs.canvas)
}
},
_touchmove (event) {
_touchmove(event) {
event.preventDefault()
},
actionsChanged ({
actionsChanged({
actions,
reserve,
callbackId
......@@ -176,7 +168,7 @@ export default {
color = resolveColor(data[1])
} else if (data[0] === 'linear') {
const LinearGradient = c2d.createLinearGradient(...data[1])
data[2].forEach(function (data2) {
data[2].forEach(function(data2) {
const offset = data2[0]
const color = resolveColor(data2[1])
LinearGradient.addColorStop(offset, color)
......@@ -187,7 +179,7 @@ export default {
const y = data[1][1]
const r = data[1][2]
const LinearGradient = c2d.createRadialGradient(x, y, 0, x, y, r)
data[2].forEach(function (data2) {
data[2].forEach(function(data2) {
const offset = data2[0]
const color = resolveColor(data2[1])
LinearGradient.addColorStop(offset, color)
......@@ -195,7 +187,7 @@ export default {
color = LinearGradient
} else if (data[0] === 'pattern') {
const loaded = this.checkImageLoaded(data[1], actions.slice(index + 1), callbackId,
function (image) {
function(image) {
if (image) {
c2d[method1] = c2d.createPattern(image, data[2])
}
......@@ -210,7 +202,7 @@ export default {
c2d[method1] = data[0] / 255
} else if (method1 === 'shadow') {
var _ = ['shadowOffsetX', 'shadowOffsetY', 'shadowBlur', 'shadowColor']
data.forEach(function (color_, method_) {
data.forEach(function(color_, method_) {
c2d[_[method_]] = _[method_] === 'shadowColor' ? resolveColor(color_) : color_
})
} else {
......@@ -235,19 +227,19 @@ export default {
} else if (method === 'fillPath' || method === 'strokePath') {
method = method.replace(/Path/, '')
c2d.beginPath()
data.forEach(function (data_) {
data.forEach(function(data_) {
c2d[data_.method].apply(c2d, data_.data)
})
c2d[method]()
} else if (method === 'fillText') {
c2d.fillText.apply(c2d, data)
} else if (method === 'drawImage') {
var A = (function () {
var A = (function() {
var dataArray = [...data]
var url = dataArray[0]
var otherData = dataArray.slice(1)
self._images = self._images || {}
if (!self.checkImageLoaded(url, actions.slice(index + 1), callbackId, function (
if (!self.checkImageLoaded(url, actions.slice(index + 1), callbackId, function(
image) {
if (image) {
c2d.drawImage.apply(c2d, [image].concat([...otherData.slice(4, 8)],
......@@ -260,7 +252,7 @@ export default {
}
} else {
if (method === 'clip') {
data.forEach(function (data_) {
data.forEach(function(data_) {
c2d[data_.method].apply(c2d, data_.data)
})
c2d.clip()
......@@ -278,9 +270,9 @@ export default {
}, this.$page.id)
}
},
preloadImage: function (actions) {
preloadImage: function(actions) {
var self = this
actions.forEach(function (action) {
actions.forEach(function(action) {
var method = action.method
var data = action.data
var src = ''
......@@ -299,28 +291,28 @@ export default {
/**
* 加载图像
*/
function loadImage () {
function loadImage() {
self._images[src] = new Image()
self._images[src].onload = function () {
self._images[src].onload = function() {
self._images[src].ready = true
}
/**
* 从Blob加载
* @param {Blob} blob
*/
function loadBlob (blob) {
function loadBlob(blob) {
self._images[src].src = (window.URL || window.webkitURL).createObjectURL(blob)
}
/**
* 从本地文件加载
* @param {string} path 文件路径
*/
function loadFile (path) {
function loadFile(path) {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.load(path, function () {
bitmap.load(path, function() {
self._images[src].src = bitmap.toBase64Data()
bitmap.clear()
}, function () {
}, function() {
bitmap.clear()
console.error('preloadImage error')
})
......@@ -329,11 +321,11 @@ export default {
* 从网络加载
* @param {string} url 文件地址
*/
function loadUrl (url) {
function plusDownload () {
function loadUrl(url) {
function plusDownload() {
plus.downloader.createDownload(url, {
filename: '_doc/uniapp_temp/download/'
}, function (d, status) {
}, function(d, status) {
if (status === 200) {
loadFile(d.filename)
} else {
......@@ -344,12 +336,12 @@ export default {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = function () {
xhr.onload = function() {
if (this.status === 200) {
loadBlob(this.response)
}
}
xhr.onerror = window.plus ? plusDownload : function () {
xhr.onerror = window.plus ? plusDownload : function() {
self._images[src].src = src
}
xhr.send()
......@@ -371,7 +363,7 @@ export default {
}
})
},
checkImageLoaded: function (src, actions, callbackId, fn) {
checkImageLoaded: function(src, actions, callbackId, fn) {
var self = this
var image = this._images[src]
if (image.ready) {
......@@ -380,7 +372,7 @@ export default {
} else {
this._actionsDefer.unshift([actions, true])
this.actionsWaiting = true
image.onload = function () {
image.onload = function() {
image.ready = true
fn(image)
self.actionsWaiting = false
......@@ -398,7 +390,7 @@ export default {
return false
}
},
getImageData ({
getImageData({
x = 0,
y = 0,
width,
......@@ -468,7 +460,7 @@ export default {
}, this.$page.id)
}
},
putImageData ({
putImageData({
data,
x,
y,
......@@ -501,7 +493,7 @@ export default {
}
}, this.$page.id)
},
getDataUrl ({
getDataUrl({
x = 0,
y = 0,
width,
......
......@@ -15,7 +15,7 @@ interface UniFormFieldCtx {
reset: () => void
}
export default defineComponent({
export default /*#__PURE__*/ defineComponent({
name: 'Form',
setup(_props, { slots, emit }) {
provideForm(emit)
......
......@@ -59,7 +59,7 @@ const ICONS = {
},
}
export default defineComponent({
export default /*#__PURE__*/ defineComponent({
name: 'Icon',
props: {
type: {
......
......@@ -40,7 +40,7 @@ export default {
},
watch: {
value (val, oldVal) {
if (__PLATFORM__ !== 'app-plus' || val === oldVal || val.length !== oldVal.length || val.findIndex((item, index) => item !== oldVal[index]) >= 0) {
if (__PLATFORM__ !== 'app' || val === oldVal || val.length !== oldVal.length || val.findIndex((item, index) => item !== oldVal[index]) >= 0) {
this.valueSync.length = val.length
val.forEach((val, index) => {
if (val !== this.valueSync[index]) {
......
......@@ -34,7 +34,7 @@ function normalizeText(text: string, { space, decode }: DecodeOptions) {
.replace(/&apos;/g, "'")
}
export default defineComponent({
export default /*#__PURE__*/ defineComponent({
name: 'Text',
props: {
selectable: {
......
......@@ -3,7 +3,7 @@ import { defineComponent } from 'vue'
import { hoverProps, useHover } from '../../helpers/useHover'
export default defineComponent({
export default /*#__PURE__*/ defineComponent({
name: 'View',
props: extend({}, hoverProps),
setup(props, { slots }) {
......
import { hasOwn } from '@vue/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
var font = this.font
this.font = font.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) {
return m * pixelRatio + u
})
_super.apply(this, args)
this.font = font
}
})(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
var font = this.font
this.font = font.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) {
return m * pixelRatio + u
})
_super.apply(this, args)
this.font = font
}
})(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 '@vue/shared'
export const pixelRatio = /*#__PURE__*/ (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
})()
export function wrapper(canvas) {
canvas.width = canvas.offsetWidth * pixelRatio
canvas.height = canvas.offsetHeight * pixelRatio
canvas.getContext('2d').__hidpi__ = true
}
let isHidpi = false
export function initHidpi() {
if (isHidpi) {
return
}
isHidpi = true
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
var font = this.font
this.font = font.replace(
/(\d+\.?\d*)(px|em|rem|pt)/g,
function (w, m, u) {
return m * pixelRatio + u
}
)
_super.apply(this, args)
this.font = font
}
})(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
var font = this.font
this.font = font.replace(
/(\d+\.?\d*)(px|em|rem|pt)/g,
function (w, m, u) {
return m * pixelRatio + u
}
)
_super.apply(this, args)
this.font = font
}
})(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)
}
}
import { initVueI18n } from '@dcloudio/uni-i18n'
const i18n = initVueI18n()
import { BuiltInLocale, initVueI18n } from '@dcloudio/uni-i18n'
import { getBaseSystemInfo } from '@dcloudio/uni-platform'
const i18n = initVueI18n(getBaseSystemInfo().language as BuiltInLocale)
export function useI18n() {
return i18n
}
......@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { initBridge } from '../../helpers/bridge'
export const ServiceJSBridge = extend(initBridge('service'), {
export const ServiceJSBridge = /*#__PURE__*/ extend(initBridge('service'), {
invokeOnCallback(name: string, res: unknown) {
return UniServiceJSBridge.emit('api.' + name, res)
},
......
import { App, ComponentPublicInstance } from 'vue'
import { isString } from '@vue/shared'
import { invokeArrayFns } from '@dcloudio/uni-shared'
import { initAppConfig } from './appConfig'
export function initService(app: App) {
......@@ -28,7 +29,25 @@ export function getCurrentPageVm() {
}
}
export function invokeHook<T>(name: string, args?: T) {
const vm = getCurrentPageVm()
return vm && vm.$callHook(name, args)
export function invokeHook(name: string, args?: unknown): unknown
export function invokeHook(
vm: ComponentPublicInstance,
name: string,
args?: unknown
): unknown
export function invokeHook(
vm: ComponentPublicInstance | string,
name?: string | unknown,
args?: unknown
) {
if (isString(vm)) {
args = name
name = vm
vm = getCurrentPageVm()!
}
if (!vm) {
return
}
const hooks = vm.$[name as string]
return hooks && invokeArrayFns(hooks, args)
}
......@@ -58,7 +58,7 @@ export function normalizeEvent(
stopPropagation() {},
}
if (__PLATFORM__ === 'app-plus' && currentTarget) {
if (__PLATFORM__ === 'app' && currentTarget) {
const nid = currentTarget.getAttribute('_i')
;(ret as any).options = {
nid,
......
此差异已折叠。
......@@ -18,7 +18,7 @@ import {
useI18n,
initI18nAsyncMsgs
} from '@dcloudio/uni-core'
initI18nAsyncMsgs()
/*#__PURE__*/ initI18nAsyncMsgs()
export default {
name: 'AsyncError',
setup() {
......
......@@ -35,9 +35,8 @@ const CSS_VARS = [
export default defineComponent({
name: 'Layout',
setup(props, { emit }) {
setup(_props, { emit }) {
useCssVar()
useAppLifecycle()
const keepAliveRoute = (__UNI_FEATURE_PAGES__ &&
useKeepAliveRoute()) as KeepAliveRoute
const topWindow = __UNI_FEATURE_TOPWINDOW__ && useTopWindow()
......@@ -64,18 +63,6 @@ function useCssVar() {
CSS_VARS.forEach((name) => updateCssVar(name, '0px'))
}
function useAppLifecycle() {
onMounted(() => {
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') {
UniServiceJSBridge.emit('onAppEnterForeground')
} else {
UniServiceJSBridge.emit('onAppEnterBackground')
}
})
})
}
function useAppClass(showTabBar?: ComputedRef<boolean>) {
const showMaxWidth = ref(false)
return computed(() => {
......
......@@ -6,6 +6,7 @@ import {
ComponentPublicInstance,
} from 'vue'
import { useRoute, RouteLocationNormalizedLoaded } from 'vue-router'
import { invokeHook } from '@dcloudio/uni-core'
import { removeLeadingSlash } from '@dcloudio/uni-shared'
import { usePageMeta } from './provide'
......@@ -34,7 +35,7 @@ export function removeCurrentPages(delta: number = -1) {
const routeKey = keys[i]
const pageVm = currentPagesMap.get(routeKey) as ComponentPublicInstance
pageVm.$.__isUnload = true
pageVm.$callHook('onUnload')
invokeHook(pageVm, 'onUnload')
currentPagesMap.delete(routeKey)
}
}
......
......@@ -11,6 +11,7 @@ import {
onBeforeDeactivate,
onBeforeMount,
} from 'vue'
import { parseQuery, decodedQuery } from '@dcloudio/uni-shared'
import { LayoutComponent } from '../..'
import { initApp } from './app'
import { initPage } from './page'
......@@ -21,6 +22,25 @@ interface SetupComponentOptions {
after?: (comp: DefineComponent) => void
}
export function usePageRoute() {
if (__UNI_FEATURE_PAGES__) {
return useRoute()
}
const url = location.href
const searchPos = url.indexOf('?')
const hashPos = url.indexOf('#', searchPos > -1 ? searchPos : 0)
let query = {}
if (searchPos > -1) {
query = parseQuery(
url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)
)
}
return {
meta: __uniRoutes[0].meta,
query: query,
}
}
function wrapperComponentSetup(
comp: DefineComponent,
{ init, setup, after }: SetupComponentOptions
......@@ -50,9 +70,10 @@ export function setupPage(comp: any) {
return setupComponent(comp, {
init: initPage,
setup(instance) {
const route = usePageRoute()
onBeforeMount(() => {
const { onLoad, onShow } = instance
onLoad && invokeArrayFns(onLoad)
onLoad && invokeArrayFns(onLoad, decodedQuery(route.query))
instance.__isVisible = true
onShow && invokeArrayFns(onShow)
})
......@@ -82,11 +103,26 @@ export function setupApp(comp: any) {
return setupComponent(comp, {
init: initApp,
setup(instance) {
const route = usePageRoute()
onBeforeMount(() => {
const { onLaunch, onShow } = instance
onLaunch && invokeArrayFns(onLaunch)
onLaunch &&
invokeArrayFns(onLaunch, {
path: route.meta.route,
query: decodedQuery(route.query),
scene: 1001,
})
onShow && invokeArrayFns(onShow)
})
onMounted(() => {
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') {
UniServiceJSBridge.emit('onAppEnterForeground')
} else {
UniServiceJSBridge.emit('onAppEnterBackground')
}
})
})
},
after(comp) {
comp.mpType = 'app'
......
......@@ -43,7 +43,7 @@ export function getWindowWidth(screenWidth: number) {
}
/**
* 简易版systemInfo,主要为upx2px服务
* 简易版systemInfo,主要为upx2px,i18n服务
* @returns
*/
export function getBaseSystemInfo() {
......@@ -53,6 +53,7 @@ export function getBaseSystemInfo() {
)
return {
platform: isIOS ? 'ios' : 'other',
language: navigator.language,
pixelRatio: window.devicePixelRatio,
windowWidth,
}
......
......@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { ServiceJSBridge } from '@dcloudio/uni-core'
export const UniServiceJSBridge = extend(ServiceJSBridge, {
export const UniServiceJSBridge = /*#__PURE__*/ extend(ServiceJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniViewJSBridge.subscribeHandler(event, args, pageId)
},
......
......@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { ViewJSBridge } from '@dcloudio/uni-core'
export const UniViewJSBridge = extend(ViewJSBridge, {
export const UniViewJSBridge = /*#__PURE__*/ extend(ViewJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniServiceJSBridge.subscribeHandler(event, args, pageId)
},
......
......@@ -80,11 +80,12 @@ export default defineConfig({
plugins: [
replace({
values: {
defineOnApi: `/*#__PURE__*/ defineOnApi`,
defineOffApi: `/*#__PURE__*/ defineOffApi`,
defineTaskApi: `/*#__PURE__*/ defineTaskApi`,
defineSyncApi: `/*#__PURE__*/ defineSyncApi`,
defineAsyncApi: `/*#__PURE__*/ defineAsyncApi`,
// extend: `/*#__PURE__*/ extend`,
// defineOnApi: `/*#__PURE__*/ defineOnApi`,
// defineOffApi: `/*#__PURE__*/ defineOffApi`,
// defineTaskApi: `/*#__PURE__*/ defineTaskApi`,
// defineSyncApi: `/*#__PURE__*/ defineSyncApi`,
// defineAsyncApi: `/*#__PURE__*/ defineAsyncApi`,
},
preventAssignment: true,
}),
......
......@@ -207,17 +207,17 @@ function initLocaleWatcher(appVm, i18n) {
immediate: true,
});
}
function getDefaultLocale() {
if (typeof navigator !== 'undefined') {
return navigator.userLanguage || navigator.language;
}
if (typeof plus !== 'undefined') {
// TODO 待调整为最新的获取语言代码
return plus.os.language;
}
return uni.getSystemInfoSync().language;
}
function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
// function getDefaultLocale() {
// if (typeof navigator !== 'undefined') {
// return (navigator as any).userLanguage || navigator.language
// }
// if (typeof plus !== 'undefined') {
// // TODO 待调整为最新的获取语言代码
// return plus.os.language
// }
// return uni.getSystemInfoSync().language
// }
function initVueI18n(locale = LOCALE_EN, messages = {}, fallbackLocale = LOCALE_EN) {
const i18n = new I18n({
locale: locale || fallbackLocale,
fallbackLocale,
......@@ -225,7 +225,7 @@ function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
});
let t = (key, values) => {
if (typeof getApp !== 'function') {
// app-plus view
// app view
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values);
......@@ -234,9 +234,9 @@ function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
else {
const appVm = getApp().$vm;
if (!appVm.$t || !appVm.$i18n) {
if (!locale) {
i18n.setLocale(getDefaultLocale());
}
// if (!locale) {
// i18n.setLocale(getDefaultLocale())
// }
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values);
......
......@@ -29,7 +29,7 @@ export declare interface I18nOptions {
watcher?: LocaleWatcher;
}
export declare function initVueI18n(messages?: LocaleMessages, fallbackLocale?: BuiltInLocale, locale?: BuiltInLocale): {
export declare function initVueI18n(locale?: BuiltInLocale, messages?: LocaleMessages, fallbackLocale?: BuiltInLocale): {
i18n: I18n;
t(key: string, values?: Record<string, unknown> | unknown[] | undefined): string;
add(locale: BuiltInLocale, message: Record<string, string>): void;
......
......@@ -203,17 +203,17 @@ function initLocaleWatcher(appVm, i18n) {
immediate: true,
});
}
function getDefaultLocale() {
if (typeof navigator !== 'undefined') {
return navigator.userLanguage || navigator.language;
}
if (typeof plus !== 'undefined') {
// TODO 待调整为最新的获取语言代码
return plus.os.language;
}
return uni.getSystemInfoSync().language;
}
function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
// function getDefaultLocale() {
// if (typeof navigator !== 'undefined') {
// return (navigator as any).userLanguage || navigator.language
// }
// if (typeof plus !== 'undefined') {
// // TODO 待调整为最新的获取语言代码
// return plus.os.language
// }
// return uni.getSystemInfoSync().language
// }
function initVueI18n(locale = LOCALE_EN, messages = {}, fallbackLocale = LOCALE_EN) {
const i18n = new I18n({
locale: locale || fallbackLocale,
fallbackLocale,
......@@ -221,7 +221,7 @@ function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
});
let t = (key, values) => {
if (typeof getApp !== 'function') {
// app-plus view
// app view
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values);
......@@ -230,9 +230,9 @@ function initVueI18n(messages = {}, fallbackLocale = LOCALE_EN, locale) {
else {
const appVm = getApp().$vm;
if (!appVm.$t || !appVm.$i18n) {
if (!locale) {
i18n.setLocale(getDefaultLocale());
}
// if (!locale) {
// i18n.setLocale(getDefaultLocale())
// }
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values);
......
......@@ -18,21 +18,21 @@ function initLocaleWatcher(appVm: any, i18n: I18n) {
)
}
function getDefaultLocale() {
if (typeof navigator !== 'undefined') {
return (navigator as any).userLanguage || navigator.language
}
if (typeof plus !== 'undefined') {
// TODO 待调整为最新的获取语言代码
return plus.os.language
}
return uni.getSystemInfoSync().language
}
// function getDefaultLocale() {
// if (typeof navigator !== 'undefined') {
// return (navigator as any).userLanguage || navigator.language
// }
// if (typeof plus !== 'undefined') {
// // TODO 待调整为最新的获取语言代码
// return plus.os.language
// }
// return uni.getSystemInfoSync().language
// }
export function initVueI18n(
locale: BuiltInLocale = LOCALE_EN,
messages: LocaleMessages = {},
fallbackLocale: BuiltInLocale = LOCALE_EN,
locale?: BuiltInLocale
fallbackLocale: BuiltInLocale = LOCALE_EN
) {
const i18n = new I18n({
locale: locale || fallbackLocale,
......@@ -41,7 +41,7 @@ export function initVueI18n(
})
let t: Interpolate = (key, values) => {
if (typeof getApp !== 'function') {
// app-plus view
// app view
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values)
......@@ -49,9 +49,9 @@ export function initVueI18n(
} else {
const appVm = getApp().$vm
if (!appVm.$t || !appVm.$i18n) {
if (!locale) {
i18n.setLocale(getDefaultLocale())
}
// if (!locale) {
// i18n.setLocale(getDefaultLocale())
// }
/* eslint-disable no-func-assign */
t = function (key, values) {
return i18n.t(key, values)
......
import { isFunction, isSymbol, extend, isMap, isObject, toRawType, def, isArray, isString, isPromise, toHandlerKey, remove, EMPTY_OBJ, camelize, capitalize, normalizeClass, normalizeStyle, isOn, NOOP, isGloballyWhitelisted, isIntegerKey, hasOwn, hasChanged, NO, invokeArrayFns, makeMap, isSet, toNumber, hyphenate, isReservedProp, EMPTY_ARR, toTypeString } from '@vue/shared';
import { isFunction, isString, isSymbol, extend, isMap, isObject, toRawType, def, isArray, isPromise, toHandlerKey, remove, EMPTY_OBJ, camelize, capitalize, normalizeClass, normalizeStyle, isOn, NOOP, isGloballyWhitelisted, isIntegerKey, hasOwn, hasChanged, NO, invokeArrayFns as invokeArrayFns$1, makeMap, isSet, toNumber, hyphenate, isReservedProp, EMPTY_ARR, toTypeString } from '@vue/shared';
export { camelize } from '@vue/shared';
import { injectHook as injectHook$1 } from 'vue';
......@@ -13,6 +13,14 @@ function applyOptions$1(options, instance, publicThis) {
});
}
const invokeArrayFns = (fns, arg) => {
let ret;
for (let i = 0; i < fns.length; i++) {
ret = fns[i](arg);
}
return ret;
};
function set$2(target, key, val) {
return (target[key] = val);
}
......@@ -25,24 +33,49 @@ function hasHook(name) {
}
function callHook(name, args) {
const hooks = this.$[name];
let ret;
if (hooks) {
for (let i = 0; i < hooks.length; i++) {
ret = hooks[i](args);
}
return hooks && invokeArrayFns(hooks, args);
}
function getCurrentPage() {
const pages = getCurrentPages();
const len = pages.length;
if (len) {
return pages[len - 1];
}
return ret;
}
function getCurrentPageVm() {
const page = getCurrentPage();
if (page) {
return page.$vm;
}
}
function invokeHook(vm, name, args) {
if (isString(vm)) {
args = name;
name = vm;
vm = getCurrentPageVm();
}
if (!vm) {
return;
}
const hooks = vm.$[name];
return hooks && invokeArrayFns(hooks, args);
}
function errorHandler(err, instance, info) {
if (!instance) {
throw err;
}
const appInstance = instance.$.appContext.$appInstance;
if (!appInstance) {
const app = getApp();
if (!app || !app.$vm) {
throw err;
}
appInstance.$callHook('onError', err, info);
if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') {
app.$vm.$callHook('onError', err, info);
}
else {
invokeHook(app.$vm, 'onError', err);
}
}
function initApp(app) {
......@@ -51,8 +84,11 @@ function initApp(app) {
appConfig.errorHandler = errorHandler;
}
const globalProperties = appConfig.globalProperties;
globalProperties.$hasHook = hasHook;
globalProperties.$callHook = callHook;
if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') {
// 小程序,待重构,不再挂靠全局
globalProperties.$hasHook = hasHook;
globalProperties.$callHook = callHook;
}
if (__VUE_OPTIONS_API__) {
globalProperties.$set = set$2;
globalProperties.$applyOptions = applyOptions$1;
......@@ -4032,8 +4068,8 @@ const prodEffectOptions = {
function createDevEffectOptions(instance) {
return {
scheduler: queueJob,
onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
onTrack: instance.rtc ? e => invokeArrayFns$1(instance.rtc, e) : void 0,
onTrigger: instance.rtg ? e => invokeArrayFns$1(instance.rtg, e) : void 0
};
}
function setupRenderEffect(instance) {
......@@ -4049,7 +4085,7 @@ function setupRenderEffect(instance) {
const { bu, u } = instance;
// beforeUpdate hook
if (bu) {
invokeArrayFns(bu);
invokeArrayFns$1(bu);
}
patch(instance);
// updated hook
......@@ -4063,7 +4099,7 @@ function unmountComponent(instance) {
const { bum, effects, update, um } = instance;
// beforeUnmount hook
if (bum) {
invokeArrayFns(bum);
invokeArrayFns$1(bum);
}
if (effects) {
for (let i = 0; i < effects.length; i++) {
......
......@@ -102,7 +102,14 @@ function getLen(str = '') {
}
function removeLeadingSlash(str) {
return str.indexOf('/') === 0 ? str.substr(1) : str;
}
}
const invokeArrayFns = (fns, arg) => {
let ret;
for (let i = 0; i < fns.length; i++) {
ret = fns[i](arg);
}
return ret;
};
const encode = encodeURIComponent;
function stringifyQuery(obj, encodeStr = encode) {
......@@ -122,6 +129,69 @@ function stringifyQuery(obj, encodeStr = encode) {
.join('&')
: null;
return res ? `?${res}` : '';
}
/**
* Decode text using `decodeURIComponent`. Returns the original text if it
* fails.
*
* @param text - string to decode
* @returns decoded string
*/
function decode(text) {
try {
return decodeURIComponent('' + text);
}
catch (err) { }
return '' + text;
}
function decodedQuery(query = {}) {
const decodedQuery = {};
Object.keys(query).forEach((name) => {
try {
decodedQuery[name] = decode(query[name]);
}
catch (e) {
decodedQuery[name] = query[name];
}
});
return decodedQuery;
}
const PLUS_RE = /\+/g; // %2B
/**
* https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
* @internal
*
* @param search - search string to parse
* @returns a query object
*/
function parseQuery(search) {
const query = {};
// avoid creating an object with an empty key and empty value
// because of split('&')
if (search === '' || search === '?')
return query;
const hasLeadingIM = search[0] === '?';
const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
for (let i = 0; i < searchParams.length; ++i) {
// pre decode the + into space
const searchParam = searchParams[i].replace(PLUS_RE, ' ');
// allow the = character
let eqPos = searchParam.indexOf('=');
let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
if (key in query) {
// an extra variable for ts types
let currentValue = query[key];
if (!Array.isArray(currentValue)) {
currentValue = query[key] = [currentValue];
}
currentValue.push(value);
}
else {
query[key] = value;
}
}
return query;
}
function debounce(fn, delay) {
......@@ -148,16 +218,21 @@ exports.COMPONENT_NAME_PREFIX = COMPONENT_NAME_PREFIX;
exports.COMPONENT_PREFIX = COMPONENT_PREFIX;
exports.COMPONENT_SELECTOR_PREFIX = COMPONENT_SELECTOR_PREFIX;
exports.NAVBAR_HEIGHT = NAVBAR_HEIGHT;
exports.PLUS_RE = PLUS_RE;
exports.PRIMARY_COLOR = PRIMARY_COLOR;
exports.RESPONSIVE_MIN_WIDTH = RESPONSIVE_MIN_WIDTH;
exports.TABBAR_HEIGHT = TABBAR_HEIGHT;
exports.TAGS = TAGS;
exports.debounce = debounce;
exports.decode = decode;
exports.decodedQuery = decodedQuery;
exports.getLen = getLen;
exports.invokeArrayFns = invokeArrayFns;
exports.isBuiltInComponent = isBuiltInComponent;
exports.isCustomElement = isCustomElement;
exports.isNativeTag = isNativeTag;
exports.normalizeDataset = normalizeDataset;
exports.parseQuery = parseQuery;
exports.passive = passive;
exports.plusReady = plusReady;
exports.removeLeadingSlash = removeLeadingSlash;
......
......@@ -12,8 +12,21 @@ export declare function debounce(fn: Function, delay: number): {
cancel(): void;
};
/**
* Decode text using `decodeURIComponent`. Returns the original text if it
* fails.
*
* @param text - string to decode
* @returns decoded string
*/
export declare function decode(text: string | number): string;
export declare function decodedQuery(query?: Record<string, any>): Record<string, string>;
export declare function getLen(str?: string): number;
export declare const invokeArrayFns: (fns: Function[], arg?: any) => any;
export declare function isBuiltInComponent(tag: string): boolean;
export declare function isCustomElement(tag: string): boolean;
......@@ -24,10 +37,21 @@ export declare const NAVBAR_HEIGHT = 44;
export declare function normalizeDataset(el: Element): any;
/**
* https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
* @internal
*
* @param search - search string to parse
* @returns a query object
*/
export declare function parseQuery(search: string): Record<string, any>;
export declare function passive(passive: boolean): {
passive: boolean;
};
export declare const PLUS_RE: RegExp;
export declare function plusReady(callback: () => void): void;
export declare const PRIMARY_COLOR = "#007aff";
......
......@@ -98,7 +98,14 @@ function getLen(str = '') {
}
function removeLeadingSlash(str) {
return str.indexOf('/') === 0 ? str.substr(1) : str;
}
}
const invokeArrayFns = (fns, arg) => {
let ret;
for (let i = 0; i < fns.length; i++) {
ret = fns[i](arg);
}
return ret;
};
const encode = encodeURIComponent;
function stringifyQuery(obj, encodeStr = encode) {
......@@ -118,6 +125,69 @@ function stringifyQuery(obj, encodeStr = encode) {
.join('&')
: null;
return res ? `?${res}` : '';
}
/**
* Decode text using `decodeURIComponent`. Returns the original text if it
* fails.
*
* @param text - string to decode
* @returns decoded string
*/
function decode(text) {
try {
return decodeURIComponent('' + text);
}
catch (err) { }
return '' + text;
}
function decodedQuery(query = {}) {
const decodedQuery = {};
Object.keys(query).forEach((name) => {
try {
decodedQuery[name] = decode(query[name]);
}
catch (e) {
decodedQuery[name] = query[name];
}
});
return decodedQuery;
}
const PLUS_RE = /\+/g; // %2B
/**
* https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
* @internal
*
* @param search - search string to parse
* @returns a query object
*/
function parseQuery(search) {
const query = {};
// avoid creating an object with an empty key and empty value
// because of split('&')
if (search === '' || search === '?')
return query;
const hasLeadingIM = search[0] === '?';
const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
for (let i = 0; i < searchParams.length; ++i) {
// pre decode the + into space
const searchParam = searchParams[i].replace(PLUS_RE, ' ');
// allow the = character
let eqPos = searchParam.indexOf('=');
let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
if (key in query) {
// an extra variable for ts types
let currentValue = query[key];
if (!Array.isArray(currentValue)) {
currentValue = query[key] = [currentValue];
}
currentValue.push(value);
}
else {
query[key] = value;
}
}
return query;
}
function debounce(fn, delay) {
......@@ -139,4 +209,4 @@ const RESPONSIVE_MIN_WIDTH = 768;
const COMPONENT_NAME_PREFIX = 'VUni';
const PRIMARY_COLOR = '#007aff';
export { BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, NAVBAR_HEIGHT, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, TABBAR_HEIGHT, TAGS, debounce, getLen, isBuiltInComponent, isCustomElement, isNativeTag, normalizeDataset, passive, plusReady, removeLeadingSlash, stringifyQuery };
export { BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, NAVBAR_HEIGHT, PLUS_RE, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, TABBAR_HEIGHT, TAGS, debounce, decode, decodedQuery, getLen, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, normalizeDataset, parseQuery, passive, plusReady, removeLeadingSlash, stringifyQuery };
......@@ -18,3 +18,66 @@ export function stringifyQuery(obj?: Record<string, any>, encodeStr = encode) {
: null
return res ? `?${res}` : ''
}
/**
* Decode text using `decodeURIComponent`. Returns the original text if it
* fails.
*
* @param text - string to decode
* @returns decoded string
*/
export function decode(text: string | number): string {
try {
return decodeURIComponent('' + text)
} catch (err) {}
return '' + text
}
export function decodedQuery(query: Record<string, any> = {}) {
const decodedQuery: Record<string, string> = {}
Object.keys(query).forEach((name) => {
try {
decodedQuery[name] = decode(query[name])
} catch (e) {
decodedQuery[name] = query[name]
}
})
return decodedQuery
}
export const PLUS_RE = /\+/g // %2B
/**
* https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
* @internal
*
* @param search - search string to parse
* @returns a query object
*/
export function parseQuery(search: string) {
const query: Record<string, any> = {}
// avoid creating an object with an empty key and empty value
// because of split('&')
if (search === '' || search === '?') return query
const hasLeadingIM = search[0] === '?'
const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&')
for (let i = 0; i < searchParams.length; ++i) {
// pre decode the + into space
const searchParam = searchParams[i].replace(PLUS_RE, ' ')
// allow the = character
let eqPos = searchParam.indexOf('=')
let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos))
let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1))
if (key in query) {
// an extra variable for ts types
let currentValue = query[key]
if (!Array.isArray(currentValue)) {
currentValue = query[key] = [currentValue]
}
currentValue.push(value)
} else {
query[key] = value
}
}
return query
}
......@@ -5,3 +5,11 @@ export function getLen(str = '') {
export function removeLeadingSlash(str: string) {
return str.indexOf('/') === 0 ? str.substr(1) : str
}
export const invokeArrayFns = (fns: Function[], arg?: any) => {
let ret
for (let i = 0; i < fns.length; i++) {
ret = fns[i](arg)
}
return ret
}
import { invokeHook } from '@dcloudio/uni-core'
import { ComponentPublicInstance } from 'vue'
export function errorHandler(
......@@ -8,9 +9,13 @@ export function errorHandler(
if (!instance) {
throw err
}
const appInstance = (instance.$.appContext as any).$appInstance
if (!appInstance) {
const app = getApp()
if (!app || !app.$vm) {
throw err
}
appInstance.$callHook('onError', err, info)
if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') {
app.$vm.$callHook('onError', err, info)
} else {
invokeHook(app.$vm, 'onError', err)
}
}
import { ComponentPublicInstance } from 'vue'
import { invokeArrayFns } from '@dcloudio/uni-shared'
export function set(target: any, key: string | number, val: unknown) {
return (target[key] = val)
......@@ -18,11 +19,5 @@ export function callHook(
args?: unknown
) {
const hooks = (this.$ as any)[name]
let ret
if (hooks) {
for (let i = 0; i < hooks.length; i++) {
ret = hooks[i](args)
}
}
return ret
return hooks && invokeArrayFns(hooks, args)
}
......@@ -11,8 +11,11 @@ export function initApp(app: App) {
appConfig.errorHandler = errorHandler
}
const globalProperties = appConfig.globalProperties
globalProperties.$hasHook = hasHook
globalProperties.$callHook = callHook
if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') {
// 小程序,待重构,不再挂靠全局
globalProperties.$hasHook = hasHook
globalProperties.$callHook = callHook
}
if (__VUE_OPTIONS_API__) {
globalProperties.$set = set
globalProperties.$applyOptions = applyOptions
......
......@@ -2,11 +2,14 @@ import path from 'path'
import slash from 'slash'
import { UserConfig } from 'vite'
import { VitePluginUniResolvedOptions } from '..'
import { FEATURE_DEFINES } from '../utils'
export function createBuild(
options: VitePluginUniResolvedOptions
options: VitePluginUniResolvedOptions,
features: FEATURE_DEFINES
): UserConfig['build'] {
return {
polyfillDynamicImport: features.__UNI_FEATURE_PAGES__,
rollupOptions: {
output: {
chunkFileNames(chunkInfo) {
......
......@@ -11,6 +11,7 @@ import { createDefine } from './define'
import { createServer } from './server'
import { createBuild } from './build'
import { createOptimizeDeps } from './optimizeDeps'
import { FEATURE_DEFINES } from '../utils'
function resolveBase(inputDir: string) {
const manifest = parse(
fs.readFileSync(path.join(inputDir, 'manifest.json'), 'utf8')
......@@ -29,13 +30,14 @@ export function createConfig(
options.inputDir = inputDir
options.outputDir = outputDir
options.command = env.command
const define = createDefine(options, env)
return {
base: options.base,
define: createDefine(options, env),
define,
resolve: createResolve(options),
optimizeDeps: createOptimizeDeps(options),
server: createServer(options),
build: createBuild(options),
build: createBuild(options, define as FEATURE_DEFINES),
css: createCss(options),
}
}
......
......@@ -68,9 +68,9 @@ export function uniManifestJsonPlugin(
defaultQQMapKey
const flexDirection =
(manifest['app-plus'] &&
manifest['app-plus'].nvue &&
manifest['app-plus'].nvue['flex-direction']) ||
(manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) ||
'column'
return {
......
......@@ -64,7 +64,9 @@ function parsePagesJson(
return `
import { extend } from '@vue/shared'
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { ${
config.define!.__UNI_FEATURE_PAGES__ ? 'defineAsyncComponent, ' : ''
}resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { setupPage, PageComponent, AsyncLoadingComponent, AsyncErrorComponent } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue } from '${manifestJsonPath}'
${cssCode}
......
......@@ -170,6 +170,10 @@ function resolveManifestFeature(
const manifest = parse(
fs.readFileSync(path.join(options.inputDir, 'manifest.json'), 'utf8')
)
if (options.command === 'build') {
// TODO 需要预编译一遍?
features.wxs = false
}
if (
manifest.h5 &&
manifest.h5.router &&
......
......@@ -84,10 +84,10 @@ function normalizePageStyle(
) {
if (pageStyle) {
if (platform === 'h5') {
Object.assign(pageStyle, pageStyle['app-plus'] || {})
Object.assign(pageStyle, pageStyle['app'] || {})
}
Object.assign(pageStyle, pageStyle[platform] || {})
if (['h5', 'app-plus'].includes(platform)) {
if (['h5', 'app'].includes(platform)) {
pageStyle.navigationBar = normalizeNavigationBar(pageStyle)
}
return removePlatformStyle(pageStyle)
......@@ -254,7 +254,7 @@ function normalizeFilepath(filepath: string) {
return filepath
}
const platforms = ['h5', 'app-plus', 'mp-', 'quickapp']
const platforms = ['h5', 'app', 'mp-', 'quickapp']
function removePlatformStyle(pageStyle: UniApp.PagesJsonPageStyle) {
Object.keys(pageStyle).forEach((name) => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册