@tarojs/taro-h5
Version:
Taro h5 framework
6,638 lines • 274 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var Taro = require('@tarojs/api');
var router$1 = require('@tarojs/router');
var shared = require('@tarojs/shared');
var runtime = require('@tarojs/runtime');
var base64Js = require('base64-js');
var tslib = require('tslib');
var platform = require('platform');
var isNil = require('lodash-es/isNil');
var queryString = require('query-string');
var throttle = require('lodash-es/throttle');
var ics = require('ics');
var components = require('@tarojs/components/dist/components');
var isMobile = require('is-mobile');
require('whatwg-fetch');
require('abortcontroller-polyfill/dist/abortcontroller-polyfill-only');
var jsonpRetry = require('jsonp-retry');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var ics__namespace = /*#__PURE__*/_interopNamespaceDefault(ics);
class MethodHandler {
constructor({ name, success, fail, complete }) {
this.isHandlerError = false;
this.methodName = name;
this.__success = success;
this.__fail = fail;
this.__complete = complete;
this.isHandlerError = shared.isFunction(this.__complete) || shared.isFunction(this.__fail);
}
success(res = {}, promise = {}) {
if (!res.errMsg) {
res.errMsg = `${this.methodName}:ok`;
}
shared.isFunction(this.__success) && this.__success(res);
shared.isFunction(this.__complete) && this.__complete(res);
const { resolve = Promise.resolve.bind(Promise) } = promise;
return resolve(res);
}
fail(res = {}, promise = {}) {
if (!res.errMsg) {
res.errMsg = `${this.methodName}:fail`;
}
else {
res.errMsg = `${this.methodName}:fail ${res.errMsg}`;
}
shared.isFunction(this.__fail) && this.__fail(res);
shared.isFunction(this.__complete) && this.__complete(res);
const { resolve = Promise.resolve.bind(Promise), reject = Promise.reject.bind(Promise) } = promise;
return this.isHandlerError
? resolve(res)
: reject(res);
}
}
class CallbackManager {
constructor() {
this.callbacks = [];
/** 添加回调 */
this.add = (opt) => {
if (opt)
this.callbacks.push(opt);
};
/** 移除回调 */
this.remove = (opt) => {
if (opt) {
let pos = -1;
this.callbacks.forEach((callback, k) => {
if (callback === opt) {
pos = k;
}
});
if (pos > -1) {
this.callbacks.splice(pos, 1);
}
}
else {
// Note: 参数为空,则取消所有的事件监听
this.callbacks = [];
}
};
/** 获取回调函数数量 */
this.count = () => {
return this.callbacks.length;
};
/** 触发回调 */
this.trigger = (...args) => {
this.callbacks.forEach(opt => {
if (shared.isFunction(opt)) {
opt(...args);
}
else {
const { callback, ctx } = opt;
shared.isFunction(callback) && callback.call(ctx, ...args);
}
});
};
/** 清空所有回调 */
this.clear = () => {
this.callbacks = [];
};
}
}
/**
* ease-in-out的函数
* @param t 0-1的数字
*/
const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
const getTimingFunc = (easeFunc, frameCnt) => {
return x => {
if (frameCnt <= 1) {
return easeFunc(1);
}
const t = x / (frameCnt - 1);
return easeFunc(t);
};
};
function createDownload(url = '', download = '') {
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.download = download;
// Note: 需要注意,该方案不能监听用户取消或禁止下载等操作,亦不能获取下载成功或失败状态
link.click();
}
const VALID_COLOR_REG = /^#[0-9a-fA-F]{6}$/;
const isValidColor = (color) => {
return VALID_COLOR_REG.test(color);
};
/* eslint-disable prefer-promise-reject-errors */
function shouldBeObject(target) {
if (target && typeof target === 'object')
return { flag: true };
return {
flag: false,
msg: getParameterError({
correct: 'Object',
wrong: target
})
};
}
function findDOM(inst) {
if (inst && runtime.hooks.isExist('getDOMNode')) {
return runtime.hooks.call('getDOMNode', inst);
}
const page = runtime.Current.page;
const path = page === null || page === void 0 ? void 0 : page.path;
const msg = '没有找到已经加载了的页面,请在页面加载完成后使用此 API。';
if (path == null) {
throw new Error(msg);
}
const el = document.getElementById(path);
if (el == null) {
throw new Error('在已加载页面中没有找到对应的容器元素。');
}
return el;
}
function getParameterError({ name = '', para, correct, wrong, level = 'error' }) {
const parameter = para ? `parameter.${para}` : 'parameter';
const errorType = upperCaseFirstLetter(wrong === null ? 'Null' : typeof wrong);
return `${name ? `${name}:fail ` : ''}parameter ${level}: ${parameter} should be ${correct} instead of ${errorType}`;
}
function upperCaseFirstLetter(string) {
if (typeof string !== 'string')
return string;
string = string.replace(/^./, match => match.toUpperCase());
return string;
}
function inlineStyle(style) {
let res = '';
for (const attr in style)
res += `${attr}: ${style[attr]};`;
if (res.indexOf('display: flex;') >= 0)
res += 'display: -webkit-box;display: -webkit-flex;';
res = res.replace(/transform:(.+?);/g, (s, $1) => `${s}-webkit-transform:${$1};`);
res = res.replace(/flex-direction:(.+?);/g, (s, $1) => `${s}-webkit-flex-direction:${$1};`);
return res;
}
function setTransform(el, val) {
el.style.webkitTransform = val;
el.style.transform = val;
}
function serializeParams(params) {
if (!params) {
return '';
}
return Object.keys(params)
.map(key => (`${encodeURIComponent(key)}=${typeof (params[key]) === 'object'
? encodeURIComponent(JSON.stringify(params[key]))
: encodeURIComponent(params[key])}`))
.join('&');
}
function temporarilyNotSupport(name = '') {
return (option = {}, ...args) => {
const { success, fail, complete } = option;
const handle = new MethodHandler({ name, success, fail, complete });
const errMsg = '暂时不支持 API';
Taro.eventCenter.trigger('__taroNotSupport', {
name,
args: [option, ...args],
type: 'method',
category: 'temporarily',
});
if (process.env.NODE_ENV === 'production') {
console.warn(errMsg);
return handle.success({ errMsg });
}
else {
return handle.fail({ errMsg });
}
};
}
function weixinCorpSupport(name) {
return (option = {}, ...args) => {
const { success, fail, complete } = option;
const handle = new MethodHandler({ name, success, fail, complete });
const errMsg = 'h5 端当前仅在微信公众号 JS-SDK 环境下支持此 API';
Taro.eventCenter.trigger('__taroNotSupport', {
name,
args: [option, ...args],
type: 'method',
category: 'weixin_corp',
});
if (process.env.NODE_ENV === 'production') {
console.warn(errMsg);
return handle.success({ errMsg });
}
else {
return handle.fail({ errMsg });
}
};
}
function permanentlyNotSupport(name = '') {
return (option = {}, ...args) => {
const { success, fail, complete } = option;
const handle = new MethodHandler({ name, success, fail, complete });
const errMsg = '不支持 API';
Taro.eventCenter.trigger('__taroNotSupport', {
name,
args: [option, ...args],
type: 'method',
category: 'permanently',
});
if (process.env.NODE_ENV === 'production') {
console.warn(errMsg);
return handle.success({ errMsg });
}
else {
return handle.fail({ errMsg });
}
};
}
function processOpenApi({ name, defaultOptions, standardMethod, formatOptions = options => options, formatResult = res => res }) {
const notSupported = weixinCorpSupport(name);
return (options = {}, ...args) => {
var _a;
// @ts-ignore
const targetApi = (_a = window === null || window === void 0 ? void 0 : window.wx) === null || _a === void 0 ? void 0 : _a[name];
const opts = formatOptions(Object.assign({}, defaultOptions, options));
if (shared.isFunction(targetApi)) {
return new Promise((resolve, reject) => {
['fail', 'success', 'complete'].forEach(k => {
opts[k] = preRef => {
const res = formatResult(preRef);
options[k] && options[k](res);
if (k === 'success') {
resolve(res);
}
else if (k === 'fail') {
reject(res);
}
};
return targetApi(opts);
});
});
}
else if (shared.isFunction(standardMethod)) {
return standardMethod(opts);
}
else {
return notSupported(options, ...args);
}
};
}
/**
* 获取当前页面路径
* @returns
*/
function getCurrentPath() {
var _a, _b, _c, _d, _e, _f;
const appConfig = window.__taroAppConfig || {};
const routePath = runtime.getCurrentPage((_a = appConfig.router) === null || _a === void 0 ? void 0 : _a.mode, (_b = appConfig.router) === null || _b === void 0 ? void 0 : _b.basename);
const homePath = runtime.getHomePage((_d = (_c = appConfig.routes) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.path, (_e = appConfig.router) === null || _e === void 0 ? void 0 : _e.basename, (_f = appConfig.router) === null || _f === void 0 ? void 0 : _f.customRoutes, appConfig.entryPagePath);
/**
* createPageConfig 时根据 stack 的长度来设置 stamp 以保证页面 path 的唯一,此函数是在 createPageConfig 之前调用,预先设置 stamp=1
* url 上没有指定应用的启动页面时使用 homePath
*/
return `${routePath === '/' ? homePath : routePath}?stamp=1`;
}
// 广告
const createRewardedVideoAd = /* @__PURE__ */ temporarilyNotSupport('createRewardedVideoAd');
const createInterstitialAd = /* @__PURE__ */ temporarilyNotSupport('createInterstitialAd');
// 人脸识别
const stopFaceDetect = /* @__PURE__ */ temporarilyNotSupport('stopFaceDetect');
const initFaceDetect = /* @__PURE__ */ temporarilyNotSupport('initFaceDetect');
const faceDetect = /* @__PURE__ */ temporarilyNotSupport('faceDetect');
// AI推理
const getInferenceEnvInfo = /* @__PURE__ */ temporarilyNotSupport('getInferenceEnvInfo');
const createInferenceSession = /* @__PURE__ */ temporarilyNotSupport('createInferenceSession');
// 判断支持版本
const isVKSupport = /* @__PURE__ */ temporarilyNotSupport('isVKSupport');
// 视觉算法
const createVKSession = /* @__PURE__ */ temporarilyNotSupport('createVKSession');
// AliPay
const getOpenUserInfo = /* @__PURE__ */ temporarilyNotSupport('getOpenUserInfo');
const tradePay = /* @__PURE__ */ temporarilyNotSupport('tradePay');
// 加密
const getUserCryptoManager = /* @__PURE__ */ temporarilyNotSupport('getUserCryptoManager');
const setEnableDebug = /* @__PURE__ */ temporarilyNotSupport('setEnableDebug');
const getRealtimeLogManager = /* @__PURE__ */ temporarilyNotSupport('getRealtimeLogManager');
const getLogManager = /* @__PURE__ */ temporarilyNotSupport('getLogManager');
// 性能
const reportPerformance = /* @__PURE__ */ temporarilyNotSupport('reportPerformance');
const getPerformance = /* @__PURE__ */ temporarilyNotSupport('getPerformance');
const preloadWebview = /* @__PURE__ */ temporarilyNotSupport('preloadWebview');
const preloadSkylineView = /* @__PURE__ */ temporarilyNotSupport('preloadSkylineView');
const preloadAssets = /* @__PURE__ */ temporarilyNotSupport('preloadAssets');
/** 跳转系统蓝牙设置页 */
const openSystemBluetoothSetting = /* @__PURE__ */ temporarilyNotSupport('openSystemBluetoothSetting');
/** 跳转系统微信授权管理页 */
const openAppAuthorizeSetting = /* @__PURE__ */ temporarilyNotSupport('openAppAuthorizeSetting');
/** 获取窗口信息 */
const getWindowInfo = () => {
const info = {
/** 设备像素比 */
pixelRatio: window.devicePixelRatio,
/** 屏幕宽度,单位px */
screenWidth: window.screen.width,
/** 屏幕高度,单位px */
screenHeight: window.screen.height,
/** 可使用窗口宽度,单位px */
windowWidth: document.documentElement.clientWidth,
/** 可使用窗口高度,单位px */
windowHeight: document.documentElement.clientHeight,
/** 状态栏的高度,单位px */
statusBarHeight: NaN,
/** 在竖屏正方向下的安全区域 */
safeArea: {
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0
}
};
return info;
};
/** 获取设备设置 */
const getSystemSetting = () => {
const isLandscape = window.screen.width >= window.screen.height;
const info = {
/** 蓝牙的系统开关 */
bluetoothEnabled: false,
/** 地理位置的系统开关 */
locationEnabled: false,
/** Wi-Fi 的系统开关 */
wifiEnabled: false,
/** 设备方向 */
deviceOrientation: isLandscape ? 'landscape' : 'portrait'
};
return info;
};
/** 获取设备设置 */
const getDeviceInfo = () => {
var _a, _b;
const info = {
/** 应用二进制接口类型(仅 Android 支持) */
abi: '',
/** 设备二进制接口类型(仅 Android 支持) */
deviceAbi: '',
/** 设备性能等级(仅Android小游戏)。取值为:-2 或 0(该设备无法运行小游戏),-1(性能未知),>=1(设备性能值,该值越高,设备性能越好,目前最高不到50) */
benchmarkLevel: -1,
/** 设备品牌 */
brand: platform.manufacturer || 'unknown',
/** 设备型号 */
model: platform.product || 'unknown',
/** 操作系统及版本 */
system: ((_a = platform.os) === null || _a === void 0 ? void 0 : _a.toString()) || 'unknown',
/** 客户端平台 */
platform: ((_b = platform.os) === null || _b === void 0 ? void 0 : _b.family) || 'unknown',
/** 设备二进制接口类型(仅 Android 支持) */
CPUType: '',
};
return info;
};
/** 获取微信APP基础信息 */
const getAppBaseInfo = () => {
var _a;
let isDarkMode = false;
if ((_a = window.matchMedia) === null || _a === void 0 ? void 0 : _a.call(window, '(prefers-color-scheme: dark)').matches) {
isDarkMode = true;
}
const info = {
/** 客户端基础库版本 */
SDKVersion: '',
/** 是否已打开调试。可通过右上角菜单或 [Taro.setEnableDebug](/docs/apis/base/debug/setEnableDebug) 打开调试。 */
enableDebug: process.env.NODE_ENV !== 'production',
/** 当前小程序运行的宿主环境 */
// host: { appId: '' },
/** 微信设置的语言 */
language: navigator.language,
/** 微信版本号 */
version: '',
/** 系统当前主题,取值为light或dark,全局配置"darkmode":true时才能获取,否则为 undefined (不支持小游戏) */
theme: isDarkMode ? 'dark' : 'light'
};
return info;
};
/** 获取微信APP授权设置 */
const getAppAuthorizeSetting = () => {
const info = {
/** 允许微信使用相册的开关(仅 iOS 有效) */
albumAuthorized: 'not determined',
/** 允许微信使用蓝牙的开关(仅 iOS 有效) */
bluetoothAuthorized: 'not determined',
/** 允许微信使用摄像头的开关 */
cameraAuthorized: 'not determined',
/** 允许微信使用定位的开关 */
locationAuthorized: 'not determined',
/** 定位准确度。true 表示模糊定位,false 表示精确定位(仅 iOS 有效) */
locationReducedAccuracy: false,
/** 允许微信使用麦克风的开关 */
microphoneAuthorized: 'not determined',
/** 允许微信通知的开关 */
notificationAuthorized: 'not determined',
/** 允许微信通知带有提醒的开关(仅 iOS 有效) */
notificationAlertAuthorized: 'not determined',
/** 允许微信通知带有标记的开关(仅 iOS 有效) */
notificationBadgeAuthorized: 'not determined',
/** 允许微信通知带有声音的开关(仅 iOS 有效) */
notificationSoundAuthorized: 'not determined',
/** 允许微信使用日历的开关 */
phoneCalendarAuthorized: 'not determined'
};
return info;
};
/** 获取设备设置 */
const getSystemInfoSync = () => {
const windowInfo = getWindowInfo();
const systemSetting = getSystemSetting();
const deviceInfo = getDeviceInfo();
const appBaseInfo = getAppBaseInfo();
const appAuthorizeSetting = getAppAuthorizeSetting();
delete deviceInfo.abi;
const info = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, windowInfo), systemSetting), deviceInfo), appBaseInfo), {
/** 用户字体大小(单位px)。以微信客户端「我-设置-通用-字体大小」中的设置为准 */
fontSizeSetting: NaN,
/** 允许微信使用相册的开关(仅 iOS 有效) */
albumAuthorized: appAuthorizeSetting.albumAuthorized === 'authorized',
/** 允许微信使用摄像头的开关 */
cameraAuthorized: appAuthorizeSetting.cameraAuthorized === 'authorized',
/** 允许微信使用定位的开关 */
locationAuthorized: appAuthorizeSetting.locationAuthorized === 'authorized',
/** 允许微信使用麦克风的开关 */
microphoneAuthorized: appAuthorizeSetting.microphoneAuthorized === 'authorized',
/** 允许微信通知的开关 */
notificationAuthorized: appAuthorizeSetting.notificationAuthorized === 'authorized',
/** 允许微信通知带有提醒的开关(仅 iOS 有效) */
notificationAlertAuthorized: appAuthorizeSetting.notificationAlertAuthorized === 'authorized',
/** 允许微信通知带有标记的开关(仅 iOS 有效) */
notificationBadgeAuthorized: appAuthorizeSetting.notificationBadgeAuthorized === 'authorized',
/** 允许微信通知带有声音的开关(仅 iOS 有效) */
notificationSoundAuthorized: appAuthorizeSetting.notificationSoundAuthorized === 'authorized',
/** 允许微信使用日历的开关 */
phoneCalendarAuthorized: appAuthorizeSetting.phoneCalendarAuthorized === 'authorized',
/** `true` 表示模糊定位,`false` 表示精确定位,仅 iOS 支持 */
locationReducedAccuracy: appAuthorizeSetting.locationReducedAccuracy,
/** 小程序当前运行环境 */
environment: '' });
return info;
};
/** 获取系统信息 */
const getSystemInfoAsync = (...args_1) => tslib.__awaiter(void 0, [...args_1], void 0, function* (options = {}) {
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'getSystemInfoAsync', success, fail, complete });
try {
const info = yield getSystemInfoSync();
return handle.success(info);
}
catch (error) {
return handle.fail({
errMsg: error
});
}
});
/** 获取系统信息 */
const getSystemInfo = (...args_2) => tslib.__awaiter(void 0, [...args_2], void 0, function* (options = {}) {
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'getSystemInfo', success, fail, complete });
try {
const info = yield getSystemInfoSync();
return handle.success(info);
}
catch (error) {
return handle.fail({
errMsg: error
});
}
});
const getSkylineInfoSync = /* @__PURE__ */ temporarilyNotSupport('getSkylineInfoSync');
const getSkylineInfo = /* @__PURE__ */ temporarilyNotSupport('getSkylineInfo');
const getRendererUserAgent = /* @__PURE__ */ temporarilyNotSupport('getRendererUserAgent');
// 更新
const updateWeChatApp = /* @__PURE__ */ temporarilyNotSupport('updateWeChatApp');
const getUpdateManager = /* @__PURE__ */ temporarilyNotSupport('getUpdateManager');
const unhandledRejectionCallbackManager = new CallbackManager();
const themeChangeCallbackManager = new CallbackManager();
const pageNotFoundCallbackManager = new CallbackManager();
const errorCallbackManager = new CallbackManager();
const appShowCallbackManager = new CallbackManager();
const appHideCallbackManager = new CallbackManager();
const unhandledRejectionListener = (res) => {
unhandledRejectionCallbackManager.trigger(res);
};
let themeMatchMedia = null;
const themeChangeListener = (res) => {
themeChangeCallbackManager.trigger({
theme: res.matches ? 'light' : 'dark'
});
};
const pageNotFoundListener = (res) => {
pageNotFoundCallbackManager.trigger(res);
};
const errorListener = (res) => {
// @ts-ignore
errorCallbackManager.trigger(res.stack || res.message || res);
};
const getApp$1 = () => {
var _a;
const path = (_a = Taro.Current.page) === null || _a === void 0 ? void 0 : _a.path;
return {
/** 小程序切前台的路径 */
path: (path === null || path === void 0 ? void 0 : path.substring(0, path.indexOf('?'))) || '',
/** 小程序切前台的 query 参数 */
query: queryString.parse(location.search),
/** 来源信息。 */
referrerInfo: {},
/** 小程序切前台的[场景值](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/scene.html) */
scene: 0,
/** shareTicket,详见[获取更多转发信息](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share.html) */
shareTicket: ''
};
};
const appShowListener = () => {
if (document.visibilityState !== 'hidden') {
appShowCallbackManager.trigger(getApp$1());
}
};
const appHideListener = () => {
if (document.visibilityState === 'hidden') {
appHideCallbackManager.trigger(getApp$1());
}
};
// 应用级事件
const onUnhandledRejection = callback => {
unhandledRejectionCallbackManager.add(callback);
if (unhandledRejectionCallbackManager.count() === 1) {
window.addEventListener('unhandledrejection', unhandledRejectionListener);
}
};
const onThemeChange = callback => {
themeChangeCallbackManager.add(callback);
if (themeChangeCallbackManager.count() === 1) {
if (isNil(themeMatchMedia)) {
themeMatchMedia = window.matchMedia('(prefers-color-scheme: light)');
}
themeMatchMedia.addEventListener('change', themeChangeListener);
}
};
const onPageNotFound = callback => {
pageNotFoundCallbackManager.add(callback);
if (pageNotFoundCallbackManager.count() === 1) {
Taro.eventCenter.on('__taroRouterNotFound', pageNotFoundListener);
}
};
const onLazyLoadError = /* @__PURE__ */ temporarilyNotSupport('onLazyLoadError');
const onError = callback => {
errorCallbackManager.add(callback);
if (errorCallbackManager.count() === 1) {
window.addEventListener('error', errorListener);
}
};
const onAudioInterruptionEnd = /* @__PURE__ */ temporarilyNotSupport('onAudioInterruptionEnd');
const onAudioInterruptionBegin = /* @__PURE__ */ temporarilyNotSupport('onAudioInterruptionBegin');
const onAppShow = callback => {
appShowCallbackManager.add(callback);
if (appShowCallbackManager.count() === 1) {
window.addEventListener('visibilitychange', appShowListener);
}
};
const onAppHide = callback => {
appHideCallbackManager.add(callback);
if (appHideCallbackManager.count() === 1) {
window.addEventListener('visibilitychange', appHideListener);
}
};
const offUnhandledRejection = callback => {
unhandledRejectionCallbackManager.remove(callback);
if (unhandledRejectionCallbackManager.count() === 0) {
window.removeEventListener('unhandledrejection', unhandledRejectionListener);
}
};
const offThemeChange = callback => {
themeChangeCallbackManager.remove(callback);
if (themeChangeCallbackManager.count() === 0) {
if (isNil(themeMatchMedia)) {
themeMatchMedia = window.matchMedia('(prefers-color-scheme: light)');
}
themeMatchMedia.removeEventListener('change', themeChangeListener);
themeMatchMedia = null;
}
};
const offPageNotFound = callback => {
pageNotFoundCallbackManager.remove(callback);
if (pageNotFoundCallbackManager.count() === 0) {
Taro.eventCenter.off('__taroRouterNotFound', pageNotFoundListener);
}
};
const offLazyLoadError = /* @__PURE__ */ temporarilyNotSupport('offLazyLoadError');
const offError = callback => {
errorCallbackManager.remove(callback);
if (errorCallbackManager.count() === 0) {
window.removeEventListener('error', errorListener);
}
};
const offAudioInterruptionEnd = /* @__PURE__ */ temporarilyNotSupport('offAudioInterruptionEnd');
const offAudioInterruptionBegin = /* @__PURE__ */ temporarilyNotSupport('offAudioInterruptionBegin');
const offAppShow = callback => {
appShowCallbackManager.remove(callback);
if (appShowCallbackManager.count() === 0) {
window.removeEventListener('visibilitychange', appShowListener);
}
};
const offAppHide = callback => {
appHideCallbackManager.remove(callback);
if (appHideCallbackManager.count() === 0) {
window.removeEventListener('visibilitychange', appHideListener);
}
};
const launchOptions = {
path: '',
query: {},
scene: 0,
shareTicket: '',
referrerInfo: {}
};
function initLaunchOptions(options = {}) {
Object.assign(launchOptions, options);
}
Taro.eventCenter.once('__taroRouterLaunch', initLaunchOptions);
// 生命周期
const getLaunchOptionsSync = () => launchOptions;
const getEnterOptionsSync = () => launchOptions;
const env = {
FRAMEWORK: process.env.FRAMEWORK,
TARO_ENV: process.env.TARO_ENV,
TARO_PLATFORM: process.env.TARO_PLATFORM,
TARO_VERSION: process.env.TARO_VERSION,
};
// Note: 该方法由 taro-plugin-platform-h5 实现
// export const canIUse = /* @__PURE__ */ temporarilyNotSupport('canIUse')
function arrayBufferToBase64(arrayBuffer) {
return base64Js.fromByteArray(arrayBuffer);
}
function base64ToArrayBuffer(base64) {
return base64Js.toByteArray(base64).buffer;
}
const TextBaseLineMap = {
top: 'top',
bottom: 'bottom',
middle: 'middle',
normal: 'alphabetic',
hanging: 'hanging',
alphabetic: 'alphabetic',
ideographic: 'ideographic'
};
class CanvasContext {
constructor(canvas, ctx) {
this.actions = [];
this.canvas = canvas;
this.ctx = ctx;
}
set ctx(e) {
this.__raw__ = e;
}
get ctx() {
return this.__raw__ || {};
}
emptyActions() {
this.actions.length = 0;
}
enqueueActions(func, ...args) {
this.actions.push({
func,
args
});
}
set fillStyle(e) { this.enqueueActions(() => { this.ctx.fillStyle = e; }); }
get fillStyle() { return this.ctx.fillStyle; }
set font(e) { this.ctx.font = e; }
get font() { return this.ctx.font; }
set globalAlpha(e) { this.enqueueActions(() => { this.ctx.globalAlpha = e; }); }
get globalAlpha() { return this.ctx.globalAlpha; }
set globalCompositeOperation(e) { this.enqueueActions(() => { this.ctx.globalCompositeOperation = e; }); }
get globalCompositeOperation() { return this.ctx.globalCompositeOperation; }
set lineCap(e) { this.enqueueActions(() => { this.ctx.lineCap = e; }); }
get lineCap() { return this.ctx.lineCap; }
set lineDashOffset(e) { this.enqueueActions(() => { this.ctx.lineDashOffset = e; }); }
get lineDashOffset() { return this.ctx.lineDashOffset; }
set lineJoin(e) { this.enqueueActions(() => { this.ctx.lineJoin = e; }); }
get lineJoin() { return this.ctx.lineJoin; }
set lineWidth(e) { this.enqueueActions(() => { this.ctx.lineWidth = e; }); }
get lineWidth() { return this.ctx.lineWidth; }
set miterLimit(e) { this.enqueueActions(() => { this.ctx.miterLimit = e; }); }
get miterLimit() { return this.ctx.miterLimit; }
set shadowBlur(e) { this.enqueueActions(() => { this.ctx.shadowBlur = e; }); }
get shadowBlur() { return this.ctx.shadowBlur; }
set shadowColor(e) { this.enqueueActions(() => { this.ctx.shadowColor = e; }); }
get shadowColor() { return this.ctx.shadowColor; }
set shadowOffsetX(e) { this.enqueueActions(() => { this.ctx.shadowOffsetX = e; }); }
get shadowOffsetX() { return this.ctx.shadowOffsetX; }
set shadowOffsetY(e) { this.enqueueActions(() => { this.ctx.shadowOffsetY = e; }); }
get shadowOffsetY() { return this.ctx.shadowOffsetY; }
set strokeStyle(e) { this.enqueueActions(() => { this.ctx.strokeStyle = e; }); }
get strokeStyle() { return this.ctx.strokeStyle; }
/** 小程序文档中不包括 ↓↓↓ */
set textAlign(e) { this.ctx.textAlign = e; }
get textAlign() { return this.ctx.textAlign; }
set textBaseline(e) { this.ctx.textBaseline = e; }
get textBaseline() { return this.ctx.textBaseline; }
set direction(e) { this.ctx.direction = e; }
get direction() { return this.ctx.direction; }
set imageSmoothingEnabled(e) { this.enqueueActions(() => { this.ctx.imageSmoothingEnabled = e; }); }
get imageSmoothingEnabled() { return this.ctx.imageSmoothingEnabled; }
set imageSmoothingQuality(e) { this.enqueueActions(() => { this.ctx.imageSmoothingQuality = e; }); }
get imageSmoothingQuality() { return this.ctx.imageSmoothingQuality; }
set filter(e) { this.enqueueActions(() => { this.ctx.filter = e; }); }
get filter() { return this.ctx.filter; }
/** 小程序文档中不包括 ↑↑↑ */
arc(...args) { return this.enqueueActions(this.ctx.arc, ...args); }
arcTo(...args) { return this.enqueueActions(this.ctx.arcTo, ...args); }
beginPath(...args) { return this.enqueueActions(this.ctx.beginPath, ...args); }
bezierCurveTo(...args) { return this.enqueueActions(this.ctx.bezierCurveTo, ...args); }
clearRect(...args) { return this.enqueueActions(this.ctx.clearRect, ...args); }
clip(...args) { return this.enqueueActions(this.ctx.clip, ...args); }
closePath(...args) { return this.enqueueActions(this.ctx.closePath, ...args); }
createPattern(imageResource, repetition) {
// 需要转换为 Image
if (typeof imageResource === 'string') {
const img = new Image();
img.src = imageResource;
return new Promise((resolve, reject) => {
img.onload = () => {
resolve(this.ctx.createPattern(img, repetition));
};
img.onerror = reject;
});
}
return this.ctx.createPattern(imageResource, repetition);
}
/**
* 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
* @todo 每次 draw 都会读取 width 和 height
*/
draw(reserve, callback) {
return tslib.__awaiter(this, void 0, void 0, function* () {
try {
if (!reserve) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
// 部分 action 是异步的
for (const { func, args } of this.actions) {
yield func.apply(this.ctx, args);
}
this.emptyActions();
callback && callback();
}
catch (e) {
/* eslint-disable no-throw-literal */
throw {
errMsg: e.message
};
}
});
}
drawImage(imageResource, ...extra) {
this.enqueueActions(() => {
// 需要转换为 Image
if (typeof imageResource === 'string') {
const img = new Image();
img.src = imageResource;
return new Promise((resolve, reject) => {
img.onload = () => {
this.ctx.drawImage(img, ...extra);
resolve();
};
img.onerror = reject;
});
}
this.ctx.drawImage(imageResource, ...extra);
});
}
fill(...args) { return this.enqueueActions(this.ctx.fill, ...args); }
fillRect(...args) { return this.enqueueActions(this.ctx.fillRect, ...args); }
fillText(...args) { return this.enqueueActions(this.ctx.fillText, ...args); }
lineTo(...args) { return this.enqueueActions(this.ctx.lineTo, ...args); }
moveTo(...args) { return this.enqueueActions(this.ctx.moveTo, ...args); }
quadraticCurveTo(...args) { return this.enqueueActions(this.ctx.quadraticCurveTo, ...args); }
rect(...args) { return this.enqueueActions(this.ctx.rect, ...args); }
// @ts-ignore
reset() { return this.ctx.reset(); }
restore() { return this.ctx.restore(); }
rotate(...args) { return this.enqueueActions(this.ctx.rotate, ...args); }
save() { return this.ctx.save(); }
scale(...args) { return this.enqueueActions(this.ctx.scale, ...args); }
setFillStyle(color) {
this.enqueueActions(() => { this.ctx.fillStyle = color; });
}
setFontSize(fontSize) {
const arr = this.font.split(/\s/);
const idx = arr.findIndex(e => /^\d+px$/.test(e));
if (idx !== -1) {
arr[idx] = `${fontSize}px`;
this.font = arr.join(' ');
}
}
setGlobalAlpha(alpha) {
this.globalAlpha = alpha;
}
setLineCap(lineCap) {
this.lineCap = lineCap;
}
setLineDash(pattern, offset) {
this.enqueueActions(() => {
this.ctx.setLineDash(pattern);
this.ctx.lineDashOffset = offset;
});
}
setLineJoin(lineJoin) {
this.lineJoin = lineJoin;
}
setLineWidth(lineWidth) {
this.lineWidth = lineWidth;
}
setMiterLimit(miterLimit) {
this.miterLimit = miterLimit;
}
setShadow(offsetX, offsetY, blur, color) {
this.enqueueActions(() => {
this.ctx.shadowOffsetX = offsetX;
this.ctx.shadowOffsetY = offsetY;
this.ctx.shadowColor = color;
this.ctx.shadowBlur = blur;
});
}
setStrokeStyle(color) {
this.enqueueActions(() => { this.ctx.strokeStyle = color; });
}
setTextAlign(align) {
this.textAlign = align;
}
setTextBaseline(textBaseline) {
this.textBaseline = TextBaseLineMap[textBaseline] || 'alphabetic';
}
setTransform(...args) { return this.enqueueActions(this.ctx.setTransform, ...args); }
stroke(...args) { return this.enqueueActions(this.ctx.stroke, ...args); }
strokeRect(...args) { return this.enqueueActions(this.ctx.strokeRect, ...args); }
strokeText(...args) { return this.enqueueActions(this.ctx.strokeText, ...args); }
transform(...args) { return this.enqueueActions(this.ctx.transform, ...args); }
translate(...args) { return this.enqueueActions(this.ctx.translate, ...args); }
measureText(text) {
return this.ctx.measureText(text);
}
createCircularGradient(x, y, r) {
const radialGradient = this.ctx.createRadialGradient(x, y, 0, x, y, r);
return radialGradient;
}
createLinearGradient(x0, y0, x1, y1) {
return this.ctx.createLinearGradient(x0, y0, x1, y1);
}
}
/**
* 创建 canvas 的绘图上下文 CanvasContext 对象
*/
const createCanvasContext = (canvasId, inst) => {
const el = findDOM(inst);
const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
const context = new CanvasContext(canvas, ctx);
if (!ctx)
return context;
context.canvas = canvas;
context.ctx = ctx;
return context;
};
/**
* 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
* @todo 暂未支持尺寸相关功能
*/
const canvasToTempFilePath = ({ canvasId, fileType, quality, success, fail, complete }, inst) => {
const handle = new MethodHandler({ name: 'canvasToTempFilePath', success, fail, complete });
const el = findDOM(inst);
const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
try {
const dataURL = canvas === null || canvas === void 0 ? void 0 : canvas.toDataURL(`image/${(fileType === 'jpg' ? 'jpeg' : fileType) || 'png'}`, quality);
return handle.success({
tempFilePath: dataURL
});
}
catch (e) {
return handle.fail({
errMsg: e.message
});
}
};
/**
* 将像素数据绘制到画布。在自定义组件下,第二个参数传入自定义组件实例 this,以操作组件内 <canvas> 组件
* @todo 暂未支持尺寸相关功能
*/
const canvasPutImageData = ({ canvasId, data, x, y, success, fail, complete }, inst) => {
const handle = new MethodHandler({ name: 'canvasPutImageData', success, fail, complete });
const el = findDOM(inst);
const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
try {
const ctx = canvas.getContext('2d');
// TODO Uint8ClampedArray => ImageData
ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(data, x, y);
return handle.success();
}
catch (e) {
return handle.fail({
errMsg: e.message
});
}
};
/**
* 获取 canvas 区域隐含的像素数据。
*/
const canvasGetImageData = ({ canvasId, success, fail, complete, x, y, width, height }, inst) => {
const handle = new MethodHandler({ name: 'canvasGetImageData', success, fail, complete });
const el = findDOM(inst);
const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
try {
const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
// TODO ImageData => Uint8ClampedArray
const data = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(x, y, width, height);
return handle.success({
width,
height,
data
});
}
catch (e) {
return handle.fail({
errMsg: e.message
});
}
};
// 画布
/** 创建离屏 canvas 实例 */
const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas');
class cloud {
constructor() {
this.init = temporarilyNotSupport('cloud.init');
this.CloudID = temporarilyNotSupport('cloud.CloudID');
// @ts-ignore
this.callFunction = temporarilyNotSupport('cloud.callFunction');
// @ts-ignore
this.uploadFile = temporarilyNotSupport('cloud.uploadFile');
// @ts-ignore
this.downloadFile = temporarilyNotSupport('cloud.downloadFile');
// @ts-ignore
this.getTempFileURL = temporarilyNotSupport('cloud.getTempFileURL');
// @ts-ignore
this.deleteFile = temporarilyNotSupport('cloud.deleteFile');
// @ts-ignore
this.database = temporarilyNotSupport('cloud.database');
// @ts-ignore
this.callContainer = temporarilyNotSupport('cloud.callContainer');
}
}
const reportMonitor = /* @__PURE__ */ temporarilyNotSupport('reportMonitor');
const reportAnalytics = /* @__PURE__ */ temporarilyNotSupport('reportAnalytics');
const reportEvent = /* @__PURE__ */ temporarilyNotSupport('reportEvent');
const getExptInfoSync = /* @__PURE__ */ temporarilyNotSupport('getExptInfoSync');
const callbackManager$3 = new CallbackManager();
let devicemotionListener;
/**
* 停止监听加速度数据。
*/
const stopAccelerometer = ({ success, fail, complete } = {}) => {
const res = {};
const handle = new MethodHandler({ name: 'stopAccelerometer', success, fail, complete });
try {
window.removeEventListener('devicemotion', devicemotionListener, true);
return handle.success(res);
}
catch (e) {
res.errMsg = e.message;
return handle.fail(res);
}
};
const INTERVAL_MAP$1 = {
game: {
interval: 20,
frequency: 50
},
ui: {
interval: 60,
frequency: 16.67
},
normal: {
interval: 200,
frequency: 5
}
};
/**
* 开始监听加速度数据。
*/
const startAccelerometer = ({ interval = 'normal', success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'startAccelerometer', success, fail, complete });
try {
if (window.DeviceMotionEvent) {
const intervalObj = INTERVAL_MAP$1[interval];
if (devicemotionListener) {
stopAccelerometer();
}
devicemotionListener = throttle((evt) => {
var _a, _b, _c;
callbackManager$3.trigger({
x: ((_a = evt.acceleration) === null || _a === void 0 ? void 0 : _a.x) || 0,
y: ((_b = evt.acceleration) === null || _b === void 0 ? void 0 : _b.y) || 0,
z: ((_c = evt.acceleration) === null || _c === void 0 ? void 0 : _c.z) || 0
});
}, intervalObj.interval);
window.addEventListener('devicemotion', devicemotionListener, true);
}
else {
throw new Error('accelerometer is not supported');
}
return handle.success();
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
};
/**
* 监听加速度数据事件。频率根据 Taro.startAccelerometer() 的 interval 参数。可使用 Taro.stopAccelerometer() 停止监听。
*/
const onAccelerometerChange = callback => {
callbackManager$3.add(callback);
};
/**
* 取消监听加速度数据事件,参数为空,则取消所有的事件监听
*/
const offAccelerometerChange = callback => {
callbackManager$3.remove(callback);
};
// 无障碍
const checkIsOpenAccessibility = /* @__PURE__ */ temporarilyNotSupport('checkIsOpenAccessibility');
// 电量
// Note: 浏览器标准下不支持,其他实现方案不准确,不建议开发者使用
const getBatteryInfoSync = /* @__PURE__ */ permanentlyNotSupport('getBatteryInfoSync');
const getBatteryInfo = (...args_1) => tslib.__awaiter(void 0, [...args_1], void 0, function* ({ success, fail, complete } = {}) {
var _a;
const handle = new MethodHandler({ name: 'getBatteryInfo', success, fail, complete });
try {
// @ts-ignore
const battery = yield ((_a = navigator.getBattery) === null || _a === void 0 ? void 0 : _a.call(navigator));
return handle.success({
isCharging: battery.charging,
level: Number(battery.level || 0) * 100
});
}
catch (error) {
return handle.fail({
errMsg: (error === null || error === void 0 ? void 0 : error.message) || error
});
}
});
// 蓝牙-通用
const stopBluetoothDevicesDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopBluetoothDevicesDiscovery');
const startBluetoothDevicesDiscovery = /* @__PURE__ */ temporarilyNotSupport('startBluetoothDevicesDiscovery');
const openBluetoothAdapter = /* @__PURE__ */ temporarilyNotSupport('openBluetoothAdapter');
const onBluetoothDeviceFound = /* @__PURE__ */ temporarilyNotSupport('onBluetoothDeviceFound');
const onBluetoothAdapterStateChange = /* @__PURE__ */ temporarilyNotSupport('onBluetoothAdapterStateChange');
const offBluetoothDeviceFound = /* @__PURE__ */ temporarilyNotSupport('offBluetoothDeviceFound');
const offBluetoothAdapterStateChange = /* @__PURE__ */ temporarilyNotSupport('offBluetoothAdapterStateChange');
const makeBluetoothPair = /* @__PURE__ */ temporarilyNotSupport('makeBluetoothPair');
const isBluetoothDevicePaired = /* @__PURE__ */ temporarilyNotSupport('isBluetoothDevicePaired');
const getConnectedBluetoothDevices = /* @__PURE__ */ temporarilyNotSupport('getConnectedBluetoothDevices');
const getBluetoothDevices = /* @__PURE__ */ temporarilyNotSupport('getBluetoothDevices');
const getBluetoothAdapterState = /* @__PURE__ */ temporarilyNotSupport('getBluetoothAdapterState');
const closeBluetoothAdapter = /* @__PURE__ */ temporarilyNotSupport('closeBluetoothAdapter');
// 蓝牙-低功耗中心设备
const writeBLECharacteristicValue = /* @__PURE__ */ temporarilyNotSupport('writeBLECharacteristicValue');
const setBLEMTU = /* @__PURE__ */ temporarilyNotSupport('setBLEMTU');
const readBLECharacteristicValue = /* @__PURE__ */ temporarilyNotSupport('readBLECharacteristicValue');
const onBLEMTUChange = /* @__PURE__ */ temporarilyNotSupport('onBLEMTUChange');
const onBLEConnectionStateChange = /* @__PURE__ */ temporarilyNotSupport('onBLEConnectionStateChange');
const onBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('onBLECharacteristicValueChange');
const offBLEMTUChange = /* @__PURE__ */ temporarilyNotSupport('offBLEMTUChange');
const offBLEConnectionStateChange = /* @__PURE__ */ temporarilyNotSupport('offBLEConnectionStateChange');
const offBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('offBLECharacteristicValueChange');
const notifyBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('notifyBLECharacteristicValueChange');
const getBLEMTU = /* @__PURE__ */ temporarilyNotSupport('getBLEMTU');
const getBLEDeviceServices = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceServices');
const getBLEDeviceRSSI = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceRSSI');
const getBLEDeviceCharacteristics = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceCharacteristics');
const createBLEConnection = /* @__PURE__ */ temporarilyNotSupport('createBLEConnection');
const closeBLEConnection = /* @__PURE__ */ temporarilyNotSupport('closeBLEConnection');
// 蓝牙-低功耗外围设备
const onBLEPeripheralConnectionStateChanged = /* @__PURE__ */ temporarilyNotSupport('onBLEPeripheralConnectionStateChanged');
const offBLEPeripheralConnectionStateChanged = /* @__PURE__ */ temporarilyNotSupport('offBLEPeripheralConnectionStateChanged');
const createBLEPeripheralServer = /* @__PURE__ */ temporarilyNotSupport('createBLEPeripheralServer');
// 日历
const 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__namespace.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 === null || error === void 0 ? void 0 : error.message
});
}
const url = URL.createObjectURL(new Blob([value]));
createDownload(url, `${title}.ics`);
return handle.success();
};
const 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__namespace.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 === null || error === void 0 ? void 0 : error.message
});
}
const url = URL.createObjectURL(new Blob([value]));
createDownload(url, `${title}.ics`);
return handle.success();
};
function parseTime2Array(time, allDay = false) {
const t = new Date(time);
const timeArr = [
t.getFullYear(),
t.getMonth() + 1,
t.getDate(),
];
if (!allDay) {
timeArr.push(t.getHours(), t.getMinutes());
}
return timeArr;
}
// 周期性更新
const setBackgroundFetchToken = /* @__PURE__ */ temporarilyNotSupport('setBackgroundFetchToken');
const onBackgroundFetchData = /* @__PURE__ */ temporarilyNotSupport('onBackgroundFetchData');
const getBackgroundFetchToken = /* @__PURE__ */ temporarilyNotSupport('getBackgroundFetchToken');
const getBackgroundFetchData = /* @__PURE__ */ temporarilyNotSupport('getBackgroundFetchData');
// 周期性更新
const createCacheManager = /* @__PURE__ */ temporarilyNotSupport('createCacheManager');
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 };
}
}
// 数据缓存
const 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));
};
const 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();
};
const revokeBufferURL = /* @__PURE__ */ temporarilyNotSupport('revokeBufferURL');
const removeStorageSync = (key) => {
if (typeof key !== 'string') {
console.error(getParameterError({
name: 'removeStorage',
correct: 'String',
wrong: key
}));
return;
}
localStorage.removeItem(key);
};
const removeStorage = (options) => {
// 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();
};
const 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 '';
};
const getStorageInfoSync = () => {
const res = {
keys: Object.keys(localStorage),
limitSize: NaN,
currentSize: NaN
};
return res;
};
const getStorageInfo = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'getStorageInfo', success, fail, complete });
return handle.success(getStorageInfoSync());
};
const 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'
});
}
};
const createBufferURL = /* @__PURE__ */ temporarilyNotSupport('createBufferURL');
const clearStorageSync = () => {
localStorage.clear();
};
const clearStorage = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'clearStorage', success, fail, complete });
clearStorageSync();
return handle.success();
};
const batchSetStorageSync = /* @__PURE__ */ temporarilyNotSupport('batchSetStorageSync');
const batchSetStorage = /* @__PURE__ */ temporarilyNotSupport('batchSetStorage');
const batchGetStorageSync = /* @__PURE__ */ temporarilyNotSupport('batchGetStorageSync');
const batchGetStorage = /* @__PURE__ */ temporarilyNotSupport('batchGetStorage');
const noop = function () { };
class ActionSheet {
constructor() {
this.options = {
alertText: '',
itemList: [],
itemColor: '#000000',
success: noop,
fail: noop,
complete: noop,
};
this.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',
},
};
this.lastConfig = {};
}
create(options = {}) {
return new Promise((resolve) => {
// style
const { maskStyle, actionSheetStyle, menuStyle, cellStyle, titleStyle, cancelStyle } = this.style;
// configuration
const config = Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, menuStyle), { color: config.itemColor })));
// cells
this.cells = config.itemList.map((item, index) => {
const cell = 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;
const index = Number(target === null || target === void 0 ? void 0 : 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 = Object.assign(Object.assign({}, 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;
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;
const index = Number(target === null || target === void 0 ? void 0 : 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);
}
}
class Modal {
constructor() {
this.options = {
title: '',
content: '',
showCancel: true,
cancelText: '取消',
cancelColor: '#000000',
confirmText: '确定',
confirmColor: '#3CC51F'
};
this.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'
}
};
}
create(options = {}) {
return new Promise((resolve) => {
var _a, _b;
// style
const { maskStyle, modalStyle, titleStyle, textStyle, footStyle, btnStyle } = this.style;
// configuration
const config = Object.assign(Object.assign({}, 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 : Object.assign(Object.assign({}, 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 : Object.assign(Object.assign({}, 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 = Object.assign(Object.assign({}, 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 = (_b = (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
});
}
show(options = {}) {
return new Promise((resolve) => {
var _a, _b;
const config = Object.assign(Object.assign({}, 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 = Object.assign(Object.assign({}, 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 = (_b = (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : 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);
}
}
class Toast {
constructor() {
this.options = {
title: '',
icon: 'none',
image: '',
duration: 1500,
mask: false
};
this.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(17, 17, 17, 0.7)'
},
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'
}
};
}
create(options = {}, _type = 'toast') {
var _a, _b;
// style
const { maskStyle, toastStyle, successStyle, errrorStyle, loadingStyle, imageStyle, textStyle } = this.style;
// configuration
const config = Object.assign(Object.assign(Object.assign({}, 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';
this.el.ontouchmove = (e) => {
e.stopPropagation();
e.preventDefault();
};
// 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(Object.assign(Object.assign({}, imageStyle), { 'background-image': `url(${config.image})` })));
}
else {
const iconStyle = config.icon === 'loading' ? loadingStyle : config.icon === 'error' ? errrorStyle : successStyle;
this.icon.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, iconStyle), (config.icon === 'none' ? { display: 'none' } : {}))));
}
// toast
this.toast = document.createElement('div');
this.toast.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, 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 = (_b = (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
return '';
}
show(options = {}, _type = 'toast') {
var _a, _b;
const config = Object.assign(Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, iconStyle), (config.icon === 'none' ? { display: 'none' } : {}))));
}
}
// toast
this.toast.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, 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 = (_b = (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : 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);
}
}
// 交互
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, 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';
}
const toast = new Toast();
const modal = new Modal();
const actionSheet = new ActionSheet();
const 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 });
};
const 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();
};
const 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 });
};
const 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();
};
const showModal = (...args_1) => tslib.__awaiter(void 0, [...args_1], void 0, function* (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 });
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 = yield modal.create(options);
}
else {
result = yield modal.show(options);
}
const res = { cancel: !1, confirm: !1 };
res[result] = !0;
return handle.success(res);
});
function hideModal() {
if (!modal.el)
return;
modal.hide();
}
const showActionSheet = (...args_2) => tslib.__awaiter(void 0, [...args_2], void 0, function* (options = { itemList: [] }, methodName = 'showActionSheet') {
init(document);
options = Object.assign({
itemColor: '#000000',
itemList: []
}, options);
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: methodName, 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 = '';
if (!actionSheet.el) {
result = yield actionSheet.create(options);
}
else {
result = yield actionSheet.show(options);
}
if (typeof result === 'string') {
return handle.fail(({ errMsg: result }));
}
else {
return handle.success(({ tapIndex: result }));
}
});
Taro.eventCenter.on('__afterTaroRouterChange', () => {
var _a, _b;
if (toast.currentPath && toast.currentPath !== ((_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path)) {
hideToast();
hideLoading();
}
if (modal.currentPath && modal.currentPath !== ((_b = runtime.Current.page) === null || _b === void 0 ? void 0 : _b.path)) {
hideModal();
}
});
const enableAlertBeforeUnload = /* @__PURE__ */ temporarilyNotSupport('enableAlertBeforeUnload');
const disableAlertBeforeUnload = /* @__PURE__ */ temporarilyNotSupport('disableAlertBeforeUnload');
/**
* 剪贴板部分的api参考了Chameleon项目的实现:
*
* 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
*/
const CLIPBOARD_STORAGE_NAME = 'taro_clipboard';
document.addEventListener('copy', () => {
var _a;
setStorage({
key: CLIPBOARD_STORAGE_NAME,
data: (_a = window.getSelection()) === null || _a === void 0 ? void 0 : _a.toString()
}).catch(e => {
console.error(e);
});
});
/**
* 设置系统剪贴板的内容
*/
const setClipboardData = (_a) => tslib.__awaiter(void 0, [_a], void 0, function* ({ 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 (shared.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 });
}
});
/**
* 获取系统剪贴板的内容
*/
const getClipboardData = (...args_1) => tslib.__awaiter(void 0, [...args_1], void 0, function* ({ success, fail, complete } = {}) {
const handle = new MethodHandler({ name: 'getClipboardData', success, fail, complete });
try {
const data = getStorageSync(CLIPBOARD_STORAGE_NAME);
return handle.success({ data });
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
});
const callbackManager$2 = new CallbackManager();
let compassListener;
/**
* Note: 按系统类型获取对应绝对 orientation 事件名,因为安卓系统中直接监听 deviceorientation 事件得到的不是绝对 orientation
*/
const deviceorientationEventName = ['absolutedeviceorientation', 'deviceorientationabsolute', 'deviceorientation'].find(item => {
if ('on' + item in window) {
return item;
}
}) || '';
/**
* 停止监听罗盘数据
*/
const stopCompass = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'stopCompass', success, fail, complete });
try {
window.removeEventListener(deviceorientationEventName, compassListener, true);
return handle.success();
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
};
let CompassChangeTrigger = false;
/**
* 开始监听罗盘数据
*/
const startCompass = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'startCompass', success, fail, complete });
try {
if (deviceorientationEventName !== '') {
if (compassListener) {
stopCompass();
}
compassListener = throttle((evt) => {
const isAndroid = getDeviceInfo().system === 'AndroidOS';
if (isAndroid && !evt.absolute && !CompassChangeTrigger) {
CompassChangeTrigger = true;
console.warn('Warning: In \'onCompassChange\', your browser is not supported to get the orientation relative to the earth, the orientation data will be related to the initial orientation of the device .');
}
const alpha = evt.alpha || 0;
/**
* 由于平台差异,accuracy 在 iOS/Android 的值不同。
* - iOS:accuracy 是一个 number 类型的值,表示相对于磁北极的偏差。0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。
* - Android:accuracy 是一个 string 类型的枚举值。
*/
const accuracy = isAndroid ? evt.absolute ? 'high' : 'medium' : alpha;
callbackManager$2.trigger({
direction: 360 - alpha,
accuracy: accuracy
});
}, 5000);
window.addEventListener(deviceorientationEventName, compassListener, true);
}
else {
throw new Error('compass is not supported');
}
return handle.success();
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
};
/**
* 监听罗盘数据变化事件。频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。
*/
const onCompassChange = callback => {
callbackManager$2.add(callback);
};
/**
* 取消监听罗盘数据变化事件,参数为空,则取消所有的事件监听。
*/
const offCompassChange = callback => {
callbackManager$2.remove(callback);
};
// 联系人
const chooseContact = /* @__PURE__ */ temporarilyNotSupport('chooseContact');
const addPhoneContact = /* @__PURE__ */ temporarilyNotSupport('addPhoneContact');
// 加密
const getRandomValues = /* @__PURE__ */ temporarilyNotSupport('getRandomValues');
// 陀螺仪
const stopGyroscope = /* @__PURE__ */ temporarilyNotSupport('stopGyroscope');
const startGyroscope = /* @__PURE__ */ temporarilyNotSupport('startGyroscope');
const onGyroscopeChange = /* @__PURE__ */ temporarilyNotSupport('onGyroscopeChange');
const offGyroscopeChange = /* @__PURE__ */ temporarilyNotSupport('offGyroscopeChange');
// 蓝牙-信标(Beacon)
const stopBeaconDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopBeaconDiscovery');
const startBeaconDiscovery = /* @__PURE__ */ temporarilyNotSupport('startBeaconDiscovery');
const onBeaconUpdate = /* @__PURE__ */ temporarilyNotSupport('onBeaconUpdate');
const onBeaconServiceChange = /* @__PURE__ */ temporarilyNotSupport('onBeaconServiceChange');
const offBeaconUpdate = /* @__PURE__ */ temporarilyNotSupport('offBeaconUpdate');
const offBeaconServiceChange = /* @__PURE__ */ temporarilyNotSupport('offBeaconServiceChange');
const getBeacons = /* @__PURE__ */ temporarilyNotSupport('getBeacons');
// 键盘
const onKeyboardHeightChange = /* @__PURE__ */ temporarilyNotSupport('onKeyboardHeightChange');
const offKeyboardHeightChange = /* @__PURE__ */ temporarilyNotSupport('offKeyboardHeightChange');
const hideKeyboard = /* @__PURE__ */ temporarilyNotSupport('hideKeyboard');
const getSelectedTextRange = /* @__PURE__ */ temporarilyNotSupport('getSelectedTextRange');
// 内存
const onMemoryWarning = /* @__PURE__ */ temporarilyNotSupport('onMemoryWarning');
const offMemoryWarning = /* @__PURE__ */ temporarilyNotSupport('offMemoryWarning');
const callbackManager$1 = new CallbackManager();
let deviceMotionListener;
const INTERVAL_MAP = {
game: {
interval: 20,
frequency: 50
},
ui: {
interval: 60,
frequency: 16.67
},
normal: {
interval: 200,
frequency: 5
}
};
/**
* 停止监听设备方向的变化。
*/
const 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 });
}
};
/**
* 开始监听设备方向的变化。
*/
const 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) => {
callbackManager$1.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 });
}
};
/**
* 监听设备方向变化事件。
*/
const onDeviceMotionChange = callback => {
callbackManager$1.add(callback);
};
/**
* 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。
*/
const offDeviceMotionChange = callback => {
callbackManager$1.remove(callback);
};
function getConnection() {
// @ts-ignore
return navigator.connection || navigator.mozConnection || navigator.webkitConnection || navigator.msConnection;
}
const getNetworkType = (options = {}) => {
const connection = getConnection();
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'getNetworkType', success, fail, complete });
let 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 = () => tslib.__awaiter(void 0, void 0, void 0, function* () {
const { networkType } = yield getNetworkType();
const isConnected = networkType !== 'none';
const obj = { isConnected, networkType };
networkStatusManager.trigger(obj);
});
/**
* 在最近的八次网络请求中, 出现下列三个现象之一则判定弱网。
* - 出现三次以上连接超时
* - 出现三次 rtt 超过 400
* - 出现三次以上的丢包
* > 弱网事件通知规则是: 弱网状态变化时立即通知, 状态不变时 30s 内最多通知一次。
*/
const onNetworkWeakChange = /* @__PURE__ */ temporarilyNotSupport('onNetworkWeakChange');
const onNetworkStatusChange = callback => {
networkStatusManager.add(callback);
const connection = getConnection();
if (connection && networkStatusManager.count() === 1) {
connection.addEventListener('change', networkStatusListener);
}
};
const offNetworkWeakChange = /* @__PURE__ */ temporarilyNotSupport('offNetworkWeakChange');
const offNetworkStatusChange = callback => {
networkStatusManager.remove(callback);
const connection = getConnection();
if (connection && networkStatusManager.count() === 0) {
connection.removeEventListener('change', networkStatusListener);
}
};
const getLocalIPAddress = /* @__PURE__ */ temporarilyNotSupport('getLocalIPAddress');
// NFC
const stopHCE = /* @__PURE__ */ temporarilyNotSupport('stopHCE');
const startHCE = /* @__PURE__ */ temporarilyNotSupport('startHCE');
const sendHCEMessage = /* @__PURE__ */ temporarilyNotSupport('sendHCEMessage');
const onHCEMessage = /* @__PURE__ */ temporarilyNotSupport('onHCEMessage');
const offHCEMessage = /* @__PURE__ */ temporarilyNotSupport('offHCEMessage');
const getNFCAdapter = /* @__PURE__ */ temporarilyNotSupport('getNFCAdapter');
const getHCEState = /* @__PURE__ */ temporarilyNotSupport('getHCEState');
const makePhoneCall = (options) => {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `makePhoneCall:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { phoneNumber, success, fail, complete } = options;
const handle = new MethodHandler({ name: 'makePhoneCall', success, fail, complete });
if (typeof phoneNumber !== 'string') {
return handle.fail({
errMsg: getParameterError({
para: 'phoneNumber',
correct: 'String',
wrong: phoneNumber
})
});
}
window.location.href = `tel:${phoneNumber}`;
return handle.success();
};
// 扫码
const scanCode = /* @__PURE__ */ processOpenApi({
name: 'scanQRCode',
defaultOptions: { needResult: 1 },
formatResult: res => ({
errMsg: res.errMsg === 'scanQRCode:ok' ? 'scanCode:ok' : res.errMsg,
result: res.resultStr
})
});
// 屏幕
const setVisualEffectOnCapture = /* @__PURE__ */ temporarilyNotSupport('setVisualEffectOnCapture');
const setScreenBrightness = /* @__PURE__ */ temporarilyNotSupport('setScreenBrightness');
const setKeepScreenOn = /* @__PURE__ */ temporarilyNotSupport('setKeepScreenOn');
const onUserCaptureScreen = /* @__PURE__ */ temporarilyNotSupport('onUserCaptureScreen');
const offUserCaptureScreen = /* @__PURE__ */ temporarilyNotSupport('offUserCaptureScreen');
const getScreenBrightness = /* @__PURE__ */ temporarilyNotSupport('getScreenBrightness');
const onScreenRecordingStateChanged = /* @__PURE__ */ temporarilyNotSupport('onScreenRecordingStateChanged');
const offScreenRecordingStateChanged = /* @__PURE__ */ temporarilyNotSupport('offScreenRecordingStateChanged');
const getScreenRecordingState = /* @__PURE__ */ temporarilyNotSupport('getScreenRecordingState');
// 短信
const sendSms = /* @__PURE__ */ temporarilyNotSupport('sendSms');
const vibrator = function vibrator(mm) {
try {
return window.navigator.vibrate(mm);
}
catch (e) {
console.warn('当前浏览器不支持 vibrate。');
}
};
/**
* 使手机发生较短时间的振动(15 ms)。仅在 iPhone 7 / 7 Plus 以上及 Android 机型生效
*/
const vibrateShort = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'vibrateShort', success, fail, complete });
if (vibrator(15)) {
return handle.success();
}
else {
return handle.fail({ errMsg: 'style is not support' });
}
};
/**
* 使手机发生较长时间的振动(400 ms)
*/
const vibrateLong = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'vibrateLong', success, fail, complete });
if (vibrator(400)) {
return handle.success();
}
else {
return handle.fail({ errMsg: 'style is not support' });
}
};
// Wi-Fi
const stopWifi = /* @__PURE__ */ temporarilyNotSupport('stopWifi');
const startWifi = /* @__PURE__ */ temporarilyNotSupport('startWifi');
const setWifiList = /* @__PURE__ */ temporarilyNotSupport('setWifiList');
const onWifiConnectedWithPartialInfo = /* @__PURE__ */ temporarilyNotSupport('onWifiConnectedWithPartialInfo');
const onWifiConnected = /* @__PURE__ */ temporarilyNotSupport('onWifiConnected');
const onGetWifiList = /* @__PURE__ */ temporarilyNotSupport('onGetWifiList');
const offWifiConnectedWithPartialInfo = /* @__PURE__ */ temporarilyNotSupport('offWifiConnectedWithPartialInfo');
const offWifiConnected = /* @__PURE__ */ temporarilyNotSupport('offWifiConnected');
const offGetWifiList = /* @__PURE__ */ temporarilyNotSupport('offGetWifiList');
const getWifiList = /* @__PURE__ */ temporarilyNotSupport('getWifiList');
const getConnectedWifi = /* @__PURE__ */ temporarilyNotSupport('getConnectedWifi');
const connectWifi = /* @__PURE__ */ temporarilyNotSupport('connectWifi');
// 第三方平台
const getExtConfigSync = /* @__PURE__ */ temporarilyNotSupport('getExtConfigSync');
const getExtConfig = /* @__PURE__ */ temporarilyNotSupport('getExtConfig');
// 文件
const saveFileToDisk = /* @__PURE__ */ temporarilyNotSupport('saveFileToDisk');
const saveFile = /* @__PURE__ */ temporarilyNotSupport('saveFile');
const removeSavedFile = /* @__PURE__ */ temporarilyNotSupport('removeSavedFile');
const openDocument = /* @__PURE__ */ temporarilyNotSupport('openDocument');
const getSavedFileList = /* @__PURE__ */ temporarilyNotSupport('getSavedFileList');
const getSavedFileInfo = /* @__PURE__ */ temporarilyNotSupport('getSavedFileInfo');
const getFileSystemManager = /* @__PURE__ */ temporarilyNotSupport('getFileSystemManager');
const getFileInfo = /* @__PURE__ */ temporarilyNotSupport('getFileInfo');
const getApp = function () {
return Taro.getCurrentInstance().app;
};
// 自定义组件
const getCurrentInstance = Taro.getCurrentInstance;
const isGeolocationSupported = () => !!navigator.geolocation;
const getLocationByW3CApi = (options) => {
var _a;
// 断言 options 必须是 Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `getLocation:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
// 解构回调函数
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'getLocation', success, fail, complete });
// const defaultMaximumAge = 5 * 1000
const positionOptions = {
enableHighAccuracy: options.isHighAccuracy || (options.altitude != null), // 海拔定位需要高精度
// maximumAge: defaultMaximumAge, // 允许取多久以内的缓存位置
timeout: options.highAccuracyExpireTime // 高精度定位超时时间
};
// Web端API实现暂时仅支持GPS坐标系
if (((_a = options.type) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== 'WGS84') {
return handle.fail({
errMsg: 'This coordinate system type is not temporarily supported'
});
}
// 判断当前浏览器是否支持位置API
if (!isGeolocationSupported()) {
return handle.fail({
errMsg: 'The current browser does not support this feature'
});
}
// 开始获取位置
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((position) => {
const result = {
/** 位置的精确度 */
accuracy: position.coords.accuracy,
/** 高度,单位 m */
altitude: position.coords.altitude,
/** 水平精度,单位 m */
horizontalAccuracy: position.coords.accuracy,
/** 纬度,范围为 -90~90,负数表示南纬 */
latitude: position.coords.latitude,
/** 经度,范围为 -180~180,负数表示西经 */
longitude: position.coords.longitude,
/** 速度,单位 m/s */
speed: position.coords.speed,
/** 垂直精度,单位 m(Android 无法获取,返回 0) */
verticalAccuracy: position.coords.altitudeAccuracy || 0,
/** 调用结果,自动补充 */
errMsg: ''
};
handle.success(result, { resolve, reject });
}, (error) => {
handle.fail({ errMsg: error.message }, { resolve, reject });
}, positionOptions);
});
};
const getLocation = /* @__PURE__ */ processOpenApi({
name: 'getLocation',
standardMethod: getLocationByW3CApi
});
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z = ".taro_choose_location{background-color:#fff;display:flex;flex-direction:column;height:100%;position:fixed;top:100%;transition:top .3s ease;width:100%;z-index:1}.taro_choose_location_bar{background-color:#ededed;color:#090909;display:flex;flex:0 95px;height:95px}.taro_choose_location_back{flex:0 45px;height:30px;margin-top:30px;position:relative;width:33px}.taro_choose_location_back:before{border:15px solid transparent;border-right-color:#090909;content:\"\";display:block;height:0;left:0;position:absolute;top:0;width:0}.taro_choose_location_back:after{border:15px solid transparent;border-right-color:#ededed;content:\"\";display:block;height:0;left:3px;position:absolute;top:0;width:0}.taro_choose_location_title{flex:1;line-height:95px;padding-left:30px}.taro_choose_location_submit{background-color:#08bf62;border:none;color:#fff;font-size:28px;height:60px;line-height:60px;margin:18px 30px 0 0;padding:0;width:110px}.taro_choose_location_frame{flex:1}";
var stylesheet=".taro_choose_location{background-color:#fff;display:flex;flex-direction:column;height:100%;position:fixed;top:100%;transition:top .3s ease;width:100%;z-index:1}.taro_choose_location_bar{background-color:#ededed;color:#090909;display:flex;flex:0 95px;height:95px}.taro_choose_location_back{flex:0 45px;height:30px;margin-top:30px;position:relative;width:33px}.taro_choose_location_back:before{border:15px solid transparent;border-right-color:#090909;content:\"\";display:block;height:0;left:0;position:absolute;top:0;width:0}.taro_choose_location_back:after{border:15px solid transparent;border-right-color:#ededed;content:\"\";display:block;height:0;left:3px;position:absolute;top:0;width:0}.taro_choose_location_title{flex:1;line-height:95px;padding-left:30px}.taro_choose_location_submit{background-color:#08bf62;border:none;color:#fff;font-size:28px;height:60px;line-height:60px;margin:18px 30px 0 0;padding:0;width:110px}.taro_choose_location_frame{flex:1}";
styleInject(css_248z,{"insertAt":"top"});
let container = null;
function createLocationChooser(handler, key = LOCATION_APIKEY, mapOpt = {}) {
var _a, _b, _c;
const { latitude, longitude } = mapOpt, opts = tslib.__rest(mapOpt, ["latitude", "longitude"]);
const query = Object.assign({ key, type: 1, coord: ((_a = mapOpt.coord) !== null && _a !== void 0 ? _a : [latitude, longitude].every(e => Number(e) >= 0)) ? `${latitude},${longitude}` : undefined, referer: 'myapp' }, opts);
if (!container) {
const html = `
<div class='taro_choose_location'>
<div class='taro_choose_location_bar'>
<div class='taro_choose_location_back'></div>
<p class='taro_choose_location_title'>位置</p>
<button class='taro_choose_location_submit'>完成</button>
</div>
<iframe class='taro_choose_location_frame' frameborder='0' src="https://apis.map.qq.com/tools/locpicker?${queryString.stringify(query, { arrayFormat: 'comma', skipNull: true })}" />
</div>
`;
container = document.createElement('div');
container.innerHTML = html;
}
const main = container.querySelector('.taro_choose_location');
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 === null || container === void 0 ? void 0 : container.remove();
container = null;
window.removeEventListener('popstate', back);
}
(_b = container.querySelector('.taro_choose_location_back')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', back);
(_c = container.querySelector('.taro_choose_location_submit')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', submit);
window.addEventListener('popstate', back);
return {
show,
remove,
container,
};
}
/**
* 打开地图选择位置。
*/
const chooseLocation = ({ success, fail, complete, mapOpts } = {}) => {
const handle = new MethodHandler({ name: 'chooseLocation', success, fail, complete });
return new Promise((resolve, reject) => {
const chooseLocation = {};
if (typeof LOCATION_APIKEY === 'undefined') {
console.warn('chooseLocation api 依赖腾讯地图定位api,需要在 defineConstants 中配置 LOCATION_APIKEY');
return handle.fail({
errMsg: 'LOCATION_APIKEY needed'
}, { resolve, reject });
}
const key = LOCATION_APIKEY;
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 });
}
}
}, key, mapOpts);
document.body.appendChild(chooser.container);
window.addEventListener('message', onMessage, false);
chooser.show();
});
};
const _successCbManager = new CallbackManager();
const _errorCbManager = new CallbackManager();
let _watchID = -1;
function onLocationChange(callback) {
_successCbManager.add(callback);
}
function offLocationChange(callback) {
if (callback && typeof callback === 'function') {
_successCbManager.remove(callback);
}
else if (callback === undefined) {
_successCbManager.clear();
}
else {
console.warn('offLocationChange failed');
}
}
function onLocationChangeError(callback) {
_errorCbManager.add(callback);
}
function offLocationChangeError(callback) {
if (callback && typeof callback === 'function') {
_errorCbManager.remove(callback);
}
else if (callback === undefined) {
_errorCbManager.clear();
}
else {
console.warn('offLocationChangeError failed');
}
}
/**
* 开始监听位置信息
* @param opts
* @returns
*/
function startLocationUpdateByW3CApi(opts) {
// 断言 options 必须是 Object
const isObject = shouldBeObject(opts);
if (!isObject.flag) {
const res = { errMsg: `startLocationUpdate:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { success, fail, complete } = opts;
const handle = new MethodHandler({ name: 'startLocationUpdate', success, fail, complete });
// 判断当前浏览器是否支持位置API
if (!isGeolocationSupported()) {
return handle.fail({
errMsg: 'The current browser does not support this feature'
});
}
try {
if (_watchID > -1) {
console.error('startLocationUpdate:fail');
return handle.fail();
}
else {
_watchID = navigator.geolocation.watchPosition(({ coords }) => {
const { latitude, longitude, altitude, accuracy, speed } = coords;
_successCbManager.trigger({
accuracy,
altitude,
horizontalAccuracy: 0,
verticalAccuracy: 0,
latitude,
longitude,
speed,
});
}, err => {
_errorCbManager.trigger({
errMsg: 'Watch Position error',
err
});
}, {
timeout: 10,
maximumAge: 0,
enableHighAccuracy: true,
});
return handle.success();
}
}
catch (error) {
return handle.fail();
}
}
/**
* 停止监听位置信息
* @param opts
* @returns
*/
function stopLocationUpdateByW3CApi(opts) {
const isObject = shouldBeObject(opts);
if (!isObject.flag) {
const res = { errMsg: `stopLocationUpdate:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { success, fail, complete } = opts;
const handle = new MethodHandler({ name: 'stopLocationUpdate', success, fail, complete });
// 判断当前浏览器是否支持位置API
if (!isGeolocationSupported()) {
return handle.fail({
errMsg: 'The current browser does not support this feature'
});
}
try {
navigator.geolocation.clearWatch(_watchID);
_watchID = -1;
return handle.success();
}
catch (error) {
return handle.fail();
}
}
const stopLocationUpdate = /* @__PURE__ */ processOpenApi({
name: 'stopLocationUpdate',
standardMethod: stopLocationUpdateByW3CApi
});
const startLocationUpdate = /* @__PURE__ */ processOpenApi({
name: 'startLocationUpdate',
standardMethod: startLocationUpdateByW3CApi
});
const startLocationUpdateBackground = /* @__PURE__ */ temporarilyNotSupport('startLocationUpdateBackground');
const openLocation = /* @__PURE__ */ processOpenApi({
name: 'openLocation',
defaultOptions: { scale: 18 }
});
const choosePoi = /* @__PURE__ */ temporarilyNotSupport('choosePoi');
const getFuzzyLocation = /* @__PURE__ */ temporarilyNotSupport('getFuzzyLocation');
class InnerAudioContext {
constructor() {
this.__startTime = 0;
this.__isFirstPlay = true;
this.play = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.play(); };
this.pause = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.pause(); };
this.stop = () => {
this.pause();
this.seek(0);
this.stopStack.trigger();
};
this.seek = (position) => {
if (this.Instance) {
this.Instance.currentTime = position;
}
};
/**
* @TODO destroy得并不干净
*/
this.destroy = () => {
this.stop();
if (this.Instance) {
this.Instance = undefined;
}
};
this.onCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('canplay', callback); };
this.onPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('play', callback); };
this.onPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('pause', callback); };
this.onStop = (callback = () => { }) => this.stopStack.add(callback);
this.onEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('ended', callback); };
this.onTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('timeupdate', callback); };
this.onError = (callback) => this.errorStack.add(callback);
this.onWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('waiting', callback); };
this.onSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeking', callback); };
this.onSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeked', callback); };
this.offCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('canplay', callback); };
this.offPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('play', callback); };
this.offPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('pause', callback); };
this.offStop = (callback = () => { }) => this.stopStack.remove(callback);
this.offEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('ended', callback); };
this.offTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('timeupdate', callback); };
this.offError = (callback = () => { }) => this.errorStack.remove(callback);
this.offWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('waiting', callback); };
this.offSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeking', callback); };
this.offSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeked', callback); };
this.Instance = new Audio();
this.errorStack = new CallbackManager();
this.stopStack = new CallbackManager();
this.Instance.onerror = this.errorStack.trigger;
Taro.eventCenter.on('__taroRouterChange', () => { this.stop(); });
this.onPlay(() => {
if (this.__isFirstPlay) {
this.__isFirstPlay = false;
this.seek(this.startTime);
}
});
}
set autoplay(e) { this.setProperty('autoplay', e); }
get autoplay() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.autoplay) || false; }
get buffered() {
const { currentTime = 0, buffered: timeRange } = this.Instance || {};
if (timeRange) {
for (let i = 0; i < timeRange.length; i++) {
if (timeRange.start(i) <= currentTime && timeRange.end(i) >= currentTime) {
return timeRange.end(i);
}
}
}
return 0;
}
get currentTime() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.currentTime) || 0; }
set currentTime(e) { this.seek(e); }
get duration() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.duration) || 0; }
set loop(e) { this.setProperty('loop', e); }
get loop() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.loop) || false; }
get paused() { var _a, _b; return (_b = (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.paused) !== null && _b !== void 0 ? _b : true; }
set src(e) { this.setProperty('src', e); }
get src() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.src) || ''; }
set volume(e) { this.setProperty('volume', e); }
get volume() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.volume) || 0; }
set playbackRate(e) { this.setProperty('playbackRate', e); }
get playbackRate() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.playbackRate) || 0; }
set obeyMuteSwitch(_e) { permanentlyNotSupport('InnerAudioContext.obeyMuteSwitch')(); }
get obeyMuteSwitch() { return true; }
set startTime(e) { this.__startTime = e; }
get startTime() { return this.__startTime || 0; }
set referrerPolicy(e) { var _a; (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.setAttribute('referrerpolicy', e); }
get referrerPolicy() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.getAttribute('referrerpolicy')) || 'origin'; }
setProperty(key, value) {
if (this.Instance) {
this.Instance[key] = value;
}
}
}
// 音频
const stopVoice = /* @__PURE__ */ temporarilyNotSupport('stopVoice');
const setInnerAudioOption = /* @__PURE__ */ temporarilyNotSupport('setInnerAudioOption');
const playVoice = /* @__PURE__ */ temporarilyNotSupport('playVoice');
const pauseVoice = /* @__PURE__ */ temporarilyNotSupport('pauseVoice');
const getAvailableAudioSources = /* @__PURE__ */ temporarilyNotSupport('getAvailableAudioSources');
const createWebAudioContext = /* @__PURE__ */ temporarilyNotSupport('createWebAudioContext');
const createMediaAudioPlayer = /* @__PURE__ */ temporarilyNotSupport('createMediaAudioPlayer');
/**
* 创建内部 audio 上下文 InnerAudioContext 对象。
*/
const createInnerAudioContext = () => new InnerAudioContext();
const createAudioContext = /* @__PURE__ */ temporarilyNotSupport('createAudioContext');
class BackgroundAudioManager {
constructor() {
this.__startTime = 0;
this.play = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.play(); };
this.pause = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.pause(); };
this.seek = (position) => {
if (this.Instance) {
this.Instance.currentTime = position;
}
};
this.stop = () => {
this.pause();
this.seek(0);
this.stopStack.trigger();
};
this.onCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('canplay', callback); };
this.onWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('waiting', callback); };
this.onError = (callback) => this.errorStack.add(callback);
this.onPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('play', callback); };
this.onPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('pause', callback); };
this.onSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeking', callback); };
this.onSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeked', callback); };
this.onEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('ended', callback); };
this.onStop = (callback = () => { }) => this.stopStack.add(callback);
this.onTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('timeupdate', callback); };
this.onPrev = permanentlyNotSupport('BackgroundAudioManager.onPrev');
this.onNext = permanentlyNotSupport('BackgroundAudioManager.onNext');
this.offCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('canplay', callback); };
this.offWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('waiting', callback); };
this.offError = (callback = () => { }) => this.errorStack.remove(callback);
this.offPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('play', callback); };
this.offPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('pause', callback); };
this.offSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeking', callback); };
this.offSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeked', callback); };
this.offEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('ended', callback); };
this.offStop = (callback = () => { }) => this.stopStack.remove(callback);
this.offTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('timeupdate', callback); };
this.offPrev = permanentlyNotSupport('BackgroundAudioManager.offPrev');
this.offNext = permanentlyNotSupport('BackgroundAudioManager.offNext');
this.Instance = new Audio();
this.errorStack = new CallbackManager();
this.stopStack = new CallbackManager();
this.Instance.onerror = this.errorStack.trigger;
this.Instance.autoplay = true;
this.onPlay(() => {
if (this.currentTime !== this.startTime) {
this.seek(this.startTime);
}
});
}
set src(e) { this.setProperty('src', e); }
get src() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.src) || ''; }
set startTime(e) { this.__startTime = e; }
get startTime() { return this.__startTime || 0; }
set title(e) { this.dataset('title', e); }
get title() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.title) || ''; }
set epname(e) { this.dataset('epname', e); }
get epname() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.epname) || ''; }
set singer(e) { this.dataset('singer', e); }
get singer() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.singer) || ''; }
set coverImgUrl(e) { this.dataset('coverImgUrl', e); }
get coverImgUrl() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.coverImgUrl) || ''; }
set webUrl(e) { this.dataset('webUrl', e); }
get webUrl() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.webUrl) || ''; }
set protocol(e) { this.dataset('protocol', e); }
get protocol() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.protocol) || ''; }
set playbackRate(e) { this.setProperty('playbackRate', e); }
get playbackRate() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.playbackRate) || 0; }
get duration() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.duration) || 0; }
get currentTime() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.currentTime) || 0; }
get paused() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.paused) || false; }
get buffered() {
const { currentTime = 0, buffered: timeRange } = this.Instance || {};
if (timeRange) {
for (let i = 0; i < timeRange.length; i++) {
if (timeRange.start(i) <= currentTime && timeRange.end(i) >= currentTime) {
return timeRange.end(i);
}
}
}
return 0;
}
set referrerPolicy(e) { var _a; (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.setAttribute('referrerpolicy', e); }
get referrerPolicy() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.getAttribute('referrerpolicy')) || 'origin'; }
setProperty(key, value) {
if (this.Instance) {
this.Instance[key] = value;
}
}
dataset(key, value) {
if (this.Instance) {
this.Instance.dataset[key] = value;
}
}
}
// 背景音频
const stopBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('stopBackgroundAudio');
const seekBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('seekBackgroundAudio');
const playBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('playBackgroundAudio');
const pauseBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('pauseBackgroundAudio');
const onBackgroundAudioStop = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioStop');
const onBackgroundAudioPlay = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioPlay');
const onBackgroundAudioPause = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioPause');
const getBackgroundAudioPlayerState = /* @__PURE__ */ temporarilyNotSupport('getBackgroundAudioPlayerState');
/**
* 获取全局唯一的背景音频管理器
*/
const getBackgroundAudioManager = () => new BackgroundAudioManager();
// 相机
const createCameraContext = /* @__PURE__ */ temporarilyNotSupport('createCameraContext');
const saveImageToPhotosAlbum = (options) => {
const methodName = 'saveImageToPhotosAlbum';
// 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 { filePath, success, fail, complete, } = options;
const handle = new MethodHandler({ name: methodName, success, fail, complete });
if (typeof filePath !== 'string') {
return handle.fail({
errMsg: getParameterError({
para: 'filePath',
correct: 'String',
wrong: filePath
})
});
}
createDownload(filePath);
return handle.success();
};
/**
* 获取图片信息。网络图片需先配置download域名才能生效。
*/
const getImageInfo = (options) => {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `getImageInfo:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const getBase64Image = (image) => {
try {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(image, 0, 0, image.width, image.height);
return canvas.toDataURL('image/png');
}
catch (e) {
console.error('getImageInfo:get base64 fail', e);
}
};
const { src, success, fail, complete } = options;
const handle = new MethodHandler({ name: 'getImageInfo', success, fail, complete });
return new Promise((resolve, reject) => {
const image = new Image();
image.crossOrigin = '';
image.onload = () => {
handle.success({
width: image.naturalWidth,
height: image.naturalHeight,
path: getBase64Image(image) || src
}, { resolve, reject });
};
image.onerror = (e) => {
handle.fail({
errMsg: e.message
}, { resolve, reject });
};
image.src = src;
});
};
/**
* previewImage api基于开源的React组件[react-wx-images-viewer](https://github.com/react-ld/react-wx-images-viewer)开发,感谢!
*/
/**
* 在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。
*/
const previewImage = (options) => tslib.__awaiter(void 0, void 0, void 0, function* () {
// TODO 改为通过 window.__taroAppConfig 获取配置的 Swiper 插件创建节点
components.defineCustomElementTaroSwiperCore();
components.defineCustomElementTaroSwiperItemCore();
function loadImage(url, loadFail) {
return new Promise((resolve) => {
const item = document.createElement('taro-swiper-item-core');
item.style.cssText = 'display:flex;align-items:start;justify-content:center;overflow-y:scroll;';
const image = new Image();
image.style.maxWidth = '100%';
image.src = url;
const div = document.createElement('div');
div.classList.add('swiper-zoom-container');
div.style.cssText = 'display:flex;align-items:center;justify-content:center;max-width:100%;min-height:100%;';
div.appendChild(image);
item.appendChild(div);
// Note: 等待图片加载完后返回,会导致轮播被卡住
resolve(item);
if (shared.isFunction(loadFail)) {
image.addEventListener('error', (err) => {
loadFail({ errMsg: err.message });
});
}
});
}
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `previewImage:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { urls = [], current = '', success, fail, complete } = options;
const handle = new MethodHandler({ name: 'previewImage', success, fail, complete });
const container = document.createElement('div');
const removeHandler = () => {
runtime.eventCenter.off('__taroRouterChange', removeHandler);
container.remove();
};
// 路由改变后应该关闭预览框
runtime.eventCenter.on('__taroRouterChange', removeHandler);
container.classList.add('preview-image');
container.style.cssText =
'position:fixed;top:0;left:0;z-index:1050;width:100%;height:100%;overflow:hidden;outline:0;background-color:#111;';
container.addEventListener('click', removeHandler);
const swiper = document.createElement('taro-swiper-core');
// @ts-ignore
swiper.full = true;
// @ts-ignore
swiper.zoom = true;
let children = [];
try {
children = yield Promise.all(urls.map((e) => loadImage(e, fail)));
}
catch (error) {
return handle.fail({
errMsg: error,
});
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
swiper.appendChild(child);
}
const currentIndex = typeof current === 'number' ? current : urls.indexOf(current);
swiper.current = currentIndex;
container.appendChild(swiper);
document.body.appendChild(container);
return handle.success();
});
/**
* H5 下的 styleSheet 操作
* @author leeenx
*/
class StyleSheet {
constructor() {
this.$style = null;
this.sheet = null;
this.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 接口');
}
};
// 添加样式命令
this.add = (cssText, index = 0) => {
var _a;
if (this.sheet === null) {
// $style 未插入到 DOM
this.appendStyleSheet();
}
(_a = this.sheet) === null || _a === void 0 ? void 0 : _a.insertRule(cssText, index);
};
this.$style = document.createElement('style');
}
}
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;
class Animation {
constructor({ duration = 400, delay = 0, timingFunction = 'linear', transformOrigin = '50% 50% 0', unit = 'px' } = {}) {
// 属性组合
this.rules = [];
// transform 对象
this.transform = [];
// 组合动画
this.steps = [];
// 动画 map ----- 永久保留
this.animationMap = {};
// animationMap 的长度
this.animationMapCount = 0;
// 历史动画
this.historyAnimations = [];
// 历史规则
this.historyRules = [];
// 默认值
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) => {
const target = e.target;
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 = [];
args.forEach(each => {
ret.push(isNaN(each) ? each : `${each}${this.unit}`);
});
return ret;
}
// 设置默认值
setDefault(duration, delay, timingFunction, transformOrigin) {
this.DEFAULT = { duration, delay, timingFunction, transformOrigin };
}
matrix(a, b, c, d, tx, ty) {
this.transform.push({ key: 'matrix', transform: `matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})` });
return this;
}
matrix3d(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4) {
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) {
this.transform.push({ key: 'rotate', transform: `rotate(${angle}deg)` });
return this;
}
rotate3d(x, y, z, angle) {
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, y) {
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 = {}) {
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;
}
// 创建底层数据
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();
}
}
// h5 的 createAnimation
const createAnimation = (option) => {
return new Animation(option);
};
const createNotSupportedObject = (obj, methods) => {
methods.forEach(method => {
Object.defineProperty(obj, method, {
get: () => temporarilyNotSupport(method)
});
});
return obj;
};
const easingMethods = [
'bounce', 'ease', 'elastic', 'linear', 'quad', 'cubic', 'poly',
'bezier', 'circle', 'sin', 'exp', 'in', 'out', 'inOut'
];
const workletMethods = [
'cancelAnimation', 'derived', 'shared', 'decay', 'spring',
'timing', 'delay', 'repeat', 'sequence', 'runOnJS', 'runOnUI'
];
const worklet = createNotSupportedObject({}, workletMethods);
worklet.Easing = createNotSupportedObject({}, easingMethods);
worklet.scrollViewContext = createNotSupportedObject({}, ['scrollTo']);
// 背景
const setBackgroundTextStyle = /* @__PURE__ */ temporarilyNotSupport('setBackgroundTextStyle');
const setBackgroundColor = /* @__PURE__ */ temporarilyNotSupport('setBackgroundColor');
// 自定义组件
const nextTick = Taro.nextTick;
// 字体
const loadFontFace = (options) => tslib.__awaiter(void 0, void 0, void 0, function* () {
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 {
yield 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' });
}
});
// 菜单
const getMenuButtonBoundingClientRect = /* @__PURE__ */ temporarilyNotSupport('getMenuButtonBoundingClientRect');
// 导航栏
/**
* 展示导航栏 loading 状态
*/
function showNavigationBarLoading(options = {}) {
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'showNavigationBarLoading', success, fail, complete });
router$1.setNavigationBarLoading(true);
return handle.success();
}
function setNavigationBarTitle(options) {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `setNavigationBarTitle:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { title, success, fail, complete } = options;
const handle = new MethodHandler({ name: 'setNavigationBarTitle', success, fail, complete });
if (!title || typeof title !== 'string') {
return handle.fail({
errMsg: getParameterError({
para: 'title',
correct: 'String',
wrong: title
})
});
}
router$1.setTitle(title);
return handle.success();
}
/**
* 设置页面导航条颜色
*/
const setNavigationBarColor = (options) => {
const { backgroundColor, frontColor, success, fail, complete } = options;
const handle = new MethodHandler({ name: 'setNavigationBarColor', success, fail, complete });
const meta = document.createElement('meta');
meta.setAttribute('name', 'theme-color');
meta.setAttribute('content', backgroundColor);
document.head.appendChild(meta);
router$1.setNavigationBarStyle({ frontColor, backgroundColor });
return handle.success();
};
/**
* 隐藏导航栏 loading 状态
*/
function hideNavigationBarLoading(options = {}) {
const { success, fail, complete } = options;
const handle = new MethodHandler({ name: 'hideNavigationBarLoading', success, fail, complete });
router$1.setNavigationBarLoading(false);
return handle.success();
}
const hideHomeButton = /* @__PURE__ */ temporarilyNotSupport('hideHomeButton');
/**
* 开始下拉刷新。调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
*/
const 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 })
});
});
};
/**
* 停止当前页面下拉刷新。
*/
const 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 })
});
});
};
let timer;
const FRAME_DURATION = 17;
/**
* 将页面滚动到目标位置
*/
const 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) => {
var _a, _b, _c;
try {
if (scrollTop === undefined && !selector) {
return handle.fail({
errMsg: 'scrollTop" 或 "selector" 需要其之一'
}, { resolve, reject });
}
const usingWindowScroll = (_a = window.__taroAppConfig) === null || _a === void 0 ? void 0 : _a.usingWindowScroll;
const id = (_c = (_b = runtime.Current.page) === null || _b === void 0 ? void 0 : _b.path) === null || _c === void 0 ? void 0 : _c.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
const el = (id
? document.querySelector(`.taro_page#${id}`)
: document.querySelector('.taro_page') ||
document.querySelector('.taro_router'));
if (!scrollFunc) {
if (usingWindowScroll) {
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;
if (selector) {
const el = document.querySelector(selector);
to = ((el === null || el === void 0 ? void 0 : 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 });
}
});
};
// 置顶
const setTopBarText = /* @__PURE__ */ temporarilyNotSupport('setTopBarText');
let tabConf;
function initTabBarApis(config = {}) {
tabConf = config.tabBar;
}
/**
* 显示 tabBar 某一项的右上角的红点
*/
const 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 })
});
});
};
/**
* 显示 tabBar
*/
const 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 })
});
});
};
/**
* 动态设置 tabBar 的整体样式
*/
const 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 = {};
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 })
});
});
};
/**
* 动态设置 tabBar 某一项的内容
*/
const 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 })
});
});
};
/**
* 为 tabBar 某一项的右上角添加文本
*/
const 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.replace(/[\u0391-\uFFE5]/g, 'aa').length > 4 ? '...' : text,
successHandler: (res = {}) => handle.success(res, { resolve, reject }),
errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
});
});
};
/**
* 移除 tabBar 某一项右上角的文本
*/
const 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 })
});
});
};
/**
* 隐藏 tabBar 某一项的右上角的红点
*/
const 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 })
});
});
};
/**
* 隐藏 tabBar
*/
const 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 })
});
});
};
const callbackManager = new CallbackManager();
const resizeListener = () => {
callbackManager.trigger({
windowWidth: window.screen.width,
windowHeight: window.screen.height
});
};
/**
* 设置窗口大小,该接口仅适用于 PC 平台,使用细则请参见指南
*/
const setWindowSize = /* @__PURE__ */ temporarilyNotSupport('setWindowSize');
/**
* 监听窗口尺寸变化事件
*/
const onWindowResize = callback => {
callbackManager.add(callback);
if (callbackManager.count() === 1) {
window.addEventListener('resize', resizeListener);
}
};
/**
* 取消监听窗口尺寸变化事件
*/
const offWindowResize = callback => {
callbackManager.remove(callback);
if (callbackManager.count() === 0) {
window.removeEventListener('resize', resizeListener);
}
};
const checkIsPictureInPictureActive = /* @__PURE__ */ temporarilyNotSupport('checkIsPictureInPictureActive');
/**
* 拍摄或从手机相册中选择图片或视频。
*/
const chooseMedia = function (options_1) {
return tslib.__awaiter(this, arguments, void 0, function* (options, methodName = 'chooseMedia') {
var _a;
// 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 { count = 9, mediaId = 'taroChooseMedia', mediaType = ['image', 'video'], sourceType = ['album', 'camera'],
// sizeType = ['original', 'compressed'], // TODO 考虑通过 ffmpeg 支持压缩
// maxDuration = 10, // TODO 考虑通过 ffmpeg 剪裁视频
camera = 'back', success, fail, complete, } = options;
const handle = new MethodHandler({ name: methodName, success, fail, complete });
const withImage = mediaType.length < 1 || mediaType.indexOf('image') > -1;
const withVideo = mediaType.length < 1 || mediaType.indexOf('video') > -1;
const res = {
tempFiles: [],
type: withImage && withVideo ? 'mix' : withImage ? 'image' : 'video',
};
if (count && typeof count !== 'number') {
res.errMsg = getParameterError({
para: 'count',
correct: 'Number',
wrong: count
});
return handle.fail(res);
}
let el = document.getElementById(mediaId);
if (!el) {
el = document.createElement('input');
el.setAttribute('type', 'file');
el.setAttribute('id', mediaId);
el.setAttribute('style', 'position: fixed; top: -4000px; left: -3000px; z-index: -300;');
}
if (count > 1) {
el.setAttribute('multiple', 'multiple');
}
else {
el.removeAttribute('multiple');
}
// Note: Input 仅在移动端支持 capture 属性,可以使用 getUserMedia 替代(暂不考虑)
if (isMobile.isMobile()) {
if (sourceType.length > 1 || sourceType.length < 1) {
try {
const { tapIndex } = yield showActionSheet({
itemList: ['拍摄', '从相册选择'],
}, methodName);
sourceType.splice(0, sourceType.length, tapIndex === 0 ? 'camera' : 'album');
}
catch (e) {
return handle.fail({
errMsg: (_a = e.errMsg) === null || _a === void 0 ? void 0 : _a.replace('^.*:fail ', '')
});
}
}
}
if (sourceType.includes('camera')) {
el.setAttribute('capture', camera === 'front' ? 'user' : 'environment');
}
else {
el.removeAttribute('capture');
}
if (res.type === 'image') {
el.setAttribute('accept', 'image/*');
}
else if (res.type === 'video') {
el.setAttribute('accept', 'video/*');
}
else {
el.setAttribute('accept', 'image/*, video/*');
}
return new Promise((resolve, reject) => {
if (!el)
return;
document.body.appendChild(el);
el.onchange = function (e) {
return tslib.__awaiter(this, void 0, void 0, function* () {
const target = e.target;
if (target) {
const files = target.files || [];
const arr = [...files];
yield Promise.all(arr.map((item) => tslib.__awaiter(this, void 0, void 0, function* () {
var _a;
try {
(_a = res.tempFiles) === null || _a === void 0 ? void 0 : _a.push(yield loadMedia(item));
}
catch (error) {
console.error(error);
}
})));
}
handle.success(res, { resolve, reject });
target.value = '';
});
};
el.onabort = () => handle.fail({ errMsg: 'abort' }, { resolve, reject });
el.oncancel = () => handle.fail({ errMsg: 'cancel' }, { resolve, reject });
el.onerror = e => handle.fail({ errMsg: e.toString() }, { resolve, reject });
el.click();
}).finally(() => {
if (!el)
return;
document.body.removeChild(el);
});
function loadMedia(file) {
const dataUrl = URL.createObjectURL(file);
const res = {
tempFilePath: dataUrl,
size: file.size,
duration: 0,
height: 0,
width: 0,
thumbTempFilePath: '',
fileType: file.type,
originalFileObj: file
};
if (/^video\//.test(res.fileType)) {
// Video
const isIOS = getDeviceInfo().system.toLowerCase().includes('ios');
const video = document.createElement('video');
const reader = new FileReader();
video.crossOrigin = 'Anonymous';
video.preload = 'metadata';
video.src = res.tempFilePath;
return new Promise((resolve, reject) => {
// 对齐旧版本实现
reader.onload = (event) => {
var _a;
res.tempFilePath = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
};
reader.onerror = e => reject(e);
reader.readAsDataURL(res.originalFileObj);
video.onloadedmetadata = () => {
res.duration = video.duration;
res.height = video.videoHeight;
res.width = video.videoWidth;
};
video.oncanplay = () => {
res.thumbTempFilePath = getThumbTempFilePath(video, res.height, res.width, 0.8);
resolve(res);
};
video.onerror = e => reject(e);
isIOS && video.load();
});
}
else {
// Image
const img = new Image();
/** 允许图片和 canvas 跨源使用
* https://developer.mozilla.org/zh-CN/docs/Web/HTML/CORS_enabled_image
*/
img.crossOrigin = 'Anonymous';
img.src = res.tempFilePath;
return new Promise((resolve, reject) => {
if (img.complete) {
res.height = img.height;
res.width = img.width;
res.thumbTempFilePath = getThumbTempFilePath(img, res.height, res.width, 0.8);
resolve(res);
}
else {
img.onload = () => {
res.height = img.height;
res.width = img.width;
res.thumbTempFilePath = getThumbTempFilePath(img, res.height, res.width, 0.8);
resolve(res);
};
img.onerror = e => reject(e);
}
});
}
}
function getThumbTempFilePath(el, height = 0, width = height, quality = 0.8) {
const max = 256;
const canvas = document.createElement('canvas');
if (height > max || width > max) {
const radio = height / width;
if (radio > 1) {
height = max;
width = height / radio;
}
else {
width = max;
height = width * radio;
}
}
canvas.height = height;
canvas.width = width;
const ctx = canvas.getContext('2d');
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(el, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL('image/jpeg', quality);
}
});
};
/**
* 从本地相册选择图片或使用相机拍照。
* @deprecated 请使用 chooseMedia 接口
*/
const chooseImage = function (options) {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `chooseImage:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
let camera = 'back';
const { sourceType = ['album', 'camera'], success, complete, fail } = options, args = tslib.__rest(options, ["sourceType", "success", "complete", "fail"]);
if (sourceType.includes('camera') && sourceType.indexOf('user') > -1) {
camera = 'front';
}
function parseRes(res) {
const { tempFiles = [], errMsg } = res;
return {
tempFilePaths: tempFiles.map(item => item.tempFilePath),
tempFiles: tempFiles.map(item => ({
path: item.tempFilePath,
size: item.size,
type: item.fileType,
originalFileObj: item.originalFileObj,
})),
errMsg,
};
}
return chooseMedia(Object.assign(Object.assign({ mediaId: 'taroChooseImage' }, args), { sourceType: sourceType, mediaType: ['image'], camera, success: (res) => {
const param = parseRes(res);
success === null || success === void 0 ? void 0 : success(param);
complete === null || complete === void 0 ? void 0 : complete(param);
}, fail: (err) => {
fail === null || fail === void 0 ? void 0 : fail(err);
complete === null || complete === void 0 ? void 0 : complete(err);
} }), 'chooseImage').then(parseRes);
};
const previewMedia = /* @__PURE__ */ temporarilyNotSupport('previewMedia');
const compressImage = /* @__PURE__ */ temporarilyNotSupport('compressImage');
const chooseMessageFile = /* @__PURE__ */ permanentlyNotSupport('chooseMessageFile');
const editImage = /* @__PURE__ */ temporarilyNotSupport('editImage');
const cropImage = /* @__PURE__ */ temporarilyNotSupport('cropImage');
// 实时音视频
const createLivePusherContext = /* @__PURE__ */ temporarilyNotSupport('createLivePusherContext');
const createLivePlayerContext = /* @__PURE__ */ temporarilyNotSupport('createLivePlayerContext');
// 地图
const createMapContext = /* @__PURE__ */ temporarilyNotSupport('createMapContext');
// 画面录制器
const createMediaRecorder = /* @__PURE__ */ temporarilyNotSupport('createMediaRecorder');
// 录音
const stopRecord = /* @__PURE__ */ temporarilyNotSupport('stopRecord');
const startRecord = /* @__PURE__ */ temporarilyNotSupport('startRecord');
const getRecorderManager = /* @__PURE__ */ temporarilyNotSupport('getRecorderManager');
const saveVideoToPhotosAlbum = (options) => {
const methodName = 'saveVideoToPhotosAlbum';
// 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 { filePath, success, fail, complete, } = options;
const handle = new MethodHandler({ name: methodName, success, fail, complete });
if (typeof filePath !== 'string') {
return handle.fail({
errMsg: getParameterError({
para: 'filePath',
correct: 'String',
wrong: filePath
})
});
}
createDownload(filePath);
return handle.success();
};
const getVideoInfo = function (options) {
return tslib.__awaiter(this, void 0, void 0, function* () {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `getVideoInfo:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const res = {
orientation: 'up',
type: '',
duration: 0,
size: 0,
height: 0,
width: 0,
fps: 30,
bitrate: 0,
};
const { src, success, fail, complete, } = options;
const handle = new MethodHandler({ name: 'getVideoInfo', success, fail, complete });
if (typeof src !== 'string') {
res.errMsg = getParameterError({
para: 'src',
correct: 'String',
wrong: src
});
return handle.fail(res);
}
const video = document.createElement('video');
video.crossOrigin = 'Anonymous';
video.preload = 'metadata';
video.src = src;
return new Promise((resolve, reject) => {
video.onloadedmetadata = () => {
res.duration = video.duration;
res.height = video.videoHeight;
res.width = video.videoWidth;
fetch(src)
.then((e) => tslib.__awaiter(this, void 0, void 0, function* () {
const blob = yield e.blob();
res.type = blob.type;
res.size = blob.size;
res.bitrate = blob.size / video.duration;
handle.success(res, { resolve, reject });
}))
.catch(e => {
handle.fail({
errMsg: e.toString()
}, { resolve, reject });
});
};
});
});
};
/**
* 拍摄视频或从手机相册中选视频。
* @deprecated 请使用 chooseMedia 接口
*/
const chooseVideo = (options) => {
// options must be an Object
const isObject = shouldBeObject(options);
if (!isObject.flag) {
const res = { errMsg: `chooseVideo:fail ${isObject.msg}` };
console.error(res.errMsg);
return Promise.reject(res);
}
const { sourceType = ['album', 'camera'],
// TODO 考虑通过 ffmpeg 支持压缩
// compressed = true,
maxDuration = 60, camera = 'back', success, fail, complete, } = options;
function parseRes(res) {
const { tempFiles = [], errMsg } = res;
const [video] = tempFiles;
return Object.assign(Object.assign({}, video), { errMsg });
}
return chooseMedia({
mediaId: 'taroChooseVideo',
sourceType,
mediaType: ['video'],
maxDuration,
camera,
success: (res) => {
const param = parseRes(res);
success === null || success === void 0 ? void 0 : success(param);
complete === null || complete === void 0 ? void 0 : complete(param);
},
fail: (err) => {
fail === null || fail === void 0 ? void 0 : fail(err);
complete === null || complete === void 0 ? void 0 : complete(err);
},
}, 'chooseVideo').then(parseRes);
};
const openVideoEditor = /* @__PURE__ */ temporarilyNotSupport('openVideoEditor');
/**
* 创建 video 上下文 VideoContext 对象。
*/
const createVideoContext = (id, inst) => {
const el = findDOM(inst);
// TODO HTMLVideoElement to VideoContext
return el === null || el === void 0 ? void 0 : el.querySelector(`taro-video-core[id=${id}]`);
};
const compressVideo = /* @__PURE__ */ temporarilyNotSupport('compressVideo');
// 视频解码器
const createVideoDecoder = /* @__PURE__ */ temporarilyNotSupport('createVideoDecoder');
// 音视频合成
const createMediaContainer = /* @__PURE__ */ temporarilyNotSupport('createMediaContainer');
// 实时语音
const updateVoIPChatMuteConfig = /* @__PURE__ */ temporarilyNotSupport('updateVoIPChatMuteConfig');
const subscribeVoIPVideoMembers = /* @__PURE__ */ temporarilyNotSupport('subscribeVoIPVideoMembers');
const setEnable1v1Chat = /* @__PURE__ */ temporarilyNotSupport('setEnable1v1Chat');
const onVoIPVideoMembersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPVideoMembersChanged');
const onVoIPChatStateChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatStateChanged');
const onVoIPChatSpeakersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatSpeakersChanged');
const onVoIPChatMembersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatMembersChanged');
const onVoIPChatInterrupted = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatInterrupted');
const offVoIPChatSpeakersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatSpeakersChanged');
const offVoIPVideoMembersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPVideoMembersChanged');
const offVoIPChatStateChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatStateChanged');
const offVoIPChatMembersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatMembersChanged');
const offVoIPChatInterrupted = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatInterrupted');
const joinVoIPChat = /* @__PURE__ */ temporarilyNotSupport('joinVoIPChat');
const join1v1Chat = /* @__PURE__ */ temporarilyNotSupport('join1v1Chat');
const exitVoIPChat = /* @__PURE__ */ temporarilyNotSupport('exitVoIPChat');
// 跳转
const openEmbeddedMiniProgram = /* @__PURE__ */ temporarilyNotSupport('openEmbeddedMiniProgram');
const navigateToMiniProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToMiniProgram');
const navigateBackMiniProgram = /* @__PURE__ */ temporarilyNotSupport('navigateBackMiniProgram');
const exitMiniProgram = /* @__PURE__ */ temporarilyNotSupport('exitMiniProgram');
const openBusinessView = /* @__PURE__ */ temporarilyNotSupport('openBusinessView');
/**
* HTTP Response Header 事件回调函数的参数
* @typedef {Object} HeadersReceivedParam
* @property {Object} header 开发者服务器返回的 HTTP Response Header
*/
/**
* HTTP Response Header 事件的回调函数
* @callback HeadersReceivedCallback
* @param {HeadersReceivedParam} res 参数
*/
/**
* 进度变化回调函数的参数
* @typedef {Object} ProgressUpdateParam
* @property {number} progress 进度百分比
* @property {number} [totalBytesWritten] 已经下载的数据长度,单位 Bytes
* @property {number} [totalBytesSent] 已经上传的数据长度,单位 Bytes
* @property {number} [totalBytesExpectedToWrite] 预期需要下载的数据总长度,单位 Bytes
* @property {number} [totalBytesExpectedToSend] 预期需要上传的数据总长度,单位 Bytes
*/
/**
* 进度变化事件的回调函数
* @callback ProgressUpdateCallback
* @param {ProgressUpdateParam} res 参数
*/
const NETWORK_TIMEOUT = 60000;
const XHR_STATS = {
UNSENT: 0, // Client has been created. open() not called yet.
OPENED: 1, // open() has been called.
HEADERS_RECEIVED: 2, // send() has been called, and headers and status are available.
LOADING: 3, // Downloading; responseText holds partial data.
DONE: 4 // The operation is complete.
};
/**
* 设置xhr的header
* @param {XMLHttpRequest} xhr
* @param {Object} header
*/
const setHeader = (xhr, header) => {
let headerKey;
for (headerKey in header) {
xhr.setRequestHeader(headerKey, header[headerKey]);
}
};
/**
* 将 blob url 转化为文件
* @param {string} url 要转换的 blob url
* @returns {Promise<File>}
*/
const convertObjectUrlToBlob = url => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.withCredentials = true;
xhr.onload = function () {
if (this.status === 200) {
resolve(this.response);
}
else {
/* eslint-disable prefer-promise-reject-errors */
reject({ status: this.status });
}
};
xhr.send();
});
};
const createDownloadTask = ({ url, header, withCredentials = true, timeout, success, error }) => {
let timeoutInter;
const apiName = 'downloadFile';
const xhr = new XMLHttpRequest();
const callbackManager = {
headersReceived: new CallbackManager(),
progressUpdate: new CallbackManager()
};
xhr.open('GET', url, true);
xhr.withCredentials = !!withCredentials;
xhr.responseType = 'blob';
setHeader(xhr, header);
xhr.onprogress = e => {
const { loaded, total } = e;
callbackManager.progressUpdate.trigger({
progress: Math.round(loaded / total * 100),
totalBytesWritten: loaded,
totalBytesExpectedToWrite: total
});
};
xhr.onreadystatechange = () => {
if (xhr.readyState !== XHR_STATS.HEADERS_RECEIVED)
return;
callbackManager.headersReceived.trigger({
header: xhr.getAllResponseHeaders()
});
};
xhr.onload = () => {
const response = xhr.response;
const status = xhr.status;
success({
errMsg: `${apiName}:ok`,
statusCode: status,
tempFilePath: window.URL.createObjectURL(response)
});
};
xhr.onabort = () => {
clearTimeout(timeoutInter);
error({
errMsg: `${apiName}:fail abort`
});
};
xhr.onerror = (e) => {
error({
errMsg: `${apiName}:fail ${e.message}`
});
};
/**
* 中断任务
*/
const abort = () => {
xhr.abort();
};
const send = () => {
xhr.send();
timeoutInter = setTimeout(() => {
xhr.onabort = null;
xhr.onload = null;
xhr.onprogress = null;
xhr.onreadystatechange = null;
xhr.onerror = null;
abort();
error({
errMsg: `${apiName}:fail timeout`
});
}, timeout || NETWORK_TIMEOUT);
};
send();
/**
* 监听 HTTP Response Header 事件。会比请求完成事件更早
* @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
*/
const onHeadersReceived = callbackManager.headersReceived.add;
/**
* 取消监听 HTTP Response Header 事件
* @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
*/
const offHeadersReceived = callbackManager.headersReceived.remove;
/**
* 监听进度变化事件
* @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
*/
const onProgressUpdate = callbackManager.progressUpdate.add;
/**
* 取消监听进度变化事件
* @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
*/
const offProgressUpdate = callbackManager.progressUpdate.remove;
return {
abort,
onHeadersReceived,
offHeadersReceived,
onProgressUpdate,
offProgressUpdate
};
};
/**
* 下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求,返回文件的本地临时路径。使用前请注意阅读相关说明。
* 注意:请在服务端响应的 header 中指定合理的 Content-Type 字段,以保证客户端正确处理文件类型。
*/
const downloadFile = ({ url, header, withCredentials, timeout, success, fail, complete }) => {
let task;
const result = new Promise((resolve, reject) => {
task = createDownloadTask({
url,
header,
withCredentials,
timeout,
success: res => {
success && success(res);
complete && complete(res);
resolve(res);
},
error: res => {
fail && fail(res);
complete && complete(res);
reject(res);
}
});
});
result.headersReceive = task.onHeadersReceived.bind(task);
result.progress = task.onProgressUpdate.bind(task);
const properties = {};
Object.keys(task).forEach(key => {
properties[key] = {
get() {
return typeof task[key] === 'function' ? task[key].bind(task) : task[key];
}
};
});
return Object.defineProperties(result, properties);
};
// mDNS
const stopLocalServiceDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopLocalServiceDiscovery');
const startLocalServiceDiscovery = /* @__PURE__ */ temporarilyNotSupport('startLocalServiceDiscovery');
const onLocalServiceResolveFail = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceResolveFail');
const onLocalServiceLost = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceLost');
const onLocalServiceFound = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceFound');
const onLocalServiceDiscoveryStop = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceDiscoveryStop');
const offLocalServiceResolveFail = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceResolveFail');
const offLocalServiceLost = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceLost');
const offLocalServiceFound = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceFound');
const offLocalServiceDiscoveryStop = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceDiscoveryStop');
// @ts-ignore
const { Link: Link$1 } = Taro;
function generateRequestUrlWithParams(url = '', params) {
params = typeof params === 'string' ? params : serializeParams(params);
if (params) {
url += (~url.indexOf('?') ? '&' : '?') + params;
}
url = url.replace('?&', '?');
return url;
}
function _request(options = {}) {
const { success, complete, fail } = options;
const params = {};
const res = {};
let { cache = 'default', credentials, data, dataType, header = {}, jsonp, method = 'GET', mode, responseType, signal, timeout, url = '' } = options, opts = tslib.__rest(options, ["cache", "credentials", "data", "dataType", "header", "jsonp", "method", "mode", "responseType", "signal", "timeout", "url"]);
if (typeof timeout !== 'number') {
timeout = NETWORK_TIMEOUT;
}
Object.assign(params, opts);
if (jsonp) {
// @ts-ignore
params.params = data;
params.cache = opts.jsonpCache;
// @ts-ignore
params.timeout = timeout;
if (typeof jsonp === 'string') {
// @ts-ignore
params.name = jsonp;
}
// Note: https://github.com/luckyadam/jsonp-retry
return jsonpRetry(url, params)
.then(data => {
res.statusCode = 200;
res.data = data;
shared.isFunction(success) && success(res);
shared.isFunction(complete) && complete(res);
return res;
})
.catch(err => {
shared.isFunction(fail) && fail(err);
shared.isFunction(complete) && complete(res);
return Promise.reject(err);
});
}
params.method = method;
const methodUpper = params.method.toUpperCase();
params.cache = cache;
if (methodUpper === 'GET' || methodUpper === 'HEAD') {
url = generateRequestUrlWithParams(url, data);
}
else if (['[object Array]', '[object Object]'].indexOf(Object.prototype.toString.call(data)) >= 0) {
const keyOfContentType = Object.keys(header).find(item => item.toLowerCase() === 'content-type');
if (!keyOfContentType) {
header['Content-Type'] = 'application/json';
}
const contentType = header[keyOfContentType || 'Content-Type'];
if (contentType.indexOf('application/json') >= 0) {
params.body = JSON.stringify(data);
}
else if (contentType.indexOf('application/x-www-form-urlencoded') >= 0) {
params.body = serializeParams(data);
}
else {
params.body = data;
}
}
else {
params.body = data;
}
if (header) {
params.headers = header;
}
if (mode) {
params.mode = mode;
}
let timeoutTimer = null;
let controller = null;
if (signal) {
params.signal = signal;
}
else {
controller = new window.AbortController();
params.signal = controller.signal;
timeoutTimer = setTimeout(function () {
if (controller)
controller.abort();
}, timeout);
}
params.credentials = credentials;
const p = fetch(url, params)
.then(response => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
if (controller) {
controller = null;
}
if (!response) {
const errorResponse = { ok: false };
throw errorResponse;
}
res.statusCode = response.status;
res.header = {};
for (const key of response.headers.keys()) {
res.header[key] = response.headers.get(key);
}
if (responseType === 'arraybuffer') {
return response.arrayBuffer();
}
if (res.statusCode !== 204) {
if (dataType === 'json' || typeof dataType === 'undefined') {
return response.json().catch(() => {
return null;
});
}
}
if (responseType === 'text' || dataType === 'text') {
return response.text();
}
return Promise.resolve(null);
})
.then(data => {
res.data = data;
shared.isFunction(success) && success(res);
shared.isFunction(complete) && complete(res);
return res;
})
.catch(err => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
if (controller) {
controller = null;
}
shared.isFunction(fail) && fail(err);
shared.isFunction(complete) && complete(res);
err.statusCode = res.statusCode;
err.errMsg = err.message;
return Promise.reject(err);
});
if (!p.abort && controller) {
p.abort = cb => {
if (controller) {
cb && cb();
controller.abort();
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
}
};
}
return p;
}
function taroInterceptor(chain) {
return _request(chain.requestParams);
}
const link = new Link$1(taroInterceptor);
const request = ((...args) => {
const [url = '', options = {}] = args;
if (typeof url === 'string') {
options.url = url;
}
else {
Object.assign(options, url);
}
return link.request(options);
});
const addInterceptor = link.addInterceptor.bind(link);
const cleanInterceptors = link.cleanInterceptors.bind(link);
// TCP 通信
const createTCPSocket = /* @__PURE__ */ temporarilyNotSupport('createTCPSocket');
// UDP 通信
const createUDPSocket = /* @__PURE__ */ temporarilyNotSupport('createUDPSocket');
const createUploadTask = ({ url, filePath, formData = {}, name, header, timeout, fileName, withCredentials = true, success, error }) => {
let timeoutInter;
let formKey;
const apiName = 'uploadFile';
const xhr = new XMLHttpRequest();
const form = new FormData();
const callbackManager = {
headersReceived: new CallbackManager(),
progressUpdate: new CallbackManager()
};
xhr.open('POST', url);
xhr.withCredentials = !!withCredentials;
setHeader(xhr, header);
for (formKey in formData) {
form.append(formKey, formData[formKey]);
}
xhr.upload.onprogress = e => {
const { loaded, total } = e;
callbackManager.progressUpdate.trigger({
progress: Math.round(loaded / total * 100),
totalBytesSent: loaded,
totalBytesExpectedToSend: total
});
};
xhr.onreadystatechange = () => {
if (xhr.readyState !== XHR_STATS.HEADERS_RECEIVED)
return;
callbackManager.headersReceived.trigger({
header: xhr.getAllResponseHeaders()
});
};
xhr.onload = () => {
const status = xhr.status;
clearTimeout(timeoutInter);
success({
errMsg: `${apiName}:ok`,
statusCode: status,
data: xhr.responseText || xhr.response
});
};
xhr.onabort = () => {
clearTimeout(timeoutInter);
error({
errMsg: `${apiName}:fail abort`
});
};
xhr.onerror = (e) => {
clearTimeout(timeoutInter);
error({
errMsg: `${apiName}:fail ${e.message}`
});
};
/**
* 中断任务
*/
const abort = () => {
clearTimeout(timeoutInter);
xhr.abort();
};
const send = () => {
xhr.send(form);
timeoutInter = setTimeout(() => {
xhr.onabort = null;
xhr.onload = null;
xhr.upload.onprogress = null;
xhr.onreadystatechange = null;
xhr.onerror = null;
abort();
error({
errMsg: `${apiName}:fail timeout`
});
}, timeout || NETWORK_TIMEOUT);
};
convertObjectUrlToBlob(filePath)
.then((fileObj) => {
if (!fileName) {
fileName = typeof fileObj !== 'string' && fileObj.name;
}
form.append(name, fileObj, fileName || `file-${Date.now()}`);
send();
})
.catch(e => {
error({
errMsg: `${apiName}:fail ${e.message}`
});
});
/**
* 监听 HTTP Response Header 事件。会比请求完成事件更早
* @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
*/
const onHeadersReceived = callbackManager.headersReceived.add;
/**
* 取消监听 HTTP Response Header 事件
* @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
*/
const offHeadersReceived = callbackManager.headersReceived.remove;
/**
* 监听进度变化事件
* @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
*/
const onProgressUpdate = callbackManager.progressUpdate.add;
/**
* 取消监听进度变化事件
* @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
*/
const offProgressUpdate = callbackManager.progressUpdate.remove;
return {
abort,
onHeadersReceived,
offHeadersReceived,
onProgressUpdate,
offProgressUpdate
};
};
/**
* 将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data。使用前请注意阅读相关说明。
*/
const uploadFile = ({ url, filePath, name, header, formData, timeout, fileName, withCredentials, success, fail, complete }) => {
let task;
const result = new Promise((resolve, reject) => {
task = createUploadTask({
url,
header,
name,
filePath,
formData,
timeout,
fileName,
withCredentials,
success: res => {
success && success(res);
complete && complete(res);
resolve(res);
},
error: res => {
fail && fail(res);
complete && complete(res);
reject(res);
}
});
});
result.headersReceive = task.onHeadersReceived.bind(task);
result.progress = task.onProgressUpdate.bind(task);
const properties = {};
Object.keys(task).forEach(key => {
properties[key] = {
get() {
return typeof task[key] === 'function' ? task[key].bind(task) : task[key];
}
};
});
return Object.defineProperties(result, properties);
};
class SocketTask {
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 = {}) {
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);
shared.isFunction(fail) && fail(res);
shared.isFunction(complete) && complete(res);
return Promise.reject(res);
}
this.ws.send(data);
const res = { errMsg: 'sendSocketMessage:ok' };
shared.isFunction(success) && success(res);
shared.isFunction(complete) && complete(res);
return Promise.resolve(res);
}
close(opts = {}) {
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' };
shared.isFunction(success) && success(res);
shared.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;
}
}
let socketTasks = [];
let socketsCounter = 1;
function sendSocketMessage() {
console.warn('Deprecated.Please use socketTask.send instead.');
}
function onSocketOpen() {
console.warn('Deprecated.Please use socketTask.onOpen instead.');
}
function onSocketMessage() {
console.warn('Deprecated.Please use socketTask.onMessage instead.');
}
function onSocketError() {
console.warn('Deprecated.Please use socketTask.onError instead.');
}
function onSocketClose() {
console.warn('Deprecated.Please use socketTask.onClose instead.');
}
function connectSocket(options) {
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;
const handle = new MethodHandler({ 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);
});
}
function closeSocket() {
console.warn('Deprecated.Please use socketTask.close instead.');
}
// 帐号信息
const getAccountInfoSync = /* @__PURE__ */ temporarilyNotSupport('getAccountInfoSync');
// 收货地址
const chooseAddress = /* @__PURE__ */ temporarilyNotSupport('chooseAddress');
// 授权
const authorizeForMiniProgram = /* @__PURE__ */ temporarilyNotSupport('authorizeForMiniProgram');
const authorize = /* @__PURE__ */ temporarilyNotSupport('authorize');
// 卡券
const openCard = /* @__PURE__ */ temporarilyNotSupport('openCard');
const addCard = /* @__PURE__ */ temporarilyNotSupport('addCard');
// 视频号
const reserveChannelsLive = /* @__PURE__ */ temporarilyNotSupport('reserveChannelsLive');
const openChannelsUserProfile = /* @__PURE__ */ temporarilyNotSupport('openChannelsUserProfile');
const openChannelsLive = /* @__PURE__ */ temporarilyNotSupport('openChannelsLive');
const openChannelsEvent = /* @__PURE__ */ temporarilyNotSupport('openChannelsEvent');
const openChannelsActivity = /* @__PURE__ */ temporarilyNotSupport('openChannelsActivity');
const getChannelsShareKey = /* @__PURE__ */ temporarilyNotSupport('getChannelsShareKey');
const getChannelsLiveNoticeInfo = /* @__PURE__ */ temporarilyNotSupport('getChannelsLiveNoticeInfo');
const getChannelsLiveInfo = /* @__PURE__ */ temporarilyNotSupport('getChannelsLiveInfo');
// 微信客服
const openCustomerServiceChat = /* @__PURE__ */ temporarilyNotSupport('openCustomerServiceChat');
// 设备(组)音视频通话
const requestDeviceVoIP = /* @__PURE__ */ temporarilyNotSupport('requestDeviceVoIP');
const getDeviceVoIPList = /* @__PURE__ */ temporarilyNotSupport('getDeviceVoIPList');
// 过往接口
const checkIsSupportFacialRecognition = /* @__PURE__ */ temporarilyNotSupport('checkIsSupportFacialRecognition');
const startFacialRecognitionVerify = /* @__PURE__ */ temporarilyNotSupport('startFacialRecognitionVerify');
const startFacialRecognitionVerifyAndUploadVideo = /* @__PURE__ */ temporarilyNotSupport('startFacialRecognitionVerifyAndUploadVideo');
const faceVerifyForPay = /* @__PURE__ */ temporarilyNotSupport('faceVerifyForPay');
// 收藏
const addVideoToFavorites = /* @__PURE__ */ temporarilyNotSupport('addVideoToFavorites');
const addFileToFavorites = /* @__PURE__ */ temporarilyNotSupport('addFileToFavorites');
// 微信群
const getGroupEnterInfo = /* @__PURE__ */ temporarilyNotSupport('getGroupEnterInfo');
// 发票
const chooseInvoiceTitle = /* @__PURE__ */ temporarilyNotSupport('chooseInvoiceTitle');
const chooseInvoice = /* @__PURE__ */ temporarilyNotSupport('chooseInvoice');
// 车牌
const chooseLicensePlate = /* @__PURE__ */ temporarilyNotSupport('chooseLicensePlate');
// 帐号信息
const pluginLogin = /* @__PURE__ */ temporarilyNotSupport('pluginLogin');
const login = /* @__PURE__ */ temporarilyNotSupport('login');
const checkSession = /* @__PURE__ */ temporarilyNotSupport('checkSession');
// 我的小程序
const checkIsAddedToMyMiniProgram = /* @__PURE__ */ temporarilyNotSupport('checkIsAddedToMyMiniProgram');
// 隐私信息授权
const requirePrivacyAuthorize = /* @__PURE__ */ temporarilyNotSupport('requirePrivacyAuthorize');
const openPrivacyContract = /* @__PURE__ */ temporarilyNotSupport('openPrivacyContract');
const onNeedPrivacyAuthorization = /* @__PURE__ */ temporarilyNotSupport('onNeedPrivacyAuthorization');
const getPrivacySetting = /* @__PURE__ */ temporarilyNotSupport('getPrivacySetting');
// 微信红包
const showRedPackage = /* @__PURE__ */ temporarilyNotSupport('showRedPackage');
// 设置
const openSetting = /* @__PURE__ */ temporarilyNotSupport('openSetting');
const getSetting = /* @__PURE__ */ temporarilyNotSupport('getSetting');
// 生物认证
const startSoterAuthentication = /* @__PURE__ */ temporarilyNotSupport('startSoterAuthentication');
const checkIsSupportSoterAuthentication = /* @__PURE__ */ temporarilyNotSupport('checkIsSupportSoterAuthentication');
const checkIsSoterEnrolledInDevice = /* @__PURE__ */ temporarilyNotSupport('checkIsSoterEnrolledInDevice');
// 订阅消息
const requestSubscribeMessage = /* @__PURE__ */ temporarilyNotSupport('requestSubscribeMessage');
// 订阅设备消息
const requestSubscribeDeviceMessage = /* @__PURE__ */ temporarilyNotSupport('requestSubscribeDeviceMessage');
// 用户信息
const getUserProfile = /* @__PURE__ */ temporarilyNotSupport('getUserProfile');
const getUserInfo = /* @__PURE__ */ temporarilyNotSupport('getUserInfo');
// 微信运动
const shareToWeRun = /* @__PURE__ */ temporarilyNotSupport('shareToWeRun');
const getWeRunData = /* @__PURE__ */ temporarilyNotSupport('getWeRunData');
// 支付
const requestPayment = /* @__PURE__ */ temporarilyNotSupport('requestPayment');
const requestPluginPayment = /* @__PURE__ */ temporarilyNotSupport('requestPluginPayment');
const requestOrderPayment = /* @__PURE__ */ temporarilyNotSupport('requestOrderPayment');
// 打开手Q说说发表界面
const openQzonePublish = /* @__PURE__ */ temporarilyNotSupport('openQzonePublish');
const getQQRunData = /* @__PURE__ */ temporarilyNotSupport('getQQRunData');
const setOfficialDress = /* @__PURE__ */ temporarilyNotSupport('setOfficialDress');
const setCustomDress = /* @__PURE__ */ temporarilyNotSupport('setCustomDress');
const updateQQApp = /* @__PURE__ */ temporarilyNotSupport('updateQQApp');
const addRecentColorSign = /* @__PURE__ */ temporarilyNotSupport('addRecentColorSign');
const getGuildInfo = /* @__PURE__ */ temporarilyNotSupport('getGuildInfo');
const applyAddToMyApps = /* @__PURE__ */ temporarilyNotSupport('applyAddToMyApps');
const isAddedToMyApps = /* @__PURE__ */ temporarilyNotSupport('isAddedToMyApps');
const router = {
addRouteBuilder: /* @__PURE__ */ temporarilyNotSupport('addRouteBuilder'),
getRouteContext: /* @__PURE__ */ temporarilyNotSupport('getRouteContext'),
removeRouteBuilder: /* @__PURE__ */ temporarilyNotSupport('removeRouteBuilder')
};
// FIXME 方法导出类型未对齐,后续修复
// 转发
/** 更新转发属性 */
const updateShareMenu = /* @__PURE__ */ temporarilyNotSupport('updateShareMenu');
/** 显示当前页面的转发按钮 */
const showShareMenu = /* @__PURE__ */ temporarilyNotSupport('showShareMenu');
/** 打开分享图片弹窗,可以将图片发送给朋友、收藏或下载 */
const showShareImageMenu = /* @__PURE__ */ temporarilyNotSupport('showShareImageMenu');
/** 转发视频到聊天 */
const shareVideoMessage = /* @__PURE__ */ temporarilyNotSupport('shareVideoMessage');
/** 转发文件到聊天 */
const shareFileMessage = /* @__PURE__ */ temporarilyNotSupport('shareFileMessage');
/** 监听用户点击右上角菜单的「复制链接」按钮时触发的事件 */
const onCopyUrl = /* @__PURE__ */ temporarilyNotSupport('onCopyUrl');
/** 移除用户点击右上角菜单的「复制链接」按钮时触发的事件的监听函数 */
const offCopyUrl = /* @__PURE__ */ temporarilyNotSupport('offCopyUrl');
/** 隐藏当前页面的转发按钮 */
const hideShareMenu = /* @__PURE__ */ temporarilyNotSupport('hideShareMenu');
/** 获取转发详细信息 */
const getShareInfo = /* @__PURE__ */ temporarilyNotSupport('getShareInfo');
/** 验证私密消息。 */
const authPrivateMessage = /* @__PURE__ */ permanentlyNotSupport('authPrivateMessage');
const setPageInfo = /* @__PURE__ */ temporarilyNotSupport('setPageInfo');
// 百度小程序 AI 相关
const ocrIdCard = /* @__PURE__ */ temporarilyNotSupport('ocrIdCard');
const ocrBankCard = /* @__PURE__ */ temporarilyNotSupport('ocrBankCard');
const ocrDrivingLicense = /* @__PURE__ */ temporarilyNotSupport('ocrDrivingLicense');
const ocrVehicleLicense = /* @__PURE__ */ temporarilyNotSupport('ocrVehicleLicense');
const textReview = /* @__PURE__ */ temporarilyNotSupport('textReview');
const textToAudio = /* @__PURE__ */ temporarilyNotSupport('textToAudio');
const imageAudit = /* @__PURE__ */ temporarilyNotSupport('imageAudit');
const advancedGeneralIdentify = /* @__PURE__ */ temporarilyNotSupport('advancedGeneralIdentify');
const objectDetectIdentify = /* @__PURE__ */ temporarilyNotSupport('objectDetectIdentify');
const carClassify = /* @__PURE__ */ temporarilyNotSupport('carClassify');
const dishClassify = /* @__PURE__ */ temporarilyNotSupport('dishClassify');
const logoClassify = /* @__PURE__ */ temporarilyNotSupport('logoClassify');
const animalClassify = /* @__PURE__ */ temporarilyNotSupport('animalClassify');
const plantClassify = /* @__PURE__ */ temporarilyNotSupport('plantClassify');
// 用户信息
const getSwanId = /* @__PURE__ */ temporarilyNotSupport('getSwanId');
// 百度收银台支付
const requestPolymerPayment = /* @__PURE__ */ temporarilyNotSupport('requestPolymerPayment');
// 打开小程序
const navigateToSmartGameProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToSmartGameProgram');
const navigateToSmartProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToSmartProgram');
const navigateBackSmartProgram = /* @__PURE__ */ temporarilyNotSupport('navigateBackSmartProgram');
const preloadSubPackage = /* @__PURE__ */ temporarilyNotSupport('preloadSubPackage');
// Worker
const createWorker = /* @__PURE__ */ temporarilyNotSupport('createWorker');
class TaroH5IntersectionObserver {
// selector 的容器节点
get container() {
const container = (this._component !== null
? (findDOM(this._component) || document)
: document);
return container;
}
constructor(component, options = {}) {
// 选项
this._options = {
thresholds: [0],
initialRatio: 0,
observeAll: false
};
// 监控中的选择器
this._listeners = [];
// 用来扩展(或收缩)参照节点布局区域的边界
this._rootMargin = {};
// 是否已初始化
this._isInited = false;
this._component = component;
Object.assign(this._options, options);
}
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) {
// 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数。
const [min, max] = [Math.min(this._options.initialRatio, entry.intersectionRatio), Math.max(this._options.initialRatio, entry.intersectionRatio)];
if (this._options.initialRatio === entry.intersectionRatio || !this._options.thresholds.some(value => value >= min && value <= max)) {
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
});
}
disconnect() {
if (this._observerInst) {
let listener;
while ((listener = this._listeners.pop())) {
this._observerInst.unobserve(listener.element);
}
this._observerInst.disconnect();
}
}
observe(targetSelector, callback) {
// 同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)];
Taro.nextTick(() => {
nodeList.forEach(element => {
if (!element)
return;
this._observerInst.observe(element);
this._listeners.push({ element, callback });
});
});
}
relativeTo(selector, margins) {
// 已设置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;
}
relativeToViewport(margins) {
return this.relativeTo('.taro_page', margins);
}
_getCallbackByElement(element) {
const listener = this._listeners.find(listener => listener.element === element);
return listener ? listener.callback : null;
}
}
function generateMediaQueryStr(descriptor) {
const mediaQueryArr = [];
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(`(${(shared.toKebabCase(item))}: ${Number(descriptor[item])}px)`);
}
if (item === 'orientation' && descriptor[item]) {
mediaQueryArr.push(`(${shared.toKebabCase(item)}: ${descriptor[item]})`);
}
}
return mediaQueryArr.join(' and ');
}
class MediaQueryObserver {
// 监听页面媒体查询变化情况
observe(descriptor, callback) {
if (shared.isFunction(callback)) {
// 创建媒体查询对象
this._mediaQueryObserver = window.matchMedia(generateMediaQueryStr(descriptor));
// 监听器
this._listener = (ev) => {
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);
}
}
}
// 停止监听,销毁媒体查询对象
disconnect() {
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);
}
}
}
}
class NodesRef {
constructor(selector, querySelectorQuery, single) {
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;
}
}
function filter(fields, dom, selector) {
if (!dom)
return null;
const isViewport = selector === '.taro_page';
const { id, dataset, rect, size, scrollOffset, properties = [], computedStyle = [], nodeCanvasType, node, context } = fields;
const res = {};
if (nodeCanvasType && node) {
const tagName = dom.tagName;
res.node = {
id: dom.id,
$taroElement: dom
};
if (/^taro-canvas-core/i.test(tagName)) {
const type = dom.type || '';
res.nodeCanvasType = type;
const canvas = dom.getElementsByTagName('canvas')[0];
if (/^(2d|webgl)/i.test(type) && canvas) {
res.node = canvas;
}
else {
res.node = null;
}
}
else if (/^taro-scroll-view-core/i.test(tagName)) {
// Note https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/ScrollViewContext.html
res.nodeCanvasType = '';
res.node = dom;
dom.scrollTo = dom.mpScrollToMethod;
dom.scrollIntoView = dom.mpScrollIntoViewMethod;
}
else {
res.nodeCanvasType = '';
res.node = dom;
}
return res;
}
if (context) {
const tagName = dom.tagName;
if (/^taro-video-core/i.test(tagName)) {
// TODO HTMLVideoElement to VideoContext
return { context: dom };
}
else if (/^taro-canvas-core/i.test(tagName)) {
const type = dom.type || '2d';
const canvas = dom === null || dom === void 0 ? void 0 : dom.querySelector('canvas');
const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext(type);
return { context: new CanvasContext(canvas, ctx) };
}
else if (/^taro-live-player-core/i.test(tagName)) {
console.error('暂时不支持通过 NodesRef.context 获取 LivePlayerContext');
}
else if (/^taro-editor-core/i.test(tagName)) {
console.error('暂时不支持通过 NodesRef.context 获取 EditorContext');
}
else if (/^taro-map-core/i.test(tagName)) {
console.error('暂时不支持通过 NodesRef.context 获取 MapContext');
}
return;
}
if (id)
res.id = dom.id;
if (dataset)
res.dataset = Object.assign({}, dom.dataset);
if (rect || size) {
const { left, right, top, bottom, width, height } = dom.getBoundingClientRect();
if (rect) {
if (!isViewport) {
res.left = left;
res.right = right;
res.top = top;
res.bottom = bottom;
}
else {
res.left = 0;
res.right = 0;
res.top = 0;
res.bottom = 0;
}
}
if (size) {
if (!isViewport) {
res.width = width;
res.height = height;
}
else {
res.width = dom.clientWidth;
res.height = dom.clientHeight;
}
}
}
if (scrollOffset) {
res.scrollLeft = dom.scrollLeft;
res.scrollTop = dom.scrollTop;
}
if (properties.length) {
properties.forEach(prop => {
const attr = dom.getAttribute(prop);
if (attr)
res[prop] = attr;
});
}
if (computedStyle.length) {
const styles = window.getComputedStyle(dom);
computedStyle.forEach(key => {
const value = styles.getPropertyValue(key) || styles[key];
if (value)
res[key] = value;
});
}
return res;
}
/**
* WXML节点信息API
* @return {Object} SelectorQuery 对象实例
*/
function queryBat(queue, cb) {
const result = [];
queue.forEach(item => {
var _a;
const { selector, single, fields, component } = item;
// selector 的容器节点
/* eslint-disable */
const container = (component !== null ?
(findDOM(component) || document) :
document);
/* eslint-enable */
// 特殊处理 ---- 选自己
let selectSelf = false;
if (container !== document) {
const $nodeList = (_a = container.parentNode) === null || _a === void 0 ? void 0 : _a.querySelectorAll(selector);
if ($nodeList) {
for (let i = 0, len = $nodeList.length; i < len; ++i) {
if (container === $nodeList[i]) {
selectSelf = true;
break;
}
}
}
}
if (single) {
const el = selectSelf === true ? container : container.querySelector(selector);
result.push(filter(fields, el, selector));
}
else {
const $children = container.querySelectorAll(selector);
const children = [];
selectSelf === true && children.push(container);
for (let i = 0, len = $children.length; i < len; ++i) {
children.push($children[i]);
}
result.push(children.map(dom => filter(fields, dom)));
}
});
cb(result);
}
class SelectorQuery {
constructor() {
this._defaultWebviewId = null;
this._webviewId = null;
this._queue = [];
this._queueCb = [];
this._component;
}
in(component) {
this._component = component;
return this;
}
select(selector) {
// 小程序里跨自定义组件的后代选择器 '>>>' 在 h5 替换为普通后代选择器 '>'
if (typeof selector === 'string')
selector = selector.replace('>>>', '>');
return new NodesRef(selector, this, true);
}
selectAll(selector) {
// 小程序里跨自定义组件的后代选择器 '>>>' 在 h5 替换为普通后代选择器 '>'
if (typeof selector === 'string')
selector = selector.replace('>>>', '>');
return new NodesRef(selector, this, false);
}
selectViewport() {
return new NodesRef('.taro_page', this, true);
}
exec(cb) {
Taro.nextTick(() => {
queryBat(this._queue, res => {
const _queueCb = this._queueCb;
res.forEach((item, index) => {
const cb = _queueCb[index];
shared.isFunction(cb) && cb.call(this, item);
});
shared.isFunction(cb) && cb.call(this, res);
});
});
return this;
}
_push(selector, component, single, fields, callback = null) {
this._queue.push({
component,
selector,
single,
fields
});
this._queueCb.push(callback);
}
}
const createSelectorQuery = () => {
return new SelectorQuery();
};
const createIntersectionObserver = (component, options) => {
return new TaroH5IntersectionObserver(component, options);
};
const createMediaQueryObserver = () => {
return new MediaQueryObserver();
};
const { Behavior, getEnv, ENV_TYPE, Link, interceptors, interceptorify, Current, options, eventCenter, Events, preload } = Taro;
const taro = {
// @ts-ignore
Behavior,
getEnv,
ENV_TYPE,
Link,
interceptors,
interceptorify,
Current,
getCurrentInstance,
options,
nextTick,
eventCenter,
Events,
preload,
history: router$1.history,
navigateBack: router$1.navigateBack,
navigateTo: router$1.navigateTo,
reLaunch: router$1.reLaunch,
redirectTo: router$1.redirectTo,
getCurrentPages: router$1.getCurrentPages,
switchTab: router$1.switchTab,
router,
worklet,
};
const requirePlugin = /* @__PURE__ */ permanentlyNotSupport('requirePlugin');
function getConfig() {
var _a;
if (this === null || this === void 0 ? void 0 : this.pxTransformConfig)
return this.pxTransformConfig;
return ((_a = taro).config || (_a.config = {}));
}
const defaultDesignWidth = 750;
const defaultDesignRatio = {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
};
const defaultBaseFontSize = 20;
const defaultUnitPrecision = 5;
const defaultTargetUnit = 'rem';
const initPxTransform = function ({ designWidth = defaultDesignWidth, deviceRatio = defaultDesignRatio, baseFontSize = defaultBaseFontSize, unitPrecision = defaultUnitPrecision, targetUnit = defaultTargetUnit }) {
const config = getConfig.call(this);
config.designWidth = designWidth;
config.deviceRatio = deviceRatio;
config.baseFontSize = baseFontSize;
config.targetUnit = targetUnit;
config.unitPrecision = unitPrecision;
};
const pxTransform = function (size = 0) {
const config = getConfig.call(this);
const baseFontSize = config.baseFontSize || defaultBaseFontSize;
const deviceRatio = config.deviceRatio || defaultDesignRatio;
const designWidth = ((input = 0) => shared.isFunction(config.designWidth)
? config.designWidth(input)
: config.designWidth)(size);
if (!(designWidth in config.deviceRatio)) {
throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`);
}
const targetUnit = config.targetUnit || defaultTargetUnit;
const unitPrecision = config.unitPrecision || defaultUnitPrecision;
const formatSize = ~~size;
let rootValue = 1 / deviceRatio[designWidth];
switch (targetUnit) {
case 'vw':
rootValue = designWidth / 100;
break;
case 'px':
rootValue *= 2;
break;
default:
// rem
rootValue *= baseFontSize * 2;
}
let val = formatSize / rootValue;
if (unitPrecision >= 0 && unitPrecision <= 100) {
// Number(val): 0.50000 => 0.5
val = Number(val.toFixed(unitPrecision));
}
return val + targetUnit;
};
const canIUseWebp = function () {
const canvas = document.createElement('canvas');
return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
};
const getAppInfo = function () {
const config = getConfig.call(this);
return {
platform: process.env.TARO_PLATFORM || shared.PLATFORM_TYPE.WEB,
taroVersion: process.env.TARO_VERSION || 'unknown',
designWidth: config.designWidth,
};
};
taro.requirePlugin = requirePlugin;
taro.getApp = getApp;
taro.pxTransform = pxTransform;
taro.initPxTransform = initPxTransform;
taro.canIUseWebp = canIUseWebp;
taro.getAppInfo = getAppInfo;
Object.defineProperty(exports, 'getCurrentPages', {
enumerable: true,
get: function () { return router$1.getCurrentPages; }
});
Object.defineProperty(exports, 'history', {
enumerable: true,
get: function () { return router$1.history; }
});
Object.defineProperty(exports, 'navigateBack', {
enumerable: true,
get: function () { return router$1.navigateBack; }
});
Object.defineProperty(exports, 'navigateTo', {
enumerable: true,
get: function () { return router$1.navigateTo; }
});
Object.defineProperty(exports, 'reLaunch', {
enumerable: true,
get: function () { return router$1.reLaunch; }
});
Object.defineProperty(exports, 'redirectTo', {
enumerable: true,
get: function () { return router$1.redirectTo; }
});
Object.defineProperty(exports, 'switchTab', {
enumerable: true,
get: function () { return router$1.switchTab; }
});
exports.Behavior = Behavior;
exports.Current = Current;
exports.ENV_TYPE = ENV_TYPE;
exports.Events = Events;
exports.Link = Link;
exports.NodesRef = NodesRef;
exports.SocketTask = SocketTask;
exports.addCard = addCard;
exports.addFileToFavorites = addFileToFavorites;
exports.addInterceptor = addInterceptor;
exports.addPhoneCalendar = addPhoneCalendar;
exports.addPhoneContact = addPhoneContact;
exports.addPhoneRepeatCalendar = addPhoneRepeatCalendar;
exports.addRecentColorSign = addRecentColorSign;
exports.addVideoToFavorites = addVideoToFavorites;
exports.advancedGeneralIdentify = advancedGeneralIdentify;
exports.animalClassify = animalClassify;
exports.applyAddToMyApps = applyAddToMyApps;
exports.arrayBufferToBase64 = arrayBufferToBase64;
exports.authPrivateMessage = authPrivateMessage;
exports.authorize = authorize;
exports.authorizeForMiniProgram = authorizeForMiniProgram;
exports.base64ToArrayBuffer = base64ToArrayBuffer;
exports.batchGetStorage = batchGetStorage;
exports.batchGetStorageSync = batchGetStorageSync;
exports.batchSetStorage = batchSetStorage;
exports.batchSetStorageSync = batchSetStorageSync;
exports.canIUseWebp = canIUseWebp;
exports.canvasGetImageData = canvasGetImageData;
exports.canvasPutImageData = canvasPutImageData;
exports.canvasToTempFilePath = canvasToTempFilePath;
exports.carClassify = carClassify;
exports.checkIsAddedToMyMiniProgram = checkIsAddedToMyMiniProgram;
exports.checkIsOpenAccessibility = checkIsOpenAccessibility;
exports.checkIsPictureInPictureActive = checkIsPictureInPictureActive;
exports.checkIsSoterEnrolledInDevice = checkIsSoterEnrolledInDevice;
exports.checkIsSupportFacialRecognition = checkIsSupportFacialRecognition;
exports.checkIsSupportSoterAuthentication = checkIsSupportSoterAuthentication;
exports.checkSession = checkSession;
exports.chooseAddress = chooseAddress;
exports.chooseContact = chooseContact;
exports.chooseImage = chooseImage;
exports.chooseInvoice = chooseInvoice;
exports.chooseInvoiceTitle = chooseInvoiceTitle;
exports.chooseLicensePlate = chooseLicensePlate;
exports.chooseLocation = chooseLocation;
exports.chooseMedia = chooseMedia;
exports.chooseMessageFile = chooseMessageFile;
exports.choosePoi = choosePoi;
exports.chooseVideo = chooseVideo;
exports.cleanInterceptors = cleanInterceptors;
exports.clearStorage = clearStorage;
exports.clearStorageSync = clearStorageSync;
exports.closeBLEConnection = closeBLEConnection;
exports.closeBluetoothAdapter = closeBluetoothAdapter;
exports.closeSocket = closeSocket;
exports.cloud = cloud;
exports.compressImage = compressImage;
exports.compressVideo = compressVideo;
exports.connectSocket = connectSocket;
exports.connectWifi = connectWifi;
exports.createAnimation = createAnimation;
exports.createAudioContext = createAudioContext;
exports.createBLEConnection = createBLEConnection;
exports.createBLEPeripheralServer = createBLEPeripheralServer;
exports.createBufferURL = createBufferURL;
exports.createCacheManager = createCacheManager;
exports.createCameraContext = createCameraContext;
exports.createCanvasContext = createCanvasContext;
exports.createInferenceSession = createInferenceSession;
exports.createInnerAudioContext = createInnerAudioContext;
exports.createIntersectionObserver = createIntersectionObserver;
exports.createInterstitialAd = createInterstitialAd;
exports.createLivePlayerContext = createLivePlayerContext;
exports.createLivePusherContext = createLivePusherContext;
exports.createMapContext = createMapContext;
exports.createMediaAudioPlayer = createMediaAudioPlayer;
exports.createMediaContainer = createMediaContainer;
exports.createMediaQueryObserver = createMediaQueryObserver;
exports.createMediaRecorder = createMediaRecorder;
exports.createOffscreenCanvas = createOffscreenCanvas;
exports.createRewardedVideoAd = createRewardedVideoAd;
exports.createSelectorQuery = createSelectorQuery;
exports.createTCPSocket = createTCPSocket;
exports.createUDPSocket = createUDPSocket;
exports.createVKSession = createVKSession;
exports.createVideoContext = createVideoContext;
exports.createVideoDecoder = createVideoDecoder;
exports.createWebAudioContext = createWebAudioContext;
exports.createWorker = createWorker;
exports.cropImage = cropImage;
exports.default = taro;
exports.disableAlertBeforeUnload = disableAlertBeforeUnload;
exports.dishClassify = dishClassify;
exports.downloadFile = downloadFile;
exports.editImage = editImage;
exports.enableAlertBeforeUnload = enableAlertBeforeUnload;
exports.env = env;
exports.eventCenter = eventCenter;
exports.exitMiniProgram = exitMiniProgram;
exports.exitVoIPChat = exitVoIPChat;
exports.faceDetect = faceDetect;
exports.faceVerifyForPay = faceVerifyForPay;
exports.getAccountInfoSync = getAccountInfoSync;
exports.getApp = getApp;
exports.getAppAuthorizeSetting = getAppAuthorizeSetting;
exports.getAppBaseInfo = getAppBaseInfo;
exports.getAppInfo = getAppInfo;
exports.getAvailableAudioSources = getAvailableAudioSources;
exports.getBLEDeviceCharacteristics = getBLEDeviceCharacteristics;
exports.getBLEDeviceRSSI = getBLEDeviceRSSI;
exports.getBLEDeviceServices = getBLEDeviceServices;
exports.getBLEMTU = getBLEMTU;
exports.getBackgroundAudioManager = getBackgroundAudioManager;
exports.getBackgroundAudioPlayerState = getBackgroundAudioPlayerState;
exports.getBackgroundFetchData = getBackgroundFetchData;
exports.getBackgroundFetchToken = getBackgroundFetchToken;
exports.getBatteryInfo = getBatteryInfo;
exports.getBatteryInfoSync = getBatteryInfoSync;
exports.getBeacons = getBeacons;
exports.getBluetoothAdapterState = getBluetoothAdapterState;
exports.getBluetoothDevices = getBluetoothDevices;
exports.getChannelsLiveInfo = getChannelsLiveInfo;
exports.getChannelsLiveNoticeInfo = getChannelsLiveNoticeInfo;
exports.getChannelsShareKey = getChannelsShareKey;
exports.getClipboardData = getClipboardData;
exports.getConnectedBluetoothDevices = getConnectedBluetoothDevices;
exports.getConnectedWifi = getConnectedWifi;
exports.getCurrentInstance = getCurrentInstance;
exports.getDeviceInfo = getDeviceInfo;
exports.getDeviceVoIPList = getDeviceVoIPList;
exports.getEnterOptionsSync = getEnterOptionsSync;
exports.getEnv = getEnv;
exports.getExptInfoSync = getExptInfoSync;
exports.getExtConfig = getExtConfig;
exports.getExtConfigSync = getExtConfigSync;
exports.getFileInfo = getFileInfo;
exports.getFileSystemManager = getFileSystemManager;
exports.getFuzzyLocation = getFuzzyLocation;
exports.getGroupEnterInfo = getGroupEnterInfo;
exports.getGuildInfo = getGuildInfo;
exports.getHCEState = getHCEState;
exports.getImageInfo = getImageInfo;
exports.getInferenceEnvInfo = getInferenceEnvInfo;
exports.getLaunchOptionsSync = getLaunchOptionsSync;
exports.getLocalIPAddress = getLocalIPAddress;
exports.getLocation = getLocation;
exports.getLogManager = getLogManager;
exports.getMenuButtonBoundingClientRect = getMenuButtonBoundingClientRect;
exports.getNFCAdapter = getNFCAdapter;
exports.getNetworkType = getNetworkType;
exports.getOpenUserInfo = getOpenUserInfo;
exports.getPerformance = getPerformance;
exports.getPrivacySetting = getPrivacySetting;
exports.getQQRunData = getQQRunData;
exports.getRandomValues = getRandomValues;
exports.getRealtimeLogManager = getRealtimeLogManager;
exports.getRecorderManager = getRecorderManager;
exports.getRendererUserAgent = getRendererUserAgent;
exports.getSavedFileInfo = getSavedFileInfo;
exports.getSavedFileList = getSavedFileList;
exports.getScreenBrightness = getScreenBrightness;
exports.getScreenRecordingState = getScreenRecordingState;
exports.getSelectedTextRange = getSelectedTextRange;
exports.getSetting = getSetting;
exports.getShareInfo = getShareInfo;
exports.getSkylineInfo = getSkylineInfo;
exports.getSkylineInfoSync = getSkylineInfoSync;
exports.getStorage = getStorage;
exports.getStorageInfo = getStorageInfo;
exports.getStorageInfoSync = getStorageInfoSync;
exports.getStorageSync = getStorageSync;
exports.getSwanId = getSwanId;
exports.getSystemInfo = getSystemInfo;
exports.getSystemInfoAsync = getSystemInfoAsync;
exports.getSystemInfoSync = getSystemInfoSync;
exports.getSystemSetting = getSystemSetting;
exports.getUpdateManager = getUpdateManager;
exports.getUserCryptoManager = getUserCryptoManager;
exports.getUserInfo = getUserInfo;
exports.getUserProfile = getUserProfile;
exports.getVideoInfo = getVideoInfo;
exports.getWeRunData = getWeRunData;
exports.getWifiList = getWifiList;
exports.getWindowInfo = getWindowInfo;
exports.hideHomeButton = hideHomeButton;
exports.hideKeyboard = hideKeyboard;
exports.hideLoading = hideLoading;
exports.hideNavigationBarLoading = hideNavigationBarLoading;
exports.hideShareMenu = hideShareMenu;
exports.hideTabBar = hideTabBar;
exports.hideTabBarRedDot = hideTabBarRedDot;
exports.hideToast = hideToast;
exports.imageAudit = imageAudit;
exports.initFaceDetect = initFaceDetect;
exports.initPxTransform = initPxTransform;
exports.initTabBarApis = initTabBarApis;
exports.interceptorify = interceptorify;
exports.interceptors = interceptors;
exports.isAddedToMyApps = isAddedToMyApps;
exports.isBluetoothDevicePaired = isBluetoothDevicePaired;
exports.isVKSupport = isVKSupport;
exports.join1v1Chat = join1v1Chat;
exports.joinVoIPChat = joinVoIPChat;
exports.loadFontFace = loadFontFace;
exports.login = login;
exports.logoClassify = logoClassify;
exports.makeBluetoothPair = makeBluetoothPair;
exports.makePhoneCall = makePhoneCall;
exports.navigateBackMiniProgram = navigateBackMiniProgram;
exports.navigateBackSmartProgram = navigateBackSmartProgram;
exports.navigateToMiniProgram = navigateToMiniProgram;
exports.navigateToSmartGameProgram = navigateToSmartGameProgram;
exports.navigateToSmartProgram = navigateToSmartProgram;
exports.nextTick = nextTick;
exports.notifyBLECharacteristicValueChange = notifyBLECharacteristicValueChange;
exports.objectDetectIdentify = objectDetectIdentify;
exports.ocrBankCard = ocrBankCard;
exports.ocrDrivingLicense = ocrDrivingLicense;
exports.ocrIdCard = ocrIdCard;
exports.ocrVehicleLicense = ocrVehicleLicense;
exports.offAccelerometerChange = offAccelerometerChange;
exports.offAppHide = offAppHide;
exports.offAppShow = offAppShow;
exports.offAudioInterruptionBegin = offAudioInterruptionBegin;
exports.offAudioInterruptionEnd = offAudioInterruptionEnd;
exports.offBLECharacteristicValueChange = offBLECharacteristicValueChange;
exports.offBLEConnectionStateChange = offBLEConnectionStateChange;
exports.offBLEMTUChange = offBLEMTUChange;
exports.offBLEPeripheralConnectionStateChanged = offBLEPeripheralConnectionStateChanged;
exports.offBeaconServiceChange = offBeaconServiceChange;
exports.offBeaconUpdate = offBeaconUpdate;
exports.offBluetoothAdapterStateChange = offBluetoothAdapterStateChange;
exports.offBluetoothDeviceFound = offBluetoothDeviceFound;
exports.offCompassChange = offCompassChange;
exports.offCopyUrl = offCopyUrl;
exports.offDeviceMotionChange = offDeviceMotionChange;
exports.offError = offError;
exports.offGetWifiList = offGetWifiList;
exports.offGyroscopeChange = offGyroscopeChange;
exports.offHCEMessage = offHCEMessage;
exports.offKeyboardHeightChange = offKeyboardHeightChange;
exports.offLazyLoadError = offLazyLoadError;
exports.offLocalServiceDiscoveryStop = offLocalServiceDiscoveryStop;
exports.offLocalServiceFound = offLocalServiceFound;
exports.offLocalServiceLost = offLocalServiceLost;
exports.offLocalServiceResolveFail = offLocalServiceResolveFail;
exports.offLocationChange = offLocationChange;
exports.offLocationChangeError = offLocationChangeError;
exports.offMemoryWarning = offMemoryWarning;
exports.offNetworkStatusChange = offNetworkStatusChange;
exports.offNetworkWeakChange = offNetworkWeakChange;
exports.offPageNotFound = offPageNotFound;
exports.offScreenRecordingStateChanged = offScreenRecordingStateChanged;
exports.offThemeChange = offThemeChange;
exports.offUnhandledRejection = offUnhandledRejection;
exports.offUserCaptureScreen = offUserCaptureScreen;
exports.offVoIPChatInterrupted = offVoIPChatInterrupted;
exports.offVoIPChatMembersChanged = offVoIPChatMembersChanged;
exports.offVoIPChatSpeakersChanged = offVoIPChatSpeakersChanged;
exports.offVoIPChatStateChanged = offVoIPChatStateChanged;
exports.offVoIPVideoMembersChanged = offVoIPVideoMembersChanged;
exports.offWifiConnected = offWifiConnected;
exports.offWifiConnectedWithPartialInfo = offWifiConnectedWithPartialInfo;
exports.offWindowResize = offWindowResize;
exports.onAccelerometerChange = onAccelerometerChange;
exports.onAppHide = onAppHide;
exports.onAppShow = onAppShow;
exports.onAudioInterruptionBegin = onAudioInterruptionBegin;
exports.onAudioInterruptionEnd = onAudioInterruptionEnd;
exports.onBLECharacteristicValueChange = onBLECharacteristicValueChange;
exports.onBLEConnectionStateChange = onBLEConnectionStateChange;
exports.onBLEMTUChange = onBLEMTUChange;
exports.onBLEPeripheralConnectionStateChanged = onBLEPeripheralConnectionStateChanged;
exports.onBackgroundAudioPause = onBackgroundAudioPause;
exports.onBackgroundAudioPlay = onBackgroundAudioPlay;
exports.onBackgroundAudioStop = onBackgroundAudioStop;
exports.onBackgroundFetchData = onBackgroundFetchData;
exports.onBeaconServiceChange = onBeaconServiceChange;
exports.onBeaconUpdate = onBeaconUpdate;
exports.onBluetoothAdapterStateChange = onBluetoothAdapterStateChange;
exports.onBluetoothDeviceFound = onBluetoothDeviceFound;
exports.onCompassChange = onCompassChange;
exports.onCopyUrl = onCopyUrl;
exports.onDeviceMotionChange = onDeviceMotionChange;
exports.onError = onError;
exports.onGetWifiList = onGetWifiList;
exports.onGyroscopeChange = onGyroscopeChange;
exports.onHCEMessage = onHCEMessage;
exports.onKeyboardHeightChange = onKeyboardHeightChange;
exports.onLazyLoadError = onLazyLoadError;
exports.onLocalServiceDiscoveryStop = onLocalServiceDiscoveryStop;
exports.onLocalServiceFound = onLocalServiceFound;
exports.onLocalServiceLost = onLocalServiceLost;
exports.onLocalServiceResolveFail = onLocalServiceResolveFail;
exports.onLocationChange = onLocationChange;
exports.onLocationChangeError = onLocationChangeError;
exports.onMemoryWarning = onMemoryWarning;
exports.onNeedPrivacyAuthorization = onNeedPrivacyAuthorization;
exports.onNetworkStatusChange = onNetworkStatusChange;
exports.onNetworkWeakChange = onNetworkWeakChange;
exports.onPageNotFound = onPageNotFound;
exports.onScreenRecordingStateChanged = onScreenRecordingStateChanged;
exports.onSocketClose = onSocketClose;
exports.onSocketError = onSocketError;
exports.onSocketMessage = onSocketMessage;
exports.onSocketOpen = onSocketOpen;
exports.onThemeChange = onThemeChange;
exports.onUnhandledRejection = onUnhandledRejection;
exports.onUserCaptureScreen = onUserCaptureScreen;
exports.onVoIPChatInterrupted = onVoIPChatInterrupted;
exports.onVoIPChatMembersChanged = onVoIPChatMembersChanged;
exports.onVoIPChatSpeakersChanged = onVoIPChatSpeakersChanged;
exports.onVoIPChatStateChanged = onVoIPChatStateChanged;
exports.onVoIPVideoMembersChanged = onVoIPVideoMembersChanged;
exports.onWifiConnected = onWifiConnected;
exports.onWifiConnectedWithPartialInfo = onWifiConnectedWithPartialInfo;
exports.onWindowResize = onWindowResize;
exports.openAppAuthorizeSetting = openAppAuthorizeSetting;
exports.openBluetoothAdapter = openBluetoothAdapter;
exports.openBusinessView = openBusinessView;
exports.openCard = openCard;
exports.openChannelsActivity = openChannelsActivity;
exports.openChannelsEvent = openChannelsEvent;
exports.openChannelsLive = openChannelsLive;
exports.openChannelsUserProfile = openChannelsUserProfile;
exports.openCustomerServiceChat = openCustomerServiceChat;
exports.openDocument = openDocument;
exports.openEmbeddedMiniProgram = openEmbeddedMiniProgram;
exports.openLocation = openLocation;
exports.openPrivacyContract = openPrivacyContract;
exports.openQzonePublish = openQzonePublish;
exports.openSetting = openSetting;
exports.openSystemBluetoothSetting = openSystemBluetoothSetting;
exports.openVideoEditor = openVideoEditor;
exports.options = options;
exports.pageScrollTo = pageScrollTo;
exports.pauseBackgroundAudio = pauseBackgroundAudio;
exports.pauseVoice = pauseVoice;
exports.plantClassify = plantClassify;
exports.playBackgroundAudio = playBackgroundAudio;
exports.playVoice = playVoice;
exports.pluginLogin = pluginLogin;
exports.preload = preload;
exports.preloadAssets = preloadAssets;
exports.preloadSkylineView = preloadSkylineView;
exports.preloadSubPackage = preloadSubPackage;
exports.preloadWebview = preloadWebview;
exports.previewImage = previewImage;
exports.previewMedia = previewMedia;
exports.pxTransform = pxTransform;
exports.readBLECharacteristicValue = readBLECharacteristicValue;
exports.removeSavedFile = removeSavedFile;
exports.removeStorage = removeStorage;
exports.removeStorageSync = removeStorageSync;
exports.removeTabBarBadge = removeTabBarBadge;
exports.reportAnalytics = reportAnalytics;
exports.reportEvent = reportEvent;
exports.reportMonitor = reportMonitor;
exports.reportPerformance = reportPerformance;
exports.request = request;
exports.requestDeviceVoIP = requestDeviceVoIP;
exports.requestOrderPayment = requestOrderPayment;
exports.requestPayment = requestPayment;
exports.requestPluginPayment = requestPluginPayment;
exports.requestPolymerPayment = requestPolymerPayment;
exports.requestSubscribeDeviceMessage = requestSubscribeDeviceMessage;
exports.requestSubscribeMessage = requestSubscribeMessage;
exports.requirePlugin = requirePlugin;
exports.requirePrivacyAuthorize = requirePrivacyAuthorize;
exports.reserveChannelsLive = reserveChannelsLive;
exports.revokeBufferURL = revokeBufferURL;
exports.router = router;
exports.saveFile = saveFile;
exports.saveFileToDisk = saveFileToDisk;
exports.saveImageToPhotosAlbum = saveImageToPhotosAlbum;
exports.saveVideoToPhotosAlbum = saveVideoToPhotosAlbum;
exports.scanCode = scanCode;
exports.seekBackgroundAudio = seekBackgroundAudio;
exports.sendHCEMessage = sendHCEMessage;
exports.sendSms = sendSms;
exports.sendSocketMessage = sendSocketMessage;
exports.setBLEMTU = setBLEMTU;
exports.setBackgroundColor = setBackgroundColor;
exports.setBackgroundFetchToken = setBackgroundFetchToken;
exports.setBackgroundTextStyle = setBackgroundTextStyle;
exports.setClipboardData = setClipboardData;
exports.setCustomDress = setCustomDress;
exports.setEnable1v1Chat = setEnable1v1Chat;
exports.setEnableDebug = setEnableDebug;
exports.setInnerAudioOption = setInnerAudioOption;
exports.setKeepScreenOn = setKeepScreenOn;
exports.setNavigationBarColor = setNavigationBarColor;
exports.setNavigationBarTitle = setNavigationBarTitle;
exports.setOfficialDress = setOfficialDress;
exports.setPageInfo = setPageInfo;
exports.setScreenBrightness = setScreenBrightness;
exports.setStorage = setStorage;
exports.setStorageSync = setStorageSync;
exports.setTabBarBadge = setTabBarBadge;
exports.setTabBarItem = setTabBarItem;
exports.setTabBarStyle = setTabBarStyle;
exports.setTopBarText = setTopBarText;
exports.setVisualEffectOnCapture = setVisualEffectOnCapture;
exports.setWifiList = setWifiList;
exports.setWindowSize = setWindowSize;
exports.shareFileMessage = shareFileMessage;
exports.shareToWeRun = shareToWeRun;
exports.shareVideoMessage = shareVideoMessage;
exports.showActionSheet = showActionSheet;
exports.showLoading = showLoading;
exports.showModal = showModal;
exports.showNavigationBarLoading = showNavigationBarLoading;
exports.showRedPackage = showRedPackage;
exports.showShareImageMenu = showShareImageMenu;
exports.showShareMenu = showShareMenu;
exports.showTabBar = showTabBar;
exports.showTabBarRedDot = showTabBarRedDot;
exports.showToast = showToast;
exports.startAccelerometer = startAccelerometer;
exports.startBeaconDiscovery = startBeaconDiscovery;
exports.startBluetoothDevicesDiscovery = startBluetoothDevicesDiscovery;
exports.startCompass = startCompass;
exports.startDeviceMotionListening = startDeviceMotionListening;
exports.startFacialRecognitionVerify = startFacialRecognitionVerify;
exports.startFacialRecognitionVerifyAndUploadVideo = startFacialRecognitionVerifyAndUploadVideo;
exports.startGyroscope = startGyroscope;
exports.startHCE = startHCE;
exports.startLocalServiceDiscovery = startLocalServiceDiscovery;
exports.startLocationUpdate = startLocationUpdate;
exports.startLocationUpdateBackground = startLocationUpdateBackground;
exports.startPullDownRefresh = startPullDownRefresh;
exports.startRecord = startRecord;
exports.startSoterAuthentication = startSoterAuthentication;
exports.startWifi = startWifi;
exports.stopAccelerometer = stopAccelerometer;
exports.stopBackgroundAudio = stopBackgroundAudio;
exports.stopBeaconDiscovery = stopBeaconDiscovery;
exports.stopBluetoothDevicesDiscovery = stopBluetoothDevicesDiscovery;
exports.stopCompass = stopCompass;
exports.stopDeviceMotionListening = stopDeviceMotionListening;
exports.stopFaceDetect = stopFaceDetect;
exports.stopGyroscope = stopGyroscope;
exports.stopHCE = stopHCE;
exports.stopLocalServiceDiscovery = stopLocalServiceDiscovery;
exports.stopLocationUpdate = stopLocationUpdate;
exports.stopPullDownRefresh = stopPullDownRefresh;
exports.stopRecord = stopRecord;
exports.stopVoice = stopVoice;
exports.stopWifi = stopWifi;
exports.subscribeVoIPVideoMembers = subscribeVoIPVideoMembers;
exports.textReview = textReview;
exports.textToAudio = textToAudio;
exports.tradePay = tradePay;
exports.updateQQApp = updateQQApp;
exports.updateShareMenu = updateShareMenu;
exports.updateVoIPChatMuteConfig = updateVoIPChatMuteConfig;
exports.updateWeChatApp = updateWeChatApp;
exports.uploadFile = uploadFile;
exports.vibrateLong = vibrateLong;
exports.vibrateShort = vibrateShort;
exports.worklet = worklet;
exports.writeBLECharacteristicValue = writeBLECharacteristicValue;
//# sourceMappingURL=index.cjs.js.map