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

refactor(api): createApi

上级 d92b46a9
import { ProtocolOptions } from '../protocols/type'
export function createApi<T extends Function = () => any>(
export function createApi<T extends Function>(
fn: T,
validate?: ProtocolOptions | ProtocolOptions[]
) {
......
......@@ -3,7 +3,6 @@ export * from './service/base/upx2px'
export * from './service/base/interceptor'
export * from './service/ui/createIntersectionObserver'
export * from './service/ui/createSelectorQuery'
// protocols
export * from './protocols/base/canIUse'
......
......@@ -8,10 +8,16 @@ import {
ArrayBufferToBase64Protocol
} from '../../protocols/base/base64'
export const base64ToArrayBuffer = createApi((base64: string) => {
return decode(base64) as ArrayBuffer
}, Base64ToArrayBufferProtocol)
export const base64ToArrayBuffer = createApi<typeof uni.base64ToArrayBuffer>(
base64 => {
return decode(base64) as ArrayBuffer
},
Base64ToArrayBufferProtocol
)
export const arrayBufferToBase64 = createApi((arrayBuffer: ArrayBuffer) => {
return encode(arrayBuffer) as string
}, ArrayBufferToBase64Protocol)
export const arrayBufferToBase64 = createApi<typeof uni.arrayBufferToBase64>(
arrayBuffer => {
return encode(arrayBuffer) as string
},
ArrayBufferToBase64Protocol
)
......@@ -14,8 +14,8 @@ function checkDeviceWidth() {
isIOS = platform === 'ios'
}
export const upx2px = createApi(
(number: number, newDeviceWidth: number | undefined) => {
export const upx2px = createApi<typeof uni.upx2px>(
(number, newDeviceWidth?: number) => {
if (deviceWidth === 0) {
checkDeviceWidth()
}
......
import { extend } from '@vue/shared'
import { createApi } from '../../helpers/api'
import { getCurrentPageVm } from '../utils'
const defaultOptions = {
thresholds: [0],
initialRatio: 0,
observeAll: false
}
interface Margins {
bottom?: number
left?: number
right?: number
top?: number
}
interface RelativeInfo {
selector: string
margins: Margins
}
type ObserveResultCallback = (result: UniApp.ObserveResult) => void
interface requestComponentObserver {
reqId: number
reqEnd: boolean
res: UniApp.ObserveResult
}
let reqComponentObserverId = 1
const reqComponentObserverCallbacks: Record<number, ObserveResultCallback> = {}
UniServiceJSBridge.subscribe(
'requestComponentObserver',
({ reqId, reqEnd, res }: requestComponentObserver) => {
const callback = reqComponentObserverCallbacks[reqId]
if (callback) {
if (reqEnd) {
return delete reqComponentObserverCallbacks[reqId]
}
callback(res)
}
}
)
class ServiceIntersectionObserver {
private _reqId?: number
private _options: UniApp.CreateIntersectionObserverOptions
private _component: any
private _pageId: number
private _relativeInfo: RelativeInfo[]
constructor(
component: any,
options: UniApp.CreateIntersectionObserverOptions
) {
this._pageId = component.$page.id
this._component = component._$id || component // app-plus 平台传输_$id
this._options = extend({}, defaultOptions, options || {})
this._relativeInfo = []
}
relativeTo(selector: string, margins: Margins) {
if (this._reqId) {
throw new Error(
'Relative nodes cannot be added after "observe" call in IntersectionObserver'
)
}
this._relativeInfo.push({
selector,
margins
})
return this
}
relativeToViewport(margins: Margins) {
return this.relativeTo((null as unknown) as string, margins)
}
observe(selector: string, callback: ObserveResultCallback) {
if (typeof callback !== 'function') {
return
}
if (this._reqId) {
throw new Error(
'"observe" call can be only called once in IntersectionObserver'
)
}
this._reqId = reqComponentObserverId++
reqComponentObserverCallbacks[this._reqId] = callback
UniServiceJSBridge.publishHandler(
'addIntersectionObserver',
{
selector,
reqId: this._reqId,
component: this._component,
options: this._options,
relativeInfo: this._relativeInfo
},
this._pageId
)
}
disconnect() {
UniServiceJSBridge.publishHandler(
'removeIntersectionObserver',
{
reqId: this._reqId
},
this._pageId
)
}
}
export const createIntersectionObserver = createApi(() => {})
export const createIntersectionObserver = createApi<
typeof uni.createIntersectionObserver
>((context?, options?) => {
if (!context) {
context = getCurrentPageVm()
}
return new ServiceIntersectionObserver(context, options)
})
import { createApi } from '../../helpers/api'
export const createSelectorQuery = createApi(() => {})
export function getCurrentPageVm() {
const pages = getCurrentPages()
const len = pages.length
const page = pages[len - 1]
return page && (page as any).$vm
}
......@@ -1414,9 +1414,76 @@ const promiseInterceptor = {
});
}
};
const createIntersectionObserver$1 = /* @__PURE__ */ createApi(() => {
function getCurrentPageVm() {
const pages = getCurrentPages();
const len = pages.length;
const page = pages[len - 1];
return page && page.$vm;
}
const defaultOptions = {
thresholds: [0],
initialRatio: 0,
observeAll: false
};
let reqComponentObserverId = 1;
const reqComponentObserverCallbacks = {};
UniServiceJSBridge.subscribe("requestComponentObserver", ({reqId, reqEnd, res}) => {
const callback = reqComponentObserverCallbacks[reqId];
if (callback) {
if (reqEnd) {
return delete reqComponentObserverCallbacks[reqId];
}
callback(res);
}
});
const createSelectorQuery$1 = /* @__PURE__ */ createApi(() => {
class ServiceIntersectionObserver {
constructor(component, options) {
this._pageId = component.$page.id;
this._component = component._$id || component;
this._options = extend({}, defaultOptions, options || {});
this._relativeInfo = [];
}
relativeTo(selector, margins) {
if (this._reqId) {
throw new Error('Relative nodes cannot be added after "observe" call in IntersectionObserver');
}
this._relativeInfo.push({
selector,
margins
});
return this;
}
relativeToViewport(margins) {
return this.relativeTo(null, margins);
}
observe(selector, callback) {
if (typeof callback !== "function") {
return;
}
if (this._reqId) {
throw new Error('"observe" call can be only called once in IntersectionObserver');
}
this._reqId = reqComponentObserverId++;
reqComponentObserverCallbacks[this._reqId] = callback;
UniServiceJSBridge.publishHandler("addIntersectionObserver", {
selector,
reqId: this._reqId,
component: this._component,
options: this._options,
relativeInfo: this._relativeInfo
}, this._pageId);
}
disconnect() {
UniServiceJSBridge.publishHandler("removeIntersectionObserver", {
reqId: this._reqId
}, this._pageId);
}
}
const createIntersectionObserver$1 = /* @__PURE__ */ createApi((context, options) => {
if (!context) {
context = getCurrentPageVm();
}
return new ServiceIntersectionObserver(context, options);
});
const CanIUseProtocol = [
{
......@@ -1459,11 +1526,8 @@ const canIUse = /* @__PURE__ */ createApi((schema) => {
}
return true;
}, CanIUseProtocol);
const makePhoneCall = /* @__PURE__ */ createApi(({phoneNumber}) => {
window.location.href = `tel:${phoneNumber}`;
return {
errMsg: "makePhoneCall:ok"
};
const makePhoneCall = /* @__PURE__ */ createApi((option) => {
window.location.href = `tel:${option.phoneNumber}`;
}, MakePhoneCallProtocol);
const ua = navigator.userAgent;
const isAndroid = /android/i.test(ua);
......@@ -1574,7 +1638,6 @@ const getSystemInfo = /* @__PURE__ */ createApi(() => {
});
const openDocument = /* @__PURE__ */ createApi((option) => {
window.open(option.filePath);
return true;
}, OpenDocumentProtocol);
const navigateBack = /* @__PURE__ */ createApi(() => {
});
......@@ -1594,7 +1657,6 @@ var api = /* @__PURE__ */ Object.freeze({
promiseInterceptor,
arrayBufferToBase64,
base64ToArrayBuffer,
createSelectorQuery: createSelectorQuery$1,
createIntersectionObserver: createIntersectionObserver$1,
canIUse,
makePhoneCall,
......@@ -2730,4 +2792,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, createSelectorQuery$1 as createSelectorQuery, 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, 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};
......@@ -12,7 +12,7 @@ const SCHEMA_CSS = {
'css.constant': cssSupports('top:constant(a)')
}
export const canIUse = createApi((schema: string) => {
export const canIUse = createApi<typeof uni.canIUse>((schema: string) => {
if (hasOwn(SCHEMA_CSS, schema)) {
return SCHEMA_CSS[schema]
}
......
......@@ -2,6 +2,6 @@ import { createApi } from '@dcloudio/uni-api'
import { getSystemInfoSync } from './getSystemInfoSync'
export const getSystemInfo = createApi(() => {
export const getSystemInfo = createApi<typeof uni.getSystemInfo>(() => {
return getSystemInfoSync()
})
......@@ -16,7 +16,7 @@ const isIOS = /iphone|ipad|ipod/i.test(ua)
/**
* 获取系统信息-同步
*/
export const getSystemInfoSync = createApi(() => {
export const getSystemInfoSync = createApi<typeof uni.getSystemInfoSync>(() => {
var screen = window.screen
var pixelRatio = window.devicePixelRatio
// 横屏时 iOS 获取的屏幕宽高颠倒,进行纠正
......@@ -133,5 +133,5 @@ export const getSystemInfoSync = createApi(() => {
bottom: safeAreaInsets.bottom,
left: safeAreaInsets.left
}
}
} as UniApp.GetSystemInfoResult
})
import { createApi, MakePhoneCallProtocol } from '@dcloudio/uni-api'
export const makePhoneCall = createApi(
({ phoneNumber }: { phoneNumber: string }) => {
window.location.href = `tel:${phoneNumber}`
return {
errMsg: 'makePhoneCall:ok'
}
},
MakePhoneCallProtocol
)
export const makePhoneCall = createApi<typeof uni.makePhoneCall>(option => {
window.location.href = `tel:${option.phoneNumber}`
}, MakePhoneCallProtocol)
import { createApi, OpenDocumentProtocol } from '@dcloudio/uni-api'
interface OpenDocumentOption {
filePath: string
}
export const openDocument = createApi((option: OpenDocumentOption) => {
export const openDocument = createApi<typeof uni.openDocument>(option => {
window.open(option.filePath)
return true
}, OpenDocumentProtocol)
......@@ -19,6 +19,5 @@ export {
promiseInterceptor,
arrayBufferToBase64,
base64ToArrayBuffer,
createSelectorQuery,
createIntersectionObserver
} from '@dcloudio/uni-api'
import { createApi } from '@dcloudio/uni-api'
export const navigateBack = createApi(() => {})
export const navigateBack = createApi<typeof uni.navigateBack>(() => {})
import { createApi } from '@dcloudio/uni-api'
export const navigateTo = createApi(() => {})
export const navigateTo = createApi<typeof uni.navigateTo>(() => {})
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册