提交 7ab8af11 编写于 作者: fxy060608's avatar fxy060608

build(deps): bump vite from 2.0.0-beta.4 to 2.0.0-beta.31

上级 2d1b746b
......@@ -11,7 +11,7 @@ module.exports = {
'error',
// we are only using this rule to check for unused arguments since TS
// catches unused variables but not args.
{ varsIgnorePattern: '.*', args: 'after-used', argsIgnorePattern: '^_' },
{ varsIgnorePattern: '.*', args: 'none' },
],
// most of the codebase are expected to be env agnostic
'no-restricted-globals': ['error', ...DOMGlobals, ...NodeGlobals],
......
此差异已折叠。
此差异已折叠。
......@@ -6,7 +6,7 @@
],
"scripts": {
"build": "node scripts/build.js",
"lint": "eslint packages/**/*.ts",
"lint": "eslint packages/*/src/**/*.ts",
"format": "prettier --write --parser typescript \"packages/**/*.ts?(x)\"",
"ls-lint": "ls-lint",
"test": "jest",
......@@ -66,7 +66,7 @@
"semver": "^7.3.4",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3",
"vite": "^2.0.0-beta.4",
"vite": "^2.0.0-beta.31",
"vue": "3.0.5",
"yorkie": "^2.0.0"
}
......
......@@ -38,7 +38,7 @@ export function createApi<T extends Function>(
fn: T,
protocol?: ApiProtocols
) {
return (function(...args: any[]) {
return (function (...args: any[]) {
if (type === API_TYPE_SYNC) {
if (!(__DEV__ && protocol && !validateProtocol(name!, args, protocol))) {
return fn.apply(null, formatApiArgs(args, options))
......
......@@ -16,7 +16,7 @@ for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i
}
exports.encode = function(arraybuffer) {
export function encode(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i,
len = bytes.length,
......@@ -38,7 +38,7 @@ exports.encode = function(arraybuffer) {
return base64
}
exports.decode = function(base64) {
export function decode(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length,
i,
......
......@@ -5,7 +5,7 @@ export enum HOOKS {
SUCCESS = 'success',
FAIL = 'fail',
COMPLETE = 'complete',
RETURN_VALUE = 'returnValue'
RETURN_VALUE = 'returnValue',
}
export type Interceptor = { [P in HOOKS]?: Function }
......@@ -16,7 +16,7 @@ export const globalInterceptors: Interceptors = {}
export const scopedInterceptors: { [key: string]: Interceptors } = {}
function wrapperHook(hook: Function) {
return function(data: unknown) {
return function (data: unknown) {
return hook(data) || data
}
}
......@@ -35,7 +35,7 @@ function queue(hooks: Function[], data: unknown): Promise<any> {
if (res === false) {
return {
then() {},
catch() {}
catch() {},
} as Promise<undefined>
}
}
......@@ -45,7 +45,7 @@ function queue(hooks: Function[], data: unknown): Promise<any> {
then(callback: Function) {
return callback(data)
},
catch() {}
catch() {},
}
)
}
......@@ -54,7 +54,7 @@ function wrapperOptions(
interceptors: Interceptors,
options: Record<string, any> = {}
) {
;[HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => {
;[HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach((name) => {
const hooks = interceptors[name]
if (!isArray(hooks)) {
return
......@@ -78,7 +78,7 @@ export function wrapperReturnValue(method: string, returnValue: unknown) {
if (interceptor && isArray(interceptor.returnValue)) {
returnValueHooks.push(...interceptor.returnValue)
}
returnValueHooks.forEach(hook => {
returnValueHooks.forEach((hook) => {
returnValue = hook(returnValue) || returnValue
})
return returnValue
......@@ -86,7 +86,7 @@ export function wrapperReturnValue(method: string, returnValue: unknown) {
function getApiInterceptorHooks(method: string) {
const interceptor = Object.create(null)
Object.keys(globalInterceptors).forEach(hook => {
Object.keys(globalInterceptors).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = (globalInterceptors[
hook as HOOKS
......@@ -95,7 +95,7 @@ function getApiInterceptorHooks(method: string) {
})
const scopedInterceptor = scopedInterceptors[method]
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => {
Object.keys(scopedInterceptor).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(
scopedInterceptor[hook as HOOKS]
......@@ -116,7 +116,7 @@ export function invokeApi(
if (interceptor && Object.keys(interceptor).length) {
if (isArray(interceptor.invoke)) {
const res = queue(interceptor.invoke, options)
return res.then(options => {
return res.then((options) => {
return api(wrapperOptions(interceptor, options), ...params)
})
} else {
......
......@@ -36,10 +36,10 @@ function handlePromise(promise: Promise<any>) {
return promise
}
return promise
.then(data => {
.then((data) => {
return [null, data]
})
.catch(err => [err])
.catch((err) => [err])
}
export function shouldPromise(name: string) {
......@@ -51,13 +51,13 @@ export function shouldPromise(name: string) {
/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
Promise.prototype.finally = function(
Promise.prototype.finally = function (
onfinally?: (() => void) | undefined | null
) {
const promise = this.constructor as PromiseConstructor
return this.then(
value => promise.resolve(onfinally && onfinally()).then(() => value),
reason =>
(value) => promise.resolve(onfinally && onfinally()).then(() => value),
(reason) =>
promise.resolve(onfinally && onfinally()).then(() => {
throw reason
})
......@@ -89,7 +89,7 @@ export function promisify(name: string, api: unknown) {
api,
Object.assign({}, options, {
success: resolve,
fail: reject
fail: reject,
}),
...params
)
......
......@@ -11,14 +11,14 @@ export const HTTP_METHODS = {
PUT: 'PUT',
DELETE: 'DELETE',
TRACE: 'TRACE',
CONNECT: 'CONNECT'
CONNECT: 'CONNECT',
}
export function normalizeStrArray(strArr: string[], optionalVal: string[]) {
if (
!isArray(strArr) ||
strArr.length === 0 ||
strArr.find(val => optionalVal.indexOf(val) === -1)
strArr.find((val) => optionalVal.indexOf(val) === -1)
) {
return optionalVal
}
......
......@@ -27,6 +27,6 @@ export {
API_TYPE_ON,
API_TYPE_SYNC,
API_TYPE_ASYNC,
API_TYPE_RETURN
API_TYPE_RETURN,
} from './helpers/api'
export { isSyncApi, isContextApi, promisify } from './helpers/promise'
......@@ -4,8 +4,8 @@ export const Base64ToArrayBufferProtocol: ProtocolOptions<String>[] = [
{
name: 'base64',
type: String,
required: true
}
required: true,
},
]
export const ArrayBufferToBase64Protocol: ProtocolOptions<
......@@ -14,6 +14,6 @@ export const ArrayBufferToBase64Protocol: ProtocolOptions<
{
name: 'arrayBuffer',
type: [ArrayBuffer, Uint8Array],
required: true
}
required: true,
},
]
import { ProtocolOptions } from '../type'
export const CanIUseProtocol: ProtocolOptions<String>[] = [
{
name: 'schema',
type: String,
required: true
}
]
import { ProtocolOptions } from '../type'
export const CanIUseProtocol: ProtocolOptions<String>[] = [
{
name: 'schema',
type: String,
required: true,
},
]
import { ProtocolOptions } from '../type'
export const $on: ProtocolOptions<String | Array<String> | Function>[] = [
{
name: 'event',
type: [String, Array],
required: true
},
{
name: 'callback',
type: Function,
required: true
}
]
export const $once = $on
export const $off: ProtocolOptions<String | Array<String> | Function>[] = [
{
name: 'event',
type: [String, Array]
},
{
name: 'callback',
type: Function
}
]
export const $emit: ProtocolOptions<String>[] = [
{
name: 'event',
type: String,
required: true
}
]
import { ProtocolOptions } from '../type'
export const $on: ProtocolOptions<String | Array<String> | Function>[] = [
{
name: 'event',
type: [String, Array],
required: true,
},
{
name: 'callback',
type: Function,
required: true,
},
]
export const $once = $on
export const $off: ProtocolOptions<String | Array<String> | Function>[] = [
{
name: 'event',
type: [String, Array],
},
{
name: 'callback',
type: Function,
},
]
export const $emit: ProtocolOptions<String>[] = [
{
name: 'event',
type: String,
required: true,
},
]
import { ProtocolOptions } from '../type'
export const AddInterceptorProtocol: ProtocolOptions<String | Object>[] = [
{
name: 'method',
type: [String, Object],
required: true
}
]
export const RemoveInterceptorProtocol = AddInterceptorProtocol
import { ProtocolOptions } from '../type'
export const AddInterceptorProtocol: ProtocolOptions<String | Object>[] = [
{
name: 'method',
type: [String, Object],
required: true,
},
]
export const RemoveInterceptorProtocol = AddInterceptorProtocol
import { ProtocolOptions } from '../type'
export const Upx2pxProtocol: ProtocolOptions<Number | String>[] = [
{
name: 'upx',
type: [Number, String],
required: true
}
]
import { ProtocolOptions } from '../type'
export const Upx2pxProtocol: ProtocolOptions<Number | String>[] = [
{
name: 'upx',
type: [Number, String],
required: true,
},
]
......@@ -3,7 +3,7 @@ import { extend } from '@vue/shared'
import { ApiProtocol, ApiOptions, Data } from '../type'
function getInt(name: string) {
return function(value: number, params: Data) {
return function (value: number, params: Data) {
if (value) {
params[name] = Math.round(value)
}
......@@ -15,31 +15,31 @@ export const CanvasGetImageDataOptions: ApiOptions = {
x: getInt('x'),
y: getInt('y'),
width: getInt('width'),
height: getInt('height')
}
height: getInt('height'),
},
}
export const CanvasGetImageDataProtocol: ApiProtocol = {
canvasId: {
type: String,
required: true
required: true,
},
x: {
type: Number,
required: true
required: true,
},
y: {
type: Number,
required: true
required: true,
},
width: {
type: Number,
required: true
required: true,
},
height: {
type: Number,
required: true
}
required: true,
},
}
export const CanvasPutImageDataOptions = CanvasGetImageDataOptions
......@@ -47,33 +47,33 @@ export const CanvasPutImageDataOptions = CanvasGetImageDataOptions
export const CanvasPutImageDataProtocol: ApiProtocol = {
canvasId: {
type: String,
required: true
required: true,
},
data: {
type: Uint8ClampedArray,
required: true
required: true,
},
x: {
type: Number,
required: true
required: true,
},
y: {
type: Number,
required: true
required: true,
},
width: {
type: Number,
required: true
required: true,
},
height: {
type: Number
}
type: Number,
},
}
const fileTypes = {
PNG: 'png',
JPG: 'jpg',
JPEG: 'jpg'
JPEG: 'jpg',
}
export const CanvasToTempFilePathOptions: ApiOptions = {
......@@ -92,56 +92,56 @@ export const CanvasToTempFilePathOptions: ApiOptions = {
quality(value: number, params: Data) {
value = Math.floor(value)
params.quality = value > 0 && value < 1 ? value : 1
}
},
},
CanvasGetImageDataOptions.formatArgs
)
),
}
export const CanvasToTempFilePathProtocol: ApiProtocol = {
x: {
type: Number,
default: 0
default: 0,
},
y: {
type: Number,
default: 0
default: 0,
},
width: {
type: Number
type: Number,
},
height: {
type: Number
type: Number,
},
destWidth: {
type: Number
type: Number,
},
destHeight: {
type: Number
type: Number,
},
canvasId: {
type: String,
required: true
required: true,
},
fileType: {
type: String
type: String,
},
quality: {
type: Number
}
type: Number,
},
}
export const DrawCanvasProtocol: ApiProtocol = {
canvasId: {
type: String,
required: true
required: true,
},
actions: {
type: Array,
required: true
required: true,
},
reserve: {
type: Boolean,
default: false
}
default: false,
},
}
import { ProtocolOptions } from '../type'
const validator: ProtocolOptions<String>[] = [
{
name: 'id',
type: String,
required: true
}
]
export const CreateAudioContextProtocol = validator
export const CreateVideoContextProtocol = validator
export const CreateMapContextProtocol = validator
export const CreateCanvasContextProtocol: ProtocolOptions<String | Object>[] = [
{
name: 'canvasId',
type: String,
required: true
},
{
name: 'componentInstance',
type: Object
}
]
import { ProtocolOptions } from '../type'
const validator: ProtocolOptions<String>[] = [
{
name: 'id',
type: String,
required: true,
},
]
export const CreateAudioContextProtocol = validator
export const CreateVideoContextProtocol = validator
export const CreateMapContextProtocol = validator
export const CreateCanvasContextProtocol: ProtocolOptions<String | Object>[] = [
{
name: 'canvasId',
type: String,
required: true,
},
{
name: 'componentInstance',
type: Object,
},
]
import { ApiProtocol } from '../type'
export const MakePhoneCallProtocol: ApiProtocol = {
phoneNumber: {
type: String,
required: true,
validator(phoneNumber: string) {
if (!phoneNumber) {
return 'makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;'
}
}
}
}
import { ApiProtocol } from '../type'
export const MakePhoneCallProtocol: ApiProtocol = {
phoneNumber: {
type: String,
required: true,
validator(phoneNumber: string) {
if (!phoneNumber) {
return 'makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;'
}
},
},
}
import { ApiOptions } from '../type'
export const SetClipboardDataOptions: ApiOptions = {
beforeSuccess() {
uni.showToast({
title: '内容已复制',
icon: 'success',
mask: false
})
}
}
import { ApiOptions } from '../type'
export const SetClipboardDataOptions: ApiOptions = {
beforeSuccess() {
uni.showToast({
title: '内容已复制',
icon: 'success',
mask: false,
})
},
}
......@@ -3,9 +3,9 @@ import { ApiProtocol } from '../type'
export const OpenDocumentProtocol: ApiProtocol = {
filePath: {
type: String,
required: true
required: true,
},
fileType: {
type: String
}
type: String,
},
}
import { ApiProtocol } from '../type'
export const ChooseLocationProtocol: ApiProtocol = {
keyword: {
type: String
}
}
import { ApiProtocol } from '../type'
export const ChooseLocationProtocol: ApiProtocol = {
keyword: {
type: String,
},
}
import { ApiProtocol, ApiOptions } from '../type'
const coordTypes = {
WGS84: 'WGS84',
GCJ02: 'GCJ02'
}
export const GetLocationOptions: ApiOptions = {
formatArgs: {
type(value, params) {
value = (value || '').toUpperCase()
let type = coordTypes[value as keyof typeof coordTypes]
if (!type) {
type = coordTypes.WGS84
}
params.type = type
}
}
}
export const GetLocationProtocol: ApiProtocol = {
type: {
type: String,
default: coordTypes.WGS84
},
altitude: {
type: Boolean,
default: false
}
}
import { ApiProtocol, ApiOptions } from '../type'
const coordTypes = {
WGS84: 'WGS84',
GCJ02: 'GCJ02',
}
export const GetLocationOptions: ApiOptions = {
formatArgs: {
type(value, params) {
value = (value || '').toUpperCase()
let type = coordTypes[value as keyof typeof coordTypes]
if (!type) {
type = coordTypes.WGS84
}
params.type = type
},
},
}
export const GetLocationProtocol: ApiProtocol = {
type: {
type: String,
default: coordTypes.WGS84,
},
altitude: {
type: Boolean,
default: false,
},
}
......@@ -5,27 +5,27 @@ export const OpenLocationOptions: ApiOptions = {
type(value, params) {
value = Math.floor(value)
params.scale = value >= 5 && value <= 18 ? value : 18
}
}
},
},
}
export const OpenLocationProtocol: ApiProtocol = {
latitude: {
type: Number,
required: true
required: true,
},
longitude: {
type: Number,
required: true
required: true,
},
scale: {
type: Number,
default: 18
default: 18,
},
name: {
type: String
type: String,
},
address: {
type: String
}
type: String,
},
}
import { ApiOptions, ApiProtocol } from '../type'
import {
CHOOSE_SIZE_TYPES,
CHOOSE_SOURCE_TYPES,
normalizeStrArray
} from '../../helpers/protocol'
export const ChooseImageOptions: ApiOptions = {
formatArgs: {
count(value, params) {
if (value <= 0) {
params.count = 9
}
},
sizeType(sizeType, params) {
params.sizeType = normalizeStrArray(sizeType, CHOOSE_SIZE_TYPES)
},
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
}
}
}
export const ChooseImageProtocol: ApiProtocol = {
count: {
type: Number,
default: 9
},
sizeType: {
type: [Array, String],
default: CHOOSE_SIZE_TYPES
},
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES
}
}
import { ApiOptions, ApiProtocol } from '../type'
import {
CHOOSE_SIZE_TYPES,
CHOOSE_SOURCE_TYPES,
normalizeStrArray,
} from '../../helpers/protocol'
export const ChooseImageOptions: ApiOptions = {
formatArgs: {
count(value, params) {
if (value <= 0) {
params.count = 9
}
},
sizeType(sizeType, params) {
params.sizeType = normalizeStrArray(sizeType, CHOOSE_SIZE_TYPES)
},
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
},
},
}
export const ChooseImageProtocol: ApiProtocol = {
count: {
type: Number,
default: 9,
},
sizeType: {
type: [Array, String],
default: CHOOSE_SIZE_TYPES,
},
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES,
},
}
import { CHOOSE_SOURCE_TYPES, normalizeStrArray } from '../../helpers/protocol'
import { ApiOptions, ApiProtocol } from '../type'
export const ChooseVideoOptions: ApiOptions = {
formatArgs: {
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
}
}
}
export const ChooseVideoProtocol: ApiProtocol = {
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES
}
}
import { CHOOSE_SOURCE_TYPES, normalizeStrArray } from '../../helpers/protocol'
import { ApiOptions, ApiProtocol } from '../type'
export const ChooseVideoOptions: ApiOptions = {
formatArgs: {
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
},
},
}
export const ChooseVideoProtocol: ApiProtocol = {
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES,
},
}
import { ApiOptions, ApiProtocol } from '../type'
export const GetImageInfoOptions: ApiOptions = {
formatArgs: {
src(src, params) {
params.src = (uni as any).getRealPath(src)
}
}
}
export const GetImageInfoProtocol: ApiProtocol = {
src: {
type: String,
required: true
}
}
import { ApiOptions, ApiProtocol } from '../type'
export const GetImageInfoOptions: ApiOptions = {
formatArgs: {
src(src, params) {
params.src = (uni as any).getRealPath(src)
},
},
}
export const GetImageInfoProtocol: ApiProtocol = {
src: {
type: String,
required: true,
},
}
......@@ -4,16 +4,16 @@ export const DownloadFileOptions: ApiOptions = {
formatArgs: {
header(value, params) {
params.header = value || {}
}
}
},
},
}
export const DownloadFileProtocol: ApiProtocol = {
url: {
type: String,
required: true
required: true,
},
header: {
type: Object
}
type: Object,
},
}
......@@ -17,35 +17,35 @@ export const ConnectSocketOptions: ApiOptions = {
if (typeof protocols === 'string') {
params.protocols = [protocols]
}
}
}
},
},
}
export const ConnectSocketProtocol: ApiProtocol = {
url: {
type: String,
required: true
required: true,
},
header: {
type: Object
type: Object,
},
method: {
type: String
type: String,
},
protocols: {
type: [Array, String] // 微信文档虽然写的是数组,但是可以正常传递字符串
}
type: [Array, String], // 微信文档虽然写的是数组,但是可以正常传递字符串
},
}
export const sendSocketMessage = {
data: {
type: [String, ArrayBuffer]
}
type: [String, ArrayBuffer],
},
}
export const closeSocket = {
code: {
type: Number
type: Number,
},
reason: {
type: String
}
type: String,
},
}
......@@ -3,6 +3,6 @@ import { ApiProtocol } from '../type'
export const GetProviderProtocol: ApiProtocol = {
service: {
type: String,
required: true
}
required: true,
},
}
import { ApiProtocol } from '../type'
export const LoadSubPackageProtocol: ApiProtocol = {
root: {
type: String,
required: true,
validator(value) {
const subPackages = __uniConfig.subPackages
if (!Array.isArray(subPackages) || subPackages.length === 0) {
return 'no subPackages'
}
if (!subPackages.find(subPackage => subPackage.root === value)) {
return 'root `' + value + '` is not found'
}
}
}
}
import { ApiProtocol } from '../type'
export const LoadSubPackageProtocol: ApiProtocol = {
root: {
type: String,
required: true,
validator(value) {
const subPackages = __uniConfig.subPackages
if (!Array.isArray(subPackages) || subPackages.length === 0) {
return 'no subPackages'
}
if (!subPackages.find((subPackage) => subPackage.root === value)) {
return 'root `' + value + '` is not found'
}
},
},
}
import { ApiProtocol, ProtocolOptions } from '../type'
export const GetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true
}
}
export const GetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
required: true
}
]
export const SetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true
},
data: {
required: true
}
}
export const SetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
required: true
},
{
name: 'data',
required: true
}
]
export const RemoveStorageProtocol = GetStorageProtocol
export const RemoveStorageSyncProtocol = GetStorageSyncProtocol
import { ApiProtocol, ProtocolOptions } from '../type'
export const GetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true,
},
}
export const GetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
required: true,
},
]
export const SetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true,
},
data: {
required: true,
},
}
export const SetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
required: true,
},
{
name: 'data',
required: true,
},
]
export const RemoveStorageProtocol = GetStorageProtocol
export const RemoveStorageSyncProtocol = GetStorageSyncProtocol
......@@ -3,13 +3,13 @@ import { ApiProtocol } from '../type'
export const LoadFontFaceProtocol: ApiProtocol = {
family: {
type: String,
required: true
required: true,
},
source: {
type: String,
required: true
required: true,
},
desc: {
type: Object
}
type: Object,
},
}
import { ApiOptions, ApiProtocol } from '../type'
const FRONT_COLORS = ['#ffffff', '#000000']
export const SetNavigationBarColorOptions: ApiOptions = {
formatArgs: {
animation(animation = {}, params) {
params.animation = {
duration: animation.duration || 0,
timingFunc: animation.timingFunc || 'linear'
}
}
}
}
export const SetNavigationBarColorProtocol: ApiProtocol = {
frontColor: {
type: String,
required: true,
validator(frontColor) {
if (FRONT_COLORS.indexOf(frontColor) === -1) {
return `invalid frontColor "${frontColor}"`
}
}
},
backgroundColor: {
type: String,
required: true
},
animation: {
type: Object,
default() {
return {
duration: 0,
timingFunc: 'linear'
}
}
}
}
export const SetNavigationBarTitleProtocol: ApiProtocol = {
title: {
type: String,
required: true
}
}
import { ApiOptions, ApiProtocol } from '../type'
const FRONT_COLORS = ['#ffffff', '#000000']
export const SetNavigationBarColorOptions: ApiOptions = {
formatArgs: {
animation(animation = {}, params) {
params.animation = {
duration: animation.duration || 0,
timingFunc: animation.timingFunc || 'linear',
}
},
},
}
export const SetNavigationBarColorProtocol: ApiProtocol = {
frontColor: {
type: String,
required: true,
validator(frontColor) {
if (FRONT_COLORS.indexOf(frontColor) === -1) {
return `invalid frontColor "${frontColor}"`
}
},
},
backgroundColor: {
type: String,
required: true,
},
animation: {
type: Object,
default() {
return {
duration: 0,
timingFunc: 'linear',
}
},
},
}
export const SetNavigationBarTitleProtocol: ApiProtocol = {
title: {
type: String,
required: true,
},
}
import { ApiProtocol } from '../type'
export const PageScrollToProtocol: ApiProtocol = {
scrollTop: {
type: Number,
required: true
},
duration: {
type: Number,
default: 300
}
}
import { ApiProtocol } from '../type'
export const PageScrollToProtocol: ApiProtocol = {
scrollTop: {
type: Number,
required: true,
},
duration: {
type: Number,
default: 300,
},
}
......@@ -5,12 +5,12 @@ import { API_TYPE_SYNC, createApi } from '../../helpers/api'
import {
Base64ToArrayBufferProtocol,
ArrayBufferToBase64Protocol
ArrayBufferToBase64Protocol,
} from '../../protocols/base/base64'
export const base64ToArrayBuffer = createApi<typeof uni.base64ToArrayBuffer>(
{ type: API_TYPE_SYNC, name: 'base64ToArrayBuffer' },
base64 => {
(base64) => {
return decode(base64) as ArrayBuffer
},
Base64ToArrayBufferProtocol
......@@ -18,7 +18,7 @@ export const base64ToArrayBuffer = createApi<typeof uni.base64ToArrayBuffer>(
export const arrayBufferToBase64 = createApi<typeof uni.arrayBufferToBase64>(
{ type: API_TYPE_SYNC, name: 'arrayBufferToBase64' },
arrayBuffer => {
(arrayBuffer) => {
return encode(arrayBuffer) as string
},
ArrayBufferToBase64Protocol
......
......@@ -5,21 +5,21 @@ import {
scopedInterceptors,
globalInterceptors,
Interceptors,
HOOKS
HOOKS,
} from '../../helpers/interceptor'
import { API_TYPE_SYNC, createApi } from '../../helpers/api'
import {
AddInterceptorProtocol,
RemoveInterceptorProtocol
RemoveInterceptorProtocol,
} from '../../protocols/base/interceptor'
function mergeInterceptorHook(
interceptors: Interceptors,
interceptor: Interceptor
) {
Object.keys(interceptor).forEach(hook => {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook as HOOKS])) {
interceptors[hook as HOOKS] = mergeHook(
interceptors[hook as HOOKS],
......@@ -36,11 +36,12 @@ function removeInterceptorHook(
if (!interceptors || !interceptor) {
return
}
Object.keys(interceptor).forEach(hook => {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook as HOOKS])) {
removeHook(interceptors[hook as HOOKS], interceptor[
hook as HOOKS
] as Function)
removeHook(
interceptors[hook as HOOKS],
interceptor[hook as HOOKS] as Function
)
}
})
}
......@@ -53,8 +54,8 @@ function mergeHook(
? parentVal
? parentVal.concat(childVal)
: isArray(childVal)
? childVal
: [childVal]
? childVal
: [childVal]
: parentVal
return res ? dedupeHooks(res) : res
}
......@@ -116,11 +117,11 @@ export const promiseInterceptor = {
return res
}
return res
.then(res => {
.then((res) => {
return res[1]
})
.catch(res => {
.catch((res) => {
return res[0]
})
}
},
}
......@@ -8,7 +8,7 @@ import { getCurrentPageVm } from '../utils'
const defaultOptions = {
thresholds: [0],
initialRatio: 0,
observeAll: false
observeAll: false,
}
interface Margins {
......@@ -74,7 +74,7 @@ class ServiceIntersectionObserver {
}
this._relativeInfo.push({
selector,
margins
margins,
})
return this
}
......@@ -103,7 +103,7 @@ class ServiceIntersectionObserver {
reqId: this._reqId,
component: this._component,
options: this._options,
relativeInfo: this._relativeInfo
relativeInfo: this._relativeInfo,
},
this._pageId
)
......@@ -113,7 +113,7 @@ class ServiceIntersectionObserver {
UniServiceJSBridge.publishHandler(
'removeIntersectionObserver',
{
reqId: this._reqId
reqId: this._reqId,
},
this._pageId
)
......
......@@ -7,7 +7,7 @@ import { initEasycom, matchEasycom, vueCompilerOptions } from '../src'
const rootDir = path.resolve(__dirname, 'example')
const dirs = [
path.resolve(__dirname, 'example/components'),
path.resolve(__dirname, 'example/uni_modules/plugin/components')
path.resolve(__dirname, 'example/uni_modules/plugin/components'),
]
const template = `<template><test/><test1/><test1/><test2/><some-other-comp/><checkbox-group/><checkbox-group/></template>`
......@@ -31,16 +31,16 @@ describe('easycom', () => {
expect(initEasycom({ dirs, rootDir })).toEqual([
{
pattern: new RegExp('^test$'),
replacement: '@/components/test/test.vue'
replacement: '@/components/test/test.vue',
},
{
pattern: new RegExp('^test1$'),
replacement: '@/components/test1/test1.vue'
replacement: '@/components/test1/test1.vue',
},
{
pattern: new RegExp('^test2$'),
replacement: '@/uni_modules/plugin/components/test2/test2.vue'
}
replacement: '@/uni_modules/plugin/components/test2/test2.vue',
},
])
expect(matchEasycom('test')).toBe('@/components/test/test.vue')
expect(matchEasycom('test1')).toBe('@/components/test1/test1.vue')
......@@ -54,8 +54,8 @@ describe('easycom', () => {
).toEqual([
{
pattern: new RegExp('^uni-(.*)'),
replacement: '@/components/uni-$1.vue'
}
replacement: '@/components/uni-$1.vue',
},
])
expect(matchEasycom('test')).toBe(false)
expect(matchEasycom('uni-test1')).toBe('@/components/uni-test1.vue')
......@@ -65,21 +65,21 @@ describe('easycom', () => {
initEasycom({
dirs,
rootDir,
custom: { '^test$': '@/components/uni-test.vue' }
custom: { '^test$': '@/components/uni-test.vue' },
})
).toEqual([
{
pattern: new RegExp('^test$'),
replacement: '@/components/uni-test.vue'
replacement: '@/components/uni-test.vue',
},
{
pattern: new RegExp('^test1$'),
replacement: '@/components/test1/test1.vue'
replacement: '@/components/test1/test1.vue',
},
{
pattern: new RegExp('^test2$'),
replacement: '@/uni_modules/plugin/components/test2/test2.vue'
}
replacement: '@/uni_modules/plugin/components/test2/test2.vue',
},
])
expect(matchEasycom('test')).toBe('@/components/uni-test.vue')
})
......@@ -87,17 +87,17 @@ describe('easycom', () => {
initEasycom({
dirs,
rootDir,
custom: { '^test$': '@/components/uni-test.vue' }
custom: { '^test$': '@/components/uni-test.vue' },
})
const { code } = compileTemplate(
Object.assign(sfcParseRes.descriptor, {
id,
compilerOptions: Object.assign(
{
bindingMetadata: sfcScriptBlock.bindings
bindingMetadata: sfcScriptBlock.bindings,
},
vueCompilerOptions
)
),
})
)
expect(code).toMatch(` // const _component_test = _resolveComponent("test")
......@@ -117,7 +117,7 @@ import _style_v_uni_checkbox_group from '@dcloudio/uni-h5/style/checkbox-group.c
initEasycom({
dirs,
rootDir,
custom: { '^test$': '@/components/uni-test.vue' }
custom: { '^test$': '@/components/uni-test.vue' },
})
const { code } = compileTemplate(
Object.assign(sfcParseResWithSetup.descriptor, {
......@@ -125,7 +125,7 @@ import _style_v_uni_checkbox_group from '@dcloudio/uni-h5/style/checkbox-group.c
compilerOptions: Object.assign(
{ bindingMetadata: sfcScriptBlockWithSetup.bindings },
vueCompilerOptions
)
),
})
)
expect(code)
......
......@@ -24,7 +24,7 @@
"dependencies": {
"@vue/compiler-core": "^3.0.4",
"debug": "^4.3.1",
"strip-json-comments": "^3.1.1",
"jsonc-parser": "^3.0.0",
"xregexp": "3.1.0"
},
"peerDependencies": {
......
import {
ExpressionNode,
SimpleExpressionNode,
TransformContext
TransformContext,
} from '@vue/compiler-core'
interface ImportItem {
......@@ -17,7 +17,7 @@ export function addAutoImport(
const importContent = (importItem.exp as SimpleExpressionNode).content
const importsArray = Array.from(context.imports)
const existing = importsArray.find(
i =>
(i) =>
i.path === importPath &&
(i.exp as SimpleExpressionNode).content === importContent
)
......
......@@ -7,7 +7,7 @@ import {
ElementNode,
ElementTypes,
ComponentNode,
TemplateChildNode
TemplateChildNode,
} from '@vue/compiler-core'
interface EasycomOption {
......@@ -26,7 +26,7 @@ interface EasycomCustom {
export * from './autoImport'
export const debugEasycom = debug('easycom')
export const debugEasycom = debug('uni:easycom')
const easycoms: EasycomMatcher[] = []
......@@ -62,7 +62,7 @@ export function initEasycom({
dirs,
rootDir,
custom,
extensions = ['.vue']
extensions = ['.vue'],
}: EasycomOption) {
debugEasycom(dirs, rootDir, custom, extensions)
clearEasycom()
......@@ -73,10 +73,10 @@ export function initEasycom({
if (custom) {
Object.assign(easycomsObj, custom)
}
Object.keys(easycomsObj).forEach(name => {
Object.keys(easycomsObj).forEach((name) => {
easycoms.push({
pattern: new RegExp(name),
replacement: easycomsObj[name]
replacement: easycomsObj[name],
})
})
debugEasycom(easycoms)
......@@ -95,7 +95,7 @@ export function matchEasycom(tag: string) {
if (easycomsInvalidCache.has(tag)) {
return false
}
const matcher = easycoms.find(matcher => matcher.pattern.test(tag))
const matcher = easycoms.find((matcher) => matcher.pattern.test(tag))
if (!matcher) {
easycomsInvalidCache.add(tag)
return false
......@@ -120,7 +120,7 @@ function initAutoScanEasycom(
if (!fs.existsSync(dir)) {
return easycoms
}
fs.readdirSync(dir).forEach(name => {
fs.readdirSync(dir).forEach((name) => {
const folder = path.resolve(dir, name)
if (!isDir(folder)) {
return
......@@ -147,7 +147,7 @@ function initAutoScanEasycoms(
return dirs.reduce<Record<string, string>>(
(easycoms: Record<string, string>, dir: string) => {
const curEasycoms = initAutoScanEasycom(dir, rootDir, extensions)
Object.keys(curEasycoms).forEach(name => {
Object.keys(curEasycoms).forEach((name) => {
// Use the first component when name conflict
if (!easycoms[name]) {
easycoms[name] = curEasycoms[name]
......
export * from './json'
export * from './easycom/index'
export * from './vueCompilerOptions'
export * from './preprocess/index'
export * from './transforms/transformBuiltInComponent'
export * from './transforms/transformBuiltInEasycom'
export * from './transforms/transformEasycom'
import stripJsonComments from 'strip-json-comments'
// @ts-ignore
import { preprocess } from '../lib/preprocess'
import { parse } from 'jsonc-parser'
import { preJson } from './preprocess'
const jsContext = {
APP_PLUS: false,
H5: true,
MP_360: false,
MP_ALIPAY: false,
MP_BAIDU: false,
MP_QQ: false,
MP_TOUTIAO: false,
MP_WEIXIN: false,
QUICKAPP_NATIVE: false,
QUICKAPP_WEBVIEW: false,
MP: false,
APP: false,
APP_PLUS_NVUE: false,
APP_VUE: false,
APP_NVUE: false
}
export function parseJson(jsonStr: string, shouldPreprocess: boolean = false) {
return JSON.parse(
stripJsonComments(
shouldPreprocess
? preprocess(jsonStr, jsContext, { type: 'js' })
: jsonStr
)
)
export function parseJson(jsonStr: string, shouldPre: boolean = false) {
return parse(shouldPre ? preJson(jsonStr) : jsonStr)
}
export const jsContext = {
APP_PLUS: false,
H5: true,
MP_360: false,
MP_ALIPAY: false,
MP_BAIDU: false,
MP_QQ: false,
MP_TOUTIAO: false,
MP_WEIXIN: false,
QUICKAPP_NATIVE: false,
QUICKAPP_WEBVIEW: false,
MP: false,
APP: false,
APP_PLUS_NVUE: false,
APP_VUE: false,
APP_NVUE: false,
}
export const htmlContext = {
APP_PLUS: false,
H5: true,
MP_360: false,
MP_ALIPAY: false,
MP_BAIDU: false,
MP_QQ: false,
MP_TOUTIAO: false,
MP_WEIXIN: false,
QUICKAPP_NATIVE: false,
QUICKAPP_WEBVIEW: false,
MP: false,
APP: false,
APP_PLUS_NVUE: false,
APP_VUE: false,
APP_NVUE: false,
}
import { jsContext } from './context'
export * from './context'
/* eslint-disable no-restricted-globals */
const { preprocess } = require('../../lib/preprocess')
export function preJs(jsCode: string) {
return preprocess(jsCode, jsContext, { type: 'js' })
}
export function preHtml(htmlCode: string) {
return preprocess(htmlCode, jsContext, { type: 'html' })
}
export const preCss = preJs
export const preJson = preJs
......@@ -5,7 +5,7 @@ import {
NodeTransform,
ElementNode,
createSimpleExpression,
toValidAssetId
toValidAssetId,
} from '@vue/compiler-core'
import { COMPONENT_PREFIX, isBuiltInComponent } from '@dcloudio/uni-shared'
......@@ -28,7 +28,7 @@ function createComponentImportItem(oldTag: string, node: ElementNode) {
false,
node.loc,
ConstantTypes.CAN_HOIST
)
),
}
}
function createStyleImportItem(oldTag: string, node: ElementNode) {
......@@ -39,7 +39,7 @@ function createStyleImportItem(oldTag: string, node: ElementNode) {
false,
node.loc,
ConstantTypes.CAN_HOIST
)
),
}
}
......
import { NodeTransform } from '@vue/compiler-core'
import { isComponentNode } from '../easycom/index'
export const transformBuiltInEasycom: NodeTransform = node => {
export const transformBuiltInEasycom: NodeTransform = (node) => {
if (!isComponentNode(node)) {
return
}
......
......@@ -5,7 +5,7 @@ import {
createSimpleExpression,
toValidAssetId,
ComponentNode,
TransformContext
TransformContext,
} from '@vue/compiler-core'
import { COMPONENT_PREFIX } from '@dcloudio/uni-shared'
......@@ -15,7 +15,7 @@ import {
debugEasycom,
matchEasycom,
addAutoImport,
isComponentNode
isComponentNode,
} from '../easycom'
function createImportItem(path: string, node: ComponentNode) {
......@@ -27,7 +27,7 @@ function createImportItem(path: string, node: ComponentNode) {
false,
node.loc,
ConstantTypes.CAN_HOIST
)
),
}
}
......
......@@ -3,7 +3,7 @@ import { CompilerOptions } from '@vue/compiler-sfc'
import {
COMPONENT_PREFIX,
isBuiltInComponent,
isNativeTag
isNativeTag,
} from '@dcloudio/uni-shared'
import { transformBuiltInComponent } from './transforms/transformBuiltInComponent'
......@@ -42,6 +42,6 @@ export const vueCompilerOptions: VueCompilerOptions = {
nodeTransforms: [
transformBuiltInComponent,
transformBuiltInEasycom,
transformEasycom
]
transformEasycom,
],
}
......@@ -56,5 +56,5 @@ export {
Switch,
// Text,
Textarea,
View
View,
}
......@@ -5,7 +5,7 @@ try {
get() {
/* istanbul ignore next */
supportsPassive = true
}
},
}) // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive' as any, null as any, opts)
} catch (e) {}
......
// @ts-ignore
export { default as emitter } from './emitter'
// @ts-ignore
export { default as listeners } from './listeners'
// @ts-ignore
export { default as hover } from './hover'
// @ts-ignore
export { default as subscriber } from './subscriber'
// @ts-ignore
export { default as keyboard } from './keyboard'
// @ts-ignore
export { default as baseInput } from './base-input'
// @ts-ignore
export { default as interact } from './interact'
// @ts-ignore
export { default as emitter } from './emitter'
// @ts-ignore
export { default as listeners } from './listeners'
// @ts-ignore
export { default as hover } from './hover'
// @ts-ignore
export { default as subscriber } from './subscriber'
// @ts-ignore
export { default as keyboard } from './keyboard'
// @ts-ignore
export { default as baseInput } from './base-input'
// @ts-ignore
export { default as interact } from './interact'
import path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
......@@ -21,7 +23,7 @@ export default defineConfig({
minify: false,
assetsDir: '.',
rollupOptions: {
input: 'src/index.ts',
input: path.resolve(__dirname, 'src/index.ts'),
external: ['vue', '@vue/shared', '@dcloudio/uni-shared'],
preserveEntrySignatures: 'strict',
output: {
......
......@@ -11,7 +11,7 @@ export function initBridge(namespace: 'service' | 'view') {
},
emit(event: string, ...args: any[]) {
console.log(event, args)
}
},
}
return {
on,
......@@ -32,6 +32,6 @@ export function initBridge(namespace: 'service' | 'view') {
)
}
return emit(`${namespace}.${event}`, args, pageId)
}
},
}
}
......@@ -11,7 +11,7 @@ function querySelector(
function querySelectorAll(vm: ComponentPublicInstance, selector: string) {
const nodeList = vm.$el.querySelectorAll(selector)
if (nodeList) {
return [...nodeList].map(node => node.__vue__).filter(Boolean)
return [...nodeList].map((node) => node.__vue__).filter(Boolean)
}
return []
}
......
......@@ -11,13 +11,13 @@ export function getWindowOffset() {
top: top ? top + safeAreaInsets.top : 0,
bottom: bottom ? bottom + safeAreaInsets.bottom : 0,
left: left ? left + safeAreaInsets.left : 0,
right: right ? right + safeAreaInsets.right : 0
right: right ? right + safeAreaInsets.right : 0,
}
}
return {
top: 0,
bottom: 0,
left: 0,
right: 0
right: 0,
}
}
......@@ -13,7 +13,7 @@ export function initAppConfig(appConfig: AppConfig) {
Object.defineProperty(globalProperties, '$ownerInstance', {
get() {
return this.$getComponentDescriptor(this)
}
},
})
globalProperties.$handleWxsEvent = handleWxsEvent
}
......
......@@ -40,7 +40,7 @@ export function normalizeEvent(
const { top } = getWindowOffset()
detail = {
x: $event.x,
y: $event.y - top
y: $event.y - top,
}
normalizeClickEvent($event)
}
......@@ -55,13 +55,13 @@ export function normalizeEvent(
touches: normalizeTouchList(($event as any).touches),
changedTouches: normalizeTouchList(($event as any).changedTouches),
preventDefault() {},
stopPropagation() {}
stopPropagation() {},
}
if (__PLATFORM__ === 'app-plus' && currentTarget) {
const nid = currentTarget.getAttribute('_i')
;(ret as any).options = {
nid
nid,
}
// 保留原始 currentTarget 方便后续对比
;(ret as any).$origCurrentTarget = currentTarget
......@@ -78,8 +78,8 @@ function normalizeClickEvent($event: MouseEvent) {
clientX: $event.clientX,
clientY: $event.clientY,
pageX: $event.pageX,
pageY: $event.pageY
}
pageY: $event.pageY,
},
]
}
......@@ -98,7 +98,7 @@ function normalizeTarget(
id: target.id,
offsetLeft: target.offsetLeft,
offsetTop: target.offsetTop,
dataset: normalizeDataset(target.dataset)
dataset: normalizeDataset(target.dataset),
}
if (detail) {
extend(res, detail)
......@@ -120,7 +120,7 @@ function normalizeTouchList(touches: unknown) {
pageY: touch.pageY - top,
clientX: touch.clientX,
clientY: touch.clientY - top,
force: touch.force || 0
force: touch.force || 0,
})
}
return res
......
......@@ -20,20 +20,20 @@ function getWxsClsArr(
) {
const wxsClsArr: string[] = []
let checkClassList: (cls: string) => boolean = function(cls: string) {
let checkClassList: (cls: string) => boolean = function (cls: string) {
if (isAdd) {
checkClassList = function(cls) {
checkClassList = function (cls) {
return !classList.contains(cls)
}
} else {
checkClassList = function(cls) {
checkClassList = function (cls) {
return classList.contains(cls)
}
}
return checkClassList(cls)
}
clsArr.forEach(cls => {
clsArr.forEach((cls) => {
cls = cls.replace(CLASS_RE, '')
checkClassList(cls) && wxsClsArr.push(cls)
})
......@@ -44,7 +44,7 @@ function parseStyleText(cssText: string) {
const res: Record<string, string> = {}
const listDelimiter = /;(?![^(]*\))/g
const propertyDelimiter = /:(.+)/
cssText.split(listDelimiter).forEach(function(item) {
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
const tmp = item.split(propertyDelimiter)
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim())
......@@ -124,7 +124,7 @@ class ComponentDescriptor {
const wxsClsArr = getWxsClsArr(clsArr, classList, false)
if (wxsClsArr.length) {
const removeWxsClsArr: string[] = []
wxsClsArr.forEach(cls => {
wxsClsArr.forEach((cls) => {
const clsIndex = addWxsClsArr.findIndex(
(oldCls: string) => oldCls === cls
)
......@@ -165,7 +165,7 @@ class ComponentDescriptor {
UniViewJSBridge.publishHandler('onWxsInvokeCallMethod', {
cid: (this.$vm as any)._$id,
method: funcName,
args
args,
})
}
}
......@@ -231,10 +231,10 @@ export function handleWxsEvent(this: ComponentPublicInstance, $event: Event) {
$origEvent.currentTarget as HTMLElement
) as Event
;($event as any).instance = instance
$event.preventDefault = function() {
$event.preventDefault = function () {
return $origEvent.preventDefault()
}
$event.stopPropagation = function() {
$event.stopPropagation = function () {
return $origEvent.stopPropagation()
}
}
......@@ -25,13 +25,13 @@ function touchstart(evt: TouchEvent) {
startPageX = pageX
startPageY = pageY
longPressTimer = setTimeout(function() {
longPressTimer = setTimeout(function () {
const customEvent = new CustomEvent('longpress', {
bubbles: true,
cancelable: true,
// @ts-ignore
target: evt.target,
currentTarget: evt.currentTarget
currentTarget: evt.currentTarget,
})
;(customEvent as any).touches = evt.touches
;(customEvent as any).changedTouches = evt.changedTouches
......
......@@ -17,5 +17,5 @@ export default {
initSystemComponents(app)
initRouter(app)
}
},
}
......@@ -3,7 +3,7 @@ import { RouteRecordRaw } from 'vue-router'
import {
createRouter,
createWebHashHistory,
createWebHistory
createWebHistory,
} from 'vue-router'
export function initRouter(app: App) {
......@@ -21,7 +21,7 @@ export function initRouter(app: App) {
return savedPosition
}
// TODO tabBar?
}
},
})
)
}
......@@ -12,9 +12,5 @@ export * from './service/bridge'
export { getApp, getCurrentPages } from './framework'
export { default as PageComponent } from './framework/components/page/index.vue'
export {
default as AsyncErrorComponent
} from './framework/components/async-error/index.vue'
export {
default as AsyncLoadingComponent
} from './framework/components/async-loading/index.vue'
export { default as AsyncErrorComponent } from './framework/components/async-error/index.vue'
export { default as AsyncLoadingComponent } from './framework/components/async-loading/index.vue'
......@@ -9,7 +9,7 @@ function cssSupports(css: string) {
const SCHEMA_CSS = {
'css.var': cssSupports('--a:0'),
'css.env': cssSupports('top:env(a)'),
'css.constant': cssSupports('top:constant(a)')
'css.constant': cssSupports('top:constant(a)'),
}
export const canIUse = createApi<typeof uni.canIUse>(
......
......@@ -74,7 +74,7 @@ export const getSystemInfoSync = createApi<typeof uni.getSystemInfoSync>(
/\/[\d\.,]+$/,
/^\s?[\d\.,]+$/,
/\bBrowser\b/i,
/\bMobile\b/i
/\bMobile\b/i,
]
for (let i = 0; i < infos.length; i++) {
const info = infos[i]
......@@ -107,7 +107,7 @@ export const getSystemInfoSync = createApi<typeof uni.getSystemInfoSync>(
top: safeAreaInsets.top,
bottom: windowHeight - safeAreaInsets.bottom,
width: windowWidth - safeAreaInsets.left - safeAreaInsets.right,
height: windowHeight - safeAreaInsets.top - safeAreaInsets.bottom
height: windowHeight - safeAreaInsets.top - safeAreaInsets.bottom,
}
const { top: windowTop, bottom: windowBottom } = getWindowOffset()
......@@ -133,8 +133,8 @@ export const getSystemInfoSync = createApi<typeof uni.getSystemInfoSync>(
top: safeAreaInsets.top,
right: safeAreaInsets.right,
bottom: safeAreaInsets.bottom,
left: safeAreaInsets.left
}
left: safeAreaInsets.left,
},
} as UniApp.GetSystemInfoResult
}
)
import {
API_TYPE_ASYNC,
createApi,
MakePhoneCallProtocol
MakePhoneCallProtocol,
} from '@dcloudio/uni-api'
export const makePhoneCall = createApi<typeof uni.makePhoneCall>(
{ type: API_TYPE_ASYNC, name: 'makePhoneCall' },
option => {
(option) => {
window.location.href = `tel:${option.phoneNumber}`
},
MakePhoneCallProtocol
......
import {
API_TYPE_ASYNC,
createApi,
OpenDocumentProtocol
OpenDocumentProtocol,
} from '@dcloudio/uni-api'
export const openDocument = createApi<typeof uni.openDocument>(
{ type: API_TYPE_ASYNC, name: 'openDocument' },
option => {
(option) => {
window.open(option.filePath)
},
OpenDocumentProtocol
......
......@@ -24,5 +24,5 @@ export {
arrayBufferToBase64,
base64ToArrayBuffer,
createIntersectionObserver,
createSelectorQuery
createSelectorQuery,
} from '@dcloudio/uni-api'
import {
API_TYPE_ASYNC,
createApi,
GetImageInfoOptions,
GetImageInfoProtocol
} from '@dcloudio/uni-api'
function _getServiceAddress() {
return window.location.protocol + '//' + window.location.host
}
export const getImageInfo = createApi<typeof uni.getImageInfo>(
{ type: API_TYPE_ASYNC, name: 'getImageInfo', options: GetImageInfoOptions },
({ src }, callback?: Function) => {
const img = new Image()
img.onload = function() {
callback!({
errMsg: 'getImageInfo:ok',
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src
})
}
img.onerror = function() {
callback!({
errMsg: 'getImageInfo:fail'
})
}
img.src = src
},
GetImageInfoProtocol
)
import {
API_TYPE_ASYNC,
createApi,
GetImageInfoOptions,
GetImageInfoProtocol,
} from '@dcloudio/uni-api'
function _getServiceAddress() {
return window.location.protocol + '//' + window.location.host
}
export const getImageInfo = createApi<typeof uni.getImageInfo>(
{ type: API_TYPE_ASYNC, name: 'getImageInfo', options: GetImageInfoOptions },
({ src }, callback?: Function) => {
const img = new Image()
img.onload = function () {
callback!({
errMsg: 'getImageInfo:ok',
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src,
})
}
img.onerror = function () {
callback!({
errMsg: 'getImageInfo:fail',
})
}
img.src = src
},
GetImageInfoProtocol
)
......@@ -2,7 +2,7 @@ import { API_TYPE_ASYNC, createApi } from '@dcloudio/uni-api'
export const navigateTo = createApi<typeof uni.navigateTo>(
{ type: API_TYPE_ASYNC },
options => {
(options) => {
const router = getApp().$router
router.push(options.url)
}
......
......@@ -5,5 +5,5 @@ import { ServiceJSBridge } from '@dcloudio/uni-core'
export const UniServiceJSBridge = extend(ServiceJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniViewJSBridge.subscribeHandler(event, args, pageId)
}
},
})
......@@ -5,5 +5,5 @@ import { ViewJSBridge } from '@dcloudio/uni-core'
export const UniViewJSBridge = extend(ViewJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniServiceJSBridge.subscribeHandler(event, args, pageId)
}
},
})
......@@ -49,7 +49,7 @@ export default defineConfig({
minify: false,
assetsDir: '.',
rollupOptions: {
input: 'src/index.ts',
input: path.resolve(__dirname, 'src/index.ts'),
external: ['vue', 'vue-router', '@vue/shared', '@dcloudio/uni-shared'],
preserveEntrySignatures: 'strict',
plugins: [
......
......@@ -23,8 +23,8 @@ const Upx2pxProtocol = [
{
name: 'upx',
type: [Number, String],
required: true
}
required: true,
},
];
const EPS = 1e-4;
......@@ -92,7 +92,7 @@ function queue(hooks, data) {
if (res === false) {
return {
then() { },
catch() { }
catch() { },
};
}
}
......@@ -101,11 +101,11 @@ function queue(hooks, data) {
then(callback) {
return callback(data);
},
catch() { }
catch() { },
});
}
function wrapperOptions(interceptors, options = {}) {
[HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => {
[HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach((name) => {
const hooks = interceptors[name];
if (!isArray(hooks)) {
return;
......@@ -128,21 +128,21 @@ function wrapperReturnValue(method, returnValue) {
if (interceptor && isArray(interceptor.returnValue)) {
returnValueHooks.push(...interceptor.returnValue);
}
returnValueHooks.forEach(hook => {
returnValueHooks.forEach((hook) => {
returnValue = hook(returnValue) || returnValue;
});
return returnValue;
}
function getApiInterceptorHooks(method) {
const interceptor = Object.create(null);
Object.keys(globalInterceptors).forEach(hook => {
Object.keys(globalInterceptors).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice();
}
});
const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => {
Object.keys(scopedInterceptor).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
}
......@@ -155,7 +155,7 @@ function invokeApi(method, api, options, ...params) {
if (interceptor && Object.keys(interceptor).length) {
if (isArray(interceptor.invoke)) {
const res = queue(interceptor.invoke, options);
return res.then(options => {
return res.then((options) => {
return api(wrapperOptions(interceptor, options), ...params);
});
}
......@@ -170,13 +170,13 @@ const AddInterceptorProtocol = [
{
name: 'method',
type: [String, Object],
required: true
}
required: true,
},
];
const RemoveInterceptorProtocol = AddInterceptorProtocol;
function mergeInterceptorHook(interceptors, interceptor) {
Object.keys(interceptor).forEach(hook => {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook])) {
interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
}
......@@ -186,7 +186,7 @@ function removeInterceptorHook(interceptors, interceptor) {
if (!interceptors || !interceptor) {
return;
}
Object.keys(interceptor).forEach(hook => {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook])) {
removeHook(interceptors[hook], interceptor[hook]);
}
......@@ -263,10 +263,10 @@ function handlePromise(promise) {
return promise;
}
return promise
.then(data => {
.then((data) => {
return [null, data];
})
.catch(err => [err]);
.catch((err) => [err]);
}
function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
......@@ -278,7 +278,7 @@ function shouldPromise(name) {
if (!Promise.prototype.finally) {
Promise.prototype.finally = function (onfinally) {
const promise = this.constructor;
return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => {
return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
throw reason;
}));
};
......@@ -299,7 +299,7 @@ function promisify(name, api) {
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, {
success: resolve,
fail: reject
fail: reject,
}), ...params);
})));
};
......@@ -413,25 +413,25 @@ function initUni(api, protocols) {
// event-api
// provider-api?
return promisify(key, wrapper(key, my[key]));
}
},
};
return new Proxy({}, UniProxyHandlers);
}
function initGetProvider(providers) {
return function getProvider({ service, success, fail, complete }) {
return function getProvider({ service, success, fail, complete, }) {
let res;
if (providers[service]) {
res = {
errMsg: 'getProvider:ok',
service,
provider: providers[service]
provider: providers[service],
};
isFunction(success) && success(res);
}
else {
res = {
errMsg: 'getProvider:fail:服务[' + service + ']不存在'
errMsg: 'getProvider:fail:服务[' + service + ']不存在',
};
isFunction(fail) && fail(res);
}
......@@ -446,7 +446,7 @@ function addSafeAreaInsets(fromRes, toRes) {
top: safeArea.top,
left: safeArea.left,
right: fromRes.windowWidth - safeArea.right,
bottom: fromRes.windowHeight - safeArea.bottom
bottom: fromRes.windowHeight - safeArea.bottom,
};
}
}
......@@ -456,24 +456,24 @@ const getProvider = initGetProvider({
oauth: ['alipay'],
share: ['alipay'],
payment: ['alipay'],
push: ['alipay']
push: ['alipay'],
});
function setStorageSync(key, data) {
return my.setStorageSync({
key,
data
data,
});
}
function getStorageSync(key) {
const result = my.getStorageSync({
key
key,
});
// 支付宝平台会返回一个 success 值,但是目前测试的结果这个始终是 true。当没有存储数据的时候,其它平台会返回空字符串。
return result.data !== null ? result.data : '';
}
function removeStorageSync(key) {
return my.removeStorageSync({
key
key,
});
}
function startGyroscope(args) {
......@@ -482,11 +482,11 @@ function startGyroscope(args) {
}
args.success &&
args.success({
errMsg: 'startGyroscope:ok'
errMsg: 'startGyroscope:ok',
});
args.complete &&
args.complete({
errMsg: 'startGyroscope:ok'
errMsg: 'startGyroscope:ok',
});
}
function createExecCallback(execCallback) {
......@@ -609,16 +609,16 @@ const request = {
fromArgs.header = {};
}
const headers = {
'content-type': 'application/json'
'content-type': 'application/json',
};
Object.keys(fromArgs.header).forEach(key => {
Object.keys(fromArgs.header).forEach((key) => {
headers[key.toLocaleLowerCase()] = fromArgs.header[key];
});
return {
header() {
return {
name: 'headers',
value: headers
value: headers,
};
},
data(data) {
......@@ -629,32 +629,32 @@ const request = {
isPlainObject(data)) {
return {
name: 'data',
value: JSON.stringify(data)
value: JSON.stringify(data),
};
}
return {
name: 'data',
value: data
value: data,
};
},
method: 'method',
responseType: false
responseType: false,
};
},
returnValue: {
status: 'statusCode',
headers: 'header'
}
headers: 'header',
},
};
const setNavigationBarColor = {
name: 'setNavigationBar',
args: {
frontColor: false,
animation: false
}
animation: false,
},
};
const setNavigationBarTitle = {
name: 'setNavigationBar'
name: 'setNavigationBar',
};
function showModal({ showCancel = true } = {}) {
if (showCancel) {
......@@ -664,24 +664,24 @@ function showModal({ showCancel = true } = {}) {
cancelColor: false,
confirmColor: false,
cancelText: 'cancelButtonText',
confirmText: 'confirmButtonText'
confirmText: 'confirmButtonText',
},
returnValue(fromRes, toRes) {
toRes.confirm = fromRes.confirm;
toRes.cancel = !fromRes.confirm;
}
},
};
}
return {
name: 'alert',
args: {
confirmColor: false,
confirmText: 'buttonText'
confirmText: 'buttonText',
},
returnValue(fromRes, toRes) {
toRes.confirm = true;
toRes.cancel = false;
}
},
};
}
function showToast({ icon = 'success' } = {}) {
......@@ -690,50 +690,49 @@ function showToast({ icon = 'success' } = {}) {
icon: 'type',
duration: false,
image: false,
mask: false
mask: false,
};
if (icon === 'loading') {
return {
name: 'showLoading',
args
args,
};
}
return {
name: 'showToast',
args
args,
};
}
const showActionSheet = {
name: 'showActionSheet',
args: {
itemList: 'items',
itemColor: false
itemColor: false,
},
returnValue: {
index: 'tapIndex'
}
index: 'tapIndex',
},
};
const showLoading = {
args: {
title: 'content',
mask: false
}
mask: false,
},
};
const uploadFile = {
args: {
name: 'fileName'
}
// 从测试结果看,是有返回对象的,文档上没有说明。
name: 'fileName',
},
};
const downloadFile = {
returnValue: {
apFilePath: 'tempFilePath'
}
apFilePath: 'tempFilePath',
},
};
const getFileInfo = {
args: {
filePath: 'apFilePath'
}
filePath: 'apFilePath',
},
};
const compressImage = {
args(fromArgs, toArgs) {
......@@ -750,25 +749,24 @@ const compressImage = {
if (apFilePaths && apFilePaths.length) {
toRes.tempFilePath = apFilePaths[0];
}
}
},
};
const chooseVideo = {
// 支付宝小程序文档中未找到(仅在getSetting处提及),但实际可用
returnValue: {
apFilePath: 'tempFilePath'
}
apFilePath: 'tempFilePath',
},
};
const connectSocket = {
args: {
method: false,
protocols: false
}
// TODO 有没有返回值还需要测试下
protocols: false,
},
};
const chooseImage = {
returnValue: {
apFilePaths: 'tempFilePaths'
}
apFilePaths: 'tempFilePaths',
},
};
const previewImage = {
args(fromArgs, toArgs) {
......@@ -785,93 +783,93 @@ const previewImage = {
}
return {
indicator: false,
loop: false
loop: false,
};
}
},
};
const saveFile = {
args: {
tempFilePath: 'apFilePath'
tempFilePath: 'apFilePath',
},
returnValue: {
apFilePath: 'savedFilePath'
}
apFilePath: 'savedFilePath',
},
};
const getSavedFileInfo = {
args: {
filePath: 'apFilePath'
}
filePath: 'apFilePath',
},
};
const getSavedFileList = {
returnValue(fromRes, toRes) {
toRes.fileList = fromRes.fileList.map(file => {
toRes.fileList = fromRes.fileList.map((file) => {
return {
filePath: file.apFilePath,
createTime: file.createTime,
size: file.size
size: file.size,
};
});
}
},
};
const removeSavedFile = {
args: {
filePath: 'apFilePath'
}
filePath: 'apFilePath',
},
};
const getLocation = {
args: {
type: false,
altitude: false
}
altitude: false,
},
};
const openLocation = {
args: {
// TODO address 参数在阿里上是必传的
}
},
};
const getNetworkType = {
returnValue: handleNetworkInfo
returnValue: handleNetworkInfo,
};
const onNetworkStatusChange = {
returnValue: handleNetworkInfo
returnValue: handleNetworkInfo,
};
const stopAccelerometer = {
name: 'offAccelerometerChange'
name: 'offAccelerometerChange',
};
const stopCompass = {
name: 'offCompassChange'
name: 'offCompassChange',
};
const scanCode = {
name: 'scan',
args: {
onlyFromCamera: 'hideAlbum'
onlyFromCamera: 'hideAlbum',
},
returnValue: {
code: 'result'
}
code: 'result',
},
};
const setClipboardData = {
name: 'setClipboard',
args: {
data: 'text'
}
data: 'text',
},
};
const getClipboardData = {
name: 'getClipboard',
returnValue: {
text: 'data'
}
text: 'data',
},
};
const pageScrollTo = {
args: {
duration: false
}
duration: false,
},
};
const login = {
name: 'getAuthCode',
returnValue: {
authCode: 'code'
}
authCode: 'code',
},
};
const getUserInfo = {
name: my.canIUse('getOpenUserInfo') ? 'getOpenUserInfo' : 'getAuthUserInfo',
......@@ -892,86 +890,86 @@ const getUserInfo = {
toRes.userInfo = {
openId: '',
nickName: fromRes.nickName,
avatarUrl: fromRes.avatar
avatarUrl: fromRes.avatar,
};
}
}
},
};
const requestPayment = {
name: 'tradePay',
args: {
orderInfo: 'tradeNO'
}
orderInfo: 'tradeNO',
},
};
const getBLEDeviceServices = {
returnValue(fromRes, toRes) {
toRes.services = fromRes.services.map(item => {
toRes.services = fromRes.services.map((item) => {
return {
uuid: item.serviceId,
isPrimary: item.isPrimary
isPrimary: item.isPrimary,
};
});
}
},
};
const createBLEConnection = {
name: 'connectBLEDevice',
args: {
timeout: false
}
timeout: false,
},
};
const closeBLEConnection = {
name: 'disconnectBLEDevice'
name: 'disconnectBLEDevice',
};
const onBLEConnectionStateChange = {
name: 'onBLEConnectionStateChanged'
name: 'onBLEConnectionStateChanged',
};
const makePhoneCall = {
args: {
phoneNumber: 'number'
}
phoneNumber: 'number',
},
};
const stopGyroscope = {
name: 'offGyroscopeChange'
name: 'offGyroscopeChange',
};
const getSystemInfo = {
returnValue: handleSystemInfo
returnValue: handleSystemInfo,
};
const getSystemInfoSync = {
returnValue: handleSystemInfo
returnValue: handleSystemInfo,
};
// 文档没提到,但是实测可用。
const canvasToTempFilePath = {
returnValue(fromRes, toRes) {
// 真机的情况下会有 tempFilePath 这个值,因此需要主动修改。
toRes.tempFilePath = fromRes.apFilePath;
}
},
};
const setScreenBrightness = {
args: {
value: 'brightness'
}
value: 'brightness',
},
};
const getScreenBrightness = {
returnValue: {
brightness: 'value'
}
brightness: 'value',
},
};
const showShareMenu = {
name: 'showSharePanel'
name: 'showSharePanel',
};
const hideHomeButton = {
name: 'hideBackHome'
name: 'hideBackHome',
};
const saveImageToPhotosAlbum = {
name: 'saveImage',
args: {
filePath: 'url'
}
filePath: 'url',
},
};
const saveVideoToPhotosAlbum = {
args: {
filePath: 'src'
}
filePath: 'src',
},
};
const chooseAddress = {
name: 'getAddress',
......@@ -984,7 +982,7 @@ const chooseAddress = {
toRes.detailInfo = info.address;
toRes.telNumber = info.mobilePhone;
toRes.errMsg = toRes.errMsg + ' ' + fromRes.resultStatus;
}
},
};
var protocols = /*#__PURE__*/Object.freeze({
......
......@@ -50,7 +50,7 @@ const MP_METHODS = [
'createSelectorQuery',
'createIntersectionObserver',
'selectAllComponents',
'selectComponent'
'selectComponent',
];
function createEmitFn(oldEmit, ctx) {
return function emit(event, ...args) {
......@@ -85,7 +85,7 @@ function initBaseInstance(instance, options) {
Object.defineProperty(instance, 'slots', {
get() {
return this.$scope && this.$scope.props.$slots;
}
},
});
}
// $emit
......@@ -94,7 +94,7 @@ function initBaseInstance(instance, options) {
function initComponentInstance(instance, options) {
initBaseInstance(instance, options);
const ctx = instance.ctx;
MP_METHODS.forEach(method => {
MP_METHODS.forEach((method) => {
ctx[method] = function (...args) {
const mpInstance = ctx.$scope;
if (mpInstance && mpInstance[method]) {
......@@ -115,7 +115,7 @@ function initComponentInstance(instance, options) {
}
function initMocks(instance, mpInstance, mocks) {
const ctx = instance.ctx;
mocks.forEach(mock => {
mocks.forEach((mock) => {
if (hasOwn(mpInstance, mock)) {
ctx[mock] = mpInstance[mock];
}
......@@ -134,12 +134,11 @@ const PAGE_HOOKS = [
'onReachBottom',
'onPullDownRefresh',
// 'onShareTimeline', // 右上角菜单,开发者手动注册
'onAddToFavorites'
// 'onShareAppMessage' // 右上角菜单,开发者手动注册
'onAddToFavorites',
];
function findHooks(vueOptions, hooks = new Set()) {
if (vueOptions) {
Object.keys(vueOptions).forEach(name => {
Object.keys(vueOptions).forEach((name) => {
if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) {
hooks.add(name);
}
......@@ -147,7 +146,7 @@ function findHooks(vueOptions, hooks = new Set()) {
if (__VUE_OPTIONS_API__) {
const { extends: extendsOptions, mixins } = vueOptions;
if (mixins) {
mixins.forEach(mixin => findHooks(mixin, hooks));
mixins.forEach((mixin) => findHooks(mixin, hooks));
}
if (extendsOptions) {
findHooks(extendsOptions, hooks);
......@@ -165,10 +164,10 @@ function initHook(mpOptions, hook, excludes) {
}
const EXCLUDE_HOOKS = ['onReady'];
function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) {
hooks.forEach(hook => initHook(mpOptions, hook, excludes));
hooks.forEach((hook) => initHook(mpOptions, hook, excludes));
}
function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) {
findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes));
findHooks(vueOptions).forEach((hook) => initHook(mpOptions, hook, excludes));
}
const HOOKS = [
......@@ -177,7 +176,7 @@ const HOOKS = [
'onError',
'onThemeChange',
'onPageNotFound',
'onUnhandledRejection'
'onUnhandledRejection',
];
function parseApp(instance, parseAppOptions) {
const internalInstance = instance.$;
......@@ -193,11 +192,11 @@ function parseApp(instance, parseAppOptions) {
initBaseInstance(internalInstance, {
mpType: 'app',
mpInstance: this,
slots: []
slots: [],
});
ctx.globalData = this.globalData;
instance.$callHook('onLaunch', options);
}
},
};
const vueOptions = instance.$.type;
initHooks(appOptions, HOOKS);
......@@ -221,7 +220,7 @@ const encode = encodeURIComponent;
function stringifyQuery(obj, encodeStr = encode) {
const res = obj
? Object.keys(obj)
.map(key => {
.map((key) => {
let val = obj[key];
if (typeof val === undefined || val === null) {
val = '';
......@@ -231,7 +230,7 @@ function stringifyQuery(obj, encodeStr = encode) {
}
return encodeStr(key) + '=' + encodeStr(val);
})
.filter(x => x.length > 0)
.filter((x) => x.length > 0)
.join('&')
: null;
return res ? `?${res}` : '';
......@@ -294,7 +293,7 @@ function initDefaultProps(isBehavior = false) {
if (!isBehavior) {
properties.vueId = {
type: String,
value: ''
value: '',
};
// 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
properties.vueSlots = {
......@@ -306,9 +305,9 @@ function initDefaultProps(isBehavior = false) {
$slots[slotName] = true;
});
this.setData({
$slots
$slots,
});
}
},
};
}
return properties;
......@@ -321,14 +320,14 @@ function createProperty(key, prop) {
function initProps(mpComponentOptions, rawProps, isBehavior = false) {
const properties = initDefaultProps(isBehavior);
if (isArray(rawProps)) {
rawProps.forEach(key => {
rawProps.forEach((key) => {
properties[key] = createProperty(key, {
type: null
type: null,
});
});
}
else if (isPlainObject(rawProps)) {
Object.keys(rawProps).forEach(key => {
Object.keys(rawProps).forEach((key) => {
const opts = rawProps[key];
if (isPlainObject(opts)) {
// title:{type:String,default:''}
......@@ -340,14 +339,14 @@ function initProps(mpComponentOptions, rawProps, isBehavior = false) {
opts.type = parsePropType(key, type);
properties[key] = createProperty(key, {
type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
value
value,
});
}
else {
// content:String
const type = parsePropType(key, opts);
properties[key] = createProperty(key, {
type: PROP_TYPES.indexOf(type) !== -1 ? type : null
type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
});
}
});
......@@ -391,7 +390,7 @@ function initBehaviors(vueOptions, initBehavior) {
}
const behaviors = [];
if (isArray(vueBehaviors)) {
vueBehaviors.forEach(behavior => {
vueBehaviors.forEach((behavior) => {
behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`));
if (behavior === 'uni://form-field') {
if (isArray(vueProps)) {
......@@ -401,11 +400,11 @@ function initBehaviors(vueOptions, initBehavior) {
else {
vueProps.name = {
type: String,
default: ''
default: '',
};
vueProps.value = {
type: [String, Number, Boolean, Array, Object, Date],
default: ''
default: '',
};
}
}
......@@ -417,7 +416,7 @@ function initBehaviors(vueOptions, initBehavior) {
behaviors.push(initBehavior(behavior));
}
if (isArray(vueMixins)) {
vueMixins.forEach(vueMixin => {
vueMixins.forEach((vueMixin) => {
if (vueMixin.props) {
const behavior = {};
initProps(behavior, vueMixin.props, true);
......@@ -442,7 +441,7 @@ function getValue(obj, path) {
}
function getExtraValue(instance, dataPathsArray) {
let context = instance;
dataPathsArray.forEach(dataPathArray => {
dataPathsArray.forEach((dataPathArray) => {
const dataPath = dataPathArray[0];
const value = dataPathArray[2];
if (dataPath || typeof value !== 'undefined') {
......@@ -472,12 +471,12 @@ function getExtraValue(instance, dataPathsArray) {
}
else {
if (isArray(vFor)) {
context = vFor.find(vForItem => {
context = vFor.find((vForItem) => {
return getValue(vForItem, propPath) === value;
});
}
else if (isPlainObject(vFor)) {
context = Object.keys(vFor).find(vForKey => {
context = Object.keys(vFor).find((vForKey) => {
return getValue(vFor[vForKey], propPath) === value;
});
}
......@@ -567,7 +566,7 @@ function processEventArgs(instance, event, args = [], extra = [], isCustom, meth
}
const extraObj = processEventExtra(instance, extra, event);
const ret = [];
args.forEach(arg => {
args.forEach((arg) => {
if (arg === '$event') {
if (methodName === '__set_model' && !isCustom) {
// input v-model value
......@@ -719,7 +718,7 @@ function onAliGetAuthorize(method, $event) {
$event.type = 'getphonenumber';
$event.detail.errMsg = 'getPhoneNumber:fail';
this[method]($event);
}
},
});
}
function parse(appOptions) {
......@@ -815,11 +814,11 @@ function customize(str) {
}
function initBehavior({ properties }) {
const props = {};
Object.keys(properties).forEach(key => {
Object.keys(properties).forEach((key) => {
props[key] = properties[key].value;
});
return {
props
props,
};
}
function initRelation(mpInstance, detail) {
......@@ -859,10 +858,10 @@ function initChildVues(mpInstance) {
}
const childVues = mpInstance._$childVues;
if (childVues) {
childVues.forEach(relationOptions => {
childVues.forEach((relationOptions) => {
// 父子关系
handleLink.call(mpInstance, {
detail: relationOptions
detail: relationOptions,
});
const { mpInstance: childMPInstance, createComponent } = relationOptions;
childMPInstance.$vm = createComponent(relationOptions.parent);
......@@ -904,14 +903,14 @@ function triggerEvent(type, detail) {
const eventOpts = this.props['data-event-opts'];
const target = {
dataset: {
eventOpts
}
eventOpts,
},
};
handler({
type: customize(type),
target,
currentTarget: target,
detail
detail,
});
}
const IGNORES = ['$slots', '$scopedSlots'];
......@@ -922,7 +921,7 @@ function createObserver(isDidUpdate = false) {
if (equal(prevProps, nextProps)) {
return;
}
Object.keys(prevProps).forEach(name => {
Object.keys(prevProps).forEach((name) => {
if (IGNORES.indexOf(name) === -1) {
const prevValue = prevProps[name];
const nextValue = nextProps[name];
......@@ -939,7 +938,7 @@ const handleLink$1 = (function () {
if (isComponent2) {
return function handleLink$1(detail) {
return handleLink.call(this, {
detail
detail,
});
};
}
......@@ -947,7 +946,7 @@ const handleLink$1 = (function () {
if (this.$vm && this.$vm.$.isMounted) {
// 父已初始化
return handleLink.call(this, {
detail
detail,
});
}
(this._$childVues || (this._$childVues = [])).unshift(detail);
......@@ -956,7 +955,7 @@ const handleLink$1 = (function () {
function createVueComponent(mpType, mpInstance, vueOptions, parent) {
return $createComponent({
type: vueOptions,
props: mpInstance.props
props: mpInstance.props,
}, {
mpType,
mpInstance,
......@@ -964,7 +963,7 @@ function createVueComponent(mpType, mpInstance, vueOptions, parent) {
onBeforeSetup(instance, options) {
initMocks(instance, mpInstance, mocks);
initComponentInstance(instance, options);
}
},
});
}
......@@ -974,7 +973,7 @@ function createPage(vueOptions) {
onLoad(query) {
this.options = query;
this.$page = {
fullPath: '/' + this.route + stringifyQuery(query)
fullPath: '/' + this.route + stringifyQuery(query),
};
// 初始化 vue 实例
this.$vm = createVueComponent('page', this, vueOptions);
......@@ -996,11 +995,11 @@ function createPage(vueOptions) {
// 支付宝小程序有些页面事件只能放在events下
onBack() {
this.$vm.$callHook('onBackPress');
}
},
},
__r: handleRef,
__e: handleEvent,
__l: handleLink$1
__l: handleLink$1,
};
if (__VUE_OPTIONS_API__) {
pageOptions.data = initData(vueOptions);
......@@ -1013,14 +1012,14 @@ function createPage(vueOptions) {
function initComponentProps(rawProps) {
const propertiesOptions = {
properties: {}
properties: {},
};
initProps(propertiesOptions, rawProps, false);
const properties = propertiesOptions.properties;
const props = {
onVueInit: function () { }
onVueInit: function () { },
};
Object.keys(properties).forEach(key => {
Object.keys(properties).forEach((key) => {
if (key !== 'vueSlots') {
props[key] = properties[key].value;
}
......@@ -1036,7 +1035,7 @@ function initVm(mpInstance, createComponent) {
const relationOptions = {
vuePid: mpInstance._$vuePid,
mpInstance,
createComponent
createComponent,
};
if (isComponent2) {
// 处理父子关系
......@@ -1086,8 +1085,8 @@ function createComponent(vueOptions) {
__r: handleRef,
__e: handleEvent,
__l: handleLink$1,
triggerEvent
}
triggerEvent,
},
};
if (__VUE_OPTIONS_API__) {
mpComponentOptions.data = initData(vueOptions);
......
......@@ -6,19 +6,19 @@ export const getProvider = initGetProvider({
oauth: ['alipay'],
share: ['alipay'],
payment: ['alipay'],
push: ['alipay']
push: ['alipay'],
})
export function setStorageSync(key: string, data: any) {
return my.setStorageSync({
key,
data
data,
})
}
export function getStorageSync(key: string) {
const result = my.getStorageSync({
key
key,
})
// 支付宝平台会返回一个 success 值,但是目前测试的结果这个始终是 true。当没有存储数据的时候,其它平台会返回空字符串。
return result.data !== null ? result.data : ''
......@@ -26,7 +26,7 @@ export function getStorageSync(key: string) {
export function removeStorageSync(key: string) {
return my.removeStorageSync({
key
key,
})
}
......@@ -36,11 +36,11 @@ export function startGyroscope(args: UniApp.StartGyroscopeOptions) {
}
args.success &&
args.success({
errMsg: 'startGyroscope:ok'
errMsg: 'startGyroscope:ok',
})
args.complete &&
args.complete({
errMsg: 'startGyroscope:ok'
errMsg: 'startGyroscope:ok',
})
}
......@@ -87,7 +87,7 @@ export function createSelectorQuery() {
}
if (!(query as any).fields) {
;(query as any).fields = function(
;(query as any).fields = function (
{ rect, size, scrollOffset }: UniApp.NodeField,
callback: Function
) {
......@@ -103,7 +103,7 @@ export function createSelectorQuery() {
}
if (!(query as any).in) {
;(query as any).in = function() {
;(query as any).in = function () {
return this
}
}
......
......@@ -6,7 +6,7 @@ import {
handleEvent,
$destroyComponent,
initVueIds,
initWxsCallMethods
initWxsCallMethods,
} from '@dcloudio/uni-mp-core'
import {
initBehavior,
......@@ -20,7 +20,7 @@ import {
initChildVues,
createVueComponent,
RelationOptions,
createObserver
createObserver,
} from './util'
declare function Component<P, D, M extends tinyapp.IComponentMethods>(
......@@ -29,14 +29,14 @@ declare function Component<P, D, M extends tinyapp.IComponentMethods>(
function initComponentProps(rawProps: Record<string, any>) {
const propertiesOptions = {
properties: {}
properties: {},
}
initProps(propertiesOptions, rawProps, false)
const properties = propertiesOptions.properties as Record<string, any>
const props: Record<string, any> = {
onVueInit: function() {}
onVueInit: function () {},
}
Object.keys(properties).forEach(key => {
Object.keys(properties).forEach((key) => {
if (key !== 'vueSlots') {
props[key] = properties[key].value
}
......@@ -57,7 +57,7 @@ function initVm(
const relationOptions: RelationOptions = {
vuePid: mpInstance._$vuePid,
mpInstance,
createComponent
createComponent,
}
if (isComponent2) {
// 处理父子关系
......@@ -106,8 +106,8 @@ export function createComponent(vueOptions: ComponentOptions) {
__r: handleRef,
__e: handleEvent,
__l: handleLink,
triggerEvent
}
triggerEvent,
},
}
if (__VUE_OPTIONS_API__) {
mpComponentOptions.data = initData(vueOptions)
......
......@@ -35,7 +35,7 @@ function onAliGetAuthorize(
$event.type = 'getphonenumber'
$event.detail.errMsg = 'getPhoneNumber:fail'
;(this as any)[method]($event)
}
},
})
}
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册