From aac7625e1ea10f4183d85d01863520fd1ac3378f Mon Sep 17 00:00:00 2001
From: tangcq-code <1192601676@qq.com>
Date: Tue, 28 Nov 2023 16:14:57 +0800
Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E5=B0=86taro-mpharmony=E4=B8=ADH5?=
=?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=9A=84=E6=8E=A5=E5=8F=A3=E7=9A=84=E4=BF=AE?=
=?UTF-8?q?=E6=94=B9=E5=90=8C=E6=AD=A5=E5=88=B0taro-h5=E4=B8=AD=EF=BC=8C?=
=?UTF-8?q?=E6=95=B4=E5=90=88taro-mpharmony=E5=92=8Ctaro-h5=E7=9B=B8?=
=?UTF-8?q?=E5=90=8C=E7=9A=84=E5=AE=9E=E7=8E=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
packages/taro-h5/src/api/base/index.ts | 2 +-
packages/taro-h5/src/api/device/clipboard.ts | 8 +-
packages/taro-h5/src/api/device/network.ts | 1 -
.../src/api/location/chooseLocation.ts | 66 ++-
packages/taro-h5/src/api/location/index.ts | 7 +-
.../taro-h5/src/api/location/openLocation.ts | 83 ++++
packages/taro-h5/src/api/location/style.scss | 23 +-
packages/taro-h5/src/api/media/map.ts | 1 +
.../src/api/network/websocket/index.ts | 2 +
.../taro-h5/src/api/ui/animation/index.ts | 141 ++++--
packages/taro-h5/src/api/ui/fonts.ts | 7 +-
.../src/api/ui/interaction/actionSheet.ts | 63 ++-
.../taro-h5/src/api/ui/interaction/index.ts | 10 +-
.../taro-h5/src/api/ui/interaction/modal.ts | 4 +-
.../src/api/wxml/IntersectionObserver.ts | 3 +-
packages/taro-h5/src/api/wxml/index.ts | 4 +-
packages/taro-h5/src/api/wxml/nodesRef.ts | 31 +-
packages/taro-mpharmony/src/api/base/index.ts | 10 +-
.../taro-mpharmony/src/api/device/battery.ts | 20 +-
.../taro-mpharmony/src/api/device/calendar.ts | 184 +-------
.../src/api/device/clipboard.ts | 69 +--
.../taro-mpharmony/src/api/device/motion.ts | 71 +---
.../taro-mpharmony/src/api/device/network.ts | 87 +---
.../taro-mpharmony/src/api/framework/index.ts | 11 +-
.../src/api/location/chooseLocation.ts | 112 +----
.../src/api/location/openLocation.ts | 78 +---
.../src/api/location/style.scss | 74 ----
.../BackgroundAudioManager.ts | 183 --------
.../src/api/media/background-audio/index.ts | 13 +-
.../src/api/media/video/index.ts | 11 +-
.../src/api/network/websocket/index.ts | 104 +----
.../src/api/network/websocket/socketTask.ts | 91 ----
.../taro-mpharmony/src/api/storage/index.ts | 192 +--------
.../src/api/ui/animation/index.ts | 401 +-----------------
packages/taro-mpharmony/src/api/ui/fonts.ts | 57 +--
.../src/api/ui/interaction/actionSheet.ts | 248 -----------
.../src/api/ui/interaction/index.ts | 330 +-------------
.../src/api/ui/interaction/modal.ts | 266 ------------
.../src/api/ui/interaction/toast.ts | 263 ------------
.../src/api/ui/pull-down-refresh.ts | 24 +-
.../taro-mpharmony/src/api/ui/scroll/index.ts | 98 +----
packages/taro-mpharmony/src/api/ui/tab-bar.ts | 291 +------------
packages/taro-mpharmony/src/api/ui/window.ts | 27 +-
.../src/api/wxml/IntersectionObserver.ts | 144 -------
.../src/api/wxml/MediaQueryObserver.ts | 63 ---
packages/taro-mpharmony/src/api/wxml/index.ts | 25 +-
.../taro-mpharmony/src/api/wxml/nodesRef.ts | 68 +--
47 files changed, 409 insertions(+), 3662 deletions(-)
create mode 100644 packages/taro-h5/src/api/location/openLocation.ts
delete mode 100644 packages/taro-mpharmony/src/api/location/style.scss
delete mode 100644 packages/taro-mpharmony/src/api/media/background-audio/BackgroundAudioManager.ts
delete mode 100644 packages/taro-mpharmony/src/api/network/websocket/socketTask.ts
delete mode 100644 packages/taro-mpharmony/src/api/ui/interaction/actionSheet.ts
delete mode 100644 packages/taro-mpharmony/src/api/ui/interaction/modal.ts
delete mode 100644 packages/taro-mpharmony/src/api/ui/interaction/toast.ts
delete mode 100644 packages/taro-mpharmony/src/api/wxml/IntersectionObserver.ts
delete mode 100644 packages/taro-mpharmony/src/api/wxml/MediaQueryObserver.ts
diff --git a/packages/taro-h5/src/api/base/index.ts b/packages/taro-h5/src/api/base/index.ts
index 65b8ea56c297..3888b0f34d75 100644
--- a/packages/taro-h5/src/api/base/index.ts
+++ b/packages/taro-h5/src/api/base/index.ts
@@ -15,7 +15,7 @@ export function arrayBufferToBase64 (arrayBuffer: ArrayBuffer) {
}
export function base64ToArrayBuffer (base64: string) {
- return toByteArray(base64)
+ return toByteArray(base64).buffer
}
export * from './crypto'
diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts
index 8635378bb1fd..20596925f4b1 100644
--- a/packages/taro-h5/src/api/device/clipboard.ts
+++ b/packages/taro-h5/src/api/device/clipboard.ts
@@ -10,9 +10,9 @@ import { isFunction } from '@tarojs/shared'
import { MethodHandler } from '../../utils/handler'
import { getStorageSync, setStorage, setStorageSync } from '../storage/index'
+import { showToast } from '../ui/interaction'
const CLIPBOARD_STORAGE_NAME = 'taro_clipboard'
-
document.addEventListener('copy', () => {
setStorage({
key: CLIPBOARD_STORAGE_NAME,
@@ -21,7 +21,6 @@ document.addEventListener('copy', () => {
console.error(e)
})
})
-
/**
* 设置系统剪贴板的内容
*/
@@ -49,6 +48,11 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, suc
} else {
throw new Error('Unsupported Function: \'document.execCommand\'.')
}
+ showToast({
+ title: '内容已复制',
+ icon: 'none',
+ duration: 1500
+ })
return handle.success()
} catch (e) {
return handle.fail({ errMsg: e.message })
diff --git a/packages/taro-h5/src/api/device/network.ts b/packages/taro-h5/src/api/device/network.ts
index 863dc270cbcd..785aaac6b72b 100644
--- a/packages/taro-h5/src/api/device/network.ts
+++ b/packages/taro-h5/src/api/device/network.ts
@@ -52,7 +52,6 @@ export const getNetworkType: typeof Taro.getNetworkType = (options = {}) => {
}
const networkStatusManager = new CallbackManager()
-
const networkStatusListener = async () => {
const { networkType } = await getNetworkType()
const isConnected = networkType !== 'none'
diff --git a/packages/taro-h5/src/api/location/chooseLocation.ts b/packages/taro-h5/src/api/location/chooseLocation.ts
index 285856f267e0..105169fc304e 100644
--- a/packages/taro-h5/src/api/location/chooseLocation.ts
+++ b/packages/taro-h5/src/api/location/chooseLocation.ts
@@ -6,26 +6,25 @@ import { stringify } from 'query-string'
import { MethodHandler } from '../../utils/handler'
let container: HTMLDivElement | null = null
-function createLocationChooser (handler, key = LOCATION_APIKEY, mapOpt: Taro.chooseLocation.Option['mapOpts'] = {}) {
- const { latitude, longitude, ...opts } = mapOpt
+function createLocationChooser (handler, mapOpt: Taro.chooseLocation.Option['mapOpts'] = {}) {
+ const { key = LOCATION_APIKEY, referer = 'myapp', ...opts } = mapOpt
const query = {
key,
type: 1,
- coord: mapOpt.coord ?? [latitude, longitude].every(e => Number(e) >= 0) ? `${latitude},${longitude}` : undefined,
- referer: 'myapp',
- ...opts
+ referer,
+ ...opts,
}
if (!container) {
const html = `
-
-`
+
+ `
container = document.createElement('div')
container.innerHTML = html
}
@@ -73,18 +72,10 @@ function createLocationChooser (handler, key = LOCATION_APIKEY, mapOpt: Taro.cho
* 打开地图选择位置。
*/
export const chooseLocation: typeof Taro.chooseLocation = ({ success, fail, complete, mapOpts } = {}) => {
- const key = LOCATION_APIKEY
const handle = new MethodHandler({ name: 'chooseLocation', success, fail, complete })
return new Promise((resolve, reject) => {
const chooseLocation: Partial = {}
- if (!key) {
- console.warn('chooseLocation api 依赖腾讯地图定位api,需要在 defineConstants 中配置 LOCATION_APIKEY')
- return handle.fail({
- errMsg: 'LOCATION_APIKEY needed'
- }, { resolve, reject })
- }
-
- const onMessage = event => {
+ const onMessage = (event) => {
// 接收位置信息,用户选择确认位置点后选点组件会触发该事件,回传用户的位置信息
const loc = event.data
@@ -97,21 +88,24 @@ export const chooseLocation: typeof Taro.chooseLocation = ({ success, fail, comp
chooseLocation.longitude = loc.latlng.lng
}
- const chooser = createLocationChooser(res => {
- window.removeEventListener('message', onMessage, false)
- setTimeout(() => {
- chooser.remove()
- }, 300)
- if (res) {
- return handle.fail(res, { resolve, reject })
- } else {
- if (chooseLocation.latitude && chooseLocation.longitude) {
- return handle.success(chooseLocation, { resolve, reject })
+ const chooser = createLocationChooser(
+ (res) => {
+ window.removeEventListener('message', onMessage, false)
+ setTimeout(() => {
+ chooser.remove()
+ }, 300)
+ if (res) {
+ return handle.fail(res, { resolve, reject })
} else {
- return handle.fail({}, { resolve, reject })
+ if (chooseLocation.latitude && chooseLocation.longitude) {
+ return handle.success(chooseLocation, { resolve, reject })
+ } else {
+ return handle.fail({}, { resolve, reject })
+ }
}
- }
- }, key, mapOpts)
+ },
+ mapOpts
+ )
document.body.appendChild(chooser.container)
diff --git a/packages/taro-h5/src/api/location/index.ts b/packages/taro-h5/src/api/location/index.ts
index df5eaef125b4..9a3d2b0af63b 100644
--- a/packages/taro-h5/src/api/location/index.ts
+++ b/packages/taro-h5/src/api/location/index.ts
@@ -1,14 +1,11 @@
-import { processOpenApi, temporarilyNotSupport } from '../../utils/index'
+import { temporarilyNotSupport } from '../../utils/index'
// 位置
export const stopLocationUpdate = /* @__PURE__ */ temporarilyNotSupport('stopLocationUpdate')
export const startLocationUpdateBackground = /* @__PURE__ */ temporarilyNotSupport('startLocationUpdateBackground')
export const startLocationUpdate = /* @__PURE__ */ temporarilyNotSupport('startLocationUpdate')
-export const openLocation = /* @__PURE__ */ processOpenApi({
- name: 'openLocation',
- defaultOptions: { scale: 18 }
-})
+export { openLocation } from './openLocation'
export const onLocationChangeError = /* @__PURE__ */ temporarilyNotSupport('onLocationChangeError')
export const onLocationChange = /* @__PURE__ */ temporarilyNotSupport('onLocationChange')
diff --git a/packages/taro-h5/src/api/location/openLocation.ts b/packages/taro-h5/src/api/location/openLocation.ts
new file mode 100644
index 000000000000..396e8c6b878e
--- /dev/null
+++ b/packages/taro-h5/src/api/location/openLocation.ts
@@ -0,0 +1,83 @@
+
+import './style.scss'
+
+import Taro from '@tarojs/api'
+import { shouldBeObject } from 'src/utils'
+
+import { MethodHandler } from '../../utils/handler'
+
+let container: HTMLDivElement | null = null
+function createContainer (options: Taro.openLocation.Option) {
+ const key = LOCATION_APIKEY
+ const { longitude, latitude, name, address } = options
+ if (!container) {
+ const html = `
+
+ `
+ container = document.createElement('div')
+ container.innerHTML = html
+ }
+ const main: HTMLDivElement = container.querySelector('.taro_choose_location') as HTMLDivElement
+
+ function show () {
+ main.style.top = '0'
+ }
+
+ function hide () {
+ main.style.top = '100%'
+ remove()
+ }
+
+ function remove () {
+ container?.remove()
+ container = null
+ }
+
+ container.querySelector('.taro_choose_location_back')?.addEventListener('click', hide)
+
+ return {
+ show,
+ container,
+ }
+}
+
+/**
+ * 使用微信内置地图查看位置(暂不支持scale入参)
+ *
+ * @canUse openLocation
+ * @__object [latitude, longitude, address, name]
+ */
+export const openLocation: typeof Taro.openLocation = (options) => {
+ const name = 'openLocation'
+ // options must be an Object
+ const isObject = shouldBeObject(options)
+ if (!isObject.flag) {
+ const res = { errMsg: `${name}:fail ${isObject.msg}` }
+ console.error(res.errMsg)
+ return Promise.reject(res)
+ }
+ const {
+ success,
+ fail,
+ complete
+ } = options as Exclude
+ const handle = new MethodHandler({ name, success, fail, complete })
+
+ return new Promise((resolve, reject) => {
+ const dispalyLoc = createContainer(options)
+ document.body.appendChild(dispalyLoc.container)
+ dispalyLoc.show()
+ document.querySelector('iframe')?.addEventListener('load', function () {
+ handle.success({}, { resolve, reject })
+ })
+ document.querySelector('iframe')?.addEventListener('error', function () {
+ handle.fail({}, { resolve, reject })
+ })
+ })
+}
diff --git a/packages/taro-h5/src/api/location/style.scss b/packages/taro-h5/src/api/location/style.scss
index 9dc8d9c06a87..cca8bf187f63 100644
--- a/packages/taro-h5/src/api/location/style.scss
+++ b/packages/taro-h5/src/api/location/style.scss
@@ -11,17 +11,18 @@
&_bar {
display: flex;
- flex: 0 95px;
- height: 95px;
+ flex: 0 60px;
+ height: 60px;
background-color: #ededed;
color: #090909;
+ align-items: center;
}
&_back {
position: relative;
- flex: 0 45px;
- margin-top: 30px;
- width: 33px;
+ flex: 0 40px;
+ margin-left: 10px;
+ width: 25px;
height: 30px;
&::before {
@@ -52,18 +53,18 @@
&_title {
flex: 1;
padding-left: 30px;
- line-height: 95px;
+ line-height: 60px;
}
&_submit {
- margin: 18px 30px 0 0;
+ margin-right: 25px;
padding: 0;
border: none;
- width: 110px;
- height: 60px;
+ width: 75px;
+ height: 40px;
background-color: #08bf62;
- line-height: 60px;
- font-size: 28px;
+ line-height: 40px;
+ font-size: 20px;
color: #fff;
}
diff --git a/packages/taro-h5/src/api/media/map.ts b/packages/taro-h5/src/api/media/map.ts
index 2e236295fc75..c7312dc14878 100644
--- a/packages/taro-h5/src/api/media/map.ts
+++ b/packages/taro-h5/src/api/media/map.ts
@@ -2,3 +2,4 @@ import { temporarilyNotSupport } from '../../utils'
// 地图
export const createMapContext = /* @__PURE__ */ temporarilyNotSupport('createMapContext')
+
diff --git a/packages/taro-h5/src/api/network/websocket/index.ts b/packages/taro-h5/src/api/network/websocket/index.ts
index e7e822a0a468..1ee6d5ff96ab 100644
--- a/packages/taro-h5/src/api/network/websocket/index.ts
+++ b/packages/taro-h5/src/api/network/websocket/index.ts
@@ -86,3 +86,5 @@ export function connectSocket (options?: Taro.connectSocket.Option) {
export function closeSocket () {
console.warn('Deprecated.Please use socketTask.close instead.')
}
+
+export { SocketTask }
\ No newline at end of file
diff --git a/packages/taro-h5/src/api/ui/animation/index.ts b/packages/taro-h5/src/api/ui/animation/index.ts
index 946de65c9686..c03a674e1ae6 100644
--- a/packages/taro-h5/src/api/ui/animation/index.ts
+++ b/packages/taro-h5/src/api/ui/animation/index.ts
@@ -110,9 +110,9 @@ class Animation implements Taro.Animation {
if (stepIndex < animStepsMaxIndex) {
// 播放下一个关键帧(因为 nerv 和 react 有差异所以 animation & data-animation 都需要写)
target.setAttribute(animAttr, `${animName}__${animIndex}--${stepIndex + 1}`)
- if (animAttr === 'animation') {
+ if (animAttr === 'data-animation') {
// Nerv 环境,animation & data-animation 双重保险
- target.setAttribute('data-animation', `${animName}__${animIndex}--${stepIndex + 1}`)
+ target.setAttribute('animation', `${animName}__${animIndex}--${stepIndex + 1}`)
}
}
}
@@ -121,7 +121,7 @@ class Animation implements Taro.Animation {
transformUnit (...args) {
const ret: string[] = []
- args.forEach(each => {
+ args.forEach((each) => {
ret.push(isNaN(each) ? each : `${each}${this.unit}`)
})
return ret
@@ -133,170 +133,193 @@ class Animation implements Taro.Animation {
}
// 属性组合
- rules: string[] = []
+ rules: { key: string, rule: string }[] = []
// transform 对象
- transform = [`${TRANSFORM}:`]
+ transform: { key: string, transform: string }[] = []
// 组合动画
steps: string[] = []
// 动画 map ----- 永久保留
animationMap = {}
// animationMap 的长度
animationMapCount = 0
+ // 历史动画
+ historyAnimations: { key: string, transform: string }[] = []
+ // 历史规则
+ historyRules: { key: string, rule: string }[] = []
matrix (a: number, b: number, c: number, d: number, tx: number, ty: number) {
- this.transform.push(`matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})`)
+ this.transform.push({ key: 'matrix', transform: `matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})` })
return this
}
- matrix3d (a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number) {
- this.transform.push(`matrix3d(${a1}, ${b1}, ${c1}, ${d1}, ${a2}, ${b2}, ${c2}, ${d2}, ${a3}, ${b3}, ${c3}, ${d3}, ${a4}, ${b4}, ${c4}, ${d4})`)
+ matrix3d (
+ a1: number,
+ b1: number,
+ c1: number,
+ d1: number,
+ a2: number,
+ b2: number,
+ c2: number,
+ d2: number,
+ a3: number,
+ b3: number,
+ c3: number,
+ d3: number,
+ a4: number,
+ b4: number,
+ c4: number,
+ d4: number
+ ) {
+ this.transform.push({
+ key: 'matrix3d',
+ transform: `matrix3d(${a1}, ${b1}, ${c1}, ${d1}, ${a2}, ${b2}, ${c2}, ${d2}, ${a3}, ${b3}, ${c3}, ${d3}, ${a4}, ${b4}, ${c4}, ${d4})`,
+ })
return this
}
rotate (angle: number) {
- this.transform.push(`rotate(${angle}deg)`)
+ this.transform.push({ key: 'rotate', transform: `rotate(${angle}deg)` })
return this
}
rotate3d (x: number, y?: number, z?: number, angle?: number) {
if (typeof y !== 'number') {
- this.transform.push(`rotate3d(${x})`)
+ this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x})` })
} else {
- this.transform.push(`rotate3d(${x}, ${y || 0}, ${z || 0}, ${angle || 0}deg)`)
+ this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x}, ${y || 0}, ${z || 0}, ${angle || 0}deg)` })
}
return this
}
rotateX (angle) {
- this.transform.push(`rotateX(${angle}deg)`)
+ this.transform.push({ key: 'rotateX', transform: `rotateX(${angle}deg)` })
return this
}
rotateY (angle) {
- this.transform.push(`rotateY(${angle}deg)`)
+ this.transform.push({ key: 'rotateY', transform: `rotateY(${angle}deg)` })
return this
}
rotateZ (angle) {
- this.transform.push(`rotateZ(${angle}deg)`)
+ this.transform.push({ key: 'rotateZ', transform: `rotateZ(${angle}deg)` })
return this
}
- scale (x, y) {
- this.transform.push(`scale(${x}, ${y})`)
+ scale (x: number, y?: number) {
+ const scaleY = (typeof y !== 'undefined' && y !== null) ? y : x
+ this.transform.push({ key: 'scale', transform: `scale(${x}, ${scaleY})` })
return this
}
scale3d (x, y, z) {
- this.transform.push(`scale3d(${x}, ${y}, ${z})`)
+ this.transform.push({ key: 'scale3d', transform: `scale3d(${x}, ${y}, ${z})` })
return this
}
scaleX (scale) {
- this.transform.push(`scaleX(${scale})`)
+ this.transform.push({ key: 'scaleX', transform: `scaleX(${scale})` })
return this
}
scaleY (scale) {
- this.transform.push(`scaleY(${scale})`)
+ this.transform.push({ key: 'scaleY', transform: `scaleY(${scale})` })
return this
}
scaleZ (scale) {
- this.transform.push(`scaleZ(${scale})`)
+ this.transform.push({ key: 'scaleZ', transform: `scaleZ(${scale})` })
return this
}
skew (x, y) {
- this.transform.push(`skew(${x}, ${y})`)
+ this.transform.push({ key: 'skew', transform: `skew(${x}deg, ${y}deg)` })
return this
}
skewX (angle) {
- this.transform.push(`skewX(${angle})`)
+ this.transform.push({ key: 'skewX', transform: `skewX(${angle}deg)` })
return this
}
skewY (angle) {
- this.transform.push(`skewY(${angle})`)
+ this.transform.push({ key: 'skewY', transform: `skewY(${angle}deg)` })
return this
}
translate (x, y) {
[x, y] = this.transformUnit(x, y)
- this.transform.push(`translate(${x}, ${y})`)
+ this.transform.push({ key: 'translate', transform: `translate(${x}, ${y})` })
return this
}
translate3d (x, y, z) {
[x, y, z] = this.transformUnit(x, y, z)
- this.transform.push(
- `translate3d(${x}, ${y}, ${z})`
- )
+ this.transform.push({ key: 'translate3d', transform: `translate3d(${x}, ${y}, ${z})` })
return this
}
translateX (translate) {
[translate] = this.transformUnit(translate)
- this.transform.push(`translateX(${translate})`)
+ this.transform.push({ key: 'translateX', transform: `translateX(${translate})` })
return this
}
translateY (translate) {
[translate] = this.transformUnit(translate)
- this.transform.push(`translateY(${translate})`)
+ this.transform.push({ key: 'translateY', transform: `translateY(${translate})` })
return this
}
translateZ (translate) {
[translate] = this.transformUnit(translate)
- this.transform.push(`translateZ(${translate})`)
+ this.transform.push({ key: 'translateZ', transform: `translateZ(${translate})` })
return this
}
opacity (value) {
- this.rules.push(`opacity: ${value}`)
+ this.rules.push({ key: 'opacity', rule: `opacity: ${value}` })
return this
}
backgroundColor (value) {
- this.rules.push(`background-color: ${value}`)
+ this.rules.push({ key: 'backgroundColor', rule: `background-color: ${value}` })
return this
}
width (value) {
[value] = this.transformUnit(value)
- this.rules.push(`width: ${value}`)
+ this.rules.push({ key: 'width', rule: `width: ${value}` })
return this
}
height (value) {
[value] = this.transformUnit(value)
- this.rules.push(`height: ${value}`)
+ this.rules.push({ key: 'height', rule: `height: ${value}` })
return this
}
top (value) {
[value] = this.transformUnit(value)
- this.rules.push(`top: ${value}`)
+ this.rules.push({ key: 'top', rule: `top: ${value}` })
return this
}
right (value) {
[value] = this.transformUnit(value)
- this.rules.push(`right: ${value}`)
+ this.rules.push({ key: 'right', rule: `right: ${value}` })
return this
}
bottom (value) {
[value] = this.transformUnit(value)
- this.rules.push(`bottom: ${value}`)
+ this.rules.push({ key: 'bottom', rule: `bottom: ${value}` })
return this
}
left (value) {
[value] = this.transformUnit(value)
- this.rules.push(`left: ${value}`)
+ this.rules.push({ key: 'left', rule: `left: ${value}` })
return this
}
@@ -307,22 +330,45 @@ class Animation implements Taro.Animation {
duration = DEFAULT.duration,
delay = DEFAULT.delay,
timingFunction = DEFAULT.timingFunction,
- transformOrigin = DEFAULT.transformOrigin
+ transformOrigin = DEFAULT.transformOrigin,
} = arg
// 生成一条 transition 动画
+
+ this.transform.map((t0) => {
+ const index = this.historyAnimations.findIndex((t1) => t1.key === t0.key)
+ if (index === -1) {
+ this.historyAnimations.push(t0)
+ } else {
+ this.historyAnimations[index] = t0
+ }
+ })
+ const transforms = this.historyAnimations.map((t) => t.transform)
+ const transformSequence = transforms.length > 0 ? `${TRANSFORM}:${transforms.join(' ')}!important` : ''
+
+ this.rules.map((r0) => {
+ const index = this.historyRules.findIndex((r1) => r1.key === r0.key)
+ if (index === -1) {
+ this.historyRules.push(r0)
+ } else {
+ this.historyRules[index] = r0
+ }
+ })
+ const rules = this.historyRules.map((t) => t.rule)
+ const ruleSequence = rules.length > 0 ? rules.map((rule) => `${rule}!important`).join(';') : ''
+
this.steps.push(
[
- this.rules.map(rule => `${rule}!important`).join(';'),
- `${this.transform.join(' ')}!important`,
+ ruleSequence,
+ transformSequence,
`${TRANSFORM}-origin: ${transformOrigin}`,
- `transition: all ${duration}ms ${timingFunction} ${delay}ms`
+ `transition: all ${duration}ms ${timingFunction} ${delay}ms`,
]
- .filter(item => item !== '' && item !== `${TRANSFORM}:`)
+ .filter((item) => item !== '')
.join(';')
)
// 清空 rules 和 transform
this.rules = []
- this.transform = [`${TRANSFORM}:`]
+ this.transform = []
return this as Taro.Animation
}
@@ -333,9 +379,10 @@ class Animation implements Taro.Animation {
this.animationMap[animIndex] = this.steps.length
// 吐出 step
this.steps.forEach((step, index) => {
- const selector = index === 0
- ? `[animation="${animIndex}"], [data-animation="${animIndex}"]`
- : `[animation="${animIndex}--${index}"], [data-animation="${animIndex}--${index}"]`
+ const selector =
+ index === 0
+ ? `[animation="${animIndex}"], [data-animation="${animIndex}"]`
+ : `[animation="${animIndex}--${index}"], [data-animation="${animIndex}--${index}"]`
styleSheet.add(`${selector} { ${step} }`)
})
diff --git a/packages/taro-h5/src/api/ui/fonts.ts b/packages/taro-h5/src/api/ui/fonts.ts
index 52764ef11c9c..a090abea4187 100644
--- a/packages/taro-h5/src/api/ui/fonts.ts
+++ b/packages/taro-h5/src/api/ui/fonts.ts
@@ -15,10 +15,11 @@ export const loadFontFace: typeof Taro.loadFontFace = async options => {
try {
await fontFace.load()
fonts.add(fontFace)
- return handle.success({})
+ return handle.success({ status: 'loaded' })
} catch (error) {
return handle.fail({
- errMsg: error.message || error
+ status: 'error',
+ errMsg: error.message || error,
})
}
} else {
@@ -59,6 +60,6 @@ export const loadFontFace: typeof Taro.loadFontFace = async options => {
style.innerText = `@font-face{${innerText}}`
document.head.appendChild(style)
- return handle.success()
+ return handle.success({ status: 'loaded' })
}
}
diff --git a/packages/taro-h5/src/api/ui/interaction/actionSheet.ts b/packages/taro-h5/src/api/ui/interaction/actionSheet.ts
index d2db0548a3e6..b130233a217c 100644
--- a/packages/taro-h5/src/api/ui/interaction/actionSheet.ts
+++ b/packages/taro-h5/src/api/ui/interaction/actionSheet.ts
@@ -4,11 +4,12 @@ const noop = function () {}
export default class ActionSheet {
options = {
+ alertText: '',
itemList: [],
itemColor: '#000000',
success: noop,
fail: noop,
- complete: noop
+ complete: noop,
}
style = {
@@ -19,7 +20,7 @@ export default class ActionSheet {
right: '0',
left: '0',
bottom: '0',
- background: 'rgba(0,0,0,0.6)'
+ background: 'rgba(0,0,0,0.6)',
},
actionSheetStyle: {
'z-index': '4999',
@@ -32,16 +33,26 @@ export default class ActionSheet {
'line-height': '1.6',
background: '#EFEFF4',
'-webkit-transition': '-webkit-transform .3s',
- transition: 'transform .3s'
+ transition: 'transform .3s',
+ 'border-radius': '15px 15px 0 0',
},
menuStyle: {
- 'background-color': '#FCFCFD'
+ 'background-color': '#FCFCFD',
+ 'border-radius': '15px 15px 0 0',
},
cellStyle: {
position: 'relative',
padding: '10px 0',
'text-align': 'center',
- 'font-size': '18px'
+ 'font-size': '18px',
+ },
+ titleStyle: {
+ position: 'relative',
+ padding: '10px 0',
+ 'text-align': 'center',
+ 'font-size': '16px',
+ color: 'rgba(0,0,0,0.8)',
+ display: 'none',
},
cancelStyle: {
'margin-top': '6px',
@@ -49,8 +60,8 @@ export default class ActionSheet {
'text-align': 'center',
'font-size': '18px',
color: '#000000',
- 'background-color': '#FCFCFD'
- }
+ 'background-color': '#FCFCFD',
+ },
}
lastConfig = {}
@@ -59,6 +70,7 @@ export default class ActionSheet {
actionSheet: HTMLDivElement
menu: HTMLDivElement
cells: HTMLDivElement[]
+ title: HTMLDivElement
cancel: HTMLDivElement
hideOpacityTimer: ReturnType
hideDisplayTimer: ReturnType
@@ -66,12 +78,12 @@ export default class ActionSheet {
create (options = {}) {
return new Promise((resolve) => {
// style
- const { maskStyle, actionSheetStyle, menuStyle, cellStyle, cancelStyle } = this.style
+ const { maskStyle, actionSheetStyle, menuStyle, cellStyle, titleStyle, cancelStyle } = this.style
// configuration
const config = {
...this.options,
- ...options
+ ...options,
}
this.lastConfig = config
@@ -92,10 +104,13 @@ export default class ActionSheet {
// menu
this.menu = document.createElement('div')
- this.menu.setAttribute('style', inlineStyle({
- ...menuStyle,
- color: config.itemColor
- }))
+ this.menu.setAttribute(
+ 'style',
+ inlineStyle({
+ ...menuStyle,
+ color: config.itemColor,
+ })
+ )
// cells
this.cells = config.itemList.map((item, index) => {
@@ -104,7 +119,7 @@ export default class ActionSheet {
cell.setAttribute('style', inlineStyle(cellStyle))
cell.textContent = item
cell.dataset.tapIndex = `${index}`
- cell.onclick = e => {
+ cell.onclick = (e) => {
this.hide()
const target = e.currentTarget as HTMLDivElement
const index = Number(target?.dataset.tapIndex) || 0
@@ -113,13 +128,21 @@ export default class ActionSheet {
return cell
})
+ // title
+ this.title = document.createElement('div')
+ this.title.setAttribute('style', inlineStyle(titleStyle))
+ this.title.className = 'taro-actionsheet__cell'
+ this.title.textContent = config.alertText
+ this.title.style.display = config.alertText ? 'block' : 'none'
+
// cancel
this.cancel = document.createElement('div')
this.cancel.setAttribute('style', inlineStyle(cancelStyle))
this.cancel.textContent = '取消'
// result
- this.cells.forEach(item => this.menu.appendChild(item))
+ this.menu.appendChild(this.title)
+ this.cells.forEach((item) => this.menu.appendChild(item))
this.actionSheet.appendChild(this.menu)
this.actionSheet.appendChild(this.cancel)
this.el.appendChild(this.mask)
@@ -146,7 +169,7 @@ export default class ActionSheet {
return new Promise((resolve) => {
const config = {
...this.options,
- ...options
+ ...options,
}
this.lastConfig = config
@@ -175,7 +198,7 @@ export default class ActionSheet {
this.menu.appendChild(cell)
}
cell.textContent = item
- cell.onclick = e => {
+ cell.onclick = (e) => {
this.hide()
const target = e.currentTarget as HTMLDivElement
const index = Number(target?.dataset.tapIndex) || 0
@@ -190,6 +213,8 @@ export default class ActionSheet {
}
this.cells.splice(itemListLen)
}
+ this.title.textContent = config.alertText
+ this.title.style.display = config.alertText ? 'block' : 'none'
// callbacks
const cb = () => {
@@ -215,7 +240,9 @@ export default class ActionSheet {
this.hideOpacityTimer = setTimeout(() => {
this.el.style.opacity = '0'
setTransform(this.actionSheet, 'translate(0, 100%)')
- this.hideDisplayTimer = setTimeout(() => { this.el.style.display = 'none' }, 200)
+ this.hideDisplayTimer = setTimeout(() => {
+ this.el.style.display = 'none'
+ }, 200)
}, 0)
}
}
diff --git a/packages/taro-h5/src/api/ui/interaction/index.ts b/packages/taro-h5/src/api/ui/interaction/index.ts
index 1cfe77159571..c39d40fce2e1 100644
--- a/packages/taro-h5/src/api/ui/interaction/index.ts
+++ b/packages/taro-h5/src/api/ui/interaction/index.ts
@@ -296,12 +296,16 @@ const showActionSheet = async (
Taro.eventCenter.on('__afterTaroRouterChange', () => {
if (toast.currentPath && toast.currentPath !== Current.page?.path) {
- hideToast()
- hideLoading()
+ if (Taro.getEnv() !== Taro.ENV_TYPE.MPHARMONY) {
+ hideToast()
+ hideLoading()
+ }
}
if (modal.currentPath && modal.currentPath !== Current.page?.path) {
- hideModal()
+ if (Taro.getEnv() !== Taro.ENV_TYPE.MPHARMONY) {
+ hideModal()
+ }
}
})
diff --git a/packages/taro-h5/src/api/ui/interaction/modal.ts b/packages/taro-h5/src/api/ui/interaction/modal.ts
index ba05262898bf..512384a29ad4 100644
--- a/packages/taro-h5/src/api/ui/interaction/modal.ts
+++ b/packages/taro-h5/src/api/ui/interaction/modal.ts
@@ -46,7 +46,9 @@ export default class Modal {
'min-height': '40px',
'font-size': '15px',
'line-height': '1.3',
- color: '#808080'
+ color: '#808080',
+ 'word-wrap': 'break-word',
+ 'word-break': 'break-all',
},
footStyle: {
position: 'relative',
diff --git a/packages/taro-h5/src/api/wxml/IntersectionObserver.ts b/packages/taro-h5/src/api/wxml/IntersectionObserver.ts
index 08d8413b71f9..bfa5686d41c6 100644
--- a/packages/taro-h5/src/api/wxml/IntersectionObserver.ts
+++ b/packages/taro-h5/src/api/wxml/IntersectionObserver.ts
@@ -61,7 +61,8 @@ export class TaroH5IntersectionObserver implements Taro.IntersectionObserver {
intersectionRatio: entry.intersectionRatio,
intersectionRect: entry.intersectionRect,
relativeRect: entry.rootBounds || { left: 0, right: 0, top: 0, bottom: 0 },
- time: entry.time
+ // 使用时间戳而不是entry.time,跟微信小程序一致
+ time: Date.now(),
}
// web端会默认首次触发
if (!this._isInited && this._options.initialRatio <= Math.min.apply(Math, this._options.thresholds)) {
diff --git a/packages/taro-h5/src/api/wxml/index.ts b/packages/taro-h5/src/api/wxml/index.ts
index 441d53bc3564..c5dbf015a976 100644
--- a/packages/taro-h5/src/api/wxml/index.ts
+++ b/packages/taro-h5/src/api/wxml/index.ts
@@ -2,6 +2,7 @@ import Taro from '@tarojs/api'
import { TaroH5IntersectionObserver } from './IntersectionObserver'
import { MediaQueryObserver } from './MediaQueryObserver'
+import { NodesRef } from './nodesRef'
import { SelectorQuery } from './selectorQuery'
export const createSelectorQuery: typeof Taro.createSelectorQuery = () => {
@@ -15,4 +16,5 @@ export const createIntersectionObserver: typeof Taro.createIntersectionObserver
export const createMediaQueryObserver: typeof Taro.createMediaQueryObserver = () => {
return new MediaQueryObserver()
}
-
\ No newline at end of file
+
+export { NodesRef }
\ No newline at end of file
diff --git a/packages/taro-h5/src/api/wxml/nodesRef.ts b/packages/taro-h5/src/api/wxml/nodesRef.ts
index 4960b4801c8e..5976ebe0bc57 100644
--- a/packages/taro-h5/src/api/wxml/nodesRef.ts
+++ b/packages/taro-h5/src/api/wxml/nodesRef.ts
@@ -41,17 +41,26 @@ export class NodesRef implements Taro.NodesRef {
fields (fields, cb) {
const { _selector, _component, _single, _selectorQuery } = this
- const { id, dataset, rect, size, scrollOffset, properties = [], computedStyle = [] } = fields
-
- _selectorQuery._push(_selector, _component, _single, {
- id,
- dataset,
- rect,
- size,
- scrollOffset,
- properties,
- computedStyle
- }, cb)
+ const { id, dataset, rect, size, scrollOffset, context, node, properties = [], computedStyle = [] } = fields
+
+ _selectorQuery._push(
+ _selector,
+ _component,
+ _single,
+ {
+ id,
+ dataset,
+ rect,
+ size,
+ scrollOffset,
+ context,
+ node,
+ nodeCanvasType: node,
+ properties,
+ computedStyle,
+ },
+ cb
+ )
return _selectorQuery
}
diff --git a/packages/taro-mpharmony/src/api/base/index.ts b/packages/taro-mpharmony/src/api/base/index.ts
index 528d78fe34b1..b6feb8f5e9ee 100644
--- a/packages/taro-mpharmony/src/api/base/index.ts
+++ b/packages/taro-mpharmony/src/api/base/index.ts
@@ -1,5 +1,3 @@
-import { fromByteArray, toByteArray } from 'base64-js'
-
/**
* 环境变量
*
@@ -19,18 +17,14 @@ export const env = {
*
* @canUse arrayBufferToBase64
*/
-export function arrayBufferToBase64 (arrayBuffer: ArrayBuffer) {
- return fromByteArray(arrayBuffer as Uint8Array)
-}
+export { arrayBufferToBase64 } from '@tarojs/taro-h5'
/**
* 将ArrayBuffer数据转成Base64字符串
*
* @canUse base64ToArrayBuffer
*/
-export function base64ToArrayBuffer (base64: string) {
- return toByteArray(base64).buffer
-}
+export { base64ToArrayBuffer } from '@tarojs/taro-h5'
/**
* 获取当前运行环境对于 Skyline 渲染引擎 的支持情况
diff --git a/packages/taro-mpharmony/src/api/device/battery.ts b/packages/taro-mpharmony/src/api/device/battery.ts
index 4804bc46b5db..05ddc74267db 100644
--- a/packages/taro-mpharmony/src/api/device/battery.ts
+++ b/packages/taro-mpharmony/src/api/device/battery.ts
@@ -1,7 +1,3 @@
-import Taro from '@tarojs/api'
-
-import { MethodHandler } from '../../utils/handler'
-
/**
* Taro.getBatteryInfo 的同步版本 Note: 浏览器标准下不支持,其他实现方案不准确,不建议开发者使用
*
@@ -15,18 +11,4 @@ export { getBatteryInfoSync } from '@tarojs/taro-h5'
* @canUse getBatteryInfo
* @__success [isCharging, level]
*/
-export const getBatteryInfo: typeof Taro.getBatteryInfo = async ({ success, fail, complete } = {}) => {
- const handle = new MethodHandler({ name: 'getBatteryInfo', success, fail, complete })
- try {
- // @ts-ignore
- const battery = await navigator.getBattery?.()
- return handle.success({
- isCharging: battery.charging,
- level: Number(battery.level || 0) * 100,
- })
- } catch (error) {
- return handle.fail({
- errMsg: error?.message || error,
- })
- }
-}
+export { getBatteryInfo } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/device/calendar.ts b/packages/taro-mpharmony/src/api/device/calendar.ts
index 271008eaa909..7d232c4b75f4 100644
--- a/packages/taro-mpharmony/src/api/device/calendar.ts
+++ b/packages/taro-mpharmony/src/api/device/calendar.ts
@@ -1,115 +1,10 @@
-import Taro from '@tarojs/api'
-import * as ics from 'ics'
-
-import { createDownload, getParameterError, shouldBeObject } from '../../utils'
-import { MethodHandler } from '../../utils/handler'
-
-import type { DateArray } from 'ics'
-
/**
* 向系统日历添加重复事件
*
* @canUse addPhoneRepeatCalendar
* @__object [title, startTime, allDay, description, location, endTime, alarm, alarmOffset, repeatInterval, repeatEndTime]
*/
-export const addPhoneRepeatCalendar: typeof Taro.addPhoneRepeatCalendar = (options) => {
- const methodName = 'addPhoneRepeatCalendar'
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `${methodName}:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const {
- title,
- startTime = new Date().getTime(),
- allDay = false,
- description = '',
- location = '',
- endTime,
- alarm = true,
- alarmOffset = 0,
- repeatInterval = 'month',
- repeatEndTime,
- success,
- fail,
- complete,
- } = options
- const handle = new MethodHandler({ name: methodName, success, fail, complete })
- if (typeof title !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'title',
- correct: 'String',
- wrong: title,
- }),
- })
- }
-
- const start = new Date(startTime)
- const end = new Date(endTime || startTime)
- if (!endTime && allDay) {
- end.setDate(end.getDate() + 1)
- }
-
- const interval = 1000 * 60 * 60 * 24
- let days = 1
- let repeat = 1
- if (repeatEndTime) {
- const repeatEnd = new Date(repeatEndTime)
- if (repeatEnd < start) {
- return handle.fail({
- errMsg: 'repeatEndTime must be greater than startTime',
- })
- }
- switch (repeatInterval) {
- case 'week':
- days = 7
- break
- case 'month':
- days = 30
- break
- case 'year':
- days = 365
- break
- default:
- }
- repeat = Math.ceil((repeatEnd.getTime() - start.getTime()) / (interval * days))
- }
- const { error, value } = ics.createEvent({
- title,
- start: parseTime2Array(start, allDay),
- description,
- location,
- end: parseTime2Array(end, allDay),
- alarms: alarm
- ? [
- {
- action: 'display',
- description,
- trigger: {
- before: true,
- seconds: alarmOffset,
- },
- duration: {
- days,
- },
- repeat,
- },
- ]
- : [],
- })
- if (error || !value) {
- return handle.fail({
- errMsg: error?.message,
- })
- }
- const url = URL.createObjectURL(new Blob([value]))
- createDownload(url, `${title}.ics`)
- return handle.success()
-}
+export { addPhoneRepeatCalendar } from '@tarojs/taro-h5'
/**
* 向系统日历添加事件
@@ -117,79 +12,4 @@ export const addPhoneRepeatCalendar: typeof Taro.addPhoneRepeatCalendar = (optio
* @canUse addPhoneCalendar
* @__object [title, startTime, allDay, description, location, endTime, alarm, alarmOffset]
*/
-export const addPhoneCalendar: typeof Taro.addPhoneCalendar = (options) => {
- const methodName = 'addPhoneCalendar'
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `${methodName}:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const {
- title,
- startTime = new Date().getTime(),
- allDay = false,
- description = '',
- location = '',
- endTime,
- alarm = true,
- alarmOffset = 0,
- success,
- fail,
- complete,
- } = options
- const handle = new MethodHandler({ name: methodName, success, fail, complete })
- if (typeof title !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'title',
- correct: 'String',
- wrong: title,
- }),
- })
- }
-
- const start = new Date(startTime)
- const end = new Date(endTime || startTime)
- if (!endTime && allDay) {
- end.setDate(end.getDate() + 1)
- }
- const { error, value } = ics.createEvent({
- title,
- start: parseTime2Array(start, allDay),
- description,
- location,
- end: parseTime2Array(end, allDay),
- alarms: alarm
- ? [
- {
- action: 'display',
- description,
- trigger: {
- before: true,
- seconds: alarmOffset,
- },
- },
- ]
- : [],
- })
- if (error || !value) {
- return handle.fail({
- errMsg: error?.message,
- })
- }
- const url = URL.createObjectURL(new Blob([value]))
- createDownload(url, `${title}.ics`)
- return handle.success()
-}
-
-function parseTime2Array (time: Date, allDay = false): DateArray {
- const t = new Date(time)
- const timeArr: DateArray = [t.getFullYear(), t.getMonth() + 1, t.getDate()]
- if (!allDay) {
- timeArr.push(t.getHours(), t.getMinutes())
- }
- return timeArr
-}
+export { addPhoneCalendar } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/device/clipboard.ts b/packages/taro-mpharmony/src/api/device/clipboard.ts
index 8f68dcc9e7a7..13130e977f96 100644
--- a/packages/taro-mpharmony/src/api/device/clipboard.ts
+++ b/packages/taro-mpharmony/src/api/device/clipboard.ts
@@ -4,65 +4,13 @@
* setClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/setClipBoardData
* getClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/getClipBoardData
*/
-
-import Taro from '@tarojs/api'
-import { isFunction } from '@tarojs/shared'
-
-import { MethodHandler } from '../../utils/handler'
-import { getStorageSync, setStorage, setStorageSync } from '../storage/index'
-import { showToast } from '../ui/interaction'
-
-const CLIPBOARD_STORAGE_NAME = 'taro_clipboard'
-
-document.addEventListener('copy', () => {
- setStorage({
- key: CLIPBOARD_STORAGE_NAME,
- data: window.getSelection()?.toString(),
- }).catch((e) => {
- console.error(e)
- })
-})
-
/**
* 设置系统剪贴板的内容
*
* @canUse setClipboardData
* @__object [data]
*/
-export const setClipboardData: typeof Taro.setClipboardData = async ({ data, success, fail, complete }) => {
- const handle = new MethodHandler({ name: 'setClipboardData', success, fail, complete })
- try {
- setStorageSync(CLIPBOARD_STORAGE_NAME, data)
- /**
- * 已于 iPhone 6s Plus iOS 13.1.3 上的 Safari 测试通过
- * iOS < 10 的系统可能无法使用编程方式访问剪贴板,参考:
- * https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios/34046084
- */
- if (isFunction(document.execCommand)) {
- const textarea = document.createElement('textarea')
- textarea.readOnly = true
- textarea.value = data
- textarea.style.position = 'absolute'
- textarea.style.width = '100px'
- textarea.style.left = '-10000px'
- document.body.appendChild(textarea)
- textarea.select()
- textarea.setSelectionRange(0, textarea.value.length)
- document.execCommand('copy')
- document.body.removeChild(textarea)
- } else {
- throw new Error("Unsupported Function: 'document.execCommand'.")
- }
- showToast({
- title: '内容已复制',
- icon: 'none',
- duration: 1500
- })
- return handle.success()
- } catch (e) {
- return handle.fail({ errMsg: e.message })
- }
-}
+export { setClipboardData } from '@tarojs/taro-h5'
/**
* 获取系统剪贴板的内容
@@ -70,17 +18,4 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, suc
* @canUse getClipboardData
* @__success [data]
*/
-export const getClipboardData: typeof Taro.getClipboardData = async ({ success, fail, complete } = {}) => {
- const handle = new MethodHandler({
- name: 'getClipboardData',
- success,
- fail,
- complete,
- })
- try {
- const data: string = getStorageSync(CLIPBOARD_STORAGE_NAME)
- return handle.success({ data })
- } catch (e) {
- return handle.fail({ errMsg: e.message })
- }
-}
+export { getClipboardData } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/device/motion.ts b/packages/taro-mpharmony/src/api/device/motion.ts
index c5cc6b2a4198..6e722bfb67fa 100644
--- a/packages/taro-mpharmony/src/api/device/motion.ts
+++ b/packages/taro-mpharmony/src/api/device/motion.ts
@@ -1,40 +1,9 @@
-import Taro from '@tarojs/api'
-
-import { throttle } from '../../utils'
-import { CallbackManager, MethodHandler } from '../../utils/handler'
-
-const callbackManager = new CallbackManager()
-let deviceMotionListener
-
-const INTERVAL_MAP = {
- game: {
- interval: 20,
- frequency: 50,
- },
- ui: {
- interval: 60,
- frequency: 16.67,
- },
- normal: {
- interval: 200,
- frequency: 5,
- },
-}
-
/**
* 停止监听设备方向的变化。
*
* @canUse stopDeviceMotionListening
*/
-export const stopDeviceMotionListening: typeof Taro.stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
- const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete })
- try {
- window.removeEventListener('deviceorientation', deviceMotionListener, true)
- return handle.success()
- } catch (e) {
- return handle.fail({ errMsg: e.message })
- }
-}
+export { stopDeviceMotionListening } from '@tarojs/taro-h5'
/**
* 开始监听设备方向的变化。
@@ -42,35 +11,7 @@ export const stopDeviceMotionListening: typeof Taro.stopDeviceMotionListening =
* @canUse startDeviceMotionListening
* @__object [interval[game, ui, normal]]
*/
-export const startDeviceMotionListening: typeof Taro.startDeviceMotionListening = ({
- interval = 'normal',
- success,
- fail,
- complete,
-} = {}) => {
- const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete })
- try {
- const intervalObj = INTERVAL_MAP[interval]
- if (window.DeviceOrientationEvent) {
- if (deviceMotionListener) {
- stopDeviceMotionListening()
- }
- deviceMotionListener = throttle((evt: DeviceOrientationEvent) => {
- callbackManager.trigger({
- alpha: evt.alpha,
- beta: evt.beta,
- gamma: evt.gamma,
- })
- }, intervalObj.interval)
- window.addEventListener('deviceorientation', deviceMotionListener, true)
- } else {
- throw new Error('deviceMotion is not supported')
- }
- return handle.success()
- } catch (e) {
- return handle.fail({ errMsg: e.message })
- }
-}
+export { startDeviceMotionListening } from '@tarojs/taro-h5'
/**
* 监听设备方向变化事件。
@@ -78,15 +19,11 @@ export const startDeviceMotionListening: typeof Taro.startDeviceMotionListening
* @canUse onDeviceMotionChange
* @__callback [alpha, beta, gamma]
*/
-export const onDeviceMotionChange: typeof Taro.onDeviceMotionChange = (callback) => {
- callbackManager.add(callback)
-}
+export { onDeviceMotionChange } from '@tarojs/taro-h5'
/**
* 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。
*
* @canUse offDeviceMotionChange
*/
-export const offDeviceMotionChange: typeof Taro.offDeviceMotionChange = (callback) => {
- callbackManager.remove(callback)
-}
+export { offDeviceMotionChange } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/device/network.ts b/packages/taro-mpharmony/src/api/device/network.ts
index 92fa4312d35b..537f7698d260 100644
--- a/packages/taro-mpharmony/src/api/device/network.ts
+++ b/packages/taro-mpharmony/src/api/device/network.ts
@@ -1,74 +1,10 @@
-import Taro from '@tarojs/api'
-
-import { CallbackManager, MethodHandler } from '../../utils/handler'
-
-function getConnection () {
- // @ts-ignore
- return navigator.connection || navigator.mozConnection || navigator.webkitConnection || navigator.msConnection
-}
-
/**
* 获取网络类型
*
* @canUse getNetworkType
* @__success [networkType[wifi, 2g, 3g, 4g, 5g, unknown, none]]
*/
-export const getNetworkType: typeof Taro.getNetworkType = (options = {}) => {
- const connection = getConnection()
- const { success, fail, complete } = options
- const handle = new MethodHandler({
- name: 'getNetworkType',
- success,
- fail,
- complete,
- })
-
- let networkType: keyof Taro.getNetworkType.NetworkType = 'unknown'
- // 浏览器不支持获取网络状态
- if (!connection) {
- return handle.success({ networkType })
- }
-
- // Supports only the navigator.connection.type value which doesn't match the latest spec.
- // https://www.davidbcalhoun.com/2010/using-navigator-connection-android/
- if (!isNaN(Number(connection.type))) {
- switch (connection.type) {
- // @ts-ignore
- case connection.WIFI:
- networkType = 'wifi'
- break
- // @ts-ignore
- case connection.CELL_3G:
- networkType = '3g'
- break
- // @ts-ignore
- case connection.CELL_2G:
- networkType = '2g'
- break
- default:
- // ETHERNET, UNKNOWN
- networkType = 'unknown'
- }
- } else if (connection.type) {
- // @ts-ignore
- networkType = connection.type // Only supports the type value.
- // @ts-ignore
- } else if (connection.effectiveType) {
- // @ts-ignore
- networkType = connection.effectiveType
- }
-
- return handle.success({ networkType })
-}
-
-const networkStatusManager = new CallbackManager()
-
-const networkStatusListener = async () => {
- const { networkType } = await getNetworkType()
- const isConnected = networkType !== 'none'
- const obj = { isConnected, networkType }
- networkStatusManager.trigger(obj)
-}
+export { getNetworkType } from '@tarojs/taro-h5'
/**
* 在最近的八次网络请求中, 出现下列三个现象之一则判定弱网。
@@ -87,13 +23,7 @@ export { onNetworkWeakChange } from '@tarojs/taro-h5'
* @canUse onNetworkStatusChange
* @__success [isConnected, networkType[wifi, 2g, 3g, 4g, 5g, unknown, none]]
*/
-export const onNetworkStatusChange: typeof Taro.onNetworkStatusChange = (callback) => {
- networkStatusManager.add(callback)
- const connection = getConnection()
- if (connection && networkStatusManager.count() === 1) {
- connection.addEventListener('change', networkStatusListener)
- }
-}
+export { onNetworkStatusChange } from '@tarojs/taro-h5'
/**
* 取消监听弱网状态变化事件
@@ -107,18 +37,7 @@ export { offNetworkWeakChange } from '@tarojs/taro-h5'
*
* @canUse offNetworkStatusChange
*/
-export const offNetworkStatusChange: typeof Taro.offNetworkStatusChange = (callback) => {
- // 取消监听网络状态变化事件,参数为空,则取消所有的事件监听。
- if (callback) {
- networkStatusManager.remove(callback)
- } else {
- networkStatusManager.removeAll()
- }
- const connection = getConnection()
- if (connection && networkStatusManager.count() === 0) {
- connection.removeEventListener('change', networkStatusListener)
- }
-}
+export { offNetworkStatusChange } from '@tarojs/taro-h5'
/**
* 获取局域网IP地址
diff --git a/packages/taro-mpharmony/src/api/framework/index.ts b/packages/taro-mpharmony/src/api/framework/index.ts
index 6ae633477ceb..b75cfd056d67 100644
--- a/packages/taro-mpharmony/src/api/framework/index.ts
+++ b/packages/taro-mpharmony/src/api/framework/index.ts
@@ -1,10 +1,3 @@
-import Taro from '@tarojs/api'
-
-export const getApp: typeof Taro.getApp = function () {
- return Taro.getCurrentInstance().app as unknown as T
-}
-
export { getCurrentPages } from '@tarojs/router'
-
-// 自定义组件
-export const getCurrentInstance = Taro.getCurrentInstance
+export { getApp } from '@tarojs/taro-h5'
+export { getCurrentInstance } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/location/chooseLocation.ts b/packages/taro-mpharmony/src/api/location/chooseLocation.ts
index fcb2195e7d6e..fb182ae3391b 100644
--- a/packages/taro-mpharmony/src/api/location/chooseLocation.ts
+++ b/packages/taro-mpharmony/src/api/location/chooseLocation.ts
@@ -1,73 +1,3 @@
-import './style.scss'
-
-import Taro from '@tarojs/api'
-import { stringify } from 'query-string'
-
-import { MethodHandler } from '../../utils/handler'
-
-let container: HTMLDivElement | null = null
-function createLocationChooser (handler, mapOpt: Taro.chooseLocation.Option['mapOpts'] = {}) {
- const { key = LOCATION_APIKEY, referer = 'myapp', ...opts } = mapOpt
- const query = {
- key,
- type: 1,
- referer,
- ...opts,
- }
- if (!container) {
- const html = `
-
- `
- container = document.createElement('div')
- container.innerHTML = html
- }
- const main: HTMLDivElement = container.querySelector('.taro_choose_location') as HTMLDivElement
-
- function show () {
- setTimeout(() => {
- main.style.top = '0'
- })
- }
-
- function hide () {
- main.style.top = '100%'
- }
-
- function back () {
- hide()
- handler({ errMsg: 'cancel' })
- }
-
- function submit () {
- hide()
- handler()
- }
-
- function remove () {
- container?.remove()
- container = null
- window.removeEventListener('popstate', back)
- }
-
- container.querySelector('.taro_choose_location_back')?.addEventListener('click', back)
- container.querySelector('.taro_choose_location_submit')?.addEventListener('click', submit)
-
- window.addEventListener('popstate', back)
-
- return {
- show,
- remove,
- container,
- }
-}
-
/**
* 打开地图选择位置。
*
@@ -75,44 +5,4 @@ function createLocationChooser (handler, mapOpt: Taro.chooseLocation.Option['map
* @__object [mapOpts]
* @__success [address, latitude, longitude, name]
*/
-export const chooseLocation: typeof Taro.chooseLocation = ({ success, fail, complete, mapOpts } = {}) => {
- const handle = new MethodHandler({ name: 'chooseLocation', success, fail, complete })
- return new Promise((resolve, reject) => {
- const chooseLocation: Partial = {}
- const onMessage = (event) => {
- // 接收位置信息,用户选择确认位置点后选点组件会触发该事件,回传用户的位置信息
- const loc = event.data
-
- // 防止其他应用也会向该页面 post 信息,需判断 module 是否为'locationPicker'
- if (!loc || loc.module !== 'locationPicker') return
-
- chooseLocation.name = loc.poiname
- chooseLocation.address = loc.poiaddress
- chooseLocation.latitude = loc.latlng.lat
- chooseLocation.longitude = loc.latlng.lng
- }
-
- const chooser = createLocationChooser(
- (res) => {
- window.removeEventListener('message', onMessage, false)
- setTimeout(() => {
- chooser.remove()
- }, 300)
- if (res) {
- return handle.fail(res, { resolve, reject })
- } else {
- if (chooseLocation.latitude && chooseLocation.longitude) {
- return handle.success(chooseLocation, { resolve, reject })
- } else {
- return handle.fail({}, { resolve, reject })
- }
- }
- },
- mapOpts
- )
-
- document.body.appendChild(chooser.container)
- window.addEventListener('message', onMessage, false)
- chooser.show()
- })
-}
+export { chooseLocation } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/location/openLocation.ts b/packages/taro-mpharmony/src/api/location/openLocation.ts
index 396e8c6b878e..83c6ee010e8a 100644
--- a/packages/taro-mpharmony/src/api/location/openLocation.ts
+++ b/packages/taro-mpharmony/src/api/location/openLocation.ts
@@ -1,83 +1,7 @@
-
-import './style.scss'
-
-import Taro from '@tarojs/api'
-import { shouldBeObject } from 'src/utils'
-
-import { MethodHandler } from '../../utils/handler'
-
-let container: HTMLDivElement | null = null
-function createContainer (options: Taro.openLocation.Option) {
- const key = LOCATION_APIKEY
- const { longitude, latitude, name, address } = options
- if (!container) {
- const html = `
-
- `
- container = document.createElement('div')
- container.innerHTML = html
- }
- const main: HTMLDivElement = container.querySelector('.taro_choose_location') as HTMLDivElement
-
- function show () {
- main.style.top = '0'
- }
-
- function hide () {
- main.style.top = '100%'
- remove()
- }
-
- function remove () {
- container?.remove()
- container = null
- }
-
- container.querySelector('.taro_choose_location_back')?.addEventListener('click', hide)
-
- return {
- show,
- container,
- }
-}
-
/**
* 使用微信内置地图查看位置(暂不支持scale入参)
*
* @canUse openLocation
* @__object [latitude, longitude, address, name]
*/
-export const openLocation: typeof Taro.openLocation = (options) => {
- const name = 'openLocation'
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `${name}:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
- const {
- success,
- fail,
- complete
- } = options as Exclude
- const handle = new MethodHandler({ name, success, fail, complete })
-
- return new Promise((resolve, reject) => {
- const dispalyLoc = createContainer(options)
- document.body.appendChild(dispalyLoc.container)
- dispalyLoc.show()
- document.querySelector('iframe')?.addEventListener('load', function () {
- handle.success({}, { resolve, reject })
- })
- document.querySelector('iframe')?.addEventListener('error', function () {
- handle.fail({}, { resolve, reject })
- })
- })
-}
+export { openLocation } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/location/style.scss b/packages/taro-mpharmony/src/api/location/style.scss
deleted file mode 100644
index 7ad28c6b8857..000000000000
--- a/packages/taro-mpharmony/src/api/location/style.scss
+++ /dev/null
@@ -1,74 +0,0 @@
-.taro_choose_location {
- display: flex;
- position: fixed;
- top: 100%;
- z-index: 1;
- flex-direction: column;
- width: 100%;
- height: 100%;
- background-color: #fff;
- transition: ease top 0.3s;
-
- &_bar {
- display: flex;
- flex: 0 60px;
- height: 60px;
- background-color: #ededed;
- color: #090909;
- align-items: center;
- }
-
- &_back {
- position: relative;
- flex: 0 40px;
- margin-left: 10px;
- width: 25px;
- height: 30px;
-
- &::before {
- display: block;
- position: absolute;
- left: 0;
- top: 0;
- border: solid 15px;
- border-color: transparent #090909 transparent transparent;
- width: 0;
- height: 0;
- content: "";
- }
-
- &::after {
- display: block;
- position: absolute;
- left: 3px;
- top: 0;
- border: solid 15px;
- border-color: transparent #ededed transparent transparent;
- width: 0;
- height: 0;
- content: "";
- }
- }
-
- &_title {
- flex: 1;
- padding-left: 30px;
- line-height: 60px;
- }
-
- &_submit {
- margin-right: 25px;
- padding: 0;
- border: none;
- width: 75px;
- height: 40px;
- background-color: #08bf62;
- line-height: 40px;
- font-size: 20px;
- color: #fff;
- }
-
- &_frame {
- flex: 1;
- }
-}
\ No newline at end of file
diff --git a/packages/taro-mpharmony/src/api/media/background-audio/BackgroundAudioManager.ts b/packages/taro-mpharmony/src/api/media/background-audio/BackgroundAudioManager.ts
deleted file mode 100644
index 9d4e4bae45e7..000000000000
--- a/packages/taro-mpharmony/src/api/media/background-audio/BackgroundAudioManager.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import Taro from '@tarojs/api'
-
-import { permanentlyNotSupport } from '../../../utils'
-import { CallbackManager } from '../../../utils/handler'
-
-/**
- * BackgroundAudioManager 实例
- *
- * @canUse BackgroundAudioManager
- * @__class
- * [play, pause, seek, stop, onCanplay, onWaiting, onError, onPlay, onPause, onSeeking,\
- * onSeeked, onEnded, onStop, onTimeUpdate]
- */
-export class BackgroundAudioManager implements Taro.BackgroundAudioManager {
- Instance?: HTMLAudioElement
- errorStack: CallbackManager
- stopStack: CallbackManager
- __startTime = 0
-
- constructor () {
- this.Instance = new Audio()
- this.errorStack = new CallbackManager()
- this.stopStack = new CallbackManager()
- this.Instance.autoplay = true
- this.onPlay(() => {
- if (this.currentTime !== this.startTime) {
- this.seek(this.startTime)
- }
- })
- }
-
- set src (e) {
- this.setProperty('src', e)
- }
-
- get src () {
- return this.Instance?.src || ''
- }
-
- set startTime (e) {
- this.__startTime = e
- }
-
- get startTime () {
- return this.__startTime || 0
- }
-
- set title (e) {
- this.dataset('title', e)
- }
-
- get title () {
- return this.Instance?.dataset.title || ''
- }
-
- set epname (e) {
- this.dataset('epname', e)
- }
-
- get epname () {
- return this.Instance?.dataset.epname || ''
- }
-
- set singer (e) {
- this.dataset('singer', e)
- }
-
- get singer () {
- return this.Instance?.dataset.singer || ''
- }
-
- set coverImgUrl (e) {
- this.dataset('coverImgUrl', e)
- }
-
- get coverImgUrl () {
- return this.Instance?.dataset.coverImgUrl || ''
- }
-
- set webUrl (e) {
- this.dataset('webUrl', e)
- }
-
- get webUrl () {
- return this.Instance?.dataset.webUrl || ''
- }
-
- set protocol (e) {
- this.dataset('protocol', e)
- }
-
- get protocol () {
- return this.Instance?.dataset.protocol || ''
- }
-
- set playbackRate (e) {
- this.setProperty('playbackRate', e)
- }
-
- get playbackRate () {
- return this.Instance?.playbackRate || 0
- }
-
- get duration () {
- return this.Instance?.duration || 0
- }
-
- get currentTime () {
- return this.Instance?.currentTime || 0
- }
-
- get paused () {
- return this.Instance?.paused || false
- }
-
- get buffered () {
- return this.Instance?.buffered.length || 0
- }
-
- set referrerPolicy (e) {
- this.Instance?.setAttribute('referrerpolicy', e)
- }
-
- get referrerPolicy () {
- return this.Instance?.getAttribute('referrerpolicy') || 'origin'
- }
-
- private setProperty (key: string, value: unknown) {
- if (this.Instance) {
- this.Instance[key] = value
- }
- }
-
- private dataset (key: string, value: string) {
- if (this.Instance) {
- this.Instance.dataset[key] = value
- }
- }
-
- play = () => this.Instance?.play()
-
- pause = () => this.Instance?.pause()
-
- seek = (position: number) => {
- if (this.Instance) {
- this.Instance.currentTime = position
- }
- }
-
- stop = () => {
- this.pause()
- this.seek(0)
- this.stopStack.trigger()
- }
-
- onCanplay = (callback = () => {}) => this.Instance?.addEventListener('canplay', callback)
- onWaiting = (callback = () => {}) => this.Instance?.addEventListener('waiting', callback)
- onError = (callback?: (res: Taro.InnerAudioContext.onErrorDetail) => void) => this.errorStack.add(callback)
- onPlay = (callback = () => {}) => this.Instance?.addEventListener('play', callback)
- onPause = (callback = () => {}) => this.Instance?.addEventListener('pause', callback)
- onSeeking = (callback = () => {}) => this.Instance?.addEventListener('seeking', callback)
- onSeeked = (callback = () => {}) => this.Instance?.addEventListener('seeked', callback)
-
- onEnded = (callback = () => {}) => this.Instance?.addEventListener('ended', callback)
- onStop = (callback = () => {}) => this.stopStack.add(callback)
- onTimeUpdate = (callback = () => {}) => this.Instance?.addEventListener('timeupdate', callback)
- onPrev = permanentlyNotSupport('BackgroundAudioManager.onPrev')
- onNext = permanentlyNotSupport('BackgroundAudioManager.onNext')
-
- offCanplay = (callback = () => {}) => this.Instance?.removeEventListener('canplay', callback)
- offWaiting = (callback = () => {}) => this.Instance?.removeEventListener('waiting', callback)
- offError = (callback = () => {}) => this.errorStack.remove(callback)
- offPlay = (callback = () => {}) => this.Instance?.removeEventListener('play', callback)
- offPause = (callback = () => {}) => this.Instance?.removeEventListener('pause', callback)
- offSeeking = (callback = () => {}) => this.Instance?.removeEventListener('seeking', callback)
- offSeeked = (callback = () => {}) => this.Instance?.removeEventListener('seeked', callback)
-
- offEnded = (callback = () => {}) => this.Instance?.removeEventListener('ended', callback)
- offStop = (callback = () => {}) => this.stopStack.remove(callback)
- offTimeUpdate = (callback = () => {}) => this.Instance?.removeEventListener('timeupdate', callback)
- offPrev = permanentlyNotSupport('BackgroundAudioManager.offPrev')
- offNext = permanentlyNotSupport('BackgroundAudioManager.offNext')
-}
diff --git a/packages/taro-mpharmony/src/api/media/background-audio/index.ts b/packages/taro-mpharmony/src/api/media/background-audio/index.ts
index 1d6b4a05719b..f0e6aed43d69 100644
--- a/packages/taro-mpharmony/src/api/media/background-audio/index.ts
+++ b/packages/taro-mpharmony/src/api/media/background-audio/index.ts
@@ -1,5 +1,3 @@
-import { BackgroundAudioManager } from './BackgroundAudioManager'
-
/**
* 停止播放音乐
*
@@ -61,4 +59,13 @@ export { getBackgroundAudioPlayerState } from '@tarojs/taro-h5'
*
* @canUse getBackgroundAudioManager
*/
-export const getBackgroundAudioManager = () => new BackgroundAudioManager()
+export { getBackgroundAudioManager } from '@tarojs/taro-h5'
+
+/**
+ * BackgroundAudioManager 实例
+ *
+ * @canUse BackgroundAudioManager
+ * @__class
+ * [play, pause, seek, stop, onCanplay, onWaiting, onError, onPlay, onPause, onSeeking,\
+ * onSeeked, onEnded, onStop, onTimeUpdate]
+ */
\ No newline at end of file
diff --git a/packages/taro-mpharmony/src/api/media/video/index.ts b/packages/taro-mpharmony/src/api/media/video/index.ts
index db6d23e3e82e..863e0c463088 100644
--- a/packages/taro-mpharmony/src/api/media/video/index.ts
+++ b/packages/taro-mpharmony/src/api/media/video/index.ts
@@ -1,7 +1,3 @@
-import Taro from '@tarojs/api'
-
-import { findDOM } from '../../../utils'
-
// 视频
export * from './getVideoInfo'
export * from './openVideoEditor'
@@ -12,14 +8,9 @@ export * from './saveVideoToPhotosAlbum'
*
* @canUse createVideoContext
*/
-export const createVideoContext: typeof Taro.createVideoContext = (id, inst) => {
- const el = findDOM(inst) as HTMLVideoElement
- // TODO HTMLVideoElement to VideoContext
- return el?.querySelector(`taro-video-core[id=${id}]`) as unknown as Taro.VideoContext
-}
-
export * from './chooseVideo'
export * from './compressVideo'
+export { createVideoContext } from '@tarojs/taro-h5'
/**
* 拍摄视频或从手机相册中选视频。
diff --git a/packages/taro-mpharmony/src/api/network/websocket/index.ts b/packages/taro-mpharmony/src/api/network/websocket/index.ts
index f9b699728726..0f36c00f6552 100644
--- a/packages/taro-mpharmony/src/api/network/websocket/index.ts
+++ b/packages/taro-mpharmony/src/api/network/websocket/index.ts
@@ -1,54 +1,37 @@
-import { getParameterError, shouldBeObject } from '../../../utils'
-import { MethodHandler } from '../../../utils/handler'
-import { SocketTask } from './socketTask'
-
-let socketTasks: SocketTask[] = []
-let socketsCounter = 1
-
/**
* 通过 WebSocket 连接发送数据
*
* @canNotUse sendSocketMessage
*/
-export function sendSocketMessage () {
- console.warn('Deprecated.Please use socketTask.send instead.')
-}
+export { sendSocketMessage } from '@tarojs/taro-h5'
/**
* 监听 WebSocket 连接打开事件
*
* @canNotUse onSocketOpen
*/
-export function onSocketOpen () {
- console.warn('Deprecated.Please use socketTask.onOpen instead.')
-}
+export { onSocketOpen } from '@tarojs/taro-h5'
/**
* 监听 WebSocket 接受到服务器的消息事件
*
* @canNotUse onSocketMessage
*/
-export function onSocketMessage () {
- console.warn('Deprecated.Please use socketTask.onMessage instead.')
-}
+export { onSocketMessage } from '@tarojs/taro-h5'
/**
* 监听 WebSocket 错误事件
*
* @canNotUse onSocketError
*/
-export function onSocketError () {
- console.warn('Deprecated.Please use socketTask.onError instead.')
-}
+export { onSocketError } from '@tarojs/taro-h5'
/**
* 监听 WebSocket 连接关闭事件
*
* @canNotUse onSocketClose
*/
-export function onSocketClose () {
- console.warn('Deprecated.Please use socketTask.onClose instead.')
-}
+export { onSocketClose } from '@tarojs/taro-h5'
/**
* 创建一个 WebSocket 连接
@@ -56,79 +39,18 @@ export function onSocketClose () {
* @canUse connectSocket
* @__object [url, header, protocols, tcpNoDelay]
*/
-export function connectSocket (options?: Taro.connectSocket.Option) {
- const name = 'connectSocket'
-
- return new Promise((resolve, reject) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `${name}:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return reject(res)
- }
- const { url, protocols, success, fail, complete } = options as Exclude
- const handle = new MethodHandler<{
- socketTaskId?: number
- }>({ name, success, fail, complete })
-
- // options.url must be String
- if (typeof url !== 'string') {
- return handle.fail(
- {
- errMsg: getParameterError({
- para: 'url',
- correct: 'String',
- wrong: url,
- }),
- },
- { resolve, reject }
- )
- }
-
- // options.url must be invalid
- if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
- return handle.fail(
- {
- errMsg: `request:fail invalid url "${url}"`,
- },
- { resolve, reject }
- )
- }
-
- // protocols must be array
- const _protocols = Array.isArray(protocols) ? protocols : null
-
- // 2 connection at most
- if (socketTasks.length >= 5) {
- return handle.fail(
- {
- errMsg: '同时最多发起 5 个 socket 请求,更多请参考文档。',
- },
- { resolve, reject }
- )
- }
-
- const task = new SocketTask(url, _protocols)
- task._destroyWhenClose = function () {
- socketTasks = socketTasks.filter((socketTask) => socketTask !== this)
- }
- socketTasks.push(task)
-
- handle.success({
- socketTaskId: socketsCounter++,
- })
-
- return resolve(task)
- })
-}
+export { connectSocket } from '@tarojs/taro-h5'
/**
* 关闭 WebSocket 连接
*
* @canNotUse closeSocket
*/
-export function closeSocket () {
- console.warn('Deprecated.Please use socketTask.close instead.')
-}
+export { closeSocket } from '@tarojs/taro-h5'
+/**
+ * WebSocket 任务
+ *
+ * @canUse SocketTask
+ * @__class [send, close, onOpen, onClose, onError, onMessage]
+ */
\ No newline at end of file
diff --git a/packages/taro-mpharmony/src/api/network/websocket/socketTask.ts b/packages/taro-mpharmony/src/api/network/websocket/socketTask.ts
deleted file mode 100644
index 43a58255c01f..000000000000
--- a/packages/taro-mpharmony/src/api/network/websocket/socketTask.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import Taro from '@tarojs/api'
-import { isFunction } from '@tarojs/shared'
-
-/**
- * WebSocket 任务
- *
- * @canUse SocketTask
- * @__class [send, close, onOpen, onClose, onError, onMessage]
- */
-export class SocketTask {
- ws: WebSocket
- CONNECTING: number
- OPEN: number
- CLOSING: number
- CLOSED: number
- closeDetail: { code: any, reason: any }
- _destroyWhenClose?: () => void
-
- constructor (url, protocols) {
- if (protocols && protocols.length) {
- this.ws = new WebSocket(url, protocols)
- } else {
- this.ws = new WebSocket(url)
- }
- this.CONNECTING = 0
- this.OPEN = 1
- this.CLOSING = 2
- this.CLOSED = 3
- }
-
- get readyState () {
- return this.ws.readyState
- }
-
- send (opts: Partial = {}) {
- if (typeof opts !== 'object' || !opts) opts = {}
-
- const { data = '', success, fail, complete } = opts
-
- if (this.readyState !== 1) {
- const res = { errMsg: 'SocketTask.send:fail SocketTask.readState is not OPEN' }
- console.error(res.errMsg)
- isFunction(fail) && fail(res)
- isFunction(complete) && complete(res)
- return Promise.reject(res)
- }
-
- this.ws.send(data)
-
- const res = { errMsg: 'sendSocketMessage:ok' }
- isFunction(success) && success(res)
- isFunction(complete) && complete(res)
- return Promise.resolve(res)
- }
-
- close (opts: Partial = {}) {
- if (typeof opts !== 'object' || !opts) opts = {}
-
- const { code = 1000, reason = 'server complete,close', success, complete } = opts
-
- this.closeDetail = { code, reason }
- // 主动断开时需要重置链接数
- this._destroyWhenClose && this._destroyWhenClose()
- this.ws.close()
-
- const res = { errMsg: 'closeSocket:ok' }
- isFunction(success) && success(res)
- isFunction(complete) && complete(res)
- return Promise.resolve(res)
- }
-
- onOpen (func) {
- this.ws.onopen = func
- }
-
- onMessage (func) {
- this.ws.onmessage = func
- }
-
- onClose (func) {
- this.ws.onclose = () => {
- // 若服务器方断掉也需要重置链接数
- this._destroyWhenClose && this._destroyWhenClose()
- func(this.closeDetail || { code: 1006, reason: 'abnormal closure' })
- }
- }
-
- onError (func) {
- this.ws.onerror = func
- }
-}
diff --git a/packages/taro-mpharmony/src/api/storage/index.ts b/packages/taro-mpharmony/src/api/storage/index.ts
index 214ba56a3fef..b286d3bfac30 100644
--- a/packages/taro-mpharmony/src/api/storage/index.ts
+++ b/packages/taro-mpharmony/src/api/storage/index.ts
@@ -1,50 +1,10 @@
-import Taro from '@tarojs/api'
-
-import { getParameterError, shouldBeObject } from '../../utils'
-import { MethodHandler } from '../../utils/handler'
-
-function getItem (key) {
- let item
- try {
- item = JSON.parse(localStorage.getItem(key) || '')
- } catch (e) { } // eslint-disable-line no-empty
-
- // 只返回使用 Taro.setStorage API 存储的数据
- if (item && typeof item === 'object' && item.hasOwnProperty('data')) {
- return { result: true, data: item.data }
- } else {
- return { result: false }
- }
-}
-
/**
* Taro.setStorage 的同步版本
*
* @canUse setStorageSync
* @__object [key, data]
*/
-export const setStorageSync: typeof Taro.setStorageSync = (key, data = '') => {
- if (typeof key !== 'string') {
- console.error(
- getParameterError({
- name: 'setStorage',
- correct: 'String',
- wrong: key,
- })
- )
- return
- }
-
- const type = typeof data
- let obj = {}
-
- if (type === 'symbol') {
- obj = { data: '' }
- } else {
- obj = { data }
- }
- localStorage.setItem(key, JSON.stringify(obj))
-}
+export { setStorageSync } from '@tarojs/taro-h5'
/**
* 将数据存储在本地缓存中指定的 key 中
@@ -52,31 +12,7 @@ export const setStorageSync: typeof Taro.setStorageSync = (key, data = '') => {
* @canUse setStorage
* @__object [data, key]
*/
-export const setStorage: typeof Taro.setStorage = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `setStorage:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { key, data, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'setStorage', success, fail, complete })
-
- if (typeof key !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'key',
- correct: 'String',
- wrong: key,
- }),
- })
- }
-
- setStorageSync(key, data)
- return handle.success()
-}
+export { setStorage } from '@tarojs/taro-h5'
/**
* 根据 URL 销毁存在内存中的数据
@@ -90,20 +26,7 @@ export { revokeBufferURL } from '@tarojs/taro-h5'
*
* @canUse removeStorageSync
*/
-export const removeStorageSync: typeof Taro.removeStorageSync = (key: string) => {
- if (typeof key !== 'string') {
- console.error(
- getParameterError({
- name: 'removeStorage',
- correct: 'String',
- wrong: key,
- })
- )
- return
- }
-
- localStorage.removeItem(key)
-}
+export { removeStorageSync } from '@tarojs/taro-h5'
/**
* 从本地缓存中移除指定 key
@@ -111,53 +34,14 @@ export const removeStorageSync: typeof Taro.removeStorageSync = (key: string) =>
* @canUse removeStorage
* @__object [key]
*/
-export const removeStorage: typeof Taro.removeStorage = (options: Taro.removeStorage.Option) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `removeStorage:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
- const { key, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'removeStorage', success, fail, complete })
-
- if (typeof key !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'key',
- correct: 'String',
- wrong: key,
- }),
- })
- }
-
- removeStorageSync(key)
- return handle.success()
-}
+export { removeStorage } from '@tarojs/taro-h5'
/**
* Taro.getStorage 的同步版本
*
* @canUse getStorageSync
*/
-export const getStorageSync: typeof Taro.getStorageSync = (key) => {
- if (typeof key !== 'string') {
- console.error(
- getParameterError({
- name: 'getStorageSync',
- correct: 'String',
- wrong: key,
- })
- )
- return
- }
-
- const res = getItem(key)
- if (res.result) return res.data
-
- return ''
-}
+export { getStorageSync } from '@tarojs/taro-h5'
/**
* Taro.getStorageInfo 的同步版本
@@ -165,14 +49,7 @@ export const getStorageSync: typeof Taro.getStorageSync = (key) => {
* @canUse getStorageInfoSync
* @__return [currentSize, keys, limitSize]
*/
-export const getStorageInfoSync: typeof Taro.getStorageInfoSync = () => {
- const res: Taro.getStorageInfoSync.Option = {
- keys: Object.keys(localStorage),
- limitSize: NaN,
- currentSize: NaN,
- }
- return res
-}
+export { getStorageInfoSync } from '@tarojs/taro-h5'
/**
* 异步获取当前storage的相关信息
@@ -180,15 +57,7 @@ export const getStorageInfoSync: typeof Taro.getStorageInfoSync = () => {
* @canUse getStorageInfo
* @__success [currentSize, keys, limitSize]
*/
-export const getStorageInfo: typeof Taro.getStorageInfo = ({ success, fail, complete } = {}) => {
- const handle = new MethodHandler({
- name: 'getStorageInfo',
- success,
- fail,
- complete,
- })
- return handle.success(getStorageInfoSync())
-}
+export { getStorageInfo } from '@tarojs/taro-h5'
/**
* 从本地缓存中异步获取指定 key 的内容
@@ -197,42 +66,7 @@ export const getStorageInfo: typeof Taro.getStorageInfo = ({ success, fail, comp
* @__object [key]
* @__success [data]
*/
-export const getStorage: typeof Taro.getStorage = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `getStorage:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { key, success, fail, complete } = options
- const handle = new MethodHandler>({
- name: 'getStorage',
- success,
- fail,
- complete,
- })
-
- if (typeof key !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'key',
- correct: 'String',
- wrong: key,
- }),
- })
- }
-
- const { result, data } = getItem(key)
- if (result) {
- return handle.success({ data })
- } else {
- return handle.fail({
- errMsg: 'data not found',
- })
- }
-}
+export { getStorage } from '@tarojs/taro-h5'
/**
* 根据传入的 buffer 创建一个唯一的 URL 存在内存中
@@ -246,20 +80,14 @@ export { createBufferURL } from '@tarojs/taro-h5'
*
* @canUse clearStorageSync
*/
-export const clearStorageSync: typeof Taro.clearStorageSync = () => {
- localStorage.clear()
-}
+export { clearStorageSync } from '@tarojs/taro-h5'
/**
* 清理本地数据缓存
*
* @canUse clearStorage
*/
-export const clearStorage: typeof Taro.clearStorage = ({ success, fail, complete } = {}) => {
- const handle = new MethodHandler({ name: 'clearStorage', success, fail, complete })
- clearStorageSync()
- return handle.success()
-}
+export { clearStorage } from '@tarojs/taro-h5'
/**
* 创建缓存管理器
diff --git a/packages/taro-mpharmony/src/api/ui/animation/index.ts b/packages/taro-mpharmony/src/api/ui/animation/index.ts
index 7df739578781..5e9024756318 100644
--- a/packages/taro-mpharmony/src/api/ui/animation/index.ts
+++ b/packages/taro-mpharmony/src/api/ui/animation/index.ts
@@ -1,76 +1,3 @@
-import Taro from '@tarojs/api'
-
-/**
- * H5 下的 styleSheet 操作
- * @author leeenx
- */
-class StyleSheet {
- constructor () {
- this.$style = document.createElement('style')
- }
-
- $style?: HTMLStyleElement | null = null
- sheet?: CSSStyleSheet | null = null
-
- appendStyleSheet = () => {
- if (this.$style) {
- const head = document.getElementsByTagName('head')[0]
- this.$style.setAttribute('type', 'text/css')
- this.$style.setAttribute('data-type', 'Taro')
- head.appendChild(this.$style)
- this.sheet = this.$style.sheet
- }
- if (this.sheet && !('insertRule' in this.sheet)) {
- console.warn('当前浏览器不支持 stylesheet.insertRule 接口')
- }
- }
-
- // 添加样式命令
- add = (cssText, index = 0) => {
- if (this.sheet === null) {
- // $style 未插入到 DOM
- this.appendStyleSheet()
- }
- this.sheet?.insertRule(cssText, index)
- }
-}
-
-const styleSheet = new StyleSheet()
-
-// 监听事件
-let TRANSITION_END = 'transitionend'
-let TRANSFORM = 'transform'
-
-const $detect = document.createElement('div')
-$detect.style.cssText =
- '-webkit-animation-name:webkit;-moz-animation-name:moz;-ms-animation-name:ms;animation-name:standard;'
-if ($detect.style['animation-name'] === 'standard') {
- // 支持标准写法
- TRANSITION_END = 'transitionend'
- TRANSFORM = 'transform'
-} else if ($detect.style['-webkit-animation-name'] === 'webkit') {
- // webkit 前缀
- TRANSITION_END = 'webkitTransitionEnd'
- TRANSFORM = '-webkit-transform'
-} else if ($detect.style['-moz-animation-name'] === 'moz') {
- // moz 前缀
- TRANSITION_END = 'mozTransitionEnd'
- TRANSFORM = '-moz-transform'
-} else if ($detect.style['-ms-animation-name'] === 'ms') {
- // ms 前缀
- TRANSITION_END = 'msTransitionEnd'
- TRANSFORM = '-ms-transform'
-}
-
-let animId = 0
-
-interface IAnimationAttr {
- duration: number
- delay: number
- timingFunction: string
- transformOrigin: string
-}
-
/**
* 动画对象
*
@@ -80,330 +7,6 @@ interface IAnimationAttr {
* scale3d, scaleX, scaleY, scaleZ, skew, skewX, skewY, translate, translate3d, translateX,\
* translateY, translateZ, opacity, backgroundColor, width, height, left, right, top, bottom]
*/
-class Animation implements Taro.Animation {
- unit: string
- id: number
- DEFAULT: IAnimationAttr
-
- constructor ({
- duration = 400,
- delay = 0,
- timingFunction = 'linear',
- transformOrigin = '50% 50% 0',
- unit = 'px',
- }: Taro.createAnimation.Option = {}) {
- // 默认值
- this.setDefault(duration, delay, timingFunction, transformOrigin)
- this.unit = unit
- // atom 环境下,animation 属性不会显示,所以要改成 data-animation
- let animAttr = 'animation'
- // 动画 id
- this.id = ++animId
- // 监听事件
- document.body.addEventListener(TRANSITION_END, (e: TransitionEvent) => {
- const target = e.target as HTMLElement
- if (target.getAttribute(animAttr) === null) {
- animAttr = 'data-animation'
- }
- const animData = target.getAttribute(animAttr)
- // 没有动画存在
- if (animData === null) return
- const [animName, animPath] = animData.split('__')
- if (animName === `taro-h5-poly-fill/${this.id}/create-animation`) {
- const [animIndex, __stepIndex = 0] = animPath.split('--')
- const stepIndex = Number(__stepIndex)
- // 动画总的关键帧
- const animStepsCount = this.animationMap[`${animName}__${animIndex}`]
- const animStepsMaxIndex = animStepsCount - 1
- if (stepIndex < animStepsMaxIndex) {
- // 播放下一个关键帧(因为 nerv 和 react 有差异所以 animation & data-animation 都需要写)
- target.setAttribute(animAttr, `${animName}__${animIndex}--${stepIndex + 1}`)
- if (animAttr === 'data-animation') {
- // Nerv 环境,animation & data-animation 双重保险
- target.setAttribute('animation', `${animName}__${animIndex}--${stepIndex + 1}`)
- }
- }
- }
- })
- }
-
- transformUnit (...args) {
- const ret: string[] = []
- args.forEach((each) => {
- ret.push(isNaN(each) ? each : `${each}${this.unit}`)
- })
- return ret
- }
-
- // 设置默认值
- setDefault (duration, delay, timingFunction, transformOrigin) {
- this.DEFAULT = { duration, delay, timingFunction, transformOrigin }
- }
-
- // 属性组合
- rules: { key: string, rule: string }[] = []
- // transform 对象
- transform: { key: string, transform: string }[] = []
- // 组合动画
- steps: string[] = []
- // 动画 map ----- 永久保留
- animationMap = {}
- // animationMap 的长度
- animationMapCount = 0
- // 历史动画
- historyAnimations: { key: string, transform: string }[] = []
- // 历史规则
- historyRules: { key: string, rule: string }[] = []
-
- matrix (a: number, b: number, c: number, d: number, tx: number, ty: number) {
- this.transform.push({ key: 'matrix', transform: `matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})` })
- return this
- }
-
- matrix3d (
- a1: number,
- b1: number,
- c1: number,
- d1: number,
- a2: number,
- b2: number,
- c2: number,
- d2: number,
- a3: number,
- b3: number,
- c3: number,
- d3: number,
- a4: number,
- b4: number,
- c4: number,
- d4: number
- ) {
- this.transform.push({
- key: 'matrix3d',
- transform: `matrix3d(${a1}, ${b1}, ${c1}, ${d1}, ${a2}, ${b2}, ${c2}, ${d2}, ${a3}, ${b3}, ${c3}, ${d3}, ${a4}, ${b4}, ${c4}, ${d4})`,
- })
- return this
- }
-
- rotate (angle: number) {
- this.transform.push({ key: 'rotate', transform: `rotate(${angle}deg)` })
- return this
- }
-
- rotate3d (x: number, y?: number, z?: number, angle?: number) {
- if (typeof y !== 'number') {
- this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x})` })
- } else {
- this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x}, ${y || 0}, ${z || 0}, ${angle || 0}deg)` })
- }
- return this
- }
-
- rotateX (angle) {
- this.transform.push({ key: 'rotateX', transform: `rotateX(${angle}deg)` })
- return this
- }
-
- rotateY (angle) {
- this.transform.push({ key: 'rotateY', transform: `rotateY(${angle}deg)` })
- return this
- }
-
- rotateZ (angle) {
- this.transform.push({ key: 'rotateZ', transform: `rotateZ(${angle}deg)` })
- return this
- }
-
- scale (x: number, y?: number) {
- const scaleY = (typeof y !== 'undefined' && y !== null) ? y : x
- this.transform.push({ key: 'scale', transform: `scale(${x}, ${scaleY})` })
- return this
- }
-
- scale3d (x, y, z) {
- this.transform.push({ key: 'scale3d', transform: `scale3d(${x}, ${y}, ${z})` })
- return this
- }
-
- scaleX (scale) {
- this.transform.push({ key: 'scaleX', transform: `scaleX(${scale})` })
- return this
- }
-
- scaleY (scale) {
- this.transform.push({ key: 'scaleY', transform: `scaleY(${scale})` })
- return this
- }
-
- scaleZ (scale) {
- this.transform.push({ key: 'scaleZ', transform: `scaleZ(${scale})` })
- return this
- }
-
- skew (x, y) {
- this.transform.push({ key: 'skew', transform: `skew(${x}deg, ${y}deg)` })
- return this
- }
-
- skewX (angle) {
- this.transform.push({ key: 'skewX', transform: `skewX(${angle}deg)` })
- return this
- }
-
- skewY (angle) {
- this.transform.push({ key: 'skewY', transform: `skewY(${angle}deg)` })
- return this
- }
-
- translate (x, y) {
- [x, y] = this.transformUnit(x, y)
- this.transform.push({ key: 'translate', transform: `translate(${x}, ${y})` })
- return this
- }
-
- translate3d (x, y, z) {
- [x, y, z] = this.transformUnit(x, y, z)
- this.transform.push({ key: 'translate3d', transform: `translate3d(${x}, ${y}, ${z})` })
- return this
- }
-
- translateX (translate) {
- [translate] = this.transformUnit(translate)
- this.transform.push({ key: 'translateX', transform: `translateX(${translate})` })
- return this
- }
-
- translateY (translate) {
- [translate] = this.transformUnit(translate)
- this.transform.push({ key: 'translateY', transform: `translateY(${translate})` })
- return this
- }
-
- translateZ (translate) {
- [translate] = this.transformUnit(translate)
- this.transform.push({ key: 'translateZ', transform: `translateZ(${translate})` })
- return this
- }
-
- opacity (value) {
- this.rules.push({ key: 'opacity', rule: `opacity: ${value}` })
- return this
- }
-
- backgroundColor (value) {
- this.rules.push({ key: 'backgroundColor', rule: `background-color: ${value}` })
- return this
- }
-
- width (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'width', rule: `width: ${value}` })
- return this
- }
-
- height (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'height', rule: `height: ${value}` })
- return this
- }
-
- top (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'top', rule: `top: ${value}` })
- return this
- }
-
- right (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'right', rule: `right: ${value}` })
- return this
- }
-
- bottom (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'bottom', rule: `bottom: ${value}` })
- return this
- }
-
- left (value) {
- [value] = this.transformUnit(value)
- this.rules.push({ key: 'left', rule: `left: ${value}` })
- return this
- }
-
- // 关键帧载入
- step (arg: Partial = {}) {
- const { DEFAULT } = this
- const {
- duration = DEFAULT.duration,
- delay = DEFAULT.delay,
- timingFunction = DEFAULT.timingFunction,
- transformOrigin = DEFAULT.transformOrigin,
- } = arg
- // 生成一条 transition 动画
-
- this.transform.map((t0) => {
- const index = this.historyAnimations.findIndex((t1) => t1.key === t0.key)
- if (index === -1) {
- this.historyAnimations.push(t0)
- } else {
- this.historyAnimations[index] = t0
- }
- })
- const transforms = this.historyAnimations.map((t) => t.transform)
- const transformSequence = transforms.length > 0 ? `${TRANSFORM}:${transforms.join(' ')}!important` : ''
-
- this.rules.map((r0) => {
- const index = this.historyRules.findIndex((r1) => r1.key === r0.key)
- if (index === -1) {
- this.historyRules.push(r0)
- } else {
- this.historyRules[index] = r0
- }
- })
- const rules = this.historyRules.map((t) => t.rule)
- const ruleSequence = rules.length > 0 ? rules.map((rule) => `${rule}!important`).join(';') : ''
-
- this.steps.push(
- [
- ruleSequence,
- transformSequence,
- `${TRANSFORM}-origin: ${transformOrigin}`,
- `transition: all ${duration}ms ${timingFunction} ${delay}ms`,
- ]
- .filter((item) => item !== '')
- .join(';')
- )
- // 清空 rules 和 transform
- this.rules = []
- this.transform = []
- return this as Taro.Animation
- }
-
- // 创建底层数据
- createAnimationData () {
- const animIndex = `taro-h5-poly-fill/${this.id}/create-animation__${this.animationMapCount++}`
- // 记录动画分几个 step
- this.animationMap[animIndex] = this.steps.length
- // 吐出 step
- this.steps.forEach((step, index) => {
- const selector =
- index === 0
- ? `[animation="${animIndex}"], [data-animation="${animIndex}"]`
- : `[animation="${animIndex}--${index}"], [data-animation="${animIndex}--${index}"]`
- styleSheet.add(`${selector} { ${step} }`)
- })
-
- // 清空 steps
- this.steps = []
- return animIndex
- }
-
- // 动画数据产出
- export () {
- return this.createAnimationData() as unknown as ReturnType
- }
-}
/**
* 创建一个动画实例 animation
@@ -411,6 +14,4 @@ class Animation implements Taro.Animation {
* @canUse createAnimation
* @__object [duration, timingFunction[linear, ease, ease-in, ease-in-out, ease-out, step-start, step-end], delay, transformOrigin, unit]
*/
-export const createAnimation: typeof Taro.createAnimation = (option) => {
- return new Animation(option)
-}
+export { createAnimation } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/ui/fonts.ts b/packages/taro-mpharmony/src/api/ui/fonts.ts
index fa4276e58187..671a1a1e18ca 100644
--- a/packages/taro-mpharmony/src/api/ui/fonts.ts
+++ b/packages/taro-mpharmony/src/api/ui/fonts.ts
@@ -1,7 +1,3 @@
-import Taro from '@tarojs/api'
-
-import { MethodHandler } from '../../utils/handler'
-
/**
* 动态加载网络字体
*
@@ -9,55 +5,4 @@ import { MethodHandler } from '../../utils/handler'
* @__object [global, family, source, desc[style, variant, weight]]
* @__success [status]
*/
-export const loadFontFace: typeof Taro.loadFontFace = async (options) => {
- options = Object.assign({ global: false }, options)
- const { success, fail, complete, family, source, desc = {} } = options
- const handle = new MethodHandler({ name: 'loadFontFace', success, fail, complete })
- // @ts-ignore
- const fonts = document.fonts
- if (fonts) {
- // @ts-ignore
- const fontFace = new FontFace(family, source, desc)
- try {
- await fontFace.load()
- fonts.add(fontFace)
- return handle.success({ status: 'loaded' })
- } catch (error) {
- return handle.fail({
- status: 'error',
- errMsg: error.message || error,
- })
- }
- } else {
- const style = document.createElement('style')
- let innerText = `font-family:"${family}";src:${source};font-style:${desc.style || 'normal'};font-weight:${
- desc.weight || 'normal'
- };font-variant:${desc.variant || 'normal'};`
-
- if (desc.ascentOverride) {
- innerText += `ascent-override:${desc.ascentOverride};`
- }
- if (desc.descentOverride) {
- innerText += `descent-override:${desc.descentOverride};`
- }
- if (desc.featureSettings) {
- innerText += `font-feature-settings:${desc.featureSettings};`
- }
- if (desc.lineGapOverride) {
- innerText += `line-gap-override:${desc.lineGapOverride};`
- }
- if (desc.stretch) {
- innerText += `font-stretch:${desc.stretch};`
- }
- if (desc.unicodeRange) {
- innerText += `unicode-range:${desc.unicodeRange};`
- }
- if (desc.variationSettings) {
- innerText += `font-variation-settings:${desc.variationSettings};`
- }
-
- style.innerText = `@font-face{${innerText}}`
- document.head.appendChild(style)
- return handle.success({ status: 'loaded' })
- }
-}
+export { loadFontFace } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/ui/interaction/actionSheet.ts b/packages/taro-mpharmony/src/api/ui/interaction/actionSheet.ts
deleted file mode 100644
index b130233a217c..000000000000
--- a/packages/taro-mpharmony/src/api/ui/interaction/actionSheet.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-import { inlineStyle, setTransform } from '../../../utils'
-
-const noop = function () {}
-
-export default class ActionSheet {
- options = {
- alertText: '',
- itemList: [],
- itemColor: '#000000',
- success: noop,
- fail: noop,
- complete: noop,
- }
-
- style = {
- maskStyle: {
- position: 'fixed',
- 'z-index': '1000',
- top: '0',
- right: '0',
- left: '0',
- bottom: '0',
- background: 'rgba(0,0,0,0.6)',
- },
- actionSheetStyle: {
- 'z-index': '4999',
- position: 'fixed',
- left: '0',
- bottom: '0',
- '-webkit-transform': 'translate(0, 100%)',
- transform: 'translate(0, 100%)',
- width: '100%',
- 'line-height': '1.6',
- background: '#EFEFF4',
- '-webkit-transition': '-webkit-transform .3s',
- transition: 'transform .3s',
- 'border-radius': '15px 15px 0 0',
- },
- menuStyle: {
- 'background-color': '#FCFCFD',
- 'border-radius': '15px 15px 0 0',
- },
- cellStyle: {
- position: 'relative',
- padding: '10px 0',
- 'text-align': 'center',
- 'font-size': '18px',
- },
- titleStyle: {
- position: 'relative',
- padding: '10px 0',
- 'text-align': 'center',
- 'font-size': '16px',
- color: 'rgba(0,0,0,0.8)',
- display: 'none',
- },
- cancelStyle: {
- 'margin-top': '6px',
- padding: '10px 0',
- 'text-align': 'center',
- 'font-size': '18px',
- color: '#000000',
- 'background-color': '#FCFCFD',
- },
- }
-
- lastConfig = {}
- el: HTMLDivElement
- mask: HTMLDivElement
- actionSheet: HTMLDivElement
- menu: HTMLDivElement
- cells: HTMLDivElement[]
- title: HTMLDivElement
- cancel: HTMLDivElement
- hideOpacityTimer: ReturnType
- hideDisplayTimer: ReturnType
-
- create (options = {}) {
- return new Promise((resolve) => {
- // style
- const { maskStyle, actionSheetStyle, menuStyle, cellStyle, titleStyle, cancelStyle } = this.style
-
- // configuration
- const config = {
- ...this.options,
- ...options,
- }
-
- this.lastConfig = config
-
- // wrapper
- this.el = document.createElement('div')
- this.el.className = 'taro__actionSheet'
- this.el.style.opacity = '0'
- this.el.style.transition = 'opacity 0.2s linear'
-
- // mask
- this.mask = document.createElement('div')
- this.mask.setAttribute('style', inlineStyle(maskStyle))
-
- // actionSheet
- this.actionSheet = document.createElement('div')
- this.actionSheet.setAttribute('style', inlineStyle(actionSheetStyle))
-
- // menu
- this.menu = document.createElement('div')
- this.menu.setAttribute(
- 'style',
- inlineStyle({
- ...menuStyle,
- color: config.itemColor,
- })
- )
-
- // cells
- this.cells = config.itemList.map((item, index) => {
- const cell: HTMLDivElement = document.createElement('div')
- cell.className = 'taro-actionsheet__cell'
- cell.setAttribute('style', inlineStyle(cellStyle))
- cell.textContent = item
- cell.dataset.tapIndex = `${index}`
- cell.onclick = (e) => {
- this.hide()
- const target = e.currentTarget as HTMLDivElement
- const index = Number(target?.dataset.tapIndex) || 0
- resolve(index)
- }
- return cell
- })
-
- // title
- this.title = document.createElement('div')
- this.title.setAttribute('style', inlineStyle(titleStyle))
- this.title.className = 'taro-actionsheet__cell'
- this.title.textContent = config.alertText
- this.title.style.display = config.alertText ? 'block' : 'none'
-
- // cancel
- this.cancel = document.createElement('div')
- this.cancel.setAttribute('style', inlineStyle(cancelStyle))
- this.cancel.textContent = '取消'
-
- // result
- this.menu.appendChild(this.title)
- this.cells.forEach((item) => this.menu.appendChild(item))
- this.actionSheet.appendChild(this.menu)
- this.actionSheet.appendChild(this.cancel)
- this.el.appendChild(this.mask)
- this.el.appendChild(this.actionSheet)
-
- // callbacks
- const cb = () => {
- this.hide()
- resolve('cancel')
- }
- this.mask.onclick = cb
- this.cancel.onclick = cb
-
- // show immediately
- document.body.appendChild(this.el)
- setTimeout(() => {
- this.el.style.opacity = '1'
- setTransform(this.actionSheet, 'translate(0, 0)')
- }, 0)
- })
- }
-
- show (options = {}) {
- return new Promise((resolve) => {
- const config = {
- ...this.options,
- ...options,
- }
-
- this.lastConfig = config
-
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- // itemColor
- if (config.itemColor) this.menu.style.color = config.itemColor
-
- // cells
- const { cellStyle } = this.style
-
- config.itemList.forEach((item, index) => {
- let cell: HTMLDivElement
- if (this.cells[index]) {
- // assign new content
- cell = this.cells[index]
- } else {
- // create new cell
- cell = document.createElement('div')
- cell.className = 'taro-actionsheet__cell'
- cell.setAttribute('style', inlineStyle(cellStyle))
- cell.dataset.tapIndex = `${index}`
- this.cells.push(cell)
- this.menu.appendChild(cell)
- }
- cell.textContent = item
- cell.onclick = (e) => {
- this.hide()
- const target = e.currentTarget as HTMLDivElement
- const index = Number(target?.dataset.tapIndex) || 0
- resolve(index)
- }
- })
- const cellsLen = this.cells.length
- const itemListLen = config.itemList.length
- if (cellsLen > itemListLen) {
- for (let i = itemListLen; i < cellsLen; i++) {
- this.menu.removeChild(this.cells[i])
- }
- this.cells.splice(itemListLen)
- }
- this.title.textContent = config.alertText
- this.title.style.display = config.alertText ? 'block' : 'none'
-
- // callbacks
- const cb = () => {
- this.hide()
- resolve('cancel')
- }
- this.mask.onclick = cb
- this.cancel.onclick = cb
-
- // show
- this.el.style.display = 'block'
- setTimeout(() => {
- this.el.style.opacity = '1'
- setTransform(this.actionSheet, 'translate(0, 0)')
- }, 0)
- })
- }
-
- hide () {
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- this.hideOpacityTimer = setTimeout(() => {
- this.el.style.opacity = '0'
- setTransform(this.actionSheet, 'translate(0, 100%)')
- this.hideDisplayTimer = setTimeout(() => {
- this.el.style.display = 'none'
- }, 200)
- }, 0)
- }
-}
diff --git a/packages/taro-mpharmony/src/api/ui/interaction/index.ts b/packages/taro-mpharmony/src/api/ui/interaction/index.ts
index 762a2a54fe25..5a69e56d5155 100644
--- a/packages/taro-mpharmony/src/api/ui/interaction/index.ts
+++ b/packages/taro-mpharmony/src/api/ui/interaction/index.ts
@@ -1,85 +1,11 @@
-import Taro from '@tarojs/api'
-import { Current } from '@tarojs/runtime'
-
-import { getParameterError } from '../../../utils'
-import { MethodHandler } from '../../../utils/handler'
-import ActionSheet from './actionSheet'
-import Modal from './modal'
-import Toast from './toast'
-
// 交互
-
-let status = 'default'
-
-// inject necessary style
-function init (doc) {
- if (status === 'ready') return
-
- const taroStyle = doc.createElement('style')
- taroStyle.textContent =
- '@font-face{font-weight:normal;font-style:normal;font-family:"taro";src:url("data:application/x-font-ttf;charset=utf-8;base64, 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") format("truetype");}@-webkit-keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}@keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}.taro-modal__foot:after {content: "";position: absolute;left: 0;top: 0;right: 0;height: 1px;border-top: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);} .taro-model__btn:active {background-color: #EEEEEE}.taro-model__btn:not(:first-child):after {content: "";position: absolute;left: 0;top: 0;width: 1px;bottom: 0;border-left: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleX(0.5);transform: scaleX(0.5);}.taro-actionsheet__cell:not(:last-child):after {content: "";position: absolute;left: 0;bottom: 0;right: 0;height: 1px;border-top: 1px solid #e5e5e5;color: #e5e5e5;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);}'
- doc.querySelector('head').appendChild(taroStyle)
-
- status = 'ready'
-}
-
-const toast = new Toast()
-const modal = new Modal()
-const actionSheet = new ActionSheet()
-
/**
* 显示消息提示框
*
* @canUse showToast
* @__object [title, duration, icon[success, error, loading, none], image, mask]
*/
-const showToast: typeof Taro.showToast = (options = { title: '' }) => {
- init(document)
- options = Object.assign(
- {
- title: '',
- icon: 'success',
- image: '',
- duration: 1500,
- mask: false,
- },
- options
- )
- const { success, fail, complete } = options
- const handle = new MethodHandler({ name: 'showToast', success, fail, complete })
-
- if (typeof options.title !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'title',
- correct: 'String',
- wrong: options.title,
- }),
- })
- }
-
- if (typeof options.duration !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'duration',
- correct: 'Number',
- wrong: options.duration,
- }),
- })
- }
-
- if (options.image && typeof options.image !== 'string') options.image = ''
-
- options.mask = !!options.mask
-
- let errMsg = ''
- if (!toast.el) {
- errMsg = toast.create(options, 'toast')
- } else {
- errMsg = toast.show(options, 'toast')
- }
- return handle.success({ errMsg })
-}
+export { showToast } from '@tarojs/taro-h5'
/**
* 隐藏消息提示框
@@ -87,12 +13,7 @@ const showToast: typeof Taro.showToast = (options = { title: '' }) => {
* @canUse hideToast
* @__object [noConflict]
*/
-const hideToast: typeof Taro.hideToast = ({ noConflict = false, success, fail, complete } = {}) => {
- const handle = new MethodHandler({ name: 'hideToast', success, fail, complete })
- if (!toast.el) return handle.success()
- toast.hide(0, noConflict ? 'toast' : '')
- return handle.success()
-}
+export { hideToast } from '@tarojs/taro-h5'
/**
* 显示 loading 提示框
@@ -100,46 +21,7 @@ const hideToast: typeof Taro.hideToast = ({ noConflict = false, success, fail, c
* @canUse showLoading
* @__object [title, mask]
*/
-const showLoading: typeof Taro.showLoading = (options = { title: '' }) => {
- init(document)
- options = Object.assign(
- {
- title: '',
- mask: false,
- },
- options
- )
- const { success, fail, complete } = options
- const handle = new MethodHandler({ name: 'showLoading', success, fail, complete })
-
- const config = {
- icon: 'loading',
- image: '',
- duration: -1,
- }
-
- options = Object.assign({}, options, config)
-
- if (typeof options.title !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'title',
- correct: 'String',
- wrong: options.title,
- }),
- })
- }
-
- options.mask = !!options.mask
-
- let errMsg = ''
- if (!toast.el) {
- errMsg = toast.create(options, 'loading')
- } else {
- errMsg = toast.show(options, 'loading')
- }
- return handle.success({ errMsg })
-}
+export { showLoading } from '@tarojs/taro-h5'
/**
* 隐藏 loading 提示框
@@ -147,12 +29,7 @@ const showLoading: typeof Taro.showLoading = (options = { title: '' }) => {
* @canUse hideLoading
* @__object [noConflict]
*/
-const hideLoading: typeof Taro.hideLoading = ({ noConflict = false, success, fail, complete } = {}) => {
- const handle = new MethodHandler({ name: 'hideLoading', success, fail, complete })
- if (!toast.el) return handle.success()
- toast.hide(0, noConflict ? 'loading' : '')
- return handle.success()
-}
+export { hideLoading } from '@tarojs/taro-h5'
/**
* 显示模态对话框
@@ -161,112 +38,8 @@ const hideLoading: typeof Taro.hideLoading = ({ noConflict = false, success, fai
* @__object [cancelColor, cancelText, confirmColor, confirmText, content, showCancel, title]
* @__success [cancel, confirm]
*/
-const showModal: typeof Taro.showModal = async (options = {}) => {
- init(document)
- options = Object.assign(
- {
- title: '',
- content: '',
- showCancel: true,
- cancelText: '取消',
- cancelColor: '#000000',
- confirmText: '确定',
- confirmColor: '#3CC51F',
- },
- options
- )
- const { success, fail, complete } = options
- const handle = new MethodHandler({ name: 'showModal', success, fail, complete })
+export { showModal } from '@tarojs/taro-h5'
- if (typeof options.title !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'title',
- correct: 'String',
- wrong: options.title,
- }),
- })
- }
-
- if (typeof options.content !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'content',
- correct: 'String',
- wrong: options.content,
- }),
- })
- }
-
- if (typeof options.cancelText !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'cancelText',
- correct: 'String',
- wrong: options.cancelText,
- }),
- })
- }
-
- if (options.cancelText.replace(/[\u0391-\uFFE5]/g, 'aa').length > 8) {
- return handle.fail({
- errMsg: 'cancelText length should not larger then 4 Chinese characters',
- })
- }
-
- if (typeof options.confirmText !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'confirmText',
- correct: 'String',
- wrong: options.confirmText,
- }),
- })
- }
-
- if (options.confirmText.replace(/[\u0391-\uFFE5]/g, 'aa').length > 8) {
- return handle.fail({
- errMsg: 'confirmText length should not larger then 4 Chinese characters',
- })
- }
-
- if (typeof options.cancelColor !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'cancelColor',
- correct: 'String',
- wrong: options.cancelColor,
- }),
- })
- }
-
- if (typeof options.confirmColor !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'confirmColor',
- correct: 'String',
- wrong: options.confirmColor,
- }),
- })
- }
-
- options.showCancel = !!options.showCancel
-
- let result = ''
- if (!modal.el) {
- result = await modal.create(options)
- } else {
- result = await modal.show(options)
- }
- const res = { cancel: !1, confirm: !1 }
- res[result] = !0
- return handle.success(res)
-}
-
-function hideModal () {
- if (!modal.el) return
- modal.hide()
-}
/**
* 显示操作菜单
@@ -275,87 +48,7 @@ function hideModal () {
* @__object [alertText, itemList, itemColor]
* @__success [tapIndex]
*/
-const showActionSheet: typeof Taro.showActionSheet = async (options = { itemList: [] }) => {
- init(document)
- options = Object.assign(
- {
- itemColor: '#000000',
- itemList: [],
- },
- options
- )
- const { success, fail, complete } = options
- const handle = new MethodHandler({
- name: 'showActionSheet',
- success,
- fail,
- complete,
- })
-
- // list item String
- if (!Array.isArray(options.itemList)) {
- return handle.fail({
- errMsg: getParameterError({
- para: 'itemList',
- correct: 'Array',
- wrong: options.itemList,
- }),
- })
- }
-
- if (options.itemList.length < 1) {
- return handle.fail({ errMsg: 'parameter error: parameter.itemList should have at least 1 item' })
- }
-
- if (options.itemList.length > 6) {
- return handle.fail({ errMsg: 'parameter error: parameter.itemList should not be large than 6' })
- }
-
- for (let i = 0; i < options.itemList.length; i++) {
- if (typeof options.itemList[i] !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: `itemList[${i}]`,
- correct: 'String',
- wrong: options.itemList[i],
- }),
- })
- }
- }
-
- if (typeof options.itemColor !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'itemColor',
- correct: 'String',
- wrong: options.itemColor,
- }),
- })
- }
-
- let result: number | string = ''
- if (!actionSheet.el) {
- result = await actionSheet.create(options)
- } else {
- result = await actionSheet.show(options)
- }
-
- if (typeof result === 'string') {
- return handle.fail({ errMsg: result })
- } else {
- return handle.success({ tapIndex: result })
- }
-}
-
-Taro.eventCenter.on('__afterTaroRouterChange', () => {
- if (toast.currentPath && toast.currentPath !== Current.page?.path) {
- // 目前跳转新的页面不需要隐藏toast
- }
-
- if (modal.currentPath && modal.currentPath !== Current.page?.path) {
- // 目前跳转新的页面不需要隐藏modal
- }
-})
+export { showActionSheet } from '@tarojs/taro-h5'
/**
* 开启小程序页面返回询问对话框
@@ -363,7 +56,7 @@ Taro.eventCenter.on('__afterTaroRouterChange', () => {
* @canUse enableAlertBeforeUnload
* @null_implementation
*/
-const enableAlertBeforeUnload = () => {}
+const enableAlertBeforeUnload = () => { }
/**
* 关闭小程序页面返回询问对话框
@@ -371,16 +64,9 @@ const enableAlertBeforeUnload = () => {}
* @canUse disableAlertBeforeUnload
* @null_implementation
*/
-const disableAlertBeforeUnload = () => {}
+const disableAlertBeforeUnload = () => { }
export {
disableAlertBeforeUnload,
enableAlertBeforeUnload,
- hideLoading,
- hideModal,
- hideToast,
- showActionSheet,
- showLoading,
- showModal,
- showToast,
}
diff --git a/packages/taro-mpharmony/src/api/ui/interaction/modal.ts b/packages/taro-mpharmony/src/api/ui/interaction/modal.ts
deleted file mode 100644
index 2b464d8f65b5..000000000000
--- a/packages/taro-mpharmony/src/api/ui/interaction/modal.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import { Current } from '@tarojs/runtime'
-
-import { getCurrentPath, inlineStyle } from '../../../utils'
-
-export default class Modal {
- options = {
- title: '',
- content: '',
- showCancel: true,
- cancelText: '取消',
- cancelColor: '#000000',
- confirmText: '确定',
- confirmColor: '#3CC51F',
- }
-
- style = {
- maskStyle: {
- position: 'fixed',
- 'z-index': '1000',
- top: '0',
- right: '0',
- left: '0',
- bottom: '0',
- background: 'rgba(0,0,0,0.6)',
- },
- modalStyle: {
- 'z-index': '4999',
- position: 'fixed',
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- width: '80%',
- 'max-width': '300px',
- 'border-radius': '3px',
- 'text-align': 'center',
- 'line-height': '1.6',
- overflow: 'hidden',
- background: '#FFFFFF',
- },
- titleStyle: {
- padding: '20px 24px 9px',
- 'font-size': '18px',
- },
- textStyle: {
- padding: '0 24px 12px',
- 'min-height': '40px',
- 'font-size': '15px',
- 'line-height': '1.3',
- color: '#808080',
- 'word-wrap': 'break-word',
- 'word-break': 'break-all',
- },
- footStyle: {
- position: 'relative',
- 'line-height': '48px',
- 'font-size': '18px',
- display: 'flex',
- },
- btnStyle: {
- position: 'relative',
- '-webkit-box-flex': '1',
- '-webkit-flex': '1',
- flex: '1',
- },
- }
-
- currentPath: string | null
- el: HTMLDivElement
- title: HTMLDivElement
- text: HTMLDivElement
- cancel: HTMLDivElement
- confirm: HTMLDivElement
- hideOpacityTimer: ReturnType
- hideDisplayTimer: ReturnType
-
- create (options = {}) {
- return new Promise((resolve) => {
- // style
- const { maskStyle, modalStyle, titleStyle, textStyle, footStyle, btnStyle } = this.style
-
- // configuration
- const config = {
- ...this.options,
- ...options,
- }
-
- // wrapper
- this.el = document.createElement('div')
- this.el.className = 'taro__modal'
- this.el.style.opacity = '0'
- this.el.style.transition = 'opacity 0.2s linear'
-
- const eventHandler = (e) => {
- e.stopPropagation()
- e.preventDefault()
- }
- // mask
- const mask = document.createElement('div')
- mask.className = 'taro-modal__mask'
- mask.setAttribute('style', inlineStyle(maskStyle))
- mask.ontouchmove = eventHandler
- // modal
- const modal = document.createElement('div')
- modal.className = 'taro-modal__content'
- modal.setAttribute('style', inlineStyle(modalStyle))
- modal.ontouchmove = eventHandler
-
- // title
- const titleCSS = config.title
- ? titleStyle
- : {
- ...titleStyle,
- display: 'none',
- }
- this.title = document.createElement('div')
-
- this.title.className = 'taro-modal__title'
- this.title.setAttribute('style', inlineStyle(titleCSS))
- this.title.textContent = config.title
-
- // text
- const textCSS = config.title
- ? textStyle
- : {
- ...textStyle,
- padding: '40px 20px 26px',
- color: '#353535',
- }
- this.text = document.createElement('div')
- this.text.className = 'taro-modal__text'
- this.text.setAttribute('style', inlineStyle(textCSS))
- this.text.textContent = config.content
-
- // foot
- const foot = document.createElement('div')
- foot.className = 'taro-modal__foot'
- foot.setAttribute('style', inlineStyle(footStyle))
-
- // cancel button
- const cancelCSS = {
- ...btnStyle,
- color: config.cancelColor,
- display: config.showCancel ? 'block' : 'none',
- }
- this.cancel = document.createElement('div')
- this.cancel.className = 'taro-model__btn taro-model__cancel'
- this.cancel.setAttribute('style', inlineStyle(cancelCSS))
- this.cancel.textContent = config.cancelText
- this.cancel.onclick = () => {
- this.hide()
- resolve('cancel')
- }
-
- // confirm button
- this.confirm = document.createElement('div')
- this.confirm.className = 'taro-model__btn taro-model__confirm'
- this.confirm.setAttribute('style', inlineStyle(btnStyle))
- this.confirm.style.color = config.confirmColor
- this.confirm.textContent = config.confirmText
- this.confirm.onclick = () => {
- this.hide()
- resolve('confirm')
- }
-
- // result
- foot.appendChild(this.cancel)
- foot.appendChild(this.confirm)
- modal.appendChild(this.title)
- modal.appendChild(this.text)
- modal.appendChild(foot)
- this.el.appendChild(mask)
- this.el.appendChild(modal)
-
- // show immediately
- document.body.appendChild(this.el)
- setTimeout(() => {
- this.el.style.opacity = '1'
- }, 0)
-
- // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
- this.currentPath = Current.page?.path ?? getCurrentPath()
- })
- }
-
- show (options = {}) {
- return new Promise((resolve) => {
- const config = {
- ...this.options,
- ...options,
- }
-
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- // title & text
- const { textStyle } = this.style
-
- if (config.title) {
- this.title.textContent = config.title
- // none => block
- this.title.style.display = 'block'
- this.text.setAttribute('style', inlineStyle(textStyle))
- } else {
- this.title.textContent = ''
- // block => none
- this.title.style.display = 'none'
- const textCSS = {
- ...textStyle,
- padding: '40px 20px 26px',
- color: '#353535',
- }
- this.text.setAttribute('style', inlineStyle(textCSS))
- }
-
- this.text.textContent = config.content || ''
-
- // showCancel
- this.cancel.style.display = config.showCancel ? 'block' : 'none'
-
- // cancelText
- this.cancel.textContent = config.cancelText || ''
-
- // cancelColor
- this.cancel.style.color = config.cancelColor || ''
-
- // confirmText
- this.confirm.textContent = config.confirmText || ''
-
- // confirmColor
- this.confirm.style.color = config.confirmColor || ''
-
- // cbs
- this.cancel.onclick = () => {
- this.hide()
- resolve('cancel')
- }
- this.confirm.onclick = () => {
- this.hide()
- resolve('confirm')
- }
-
- // show
- this.el.style.display = 'block'
- setTimeout(() => {
- this.el.style.opacity = '1'
- }, 0)
-
- // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
- this.currentPath = Current.page?.path ?? getCurrentPath()
- })
- }
-
- hide () {
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- this.currentPath = null
-
- this.hideOpacityTimer = setTimeout(() => {
- this.el.style.opacity = '0'
- this.hideDisplayTimer = setTimeout(() => {
- this.el.style.display = 'none'
- }, 200)
- }, 0)
- }
-}
diff --git a/packages/taro-mpharmony/src/api/ui/interaction/toast.ts b/packages/taro-mpharmony/src/api/ui/interaction/toast.ts
deleted file mode 100644
index 2656a9acfb5b..000000000000
--- a/packages/taro-mpharmony/src/api/ui/interaction/toast.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-import { Current } from '@tarojs/runtime'
-
-import { getCurrentPath, inlineStyle } from '../../../utils'
-
-export default class Toast {
- options = {
- title: '',
- icon: 'none',
- image: '',
- duration: 1500,
- mask: false,
- }
-
- style = {
- maskStyle: {
- position: 'fixed',
- 'z-index': '1000',
- top: '0',
- right: '0',
- left: '0',
- bottom: '0',
- },
- toastStyle: {
- 'z-index': '5000',
- 'box-sizing': 'border-box',
- display: 'flex',
- 'flex-direction': 'column',
- 'justify-content': 'center',
- '-webkit-justify-content': 'center',
- position: 'fixed',
- top: '50%',
- left: '50%',
- 'min-width': '120px',
- 'max-width': '200px',
- 'min-height': '120px',
- padding: '15px',
- transform: 'translate(-50%, -50%)',
- 'border-radius': '5px',
- 'text-align': 'center',
- 'line-height': '1.6',
- color: '#FFFFFF',
- background: 'rgba(76, 76, 76, 1)',
- },
- successStyle: {
- margin: '6px auto',
- width: '38px',
- height: '38px',
- background:
- 'transparent url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjM5NTQ4OTYzMjA0IiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjQzNDgiIHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIj48cGF0aCBkPSJNMjE5Ljk1MiA1MTIuNTc2bDIxMC40MzIgMjEwLjQzMi00NS4yNDggNDUuMjU2LTIxMC40MzItMjEwLjQzMnoiIHAtaWQ9IjQzNDkiIGZpbGw9IiNmZmZmZmYiPjwvcGF0aD48cGF0aCBkPSJNNzk5LjY3MiAyNjIuMjY0bDQ1LjI1NiA0NS4yNTYtNDYwLjQ2NCA0NjAuNDY0LTQ1LjI1Ni00NS4yNTZ6IiBwLWlkPSI0MzUwIiBmaWxsPSIjZmZmZmZmIj48L3BhdGg+PC9zdmc+) no-repeat',
- 'background-size': '100%',
- },
- errrorStyle: {
- margin: '6px auto',
- width: '38px',
- height: '38px',
- background:
- 'transparent url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjM5NTUxMDU1MTgzIiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjE0MDc2IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCI+PHBhdGggZD0iTTUxMiA2NEMyNjQuNTggNjQgNjQgMjY0LjU4IDY0IDUxMnMyMDAuNTggNDQ4IDQ0OCA0NDggNDQ4LTIwMC41OCA0NDgtNDQ4Uzc1OS40MiA2NCA1MTIgNjR6IG0wIDc1MmEzNiAzNiAwIDEgMSAzNi0zNiAzNiAzNiAwIDAgMS0zNiAzNnogbTUxLjgzLTU1MS45NUw1NDggNjM2YTM2IDM2IDAgMCAxLTcyIDBsLTE1LjgzLTM3MS45NWMtMC4xLTEuMzMtMC4xNy0yLjY4LTAuMTctNC4wNWE1MiA1MiAwIDAgMSAxMDQgMGMwIDEuMzctMC4wNyAyLjcyLTAuMTcgNC4wNXoiIHAtaWQ9IjE0MDc3IiBmaWxsPSIjZmZmZmZmIj48L3BhdGg+PC9zdmc+) no-repeat',
- 'background-size': '100%',
- },
- loadingStyle: {
- margin: '6px auto',
- width: '38px',
- height: '38px',
- '-webkit-animation': 'taroLoading 1s steps(12, end) infinite',
- animation: 'taroLoading 1s steps(12, end) infinite',
- background:
- 'transparent url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0EzQTFBMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA2NSA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNBQkE5QUEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoMTIwIDU4LjY2IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0IyQjJCMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgxNTAgNTQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjQkFCOEI5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDE4MCA1MCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDMkMwQzEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTE1MCA0NS45OCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDQkNCQ0IiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=) no-repeat',
- 'background-size': '100%',
- },
- imageStyle: {
- margin: '6px auto',
- width: '40px',
- height: '40px',
- background: 'transparent no-repeat',
- 'background-size': '100%',
- },
- textStyle: {
- margin: '0',
- 'font-size': '16px',
- },
- }
-
- currentPath: string | null
- el: HTMLDivElement
- mask: HTMLDivElement
- icon: HTMLParagraphElement
- toast: HTMLDivElement
- title: HTMLParagraphElement
- type: any
- hideOpacityTimer: ReturnType
- hideDisplayTimer: ReturnType
-
- create (options = {}, _type: 'loading' | 'toast' = 'toast') {
- // style
- const { maskStyle, toastStyle, successStyle, errrorStyle, loadingStyle, imageStyle, textStyle } = this.style
-
- // configuration
- const config = {
- ...this.options,
- ...options,
- _type,
- }
-
- // wrapper
- this.el = document.createElement('div')
- this.el.className = 'taro__toast'
- this.el.style.opacity = '0'
- this.el.style.transition = 'opacity 0.1s linear'
-
- // mask
- this.mask = document.createElement('div')
- this.mask.setAttribute('style', inlineStyle(maskStyle))
- this.mask.style.display = config.mask ? 'block' : 'none'
-
- // icon
- this.icon = document.createElement('p')
- if (config.image) {
- this.icon.setAttribute(
- 'style',
- inlineStyle({
- ...imageStyle,
- 'background-image': `url(${config.image})`,
- })
- )
- } else {
- const iconStyle = config.icon === 'loading' ? loadingStyle : config.icon === 'error' ? errrorStyle : successStyle
- this.icon.setAttribute(
- 'style',
- inlineStyle({
- ...iconStyle,
- ...(config.icon === 'none' ? { display: 'none' } : {}),
- })
- )
- }
-
- // toast
- this.toast = document.createElement('div')
- this.toast.setAttribute(
- 'style',
- inlineStyle({
- ...toastStyle,
- ...(config.icon === 'none'
- ? {
- 'min-height': '0',
- padding: '10px 15px',
- }
- : {}),
- })
- )
-
- // title
- this.title = document.createElement('p')
- this.title.setAttribute('style', inlineStyle(textStyle))
- this.title.textContent = config.title
-
- // result
- this.toast.appendChild(this.icon)
- this.toast.appendChild(this.title)
- this.el.appendChild(this.mask)
- this.el.appendChild(this.toast)
-
- // show immediately
- document.body.appendChild(this.el)
- setTimeout(() => {
- this.el.style.opacity = '1'
- }, 0)
- this.type = config._type
-
- // disappear after duration
- config.duration >= 0 && this.hide(config.duration, this.type)
-
- // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
- this.currentPath = Current.page?.path ?? getCurrentPath()
-
- return ''
- }
-
- show (options = {}, _type: 'loading' | 'toast' = 'toast') {
- const config = {
- ...this.options,
- ...options,
- _type,
- }
-
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- // title
- this.title.textContent = config.title || ''
-
- // mask
- this.mask.style.display = config.mask ? 'block' : 'none'
-
- // image
- const { toastStyle, successStyle, errrorStyle, loadingStyle, imageStyle } = this.style
- if (config.image) {
- this.icon.setAttribute(
- 'style',
- inlineStyle({
- ...imageStyle,
- 'background-image': `url(${config.image})`,
- })
- )
- } else {
- if (!config.image && config.icon) {
- const iconStyle =
- config.icon === 'loading' ? loadingStyle : config.icon === 'error' ? errrorStyle : successStyle
- this.icon.setAttribute(
- 'style',
- inlineStyle({
- ...iconStyle,
- ...(config.icon === 'none' ? { display: 'none' } : {}),
- })
- )
- }
- }
-
- // toast
- this.toast.setAttribute(
- 'style',
- inlineStyle({
- ...toastStyle,
- ...(config.icon === 'none'
- ? {
- 'min-height': '0',
- padding: '10px 15px',
- }
- : {}),
- })
- )
-
- // show
- this.el.style.display = 'block'
- setTimeout(() => {
- this.el.style.opacity = '1'
- }, 0)
- this.type = config._type
-
- // disappear after duration
- config.duration >= 0 && this.hide(config.duration, this.type)
-
- // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
- this.currentPath = Current.page?.path ?? getCurrentPath()
-
- return ''
- }
-
- hide (duration = 0, type = '') {
- if (type && type !== this.type) return
-
- if (this.hideOpacityTimer) clearTimeout(this.hideOpacityTimer)
- if (this.hideDisplayTimer) clearTimeout(this.hideDisplayTimer)
-
- this.currentPath = null
-
- this.hideOpacityTimer = setTimeout(() => {
- this.el.style.opacity = '0'
- this.hideDisplayTimer = setTimeout(() => {
- this.el.style.display = 'none'
- }, 100)
- }, duration)
- }
-}
diff --git a/packages/taro-mpharmony/src/api/ui/pull-down-refresh.ts b/packages/taro-mpharmony/src/api/ui/pull-down-refresh.ts
index e95f6c2ff27f..c6ca81522fd3 100644
--- a/packages/taro-mpharmony/src/api/ui/pull-down-refresh.ts
+++ b/packages/taro-mpharmony/src/api/ui/pull-down-refresh.ts
@@ -1,33 +1,13 @@
-import Taro from '@tarojs/api'
-
-import { MethodHandler } from '../../utils/handler'
-
/**
* 开始下拉刷新。调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
*
* @canUse startPullDownRefresh
*/
-export const startPullDownRefresh: typeof Taro.startPullDownRefresh = function ({ success, fail, complete } = {}) {
- const handle = new MethodHandler({ name: 'startPullDownRefresh', success, fail, complete })
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroStartPullDownRefresh', {
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { startPullDownRefresh } from '@tarojs/taro-h5'
/**
* 停止当前页面下拉刷新。
*
* @canUse stopPullDownRefresh
*/
-export const stopPullDownRefresh: typeof Taro.stopPullDownRefresh = function ({ success, fail, complete } = {}) {
- const handle = new MethodHandler({ name: 'stopPullDownRefresh', success, fail, complete })
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroStopPullDownRefresh', {
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { stopPullDownRefresh } from '@tarojs/taro-h5'
diff --git a/packages/taro-mpharmony/src/api/ui/scroll/index.ts b/packages/taro-mpharmony/src/api/ui/scroll/index.ts
index e585b5fb5762..e79547c0fc01 100644
--- a/packages/taro-mpharmony/src/api/ui/scroll/index.ts
+++ b/packages/taro-mpharmony/src/api/ui/scroll/index.ts
@@ -1,106 +1,10 @@
-import Taro from '@tarojs/api'
-import { Current } from '@tarojs/runtime'
-
-import { easeInOut, getTimingFunc } from '../../../utils'
-import { MethodHandler } from '../../../utils/handler'
-
-let timer: ReturnType
-const FRAME_DURATION = 17
-
/**
* 将页面滚动到目标位置
*
* @canUse pageScrollTo
* @__object [duration, scrollTop, selector, offsetTop]
*/
-export const pageScrollTo: typeof Taro.pageScrollTo = ({
- scrollTop,
- selector = '',
- offsetTop = 0,
- duration = 300,
- success,
- fail,
- complete,
-}) => {
- let scrollFunc
- const handle = new MethodHandler({ name: 'pageScrollTo', success, fail, complete })
- return new Promise((resolve, reject) => {
- try {
- if (scrollTop === undefined && !selector) {
- return handle.fail(
- {
- errMsg: 'scrollTop" 或 "selector" 需要其之一',
- },
- { resolve, reject }
- )
- }
-
- const id = Current.page?.path?.replace(/([^a-z0-9\u00a0-\uffff_-])/gi, '\\$1')
- const el: HTMLDivElement | null = (
- id
- ? document.querySelector(`.taro_page#${id}`)
- : document.querySelector('.taro_page') || document.querySelector('.taro_router')
- ) as HTMLDivElement
-
- if (!scrollFunc) {
- if (!el) {
- scrollFunc = (pos) => {
- if (pos === undefined) {
- return window.pageYOffset
- } else {
- window.scrollTo(0, pos)
- }
- }
- } else {
- scrollFunc = (pos) => {
- if (pos === undefined) {
- return el.scrollTop
- } else {
- el.scrollTop = pos
- }
- }
- }
- }
-
- if (scrollTop && selector) {
- console.warn('"scrollTop" 或 "selector" 建议只设一个值,全部设置会忽略selector')
- }
- const from = scrollFunc()
- let to: number
- if (selector) {
- const el = document.querySelector(selector) as HTMLElement
- to = (el?.offsetTop || 0) + offsetTop
- } else {
- to = typeof scrollTop === 'number' ? scrollTop : 0
- }
- const delta = to - from
-
- const frameCnt = duration / FRAME_DURATION
- const easeFunc = getTimingFunc(easeInOut, frameCnt)
-
- const scroll = (frame = 0) => {
- const dest = from + delta * easeFunc(frame)
- scrollFunc(dest)
- if (frame < frameCnt) {
- timer && clearTimeout(timer)
- timer = setTimeout(() => {
- scroll(frame + 1)
- }, FRAME_DURATION)
- } else {
- return handle.success({}, { resolve, reject })
- }
- }
- scroll()
- } catch (e) {
- return handle.fail(
- {
- errMsg: e.message,
- },
- { resolve, reject }
- )
- }
- })
-}
+export { pageScrollTo } from '@tarojs/taro-h5'
/**
* 增强 ScrollView 实例
diff --git a/packages/taro-mpharmony/src/api/ui/tab-bar.ts b/packages/taro-mpharmony/src/api/ui/tab-bar.ts
index 0af6b4224dcd..43515678dc23 100644
--- a/packages/taro-mpharmony/src/api/ui/tab-bar.ts
+++ b/packages/taro-mpharmony/src/api/ui/tab-bar.ts
@@ -1,13 +1,4 @@
-import Taro, { AppConfig } from '@tarojs/api'
-
-import { getParameterError, isValidColor, shouldBeObject } from '../../utils'
-import { MethodHandler } from '../../utils/handler'
-
-let tabConf
-
-export function initTabBarApis (config: AppConfig = {}) {
- tabConf = config.tabBar
-}
+export { initTabBarApis } from '@tarojs/taro-h5'
/**
* 显示 tabBar 某一项的右上角的红点
@@ -15,36 +6,7 @@ export function initTabBarApis (config: AppConfig = {}) {
* @canUse showTabBarRedDot
* @__object [index]
*/
-export const showTabBarRedDot: typeof Taro.showTabBarRedDot = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `showTabBarRedDot:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { index, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'showTabBarRedDot', success, fail, complete })
-
- if (typeof index !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'index',
- correct: 'Number',
- wrong: index,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroShowTabBarRedDotHandler', {
- index,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { showTabBarRedDot } from '@tarojs/taro-h5'
/**
* 显示 tabBar
@@ -52,36 +14,7 @@ export const showTabBarRedDot: typeof Taro.showTabBarRedDot = (options) => {
* @canUse showTabBar
* @__object [animation]
*/
-export const showTabBar: typeof Taro.showTabBar = (options = {}) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `showTabBar:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { animation, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'showTabBar', success, fail, complete })
-
- if (options.hasOwnProperty('animation') && typeof animation !== 'boolean') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'animation',
- correct: 'Boolean',
- wrong: animation,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroShowTabBar', {
- animation,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { showTabBar } from '@tarojs/taro-h5'
/**
* 动态设置 tabBar 的整体样式
@@ -89,54 +22,7 @@ export const showTabBar: typeof Taro.showTabBar = (options = {}) => {
* @canUse setTabBarStyle
* @__object [backgroundColor, borderStyle, color, selectedColor]
*/
-export const setTabBarStyle: typeof Taro.setTabBarStyle = (options = {}) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `setTabBarStyle:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { color, selectedColor, backgroundColor, borderStyle, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'setTabBarStyle', success, fail, complete })
-
- let errMsg
- if (color && !isValidColor(color)) {
- errMsg = 'color'
- } else if (selectedColor && !isValidColor(selectedColor)) {
- errMsg = 'selectedColor'
- } else if (backgroundColor && !isValidColor(backgroundColor)) {
- errMsg = 'backgroundColor'
- } else if (borderStyle && !/^(black|white)$/.test(borderStyle)) {
- errMsg = 'borderStyle'
- }
-
- if (errMsg) {
- return handle.fail({ errMsg: `invalid ${errMsg}` })
- }
-
- if (!tabConf) {
- return handle.fail()
- }
-
- const obj: Taro.setTabBarStyle.Option = {}
- if (color) obj.color = color
- if (selectedColor) obj.selectedColor = selectedColor
- if (backgroundColor) obj.backgroundColor = backgroundColor
- if (borderStyle) obj.borderStyle = borderStyle
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroSetTabBarStyle', {
- color,
- selectedColor,
- backgroundColor,
- borderStyle,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { setTabBarStyle } from '@tarojs/taro-h5'
/**
* 动态设置 tabBar 某一项的内容
@@ -144,39 +30,7 @@ export const setTabBarStyle: typeof Taro.setTabBarStyle = (options = {}) => {
* @canUse setTabBarItem
* @__object [index, iconPath, selectedIconPath, text]
*/
-export const setTabBarItem: typeof Taro.setTabBarItem = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `setTabBarItem:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { index, text, iconPath, selectedIconPath, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'setTabBarItem', success, fail, complete })
-
- if (typeof index !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'index',
- correct: 'Number',
- wrong: index,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroSetTabBarItem', {
- index,
- text,
- iconPath,
- selectedIconPath,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { setTabBarItem } from '@tarojs/taro-h5'
/**
* 为 tabBar 某一项的右上角添加文本
@@ -184,47 +38,7 @@ export const setTabBarItem: typeof Taro.setTabBarItem = (options) => {
* @canUse setTabBarBadge
* @__object [index, text]
*/
-export const setTabBarBadge: typeof Taro.setTabBarBadge = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `setTabBarBadge:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { index, text, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'setTabBarBadge', success, fail, complete })
-
- if (typeof index !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'index',
- correct: 'Number',
- wrong: index,
- }),
- })
- }
-
- if (typeof text !== 'string') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'text',
- correct: 'String',
- wrong: text,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroSetTabBarBadge', {
- index,
- text: text.length > 4 ? '...' : text,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { setTabBarBadge } from '@tarojs/taro-h5'
/**
* 移除 tabBar 某一项右上角的文本
@@ -232,36 +46,7 @@ export const setTabBarBadge: typeof Taro.setTabBarBadge = (options) => {
* @canUse removeTabBarBadge
* @__object [index]
*/
-export const removeTabBarBadge: typeof Taro.removeTabBarBadge = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `removeTabBarBadge:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { index, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'removeTabBarBadge', success, fail, complete })
-
- if (typeof index !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'index',
- correct: 'Number',
- wrong: index,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroRemoveTabBarBadge', {
- index,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { removeTabBarBadge } from '@tarojs/taro-h5'
/**
* 隐藏 tabBar 某一项的右上角的红点
@@ -269,36 +54,7 @@ export const removeTabBarBadge: typeof Taro.removeTabBarBadge = (options) => {
* @canUse hideTabBarRedDot
* @__object [index]
*/
-export const hideTabBarRedDot: typeof Taro.hideTabBarRedDot = (options) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `hideTabBarRedDot:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { index, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'hideTabBarRedDot', success, fail, complete })
-
- if (typeof index !== 'number') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'index',
- correct: 'Number',
- wrong: index,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroHideTabBarRedDotHandler', {
- index,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { hideTabBarRedDot } from '@tarojs/taro-h5'
/**
* 隐藏 tabBar
@@ -306,33 +62,4 @@ export const hideTabBarRedDot: typeof Taro.hideTabBarRedDot = (options) => {
* @canUse hideTabBar
* @__object [animation]
*/
-export const hideTabBar: typeof Taro.hideTabBar = (options = {}) => {
- // options must be an Object
- const isObject = shouldBeObject(options)
- if (!isObject.flag) {
- const res = { errMsg: `hideTabBar:fail ${isObject.msg}` }
- console.error(res.errMsg)
- return Promise.reject(res)
- }
-
- const { animation, success, fail, complete } = options
- const handle = new MethodHandler({ name: 'hideTabBar', success, fail, complete })
-
- if (options.hasOwnProperty('animation') && typeof animation !== 'boolean') {
- return handle.fail({
- errMsg: getParameterError({
- para: 'animation',
- correct: 'Boolean',
- wrong: animation,
- }),
- })
- }
-
- return new Promise((resolve, reject) => {
- Taro.eventCenter.trigger('__taroHideTabBar', {
- animation,
- successHandler: (res = {}) => handle.success(res, { resolve, reject }),
- errorHandler: (res = {}) => handle.fail(res, { resolve, reject }),
- })
- })
-}
+export { hideTabBar } from '@tarojs/taro-h5'
\ No newline at end of file
diff --git a/packages/taro-mpharmony/src/api/ui/window.ts b/packages/taro-mpharmony/src/api/ui/window.ts
index 2bcf265b26f2..6ae590af633d 100644
--- a/packages/taro-mpharmony/src/api/ui/window.ts
+++ b/packages/taro-mpharmony/src/api/ui/window.ts
@@ -1,16 +1,3 @@
-import Taro from '@tarojs/api'
-
-import { CallbackManager } from '../../utils/handler'
-
-const callbackManager = new CallbackManager()
-
-const resizeListener = () => {
- callbackManager.trigger({
- windowWidth: window.screen.width,
- windowHeight: window.screen.height,
- })
-}
-
/**
* 设置窗口大小,该接口仅适用于 PC 平台,使用细则请参见指南
*
@@ -23,24 +10,14 @@ export { setWindowSize } from '@tarojs/taro-h5'
*
* @canUse onWindowResize
*/
-export const onWindowResize: typeof Taro.onWindowResize = (callback) => {
- callbackManager.add(callback)
- if (callbackManager.count() === 1) {
- window.addEventListener('resize', resizeListener)
- }
-}
+export { onWindowResize } from '@tarojs/taro-h5'
/**
* 取消监听窗口尺寸变化事件
*
* @canUse offWindowResize
*/
-export const offWindowResize: typeof Taro.offWindowResize = (callback) => {
- callbackManager.remove(callback)
- if (callbackManager.count() === 0) {
- window.removeEventListener('resize', resizeListener)
- }
-}
+export { offWindowResize } from '@tarojs/taro-h5'
/**
* 返回当前是否存在小窗播放
diff --git a/packages/taro-mpharmony/src/api/wxml/IntersectionObserver.ts b/packages/taro-mpharmony/src/api/wxml/IntersectionObserver.ts
deleted file mode 100644
index 30fd456f6ccb..000000000000
--- a/packages/taro-mpharmony/src/api/wxml/IntersectionObserver.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import Taro from '@tarojs/taro'
-
-import { findDOM } from '../../utils'
-// pollify
-import('intersection-observer')
-
-type TElement = Document | HTMLElement | Element
-
-type TListener = {
- element: Element
- callback: Taro.IntersectionObserver.ObserveCallback
-}
-
-/**
- * IntersectionObserver 对象,用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见
- *
- * @canUse IntersectionObserver
- * @__class [disconnect, observe, relativeTo, relativeToViewport]
- */
-export class TaroH5IntersectionObserver implements Taro.IntersectionObserver {
- // 自定义组件实例
- private _component: TaroGeneral.IAnyObject
- // 选项
- private _options = {
- thresholds: [0],
- initialRatio: 0,
- observeAll: false,
- }
-
- // Observer实例
- private _observerInst: IntersectionObserver
- // 监控中的选择器
- private _listeners: TListener[] = []
- // 参照区域
- private _root: Element | null
- // 用来扩展(或收缩)参照节点布局区域的边界
- private _rootMargin: Taro.IntersectionObserver.RelativeToViewportMargins = {}
- // 是否已初始化
- private _isInited = false
-
- // selector 的容器节点
- protected get container () {
- const container: TElement =
- this._component !== null ? (findDOM(this._component) as HTMLElement) || document : document
- return container
- }
-
- constructor (component: TaroGeneral.IAnyObject, options: Taro.createIntersectionObserver.Option = {}) {
- this._component = component
- Object.assign(this._options, options)
- }
-
- private createInst () {
- // 去除原本的实例
- this.disconnect()
-
- const { left = 0, top = 0, bottom = 0, right = 0 } = this._rootMargin
- return new IntersectionObserver(
- (entries) => {
- entries.forEach((entry) => {
- const _callback = this._getCallbackByElement(entry.target)
- const result = {
- boundingClientRect: entry.boundingClientRect,
- intersectionRatio: entry.intersectionRatio,
- intersectionRect: entry.intersectionRect,
- relativeRect: entry.rootBounds || { left: 0, right: 0, top: 0, bottom: 0 },
- // 使用时间戳而不是entry.time,跟微信小程序一致
- time: Date.now(),
- }
- // web端会默认首次触发
- if (!this._isInited && this._options.initialRatio <= Math.min.apply(Math, this._options.thresholds)) {
- // 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数。
- return
- }
- _callback && _callback.call(this, result)
- })
- this._isInited = true
- },
- {
- root: this._root,
- rootMargin: [`${top}px`, `${right}px`, `${bottom}px`, `${left}px`].join(' '),
- threshold: this._options.thresholds,
- }
- )
- }
-
- public disconnect (): void {
- if (this._observerInst) {
- let listener
- while ((listener = this._listeners.pop())) {
- this._observerInst.unobserve(listener.element)
- }
- this._observerInst.disconnect()
- }
- }
-
- public observe (targetSelector: string, callback: Taro.IntersectionObserver.ObserveCallback): void {
- // 同wx小程序效果一致,每个实例监听一个Selector
- if (this._listeners.length) return
- // 监听前没有设置关联的节点
- if (!this._observerInst) {
- console.warn('Intersection observer will be ignored because no relative nodes are found.')
- return
- }
-
- const nodeList = this._options.observeAll
- ? this.container.querySelectorAll(targetSelector)
- : [this.container.querySelector(targetSelector)]
-
- nodeList.forEach((element) => {
- if (!element) return
- this._observerInst.observe(element)
- this._listeners.push({ element, callback })
- })
- }
-
- public relativeTo (
- selector: string,
- margins?: Taro.IntersectionObserver.RelativeToMargins | undefined
- ): Taro.IntersectionObserver {
- // 已设置observe监听后,重新关联节点
- if (this._listeners.length) {
- console.error('Relative nodes cannot be added after "observe" call in IntersectionObserver')
- return this
- }
- this._root = this.container.querySelector(selector) || null
- if (margins) {
- this._rootMargin = margins
- }
- this._observerInst = this.createInst()
- return this
- }
-
- public relativeToViewport (
- margins?: Taro.IntersectionObserver.RelativeToViewportMargins | undefined
- ): Taro.IntersectionObserver {
- return this.relativeTo('.taro_page', margins)
- }
-
- private _getCallbackByElement (element: Element) {
- const listener = this._listeners.find((listener) => listener.element === element)
- return listener ? listener.callback : null
- }
-}
diff --git a/packages/taro-mpharmony/src/api/wxml/MediaQueryObserver.ts b/packages/taro-mpharmony/src/api/wxml/MediaQueryObserver.ts
deleted file mode 100644
index 7c0664720049..000000000000
--- a/packages/taro-mpharmony/src/api/wxml/MediaQueryObserver.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { isFunction, toKebabCase } from '@tarojs/shared'
-import Taro from '@tarojs/taro'
-
-function generateMediaQueryStr (descriptor: Taro.MediaQueryObserver.descriptor) {
- const mediaQueryArr: string[] = []
- const descriptorMenu = ['width', 'minWidth', 'maxWidth', 'height', 'minHeight', 'maxHeight', 'orientation']
- for (const item of descriptorMenu) {
- if (item !== 'orientation' && descriptor[item] && Number(descriptor[item]) >= 0) {
- mediaQueryArr.push(`(${toKebabCase(item)}: ${Number(descriptor[item])}px)`)
- }
- if (item === 'orientation' && descriptor[item]) {
- mediaQueryArr.push(`(${toKebabCase(item)}: ${descriptor[item]})`)
- }
- }
- return mediaQueryArr.join(' and ')
-}
-
-/**
- * MediaQueryObserver 对象,用于监听页面 media query 状态的变化,如界面的长宽是不是在某个指定的范围内
- *
- * @canUse MediaQueryObserver
- * @__class [observe, disconnect]
- */
-export class MediaQueryObserver implements Taro.MediaQueryObserver {
- private _mediaQueryObserver: MediaQueryList
- private _listener: (ev: MediaQueryListEvent) => void
-
- // 监听页面媒体查询变化情况
- public observe (
- descriptor: Taro.MediaQueryObserver.descriptor,
- callback: Taro.MediaQueryObserver.observeCallback
- ): void {
- if (isFunction(callback)) {
- // 创建媒体查询对象
- this._mediaQueryObserver = window.matchMedia(generateMediaQueryStr(descriptor))
- // 监听器
- this._listener = (ev: MediaQueryListEvent) => {
- callback({ matches: ev.matches })
- }
- callback({ matches: this._mediaQueryObserver.matches })
- // 兼容旧浏览器中 MediaQueryList 尚未继承于 EventTarget 导致不存在 'addEventListener'
- if ('addEventListener' in this._mediaQueryObserver) {
- this._mediaQueryObserver.addEventListener('change', this._listener)
- } else {
- // @ts-ignore
- this._mediaQueryObserver.addListener(this._listener)
- }
- }
- }
-
- // 停止监听,销毁媒体查询对象
- public disconnect (): void {
- if (this._mediaQueryObserver && this._listener) {
- // 兼容旧浏览器中 MediaQueryList 尚未继承于 EventTarget 导致不存在 'removeEventListener'
- if ('removeEventListener' in this._mediaQueryObserver) {
- this._mediaQueryObserver.removeEventListener('change', this._listener)
- } else {
- // @ts-ignore
- this._mediaQueryObserver.removeListener(this._listener)
- }
- }
- }
-}
diff --git a/packages/taro-mpharmony/src/api/wxml/index.ts b/packages/taro-mpharmony/src/api/wxml/index.ts
index 3a522758ceee..062415b9cfd6 100644
--- a/packages/taro-mpharmony/src/api/wxml/index.ts
+++ b/packages/taro-mpharmony/src/api/wxml/index.ts
@@ -1,7 +1,5 @@
import Taro from '@tarojs/api'
-import { TaroH5IntersectionObserver } from './IntersectionObserver'
-import { MediaQueryObserver } from './MediaQueryObserver'
import { SelectorQuery } from './selectorQuery'
/**
@@ -9,6 +7,7 @@ import { SelectorQuery } from './selectorQuery'
*
* @canUse createSelectorQuery
*/
+
export const createSelectorQuery: typeof Taro.createSelectorQuery = () => {
return new SelectorQuery()
}
@@ -18,18 +17,28 @@ export const createSelectorQuery: typeof Taro.createSelectorQuery = () => {
*
* @canUse createIntersectionObserver
*/
-export const createIntersectionObserver: typeof Taro.createIntersectionObserver = (component, options) => {
- return new TaroH5IntersectionObserver(component, options)
-}
+export { createIntersectionObserver } from '@tarojs/taro-h5'
+
+/**
+ * IntersectionObserver 对象,用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见
+ *
+ * @canUse IntersectionObserver
+ * @__class [disconnect, observe, relativeTo, relativeToViewport]
+ */
/**
* 创建并返回一个 MediaQueryObserver 对象实例
*
* @canUse createMediaQueryObserver
*/
-export const createMediaQueryObserver: typeof Taro.createMediaQueryObserver = () => {
- return new MediaQueryObserver()
-}
+export { createMediaQueryObserver } from '@tarojs/taro-h5'
+
+/**
+ * MediaQueryObserver 对象,用于监听页面 media query 状态的变化,如界面的长宽是不是在某个指定的范围内
+ *
+ * @canUse MediaQueryObserver
+ * @__class [observe, disconnect]
+ */
/**
* Snapshot 实例,可通过 SelectorQuery 获取。
diff --git a/packages/taro-mpharmony/src/api/wxml/nodesRef.ts b/packages/taro-mpharmony/src/api/wxml/nodesRef.ts
index 23d4296fab74..de2dd447cb4b 100644
--- a/packages/taro-mpharmony/src/api/wxml/nodesRef.ts
+++ b/packages/taro-mpharmony/src/api/wxml/nodesRef.ts
@@ -1,73 +1,7 @@
-import Taro from '@tarojs/api'
-
-import { SelectorQuery } from './selectorQuery'
-
/**
* 用于获取 WXML 节点信息
*
* @canUse NodesRef
* @__class [context, node, boundingClientRect, scrollOffset, fields]
*/
-export class NodesRef implements Taro.NodesRef {
- _component?: TaroGeneral.IAnyObject
- _selector: string
- _selectorQuery: SelectorQuery
- _single: boolean
-
- constructor (selector: string, querySelectorQuery: SelectorQuery, single: boolean) {
- this._component = querySelectorQuery._component
- this._selector = selector
- this._selectorQuery = querySelectorQuery
- this._single = single
- }
-
- context (cb) {
- const { _selector, _component, _single, _selectorQuery } = this
- _selectorQuery._push(_selector, _component, _single, { context: !0 }, cb)
- return _selectorQuery
- }
-
- node (cb) {
- const { _selector, _component, _single, _selectorQuery } = this
- _selectorQuery._push(_selector, _component, _single, { nodeCanvasType: !0, node: !0 }, cb)
- return _selectorQuery
- }
-
- boundingClientRect (cb) {
- const { _selector, _component, _single, _selectorQuery } = this
- _selectorQuery._push(_selector, _component, _single, { id: !0, dataset: !0, rect: !0, size: !0 }, cb)
- return _selectorQuery
- }
-
- scrollOffset (cb) {
- const { _selector, _component, _single, _selectorQuery } = this
- _selectorQuery._push(_selector, _component, _single, { id: !0, dataset: !0, scrollOffset: !0 }, cb)
- return _selectorQuery
- }
-
- fields (fields, cb) {
- const { _selector, _component, _single, _selectorQuery } = this
- const { id, dataset, rect, size, scrollOffset, context, node, properties = [], computedStyle = [] } = fields
-
- _selectorQuery._push(
- _selector,
- _component,
- _single,
- {
- id,
- dataset,
- rect,
- size,
- scrollOffset,
- context,
- node,
- nodeCanvasType: node,
- properties,
- computedStyle,
- },
- cb
- )
-
- return _selectorQuery
- }
-}
+export { NodesRef } from '@tarojs/taro-h5'
From 9b23295570245f2d0d7cbf306a24a968b96fa845 Mon Sep 17 00:00:00 2001
From: tangcq-code <1192601676@qq.com>
Date: Wed, 29 Nov 2023 11:27:41 +0800
Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=E5=B0=86taro-mpharmony=E4=B8=ADH5?=
=?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=9A=84=E6=8E=A5=E5=8F=A3=E7=9A=84=E4=BF=AE?=
=?UTF-8?q?=E6=94=B9=E5=90=8C=E6=AD=A5=E5=88=B0taro-h5=E4=B8=AD=EF=BC=8C?=
=?UTF-8?q?=E6=95=B4=E5=90=88taro-mpharmony=E5=92=8Ctaro-h5=E7=9B=B8?=
=?UTF-8?q?=E5=90=8C=E7=9A=84=E5=AE=9E=E7=8E=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
packages/taro-h5/src/api/device/network.ts | 9 +++++++--
packages/taro-h5/src/api/ui/interaction/index.ts | 3 ++-
packages/taro-h5/src/api/ui/tab-bar.ts | 2 +-
packages/taro-h5/src/utils/handler.ts | 5 +++++
4 files changed, 15 insertions(+), 4 deletions(-)
diff --git a/packages/taro-h5/src/api/device/network.ts b/packages/taro-h5/src/api/device/network.ts
index 785aaac6b72b..c1cfe04913f4 100644
--- a/packages/taro-h5/src/api/device/network.ts
+++ b/packages/taro-h5/src/api/device/network.ts
@@ -78,8 +78,13 @@ export const onNetworkStatusChange: typeof Taro.onNetworkStatusChange = callback
export const offNetworkWeakChange = /* @__PURE__ */ temporarilyNotSupport('offNetworkWeakChange')
-export const offNetworkStatusChange: typeof Taro.offNetworkStatusChange = callback => {
- networkStatusManager.remove(callback)
+export const offNetworkStatusChange: typeof Taro.offNetworkStatusChange = (callback) => {
+ // 取消监听网络状态变化事件,参数为空,则取消所有的事件监听。
+ if (callback) {
+ networkStatusManager.remove(callback)
+ } else {
+ networkStatusManager.removeAll()
+ }
const connection = getConnection()
if (connection && networkStatusManager.count() === 0) {
connection.removeEventListener('change', networkStatusListener)
diff --git a/packages/taro-h5/src/api/ui/interaction/index.ts b/packages/taro-h5/src/api/ui/interaction/index.ts
index c39d40fce2e1..2c1c44e8621c 100644
--- a/packages/taro-h5/src/api/ui/interaction/index.ts
+++ b/packages/taro-h5/src/api/ui/interaction/index.ts
@@ -16,7 +16,8 @@ function init (doc) {
if (status === 'ready') return
const taroStyle = doc.createElement('style')
- taroStyle.textContent = '@font-face{font-weight:normal;font-style:normal;font-family:"taro";src:url("data:application/x-font-ttf;charset=utf-8;base64, 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") format("truetype");}@-webkit-keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}@keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}.taro-modal__foot:after {content: "";position: absolute;left: 0;top: 0;right: 0;height: 1px;border-top: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);} .taro-model__btn:active {background-color: #EEEEEE}.taro-model__btn:not(:first-child):after {content: "";position: absolute;left: 0;top: 0;width: 1px;bottom: 0;border-left: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleX(0.5);transform: scaleX(0.5);}.taro-actionsheet__cell:not(:first-child):after {content: "";position: absolute;left: 0;top: 0;right: 0;height: 1px;border-top: 1px solid #e5e5e5;color: #e5e5e5;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);}'
+ taroStyle.textContent =
+ '@font-face{font-weight:normal;font-style:normal;font-family:"taro";src:url("data:application/x-font-ttf;charset=utf-8;base64, AAEAAAALAIAAAwAwR1NVQrD+s+0AAAE4AAAAQk9TLzJWs0t/AAABfAAAAFZjbWFwqVgGvgAAAeAAAAGGZ2x5Zph7qG0AAANwAAAAdGhlYWQRFoGhAAAA4AAAADZoaGVhCCsD7AAAALwAAAAkaG10eAg0AAAAAAHUAAAADGxvY2EADAA6AAADaAAAAAhtYXhwAQ4AJAAAARgAAAAgbmFtZYrphEEAAAPkAAACVXBvc3S3shtSAAAGPAAAADUAAQAAA+gAAABaA+gAAAAAA+gAAQAAAAAAAAAAAAAAAAAAAAMAAQAAAAEAAADih+FfDzz1AAsD6AAAAADXB57LAAAAANcHnssAAP/sA+gDOgAAAAgAAgAAAAAAAAABAAAAAwAYAAEAAAAAAAIAAAAKAAoAAAD/AAAAAAAAAAEAAAAKAB4ALAABREZMVAAIAAQAAAAAAAAAAQAAAAFsaWdhAAgAAAABAAAAAQAEAAQAAAABAAgAAQAGAAAAAQAAAAAAAQK8AZAABQAIAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABAAHjqCAPoAAAAWgPoABQAAAABAAAAAAAAA+gAAABkAAAD6AAAAAAABQAAAAMAAAAsAAAABAAAAV4AAQAAAAAAWAADAAEAAAAsAAMACgAAAV4ABAAsAAAABgAEAAEAAgB46gj//wAAAHjqCP//AAAAAAABAAYABgAAAAEAAgAAAQYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAKAAAAAAAAAACAAAAeAAAAHgAAAABAADqCAAA6ggAAAACAAAAAAAAAAwAOgABAAD/7AAyABQAAgAANzMVFB4UKAAAAAABAAAAAAO7AzoAFwAAEy4BPwE+AR8BFjY3ATYWFycWFAcBBiInPQoGBwUHGgzLDCELAh0LHwsNCgr9uQoeCgGzCyEOCw0HCZMJAQoBvgkCCg0LHQv9sQsKAAAAAAAAEgDeAAEAAAAAAAAAHQAAAAEAAAAAAAEABAAdAAEAAAAAAAIABwAhAAEAAAAAAAMABAAoAAEAAAAAAAQABAAsAAEAAAAAAAUACwAwAAEAAAAAAAYABAA7AAEAAAAAAAoAKwA/AAEAAAAAAAsAEwBqAAMAAQQJAAAAOgB9AAMAAQQJAAEACAC3AAMAAQQJAAIADgC/AAMAAQQJAAMACADNAAMAAQQJAAQACADVAAMAAQQJAAUAFgDdAAMAAQQJAAYACADzAAMAAQQJAAoAVgD7AAMAAQQJAAsAJgFRCiAgQ3JlYXRlZCBieSBmb250LWNhcnJpZXIKICB3ZXVpUmVndWxhcndldWl3ZXVpVmVyc2lvbiAxLjB3ZXVpR2VuZXJhdGVkIGJ5IHN2ZzJ0dGYgZnJvbSBGb250ZWxsbyBwcm9qZWN0Lmh0dHA6Ly9mb250ZWxsby5jb20ACgAgACAAQwByAGUAYQB0AGUAZAAgAGIAeQAgAGYAbwBuAHQALQBjAGEAcgByAGkAZQByAAoAIAAgAHcAZQB1AGkAUgBlAGcAdQBsAGEAcgB3AGUAdQBpAHcAZQB1AGkAVgBlAHIAcwBpAG8AbgAgADEALgAwAHcAZQB1AGkARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABzAHYAZwAyAHQAdABmACAAZgByAG8AbQAgAEYAbwBuAHQAZQBsAGwAbwAgAHAAcgBvAGoAZQBjAHQALgBoAHQAdABwADoALwAvAGYAbwBuAHQAZQBsAGwAbwAuAGMAbwBtAAAAAAIAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwECAQMBBAABeAd1bmlFQTA4AAAAAAA=") format("truetype");}@-webkit-keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}@keyframes taroLoading{0%{-webkit-transform:rotate3d(0, 0, 1, 0deg);}100%{-webkit-transform:rotate3d(0, 0, 1, 360deg);transform:rotate3d(0, 0, 1, 360deg);}}.taro-modal__foot:after {content: "";position: absolute;left: 0;top: 0;right: 0;height: 1px;border-top: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);} .taro-model__btn:active {background-color: #EEEEEE}.taro-model__btn:not(:first-child):after {content: "";position: absolute;left: 0;top: 0;width: 1px;bottom: 0;border-left: 1px solid #D5D5D6;color: #D5D5D6;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleX(0.5);transform: scaleX(0.5);}.taro-actionsheet__cell:not(:last-child):after {content: "";position: absolute;left: 0;bottom: 0;right: 0;height: 1px;border-top: 1px solid #e5e5e5;color: #e5e5e5;-webkit-transform-origin: 0 0;transform-origin: 0 0;-webkit-transform: scaleY(0.5);transform: scaleY(0.5);}'
doc.querySelector('head').appendChild(taroStyle)
status = 'ready'
diff --git a/packages/taro-h5/src/api/ui/tab-bar.ts b/packages/taro-h5/src/api/ui/tab-bar.ts
index 96019d88db33..af40adbb28e1 100644
--- a/packages/taro-h5/src/api/ui/tab-bar.ts
+++ b/packages/taro-h5/src/api/ui/tab-bar.ts
@@ -217,7 +217,7 @@ export const setTabBarBadge: typeof Taro.setTabBarBadge = (options) => {
return new Promise((resolve, reject) => {
Taro.eventCenter.trigger('__taroSetTabBarBadge', {
index,
- text,
+ text: text.length > 4 ? '...' : text,
successHandler: (res = {}) => handle.success(res, { resolve, reject }),
errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
})
diff --git a/packages/taro-h5/src/utils/handler.ts b/packages/taro-h5/src/utils/handler.ts
index 6d28feb24fd2..c5a398f43ec6 100644
--- a/packages/taro-h5/src/utils/handler.ts
+++ b/packages/taro-h5/src/utils/handler.ts
@@ -91,6 +91,11 @@ export class CallbackManager {
}
}
+ /** 移除所有回调 */
+ removeAll = () => {
+ this.callbacks = []
+ }
+
/** 获取回调函数数量 */
count = () => {
return this.callbacks.length