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