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

feat(h5): api

上级 1c035f7e
import { ProtocolOptions } from '../protocols/type'
import { ApiOptions, ApiProtocol, ProtocolOptions } from '../protocols/type'
export function createApi<T extends Function>(
fn: T,
validate?: ProtocolOptions | ProtocolOptions[]
protocol?: ApiProtocol | ProtocolOptions[],
options?: ApiOptions
) {
if (__DEV__ && validate) {
if (__DEV__ && protocol) {
}
if (options) {
console.log(options)
}
return fn
}
import { isArray } from '@vue/shared'
export const CHOOSE_SIZE_TYPES = ['original', 'compressed']
export const CHOOSE_SOURCE_TYPES = ['album', 'camera']
export const HTTP_METHODS = {
OPTIONS: 'OPTIONS',
GET: 'GET',
HEAD: 'HEAD',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
TRACE: 'TRACE',
CONNECT: 'CONNECT'
}
export function normalizeStrArray(strArr: string[], optionalVal: string[]) {
if (
!isArray(strArr) ||
strArr.length === 0 ||
strArr.find(val => optionalVal.indexOf(val) === -1)
) {
return optionalVal
}
return strArr
}
......@@ -16,6 +16,10 @@ export * from './protocols/location/chooseLocation'
export * from './protocols/location/getLocation'
export * from './protocols/location/openLocation'
export * from './protocols/media/chooseImage'
export * from './protocols/media/chooseVideo'
export * from './protocols/media/getImageInfo'
// helpers
export { createApi } from './helpers/api'
export { isSyncApi, isContextApi, promisify } from './helpers/promise'
const SIZE_TYPES = ['original', 'compressed']
const SOURCE_TYPES = ['album', 'camera']
export const chooseImage = {
count: {
type: Number,
required: false,
default: 9,
validator(count, params) {
if (count <= 0) {
params.count = 9
}
}
},
sizeType: {
type: [Array, String],
required: false,
default: SIZE_TYPES,
validator(sizeType, params) {
// 非必传的参数,不符合预期时处理为默认值。
const length = sizeType.length
if (!length) {
params.sizeType = SIZE_TYPES
} else if (typeof sizeType === 'string') {
if (!~SIZE_TYPES.indexOf(sizeType)) {
params.sizeType = SIZE_TYPES
}
} else {
for (let i = 0; i < length; i++) {
if (
typeof sizeType[i] !== 'string' ||
!~SIZE_TYPES.indexOf(sizeType[i])
) {
params.sizeType = SIZE_TYPES
break
}
}
}
}
},
sourceType: {
type: Array,
required: false,
default: SOURCE_TYPES,
validator(sourceType, params) {
const length = sourceType.length
if (!length) {
params.sourceType = SOURCE_TYPES
} else {
for (let i = 0; i < length; i++) {
if (
typeof sourceType[i] !== 'string' ||
!~SOURCE_TYPES.indexOf(sourceType[i])
) {
params.sourceType = SOURCE_TYPES
break
}
}
}
}
}
}
const SOURCE_TYPES = ['album', 'camera']
export const chooseVideo = {
sourceType: {
type: Array,
required: false,
default: SOURCE_TYPES,
validator(sourceType, params) {
const length = sourceType.length
if (!length) {
params.sourceType = SOURCE_TYPES
} else {
for (let i = 0; i < length; i++) {
if (
typeof sourceType[i] !== 'string' ||
!~SOURCE_TYPES.indexOf(sourceType[i])
) {
params.sourceType = SOURCE_TYPES
break
}
}
}
}
}
}
import { ApiOptions, ApiProtocol } from '../type'
import {
CHOOSE_SIZE_TYPES,
CHOOSE_SOURCE_TYPES,
normalizeStrArray
} from '../../helpers/protocol'
export const ChooseImageOptions: ApiOptions = {
formatArgs: {
count(value, params) {
if (value <= 0) {
params.count = 9
}
},
sizeType(sizeType, params) {
params.sizeType = normalizeStrArray(sizeType, CHOOSE_SIZE_TYPES)
},
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
}
}
}
export const ChooseImageProtocol: ApiProtocol = {
count: {
type: Number,
default: 9
},
sizeType: {
type: [Array, String],
default: CHOOSE_SIZE_TYPES
},
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES
}
}
import { CHOOSE_SOURCE_TYPES, normalizeStrArray } from '../../helpers/protocol'
import { ApiOptions, ApiProtocol } from '../type'
export const ChooseVideoOptions: ApiOptions = {
formatArgs: {
sourceType(sourceType, params) {
params.sourceType = normalizeStrArray(sourceType, CHOOSE_SOURCE_TYPES)
}
}
}
export const ChooseVideoProtocol: ApiProtocol = {
sourceType: {
type: Array,
default: CHOOSE_SOURCE_TYPES
}
}
import getRealPath from 'uni-platform/helpers/get-real-path'
export const getImageInfo = {
src: {
type: String,
required: true,
validator(src, params) {
params.src = getRealPath(src)
}
}
}
import { ApiOptions, ApiProtocol } from '../type'
export const GetImageInfoOptions: ApiOptions = {
formatArgs: {
src(src, params) {
params.src = (uni as any).getRealPath(src)
}
}
}
export const GetImageInfoProtocol: ApiProtocol = {
src: {
type: String,
required: true
}
}
export const downloadFile = {
import { ApiOptions, ApiProtocol } from '../type'
export const DownloadFileOptions: ApiOptions = {
formatArgs: {
header(value, params) {
params.header = value || {}
}
}
}
export const DownloadFileProtocol: ApiProtocol = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator(value, params) {
params.header = value || {}
}
type: Object
}
}
const method = {
OPTIONS: 'OPTIONS',
GET: 'GET',
HEAD: 'HEAD',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
TRACE: 'TRACE',
CONNECT: 'CONNECT'
import { HTTP_METHODS } from '../../helpers/protocol'
import { ApiOptions, ApiProtocol } from '../type'
export const ConnectSocketOptions: ApiOptions = {
formatArgs: {
header(value, params) {
params.header = value || {}
},
method(value, params) {
value = (value || '').toUpperCase()
if (!HTTP_METHODS[value as keyof typeof HTTP_METHODS]) {
value = HTTP_METHODS.GET
}
params.method = value
},
protocols(protocols, params) {
if (typeof protocols === 'string') {
params.protocols = [protocols]
}
}
}
}
export const connectSocket = {
export const ConnectSocketProtocol: ApiProtocol = {
url: {
type: String,
required: true
},
header: {
type: Object,
validator(value, params) {
params.header = value || {}
}
type: Object
},
method: {
type: String,
validator(value, params) {
value = (value || '').toUpperCase()
params.method =
Object.values(method).indexOf(value) < 0 ? method.GET : value
}
type: String
},
protocols: {
// 微信文档虽然写的是数组,但是可以正常传递字符串
type: [Array, String],
validator(value, params) {
if (typeof value === 'string') {
value = [value]
}
params.protocols = (value || []).filter(str => typeof str === 'string')
}
type: [Array, String] // 微信文档虽然写的是数组,但是可以正常传递字符串
}
}
export const sendSocketMessage = {
......
const service = {
OAUTH: 'OAUTH',
SHARE: 'SHARE',
PAYMENT: 'PAYMENT',
PUSH: 'PUSH'
}
export const getProvider = {
service: {
type: String,
required: true,
validator(value, params) {
value = (value || '').toUpperCase()
if (value && Object.values(service).indexOf(value) < 0) {
return 'service error'
}
}
}
}
import { ApiProtocol } from '../type'
export const GetProviderProtocol: ApiProtocol = {
service: {
type: String,
required: true
}
}
export const loadSubPackage = {
import { ApiProtocol } from '../type'
export const LoadSubPackageProtocol: ApiProtocol = {
root: {
type: String,
required: true,
validator(value, params) {
validator(value) {
const subPackages = __uniConfig.subPackages
if (!Array.isArray(subPackages) || subPackages.length === 0) {
return 'no subPackages'
......
export const getStorage = {
import { ApiProtocol, ProtocolOptions } from '../type'
export const GetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true
}
}
export const getStorageSync = [
export const GetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
......@@ -13,7 +15,7 @@ export const getStorageSync = [
}
]
export const setStorage = {
export const SetStorageProtocol: ApiProtocol = {
key: {
type: String,
required: true
......@@ -23,7 +25,7 @@ export const setStorage = {
}
}
export const setStorageSync = [
export const SetStorageSyncProtocol: ProtocolOptions[] = [
{
name: 'key',
type: String,
......@@ -35,5 +37,5 @@ export const setStorageSync = [
}
]
export const removeStorage = getStorage
export const removeStorageSync = getStorageSync
export const RemoveStorageProtocol = GetStorageProtocol
export const RemoveStorageSyncProtocol = GetStorageSyncProtocol
......@@ -10,6 +10,7 @@ type ProtocolMethod<T, TConstructor = any> = T extends (...args: any) => any
: never
type ProtocolType<T> = ProtocolConstructor<T> | ProtocolConstructor<T>[]
type Validator = (value: any, params: Record<string, any>) => void
export interface ApiProtocol {
[name: string]: ProtocolOptions
}
......@@ -18,7 +19,7 @@ export interface ApiOptions {
beforeAll?: () => void
beforeSuccess?: () => void
formatArgs?: {
[name: string]: (value: any, params: Record<string, any>) => void
[name: string]: Validator
}
}
......@@ -27,5 +28,5 @@ export interface ProtocolOptions<T = any, D = T> {
type?: ProtocolType<T> | true | null
required?: boolean
default?: D | DefaultFactory<D> | null | undefined | object
validator?(value: unknown): boolean | undefined | string
validator?(value: any): boolean | undefined | string
}
export const loadFontFace = {
import { ApiProtocol } from '../type'
export const LoadFontFaceProtocol: ApiProtocol = {
family: {
type: String,
required: true
......@@ -8,19 +10,6 @@ export const loadFontFace = {
required: true
},
desc: {
type: Object,
required: false
},
success: {
type: Function,
required: false
},
fail: {
type: Function,
required: false
},
complete: {
type: Function,
required: false
type: Object
}
}
import { ApiOptions, ApiProtocol } from '../type'
const FRONT_COLORS = ['#ffffff', '#000000']
export const setNavigationBarColor = {
export const SetNavigationBarColorOptions: ApiOptions = {
formatArgs: {
animation(animation = {}, params) {
params.animation = {
duration: animation.duration || 0,
timingFunc: animation.timingFunc || 'linear'
}
}
}
}
export const SetNavigationBarColorProtocol: ApiProtocol = {
frontColor: {
type: String,
required: true,
validator(frontColor, params) {
validator(frontColor) {
if (FRONT_COLORS.indexOf(frontColor) === -1) {
return `invalid frontColor "${frontColor}"`
}
......@@ -20,16 +34,11 @@ export const setNavigationBarColor = {
duration: 0,
timingFunc: 'linear'
}
},
validator(animation = {}, params) {
params.animation = {
duration: animation.duration || 0,
timingFunc: animation.timingFunc || 'linear'
}
}
}
}
export const setNavigationBarTitle = {
export const SetNavigationBarTitleProtocol: ApiProtocol = {
title: {
type: String,
required: true
......
export const pageScrollTo = {
import { ApiProtocol } from '../type'
export const PageScrollToProtocol: ApiProtocol = {
scrollTop: {
type: Number,
required: true
},
duration: {
type: Number,
default: 300,
validator(duration, params) {
params.duration = Math.max(0, duration)
}
default: 300
}
}
import { extend } from '@vue/shared'
import { ServiceJSBridge } from '@dcloudio/uni-core'
import { createApi } from '../../helpers/api'
import { getCurrentPageVm } from '../utils'
......@@ -33,7 +35,7 @@ let reqComponentObserverId = 1
const reqComponentObserverCallbacks: Record<number, ObserveResultCallback> = {}
UniServiceJSBridge.subscribe(
ServiceJSBridge.subscribe(
'requestComponentObserver',
({ reqId, reqEnd, res }: requestComponentObserver) => {
const callback = reqComponentObserverCallbacks[reqId]
......
......@@ -171,7 +171,7 @@ class ComponentDescriptor {
}
requestAnimationFrame(callback: FrameRequestCallback) {
return global.requestAnimationFrame(callback), this
return window.requestAnimationFrame(callback), this
}
getState() {
......
......@@ -682,20 +682,6 @@ function initAppConfig$1(appConfig) {
function initService(app) {
initAppConfig$1(app._context.config);
}
var UniServiceJSBridge$1 = extend(ServiceJSBridge, {
publishHandler(event, args, pageId) {
window.UniViewJSBridge.subscribeHandler(event, args, pageId);
}
});
var UniViewJSBridge$1 = extend(ViewJSBridge, {
publishHandler(event, args, pageId) {
window.UniServiceJSBridge.subscribeHandler(event, args, pageId);
}
});
function initBridge$1() {
window.UniServiceJSBridge = UniServiceJSBridge$1;
window.UniViewJSBridge = UniViewJSBridge$1;
}
function initRouter(app) {
const history = __UNI_ROUTER_MODE__ === "history" ? createWebHistory() : createWebHashHistory();
app.use(createRouter({
......@@ -1262,9 +1248,11 @@ var decode = function(base64) {
}
return arraybuffer;
};
function createApi(fn, validate) {
if (process.env.NODE_ENV !== "production" && validate)
function createApi(fn, protocol, options) {
if (process.env.NODE_ENV !== "production" && protocol)
;
if (options) {
}
return fn;
}
const Base64ToArrayBufferProtocol = [
......@@ -1427,7 +1415,7 @@ const defaultOptions = {
};
let reqComponentObserverId = 1;
const reqComponentObserverCallbacks = {};
UniServiceJSBridge.subscribe("requestComponentObserver", ({reqId, reqEnd, res}) => {
ServiceJSBridge.subscribe("requestComponentObserver", ({reqId, reqEnd, res}) => {
const callback = reqComponentObserverCallbacks[reqId];
if (callback) {
if (reqEnd) {
......@@ -1512,6 +1500,19 @@ const OpenDocumentProtocol = {
type: String
}
};
const GetImageInfoOptions = {
formatArgs: {
src(src, params) {
params.src = uni.getRealPath(src);
}
}
};
const GetImageInfoProtocol = {
src: {
type: String,
required: true
}
};
function cssSupports(css) {
return window.CSS && window.CSS.supports && window.CSS.supports(css);
}
......@@ -1639,9 +1640,33 @@ const getSystemInfo = /* @__PURE__ */ createApi(() => {
const openDocument = /* @__PURE__ */ createApi((option) => {
window.open(option.filePath);
}, OpenDocumentProtocol);
function _getServiceAddress() {
return window.location.protocol + "//" + window.location.host;
}
const getImageInfo = /* @__PURE__ */ createApi(({src}, callbackId) => {
const {invokeCallbackHandler: invoke} = UniServiceJSBridge;
const img = new Image();
const realPath = src;
img.onload = function() {
invoke(callbackId, {
errMsg: "getImageInfo:ok",
width: img.naturalWidth,
height: img.naturalHeight,
path: realPath.indexOf("/") === 0 ? _getServiceAddress() + realPath : realPath
});
};
img.onerror = function() {
invoke(callbackId, {
errMsg: "getImageInfo:fail"
});
};
img.src = src;
}, GetImageInfoProtocol, GetImageInfoOptions);
const navigateBack = /* @__PURE__ */ createApi(() => {
});
const navigateTo = /* @__PURE__ */ createApi(() => {
const navigateTo = /* @__PURE__ */ createApi((options) => {
const router = getApp().$router;
router.push(options.url);
});
const redirectTo = /* @__PURE__ */ createApi(() => {
});
......@@ -1649,6 +1674,9 @@ const reLaunch = /* @__PURE__ */ createApi(() => {
});
const switchTab = /* @__PURE__ */ createApi(() => {
});
const getRealPath = /* @__PURE__ */ createApi((path) => {
return path;
});
var api = /* @__PURE__ */ Object.freeze({
__proto__: null,
upx2px,
......@@ -1663,11 +1691,13 @@ var api = /* @__PURE__ */ Object.freeze({
getSystemInfo,
getSystemInfoSync,
openDocument,
getImageInfo,
navigateBack,
navigateTo,
redirectTo,
reLaunch,
switchTab
switchTab,
getRealPath
});
var script$4 = {
name: "App",
......@@ -1775,7 +1805,6 @@ function initSystemComponents(app2) {
}
var index = {
install(app) {
initBridge$1();
initApp(app);
initView(app);
initService(app);
......@@ -1783,9 +1812,19 @@ var index = {
initRouter(app);
}
};
const UniViewJSBridge$1 = extend(ViewJSBridge, {
publishHandler(event, args, pageId) {
window.UniServiceJSBridge.subscribeHandler(event, args, pageId);
}
});
const uni$1 = api;
const UniServiceJSBridge$1 = extend(ServiceJSBridge, {
publishHandler(event, args, pageId) {
window.UniViewJSBridge.subscribeHandler(event, args, pageId);
}
});
let appVm;
function getApp() {
function getApp$1() {
return appVm;
}
function getCurrentPages$1() {
......@@ -2792,4 +2831,4 @@ function render$a(_ctx, _cache, $props, $setup, $data, $options) {
;
script$a.render = render$a;
script$a.__file = "packages/uni-h5/src/framework/components/async-loading/index.vue";
export {script$9 as AsyncErrorComponent, script$a as AsyncLoadingComponent, script$8 as PageComponent, addInterceptor, arrayBufferToBase64, base64ToArrayBuffer, canIUse, createIntersectionObserver$1 as createIntersectionObserver, getApp, getCurrentPages$1 as getCurrentPages, getSystemInfo, getSystemInfoSync, makePhoneCall, navigateBack, navigateTo, openDocument, index as plugin, promiseInterceptor, reLaunch, redirectTo, removeInterceptor, switchTab, uni$1 as uni, upx2px};
export {script$9 as AsyncErrorComponent, script$a as AsyncLoadingComponent, script$8 as PageComponent, UniServiceJSBridge$1 as UniServiceJSBridge, UniViewJSBridge$1 as UniViewJSBridge, addInterceptor, arrayBufferToBase64, base64ToArrayBuffer, canIUse, createIntersectionObserver$1 as createIntersectionObserver, getApp$1 as getApp, getCurrentPages$1 as getCurrentPages, getImageInfo, getRealPath, getSystemInfo, getSystemInfoSync, makePhoneCall, navigateBack, navigateTo, openDocument, index as plugin, promiseInterceptor, reLaunch, redirectTo, removeInterceptor, switchTab, uni$1 as uni, upx2px};
import { ComponentPublicInstance } from 'vue'
let appVm: ComponentPublicInstance
export function getApp() {
return appVm
}
export function getCurrentPages() {
return []
}
import { ComponentPublicInstance } from 'vue'
let appVm: ComponentPublicInstance
export function getApp() {
return appVm
}
export function getCurrentPages() {
return []
}
export * from './app'
import UniServiceJSBridge from '../../service/bridge'
import UniViewJSBridge from '../../view/bridge'
export function initBridge() {
global.UniServiceJSBridge = UniServiceJSBridge
global.UniViewJSBridge = UniViewJSBridge
}
......@@ -3,14 +3,11 @@ import { App } from 'vue'
import { initApp } from '@dcloudio/uni-vue'
import { initView, initService } from '@dcloudio/uni-core'
import { initBridge } from './bridge'
import { initRouter } from './router'
import { initSystemComponents } from './components'
export default {
install(app: App) {
initBridge()
initApp(app)
initView(app)
initService(app)
......
import plugin from './framework/plugin'
export { plugin }
export * from '@dcloudio/uni-components'
export * from './view/bridge'
export * from './service/api'
export * from './service/api/uni'
export * from './service/bridge'
export { getApp, getCurrentPages } from './framework'
export { default as PageComponent } from './framework/components/page/index.vue'
export {
default as AsyncErrorComponent
......
......@@ -6,12 +6,16 @@ export * from './device/getSystemInfoSync'
export * from './file/openDocument'
export * from './media/getImageInfo'
export * from './route/navigateBack'
export * from './route/navigateTo'
export * from './route/redirectTo'
export * from './route/reLaunch'
export * from './route/switchTab'
export * from './util/getRealPath'
export {
upx2px,
addInterceptor,
......
import { fileToUrl } from 'uni-platform/helpers/file'
import { updateElementStyle } from 'uni-shared'
const { invokeCallbackHandler: invoke } = UniServiceJSBridge
let imageInput = null
const _createInput = function(options) {
const inputEl = document.createElement('input')
inputEl.type = 'file'
updateElementStyle(inputEl, {
position: 'absolute',
visibility: 'hidden',
'z-index': -999,
width: 0,
height: 0,
top: 0,
left: 0
})
inputEl.accept = 'image/*'
if (options.count > 1) {
inputEl.multiple = 'multiple'
}
// 经过测试,仅能限制只通过相机拍摄,不能限制只允许从相册选择。
if (options.sourceType.length === 1 && options.sourceType[0] === 'camera') {
inputEl.capture = 'camera'
}
return inputEl
}
export function chooseImage(
{
count,
// sizeType,
sourceType
},
callbackId
) {
// TODO handle sizeType 尝试通过 canvas 压缩
if (imageInput) {
document.body.removeChild(imageInput)
imageInput = null
}
imageInput = _createInput({
count: count,
sourceType: sourceType
})
document.body.appendChild(imageInput)
imageInput.addEventListener('change', function(event) {
const tempFiles = []
const fileCount = event.target.files.length
for (let i = 0; i < fileCount; i++) {
const file = event.target.files[i]
let filePath
Object.defineProperty(file, 'path', {
get() {
filePath = filePath || fileToUrl(file)
return filePath
}
})
tempFiles.push(file)
}
const res = {
errMsg: 'chooseImage:ok',
get tempFilePaths() {
return tempFiles.map(({ path }) => path)
},
tempFiles: tempFiles
}
invoke(callbackId, res)
// TODO 用户取消选择时,触发 fail,目前尚未找到合适的方法。
})
imageInput.click()
}
import { fileToUrl, revokeObjectURL } from 'uni-platform/helpers/file'
import { updateElementStyle } from 'uni-shared'
const { invokeCallbackHandler: invoke } = UniServiceJSBridge
let videoInput = null
const _createInput = function(options) {
const inputEl = document.createElement('input')
inputEl.type = 'file'
updateElementStyle(inputEl, {
position: 'absolute',
visibility: 'hidden',
'z-index': -999,
width: 0,
height: 0,
top: 0,
left: 0
})
inputEl.accept = 'video/*'
// 经过测试,仅能限制只通过相机拍摄,不能限制只允许从相册选择。
if (options.sourceType.length === 1 && options.sourceType[0] === 'camera') {
inputEl.capture = 'camera'
}
return inputEl
}
export function chooseVideo({ sourceType }, callbackId) {
if (videoInput) {
document.body.removeChild(videoInput)
videoInput = null
}
videoInput = _createInput({
sourceType: sourceType
})
document.body.appendChild(videoInput)
videoInput.addEventListener('change', function(event) {
const file = event.target.files[0]
const callbackResult = {
errMsg: 'chooseVideo:ok',
tempFile: file,
size: file.size,
duration: 0,
width: 0,
height: 0,
name: file.name
}
let filePath
Object.defineProperty(callbackResult, 'tempFilePath', {
get() {
filePath = filePath || fileToUrl(this.tempFile)
return filePath
}
})
const video = document.createElement('video')
if (video.onloadedmetadata !== undefined) {
const filePath = fileToUrl(file)
// 尝试获取视频的宽高信息
video.onloadedmetadata = function() {
revokeObjectURL(filePath)
invoke(
callbackId,
Object.assign(callbackResult, {
duration: video.duration || 0,
width: video.videoWidth || 0,
height: video.videoHeight || 0
})
)
}
// 部分浏览器(如微信内置浏览器)未播放无法触发loadedmetadata事件
setTimeout(() => {
video.onloadedmetadata = null
revokeObjectURL(filePath)
invoke(callbackId, callbackResult)
}, 300)
video.src = filePath
} else {
invoke(callbackId, callbackResult)
}
// TODO 用户取消选择时,触发 fail,目前尚未找到合适的方法。
})
videoInput.click()
}
import {
createApi,
GetImageInfoOptions,
GetImageInfoProtocol
} from '@dcloudio/uni-api'
function _getServiceAddress() {
return window.location.protocol + '//' + window.location.host
}
export const getImageInfo = createApi<typeof uni.getImageInfo>(
({ src }, callbackId?: number) => {
const { invokeCallbackHandler: invoke } = UniServiceJSBridge
const img = new Image()
const realPath = src
img.onload = function() {
invoke(callbackId, {
errMsg: 'getImageInfo:ok',
width: img.naturalWidth,
height: img.naturalHeight,
path:
realPath.indexOf('/') === 0
? _getServiceAddress() + realPath
: realPath
})
}
img.onerror = function() {
invoke(callbackId, {
errMsg: 'getImageInfo:fail'
})
}
img.src = src
},
GetImageInfoProtocol,
GetImageInfoOptions
)
export function previewImage({ urls, current }, callbackId) {
const { invokeCallbackHandler: invoke } = UniServiceJSBridge
getApp().$router.push(
{
type: 'navigateTo',
path: '/preview-image',
params: {
urls,
current
}
},
function() {
invoke(callbackId, {
errMsg: 'previewImage:ok'
})
},
function() {
invoke(callbackId, {
errMsg: 'previewImage:fail'
})
}
)
}
import { createApi } from '@dcloudio/uni-api'
export const navigateTo = createApi<typeof uni.navigateTo>(() => {})
export const navigateTo = createApi<typeof uni.navigateTo>(options => {
const router = getApp().$router
router.push(options.url)
})
import { createApi } from '@dcloudio/uni-api'
export const getRealPath = createApi((path: string) => {
return path
})
......@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { ServiceJSBridge } from '@dcloudio/uni-core'
export default extend(ServiceJSBridge, {
export const UniServiceJSBridge = extend(ServiceJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniViewJSBridge.subscribeHandler(event, args, pageId)
}
......
......@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { ViewJSBridge } from '@dcloudio/uni-core'
export default extend(ViewJSBridge, {
export const UniViewJSBridge = extend(ViewJSBridge, {
publishHandler(event: string, args: any, pageId: number) {
window.UniServiceJSBridge.subscribeHandler(event, args, pageId)
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
function createApi(fn, validate) {
if ((process.env.NODE_ENV !== 'production') && validate) ;
function createApi(fn, protocol, options) {
if ((process.env.NODE_ENV !== 'production') && protocol) ;
return fn;
}
......
......@@ -273,5 +273,6 @@ export const buildPluginInject: Plugin = inject({
'__GLOBAL__.': '@dcloudio/uni-h5',
'uni.': '@dcloudio/uni-h5',
getApp: ['@dcloudio/uni-h5', 'getApp'],
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages']
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages'],
UniServiceJSBridge: ['@dcloudio/uni-h5', 'UniServiceJSBridge']
})
......@@ -2,10 +2,12 @@ import { ServerPlugin } from 'vite'
import { readBody } from 'vite'
import { parsePagesJson } from '../utils'
const uniCode = `import {uni,getCurrentPages,getApp} from '@dcloudio/uni-h5'
const uniCode = `import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
window.getApp = getApp
window.getCurrentPages = getCurrentPages
window.uni = window.__GLOBAL__ = uni
window.UniViewJSBridge = UniViewJSBridge
window.UniServiceJSBridge = UniServiceJSBridge
`
export const serverPluginPagesJson: ServerPlugin = ({ app }) => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册